omp-config-crypt 0.6.5 → 0.7.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
@@ -1,4 +1,4 @@
1
- # omp-config-crypt (v0.5.0)
1
+ # omp-config-crypt (v0.7.0)
2
2
 
3
3
  Universal, zero-repair cross-platform configuration encryption and synchronization engine for `omp` (Oh My Pi).
4
4
 
@@ -48,8 +48,20 @@ npx omp-config-crypt push gist:new --pass "mysecret" --token "$GITHUB_TOKEN"
48
48
  # Cloud Pull (GitHub Gist)
49
49
  npx omp-config-crypt pull gist:<id> --pass "mysecret" --token "$GITHUB_TOKEN"
50
50
 
51
+ # Cloud Pull adopting a different remote configuration set (takeover):
52
+ # aligns local sync-policy/sync-state namespace to the remote one; both files are backed up to .bak first
53
+ npx omp-config-crypt pull gist:<id> --pass "mysecret" --token "$GITHUB_TOKEN" --force
54
+
55
+ # Cloud Pull self-healing: machines with no sync state yet adopt the remote set
56
+ # automatically (no --force needed); corrupt policy/state JSON is backed up and rebuilt
57
+ npx omp-config-crypt pull gist:<id> --pass "mysecret" --token "$GITHUB_TOKEN"
58
+
51
59
  # Rollback to previous configuration snapshot
52
60
  npx omp-config-crypt rollback
61
+
62
+ # Self-update the package (plugins dir or global install); --check only reports
63
+ npx omp-config-crypt upgrade --check
64
+ npx omp-config-crypt upgrade
53
65
  ```
54
66
 
55
67
  # Provider Auto-Probing & Management (Public / Private)
@@ -77,9 +89,10 @@ Configuration exports include the installed `omp-config-crypt` source (excluding
77
89
  /config-push gist:new
78
90
  /config-push gist:<id>
79
91
  /config-push https://…
80
- /config-pull gist:<id> [--dry-run]
81
- /config-pull https://… [--dry-run]
92
+ /config-pull gist:<id> [--dry-run] [--force]
93
+ /config-pull https://… [--dry-run] [--force]
82
94
  /config-rollback
95
+ /config-upgrade [--check]
83
96
  ```
84
97
 
85
98
  ### Provider control menu
package/bin/omp-sync.js CHANGED
@@ -30,6 +30,7 @@ import {
30
30
  setRole,
31
31
  VALID_ROLES,
32
32
  runMaintenance,
33
+ runUpgrade,
33
34
  getCronStatus,
34
35
  installCron,
35
36
  removeCron,
@@ -55,10 +56,13 @@ Commands:
55
56
  adapt <srcFile> [out] Adapt legacy v1/v2 archive to current v3 specification
56
57
  push <gist:id|url> Encrypt and push configs to GitHub Gist or HTTP URL
57
58
  pull <gist:id|url> Download and restore configs from Gist or HTTP URL
59
+ (-f/--force adopts a differing remote namespace; local
60
+ policy/state are backed up to .bak first)
58
61
  rollback Revert the most recent config restore from its backup
59
62
  rehydrate Rehydrate and repair locked/linked plugins in ~/.omp/plugins
60
63
  maint / gc [--force] Run automatic storage maintenance, WAL checkpoint & GC
61
64
  cron [install|status|rm] Manage OS-level scheduled crontab maintenance job
65
+ upgrade [--check] Update omp-config-crypt in place (plugins dir or global)
62
66
  provider add <name> Auto-probe and add an LLM provider (public or private)
63
67
  provider ls / list List configured providers, models and active role bindings
64
68
  provider rm <name> Remove a provider from public or private store
@@ -79,7 +83,7 @@ Options:
79
83
  --private Save as private (local-only, unsynced, non-overwritten) [default]
80
84
  --public Save as public (synced across machines via models.yml)
81
85
  -y, --yes Non-interactive mode (use defaults without prompting)
82
- -f, --force Force operations (e.g. bypass maintenance debounce)
86
+ -f, --force Force operations (pull: adopt differing remote namespace)
83
87
  --profile <name> Target specific profile scene (e.g. dev, ops)
84
88
 
85
89
  Environment Variables:
@@ -110,6 +114,7 @@ function parseCliArgs(argv) {
110
114
  isPrivate: null,
111
115
  nonInteractive: false,
112
116
  force: false,
117
+ checkOnly: false,
113
118
  positional: [],
114
119
  profile: null,
115
120
  };
@@ -147,6 +152,8 @@ function parseCliArgs(argv) {
147
152
  options.nonInteractive = true;
148
153
  } else if (a === "-f" || a === "--force") {
149
154
  options.force = true;
155
+ } else if (a === "--check") {
156
+ options.checkOnly = true;
150
157
  } else if (a === "--profile") {
151
158
  options.profile = args[++i];
152
159
  } else if (a.startsWith("--profile=")) {
@@ -354,8 +361,14 @@ async function main() {
354
361
  const token = await resolveToken(options.token, target.kind === "gist");
355
362
  const res =
356
363
  target.kind === "gist"
357
- ? await pullGist(target.id, pass, root, token, { dryRun: options.dryRun })
358
- : await pullHttp(target.url, pass, root, token, { dryRun: options.dryRun });
364
+ ? await pullGist(target.id, pass, root, token, { dryRun: options.dryRun, force: options.force })
365
+ : await pullHttp(target.url, pass, root, token, { dryRun: options.dryRun, force: options.force });
366
+ if (res.adoptedNamespace) {
367
+ console.log(`[pull] Adopted remote namespace ${res.adoptedNamespace} (--force); prior policy/state saved as .bak`);
368
+ }
369
+ if (Array.isArray(res.healed) && res.healed.length > 0) {
370
+ console.log(`[pull] Self-healed: ${res.healed.join("; ")}`);
371
+ }
359
372
  if (res.adaptedFile) {
360
373
  console.log(`[pull] incompatible v${res.legacy?.from}; adapted -> ${res.adaptedFile}`);
361
374
  }
@@ -442,6 +455,13 @@ async function main() {
442
455
  }
443
456
  break;
444
457
  }
458
+ case "upgrade": {
459
+ const r = runUpgrade({ check: options.checkOnly });
460
+ console.log(`[upgrade] local ${r.local} / latest ${r.latest ?? "unavailable"}`);
461
+ console.log(`[upgrade] ${r.action}${r.reason ? `: ${r.reason}` : ""}`);
462
+ if (r.action === "manual") process.exitCode = 2;
463
+ break;
464
+ }
445
465
  case "cron": {
446
466
  const sub = (options.target || "status").toLowerCase();
447
467
  if (sub === "status") {
@@ -712,7 +732,7 @@ async function main() {
712
732
  process.exit(1);
713
733
  }
714
734
  } catch (err) {
715
- console.error(`[error] ${err.message || err}`);
735
+ console.error(`[error] ${err.stack || err.message || err}`);
716
736
  process.exit(1);
717
737
  }
718
738
  }
package/index.js CHANGED
@@ -43,6 +43,7 @@ import { getRoles, setRole, VALID_ROLES } from "./src/role-manager.js";
43
43
  import { handleProviderCommand, providerCompletions } from "./src/provider-menu.js";
44
44
  import {
45
45
  runMaintenance,
46
+ runUpgrade,
46
47
  cleanCorruptFiles,
47
48
  pruneOldBackups,
48
49
  cleanObsoleteFiles,
@@ -70,6 +71,7 @@ export {
70
71
  setRole,
71
72
  VALID_ROLES,
72
73
  runMaintenance,
74
+ runUpgrade,
73
75
  cleanCorruptFiles,
74
76
  pruneOldBackups,
75
77
  cleanObsoleteFiles,
@@ -109,6 +111,8 @@ import {
109
111
  inspectArchivePayload,
110
112
  adaptLegacySnapshot,
111
113
  planSync,
114
+ adoptSyncNamespace,
115
+ healSyncMetadata,
112
116
  } from "./src/sync-plan.js";
113
117
  import {
114
118
  applySyncPlan,
@@ -146,6 +150,8 @@ export {
146
150
  };
147
151
 
148
152
  const MAGIC = Buffer.from("OMPCFG1\0", "latin1");
153
+ // Pinned to Node's historical defaults so archives stay decryptable across Node versions.
154
+ const SCRYPT_PARAMS = { N: 16384, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
149
155
 
150
156
  /**
151
157
  * Collect is now defined strictly as the read-only file projection of public resources.
@@ -286,7 +292,7 @@ export function decryptArchiveBlob(blob, pass) {
286
292
  const iv = blob.subarray(o, (o += 12));
287
293
  const tag = blob.subarray(o, (o += 16));
288
294
  const ct = blob.subarray(o);
289
- const key = scryptSync(pass, salt, 32);
295
+ const key = scryptSync(pass, salt, 32, SCRYPT_PARAMS);
290
296
  const decipher = createDecipheriv("aes-256-gcm", key, iv);
291
297
  decipher.setAuthTag(tag);
292
298
 
@@ -308,7 +314,7 @@ export function encryptArchivePayload(payload, pass) {
308
314
  const plain = gzipSync(Buffer.from(JSON.stringify(payload)), { level: 9 });
309
315
  const salt = randomBytes(16);
310
316
  const iv = randomBytes(12);
311
- const key = scryptSync(pass, salt, 32);
317
+ const key = scryptSync(pass, salt, 32, SCRYPT_PARAMS);
312
318
  const cipher = createCipheriv("aes-256-gcm", key, iv);
313
319
  const ct = Buffer.concat([cipher.update(plain), cipher.final()]);
314
320
  return Buffer.concat([MAGIC, salt, iv, cipher.getAuthTag(), ct]);
@@ -621,12 +627,49 @@ export async function pushGist(id, pass, root = configRoot(), token = envToken()
621
627
  return { id: data.id, url: data.html_url, files, bytes: blob.length };
622
628
  }
623
629
 
624
- function restoreRemoteArchive(blob, pass, root = configRoot(), options = {}) {
630
+ /**
631
+ * A local install may take over a remote namespace without --force only when it holds
632
+ * no sync state worth losing: no state file, or a policy with no public resources.
633
+ */
634
+ function canAutoAdoptLocal(root) {
635
+ if (!fs.existsSync(path.join(root, STATE_FILE))) return true;
636
+ try {
637
+ const policy = readSyncPolicy(root);
638
+ return !Object.values(policy.resources || {}).includes("public");
639
+ } catch {
640
+ return false;
641
+ }
642
+ }
643
+
644
+ function restoreWithForce(attempt, payload, root, options, healing = { healed: [] }) {
645
+ let res;
646
+ try {
647
+ res = attempt();
648
+ } catch (error) {
649
+ const blocked = error?.blocked;
650
+ const nsOnly =
651
+ Array.isArray(blocked) && blocked.length > 0 && blocked.every((b) => b.id === "namespace");
652
+ const auto = options.force || canAutoAdoptLocal(root);
653
+ if (!auto || !nsOnly || !payload?.namespace) throw error;
654
+ const adoption = adoptSyncNamespace(payload.namespace, root);
655
+ res = attempt();
656
+ return {
657
+ ...res,
658
+ adoptedNamespace: payload.namespace,
659
+ adoptedBackups: adoption.backups,
660
+ healed: [...healing.healed, options.force ? "namespace:forced-adopted" : "namespace:auto-adopted"],
661
+ };
662
+ }
663
+ return { ...res, healed: [...healing.healed] };
664
+ }
665
+
666
+ export function restoreRemoteArchive(blob, pass, root = configRoot(), options = {}) {
667
+ const healing = options.dryRun ? { healed: [] } : healSyncMetadata(root);
625
668
  const payload = decryptArchiveBlob(blob, pass);
626
669
  const inspection = inspectArchivePayload(payload);
627
670
 
628
671
  if (inspection.compatible) {
629
- return restoreArchive(blob, pass, root, options);
672
+ return restoreWithForce(() => restoreArchive(blob, pass, root, options), payload, root, options, healing);
630
673
  }
631
674
 
632
675
  if (!inspection.adaptable) {
@@ -650,7 +693,7 @@ function restoreRemoteArchive(blob, pass, root = configRoot(), options = {}) {
650
693
 
651
694
  const adaptedFile = path.join(os.tmpdir(), `omp-archive-v3-${Date.now()}.enc`);
652
695
  fs.writeFileSync(adaptedFile, adaptedBlob, { mode: 0o600 });
653
- const res = restoreArchive(adaptedBlob, pass, root, options);
696
+ const res = restoreWithForce(() => restoreArchive(adaptedBlob, pass, root, options), adapted, root, options, healing);
654
697
  return {
655
698
  ...res,
656
699
  adaptedFile,
@@ -719,19 +762,24 @@ export function extractDryRun(str) {
719
762
  const tokens = [];
720
763
  const re = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|(\S+)/g;
721
764
  let match;
722
- while ((match = re.exec(raw))) {
723
- tokens.push(match[1] !== undefined ? match[1] : match[2] !== undefined ? match[2] : match[3]);
724
- }
725
765
  let dryRun = false;
766
+ let force = false;
726
767
  const kept = [];
727
- for (const token of tokens) {
768
+ while ((match = re.exec(raw))) {
769
+ const token = match[1] !== undefined ? match[1] : match[2] !== undefined ? match[2] : match[3];
728
770
  if (token === "--dry-run" || token === "-d") {
729
771
  dryRun = true;
730
772
  continue;
731
773
  }
774
+ if (token === "--force" || token === "-f") {
775
+ force = true;
776
+ continue;
777
+ }
732
778
  kept.push(token);
733
779
  }
734
- return { dryRun, clean: kept.join(" ") };
780
+ const result = { dryRun, clean: kept.join(" ") };
781
+ if (force) result.force = true;
782
+ return result;
735
783
  }
736
784
 
737
785
  export function formatSyncReport(result = {}) {
@@ -1028,9 +1076,9 @@ export default function (pi) {
1028
1076
  const sel = await selectPublicResources(ctx, root);
1029
1077
  if (sel === null) return;
1030
1078
  }
1031
- const { dryRun, clean: spec } = extractDryRun(args || "");
1079
+ const { dryRun, force, clean: spec } = extractDryRun(args || "");
1032
1080
  if (!spec) {
1033
- ctx.ui.notify("usage: /config-pull gist:<id> | https://… [--dry-run]", "error");
1081
+ ctx.ui.notify("usage: /config-pull gist:<id> | https://… [--dry-run] [--force]", "error");
1034
1082
  return;
1035
1083
  }
1036
1084
  try {
@@ -1038,8 +1086,14 @@ export default function (pi) {
1038
1086
  const pass = await askPass(ctx, "Pull passphrase");
1039
1087
  const token = await askToken(ctx, "Cloud token", target.kind === "gist");
1040
1088
  const r = target.kind === "gist"
1041
- ? await pullGist(target.id, pass, configRoot(), token, { dryRun })
1042
- : await pullHttp(target.url, pass, configRoot(), token, { dryRun });
1089
+ ? await pullGist(target.id, pass, configRoot(), token, { dryRun, force })
1090
+ : await pullHttp(target.url, pass, configRoot(), token, { dryRun, force });
1091
+ if (r.adoptedNamespace) {
1092
+ ctx.ui.notify(`[pull] adopted remote namespace ${r.adoptedNamespace}; prior policy/state saved as .bak`, "info");
1093
+ }
1094
+ if (Array.isArray(r.healed) && r.healed.length > 0) {
1095
+ ctx.ui.notify(`[pull] self-healed: ${r.healed.join("; ")}`, "info");
1096
+ }
1043
1097
  if (r.adaptedFile) {
1044
1098
  ctx.ui.notify(`[pull] incompatible v${r.legacy?.from}; adapted -> ${r.adaptedFile}`, "info");
1045
1099
  }
@@ -1067,6 +1121,21 @@ export default function (pi) {
1067
1121
  },
1068
1122
  });
1069
1123
 
1124
+ pi.registerCommand("config-upgrade", {
1125
+ description: "Check for and install omp-config-crypt updates (--check for check-only)",
1126
+ handler: async (args, ctx) => {
1127
+ try {
1128
+ const r = runUpgrade({ check: /--check/.test(args || "") });
1129
+ ctx.ui.notify(
1130
+ `upgrade: local ${r.local}, latest ${r.latest ?? "unavailable"} -> ${r.action}${r.reason ? ` (${r.reason})` : ""}`,
1131
+ r.action === "manual" ? "warn" : "info",
1132
+ );
1133
+ } catch (error) {
1134
+ ctx.ui.notify(`config-upgrade failed: ${error?.message ?? error}`, "error");
1135
+ }
1136
+ },
1137
+ });
1138
+
1070
1139
  pi.registerCommand("provider", {
1071
1140
  description: "Provider control menu · ls | add | edit <name> | test <name> | rm <name>",
1072
1141
  getArgumentCompletions: prefix => providerCompletions(prefix, configRoot()),
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "omp-config-crypt",
3
- "version": "0.6.5",
3
+ "version": "0.7.0",
4
4
  "description": "Universal cross-platform encrypted portability for omp config, extensions, and instructions",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
7
10
  "bin": {
8
11
  "omp-sync": "./bin/omp-sync.js"
9
12
  },
@@ -1,8 +1,11 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import os from "node:os";
4
- import { exec, execSync } from "node:child_process";
4
+ import { fileURLToPath } from "node:url";
5
+ import { randomUUID } from "node:crypto";
6
+ import { exec, execSync, execFileSync } from "node:child_process";
5
7
  import { promisify } from "node:util";
8
+ import { resolveNpmCommand } from "./rehydrator.js";
6
9
 
7
10
  const execAsync = promisify(exec);
8
11
 
@@ -225,10 +228,20 @@ export function getCronStatus() {
225
228
  }
226
229
  }
227
230
 
231
+ /**
232
+ * A valid cron schedule is exactly 5 whitespace-separated fields of digits, *, -, /, comma.
233
+ */
234
+ export function validateCronSchedule(s) {
235
+ return /^[\d*,\-/]+(?: [\d*,\-/]+){4}$/.test(String(s ?? ""));
236
+ }
237
+
228
238
  /**
229
239
  * Install scheduled maintenance into system crontab.
230
240
  */
231
241
  export function installCron(schedule = "0 3 * * *", command = null) {
242
+ if (!validateCronSchedule(schedule)) {
243
+ throw new Error("invalid cron schedule: expected 5 fields of digits, *, -, /, comma");
244
+ }
232
245
  try {
233
246
  let current = "";
234
247
  try {
@@ -239,7 +252,15 @@ export function installCron(schedule = "0 3 * * *", command = null) {
239
252
  const cmd = command || "npx -y omp-config-crypt maint --force > /dev/null 2>&1";
240
253
  lines.push(`${schedule} ${cmd} ${CRON_TAG}`);
241
254
 
242
- execSync(`(echo "${lines.join("\n")}") | crontab -`);
255
+ const tmp = path.join(os.tmpdir(), `omp-crontab-${randomUUID()}`);
256
+ fs.writeFileSync(tmp, `${lines.join("\n")}\n`, { mode: 0o600 });
257
+ try {
258
+ execFileSync("crontab", [tmp], { stdio: "pipe" });
259
+ } finally {
260
+ try {
261
+ fs.unlinkSync(tmp);
262
+ } catch {}
263
+ }
243
264
  return { success: true, schedule, command: cmd };
244
265
  } catch (err) {
245
266
  return { success: false, error: err.message };
@@ -258,7 +279,15 @@ export function removeCron() {
258
279
 
259
280
  const lines = current.split("\n").filter((l) => !l.includes(CRON_TAG) && l.trim().length > 0);
260
281
  if (lines.length > 0) {
261
- execSync(`(echo "${lines.join("\n")}") | crontab -`);
282
+ const tmp = path.join(os.tmpdir(), `omp-crontab-${randomUUID()}`);
283
+ fs.writeFileSync(tmp, `${lines.join("\n")}\n`, { mode: 0o600 });
284
+ try {
285
+ execFileSync("crontab", [tmp], { stdio: "pipe" });
286
+ } finally {
287
+ try {
288
+ fs.unlinkSync(tmp);
289
+ } catch {}
290
+ }
262
291
  } else {
263
292
  execSync("crontab -r 2>/dev/null || true");
264
293
  }
@@ -267,3 +296,61 @@ export function removeCron() {
267
296
  return { success: false, error: err.message };
268
297
  }
269
298
  }
299
+
300
+ function cmpSemver(a, b) {
301
+ const pa = String(a).replace(/-.*$/, "").split(".").map(Number);
302
+ const pb = String(b).replace(/-.*$/, "").split(".").map(Number);
303
+ for (let i = 0; i < 3; i++) {
304
+ if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) < (pb[i] || 0) ? -1 : 1;
305
+ }
306
+ return 0;
307
+ }
308
+
309
+ /**
310
+ * Compares the local package version against the latest published version.
311
+ */
312
+ export function planUpgrade(localVersion, latestVersion) {
313
+ if (!localVersion || !latestVersion) return { action: "unknown", reason: "version unavailable" };
314
+ const c = cmpSemver(localVersion, latestVersion);
315
+ if (c === 0) return { action: "none", reason: "up to date" };
316
+ return c < 0 ? { action: "upgrade" } : { action: "none", reason: "local is newer" };
317
+ }
318
+
319
+ /**
320
+ * Checks npm for a newer omp-config-crypt and, unless check-only, updates the
321
+ * package in place: plugins installs are updated via the enclosing plugins root,
322
+ * everything else falls back to a global install. Dev/symlinked checkouts report
323
+ * manual upgrade instead of touching the working tree.
324
+ */
325
+ export function runUpgrade({ check = false } = {}) {
326
+ const pkg = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
327
+ const npmCmd = resolveNpmCommand();
328
+ let latest = "";
329
+ try {
330
+ latest = execFileSync(npmCmd.file, ["view", "omp-config-crypt", "version", "--registry", "https://registry.npmjs.org"], { encoding: "utf8", shell: npmCmd.shell }).trim();
331
+ } catch { /* latest stays empty; planUpgrade reports unknown */ }
332
+ const plan = planUpgrade(pkg.version, latest);
333
+
334
+ if (plan.action !== "upgrade" || check) {
335
+ return { local: pkg.version, latest: latest || null, ...plan };
336
+ }
337
+
338
+ const selfDir = path.dirname(fileURLToPath(import.meta.url));
339
+ let isDev = false;
340
+ try { isDev = fs.realpathSync(selfDir) !== selfDir; } catch {}
341
+ if (isDev) return { local: pkg.version, latest, action: "manual", reason: "dev/symlinked install; upgrade via git pull" };
342
+
343
+ const parts = selfDir.split(path.sep);
344
+ const nmIdx = parts.lastIndexOf("node_modules");
345
+ try {
346
+ if (nmIdx !== -1 && parts[nmIdx + 1] === "omp-config-crypt") {
347
+ const installRoot = path.join(...parts.slice(0, nmIdx));
348
+ execFileSync(npmCmd.file, ["install", "--prefix", installRoot, "omp-config-crypt@latest"], { stdio: "pipe", shell: npmCmd.shell });
349
+ return { local: pkg.version, latest, action: "upgraded" };
350
+ }
351
+ execFileSync(npmCmd.file, ["install", "-g", "omp-config-crypt@latest"], { stdio: "pipe", shell: npmCmd.shell });
352
+ return { local: pkg.version, latest, action: "upgraded" };
353
+ } catch {
354
+ return { local: pkg.version, latest, action: "manual", reason: "automatic install failed; run: npx -y omp-config-crypt@latest <command>" };
355
+ }
356
+ }
package/src/rehydrator.js CHANGED
@@ -6,6 +6,16 @@ import { ompHome } from "./sync-files.js";
6
6
 
7
7
  const LINKS_FILE = ".plugin-links.json";
8
8
 
9
+ /**
10
+ * npm on Windows is npm.cmd; spawning .cmd files requires shell:true (Node CVE-2024-27980).
11
+ * Args are validated snapshot-derived constants, so no shell metacharacters can appear.
12
+ */
13
+ export function resolveNpmCommand() {
14
+ return process.platform === "win32"
15
+ ? { file: "npm.cmd", shell: true }
16
+ : { file: "npm", shell: false };
17
+ }
18
+
9
19
  /**
10
20
  * Scan plugins directory node_modules for symlinks and return a map of name -> targetPath.
11
21
  */
@@ -145,10 +155,12 @@ export function rehydratePlugins(root, options = {}) {
145
155
  results.npmInstalled.push(...missing.npmDependencies);
146
156
  } else {
147
157
  try {
148
- execFileSync("npm", ["install", "--omit=dev", "--no-audit", "--no-fund"], {
158
+ const npmCmd = resolveNpmCommand();
159
+ execFileSync(npmCmd.file, ["install", "--omit=dev", "--no-audit", "--no-fund"], {
149
160
  cwd: pluginsDir,
150
161
  stdio: "pipe",
151
162
  timeout: 60000,
163
+ shell: npmCmd.shell,
152
164
  });
153
165
  results.npmInstalled.push(...missing.npmDependencies);
154
166
  } catch (err) {
@@ -165,11 +177,18 @@ export function rehydratePlugins(root, options = {}) {
165
177
  } catch {}
166
178
  }
167
179
 
168
- // Known candidate fallback directories for common local plugins
180
+ // Known candidate fallback directories for common local plugins.
181
+ // Extra dev roots come from OMP_PLUGIN_DEV_DIRS (path.delimiter-separated); no host-specific paths.
182
+ const devRoots = (process.env.OMP_PLUGIN_DEV_DIRS || "")
183
+ .split(path.delimiter)
184
+ .filter(Boolean);
169
185
  const candidateDirs = {
170
- "@omp/plugin-rsi": ["/opt/project/omp-rsi", path.join(os.homedir(), "omp-rsi")],
171
- "omp-config-crypt": ["/root/omp-config-crypt", path.join(os.homedir(), "omp-config-crypt")],
186
+ "@omp/plugin-rsi": [path.join(os.homedir(), "omp-rsi")],
187
+ "omp-config-crypt": [path.join(os.homedir(), "omp-config-crypt")],
172
188
  };
189
+ for (const [name, dirs] of Object.entries(candidateDirs)) {
190
+ for (const root of devRoots) dirs.push(path.join(root, name));
191
+ }
173
192
 
174
193
  // 3. Resolve and repair linked plugins
175
194
  const pluginsToLink = Array.from(
@@ -197,10 +216,12 @@ export function rehydratePlugins(root, options = {}) {
197
216
  if (!targetDir || !fs.existsSync(targetDir)) {
198
217
  if (!dryRun) {
199
218
  try {
200
- execFileSync("npm", ["install", `${name}@latest`, "--omit=dev", "--no-audit", "--no-fund"], {
219
+ const npmCmd = resolveNpmCommand();
220
+ execFileSync(npmCmd.file, ["install", `${name}@latest`, "--omit=dev", "--no-audit", "--no-fund"], {
201
221
  cwd: pluginsDir,
202
222
  stdio: "pipe",
203
223
  timeout: 60000,
224
+ shell: npmCmd.shell,
204
225
  });
205
226
  results.npmInstalled.push(name);
206
227
  continue;
package/src/sync-files.js CHANGED
@@ -510,6 +510,32 @@ export function isPidAlive(pid) {
510
510
  }
511
511
  }
512
512
 
513
+ const TERMINAL_JOURNAL_STATUSES = new Set(["completed", "rolled_back"]);
514
+
515
+ /**
516
+ * True when any .import-backup-* dir holds a journal that is missing, unreadable,
517
+ * or non-terminal — i.e. a crashed transaction that still needs rollback, not lock removal.
518
+ */
519
+ function hasUnfinishedJournal(agentDir) {
520
+ let entries;
521
+ try {
522
+ entries = fs.readdirSync(agentDir, { withFileTypes: true });
523
+ } catch {
524
+ return false;
525
+ }
526
+ for (const entry of entries) {
527
+ if (!entry.isDirectory() || !entry.name.startsWith(".import-backup-")) continue;
528
+ let journal;
529
+ try {
530
+ journal = JSON.parse(fs.readFileSync(path.join(agentDir, entry.name, "journal.json"), "utf8"));
531
+ } catch {
532
+ return true;
533
+ }
534
+ if (!TERMINAL_JOURNAL_STATUSES.has(journal.status)) return true;
535
+ }
536
+ return false;
537
+ }
538
+
513
539
  export function withSyncLock(root, operation, options = {}) {
514
540
  const agentDir = path.resolve(root);
515
541
  if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true });
@@ -529,9 +555,28 @@ export function withSyncLock(root, operation, options = {}) {
529
555
  `Sync lock could not be created at ${lockPath}: permission denied (${error.code}). Check directory ACL/permissions; manual recovery may be required.`
530
556
  );
531
557
  }
532
- throw new Error(
533
- `Sync lock active at ${lockPath}. Another sync may be running, or a previous sync failed. Run rollback or remove lock if stale.`
534
- );
558
+ // EEXIST (usual case): recover from a stale lock left behind by an exited process,
559
+ // but only when no unfinished transaction journal exists (crash recovery stays manual).
560
+ let stale = false;
561
+ try {
562
+ const record = JSON.parse(fs.readFileSync(lockPath, "utf8"));
563
+ if (record && record.pid != null && !isPidAlive(record.pid) && !hasUnfinishedJournal(agentDir)) {
564
+ stale = true;
565
+ }
566
+ } catch {}
567
+ if (!stale) {
568
+ throw new Error(
569
+ `Sync lock active at ${lockPath}. Another sync may be running, or a previous sync failed. Run rollback or remove lock if stale.`
570
+ );
571
+ }
572
+ try {
573
+ fs.unlinkSync(lockPath);
574
+ fd = fs.openSync(lockPath, "wx");
575
+ } catch {
576
+ throw new Error(
577
+ `Sync lock active at ${lockPath}. Another sync may be running, or a previous sync failed. Run rollback or remove lock if stale.`
578
+ );
579
+ }
535
580
  }
536
581
 
537
582
  const content = {
package/src/sync-plan.js CHANGED
@@ -14,12 +14,14 @@ import {
14
14
  validateAssetFiles,
15
15
  } from "./sync-files.js";
16
16
  import {
17
+ POLICY_FILE,
17
18
  checkSettingOverlap,
18
19
  isExactSemver,
19
20
  readSyncPolicy,
20
21
  resolveResourceScope,
21
22
  resolveSyncNamespace,
22
23
  validateResourceId,
24
+ writeSyncPolicyAtomic,
23
25
  } from "./sync-policy.js";
24
26
  import {
25
27
  canonicalResourceValue,
@@ -192,6 +194,81 @@ export function writeSyncState(root = configRoot(), state) {
192
194
  }
193
195
  }
194
196
 
197
+ function backupSyncFile(root, fileName) {
198
+ const target = path.join(root, fileName);
199
+ if (!fs.existsSync(target)) return null;
200
+ const backup = `${target}.bak`;
201
+ fs.copyFileSync(target, backup);
202
+ return backup;
203
+ }
204
+
205
+ /**
206
+ * Adopts a remote namespace for explicit force pulls: aligns sync-policy.local.json and
207
+ * sync-state.local.json to the remote configuration set. Both existing files are backed
208
+ * up to <file>.bak before the rewrite. Local resources/scope entries are preserved; only
209
+ * the namespace pointer moves, so a subsequent pull applies the remote set as its own.
210
+ */
211
+ export function adoptSyncNamespace(remoteNamespace, root = configRoot()) {
212
+ const ns = String(remoteNamespace ?? "").trim();
213
+ if (!ns) {
214
+ throw new Error("Cannot adopt namespace: remote namespace is empty");
215
+ }
216
+
217
+ const backups = [];
218
+ const policy = readSyncPolicy(root);
219
+ if (policy.namespace !== ns) {
220
+ const backup = backupSyncFile(root, POLICY_FILE);
221
+ if (backup) backups.push(backup);
222
+ policy.namespace = ns;
223
+ writeSyncPolicyAtomic(root, policy);
224
+ }
225
+
226
+ const statePath = path.join(root, STATE_FILE);
227
+ if (fs.existsSync(statePath)) {
228
+ const state = readSyncState(root);
229
+ if (state.namespace !== ns) {
230
+ backups.push(backupSyncFile(root, STATE_FILE));
231
+ state.namespace = ns;
232
+ writeSyncState(root, state);
233
+ }
234
+ }
235
+
236
+ return { namespace: ns, changed: backups.length > 0, backups: backups.filter(Boolean) };
237
+ }
238
+
239
+ const MINIMAL_STATE = () => ({ version: 1, resources: {}, tombstones: [] });
240
+
241
+ /**
242
+ * Repairs unreadable sync metadata: if sync-policy.local.json or sync-state.local.json
243
+ * exists but fails strict parsing, it is backed up to <file>.corrupt-<ts> (compatible
244
+ * with maintenance cleanCorruptFiles retention) and rebuilt in a valid empty state so
245
+ * pull/push can proceed instead of failing. Only genuinely unreadable files are touched.
246
+ */
247
+ export function healSyncMetadata(root = configRoot()) {
248
+ const healed = [];
249
+ const policyPath = path.join(root, POLICY_FILE);
250
+ if (fs.existsSync(policyPath)) {
251
+ try {
252
+ readSyncPolicy(root);
253
+ } catch {
254
+ fs.copyFileSync(policyPath, `${policyPath}.corrupt-${Date.now()}`);
255
+ writeSyncPolicyAtomic(root, { version: 1, resources: {} });
256
+ healed.push("policy:rebuilt-from-corrupt");
257
+ }
258
+ }
259
+ const statePath = path.join(root, STATE_FILE);
260
+ if (fs.existsSync(statePath)) {
261
+ try {
262
+ readSyncState(root);
263
+ } catch {
264
+ fs.copyFileSync(statePath, `${statePath}.corrupt-${Date.now()}`);
265
+ writeSyncState(root, MINIMAL_STATE());
266
+ healed.push("state:rebuilt-from-corrupt");
267
+ }
268
+ }
269
+ return { healed, backups: healed.length > 0 };
270
+ }
271
+
195
272
  /**
196
273
  * Validates remote snapshot structure before planning.
197
274
  */
@@ -738,11 +815,12 @@ export function planSync(snapshot, root = configRoot()) {
738
815
  try {
739
816
  localNamespace = resolveSyncNamespace(policy, state);
740
817
  } catch (error) {
741
- blocked.push({ reason: error.message });
818
+ blocked.push({ id: "namespace", reason: error.message });
742
819
  return { namespace: validSnapshot.namespace, actions: [], conflicts: [], blocked, prerequisites: [], writes: {} };
743
820
  }
744
821
  if (localNamespace && localNamespace !== validSnapshot.namespace) {
745
822
  blocked.push({
823
+ id: "namespace",
746
824
  reason: `Namespace mismatch: remote is '${validSnapshot.namespace}', local is '${localNamespace}'. Cannot take over different configuration set.`,
747
825
  });
748
826
  return { namespace: validSnapshot.namespace, actions: [], conflicts: [], blocked, prerequisites: [], writes: {} };
@@ -214,7 +214,7 @@ export function readSyncPolicy(root) {
214
214
  /**
215
215
  * Writes sync-policy.local.json atomically using temp file + rename.
216
216
  */
217
- function writeSyncPolicyAtomic(root, policy) {
217
+ export function writeSyncPolicyAtomic(root, policy) {
218
218
  if (!fs.existsSync(root)) {
219
219
  fs.mkdirSync(root, { recursive: true });
220
220
  }
@@ -25,7 +25,7 @@ function fileSha256(bufOrStr) {
25
25
  }
26
26
 
27
27
  function ensureDir(abs) {
28
- if (!fs.existsSync(abs)) fs.mkdirSync(abs, { recursive: true });
28
+ if (!fs.existsSync(abs)) fs.mkdirSync(abs, { recursive: true, mode: 0o700 });
29
29
  }
30
30
 
31
31
  function fsyncPath(abs) {
@@ -222,7 +222,7 @@ function ensureParents(abs, createdDirectories) {
222
222
  probe = path.dirname(probe);
223
223
  }
224
224
  for (const dir of stack.reverse()) {
225
- fs.mkdirSync(dir);
225
+ fs.mkdirSync(dir, { mode: 0o700 });
226
226
  createdDirectories.push(dir);
227
227
  }
228
228
  }
@@ -373,6 +373,10 @@ export function commitFileTransaction(root, transaction, lock) {
373
373
  journal.status = "completed";
374
374
  writeJournalAtomic(journalPath, journal);
375
375
 
376
+ try {
377
+ pruneBackups(agentDir);
378
+ } catch {}
379
+
376
380
  return {
377
381
  success: true,
378
382
  filesWritten: journal.entries.filter((entry) => entry.rel !== STATE_FILE).length,
@@ -446,6 +450,20 @@ function acquireRecoveryLock(root) {
446
450
  };
447
451
  }
448
452
 
453
+ /**
454
+ * Removes all but the newest `keep` .import-backup-* directories (name-sorted, oldest first).
455
+ */
456
+ export function pruneBackups(agentDir, keep = 3) {
457
+ const backups = fs
458
+ .readdirSync(agentDir, { withFileTypes: true })
459
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith(".import-backup-"))
460
+ .map((entry) => entry.name)
461
+ .sort();
462
+ for (const name of backups.slice(0, Math.max(0, backups.length - keep))) {
463
+ fs.rmSync(path.join(agentDir, name), { recursive: true, force: true });
464
+ }
465
+ }
466
+
449
467
  function loadLatestJournal(agentDir) {
450
468
  const backups = fs
451
469
  .readdirSync(agentDir, { withFileTypes: true })