openclaw-scheduler 0.2.0
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/AGENTS.md +302 -0
- package/BEST-PRACTICES.md +506 -0
- package/CHANGELOG.md +82 -0
- package/CODE_OF_CONDUCT.md +22 -0
- package/CONTEXT.md +26 -0
- package/CONTRIBUTING.md +73 -0
- package/IMPLEMENTATION_SPEC.md +170 -0
- package/INSTALL-ADDITIONAL-HOST.md +333 -0
- package/INSTALL-LINUX.md +419 -0
- package/INSTALL-WINDOWS.md +305 -0
- package/INSTALL.md +364 -0
- package/JOB-QUICK-REF.md +222 -0
- package/LICENSE +21 -0
- package/QUICK-START.md +256 -0
- package/README.md +2170 -0
- package/SECURITY.md +34 -0
- package/UNINSTALL.md +129 -0
- package/UPGRADING.md +436 -0
- package/agents.js +67 -0
- package/approval.js +107 -0
- package/backup.js +390 -0
- package/bin/openclaw-scheduler.js +138 -0
- package/cli.js +1083 -0
- package/db.js +122 -0
- package/dispatch/529-recovery.mjs +204 -0
- package/dispatch/README.md +372 -0
- package/dispatch/config.example.json +24 -0
- package/dispatch/deliver-watcher.sh +57 -0
- package/dispatch/hooks.mjs +171 -0
- package/dispatch/index.mjs +1836 -0
- package/dispatch/watcher.mjs +1396 -0
- package/dispatch-queue.js +112 -0
- package/dispatcher-approvals.js +96 -0
- package/dispatcher-delivery.js +43 -0
- package/dispatcher-maintenance.js +242 -0
- package/dispatcher-shell.js +29 -0
- package/dispatcher-strategies.js +1280 -0
- package/dispatcher-utils.js +81 -0
- package/dispatcher.js +855 -0
- package/docs/adr-schedule-ownership.md +73 -0
- package/docs/gateway-contract.md +904 -0
- package/docs/plans/2026-03-09-fix-typescript-types.md +91 -0
- package/docs/plans/2026-03-09-test-coverage-gaps.md +83 -0
- package/docs/plans/2026-03-10-dispatcher-refactor.md +801 -0
- package/docs/trust-architecture.md +266 -0
- package/gateway.js +473 -0
- package/idempotency.js +119 -0
- package/index.d.ts +864 -0
- package/index.js +17 -0
- package/jobs.js +1224 -0
- package/messages.js +357 -0
- package/migrate-consolidate.js +694 -0
- package/migrate.js +125 -0
- package/package.json +130 -0
- package/paths.js +79 -0
- package/prompt-context.js +94 -0
- package/retrieval.js +176 -0
- package/runs.js +270 -0
- package/scheduler-schema.js +101 -0
- package/schema.sql +480 -0
- package/scripts/dispatch-cli-utils.mjs +65 -0
- package/scripts/inbox-consumer.mjs +288 -0
- package/scripts/stuck-detector.sh +18 -0
- package/scripts/stuck-run-detector.mjs +333 -0
- package/scripts/telegram-webhook-check.mjs +238 -0
- package/setup.mjs +724 -0
- package/shell-result.js +214 -0
- package/task-tracker.js +300 -0
- package/team-adapter.js +335 -0
- package/v02-runtime.js +599 -0
package/approval.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// Approval gate management for HITL workflows
|
|
2
|
+
import { randomUUID } from 'crypto';
|
|
3
|
+
import { getDb } from './db.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Create a pending approval record for a job (optionally linked to a run).
|
|
7
|
+
*/
|
|
8
|
+
export function createApproval(jobId, runId, dispatchQueueId = null) {
|
|
9
|
+
const db = getDb();
|
|
10
|
+
const id = randomUUID();
|
|
11
|
+
|
|
12
|
+
db.prepare(`
|
|
13
|
+
INSERT INTO approvals (id, job_id, run_id, dispatch_queue_id, status, requested_at)
|
|
14
|
+
VALUES (?, ?, ?, ?, 'pending', datetime('now'))
|
|
15
|
+
`).run(id, jobId, runId || null, dispatchQueueId || null);
|
|
16
|
+
|
|
17
|
+
return getApproval(id);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Get an approval by ID.
|
|
22
|
+
*/
|
|
23
|
+
export function getApproval(id) {
|
|
24
|
+
return getDb().prepare('SELECT * FROM approvals WHERE id = ?').get(id);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Get the latest pending approval for a job (if any).
|
|
29
|
+
*/
|
|
30
|
+
export function getPendingApproval(jobId) {
|
|
31
|
+
return getDb().prepare(`
|
|
32
|
+
SELECT * FROM approvals
|
|
33
|
+
WHERE job_id = ? AND status = 'pending'
|
|
34
|
+
ORDER BY requested_at DESC
|
|
35
|
+
LIMIT 1
|
|
36
|
+
`).get(jobId);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* List all pending approvals.
|
|
41
|
+
*/
|
|
42
|
+
export function listPendingApprovals() {
|
|
43
|
+
return getDb().prepare(`
|
|
44
|
+
SELECT a.*, j.name as job_name
|
|
45
|
+
FROM approvals a
|
|
46
|
+
LEFT JOIN jobs j ON a.job_id = j.id
|
|
47
|
+
WHERE a.status = 'pending'
|
|
48
|
+
ORDER BY a.requested_at ASC
|
|
49
|
+
`).all();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function countPendingApprovalsForJob(jobId) {
|
|
53
|
+
const row = getDb().prepare(`
|
|
54
|
+
SELECT COUNT(*) AS cnt
|
|
55
|
+
FROM approvals
|
|
56
|
+
WHERE job_id = ? AND status = 'pending'
|
|
57
|
+
`).get(jobId);
|
|
58
|
+
return row?.cnt || 0;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Resolve an approval (approve / reject / timed_out).
|
|
63
|
+
*/
|
|
64
|
+
const VALID_APPROVAL_STATUSES = new Set(['approved', 'rejected', 'timed_out']);
|
|
65
|
+
|
|
66
|
+
export function resolveApproval(id, status, resolvedBy, notes) {
|
|
67
|
+
if (!VALID_APPROVAL_STATUSES.has(status)) {
|
|
68
|
+
throw new Error(`Invalid approval status '${status}': must be one of ${[...VALID_APPROVAL_STATUSES].join(', ')}`);
|
|
69
|
+
}
|
|
70
|
+
const db = getDb();
|
|
71
|
+
db.prepare(`
|
|
72
|
+
UPDATE approvals SET
|
|
73
|
+
status = ?,
|
|
74
|
+
resolved_at = datetime('now'),
|
|
75
|
+
resolved_by = ?,
|
|
76
|
+
notes = ?
|
|
77
|
+
WHERE id = ? AND status = 'pending'
|
|
78
|
+
`).run(status, resolvedBy || null, notes || null, id);
|
|
79
|
+
|
|
80
|
+
return getApproval(id);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Get pending approvals that have exceeded their job's approval_timeout_s.
|
|
85
|
+
* Joins with jobs to read the timeout value.
|
|
86
|
+
*/
|
|
87
|
+
export function getTimedOutApprovals() {
|
|
88
|
+
return getDb().prepare(`
|
|
89
|
+
SELECT a.*, j.name as job_name, j.approval_timeout_s, j.approval_auto
|
|
90
|
+
FROM approvals a
|
|
91
|
+
JOIN jobs j ON a.job_id = j.id
|
|
92
|
+
WHERE a.status = 'pending'
|
|
93
|
+
AND j.approval_timeout_s IS NOT NULL
|
|
94
|
+
AND (julianday('now') - julianday(a.requested_at)) * 86400 > j.approval_timeout_s
|
|
95
|
+
`).all();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Prune old resolved approvals past retention.
|
|
100
|
+
*/
|
|
101
|
+
export function pruneApprovals(retentionDays = 30) {
|
|
102
|
+
return getDb().prepare(`
|
|
103
|
+
DELETE FROM approvals
|
|
104
|
+
WHERE status != 'pending'
|
|
105
|
+
AND resolved_at < datetime('now', '-' || ? || ' days')
|
|
106
|
+
`).run(retentionDays);
|
|
107
|
+
}
|
package/backup.js
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Scheduler DB Backup -- Ship SQLite snapshots to MinIO
|
|
4
|
+
*
|
|
5
|
+
* Modes:
|
|
6
|
+
* snapshot -- Full DB copy to MinIO (5-min granularity)
|
|
7
|
+
* rollup -- Tagged hourly snapshot + prune old 5-min snapshots
|
|
8
|
+
* restore -- Pull latest snapshot from MinIO and restore
|
|
9
|
+
* status -- Show backup status (latest snapshot, count, size)
|
|
10
|
+
* prune -- Remove snapshots older than retention policy
|
|
11
|
+
*
|
|
12
|
+
* Storage layout on MinIO:
|
|
13
|
+
* scheduler-backups/scheduler/snapshots/YYYY-MM-DD/HH-MM.db
|
|
14
|
+
* scheduler-backups/scheduler/rollups/YYYY-MM-DD/HH.db
|
|
15
|
+
*
|
|
16
|
+
* Retention:
|
|
17
|
+
* snapshots: 24 hours (288 files max at 5-min intervals)
|
|
18
|
+
* rollups: 7 days (168 files max)
|
|
19
|
+
*
|
|
20
|
+
* Requires: MinIO client (`mc`) binary in PATH or ~/bin/mc.
|
|
21
|
+
* Install: https://min.io/docs/minio/linux/reference/minio-mc.html
|
|
22
|
+
*
|
|
23
|
+
* Usage:
|
|
24
|
+
* node backup.js snapshot # Ship current DB
|
|
25
|
+
* node backup.js rollup # Hourly rollup + prune old snapshots
|
|
26
|
+
* node backup.js restore # Restore from latest
|
|
27
|
+
* node backup.js status # Show backup stats
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import Database from 'better-sqlite3';
|
|
31
|
+
import { execFileSync } from 'child_process';
|
|
32
|
+
import { copyFileSync, existsSync, mkdirSync, statSync, unlinkSync } from 'fs';
|
|
33
|
+
import { join } from 'path';
|
|
34
|
+
import { homedir } from 'os';
|
|
35
|
+
import { resolveBackupStagingDir, resolveSchedulerDbPath } from './paths.js';
|
|
36
|
+
|
|
37
|
+
const DB_PATH = resolveSchedulerDbPath({ env: process.env });
|
|
38
|
+
const STAGING_DIR = resolveBackupStagingDir(process.env);
|
|
39
|
+
const MC_ALIAS = process.env.SCHEDULER_BACKUP_MC_ALIAS || 'backupstore';
|
|
40
|
+
const BUCKET = process.env.SCHEDULER_BACKUP_BUCKET || 'scheduler-backups';
|
|
41
|
+
const PREFIX = process.env.SCHEDULER_BACKUP_PREFIX || 'scheduler';
|
|
42
|
+
|
|
43
|
+
// Find mc binary -- may be in ~/bin on some hosts
|
|
44
|
+
const MC_BIN = existsSync(join(homedir(), 'bin', 'mc'))
|
|
45
|
+
? join(homedir(), 'bin', 'mc')
|
|
46
|
+
: 'mc';
|
|
47
|
+
|
|
48
|
+
// Retention
|
|
49
|
+
const SNAPSHOT_RETENTION_HOURS = 24;
|
|
50
|
+
const ROLLUP_RETENTION_DAYS = 7;
|
|
51
|
+
|
|
52
|
+
const LOG_PREFIX = '[backup]';
|
|
53
|
+
|
|
54
|
+
function log(level, msg) {
|
|
55
|
+
const ts = new Date().toISOString();
|
|
56
|
+
process.stderr.write(`${ts} ${LOG_PREFIX} [${level}] ${msg}\n`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function now() {
|
|
60
|
+
return new Date();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function mcPath(subpath) {
|
|
64
|
+
return `${MC_ALIAS}/${BUCKET}/${PREFIX}/${subpath}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Create a consistent backup of the SQLite database. Checkpoints WAL first
|
|
69
|
+
* via better-sqlite3 (no external sqlite3 binary needed), then copies the
|
|
70
|
+
* main DB file. This is safe for WAL-mode databases.
|
|
71
|
+
* Returns true on success, false on failure.
|
|
72
|
+
*/
|
|
73
|
+
function backupDatabase(srcPath, destPath) {
|
|
74
|
+
try {
|
|
75
|
+
const src = new Database(srcPath, { readonly: false, fileMustExist: true });
|
|
76
|
+
try {
|
|
77
|
+
src.pragma('wal_checkpoint(TRUNCATE)');
|
|
78
|
+
} finally {
|
|
79
|
+
src.close();
|
|
80
|
+
}
|
|
81
|
+
copyFileSync(srcPath, destPath);
|
|
82
|
+
return true;
|
|
83
|
+
} catch (err) {
|
|
84
|
+
log('warn', `Database backup failed: ${err.message}`);
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function hasSqlite3() {
|
|
90
|
+
try {
|
|
91
|
+
execFileSync('sqlite3', ['--version'], { stdio: 'pipe' });
|
|
92
|
+
return true;
|
|
93
|
+
} catch {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function runFile(bin, args, opts = {}) {
|
|
99
|
+
try {
|
|
100
|
+
return execFileSync(bin, args, { encoding: 'utf8', timeout: 30000, stdio: 'pipe', ...opts }).trim();
|
|
101
|
+
} catch (err) {
|
|
102
|
+
if (!opts.ignoreError) {
|
|
103
|
+
log('error', `Command failed: ${bin} ${args.join(' ')}\n${err.stderr || err.message}`);
|
|
104
|
+
}
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function runSqlite3(dbPath, sqlCmd, opts = {}) {
|
|
110
|
+
return runFile('sqlite3', [dbPath, sqlCmd], opts);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function runMc(args, opts = {}) {
|
|
114
|
+
return runFile(MC_BIN, args, opts);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// -- Snapshot (5-min) ----------------------------------------
|
|
118
|
+
function snapshot() {
|
|
119
|
+
if (!existsSync(DB_PATH)) {
|
|
120
|
+
log('error', `DB not found: ${DB_PATH}`);
|
|
121
|
+
process.exit(1);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Stage: checkpoint WAL then copy
|
|
125
|
+
mkdirSync(STAGING_DIR, { recursive: true });
|
|
126
|
+
const stagingFile = join(STAGING_DIR, 'scheduler-snapshot.db');
|
|
127
|
+
|
|
128
|
+
// Checkpoint WAL and copy the database file
|
|
129
|
+
if (!backupDatabase(DB_PATH, stagingFile)) {
|
|
130
|
+
log('warn', 'Structured backup failed, falling back to direct file copy');
|
|
131
|
+
copyFileSync(DB_PATH, stagingFile);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const size = statSync(stagingFile).size;
|
|
135
|
+
const d = now();
|
|
136
|
+
const dateStr = d.toISOString().slice(0, 10);
|
|
137
|
+
const timeStr = `${String(d.getUTCHours()).padStart(2, '0')}-${String(d.getUTCMinutes()).padStart(2, '0')}`;
|
|
138
|
+
const remotePath = mcPath(`snapshots/${dateStr}/${timeStr}.db`);
|
|
139
|
+
|
|
140
|
+
const uploadResult = runMc(['cp', stagingFile, remotePath]);
|
|
141
|
+
if (uploadResult !== null) {
|
|
142
|
+
log('info', `Snapshot shipped: ${remotePath} (${(size / 1024).toFixed(1)}KB)`);
|
|
143
|
+
} else {
|
|
144
|
+
log('error', `Failed to upload snapshot to ${remotePath}`);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Cleanup staging
|
|
148
|
+
try { unlinkSync(stagingFile); } catch {}
|
|
149
|
+
|
|
150
|
+
return { remotePath, size };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// -- Rollup (hourly) -----------------------------------------
|
|
154
|
+
function rollup() {
|
|
155
|
+
// First, take a snapshot and save it as a rollup
|
|
156
|
+
if (!existsSync(DB_PATH)) {
|
|
157
|
+
log('error', `DB not found: ${DB_PATH}`);
|
|
158
|
+
process.exit(1);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
mkdirSync(STAGING_DIR, { recursive: true });
|
|
162
|
+
const stagingFile = join(STAGING_DIR, 'scheduler-rollup.db');
|
|
163
|
+
|
|
164
|
+
if (!backupDatabase(DB_PATH, stagingFile)) {
|
|
165
|
+
log('warn', 'Structured backup failed in rollup, falling back to direct file copy');
|
|
166
|
+
copyFileSync(DB_PATH, stagingFile);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const size = statSync(stagingFile).size;
|
|
170
|
+
const d = now();
|
|
171
|
+
const dateStr = d.toISOString().slice(0, 10);
|
|
172
|
+
const hourStr = String(d.getUTCHours()).padStart(2, '0');
|
|
173
|
+
const remotePath = mcPath(`rollups/${dateStr}/${hourStr}.db`);
|
|
174
|
+
|
|
175
|
+
const rollupResult = runMc(['cp', stagingFile, remotePath]);
|
|
176
|
+
if (rollupResult !== null) {
|
|
177
|
+
log('info', `Rollup shipped: ${remotePath} (${(size / 1024).toFixed(1)}KB)`);
|
|
178
|
+
} else {
|
|
179
|
+
log('error', `Failed to upload rollup to ${remotePath}`);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
try { unlinkSync(stagingFile); } catch {}
|
|
183
|
+
|
|
184
|
+
// Only prune if the rollup uploaded successfully -- avoid deleting the only copies
|
|
185
|
+
if (rollupResult !== null) {
|
|
186
|
+
pruneSnapshots();
|
|
187
|
+
pruneRollups();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// -- Prune ---------------------------------------------------
|
|
192
|
+
function pruneSnapshots() {
|
|
193
|
+
const cutoff = new Date(Date.now() - SNAPSHOT_RETENTION_HOURS * 3600 * 1000);
|
|
194
|
+
const cutoffDate = cutoff.toISOString().slice(0, 10);
|
|
195
|
+
|
|
196
|
+
// List snapshot date directories
|
|
197
|
+
const listing = runMc(['ls', mcPath('snapshots/'), '--json'], { ignoreError: true });
|
|
198
|
+
if (!listing) return;
|
|
199
|
+
|
|
200
|
+
let pruned = 0;
|
|
201
|
+
for (const line of listing.split('\n').filter(Boolean)) {
|
|
202
|
+
try {
|
|
203
|
+
const obj = JSON.parse(line);
|
|
204
|
+
const dirName = obj.key?.replace(/\/$/, '');
|
|
205
|
+
if (dirName && dirName < cutoffDate) {
|
|
206
|
+
runMc(['rm', '--recursive', '--force', mcPath(`snapshots/${dirName}/`)], { ignoreError: true });
|
|
207
|
+
pruned++;
|
|
208
|
+
log('info', `Pruned snapshot dir: ${dirName}`);
|
|
209
|
+
}
|
|
210
|
+
} catch {}
|
|
211
|
+
}
|
|
212
|
+
if (pruned > 0) log('info', `Pruned ${pruned} old snapshot dir(s)`);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function pruneRollups() {
|
|
216
|
+
const cutoff = new Date(Date.now() - ROLLUP_RETENTION_DAYS * 86400 * 1000);
|
|
217
|
+
const cutoffDate = cutoff.toISOString().slice(0, 10);
|
|
218
|
+
|
|
219
|
+
const listing = runMc(['ls', mcPath('rollups/'), '--json'], { ignoreError: true });
|
|
220
|
+
if (!listing) return;
|
|
221
|
+
|
|
222
|
+
let pruned = 0;
|
|
223
|
+
for (const line of listing.split('\n').filter(Boolean)) {
|
|
224
|
+
try {
|
|
225
|
+
const obj = JSON.parse(line);
|
|
226
|
+
const dirName = obj.key?.replace(/\/$/, '');
|
|
227
|
+
if (dirName && dirName < cutoffDate) {
|
|
228
|
+
runMc(['rm', '--recursive', '--force', mcPath(`rollups/${dirName}/`)], { ignoreError: true });
|
|
229
|
+
pruned++;
|
|
230
|
+
log('info', `Pruned rollup dir: ${dirName}`);
|
|
231
|
+
}
|
|
232
|
+
} catch {}
|
|
233
|
+
}
|
|
234
|
+
if (pruned > 0) log('info', `Pruned ${pruned} old rollup dir(s)`);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// -- Restore -------------------------------------------------
|
|
238
|
+
function restore() {
|
|
239
|
+
// Find latest rollup first, then latest snapshot
|
|
240
|
+
let latest = null;
|
|
241
|
+
|
|
242
|
+
// Try rollups first (more reliable)
|
|
243
|
+
const rollupDirs = runMc(['ls', mcPath('rollups/'), '--json'], { ignoreError: true });
|
|
244
|
+
if (rollupDirs) {
|
|
245
|
+
const dirs = rollupDirs.split('\n').filter(Boolean).map(l => {
|
|
246
|
+
try { return JSON.parse(l).key?.replace(/\/$/, ''); } catch { return null; }
|
|
247
|
+
}).filter(Boolean).sort().reverse();
|
|
248
|
+
|
|
249
|
+
for (const dir of dirs) {
|
|
250
|
+
const files = runMc(['ls', mcPath(`rollups/${dir}/`), '--json'], { ignoreError: true });
|
|
251
|
+
if (files) {
|
|
252
|
+
const fList = files.split('\n').filter(Boolean).map(l => {
|
|
253
|
+
try { return JSON.parse(l).key; } catch { return null; }
|
|
254
|
+
}).filter(Boolean).sort().reverse();
|
|
255
|
+
if (fList.length > 0) {
|
|
256
|
+
latest = { type: 'rollup', path: mcPath(`rollups/${dir}/${fList[0]}`) };
|
|
257
|
+
break;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Try snapshots if no rollup found
|
|
264
|
+
if (!latest) {
|
|
265
|
+
const snapDirs = runMc(['ls', mcPath('snapshots/'), '--json'], { ignoreError: true });
|
|
266
|
+
if (snapDirs) {
|
|
267
|
+
const dirs = snapDirs.split('\n').filter(Boolean).map(l => {
|
|
268
|
+
try { return JSON.parse(l).key?.replace(/\/$/, ''); } catch { return null; }
|
|
269
|
+
}).filter(Boolean).sort().reverse();
|
|
270
|
+
|
|
271
|
+
for (const dir of dirs) {
|
|
272
|
+
const files = runMc(['ls', mcPath(`snapshots/${dir}/`), '--json'], { ignoreError: true });
|
|
273
|
+
if (files) {
|
|
274
|
+
const fList = files.split('\n').filter(Boolean).map(l => {
|
|
275
|
+
try { return JSON.parse(l).key; } catch { return null; }
|
|
276
|
+
}).filter(Boolean).sort().reverse();
|
|
277
|
+
if (fList.length > 0) {
|
|
278
|
+
latest = { type: 'snapshot', path: mcPath(`snapshots/${dir}/${fList[0]}`) };
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
if (!latest) {
|
|
287
|
+
log('error', 'No backups found to restore from');
|
|
288
|
+
process.exit(1);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
log('info', `Restoring from ${latest.type}: ${latest.path}`);
|
|
292
|
+
|
|
293
|
+
// Backup current DB
|
|
294
|
+
if (existsSync(DB_PATH)) {
|
|
295
|
+
const backupPath = `${DB_PATH}.pre-restore.${Date.now()}`;
|
|
296
|
+
copyFileSync(DB_PATH, backupPath);
|
|
297
|
+
log('info', `Current DB backed up to ${backupPath}`);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Download and replace
|
|
301
|
+
mkdirSync(STAGING_DIR, { recursive: true });
|
|
302
|
+
const downloadPath = join(STAGING_DIR, 'restore.db');
|
|
303
|
+
const dlResult = runMc(['cp', latest.path, downloadPath]);
|
|
304
|
+
if (dlResult === null) {
|
|
305
|
+
log('error', 'Download failed');
|
|
306
|
+
process.exit(1);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Verify the downloaded DB
|
|
310
|
+
if (!hasSqlite3()) {
|
|
311
|
+
log('error', 'sqlite3 not found in PATH; cannot verify downloaded DB integrity');
|
|
312
|
+
process.exit(1);
|
|
313
|
+
}
|
|
314
|
+
const verify = runSqlite3(downloadPath, 'SELECT count(*) FROM jobs');
|
|
315
|
+
if (verify === null) {
|
|
316
|
+
log('error', 'Downloaded DB failed verification (corrupt or missing expected tables)');
|
|
317
|
+
process.exit(1);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// Remove WAL/SHM files from current DB
|
|
321
|
+
try { unlinkSync(`${DB_PATH}-wal`); } catch {}
|
|
322
|
+
try { unlinkSync(`${DB_PATH}-shm`); } catch {}
|
|
323
|
+
|
|
324
|
+
// Replace
|
|
325
|
+
copyFileSync(downloadPath, DB_PATH);
|
|
326
|
+
try { unlinkSync(downloadPath); } catch {}
|
|
327
|
+
|
|
328
|
+
log('info', `Restored: ${verify} jobs from ${latest.type}`);
|
|
329
|
+
console.log(`Restored ${verify} jobs from ${latest.path}`);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// -- Status --------------------------------------------------
|
|
333
|
+
function status() {
|
|
334
|
+
console.log('=== Scheduler Backup Status ===\n');
|
|
335
|
+
|
|
336
|
+
// Current DB
|
|
337
|
+
if (existsSync(DB_PATH)) {
|
|
338
|
+
const st = statSync(DB_PATH);
|
|
339
|
+
console.log(`Local DB: ${(st.size / 1024).toFixed(1)}KB, modified ${st.mtime.toISOString()}`);
|
|
340
|
+
if (hasSqlite3()) {
|
|
341
|
+
const jobCount = runSqlite3(DB_PATH, 'SELECT count(*) FROM jobs') || '?';
|
|
342
|
+
console.log(`Jobs: ${jobCount}`);
|
|
343
|
+
} else {
|
|
344
|
+
console.log('Jobs: ? (sqlite3 not found in PATH)');
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// Snapshots
|
|
349
|
+
console.log('\nSnapshots (last 24h):');
|
|
350
|
+
const snapDirs = runMc(['ls', mcPath('snapshots/')], { ignoreError: true });
|
|
351
|
+
if (snapDirs) {
|
|
352
|
+
console.log(snapDirs);
|
|
353
|
+
} else {
|
|
354
|
+
console.log(' (none)');
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// Rollups
|
|
358
|
+
console.log('\nRollups (last 7d):');
|
|
359
|
+
const rollupDirsOut = runMc(['ls', mcPath('rollups/')], { ignoreError: true });
|
|
360
|
+
if (rollupDirsOut) {
|
|
361
|
+
console.log(rollupDirsOut);
|
|
362
|
+
} else {
|
|
363
|
+
console.log(' (none)');
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// Total size
|
|
367
|
+
const du = runMc(['du', mcPath('')], { ignoreError: true });
|
|
368
|
+
if (du) console.log(`\nTotal backup size: ${du}`);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// -- Exports for programmatic consumers -----------------------
|
|
372
|
+
export { snapshot, rollup, restore, status, pruneSnapshots, pruneRollups };
|
|
373
|
+
|
|
374
|
+
// -- Main (only runs when executed directly, not when imported) --
|
|
375
|
+
import { fileURLToPath } from 'url';
|
|
376
|
+
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
377
|
+
const command = process.argv[2] || 'status';
|
|
378
|
+
|
|
379
|
+
switch (command) {
|
|
380
|
+
case 'snapshot': snapshot(); break;
|
|
381
|
+
case 'rollup': rollup(); break;
|
|
382
|
+
case 'restore': restore(); break;
|
|
383
|
+
case 'status': status(); break;
|
|
384
|
+
case 'prune': pruneSnapshots(); pruneRollups(); break;
|
|
385
|
+
default:
|
|
386
|
+
console.error(`Unknown command: ${command}`);
|
|
387
|
+
console.error('Usage: node backup.js [snapshot|rollup|restore|status|prune]');
|
|
388
|
+
process.exit(1);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { spawnSync } from 'child_process';
|
|
4
|
+
import { readFileSync } from 'fs';
|
|
5
|
+
import { homedir } from 'os';
|
|
6
|
+
import { dirname, join } from 'path';
|
|
7
|
+
import { fileURLToPath } from 'url';
|
|
8
|
+
|
|
9
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
const root = join(__dirname, '..');
|
|
11
|
+
|
|
12
|
+
// Dispatch subcommands -- routed to dispatch/index.mjs
|
|
13
|
+
const DISPATCH_SUBCOMMANDS = new Set([
|
|
14
|
+
'dispatch',
|
|
15
|
+
'enqueue',
|
|
16
|
+
'stuck',
|
|
17
|
+
'result',
|
|
18
|
+
'sync',
|
|
19
|
+
'done',
|
|
20
|
+
'send',
|
|
21
|
+
'steer',
|
|
22
|
+
'heartbeat',
|
|
23
|
+
'list',
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
function printUsage() {
|
|
27
|
+
process.stdout.write(`
|
|
28
|
+
openclaw-scheduler <command> [args]
|
|
29
|
+
|
|
30
|
+
Commands:
|
|
31
|
+
setup [--service-mode agent|daemon|skip]
|
|
32
|
+
Run interactive setup wizard
|
|
33
|
+
start Start dispatcher loop
|
|
34
|
+
migrate Import OC cron jobs from ~/.openclaw/cron/jobs.json
|
|
35
|
+
status Show scheduler health
|
|
36
|
+
webhook-check Run Telegram webhook health check / repair utility
|
|
37
|
+
help Show this help
|
|
38
|
+
|
|
39
|
+
Dispatch subcommands (routed to dispatch/index.mjs):
|
|
40
|
+
dispatch <sub> Explicit dispatch namespace
|
|
41
|
+
enqueue Spawn a sub-agent session (alias: dispatch enqueue)
|
|
42
|
+
dispatch status Query session status by label
|
|
43
|
+
stuck Find sessions running past threshold
|
|
44
|
+
result Get last assistant reply from a session
|
|
45
|
+
send / steer Send/steer a running session
|
|
46
|
+
heartbeat Check session liveness
|
|
47
|
+
list List all tracked labels
|
|
48
|
+
sync Reconcile labels.json with sessions store
|
|
49
|
+
done Agent-side completion signal
|
|
50
|
+
|
|
51
|
+
All other commands are forwarded to scheduler CLI (cli.js):
|
|
52
|
+
openclaw-scheduler jobs list
|
|
53
|
+
openclaw-scheduler runs running
|
|
54
|
+
openclaw-scheduler msg send system main "hello"
|
|
55
|
+
|
|
56
|
+
Flags:
|
|
57
|
+
--json Output machine-readable JSON (supported by all CLI subcommands)
|
|
58
|
+
|
|
59
|
+
Environment:
|
|
60
|
+
DISPATCH_CONFIG_DIR Override dispatch config directory (default: ~/.openclaw/dispatch)
|
|
61
|
+
`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function hasDispatchStatusLabel(args) {
|
|
65
|
+
return args.some(arg => arg === '--label' || arg.startsWith('--label='));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function runScript(script, args) {
|
|
69
|
+
const scriptPath = join(root, script);
|
|
70
|
+
const result = spawnSync(process.execPath, [scriptPath, ...args], {
|
|
71
|
+
stdio: 'inherit',
|
|
72
|
+
env: process.env,
|
|
73
|
+
});
|
|
74
|
+
if (result.error) {
|
|
75
|
+
process.stderr.write(`Error: could not run ${script}: ${result.error.message}\n`);
|
|
76
|
+
process.exit(1);
|
|
77
|
+
}
|
|
78
|
+
process.exit(typeof result.status === 'number' ? result.status : 1);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Run dispatch/index.mjs with the given args.
|
|
83
|
+
* Honors DISPATCH_CONFIG_DIR env var for config override.
|
|
84
|
+
* Defaults to ~/.openclaw/dispatch if not set.
|
|
85
|
+
*/
|
|
86
|
+
function runDispatch(args) {
|
|
87
|
+
const dispatchScript = join(root, 'dispatch', 'index.mjs');
|
|
88
|
+
const env = { ...process.env };
|
|
89
|
+
if (!env.DISPATCH_CONFIG_DIR) {
|
|
90
|
+
env.DISPATCH_CONFIG_DIR = join(process.env.HOME || homedir(), '.openclaw', 'dispatch');
|
|
91
|
+
}
|
|
92
|
+
const result = spawnSync(process.execPath, [dispatchScript, ...args], {
|
|
93
|
+
stdio: 'inherit',
|
|
94
|
+
env,
|
|
95
|
+
});
|
|
96
|
+
if (result.error) {
|
|
97
|
+
process.stderr.write(`Error: could not run dispatch: ${result.error.message}\n`);
|
|
98
|
+
process.exit(1);
|
|
99
|
+
}
|
|
100
|
+
process.exit(typeof result.status === 'number' ? result.status : 1);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const args = process.argv.slice(2);
|
|
104
|
+
const cmd = args[0] || '';
|
|
105
|
+
|
|
106
|
+
if (cmd === 'help' || cmd === '--help' || cmd === '-h') {
|
|
107
|
+
printUsage();
|
|
108
|
+
process.exit(0);
|
|
109
|
+
} else if (cmd === 'setup') {
|
|
110
|
+
runScript('setup.mjs', args.slice(1));
|
|
111
|
+
} else if (cmd === 'start' || cmd === 'dispatcher') {
|
|
112
|
+
runScript('dispatcher.js', args.slice(1));
|
|
113
|
+
} else if (cmd === 'migrate') {
|
|
114
|
+
runScript('migrate.js', args.slice(1));
|
|
115
|
+
} else if (cmd === 'webhook-check') {
|
|
116
|
+
runScript('scripts/telegram-webhook-check.mjs', args.slice(1));
|
|
117
|
+
} else if (cmd === 'version' || cmd === '--version' || cmd === '-v') {
|
|
118
|
+
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
|
119
|
+
process.stdout.write(`${pkg.name} ${pkg.version}\n`);
|
|
120
|
+
process.exit(0);
|
|
121
|
+
} else if (cmd === 'status' && hasDispatchStatusLabel(args.slice(1))) {
|
|
122
|
+
// Preserve the historical dispatch convenience alias:
|
|
123
|
+
// openclaw-scheduler status --label <name>
|
|
124
|
+
// Without --label, "status" means scheduler health via cli.js.
|
|
125
|
+
runDispatch(args);
|
|
126
|
+
} else if (DISPATCH_SUBCOMMANDS.has(cmd)) {
|
|
127
|
+
// Route dispatch subcommands to dispatch/index.mjs
|
|
128
|
+
// If the command is 'dispatch', strip it and pass the rest
|
|
129
|
+
// If it's a convenience alias (enqueue, status, etc.), pass everything as-is
|
|
130
|
+
if (cmd === 'dispatch') {
|
|
131
|
+
runDispatch(args.slice(1));
|
|
132
|
+
} else {
|
|
133
|
+
runDispatch(args);
|
|
134
|
+
}
|
|
135
|
+
} else {
|
|
136
|
+
// All other commands forwarded to scheduler CLI (cli.js)
|
|
137
|
+
runScript('cli.js', args);
|
|
138
|
+
}
|