@hivemagnus/magnus 3.7.0 → 4.1.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/README.md CHANGED
@@ -70,8 +70,13 @@ Slow or one-way migrations need `--yes`. An upgrade that is interrupted is recor
70
70
  ```bash
71
71
  magnus rollback [--restore-db] [--force] # back to the previous version
72
72
  magnus restore <dump> # stop, restore into a clean schema, start again
73
+ magnus backups [prune] [--dry-run] # list dumps; delete those the retention does not keep
73
74
  ```
74
75
 
76
+ Dumps in `backups/` are pruned after every successful upgrade: the newest `keepBackups` (5) and any
77
+ younger than `keepBackupDays` (7) stay, as do the newest good dump and the one a rollback would
78
+ restore.
79
+
75
80
  `magnus-server upgrade` hands the same command to the project it was installed into.
76
81
 
77
82
  ## `magnus adopt`
@@ -0,0 +1,15 @@
1
+ import type { Io } from './io.js';
2
+ export interface BackupsOptions {
3
+ dir: string;
4
+ /** Delete the dumps the retention does not keep (otherwise only list them). */
5
+ prune: boolean;
6
+ /** With `prune`: say what would go, delete nothing. */
7
+ dryRun: boolean;
8
+ /** Override magnus-project.json `keepBackups` for this run. */
9
+ keep?: number;
10
+ /** Override magnus-project.json `keepBackupDays` for this run. */
11
+ keepDays?: number;
12
+ json: boolean;
13
+ breakLock?: boolean;
14
+ }
15
+ export declare function backups(io: Io, options: BackupsOptions): Promise<number>;
@@ -0,0 +1,62 @@
1
+ /** `magnus backups [prune] [--dry-run]`: list the dumps in backups/ and prune them by the project's retention. */
2
+ import { planBackupPrune, pruneBackups, rollbackDumps } from './database.js';
3
+ import { acquireLock, Project } from './project.js';
4
+ import { requirePrivileges, UpgradeError } from './upgrade.js';
5
+ function size(bytes) {
6
+ if (bytes >= 1024 ** 3)
7
+ return `${(bytes / 1024 ** 3).toFixed(1)} GiB`;
8
+ if (bytes >= 1024 ** 2)
9
+ return `${(bytes / 1024 ** 2).toFixed(1)} MiB`;
10
+ return `${Math.ceil(bytes / 1024)} KiB`;
11
+ }
12
+ export async function backups(io, options) {
13
+ const project = Project.load(options.dir);
14
+ const retention = { keep: options.keep ?? project.keepBackups(), keepDays: options.keepDays ?? project.keepBackupDays() };
15
+ if (!Number.isInteger(retention.keep) || retention.keep < 1)
16
+ throw new UpgradeError('--keep must be a whole number of at least 1');
17
+ if (!Number.isFinite(retention.keepDays) || retention.keepDays < 0)
18
+ throw new UpgradeError('--keep-days must be a number of days, 0 or more');
19
+ const dir = project.path('backups');
20
+ const deleting = options.prune && !options.dryRun;
21
+ if (deleting)
22
+ requirePrivileges(io, project);
23
+ // Deleting takes the upgrade lock so a prune never races an upgrade's own dump; listing does not.
24
+ const release = deleting ? acquireLock(project.path('run', 'upgrade.lock'), { breakLock: options.breakLock, command: 'magnus backups prune' }) : null;
25
+ try {
26
+ const now = io.now().getTime();
27
+ const protect = rollbackDumps(project);
28
+ const plan = planBackupPrune(dir, retention, protect, now);
29
+ const removed = deleting ? pruneBackups(dir, retention, protect, { now }) : plan.remove.map((dump) => dump.file);
30
+ const freed = plan.remove.reduce((sum, dump) => sum + dump.bytes, 0);
31
+ if (options.json) {
32
+ io.log(JSON.stringify({
33
+ dir, retention, dryRun: !deleting,
34
+ keep: plan.keep.map(({ file, at, bytes, label, good, reasons }) => ({ file, createdAt: new Date(at).toISOString(), bytes, label, good, reasons })),
35
+ remove: plan.remove.map(({ file, at, bytes, label, good }) => ({ file, createdAt: new Date(at).toISOString(), bytes, label, good })),
36
+ ...(deleting ? { removed } : {}),
37
+ }, null, 2));
38
+ return 0;
39
+ }
40
+ if (plan.keep.length + plan.remove.length === 0) {
41
+ io.log(`No dumps in ${dir}.`);
42
+ return 0;
43
+ }
44
+ io.log(`Dumps in ${dir} (keep the newest ${retention.keep}${retention.keepDays > 0 ? ` and any younger than ${retention.keepDays} day(s)` : ''}):`);
45
+ const rows = [...plan.keep.map((dump) => ({ ...dump, mark: `keep (${dump.reasons.join(', ')})` })),
46
+ ...plan.remove.map((dump) => ({ ...dump, mark: deleting ? 'removed' : options.prune ? 'would remove' : 'prunable' }))]
47
+ .sort((a, b) => b.at - a.at);
48
+ for (const row of rows) {
49
+ io.log(` ${new Date(row.at).toISOString()} ${size(row.bytes).padStart(9)} ${row.good ? '' : '[unverified] '}${row.label ?? row.file} ${row.mark}`);
50
+ }
51
+ if (!plan.remove.length)
52
+ io.log('Nothing to prune.');
53
+ else if (deleting)
54
+ io.log(`Removed ${removed.length} dump(s), ${size(freed)}.`);
55
+ else
56
+ io.log(`${plan.remove.length} dump(s), ${size(freed)}, ${options.prune ? 'would be removed (dry run; nothing deleted)' : 'can go'}: \`magnus backups prune --dir ${project.dir}\`${options.prune ? '' : ' (add --dry-run to check first)'}.`);
57
+ return 0;
58
+ }
59
+ finally {
60
+ release?.();
61
+ }
62
+ }
@@ -11,13 +11,45 @@ export declare function restoreCommandFor(project: Project, file: string): strin
11
11
  export declare const SERVER_RESTORE_SINCE = "1.1.3";
12
12
  /** Bytes the database occupies (an upper bound for its dump), or null when it cannot be asked. */
13
13
  export declare function databaseBytes(io: Io, project: Project): Promise<number | null>;
14
+ /** How many dumps backups/ keeps, and for how long. */
15
+ export interface BackupRetention {
16
+ /** Newest dumps always kept (magnus-project.json `keepBackups`, default 5). Below 1, nothing is pruned. */
17
+ keep: number;
18
+ /** Dumps younger than this many days are always kept (`keepBackupDays`, default 7; 0 turns the age rule off). */
19
+ keepDays: number;
20
+ }
21
+ export interface DumpInfo {
22
+ file: string;
23
+ /** When it was taken: the metadata's createdAt, else the file's mtime (ms). */
24
+ at: number;
25
+ bytes: number;
26
+ label: string | null;
27
+ /** Non-empty, with metadata, and not marked unverified: a dump a restore can use. */
28
+ good: boolean;
29
+ }
30
+ export interface BackupPrunePlan {
31
+ keep: Array<DumpInfo & {
32
+ reasons: string[];
33
+ }>;
34
+ remove: DumpInfo[];
35
+ }
36
+ /** Every dump in `dir`, newest first. */
37
+ export declare function listDumps(dir: string): DumpInfo[];
14
38
  /**
15
- * Keep the newest `keep` dumps in backups/ and any file in `protect` (the dump
16
- * the current upgrade's rollback restores); older ones go. Upgrade labels are
17
- * unique per step (`pre-upgrade-A-to-B`), so a per-label exemption would keep
18
- * every dump forever.
39
+ * Which dumps a prune keeps and which it deletes. A dump is kept when it is one of the newest
40
+ * `keep`, younger than `keepDays`, named in `protect` (what a rollback would restore), or the
41
+ * newest good dump (so a run of failed or partial dumps can never push out the last usable one).
42
+ * Everything else goes. Upgrade labels are unique per step (`pre-upgrade-A-to-B`), so a per-label
43
+ * exemption would keep every dump forever.
19
44
  */
20
- export declare function pruneBackups(dir: string, keep: number, protect?: readonly string[]): string[];
45
+ export declare function planBackupPrune(dir: string, retention: BackupRetention, protect?: readonly string[], now?: number): BackupPrunePlan;
46
+ /** Apply {@link planBackupPrune}; with `dryRun` nothing is deleted. Returns the files (to be) removed. */
47
+ export declare function pruneBackups(dir: string, retention: BackupRetention, protect?: readonly string[], options?: {
48
+ dryRun?: boolean;
49
+ now?: number;
50
+ }): string[];
51
+ /** Dumps a rollback of this project could still restore: the interrupted upgrade's and the last upgrade's. */
52
+ export declare function rollbackDumps(project: Project): string[];
21
53
  /**
22
54
  * Dump before migrating. Compose databases are dumped with the container's own
23
55
  * pg_dump (always the server's version); external ones through the target
package/dist/database.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /** Pre-migration dumps and restores for both database kinds a project can use. */
2
2
  import { closeSync, chmodSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
- import { dirname, join } from 'node:path';
3
+ import { basename, dirname, join } from 'node:path';
4
4
  import { compareVersions, restoreAsideSchema, restoreFinishSql, restoreRevertSql, restoreSwapSql } from '@hivemagnus/magnus-contracts';
5
5
  import { readEnvFile } from './env-file.js';
6
6
  import { mustRun } from './io.js';
@@ -43,33 +43,79 @@ export async function databaseBytes(io, project) {
43
43
  const bytes = Number(result?.stdout.trim());
44
44
  return Number.isFinite(bytes) && bytes > 0 ? bytes : null;
45
45
  }
46
- /**
47
- * Keep the newest `keep` dumps in backups/ and any file in `protect` (the dump
48
- * the current upgrade's rollback restores); older ones go. Upgrade labels are
49
- * unique per step (`pre-upgrade-A-to-B`), so a per-label exemption would keep
50
- * every dump forever.
51
- */
52
- export function pruneBackups(dir, keep, protect = []) {
53
- if (!existsSync(dir) || keep < 1)
46
+ function dumpMetadata(file) {
47
+ try {
48
+ const meta = JSON.parse(readFileSync(`${file}.json`, 'utf8'));
49
+ return meta && typeof meta === 'object' ? meta : null;
50
+ }
51
+ catch {
52
+ return null; // no metadata
53
+ }
54
+ }
55
+ /** Every dump in `dir`, newest first. */
56
+ export function listDumps(dir) {
57
+ if (!existsSync(dir))
54
58
  return [];
55
- const dumps = readdirSync(dir).filter((name) => name.endsWith('.dump')).map((name) => {
59
+ return readdirSync(dir).filter((name) => name.endsWith('.dump')).map((name) => {
56
60
  const file = join(dir, name);
57
- let meta = {};
58
- try {
59
- meta = JSON.parse(readFileSync(`${file}.json`, 'utf8'));
60
- }
61
- catch { /* no metadata */ }
62
- return { file, at: Date.parse(meta.createdAt ?? '') || statSync(file).mtimeMs };
63
- }).sort((a, b) => b.at - a.at);
64
- const removed = [];
61
+ const meta = dumpMetadata(file);
62
+ const stat = statSync(file);
63
+ const created = Date.parse(meta?.createdAt ?? '');
64
+ return {
65
+ file, at: Number.isFinite(created) ? created : stat.mtimeMs, bytes: stat.size, label: meta?.label ?? null,
66
+ good: stat.size > 0 && meta !== null && Number.isFinite(created) && meta.verified !== false,
67
+ };
68
+ }).sort((a, b) => b.at - a.at || b.file.localeCompare(a.file));
69
+ }
70
+ /**
71
+ * Which dumps a prune keeps and which it deletes. A dump is kept when it is one of the newest
72
+ * `keep`, younger than `keepDays`, named in `protect` (what a rollback would restore), or the
73
+ * newest good dump (so a run of failed or partial dumps can never push out the last usable one).
74
+ * Everything else goes. Upgrade labels are unique per step (`pre-upgrade-A-to-B`), so a per-label
75
+ * exemption would keep every dump forever.
76
+ */
77
+ export function planBackupPrune(dir, retention, protect = [], now = Date.now()) {
78
+ const dumps = listDumps(dir);
79
+ if (!Number.isInteger(retention.keep) || retention.keep < 1)
80
+ return { keep: dumps.map((dump) => ({ ...dump, reasons: ['pruning off'] })), remove: [] };
81
+ const newestGood = dumps.find((dump) => dump.good)?.file;
82
+ // Every dump lives in `dir`, so compare names: a project reached through a symlink records other paths.
83
+ const protectedNames = new Set(protect.map((file) => basename(file)));
84
+ const maxAgeMs = Math.max(0, retention.keepDays) * 86_400_000;
85
+ const plan = { keep: [], remove: [] };
65
86
  dumps.forEach((dump, index) => {
66
- if (index < keep || protect.includes(dump.file))
67
- return;
68
- rmSync(dump.file, { force: true });
69
- rmSync(`${dump.file}.json`, { force: true });
70
- removed.push(dump.file);
87
+ const reasons = [];
88
+ if (index < retention.keep)
89
+ reasons.push(`newest ${retention.keep}`);
90
+ if (maxAgeMs > 0 && now - dump.at < maxAgeMs)
91
+ reasons.push(`younger than ${retention.keepDays}d`);
92
+ if (protectedNames.has(basename(dump.file)))
93
+ reasons.push('rollback dump');
94
+ if (dump.file === newestGood)
95
+ reasons.push('newest good dump');
96
+ if (reasons.length)
97
+ plan.keep.push({ ...dump, reasons });
98
+ else
99
+ plan.remove.push(dump);
71
100
  });
72
- return removed;
101
+ return plan;
102
+ }
103
+ /** Apply {@link planBackupPrune}; with `dryRun` nothing is deleted. Returns the files (to be) removed. */
104
+ export function pruneBackups(dir, retention, protect = [], options = {}) {
105
+ const { remove } = planBackupPrune(dir, retention, protect, options.now);
106
+ if (!options.dryRun) {
107
+ for (const dump of remove) {
108
+ rmSync(dump.file, { force: true });
109
+ rmSync(`${dump.file}.json`, { force: true });
110
+ }
111
+ }
112
+ return remove.map((dump) => dump.file);
113
+ }
114
+ /** Dumps a rollback of this project could still restore: the interrupted upgrade's and the last upgrade's. */
115
+ export function rollbackDumps(project) {
116
+ const files = [project.state.inProgress?.backup,
117
+ project.state.history.findLast((entry) => entry.action === 'upgrade' && entry.result === 'ok' && entry.backup)?.backup];
118
+ return files.filter((file) => Boolean(file));
73
119
  }
74
120
  /**
75
121
  * Dump before migrating. Compose databases are dumped with the container's own
@@ -80,7 +126,9 @@ export function pruneBackups(dir, keep, protect = []) {
80
126
  export async function backupDatabase(io, project, version, label) {
81
127
  const db = project.state.database;
82
128
  if (db.kind === 'external') {
83
- const { stdout } = await serverCli(io, project, version, ['backup', '--label', label], { capture: true });
129
+ // The server must not prune here: it cannot know which dump this project's rollback needs.
130
+ // magnus prunes with that protection once the upgrade succeeded (and `magnus backups prune`).
131
+ const { stdout } = await serverCli(io, project, version, ['backup', '--label', label], { capture: true, env: { MAGNUS_BACKUP_PRUNE: 'false' } });
84
132
  const result = JSON.parse(stdout.trim().split('\n').pop() ?? '{}');
85
133
  if (!result.file)
86
134
  throw new Error('magnus-server backup did not report a dump file');
@@ -118,7 +166,7 @@ export async function backupDatabase(io, project, version, label) {
118
166
  }
119
167
  const restoreCommand = restoreCommandFor(project, file);
120
168
  writeFileSync(`${file}.json`, `${JSON.stringify({ createdAt: io.now().toISOString(), label, restoreCommand }, null, 2)}\n`, { mode: 0o600 });
121
- pruneBackups(dir, project.keepBackups(), [file]);
169
+ pruneBackups(dir, project.backupRetention(), [file, ...rollbackDumps(project)], { now: io.now().getTime() });
122
170
  return { file, restoreCommand };
123
171
  }
124
172
  /** Newest installed version whose server CLI can restore (1.1.3+). */
package/dist/init.d.ts CHANGED
@@ -26,4 +26,12 @@ export interface InitOptions {
26
26
  healthTimeoutMs: number;
27
27
  }
28
28
  export declare function defaultProjectDir(io: Io, system: boolean): string;
29
+ /**
30
+ * Hashes MAGNUS_INIT_PASSWORD with the argon2 installed with the release: the first of the
31
+ * directories in argv that resolves it. Shrinkwrapped releases (3.2.0 on) nest argon2 under the
32
+ * console and server packages, so a bare `import 'argon2'` from the version root does not find it.
33
+ */
34
+ export declare const HASH_PASSWORD_SCRIPT = "import { createRequire } from 'node:module';\nimport { pathToFileURL } from 'node:url';\nlet path;\nfor (const root of process.argv.slice(1)) { try { path = createRequire(root + '/').resolve('argon2'); break; } catch {} }\nif (!path) { console.error('argon2 is not installed with this release (looked in ' + process.argv.slice(1).join(', ') + ')'); process.exit(1); }\nconst mod = await import(pathToFileURL(path).href);\nconst argon2 = mod.default ?? mod;\nconsole.log(await argon2.hash(process.env.MAGNUS_INIT_PASSWORD, { type: argon2.argon2id }));";
35
+ /** Where argon2 can be: the console's own copy (it verifies the hash), the server's, then the version root. */
36
+ export declare function argon2Roots(versionDir: string): string[];
29
37
  export declare function init(io: Io, options: InitOptions): Promise<number>;
package/dist/init.js CHANGED
@@ -31,10 +31,26 @@ async function selfSignedCertificate(io, dir, host) {
31
31
  });
32
32
  return { cert, key };
33
33
  }
34
+ /**
35
+ * Hashes MAGNUS_INIT_PASSWORD with the argon2 installed with the release: the first of the
36
+ * directories in argv that resolves it. Shrinkwrapped releases (3.2.0 on) nest argon2 under the
37
+ * console and server packages, so a bare `import 'argon2'` from the version root does not find it.
38
+ */
39
+ export const HASH_PASSWORD_SCRIPT = `import { createRequire } from 'node:module';
40
+ import { pathToFileURL } from 'node:url';
41
+ let path;
42
+ for (const root of process.argv.slice(1)) { try { path = createRequire(root + '/').resolve('argon2'); break; } catch {} }
43
+ if (!path) { console.error('argon2 is not installed with this release (looked in ' + process.argv.slice(1).join(', ') + ')'); process.exit(1); }
44
+ const mod = await import(pathToFileURL(path).href);
45
+ const argon2 = mod.default ?? mod;
46
+ console.log(await argon2.hash(process.env.MAGNUS_INIT_PASSWORD, { type: argon2.argon2id }));`;
47
+ /** Where argon2 can be: the console's own copy (it verifies the hash), the server's, then the version root. */
48
+ export function argon2Roots(versionDir) {
49
+ return [join(versionDir, 'node_modules', '@hivemagnus', 'magnus-ui'), join(versionDir, 'node_modules', '@hivemagnus', 'magnus-server'), versionDir];
50
+ }
34
51
  async function hashPassword(io, project, version, password) {
35
- // argon2 comes with the server install; nothing extra is downloaded.
36
- const { stdout } = await mustRun(io, project.nodePath(), ['--input-type=module', '-e',
37
- "import argon2 from 'argon2'; console.log(await argon2.hash(process.env.MAGNUS_INIT_PASSWORD, { type: argon2.argon2id }))"], { cwd: project.versionDir(version), capture: true, env: { ...io.env, MAGNUS_INIT_PASSWORD: password } });
52
+ // argon2 comes with the release install; nothing extra is downloaded.
53
+ const { stdout } = await mustRun(io, project.nodePath(), ['--input-type=module', '-e', HASH_PASSWORD_SCRIPT, ...argon2Roots(project.versionDir(version))], { cwd: project.versionDir(version), capture: true, env: { ...io.env, MAGNUS_INIT_PASSWORD: password } });
38
54
  return stdout.trim();
39
55
  }
40
56
  async function startDeps(io, project) {
package/dist/install.js CHANGED
@@ -145,7 +145,7 @@ export function serverCli(io, project, version, args, options = {}) {
145
145
  cwd: project.dir,
146
146
  capture: options.capture,
147
147
  detached: options.detached,
148
- env: { ...io.env, MAGNUS_PROJECT_DIR: project.dir, MAGNUS_BACKUP_DIR: project.path('backups'), MAGNUS_BACKUP_KEEP: String(project.keepBackups()), ...options.env },
148
+ env: { ...io.env, MAGNUS_PROJECT_DIR: project.dir, MAGNUS_BACKUP_DIR: project.path('backups'), MAGNUS_BACKUP_KEEP: String(project.keepBackups()), MAGNUS_BACKUP_KEEP_DAYS: String(project.keepBackupDays()), ...options.env },
149
149
  });
150
150
  }
151
151
  /**
package/dist/main.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Io } from './io.js';
2
- export declare const USAGE = "Usage: magnus <command> [options]\n\nCommands:\n init Create a managed project, install the pinned release and start it\n upgrade Upgrade the project (same major version unless --allow-major)\n rollback Switch back to the version that served before the last upgrade\n restore Restore a database dump: stop the services, restore, start them again\n status Show installed and serving versions, history and available updates\n adopt Turn an existing npm install into a managed project\n version Print this tool's version\n\nCommon options:\n --dir DIR Project directory (default ~/.magnus, or /opt/magnus with --system)\n --registry URL npm registry (default MAGNUS_UPDATE_REGISTRY, then npm's configured registry)\n --source DIR Install from packed tarballs in DIR instead of the registry\n --health-timeout SEC How long to wait for the new version to become healthy (default 180)\n --yes Confirm slow or one-way migrations and restores without asking\n --break-lock Remove a lock left behind by a magnus command that no longer runs\n\ninit:\n --version X.Y.Z Release to install (default: newest of this major)\n --system System units (root) instead of user units; needs --service-user\n --service-user NAME Account the system services run as\n --supervisor KIND systemd (default) or none (you start the processes yourself)\n --database-url URL Existing PostgreSQL (with --redis-url); otherwise PostgreSQL and\n --redis-url URL Redis run on loopback through docker compose\n --postgres-port N Loopback port for the bundled PostgreSQL (default 5432)\n --redis-port N Loopback port for the bundled Redis (default 6379)\n --server-port N Server port (default 4000)\n --ui-port N Console port (default 3000)\n --public-host NAME Host name for URLs and the certificate (default: this host's name)\n --admin-user NAME Console administrator (default admin)\n --admin-password PW Console password (default: generated and printed once)\n --tls-cert FILE Certificate and key (default: a self-signed certificate)\n --tls-key FILE\n --no-ui Install only the server\n --no-start Install and configure, but do not start\n --no-auto-migrate Write MAGNUS_AUTO_MIGRATE=false (default true for init projects)\n\nupgrade:\n --to X.Y.Z Target release (default: newest of the current major)\n --dry-run Show what would happen and check prerequisites; change nothing\n --allow-major Permit crossing a major version\n --generate-secrets Generate values for new required secret settings\n --resume Finish an upgrade that was interrupted (see `magnus status`)\n --node PATH Node.js the services run and the upgrade uses (rewrites the units)\n --force After a failed upgrade, start the old version even over one-way migrations\n\nrollback:\n --restore-db Also restore the pre-upgrade database dump (data written since is lost)\n --force Start the previous version even over one-way migrations it does not know\n\nrestore FILE: A dump from backups/ (shown by upgrade, rollback and status)\n\nstatus:\n --json Machine-readable output\n --offline Skip the registry check\n\nadopt:\n --server-env-file F The env file your magnus-server runs with (required)\n --ui-env-file F The env file your magnus-ui runs with\n --version X.Y.Z Installed version (default: magnus-server --version)\n --install-units Install and enable the new units (otherwise only print the steps)\n";
2
+ export declare const USAGE = "Usage: magnus <command> [options]\n\nCommands:\n init Create a managed project, install the pinned release and start it\n upgrade Upgrade the project (same major version unless --allow-major)\n rollback Switch back to the version that served before the last upgrade\n restore Restore a database dump: stop the services, restore, start them again\n status Show installed and serving versions, history and available updates\n backups List the database dumps in backups/; `backups prune` deletes those the retention does not keep\n adopt Turn an existing npm install into a managed project\n version Print this tool's version\n\nCommon options:\n --dir DIR Project directory (default ~/.magnus, or /opt/magnus with --system)\n --registry URL npm registry (default MAGNUS_UPDATE_REGISTRY, then npm's configured registry)\n --source DIR Install from packed tarballs in DIR instead of the registry\n --health-timeout SEC How long to wait for the new version to become healthy (default 180)\n --yes Confirm slow or one-way migrations and restores without asking\n --break-lock Remove a lock left behind by a magnus command that no longer runs\n\ninit:\n --version X.Y.Z Release to install (default: newest of this major)\n --system System units (root) instead of user units; needs --service-user\n --service-user NAME Account the system services run as\n --supervisor KIND systemd (default) or none (you start the processes yourself)\n --database-url URL Existing PostgreSQL (with --redis-url); otherwise PostgreSQL and\n --redis-url URL Redis run on loopback through docker compose\n --postgres-port N Loopback port for the bundled PostgreSQL (default 5432)\n --redis-port N Loopback port for the bundled Redis (default 6379)\n --server-port N Server port (default 4000)\n --ui-port N Console port (default 3000)\n --public-host NAME Host name for URLs and the certificate (default: this host's name)\n --admin-user NAME Console administrator (default admin)\n --admin-password PW Console password (default: generated and printed once)\n --tls-cert FILE Certificate and key (default: a self-signed certificate)\n --tls-key FILE\n --no-ui Install only the server\n --no-start Install and configure, but do not start\n --no-auto-migrate Write MAGNUS_AUTO_MIGRATE=false (default true for init projects)\n\nupgrade:\n --to X.Y.Z Target release (default: newest of the current major)\n --dry-run Show what would happen and check prerequisites; change nothing\n --allow-major Permit crossing a major version\n --generate-secrets Generate values for new required secret settings\n --resume Finish an upgrade that was interrupted (see `magnus status`)\n --node PATH Node.js the services run and the upgrade uses (rewrites the units)\n --force After a failed upgrade, start the old version even over one-way migrations\n\nrollback:\n --restore-db Also restore the pre-upgrade database dump (data written since is lost)\n --force Start the previous version even over one-way migrations it does not know\n\nrestore FILE: A dump from backups/ (shown by upgrade, rollback and status)\n\nbackups [prune]:\n --dry-run prune: show what would be deleted; delete nothing\n --keep N Newest dumps to keep (default: magnus-project.json keepBackups, 5)\n --keep-days D Keep every dump younger than D days (default: keepBackupDays, 7; 0: off)\n --json Machine-readable output\n The newest good dump and the dump a rollback would restore are always kept.\n\nstatus:\n --json Machine-readable output\n --offline Skip the registry check\n\nadopt:\n --server-env-file F The env file your magnus-server runs with (required)\n --ui-env-file F The env file your magnus-ui runs with\n --version X.Y.Z Installed version (default: magnus-server --version)\n --install-units Install and enable the new units (otherwise only print the steps)\n";
3
3
  export declare class ArgsError extends Error {
4
4
  }
5
5
  interface Parsed {
package/dist/main.js CHANGED
@@ -6,9 +6,11 @@
6
6
  * magnus rollback [--restore-db] switch back to the previous version
7
7
  * magnus restore FILE restore a database dump (stops and restarts the services)
8
8
  * magnus status versions, health and available updates
9
+ * magnus backups [prune] [--dry-run] list database dumps; prune them by the retention
9
10
  * magnus adopt --server-env-file FILE take over an existing npm install
10
11
  */
11
12
  import { adopt } from './adopt.js';
13
+ import { backups } from './backups.js';
12
14
  import { init, defaultProjectDir } from './init.js';
13
15
  import { findProjectDir } from './project.js';
14
16
  import { ownPackage, resolveRegistry } from './release.js';
@@ -24,6 +26,7 @@ Commands:
24
26
  rollback Switch back to the version that served before the last upgrade
25
27
  restore Restore a database dump: stop the services, restore, start them again
26
28
  status Show installed and serving versions, history and available updates
29
+ backups List the database dumps in backups/; \`backups prune\` deletes those the retention does not keep
27
30
  adopt Turn an existing npm install into a managed project
28
31
  version Print this tool's version
29
32
 
@@ -70,6 +73,13 @@ rollback:
70
73
 
71
74
  restore FILE: A dump from backups/ (shown by upgrade, rollback and status)
72
75
 
76
+ backups [prune]:
77
+ --dry-run prune: show what would be deleted; delete nothing
78
+ --keep N Newest dumps to keep (default: magnus-project.json keepBackups, 5)
79
+ --keep-days D Keep every dump younger than D days (default: keepBackupDays, 7; 0: off)
80
+ --json Machine-readable output
81
+ The newest good dump and the dump a rollback would restore are always kept.
82
+
73
83
  status:
74
84
  --json Machine-readable output
75
85
  --offline Skip the registry check
@@ -84,10 +94,10 @@ export class ArgsError extends Error {
84
94
  }
85
95
  const VALUE_OPTIONS = new Set(['--dir', '--registry', '--source', '--health-timeout', '--version', '--service-user', '--supervisor',
86
96
  '--database-url', '--redis-url', '--postgres-port', '--redis-port', '--server-port', '--ui-port', '--public-host', '--admin-user',
87
- '--admin-password', '--tls-cert', '--tls-key', '--to', '--server-env-file', '--ui-env-file', '--node']);
97
+ '--admin-password', '--tls-cert', '--tls-key', '--to', '--server-env-file', '--ui-env-file', '--node', '--keep', '--keep-days']);
88
98
  const FLAG_OPTIONS = new Set(['--yes', '--system', '--no-ui', '--no-start', '--no-auto-migrate', '--dry-run', '--allow-major',
89
99
  '--generate-secrets', '--resume', '--restore-db', '--json', '--offline', '--install-units', '--force', '--break-lock', '--help', '-h']);
90
- const COMMANDS = new Set(['init', 'upgrade', 'rollback', 'restore', 'status', 'adopt', 'version', 'help']);
100
+ const COMMANDS = new Set(['init', 'upgrade', 'rollback', 'restore', 'status', 'adopt', 'backups', 'version', 'help']);
91
101
  export function parseArgs(argv) {
92
102
  const values = new Map();
93
103
  const flags = new Set();
@@ -118,6 +128,9 @@ export function parseArgs(argv) {
118
128
  else if (command === 'restore' && args.length === 0) {
119
129
  args.push(name);
120
130
  }
131
+ else if (command === 'backups' && args.length === 0 && name === 'prune') {
132
+ args.push(name);
133
+ }
121
134
  else {
122
135
  throw new ArgsError(`unexpected argument ${name}`);
123
136
  }
@@ -188,6 +201,24 @@ export async function run(io, argv) {
188
201
  throw new ArgsError('restore needs the dump file: magnus restore <file>');
189
202
  return restore(io, { dir: projectDir(io, values, false), file, yes, healthTimeoutMs, breakLock });
190
203
  }
204
+ case 'backups': {
205
+ const count = (name) => {
206
+ const raw = values.get(name);
207
+ if (raw === undefined)
208
+ return undefined;
209
+ const value = Number(raw);
210
+ if (!Number.isFinite(value) || value < 0 || (name === '--keep' && (!Number.isInteger(value) || value < 1))) {
211
+ throw new ArgsError(name === '--keep' ? '--keep must be a whole number of at least 1' : '--keep-days must be a number of days, 0 or more');
212
+ }
213
+ return value;
214
+ };
215
+ const keep = count('--keep');
216
+ const keepDays = count('--keep-days');
217
+ return backups(io, {
218
+ dir: projectDir(io, values, false), prune: args[0] === 'prune', dryRun: flags.has('--dry-run'), json: flags.has('--json'), breakLock,
219
+ ...(keep !== undefined ? { keep } : {}), ...(keepDays !== undefined ? { keepDays } : {}),
220
+ });
221
+ }
191
222
  case 'status':
192
223
  return status(io, { dir: projectDir(io, values, false), json: flags.has('--json'), offline: flags.has('--offline'), registry });
193
224
  case 'adopt': {
package/dist/project.d.ts CHANGED
@@ -54,6 +54,8 @@ export interface ProjectState {
54
54
  keepVersions: number;
55
55
  /** Dumps kept in backups/ (default 5), plus the dump the current upgrade's rollback restores. */
56
56
  keepBackups?: number;
57
+ /** Dumps younger than this many days are never pruned (default 7; 0: only `keepBackups` counts). */
58
+ keepBackupDays?: number;
57
59
  /** Node.js the units run (and the upgrade uses for npm and the server CLI); default: the units' ExecStart. */
58
60
  nodePath?: string;
59
61
  /** docker compose project of the bundled PostgreSQL and Redis (projects before 1.1.3: magnus-deps). */
@@ -62,6 +64,7 @@ export interface ProjectState {
62
64
  history: HistoryEntry[];
63
65
  }
64
66
  export declare const DEFAULT_KEEP_BACKUPS = 5;
67
+ export declare const DEFAULT_KEEP_BACKUP_DAYS = 7;
65
68
  export declare class Project {
66
69
  readonly dir: string;
67
70
  state: ProjectState;
@@ -74,6 +77,11 @@ export declare class Project {
74
77
  nodePath(): string;
75
78
  composeProject(): string;
76
79
  keepBackups(): number;
80
+ keepBackupDays(): number;
81
+ backupRetention(): {
82
+ keep: number;
83
+ keepDays: number;
84
+ };
77
85
  path(...segments: string[]): string;
78
86
  envFile(component: Component): string;
79
87
  versionDir(version: string): string;
package/dist/project.js CHANGED
@@ -16,6 +16,7 @@ import { chownSync, closeSync, copyFileSync, existsSync, fsyncSync, linkSync, mk
16
16
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
17
17
  export const PROJECT_FILE = 'magnus-project.json';
18
18
  export const DEFAULT_KEEP_BACKUPS = 5;
19
+ export const DEFAULT_KEEP_BACKUP_DAYS = 7;
19
20
  export class Project {
20
21
  dir;
21
22
  state;
@@ -70,6 +71,13 @@ export class Project {
70
71
  keepBackups() {
71
72
  return this.state.keepBackups ?? DEFAULT_KEEP_BACKUPS;
72
73
  }
74
+ keepBackupDays() {
75
+ const days = this.state.keepBackupDays;
76
+ return typeof days === 'number' && Number.isFinite(days) && days >= 0 ? days : DEFAULT_KEEP_BACKUP_DAYS;
77
+ }
78
+ backupRetention() {
79
+ return { keep: this.keepBackups(), keepDays: this.keepBackupDays() };
80
+ }
73
81
  path(...segments) {
74
82
  return join(this.dir, ...segments);
75
83
  }
@@ -38,8 +38,13 @@ export declare const START_LIMIT: string[];
38
38
  export declare function unitPathProblem(what: string, path: string): string | null;
39
39
  export declare function serverUnit(options: ServiceUnitOptions): string;
40
40
  /**
41
- * Bring a unit generated by an older engine up to date without touching
42
- * anything else in it: the start limit, and the Node.js binary in ExecStart.
41
+ * The console exits 0 on SIGTERM; consoles before 4.0.1 exited 143 (128 + SIGTERM), which
42
+ * systemd reads as a failed stop. Kept in the console unit for those.
43
+ */
44
+ export declare const UI_SUCCESS_EXIT = "SuccessExitStatus=143";
45
+ /**
46
+ * Bring a unit generated by an older engine up to date without touching anything else in it: the
47
+ * start limit, the console's stop exit status, and the Node.js binary in ExecStart.
43
48
  */
44
49
  export declare function refreshUnit(content: string, nodePath?: string): string;
45
50
  /** docker compose project name for a new project's PostgreSQL and Redis. */
package/dist/templates.js CHANGED
@@ -92,8 +92,13 @@ export function serverUnit(options) {
92
92
  ].join('\n');
93
93
  }
94
94
  /**
95
- * Bring a unit generated by an older engine up to date without touching
96
- * anything else in it: the start limit, and the Node.js binary in ExecStart.
95
+ * The console exits 0 on SIGTERM; consoles before 4.0.1 exited 143 (128 + SIGTERM), which
96
+ * systemd reads as a failed stop. Kept in the console unit for those.
97
+ */
98
+ export const UI_SUCCESS_EXIT = 'SuccessExitStatus=143';
99
+ /**
100
+ * Bring a unit generated by an older engine up to date without touching anything else in it: the
101
+ * start limit, the console's stop exit status, and the Node.js binary in ExecStart.
97
102
  */
98
103
  export function refreshUnit(content, nodePath) {
99
104
  let lines = content.split('\n');
@@ -102,6 +107,9 @@ export function refreshUnit(content, nodePath) {
102
107
  const end = lines.findIndex((line, index) => index > unitAt && (line.startsWith('[') || line === ''));
103
108
  lines.splice(end < 0 ? lines.length : end, 0, ...START_LIMIT);
104
109
  }
110
+ const execAt = lines.findIndex((line) => line.startsWith('ExecStart=') && /\/magnus-ui(\.mjs)?\s/.test(line));
111
+ if (execAt >= 0 && !lines.some((line) => line.startsWith('SuccessExitStatus=')))
112
+ lines.splice(execAt + 1, 0, UI_SUCCESS_EXIT);
105
113
  if (nodePath)
106
114
  lines = lines.map((line) => (line.startsWith('ExecStart=') ? line.replace(/^ExecStart=\S+/, `ExecStart=${nodePath}`) : line));
107
115
  return lines.join('\n');
@@ -130,6 +138,7 @@ export function uiUnit(options) {
130
138
  ...(options.serviceUser ? [`User=${options.serviceUser}`] : []),
131
139
  `WorkingDirectory=${dataDir}`,
132
140
  `ExecStart=${options.nodePath} ${project.bin('current', 'magnus-ui')} start --env-file ${project.envFile('ui')} --data-dir ${dataDir}`,
141
+ UI_SUCCESS_EXIT,
133
142
  ...hardening(options, [dataDir, project.path('run')]),
134
143
  ].join('\n');
135
144
  }
package/dist/upgrade.js CHANGED
@@ -13,7 +13,7 @@
13
13
  import { spawn } from 'node:child_process';
14
14
  import { existsSync, statSync } from 'node:fs';
15
15
  import { checkUpgradeAllowed, compareVersions, satisfiesRange, summarizeUpgradePath, } from '@hivemagnus/magnus-contracts';
16
- import { backupDatabase, databaseBytes, pruneBackups, restoreCommandFor } from './database.js';
16
+ import { backupDatabase, databaseBytes, pruneBackups, restoreCommandFor, rollbackDumps } from './database.js';
17
17
  import { appendMissing, generateSecret, readEnvFile } from './env-file.js';
18
18
  import { waitForHealthy } from './health.js';
19
19
  import { installVersion, isInstalled, migrationReport, nodeVersionOf, npmFor, publishPins, pruneVersions, removeStaleStaging, serverCli, smokeTest, } from './install.js';
@@ -471,7 +471,7 @@ export async function applyInstalled(io, project, current, target, options, prio
471
471
  return await revert(io, project, { current, target, backup, oneWay, reason: health.detail, options, trap, entry, finish });
472
472
  publishPins(project, target);
473
473
  const pruned = pruneVersions(project, project.state.keepVersions, compareVersions);
474
- const dumps = pruneBackups(project.path('backups'), project.keepBackups(), backup ? [backup.file] : []);
474
+ const dumps = pruneBackups(project.path('backups'), project.backupRetention(), [...(backup ? [backup.file] : []), ...rollbackDumps(project)], { now: io.now().getTime() });
475
475
  finish(entry('ok'));
476
476
  io.log(`Upgraded to ${target}: ${health.detail}.${pruned.length ? ` Removed old versions ${pruned.join(', ')}.` : ''}${dumps.length ? ` Removed ${dumps.length} old dump(s).` : ''}`);
477
477
  io.log('Agents keep running their version until you upgrade them: `magnus-server agents upgrade` or the "Upgrade agents" button on the Nodes page.');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hivemagnus/magnus",
3
- "version": "3.7.0",
3
+ "version": "4.1.0",
4
4
  "description": "Install, upgrade and roll back a Magnus server and console with one command: `npx @hivemagnus/magnus init`, then `magnus upgrade`. Pins exact, tested component versions, backs up PostgreSQL before every migration and reverts automatically when the new version fails its health check.",
5
5
  "keywords": [
6
6
  "magnus",
@@ -47,7 +47,7 @@
47
47
  "clean": "node -e \"const fs=require('node:fs');fs.rmSync('dist',{recursive:true,force:true});fs.rmSync('tsconfig.tsbuildinfo',{force:true})\""
48
48
  },
49
49
  "dependencies": {
50
- "@hivemagnus/magnus-contracts": "3.7.0"
50
+ "@hivemagnus/magnus-contracts": "4.1.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/node": "^24.19.2",
@@ -56,18 +56,18 @@
56
56
  },
57
57
  "magnusRelease": {
58
58
  "schema": 1,
59
- "version": "3.7.0",
59
+ "version": "4.1.0",
60
60
  "engines": {
61
61
  "node": "^24.22.3 || ^26.13.1"
62
62
  },
63
63
  "components": {
64
- "@hivemagnus/magnus-server": "3.7.0",
65
- "@hivemagnus/magnus-ui": "3.7.0",
66
- "@hivemagnus/magnus-contracts": "3.7.0",
67
- "@hivemagnus/magnus-agent": "3.7.0"
64
+ "@hivemagnus/magnus-server": "4.1.0",
65
+ "@hivemagnus/magnus-ui": "4.1.0",
66
+ "@hivemagnus/magnus-contracts": "4.1.0",
67
+ "@hivemagnus/magnus-agent": "4.1.0"
68
68
  },
69
69
  "breaking": false,
70
- "minUpgradeFrom": "2.10.2",
70
+ "minUpgradeFrom": "4.0.0",
71
71
  "engineProtocol": 2,
72
72
  "newRequiredEnv": [],
73
73
  "newOptionalEnv": [],
@@ -77,8 +77,8 @@
77
77
  "selfUpgradeProtocol": 1,
78
78
  "minLauncher": 1
79
79
  },
80
- "summary": "The bridge to Magnus 4. The standalone console re-encrypts control-node credentials left under the legacy JWT_SECRET-derived key at start, magnus-ui credentials --reencrypt does it on demand, and magnus-ui credentials --check passes only when every stored credential decrypts under CONTROL_NODE_CREDENTIAL_KEY: run it with the console stopped, as the console account, against the real state file, and make it pass before 4.0.0, which refuses to start while legacy values remain. A supervised agent refuses commands outside the completion registry before starting a unit, and an ADMIN can settle an unknown non-Ardent command. The embedded Hermes dashboard and router admin UI run sandboxed; reconnect open Hermes frames after the upgrade. Upgrade the node agents first. Ardent stays 3.6.0. No migration, no new setting.",
81
- "notesUrl": "https://github.com/ChefTaco/magnus/releases/tag/v3.7.0",
80
+ "summary": "New Agent can enable the reviewed Lucent 0.1.0 extension. Managed nodes install Ardent 3.7.0 with the verified extension archive and retain other reviewed packages. Existing agents keep their configured plugins.",
81
+ "notesUrl": "https://github.com/ChefTaco/magnus/releases/tag/v4.1.0",
82
82
  "allowScripts": {
83
83
  "@prisma/engines": true,
84
84
  "argon2": true,