talon-agent 5.26.1 → 5.26.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/package.json +1 -1
- package/src/app.ts +42 -1
- package/src/bootstrap.ts +171 -57
- package/src/cli/commands/backup.ts +4 -1
- package/src/core/backup/boot/version-checkpoint.ts +199 -0
- package/src/core/backup/index.ts +3 -0
- package/src/core/backup/passphrase.ts +55 -2
- package/src/core/backup/restore.ts +32 -4
- package/src/core/backup/scheduler.ts +125 -13
- package/src/core/backup/status.ts +26 -3
- package/src/core/update/self-update.ts +144 -47
- package/src/frontend/discord/commands/admin.ts +22 -3
- package/src/frontend/discord/commands/definitions.ts +7 -0
- package/src/frontend/telegram/commands/admin.ts +21 -3
- package/src/storage/backup/index.ts +1 -1
- package/src/storage/chat-settings.ts +13 -0
- package/src/storage/db.ts +5 -0
- package/src/storage/media-index.ts +4 -3
- package/src/storage/sessions.ts +60 -1
|
@@ -37,7 +37,7 @@ import {
|
|
|
37
37
|
copyFile,
|
|
38
38
|
} from "node:fs/promises";
|
|
39
39
|
import { homedir } from "node:os";
|
|
40
|
-
import { dirname, join } from "node:path";
|
|
40
|
+
import { dirname, join, resolve } from "node:path";
|
|
41
41
|
import writeFileAtomic from "write-file-atomic";
|
|
42
42
|
import { dirs } from "../../util/paths.js";
|
|
43
43
|
import { log, logWarn } from "../../util/log.js";
|
|
@@ -50,7 +50,7 @@ import {
|
|
|
50
50
|
import { sha256File } from "./archive/digest.js";
|
|
51
51
|
import { extractTar } from "./archive/tar.js";
|
|
52
52
|
import { createDecompressor } from "./archive/zstd.js";
|
|
53
|
-
import { requirePassphrase } from "./passphrase.js";
|
|
53
|
+
import { passphraseFilePath, requirePassphrase } from "./passphrase.js";
|
|
54
54
|
import { collectTree, excludeForRoot } from "./plan.js";
|
|
55
55
|
import {
|
|
56
56
|
authenticateManifest,
|
|
@@ -348,20 +348,32 @@ export function destinationFor(
|
|
|
348
348
|
return join(home, ...segments);
|
|
349
349
|
}
|
|
350
350
|
|
|
351
|
+
/** True when `path` is the active backup passphrase file. */
|
|
352
|
+
function isKeyFile(path: string, keyFile: string | null): boolean {
|
|
353
|
+
return keyFile !== null && resolve(path) === keyFile;
|
|
354
|
+
}
|
|
355
|
+
|
|
351
356
|
/**
|
|
352
357
|
* Bring one include root to exactly the snapshot's state: remove what the
|
|
353
358
|
* snapshot rules would have captured, keep what they deliberately skip.
|
|
354
359
|
* Returns how many live files were removed.
|
|
360
|
+
*
|
|
361
|
+
* The active passphrase file is never removed. The snapshot builder leaves
|
|
362
|
+
* it out of every part (a key inside the backup it unlocks is no key), so
|
|
363
|
+
* when it sits inside an include root — `workspace/secrets/`, `keys/`, an
|
|
364
|
+
* extra path — nothing in the snapshot would ever put it back.
|
|
355
365
|
*/
|
|
356
366
|
async function clearCovered(
|
|
357
367
|
destRoot: string,
|
|
358
368
|
archiveRoot: string,
|
|
369
|
+
keyFile: string | null,
|
|
359
370
|
): Promise<number> {
|
|
360
371
|
const existing = await collectTree(destRoot, archiveRoot, {
|
|
361
372
|
exclude: excludeForRoot(archiveRoot),
|
|
362
373
|
});
|
|
363
374
|
let removed = 0;
|
|
364
375
|
for (const entry of [...existing].reverse()) {
|
|
376
|
+
if (isKeyFile(entry.source, keyFile)) continue;
|
|
365
377
|
try {
|
|
366
378
|
if (entry.type === "dir") await rmdir(entry.source).catch(() => {});
|
|
367
379
|
else {
|
|
@@ -410,6 +422,7 @@ async function applyStaged(
|
|
|
410
422
|
staging: string,
|
|
411
423
|
home: string,
|
|
412
424
|
external: readonly ExternalDestination[],
|
|
425
|
+
keyFile: string | null,
|
|
413
426
|
): Promise<RestoreReport> {
|
|
414
427
|
const extras = manifest.extras ?? [];
|
|
415
428
|
const report: RestoreReport = {
|
|
@@ -429,7 +442,7 @@ async function applyStaged(
|
|
|
429
442
|
logWarn("backup", `No destination for ${root} on this machine — skipped`);
|
|
430
443
|
continue;
|
|
431
444
|
}
|
|
432
|
-
report.removed += await clearCovered(destRoot, root);
|
|
445
|
+
report.removed += await clearCovered(destRoot, root, keyFile);
|
|
433
446
|
// A session database's sidecars describe the file being replaced.
|
|
434
447
|
if (external.some((entry) => entry.root === root && entry.sqlite)) {
|
|
435
448
|
await rm(`${destRoot}-wal`, { force: true });
|
|
@@ -439,6 +452,15 @@ async function applyStaged(
|
|
|
439
452
|
for (const entry of staged) {
|
|
440
453
|
const dest = destinationFor(entry.archivePath, home, extras, external);
|
|
441
454
|
if (!dest) continue;
|
|
455
|
+
// An older snapshot (or one from another machine) may carry a file
|
|
456
|
+
// where this machine keeps its key. The key path is never written.
|
|
457
|
+
if (entry.type !== "dir" && isKeyFile(dest, keyFile)) {
|
|
458
|
+
logWarn(
|
|
459
|
+
"backup",
|
|
460
|
+
`Left the backup passphrase file ${dest} untouched — the snapshot's copy was not applied`,
|
|
461
|
+
);
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
442
464
|
if (entry.type === "dir") await mkdir(dest, { recursive: true });
|
|
443
465
|
else {
|
|
444
466
|
await placeFile(entry.source, dest);
|
|
@@ -585,7 +607,13 @@ export async function restoreSnapshot(
|
|
|
585
607
|
const staging = join(snapshotDir(manifest.id, home), "restore-staging");
|
|
586
608
|
await extractParts(manifest, home, staging, options.settings, parts);
|
|
587
609
|
await options.beforeApply?.();
|
|
588
|
-
const report = await applyStaged(
|
|
610
|
+
const report = await applyStaged(
|
|
611
|
+
manifest,
|
|
612
|
+
staging,
|
|
613
|
+
home,
|
|
614
|
+
external,
|
|
615
|
+
passphraseFilePath(options.settings),
|
|
616
|
+
);
|
|
589
617
|
report.checkpointId = checkpointId;
|
|
590
618
|
if (options.clone && manifest.origin) {
|
|
591
619
|
report.configRewritten = await rewriteConfigForClone(
|
|
@@ -31,6 +31,7 @@ import { faultText } from "../engine/fault-text.js";
|
|
|
31
31
|
import { bus } from "../bus/index.js";
|
|
32
32
|
import { log, logError } from "../../util/log.js";
|
|
33
33
|
import { dirs } from "../../util/paths.js";
|
|
34
|
+
import { passphraseProblem } from "./passphrase.js";
|
|
34
35
|
import { buildSnapshot } from "./snapshot.js";
|
|
35
36
|
import { listLocalManifests, pruneLocal, reconcileIndex } from "./store.js";
|
|
36
37
|
import { discoverTargets, selectTargets } from "./targets.js";
|
|
@@ -54,6 +55,7 @@ export type RunRequest = {
|
|
|
54
55
|
/** Test seam: the expensive collaborators, swappable in unit tests. */
|
|
55
56
|
export const _backupDeps = {
|
|
56
57
|
build: buildSnapshot,
|
|
58
|
+
keyProblem: (settings: BackupSettings) => passphraseProblem(settings),
|
|
57
59
|
discover: discoverTargets,
|
|
58
60
|
upload: uploadSnapshot,
|
|
59
61
|
pruneLocal,
|
|
@@ -85,6 +87,10 @@ type SchedulerState = {
|
|
|
85
87
|
lastSnapshotId: string | undefined;
|
|
86
88
|
lastError: string | undefined;
|
|
87
89
|
nextRunAt: number | undefined;
|
|
90
|
+
/** The hourly passphrase check (see checkBackupKey). */
|
|
91
|
+
keyTimer: ReturnType<typeof setInterval> | null;
|
|
92
|
+
/** What was wrong with the key at the last check, if anything. */
|
|
93
|
+
keyProblem: string | undefined;
|
|
88
94
|
};
|
|
89
95
|
|
|
90
96
|
const state: SchedulerState = {
|
|
@@ -100,6 +106,8 @@ const state: SchedulerState = {
|
|
|
100
106
|
lastSnapshotId: undefined,
|
|
101
107
|
lastError: undefined,
|
|
102
108
|
nextRunAt: undefined,
|
|
109
|
+
keyTimer: null,
|
|
110
|
+
keyProblem: undefined,
|
|
103
111
|
};
|
|
104
112
|
|
|
105
113
|
/**
|
|
@@ -242,6 +250,7 @@ async function tick(generation: number): Promise<void> {
|
|
|
242
250
|
const intervalMs = settings.intervalHours * HOUR_MS;
|
|
243
251
|
// Recomputed every tick: a suspended machine or a stepped clock lands
|
|
244
252
|
// here late, and the answer is "run now", not "run N missed times".
|
|
253
|
+
await checkBackupKey();
|
|
245
254
|
if (backoff.active()) {
|
|
246
255
|
schedule(Math.min(intervalMs, BOOT_DELAY_MS), generation);
|
|
247
256
|
return;
|
|
@@ -254,6 +263,82 @@ async function tick(generation: number): Promise<void> {
|
|
|
254
263
|
schedule(intervalMs, generation);
|
|
255
264
|
}
|
|
256
265
|
|
|
266
|
+
// ── The key check ───────────────────────────────────────────────────────────
|
|
267
|
+
|
|
268
|
+
const KEY_ALERT = "backup.key";
|
|
269
|
+
const KEY_CHECK_MS = HOUR_MS;
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Is the configured passphrase still there? A key that disappears breaks
|
|
273
|
+
* every snapshot and the pre-update checkpoint, and a run only notices at
|
|
274
|
+
* its next window, hours later. So this runs at boot, every hour, before
|
|
275
|
+
* each scheduled run and on every status request.
|
|
276
|
+
*
|
|
277
|
+
* It tells the admin once when the key goes bad and once when it is back,
|
|
278
|
+
* never on every check. Returns the current problem, or null. Never throws.
|
|
279
|
+
*/
|
|
280
|
+
export async function checkBackupKey(): Promise<string | null> {
|
|
281
|
+
const settings = state.settings;
|
|
282
|
+
if (!settings) return null;
|
|
283
|
+
let problem: { message: string; blocking: boolean } | null;
|
|
284
|
+
try {
|
|
285
|
+
problem = await _backupDeps.keyProblem(settings);
|
|
286
|
+
} catch (err) {
|
|
287
|
+
problem = {
|
|
288
|
+
message: err instanceof Error ? err.message : String(err),
|
|
289
|
+
blocking: true,
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
// A check that finished after a reconfiguration describes old settings.
|
|
293
|
+
if (state.settings !== settings) return state.keyProblem ?? null;
|
|
294
|
+
const previous = state.keyProblem;
|
|
295
|
+
state.keyProblem = problem?.message;
|
|
296
|
+
if (problem && previous === undefined) {
|
|
297
|
+
await reportKeyProblem(problem);
|
|
298
|
+
} else if (!problem && previous !== undefined) {
|
|
299
|
+
await reportKeyRecovered();
|
|
300
|
+
}
|
|
301
|
+
return problem?.message ?? null;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async function reportKeyProblem(problem: {
|
|
305
|
+
message: string;
|
|
306
|
+
blocking: boolean;
|
|
307
|
+
}): Promise<void> {
|
|
308
|
+
const consequence = problem.blocking
|
|
309
|
+
? "Backups and the pre-update checkpoint will fail until it is fixed, and /update is refused unless forced."
|
|
310
|
+
: "Backups still run for now.";
|
|
311
|
+
const text = `Backup key problem: ${faultText(problem.message, 300)}. ${consequence}`;
|
|
312
|
+
logError("backup", text);
|
|
313
|
+
if (state.notify === notifyAdmin) {
|
|
314
|
+
raiseAlert(KEY_ALERT, text, {
|
|
315
|
+
severity: problem.blocking ? "error" : "warn",
|
|
316
|
+
});
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
await state.notify(`⚠️ ${text}`).catch(() => {
|
|
320
|
+
/* the notifier logs its own failures */
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async function reportKeyRecovered(): Promise<void> {
|
|
325
|
+
const text = "The backup passphrase is readable again.";
|
|
326
|
+
log("backup", text);
|
|
327
|
+
if (state.notify === notifyAdmin) {
|
|
328
|
+
resolveAlert(KEY_ALERT, text);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
await state.notify(`✅ ${text}`).catch(() => {
|
|
332
|
+
/* the notifier logs its own failures */
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function armKeyCheck(): void {
|
|
337
|
+
if (state.keyTimer) clearInterval(state.keyTimer);
|
|
338
|
+
state.keyTimer = setInterval(() => void checkBackupKey(), KEY_CHECK_MS);
|
|
339
|
+
state.keyTimer.unref?.();
|
|
340
|
+
}
|
|
341
|
+
|
|
257
342
|
/**
|
|
258
343
|
* Wire the subsystem and arm the timer. Safe to call with backups
|
|
259
344
|
* disabled — it reconciles the index either way, so the listing surfaces
|
|
@@ -274,6 +359,10 @@ export async function initBackup(options: {
|
|
|
274
359
|
const newest = (await listLocalManifests(state.home))[0];
|
|
275
360
|
state.lastRunAt = newest?.createdAt ?? 0;
|
|
276
361
|
state.lastSnapshotId = newest?.id;
|
|
362
|
+
// The key is checked whether or not the schedule runs: manual
|
|
363
|
+
// checkpoints and the pre-update checkpoint need it too.
|
|
364
|
+
await checkBackupKey();
|
|
365
|
+
armKeyCheck();
|
|
277
366
|
if (!options.settings.enabled) {
|
|
278
367
|
log(
|
|
279
368
|
"backup",
|
|
@@ -301,6 +390,8 @@ export function stopBackupScheduler(): void {
|
|
|
301
390
|
if (state.timer) clearTimeout(state.timer);
|
|
302
391
|
state.timer = null;
|
|
303
392
|
state.nextRunAt = undefined;
|
|
393
|
+
if (state.keyTimer) clearInterval(state.keyTimer);
|
|
394
|
+
state.keyTimer = null;
|
|
304
395
|
}
|
|
305
396
|
|
|
306
397
|
/** What the status surfaces report about the schedule itself. */
|
|
@@ -326,18 +417,39 @@ export function schedulerStatus(): {
|
|
|
326
417
|
};
|
|
327
418
|
}
|
|
328
419
|
|
|
420
|
+
/**
|
|
421
|
+
* What the pre-update hook managed. `disabled` is the operator's explicit
|
|
422
|
+
* opt-out (`backup.checkpointBeforeUpdate: false`); `failed` covers both a
|
|
423
|
+
* run that threw and a process with no backup subsystem to ask.
|
|
424
|
+
*/
|
|
425
|
+
export type UpdateCheckpoint =
|
|
426
|
+
| { status: "taken"; id: string }
|
|
427
|
+
| { status: "disabled" }
|
|
428
|
+
| { status: "failed"; error: string };
|
|
429
|
+
|
|
329
430
|
/**
|
|
330
431
|
* The self-update hook: a pinned checkpoint before the tree moves, so a
|
|
331
|
-
* bad update is one `talon backup restore` away from undone.
|
|
332
|
-
*
|
|
333
|
-
*
|
|
334
|
-
*
|
|
432
|
+
* bad update is one `talon backup restore` away from undone.
|
|
433
|
+
*
|
|
434
|
+
* Never throws — it reports. The caller decides: `/update` refuses to go
|
|
435
|
+
* on after a `failed` checkpoint unless the operator forces it, because
|
|
436
|
+
* an update with no way back is exactly when data goes missing.
|
|
437
|
+
*
|
|
438
|
+
* `backup.enabled: false` only stops the schedule; manual checkpoints
|
|
439
|
+
* still work, so this one is still taken.
|
|
335
440
|
*/
|
|
336
441
|
export async function checkpointBeforeUpdate(
|
|
337
442
|
fromVersion: string,
|
|
338
443
|
toVersion: string,
|
|
339
|
-
): Promise<
|
|
340
|
-
|
|
444
|
+
): Promise<UpdateCheckpoint> {
|
|
445
|
+
const settings = state.settings;
|
|
446
|
+
if (!settings) {
|
|
447
|
+
return {
|
|
448
|
+
status: "failed",
|
|
449
|
+
error: "the backup subsystem is not running in this process",
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
if (!settings.checkpointBeforeUpdate) return { status: "disabled" };
|
|
341
453
|
try {
|
|
342
454
|
const manifest = await runBackup({
|
|
343
455
|
kind: "checkpoint",
|
|
@@ -345,14 +457,13 @@ export async function checkpointBeforeUpdate(
|
|
|
345
457
|
pinned: true,
|
|
346
458
|
trigger: "pre-update",
|
|
347
459
|
});
|
|
348
|
-
return manifest.id;
|
|
460
|
+
return { status: "taken", id: manifest.id };
|
|
349
461
|
} catch (err) {
|
|
350
|
-
logError(
|
|
351
|
-
|
|
352
|
-
"
|
|
353
|
-
err,
|
|
354
|
-
|
|
355
|
-
return null;
|
|
462
|
+
logError("backup", "Pre-update checkpoint failed", err);
|
|
463
|
+
return {
|
|
464
|
+
status: "failed",
|
|
465
|
+
error: err instanceof Error ? err.message : String(err),
|
|
466
|
+
};
|
|
356
467
|
}
|
|
357
468
|
}
|
|
358
469
|
|
|
@@ -372,5 +483,6 @@ export function _resetBackupScheduler(): void {
|
|
|
372
483
|
state.lastRunAt = 0;
|
|
373
484
|
state.lastSnapshotId = undefined;
|
|
374
485
|
state.lastError = undefined;
|
|
486
|
+
state.keyProblem = undefined;
|
|
375
487
|
backoff.succeed();
|
|
376
488
|
}
|
|
@@ -15,8 +15,12 @@ import {
|
|
|
15
15
|
selectTargets,
|
|
16
16
|
type BackupTarget,
|
|
17
17
|
} from "./targets.js";
|
|
18
|
-
import {
|
|
19
|
-
|
|
18
|
+
import {
|
|
19
|
+
backupSettings,
|
|
20
|
+
checkBackupKey,
|
|
21
|
+
schedulerStatus,
|
|
22
|
+
} from "./scheduler.js";
|
|
23
|
+
import { PASSPHRASE_ENV, passphraseProblem } from "./passphrase.js";
|
|
20
24
|
import type { BackupSettings, SnapshotSummary } from "./types.js";
|
|
21
25
|
|
|
22
26
|
type TargetStatus = {
|
|
@@ -41,6 +45,8 @@ export type BackupStatus = {
|
|
|
41
45
|
snapshots: SnapshotSummary[];
|
|
42
46
|
/** Retention and encryption, when the subsystem is initialised. */
|
|
43
47
|
policy?: BackupPolicy;
|
|
48
|
+
/** What is wrong with the configured passphrase, if anything. */
|
|
49
|
+
keyProblem?: string;
|
|
44
50
|
};
|
|
45
51
|
|
|
46
52
|
/** The settings a status panel renders alongside the numbers. */
|
|
@@ -125,12 +131,25 @@ export async function collectBackupStatus(
|
|
|
125
131
|
options: {
|
|
126
132
|
home?: string;
|
|
127
133
|
withTargets?: boolean;
|
|
134
|
+
/**
|
|
135
|
+
* Settings to describe when this process runs no backup subsystem
|
|
136
|
+
* (the CLI with the daemon down). The daemon's own settings win.
|
|
137
|
+
*/
|
|
138
|
+
settings?: BackupSettings;
|
|
128
139
|
} = {},
|
|
129
140
|
): Promise<BackupStatus> {
|
|
130
141
|
const home = options.home ?? dirs.root;
|
|
131
142
|
const snapshots = await listSnapshots(home);
|
|
132
143
|
const local = snapshots.filter((snapshot) => snapshot.local);
|
|
133
|
-
const
|
|
144
|
+
const live = backupSettings();
|
|
145
|
+
const settings = live ?? options.settings ?? null;
|
|
146
|
+
// In the daemon the check also raises (or clears) the key alert; outside
|
|
147
|
+
// it there is nobody to alert, so it only reports.
|
|
148
|
+
const keyProblem = live
|
|
149
|
+
? await checkBackupKey()
|
|
150
|
+
: settings
|
|
151
|
+
? ((await passphraseProblem(settings))?.message ?? null)
|
|
152
|
+
: null;
|
|
134
153
|
const targets =
|
|
135
154
|
options.withTargets === false
|
|
136
155
|
? []
|
|
@@ -148,6 +167,7 @@ export async function collectBackupStatus(
|
|
|
148
167
|
targets,
|
|
149
168
|
snapshots,
|
|
150
169
|
policy: describePolicy(settings),
|
|
170
|
+
...(keyProblem ? { keyProblem } : {}),
|
|
151
171
|
};
|
|
152
172
|
}
|
|
153
173
|
|
|
@@ -198,6 +218,9 @@ export function formatBackupStatus(
|
|
|
198
218
|
`Last run: ${formatRelative(schedule.lastRunAt, now)}` +
|
|
199
219
|
(schedule.lastSnapshotId ? ` — ${schedule.lastSnapshotId}` : ""),
|
|
200
220
|
);
|
|
221
|
+
if (status.keyProblem) {
|
|
222
|
+
lines.push(`Key: PROBLEM — ${status.keyProblem}`);
|
|
223
|
+
}
|
|
201
224
|
if (schedule.consecutiveFailures > 0) {
|
|
202
225
|
lines.push(
|
|
203
226
|
`Failing: ${schedule.consecutiveFailures} consecutive — ${schedule.lastError ?? "unknown error"}`,
|
|
@@ -27,10 +27,19 @@
|
|
|
27
27
|
* can never leave the deployment un-updatable, which is what the old
|
|
28
28
|
* `pull --ff-only` did (it aborts on any dirty/diverged tree). `.gitignore`
|
|
29
29
|
* is respected (no `-x`), so node_modules, secrets and local config survive.
|
|
30
|
+
*
|
|
31
|
+
* Before anything in the checkout moves, a pinned pre-update checkpoint is
|
|
32
|
+
* taken. If it fails, the update is refused. An update with no way back is
|
|
33
|
+
* when data goes missing, so the operator must say `force` to go on
|
|
34
|
+
* without one. Opting out in config (`backup.checkpointBeforeUpdate:
|
|
35
|
+
* false`) is the only way to skip it without being asked.
|
|
30
36
|
*/
|
|
31
37
|
|
|
32
38
|
import { execFile } from "node:child_process";
|
|
33
|
-
import {
|
|
39
|
+
import {
|
|
40
|
+
checkpointBeforeUpdate,
|
|
41
|
+
type UpdateCheckpoint,
|
|
42
|
+
} from "../backup/index.js";
|
|
34
43
|
import { existsSync } from "node:fs";
|
|
35
44
|
import { dirname, join } from "node:path";
|
|
36
45
|
import { fileURLToPath } from "node:url";
|
|
@@ -60,6 +69,13 @@ export interface UpdateOptions {
|
|
|
60
69
|
entry?: { cmd: string; args: readonly string[] };
|
|
61
70
|
/** Injectable command runner (tests). */
|
|
62
71
|
runner?: CommandRunner;
|
|
72
|
+
/**
|
|
73
|
+
* Go on even when the pre-update checkpoint fails (`/update force`).
|
|
74
|
+
* The result still says the checkpoint failed.
|
|
75
|
+
*/
|
|
76
|
+
force?: boolean;
|
|
77
|
+
/** Injectable pre-update checkpoint (tests). */
|
|
78
|
+
checkpoint?: (from: string, to: string) => Promise<UpdateCheckpoint>;
|
|
63
79
|
}
|
|
64
80
|
|
|
65
81
|
/** One executed step in an update run. */
|
|
@@ -82,6 +98,13 @@ export interface UpdateResult {
|
|
|
82
98
|
changed: boolean;
|
|
83
99
|
/** Human-readable failure reason when `ok` is false. */
|
|
84
100
|
error?: string;
|
|
101
|
+
/** The pre-update checkpoint, when the update got far enough to take one. */
|
|
102
|
+
checkpoint?: UpdateCheckpoint;
|
|
103
|
+
/**
|
|
104
|
+
* True when the update was refused because the checkpoint failed. Nothing
|
|
105
|
+
* in the checkout was touched; `force` would have gone on.
|
|
106
|
+
*/
|
|
107
|
+
checkpointRefused?: boolean;
|
|
85
108
|
}
|
|
86
109
|
|
|
87
110
|
export type CommandRunner = (
|
|
@@ -171,12 +194,7 @@ export async function runSelfUpdate(
|
|
|
171
194
|
const branch = opts.branch?.trim() || "main";
|
|
172
195
|
const run = opts.runner ?? defaultRunner;
|
|
173
196
|
|
|
174
|
-
const record = async (
|
|
175
|
-
label: string,
|
|
176
|
-
cmd: string,
|
|
177
|
-
args: readonly string[],
|
|
178
|
-
timeoutMs: number,
|
|
179
|
-
): Promise<UpdateStep> => {
|
|
197
|
+
const record: Recorder = async (label, cmd, args, timeoutMs) => {
|
|
180
198
|
const { ok, output } = await run(cmd, args, repoRoot, timeoutMs);
|
|
181
199
|
const step: UpdateStep = { label, ok, output };
|
|
182
200
|
steps.push(step);
|
|
@@ -210,22 +228,58 @@ export async function runSelfUpdate(
|
|
|
210
228
|
);
|
|
211
229
|
if (!fetch.ok) return fail(`git fetch failed: ${fetch.output}`, before);
|
|
212
230
|
|
|
231
|
+
// Where the update is going, read before the tree moves: the checkpoint
|
|
232
|
+
// is labelled with it, and "already up to date" needs no checkpoint.
|
|
233
|
+
const targetRef = `${remote}/${branch}`;
|
|
234
|
+
const target = await record(
|
|
235
|
+
`rev-parse ${targetRef}`,
|
|
236
|
+
"git",
|
|
237
|
+
["rev-parse", targetRef],
|
|
238
|
+
GIT_TIMEOUT_MS,
|
|
239
|
+
);
|
|
240
|
+
if (!target.ok) {
|
|
241
|
+
return fail(`Failed to read ${targetRef}: ${target.output}`, before);
|
|
242
|
+
}
|
|
243
|
+
const upcoming = shortSha(target.output);
|
|
244
|
+
|
|
245
|
+
// The safety net goes up before anything is destroyed: the reset and
|
|
246
|
+
// clean below discard local state, and the new code may migrate data.
|
|
247
|
+
let checkpoint: UpdateCheckpoint | undefined;
|
|
248
|
+
if (upcoming !== before) {
|
|
249
|
+
checkpoint = await (opts.checkpoint ?? checkpointBeforeUpdate)(
|
|
250
|
+
before,
|
|
251
|
+
upcoming,
|
|
252
|
+
);
|
|
253
|
+
steps.push({
|
|
254
|
+
label: "pre-update checkpoint",
|
|
255
|
+
ok: checkpoint.status !== "failed",
|
|
256
|
+
output: describeCheckpoint(checkpoint),
|
|
257
|
+
});
|
|
258
|
+
if (checkpoint.status === "failed" && !opts.force) {
|
|
259
|
+
return {
|
|
260
|
+
...fail(refusal(checkpoint.error), before),
|
|
261
|
+
checkpoint,
|
|
262
|
+
checkpointRefused: true,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
213
267
|
// Force the checkout to exactly match the freshly-fetched remote
|
|
214
268
|
// branch, discarding ANY local edits or diverged commits. The old
|
|
215
269
|
// `pull --ff-only` aborted here whenever the tree was dirty, leaving the
|
|
216
270
|
// deployment stuck; a bot host is meant to mirror the remote, so resetting
|
|
217
271
|
// to it is both correct and reliable.
|
|
218
272
|
const reset = await record(
|
|
219
|
-
`reset --hard ${
|
|
273
|
+
`reset --hard ${targetRef}`,
|
|
220
274
|
"git",
|
|
221
|
-
["reset", "--hard",
|
|
275
|
+
["reset", "--hard", targetRef],
|
|
222
276
|
GIT_TIMEOUT_MS,
|
|
223
277
|
);
|
|
224
278
|
if (!reset.ok) {
|
|
225
|
-
return
|
|
226
|
-
`git reset --hard ${
|
|
227
|
-
|
|
228
|
-
|
|
279
|
+
return {
|
|
280
|
+
...fail(`git reset --hard ${targetRef} failed: ${reset.output}`, before),
|
|
281
|
+
checkpoint,
|
|
282
|
+
};
|
|
229
283
|
}
|
|
230
284
|
|
|
231
285
|
// Drop untracked files too so the tree is pristine and a future update
|
|
@@ -246,28 +300,62 @@ export async function runSelfUpdate(
|
|
|
246
300
|
// Nothing moved — skip the expensive install/setup and tell the
|
|
247
301
|
// caller no restart is needed.
|
|
248
302
|
if (!changed) {
|
|
249
|
-
return {
|
|
303
|
+
return {
|
|
304
|
+
ok: true,
|
|
305
|
+
repoRoot,
|
|
306
|
+
steps,
|
|
307
|
+
before,
|
|
308
|
+
after,
|
|
309
|
+
changed: false,
|
|
310
|
+
checkpoint,
|
|
311
|
+
};
|
|
250
312
|
}
|
|
251
313
|
|
|
252
|
-
await
|
|
314
|
+
const error = await installAndVerify(record, opts, before, after);
|
|
315
|
+
return {
|
|
316
|
+
ok: !error,
|
|
317
|
+
repoRoot,
|
|
318
|
+
steps,
|
|
319
|
+
before,
|
|
320
|
+
after,
|
|
321
|
+
changed: true,
|
|
322
|
+
checkpoint,
|
|
323
|
+
...(error ? { error } : {}),
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
type Recorder = (
|
|
328
|
+
label: string,
|
|
329
|
+
cmd: string,
|
|
330
|
+
args: readonly string[],
|
|
331
|
+
timeoutMs: number,
|
|
332
|
+
) => Promise<UpdateStep>;
|
|
253
333
|
|
|
334
|
+
function refusal(error: string): string {
|
|
335
|
+
return (
|
|
336
|
+
`the pre-update checkpoint failed (${error}). ` +
|
|
337
|
+
`Nothing was changed. Fix the backup problem, or run the update ` +
|
|
338
|
+
`with "force" to go on without a checkpoint.`
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Reinstall, run setup, and prove the new tree imports. Returns the
|
|
344
|
+
* failure reason, or null when the tree is ready to restart into.
|
|
345
|
+
*/
|
|
346
|
+
async function installAndVerify(
|
|
347
|
+
record: Recorder,
|
|
348
|
+
opts: UpdateOptions,
|
|
349
|
+
before: string,
|
|
350
|
+
after: string,
|
|
351
|
+
): Promise<string | null> {
|
|
254
352
|
const install = await record(
|
|
255
353
|
"npm install",
|
|
256
354
|
"npm",
|
|
257
355
|
["install"],
|
|
258
356
|
INSTALL_TIMEOUT_MS,
|
|
259
357
|
);
|
|
260
|
-
if (!install.ok) {
|
|
261
|
-
return {
|
|
262
|
-
ok: false,
|
|
263
|
-
repoRoot,
|
|
264
|
-
steps,
|
|
265
|
-
before,
|
|
266
|
-
after,
|
|
267
|
-
changed,
|
|
268
|
-
error: `npm install failed: ${install.output}`,
|
|
269
|
-
};
|
|
270
|
-
}
|
|
358
|
+
if (!install.ok) return `npm install failed: ${install.output}`;
|
|
271
359
|
|
|
272
360
|
for (const cmd of opts.setup ?? []) {
|
|
273
361
|
const trimmed = cmd.trim();
|
|
@@ -279,15 +367,7 @@ export async function runSelfUpdate(
|
|
|
279
367
|
SETUP_TIMEOUT_MS,
|
|
280
368
|
);
|
|
281
369
|
if (!setup.ok) {
|
|
282
|
-
return {
|
|
283
|
-
ok: false,
|
|
284
|
-
repoRoot,
|
|
285
|
-
steps,
|
|
286
|
-
before,
|
|
287
|
-
after,
|
|
288
|
-
changed,
|
|
289
|
-
error: `setup command failed (${trimmed}): ${setup.output}`,
|
|
290
|
-
};
|
|
370
|
+
return `setup command failed (${trimmed}): ${setup.output}`;
|
|
291
371
|
}
|
|
292
372
|
}
|
|
293
373
|
|
|
@@ -299,18 +379,35 @@ export async function runSelfUpdate(
|
|
|
299
379
|
VERIFY_TIMEOUT_MS,
|
|
300
380
|
);
|
|
301
381
|
if (!verify.ok || !verify.output.includes(BOOT_SMOKE_OK)) {
|
|
302
|
-
return
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
382
|
+
return (
|
|
383
|
+
`the updated tree does not import — not restarting into it. ` +
|
|
384
|
+
`Still running ${before}; the checkout is at ${after}.`
|
|
385
|
+
);
|
|
386
|
+
}
|
|
387
|
+
return null;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** One line for the step log and the chat reply. */
|
|
391
|
+
export function describeCheckpoint(checkpoint: UpdateCheckpoint): string {
|
|
392
|
+
switch (checkpoint.status) {
|
|
393
|
+
case "taken":
|
|
394
|
+
return `checkpoint ${checkpoint.id} taken`;
|
|
395
|
+
case "disabled":
|
|
396
|
+
return "no checkpoint (backup.checkpointBeforeUpdate is off)";
|
|
397
|
+
case "failed":
|
|
398
|
+
return `checkpoint failed: ${checkpoint.error}`;
|
|
313
399
|
}
|
|
400
|
+
}
|
|
314
401
|
|
|
315
|
-
|
|
402
|
+
/**
|
|
403
|
+
* Whether the arguments to `/update` ask to go on without a checkpoint.
|
|
404
|
+
* `force` and `--force` both work, so the chat command and a CLI habit
|
|
405
|
+
* read the same.
|
|
406
|
+
*/
|
|
407
|
+
export function wantsForce(args: string | undefined | null): boolean {
|
|
408
|
+
return (args ?? "")
|
|
409
|
+
.trim()
|
|
410
|
+
.toLowerCase()
|
|
411
|
+
.split(/\s+/)
|
|
412
|
+
.some((token) => token === "force" || token === "--force");
|
|
316
413
|
}
|