omp-config-crypt 0.6.6 → 0.8.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,26 @@ 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
+
59
+ # Conflict resolution: when local files differ from remote with no baseline
60
+ # (initial-conflict-both-exist-different), default behavior aborts. Auto-resolve:
61
+ # --strategy prefer-remote overwrite local with remote (typical fresh-machine pull)
62
+ # --strategy prefer-local keep local files and adopt them as the new baseline
63
+ npx omp-config-crypt pull gist:<id> --pass "mysecret" --token "$GITHUB_TOKEN" --strategy prefer-remote
64
+
51
65
  # Rollback to previous configuration snapshot
52
66
  npx omp-config-crypt rollback
67
+
68
+ # Self-update the package (plugins dir or global install); --check only reports
69
+ npx omp-config-crypt upgrade --check
70
+ npx omp-config-crypt upgrade
53
71
  ```
54
72
 
55
73
  # Provider Auto-Probing & Management (Public / Private)
@@ -77,9 +95,10 @@ Configuration exports include the installed `omp-config-crypt` source (excluding
77
95
  /config-push gist:new
78
96
  /config-push gist:<id>
79
97
  /config-push https://…
80
- /config-pull gist:<id> [--dry-run]
81
- /config-pull https://… [--dry-run]
98
+ /config-pull gist:<id> [--dry-run] [--force]
99
+ /config-pull https://… [--dry-run] [--force]
82
100
  /config-rollback
101
+ /config-upgrade [--check]
83
102
  ```
84
103
 
85
104
  ### 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,16 @@ 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)
61
+ (--strategy prefer-remote|prefer-local auto-resolves
62
+ conflicts by taking remote or local side; default:
63
+ report conflicts and abort)
58
64
  rollback Revert the most recent config restore from its backup
59
65
  rehydrate Rehydrate and repair locked/linked plugins in ~/.omp/plugins
60
66
  maint / gc [--force] Run automatic storage maintenance, WAL checkpoint & GC
61
67
  cron [install|status|rm] Manage OS-level scheduled crontab maintenance job
68
+ upgrade [--check] Update omp-config-crypt in place (plugins dir or global)
62
69
  provider add <name> Auto-probe and add an LLM provider (public or private)
63
70
  provider ls / list List configured providers, models and active role bindings
64
71
  provider rm <name> Remove a provider from public or private store
@@ -79,7 +86,8 @@ Options:
79
86
  --private Save as private (local-only, unsynced, non-overwritten) [default]
80
87
  --public Save as public (synced across machines via models.yml)
81
88
  -y, --yes Non-interactive mode (use defaults without prompting)
82
- -f, --force Force operations (e.g. bypass maintenance debounce)
89
+ -f, --force Force operations (pull: adopt differing remote namespace)
90
+ --strategy <mode> Conflict resolution for pull: prefer-remote | prefer-local
83
91
  --profile <name> Target specific profile scene (e.g. dev, ops)
84
92
 
85
93
  Environment Variables:
@@ -110,6 +118,8 @@ function parseCliArgs(argv) {
110
118
  isPrivate: null,
111
119
  nonInteractive: false,
112
120
  force: false,
121
+ strategy: null,
122
+ checkOnly: false,
113
123
  positional: [],
114
124
  profile: null,
115
125
  };
@@ -147,6 +157,12 @@ function parseCliArgs(argv) {
147
157
  options.nonInteractive = true;
148
158
  } else if (a === "-f" || a === "--force") {
149
159
  options.force = true;
160
+ } else if (a === "--strategy") {
161
+ options.strategy = args[++i];
162
+ } else if (a.startsWith("--strategy=")) {
163
+ options.strategy = a.slice(11);
164
+ } else if (a === "--check") {
165
+ options.checkOnly = true;
150
166
  } else if (a === "--profile") {
151
167
  options.profile = args[++i];
152
168
  } else if (a.startsWith("--profile=")) {
@@ -303,6 +319,7 @@ async function main() {
303
319
  const pass = await resolvePass(options.pass);
304
320
  const res = importEncrypted(options.target, pass, root, {
305
321
  dryRun: options.dryRun,
322
+ strategy: options.strategy,
306
323
  });
307
324
  if (res.adaptedFile) {
308
325
  console.log(`[import] incompatible v${res.legacy?.from}; adapted -> ${res.adaptedFile}`);
@@ -354,8 +371,14 @@ async function main() {
354
371
  const token = await resolveToken(options.token, target.kind === "gist");
355
372
  const res =
356
373
  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 });
374
+ ? await pullGist(target.id, pass, root, token, { dryRun: options.dryRun, force: options.force, strategy: options.strategy })
375
+ : await pullHttp(target.url, pass, root, token, { dryRun: options.dryRun, force: options.force, strategy: options.strategy });
376
+ if (res.adoptedNamespace) {
377
+ console.log(`[pull] Adopted remote namespace ${res.adoptedNamespace} (--force); prior policy/state saved as .bak`);
378
+ }
379
+ if (Array.isArray(res.healed) && res.healed.length > 0) {
380
+ console.log(`[pull] Self-healed: ${res.healed.join("; ")}`);
381
+ }
359
382
  if (res.adaptedFile) {
360
383
  console.log(`[pull] incompatible v${res.legacy?.from}; adapted -> ${res.adaptedFile}`);
361
384
  }
@@ -442,6 +465,13 @@ async function main() {
442
465
  }
443
466
  break;
444
467
  }
468
+ case "upgrade": {
469
+ const r = runUpgrade({ check: options.checkOnly });
470
+ console.log(`[upgrade] local ${r.local} / latest ${r.latest ?? "unavailable"}`);
471
+ console.log(`[upgrade] ${r.action}${r.reason ? `: ${r.reason}` : ""}`);
472
+ if (r.action === "manual") process.exitCode = 2;
473
+ break;
474
+ }
445
475
  case "cron": {
446
476
  const sub = (options.target || "status").toLowerCase();
447
477
  if (sub === "status") {
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,
@@ -360,7 +364,7 @@ export function restoreArchive(blob, pass, root = configRoot(), options = {}) {
360
364
  }
361
365
 
362
366
  const dryRun = Boolean(options.dryRun);
363
- const plan = planSync(effectivePayload, root);
367
+ const plan = planSync(effectivePayload, root, { strategy: options.strategy });
364
368
 
365
369
  if (dryRun) {
366
370
  return {
@@ -623,12 +627,49 @@ export async function pushGist(id, pass, root = configRoot(), token = envToken()
623
627
  return { id: data.id, url: data.html_url, files, bytes: blob.length };
624
628
  }
625
629
 
626
- 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);
627
668
  const payload = decryptArchiveBlob(blob, pass);
628
669
  const inspection = inspectArchivePayload(payload);
629
670
 
630
671
  if (inspection.compatible) {
631
- return restoreArchive(blob, pass, root, options);
672
+ return restoreWithForce(() => restoreArchive(blob, pass, root, options), payload, root, options, healing);
632
673
  }
633
674
 
634
675
  if (!inspection.adaptable) {
@@ -652,7 +693,7 @@ function restoreRemoteArchive(blob, pass, root = configRoot(), options = {}) {
652
693
 
653
694
  const adaptedFile = path.join(os.tmpdir(), `omp-archive-v3-${Date.now()}.enc`);
654
695
  fs.writeFileSync(adaptedFile, adaptedBlob, { mode: 0o600 });
655
- const res = restoreArchive(adaptedBlob, pass, root, options);
696
+ const res = restoreWithForce(() => restoreArchive(adaptedBlob, pass, root, options), adapted, root, options, healing);
656
697
  return {
657
698
  ...res,
658
699
  adaptedFile,
@@ -721,19 +762,24 @@ export function extractDryRun(str) {
721
762
  const tokens = [];
722
763
  const re = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|(\S+)/g;
723
764
  let match;
724
- while ((match = re.exec(raw))) {
725
- tokens.push(match[1] !== undefined ? match[1] : match[2] !== undefined ? match[2] : match[3]);
726
- }
727
765
  let dryRun = false;
766
+ let force = false;
728
767
  const kept = [];
729
- 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];
730
770
  if (token === "--dry-run" || token === "-d") {
731
771
  dryRun = true;
732
772
  continue;
733
773
  }
774
+ if (token === "--force" || token === "-f") {
775
+ force = true;
776
+ continue;
777
+ }
734
778
  kept.push(token);
735
779
  }
736
- return { dryRun, clean: kept.join(" ") };
780
+ const result = { dryRun, clean: kept.join(" ") };
781
+ if (force) result.force = true;
782
+ return result;
737
783
  }
738
784
 
739
785
  export function formatSyncReport(result = {}) {
@@ -1030,9 +1076,9 @@ export default function (pi) {
1030
1076
  const sel = await selectPublicResources(ctx, root);
1031
1077
  if (sel === null) return;
1032
1078
  }
1033
- const { dryRun, clean: spec } = extractDryRun(args || "");
1079
+ const { dryRun, force, clean: spec } = extractDryRun(args || "");
1034
1080
  if (!spec) {
1035
- 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");
1036
1082
  return;
1037
1083
  }
1038
1084
  try {
@@ -1040,8 +1086,14 @@ export default function (pi) {
1040
1086
  const pass = await askPass(ctx, "Pull passphrase");
1041
1087
  const token = await askToken(ctx, "Cloud token", target.kind === "gist");
1042
1088
  const r = target.kind === "gist"
1043
- ? await pullGist(target.id, pass, configRoot(), token, { dryRun })
1044
- : 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
+ }
1045
1097
  if (r.adaptedFile) {
1046
1098
  ctx.ui.notify(`[pull] incompatible v${r.legacy?.from}; adapted -> ${r.adaptedFile}`, "info");
1047
1099
  }
@@ -1069,6 +1121,21 @@ export default function (pi) {
1069
1121
  },
1070
1122
  });
1071
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
+
1072
1139
  pi.registerCommand("provider", {
1073
1140
  description: "Provider control menu · ls | add | edit <name> | test <name> | rm <name>",
1074
1141
  getArgumentCompletions: prefix => providerCompletions(prefix, configRoot()),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omp-config-crypt",
3
- "version": "0.6.6",
3
+ "version": "0.8.0",
4
4
  "description": "Universal cross-platform encrypted portability for omp config, extensions, and instructions",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,9 +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 { fileURLToPath } from "node:url";
4
5
  import { randomUUID } from "node:crypto";
5
6
  import { exec, execSync, execFileSync } from "node:child_process";
6
7
  import { promisify } from "node:util";
8
+ import { resolveNpmCommand } from "./rehydrator.js";
7
9
 
8
10
  const execAsync = promisify(exec);
9
11
 
@@ -294,3 +296,61 @@ export function removeCron() {
294
296
  return { success: false, error: err.message };
295
297
  }
296
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/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
  */
@@ -685,7 +762,13 @@ export function adaptLegacySnapshot(snapshot) {
685
762
  * Plans the 3-way synchronization between local environment, local baseline, and remote snapshot.
686
763
  * Returns { namespace, actions, conflicts, blocked, prerequisites, writes }
687
764
  */
688
- export function planSync(snapshot, root = configRoot()) {
765
+ export const SYNC_STRATEGIES = new Set(["manual", "prefer-remote", "prefer-local"]);
766
+
767
+ export function planSync(snapshot, root = configRoot(), options = {}) {
768
+ const strategy = options.strategy == null || options.strategy === undefined ? "manual" : options.strategy;
769
+ if (!SYNC_STRATEGIES.has(strategy)) {
770
+ throw new Error(`Invalid sync strategy '${strategy}'; expected one of: ${Array.from(SYNC_STRATEGIES).join(", ")}`);
771
+ }
689
772
  const validSnapshot = validateSnapshot(snapshot);
690
773
  const policy = readSyncPolicy(root);
691
774
  const state = readSyncState(root);
@@ -908,6 +991,28 @@ export function planSync(snapshot, root = configRoot()) {
908
991
  acceptedTransitions.set(id, { hash: SENTINEL_DELETED, tombstone: true });
909
992
  }
910
993
 
994
+ // Strategy-based resolution of otherwise-unresolvable conflicts.
995
+ if (plannedAction === "conflict" && strategy !== "manual") {
996
+ if (strategy === "prefer-remote") {
997
+ if (isRemoteResource) {
998
+ plannedAction = "update";
999
+ reason = "conflict-resolved-remote-preferred";
1000
+ effectiveValue = remoteVal;
1001
+ acceptedTransitions.set(id, { hash: remoteHash, tombstone: false });
1002
+ } else {
1003
+ plannedAction = "delete";
1004
+ reason = "conflict-resolved-remote-preferred";
1005
+ acceptedTransitions.set(id, { hash: SENTINEL_DELETED, tombstone: true });
1006
+ }
1007
+ } else {
1008
+ plannedAction = localPresent ? "keep" : "delete";
1009
+ reason = "conflict-resolved-local-preferred";
1010
+ acceptedTransitions.set(id, localPresent
1011
+ ? { hash: localHash, tombstone: false }
1012
+ : { hash: SENTINEL_DELETED, tombstone: true });
1013
+ }
1014
+ }
1015
+
911
1016
  // Check for plugin prerequisite if plannedAction is add or update
912
1017
  if ((plannedAction === "add" || plannedAction === "update") && id.startsWith("plugin:")) {
913
1018
  const pluginName = id.slice("plugin:".length);
@@ -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
  }