omp-config-crypt 0.5.6 → 0.6.1

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/bin/omp-sync.js CHANGED
@@ -25,6 +25,10 @@ import {
25
25
  getRoles,
26
26
  setRole,
27
27
  VALID_ROLES,
28
+ runMaintenance,
29
+ getCronStatus,
30
+ installCron,
31
+ removeCron,
28
32
  } from "../index.js";
29
33
 
30
34
  function printHelp() {
@@ -41,6 +45,8 @@ Commands:
41
45
  pull <gist:id|url> Download and restore configs from Gist or HTTP URL
42
46
  rollback Revert the most recent config restore from its backup
43
47
  rehydrate Rehydrate and repair locked/linked plugins in ~/.omp/plugins
48
+ maint / gc [--force] Run automatic storage maintenance, WAL checkpoint & GC
49
+ cron [install|status|rm] Manage OS-level scheduled crontab maintenance job
44
50
  provider add <name> Auto-probe and add an LLM provider (public or private)
45
51
  provider ls / list List configured providers, models and active role bindings
46
52
  provider rm <name> Remove a provider from public or private store
@@ -63,6 +69,7 @@ Options:
63
69
  --private Save as private (local-only, unsynced, non-overwritten) [default]
64
70
  --public Save as public (synced across machines via models.yml)
65
71
  -y, --yes Non-interactive mode (use defaults without prompting)
72
+ -f, --force Force operations (e.g. bypass maintenance debounce)
66
73
 
67
74
  Environment Variables:
68
75
  OMP_CONFIG_PASS Passphrase for non-interactive automation
@@ -91,6 +98,7 @@ function parseCliArgs(argv) {
91
98
  role: null,
92
99
  isPrivate: null,
93
100
  nonInteractive: false,
101
+ force: false,
94
102
  positional: [],
95
103
  };
96
104
 
@@ -127,6 +135,8 @@ function parseCliArgs(argv) {
127
135
  options.isPrivate = false;
128
136
  } else if (a === "-y" || a === "--yes" || a === "--non-interactive") {
129
137
  options.nonInteractive = true;
138
+ } else if (a === "-f" || a === "--force") {
139
+ options.force = true;
130
140
  } else if (a.startsWith("--pass=")) {
131
141
  options.pass = a.slice(7);
132
142
  } else if (a.startsWith("--token=")) {
@@ -307,6 +317,66 @@ async function main() {
307
317
  }
308
318
  break;
309
319
  }
320
+ case "maint":
321
+ case "gc": {
322
+ const force = Boolean(options.force || options.positional?.includes("--force"));
323
+ console.log(`[maint] Running storage maintenance and garbage collection on ${root}...`);
324
+ const res = await runMaintenance({
325
+ agentDir: root,
326
+ force,
327
+ dryRun: options.dryRun,
328
+ });
329
+
330
+ if (res.skipped) {
331
+ console.log(
332
+ `[maint] Storage maintenance skipped (already executed recently). Next run in ~${res.nextRunInMinutes}m. Use --force to override.`
333
+ );
334
+ break;
335
+ }
336
+
337
+ console.log(`[maint] ✓ Corrupt crash files cleaned: ${res.corruptCleaned?.length || 0}`);
338
+ console.log(`[maint] ✓ Obsolete legacy files purged: ${res.obsoletePurged?.length || 0}`);
339
+ console.log(`[maint] ✓ Old backup snapshots pruned: ${res.backupsPruned?.length || 0}`);
340
+ if (res.gc) {
341
+ if (res.gc.success) {
342
+ console.log(`[maint] ✓ Native GC & WAL checkpoint:\n ${res.gc.output.split("\n").join("\n ")}`);
343
+ } else {
344
+ console.warn(`[maint] ⚠ Native GC warning: ${res.gc.error}`);
345
+ }
346
+ }
347
+ break;
348
+ }
349
+ case "cron": {
350
+ const sub = (options.target || "status").toLowerCase();
351
+ if (sub === "status") {
352
+ const st = getCronStatus();
353
+ if (!st.supported) {
354
+ console.log("[cron] System crontab is not supported or not available in this environment.");
355
+ } else if (st.installed) {
356
+ console.log(`[cron] ✓ Active scheduled maintenance job:\n ${st.line}`);
357
+ } else {
358
+ console.log("[cron] No automated maintenance job installed in crontab. Run 'omp-sync cron install' to enable.");
359
+ }
360
+ } else if (sub === "install" || sub === "enable") {
361
+ const schedule = options.positional[2] || "0 3 * * *";
362
+ const res = installCron(schedule);
363
+ if (res.success) {
364
+ console.log(`[cron] ✓ Successfully installed maintenance job (${res.schedule}) in system crontab.`);
365
+ } else {
366
+ console.error(`[cron] ✗ Failed to install crontab job: ${res.error}`);
367
+ }
368
+ } else if (sub === "remove" || sub === "rm" || sub === "uninstall" || sub === "disable") {
369
+ const res = removeCron();
370
+ if (res.success) {
371
+ console.log("[cron] ✓ Successfully removed maintenance job from system crontab.");
372
+ } else {
373
+ console.error(`[cron] ✗ Failed to remove crontab job: ${res.error}`);
374
+ }
375
+ } else {
376
+ throw new Error(`Unknown cron subcommand: ${sub}. Allowed: status, install [schedule], remove.`);
377
+ }
378
+ break;
379
+ }
310
380
 
311
381
  case "provider": {
312
382
  const sub = (options.target || "list").toLowerCase();
package/index.js CHANGED
@@ -40,6 +40,17 @@ import {
40
40
  formatYamlModels,
41
41
  } from "./src/provider-store.js";
42
42
  import { getRoles, setRole, VALID_ROLES } from "./src/role-manager.js";
43
+ import {
44
+ runMaintenance,
45
+ cleanCorruptFiles,
46
+ pruneOldBackups,
47
+ cleanObsoleteFiles,
48
+ runOmpGc,
49
+ scheduleAutoMaintenance,
50
+ getCronStatus,
51
+ installCron,
52
+ removeCron,
53
+ } from "./src/maintenance.js";
43
54
 
44
55
  export {
45
56
  probeProvider,
@@ -57,6 +68,15 @@ export {
57
68
  getRoles,
58
69
  setRole,
59
70
  VALID_ROLES,
71
+ runMaintenance,
72
+ cleanCorruptFiles,
73
+ pruneOldBackups,
74
+ cleanObsoleteFiles,
75
+ runOmpGc,
76
+ scheduleAutoMaintenance,
77
+ getCronStatus,
78
+ installCron,
79
+ removeCron,
60
80
  };
61
81
 
62
82
  const MAGIC = Buffer.from("OMPCFG1\0", "latin1");
@@ -925,4 +945,35 @@ export default function (pi) {
925
945
  }
926
946
  },
927
947
  });
948
+
949
+ // Register maintenance command (/maint or /gc)
950
+ pi.registerCommand("maint", {
951
+ description: "Run storage maintenance, WAL checkpoint, and garbage collection (/maint [--force])",
952
+ handler: async (args, ctx) => {
953
+ const force = (args || "").includes("--force");
954
+ ctx.ui.notify("Running storage maintenance & garbage collection...", "info");
955
+ try {
956
+ const res = await runMaintenance({
957
+ agentDir: configRoot(),
958
+ force: true, // User manual trigger always forces execution
959
+ });
960
+
961
+ const parts = [];
962
+ if (res.corruptCleaned?.length > 0) parts.push(`cleaned ${res.corruptCleaned.length} corrupt file(s)`);
963
+ if (res.backupsPruned?.length > 0) parts.push(`pruned ${res.backupsPruned.length} backup snapshot(s)`);
964
+ if (res.obsoletePurged?.length > 0) parts.push(`purged ${res.obsoletePurged.length} obsolete file(s)`);
965
+ if (res.gc?.success) parts.push("WAL checkpointed & GC complete");
966
+
967
+ const msg = parts.length > 0 ? `Maintenance complete: ${parts.join(", ")}.` : "Storage is already optimal. No cleanup needed.";
968
+ ctx.ui.notify(msg, "info");
969
+ } catch (err) {
970
+ ctx.ui.notify(`Maintenance error: ${err.message || err}`, "error");
971
+ }
972
+ },
973
+ });
974
+
975
+ // Launch non-blocking background auto-maintenance (debounced every 24h)
976
+ try {
977
+ scheduleAutoMaintenance(configRoot(), 4000);
978
+ } catch {}
928
979
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omp-config-crypt",
3
- "version": "0.5.6",
3
+ "version": "0.6.1",
4
4
  "description": "Universal cross-platform encrypted portability for omp config, extensions, and instructions",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,241 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import { exec, execSync } from "node:child_process";
5
+ import { promisify } from "node:util";
6
+
7
+ const execAsync = promisify(exec);
8
+
9
+ export function getAgentDir(root) {
10
+ return root || process.env.OMP_CFG_ROOT || path.join(os.homedir(), ".omp", "agent");
11
+ }
12
+
13
+ export function getOmpHome(agentDir) {
14
+ const norm = path.resolve(agentDir);
15
+ return path.basename(norm) === "agent" ? path.dirname(norm) : norm;
16
+ }
17
+
18
+ /**
19
+ * Remove corrupt database files (*.corrupt-*) left over from crashes.
20
+ */
21
+ export function cleanCorruptFiles(agentDir) {
22
+ const cleaned = [];
23
+ if (!fs.existsSync(agentDir)) return cleaned;
24
+
25
+ const entries = fs.readdirSync(agentDir, { withFileTypes: true });
26
+ for (const entry of entries) {
27
+ if (entry.name.includes(".corrupt-")) {
28
+ const fullPath = path.join(agentDir, entry.name);
29
+ try {
30
+ const stat = fs.statSync(fullPath);
31
+ fs.rmSync(fullPath, { recursive: true, force: true });
32
+ cleaned.push({ path: fullPath, bytes: stat.size });
33
+ } catch {}
34
+ }
35
+ }
36
+ return cleaned;
37
+ }
38
+
39
+ /**
40
+ * Prune historical .import-backup-* directories, keeping only the most recent N.
41
+ */
42
+ export function pruneOldBackups(agentDir, keepCount = 3) {
43
+ const pruned = [];
44
+ if (!fs.existsSync(agentDir)) return pruned;
45
+
46
+ const entries = fs.readdirSync(agentDir, { withFileTypes: true });
47
+ const backups = entries
48
+ .filter((e) => e.isDirectory() && e.name.startsWith(".import-backup-"))
49
+ .map((e) => e.name)
50
+ .sort()
51
+ .reverse();
52
+
53
+ if (backups.length > keepCount) {
54
+ const toRemove = backups.slice(keepCount);
55
+ for (const name of toRemove) {
56
+ const fullPath = path.join(agentDir, name);
57
+ try {
58
+ fs.rmSync(fullPath, { recursive: true, force: true });
59
+ pruned.push(fullPath);
60
+ } catch {}
61
+ }
62
+ }
63
+ return pruned;
64
+ }
65
+
66
+ /**
67
+ * Remove obsolete legacy transition files.
68
+ */
69
+ export function cleanObsoleteFiles(agentDir) {
70
+ const ompDir = getOmpHome(agentDir);
71
+ const targets = [
72
+ path.join(agentDir, "models.local.json"),
73
+ path.join(ompDir, "extensions", "local-models.js"),
74
+ path.join(ompDir, "extensions", "agy.js"),
75
+ ];
76
+
77
+ const purged = [];
78
+ for (const p of targets) {
79
+ if (fs.existsSync(p)) {
80
+ try {
81
+ fs.rmSync(p, { force: true });
82
+ purged.push(p);
83
+ } catch {}
84
+ }
85
+ }
86
+ return purged;
87
+ }
88
+
89
+ /**
90
+ * Execute OMP native garbage collection and checkpoint WAL files.
91
+ */
92
+ export async function runOmpGc({
93
+ archiveDays = 14,
94
+ retainNewest = 20,
95
+ agentDir = null,
96
+ } = {}) {
97
+ const dirFlag = agentDir ? `--agent-dir="${agentDir}"` : "";
98
+ const cmd = `omp gc --apply --blobs --stale --wal --archive --cold-archive-after-days=${archiveDays} --retain-newest-global=${retainNewest} ${dirFlag}`.trim();
99
+ try {
100
+ const { stdout, stderr } = await execAsync(cmd);
101
+ return { success: true, output: (stdout + "\n" + stderr).trim() };
102
+ } catch (err) {
103
+ return { success: false, error: err.message, output: (err.stdout || "") + (err.stderr || "") };
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Full automatic maintenance cycle with debouncing.
109
+ */
110
+ export async function runMaintenance({
111
+ agentDir = getAgentDir(),
112
+ dryRun = false,
113
+ force = false,
114
+ intervalHours = 24,
115
+ archiveDays = 14,
116
+ keepBackups = 3,
117
+ skipGc = false,
118
+ } = {}) {
119
+ const stampFile = path.join(agentDir, ".last-maintenance.json");
120
+ const now = Date.now();
121
+ const minIntervalMs = intervalHours * 3600 * 1000;
122
+
123
+ if (!force && fs.existsSync(stampFile)) {
124
+ try {
125
+ const stamp = JSON.parse(fs.readFileSync(stampFile, "utf8"));
126
+ if (stamp.timestamp && now - stamp.timestamp < minIntervalMs) {
127
+ return {
128
+ skipped: true,
129
+ reason: "debounced",
130
+ lastRun: stamp.lastRun,
131
+ nextRunInMinutes: Math.round((minIntervalMs - (now - stamp.timestamp)) / 60000),
132
+ };
133
+ }
134
+ } catch {}
135
+ }
136
+
137
+ const result = {
138
+ skipped: false,
139
+ timestamp: now,
140
+ lastRun: new Date(now).toISOString(),
141
+ corruptCleaned: [],
142
+ backupsPruned: [],
143
+ obsoletePurged: [],
144
+ gc: null,
145
+ };
146
+
147
+ if (dryRun) {
148
+ result.dryRun = true;
149
+ return result;
150
+ }
151
+
152
+ // 1. Clean corrupt crash dumps
153
+ result.corruptCleaned = cleanCorruptFiles(agentDir);
154
+
155
+ // 2. Prune old import backup snapshots
156
+ result.backupsPruned = pruneOldBackups(agentDir, keepBackups);
157
+
158
+ // 3. Purge obsolete files
159
+ result.obsoletePurged = cleanObsoleteFiles(agentDir);
160
+
161
+ // 4. Run native GC
162
+ if (!skipGc) {
163
+ result.gc = await runOmpGc({ archiveDays, agentDir });
164
+ }
165
+
166
+ // 5. Update stamp
167
+ try {
168
+ fs.mkdirSync(agentDir, { recursive: true });
169
+ fs.writeFileSync(stampFile, JSON.stringify(result, null, 2), "utf8");
170
+ } catch {}
171
+
172
+ return result;
173
+ }
174
+
175
+ /**
176
+ * Start non-blocking background auto-maintenance.
177
+ * Runs in background after delayMs without blocking startup.
178
+ */
179
+ export function scheduleAutoMaintenance(agentDir = getAgentDir(), delayMs = 4000) {
180
+ setTimeout(() => {
181
+ runMaintenance({ agentDir }).catch(() => {});
182
+ }, delayMs).unref?.();
183
+ }
184
+
185
+ const CRON_TAG = "# omp-auto-maint";
186
+
187
+ /**
188
+ * Check if automated maintenance is scheduled in system crontab.
189
+ */
190
+ export function getCronStatus() {
191
+ try {
192
+ const out = execSync("crontab -l 2>/dev/null", { encoding: "utf8" });
193
+ const line = out.split("\n").find((l) => l.includes(CRON_TAG));
194
+ return { installed: Boolean(line), line: line || null, supported: true };
195
+ } catch {
196
+ return { installed: false, line: null, supported: false };
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Install scheduled maintenance into system crontab.
202
+ */
203
+ export function installCron(schedule = "0 3 * * *", command = null) {
204
+ try {
205
+ let current = "";
206
+ try {
207
+ current = execSync("crontab -l 2>/dev/null", { encoding: "utf8" });
208
+ } catch {}
209
+
210
+ const lines = current.split("\n").filter((l) => !l.includes(CRON_TAG) && l.trim().length > 0);
211
+ const cmd = command || "npx -y omp-config-crypt maint --force > /dev/null 2>&1";
212
+ lines.push(`${schedule} ${cmd} ${CRON_TAG}`);
213
+
214
+ execSync(`(echo "${lines.join("\n")}") | crontab -`);
215
+ return { success: true, schedule, command: cmd };
216
+ } catch (err) {
217
+ return { success: false, error: err.message };
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Remove scheduled maintenance from system crontab.
223
+ */
224
+ export function removeCron() {
225
+ try {
226
+ let current = "";
227
+ try {
228
+ current = execSync("crontab -l 2>/dev/null", { encoding: "utf8" });
229
+ } catch {}
230
+
231
+ const lines = current.split("\n").filter((l) => !l.includes(CRON_TAG) && l.trim().length > 0);
232
+ if (lines.length > 0) {
233
+ execSync(`(echo "${lines.join("\n")}") | crontab -`);
234
+ } else {
235
+ execSync("crontab -r 2>/dev/null || true");
236
+ }
237
+ return { success: true };
238
+ } catch (err) {
239
+ return { success: false, error: err.message };
240
+ }
241
+ }