omp-config-crypt 0.6.6 → 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 +16 -3
- package/bin/omp-sync.js +23 -3
- package/index.js +79 -12
- package/package.json +1 -1
- package/src/maintenance.js +60 -0
- package/src/sync-plan.js +77 -0
- package/src/sync-policy.js +1 -1
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# omp-config-crypt (v0.
|
|
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 (
|
|
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") {
|
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,
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
package/src/maintenance.js
CHANGED
|
@@ -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
|
*/
|
package/src/sync-policy.js
CHANGED
|
@@ -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
|
}
|