omp-config-crypt 0.6.3 → 0.6.5

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.
@@ -0,0 +1,1062 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import {
5
+ assertSafeTarget,
6
+ configRoot,
7
+ createReadContext,
8
+ ompHome,
9
+ parseJsonStrict,
10
+ parseYamlStrict,
11
+ renderResourceChanges,
12
+ resolveDestination,
13
+ STRICT_BASE64,
14
+ validateAssetFiles,
15
+ } from "./sync-files.js";
16
+ import {
17
+ checkSettingOverlap,
18
+ isExactSemver,
19
+ readSyncPolicy,
20
+ resolveResourceScope,
21
+ resolveSyncNamespace,
22
+ validateResourceId,
23
+ } from "./sync-policy.js";
24
+ import {
25
+ canonicalResourceValue,
26
+ inventoryResources,
27
+ readResource,
28
+ restoreResourceForImport,
29
+ tokensToPointer,
30
+ } from "./sync-resources.js";
31
+
32
+ export const STATE_FILE = "sync-state.local.json";
33
+ export const SENTINEL_DELETED = "__OMP_SENTINEL_DELETED__";
34
+ const planTransactions = new WeakMap();
35
+
36
+ export function getSyncPlanTransaction(plan, root = configRoot()) {
37
+ const transaction = planTransactions.get(plan);
38
+ if (!transaction || transaction.root !== path.resolve(root) || transaction.consumed) {
39
+ throw new Error("Invalid or already-consumed sync plan; rebuild the plan for this root");
40
+ }
41
+ try {
42
+ transaction.readContext?.verify?.();
43
+ } catch (error) {
44
+ if (/Concurrent modification detected/i.test(String(error?.message || error))) {
45
+ throw error;
46
+ }
47
+ throw new Error("Invalid or already-consumed sync plan; rebuild the plan for this root");
48
+ }
49
+ transaction.consumed = true;
50
+ return transaction;
51
+ }
52
+
53
+ /**
54
+ * Computes canonical SHA-256 hash of a JSON/object or asset array.
55
+ * Keys are recursively sorted, arrays preserved in order.
56
+ */
57
+ export function canonicalHash(val) {
58
+ if (val === undefined) {
59
+ return SENTINEL_DELETED;
60
+ }
61
+
62
+ function canonicalize(v) {
63
+ if (v === null || typeof v !== "object") {
64
+ return v;
65
+ }
66
+ if (Array.isArray(v)) {
67
+ return v.map(canonicalize);
68
+ }
69
+ const sorted = Object.create(null);
70
+ for (const key of Object.keys(v).sort()) {
71
+ Object.defineProperty(sorted, key, {
72
+ value: canonicalize(v[key]),
73
+ enumerable: true,
74
+ configurable: true,
75
+ writable: true,
76
+ });
77
+ }
78
+ return sorted;
79
+ }
80
+
81
+ const jsonStr = JSON.stringify(canonicalize(val));
82
+ return createHash("sha256").update(jsonStr, "utf8").digest("hex");
83
+ }
84
+
85
+ function deepFreeze(value) {
86
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
87
+ Object.freeze(value);
88
+ for (const child of Object.values(value)) deepFreeze(child);
89
+ }
90
+ return value;
91
+ }
92
+
93
+ function cloneOwn(value) {
94
+ if (Array.isArray(value)) return value.map(cloneOwn);
95
+ if (!value || typeof value !== "object") return value;
96
+ const copy = {};
97
+ for (const key of Object.keys(value)) {
98
+ Object.defineProperty(copy, key, {
99
+ value: cloneOwn(value[key]),
100
+ enumerable: true,
101
+ configurable: true,
102
+ writable: true,
103
+ });
104
+ }
105
+ return copy;
106
+ }
107
+
108
+ export function validateSyncState(parsed) {
109
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
110
+ throw new Error(`Invalid ${STATE_FILE}: root must be an object`);
111
+ }
112
+ if (parsed.version !== 1) {
113
+ throw new Error(`Invalid ${STATE_FILE}: unsupported version ${parsed.version}; expected 1`);
114
+ }
115
+ if (parsed.namespace !== undefined && (typeof parsed.namespace !== "string" || !parsed.namespace.trim())) {
116
+ throw new Error(`Invalid ${STATE_FILE}: namespace must be a non-empty string`);
117
+ }
118
+ if (!parsed.resources || typeof parsed.resources !== "object" || Array.isArray(parsed.resources)) {
119
+ throw new Error(`Invalid ${STATE_FILE}: resources must be an object`);
120
+ }
121
+ if (!Array.isArray(parsed.tombstones)) {
122
+ throw new Error(`Invalid ${STATE_FILE}: tombstones must be an array`);
123
+ }
124
+
125
+ const resources = {};
126
+ for (const id of Object.keys(parsed.resources)) {
127
+ validateResourceId(id);
128
+ const record = parsed.resources[id];
129
+ if (!record || typeof record !== "object" || Array.isArray(record)) {
130
+ throw new Error(`Invalid ${STATE_FILE}: record for '${id}' must be an object`);
131
+ }
132
+ if (typeof record.hash !== "string" ||
133
+ (record.hash !== SENTINEL_DELETED && !/^[a-f0-9]{64}$/i.test(record.hash))) {
134
+ throw new Error(`Invalid ${STATE_FILE}: record for '${id}' has an invalid hash`);
135
+ }
136
+ if (record.hashFormat !== undefined && record.hashFormat !== "portable-v1") {
137
+ throw new Error(`Invalid ${STATE_FILE}: record for '${id}' has an unsupported hash format`);
138
+ }
139
+ Object.defineProperty(resources, id, {
140
+ value: cloneOwn(record),
141
+ enumerable: true,
142
+ configurable: true,
143
+ writable: true,
144
+ });
145
+ }
146
+
147
+ const tombstones = [];
148
+ const seen = new Set();
149
+ for (const id of parsed.tombstones) {
150
+ validateResourceId(id);
151
+ if (seen.has(id)) throw new Error(`Invalid ${STATE_FILE}: duplicate tombstone '${id}'`);
152
+ seen.add(id);
153
+ if (resources[id] && resources[id].hash !== SENTINEL_DELETED) {
154
+ throw new Error(`Invalid ${STATE_FILE}: '${id}' is both active and tombstoned`);
155
+ }
156
+ tombstones.push(id);
157
+ }
158
+
159
+ return {
160
+ ...cloneOwn(parsed),
161
+ version: 1,
162
+ namespace: parsed.namespace?.trim(),
163
+ resources,
164
+ tombstones,
165
+ };
166
+ }
167
+
168
+ export function readSyncState(root = configRoot()) {
169
+ const filePath = path.join(root, STATE_FILE);
170
+ if (!fs.existsSync(filePath)) {
171
+ return { version: 1, resources: {}, tombstones: [] };
172
+ }
173
+ const parsed = parseJsonStrict(fs.readFileSync(filePath, "utf8"), STATE_FILE);
174
+ return validateSyncState(parsed);
175
+ }
176
+
177
+ /**
178
+ * Writes sync-state.local.json atomically.
179
+ */
180
+ export function writeSyncState(root = configRoot(), state) {
181
+ const validState = validateSyncState(state);
182
+ if (!fs.existsSync(root)) fs.mkdirSync(root, { recursive: true });
183
+ const target = path.join(root, STATE_FILE);
184
+ const tmp = path.join(root, `.${STATE_FILE}.tmp-${randomUUID()}`);
185
+ const data = JSON.stringify(validState, null, 2) + "\n";
186
+ try {
187
+ fs.writeFileSync(tmp, data, "utf8");
188
+ fs.renameSync(tmp, target);
189
+ } catch (err) {
190
+ try { fs.unlinkSync(tmp); } catch {}
191
+ throw err;
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Validates remote snapshot structure before planning.
197
+ */
198
+ export function validateSnapshot(snapshot) {
199
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) {
200
+ throw new Error("Invalid archive snapshot: payload is not an object");
201
+ }
202
+ if (snapshot.v === 1 || snapshot.v === 2) {
203
+ throw new Error("legacy archive: re-export as v3");
204
+ }
205
+ if (snapshot.v !== 3) {
206
+ throw new Error(`unsupported archive payload: version ${snapshot.v}; expected v3`);
207
+ }
208
+ if (typeof snapshot.namespace !== "string" || !snapshot.namespace.trim()) {
209
+ throw new Error("Invalid archive snapshot: namespace must be a non-empty string");
210
+ }
211
+ if (typeof snapshot.createdAt !== "string" || !Number.isFinite(Date.parse(snapshot.createdAt))) {
212
+ throw new Error("Invalid archive snapshot: createdAt must be a parseable timestamp");
213
+ }
214
+ if (!Array.isArray(snapshot.resources) || !Array.isArray(snapshot.tombstones)) {
215
+ throw new Error("Invalid archive snapshot: resources and tombstones must be arrays");
216
+ }
217
+
218
+ const seenIds = new Set();
219
+ const settingIds = [];
220
+ const assetRoots = [];
221
+ for (const resource of snapshot.resources) {
222
+ if (!resource || typeof resource !== "object" || Array.isArray(resource) ||
223
+ typeof resource.id !== "string" || !Object.hasOwn(resource, "value")) {
224
+ throw new Error("Invalid archive snapshot: every resource requires an id and own value");
225
+ }
226
+ const { prefix, name } = validateResourceId(resource.id);
227
+ if (seenIds.has(resource.id)) {
228
+ throw new Error(`Duplicate resource ID in snapshot: '${resource.id}'`);
229
+ }
230
+ seenIds.add(resource.id);
231
+ const value = resource.value;
232
+ if (prefix === "provider" || prefix === "mcp") {
233
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
234
+ throw new Error(`Invalid '${resource.id}': value must be a JSON object`);
235
+ }
236
+ } else if (prefix === "setting") {
237
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
238
+ throw new Error(`Invalid '${resource.id}': settings must be null, scalar, or an array`);
239
+ }
240
+ if (typeof value === "number" && !Number.isFinite(value)) {
241
+ throw new Error(`Invalid '${resource.id}': setting number must be finite`);
242
+ }
243
+ settingIds.push(resource.id);
244
+ } else if (prefix === "plugin") {
245
+ if (!value || typeof value !== "object" || Array.isArray(value) ||
246
+ Object.keys(value).sort().join(",") !== "enabled,name,version") {
247
+ throw new Error(`Invalid '${resource.id}': plugin requires exactly name, version, and enabled`);
248
+ }
249
+ if (value.name !== name || !isExactSemver(value.version) || typeof value.enabled !== "boolean") {
250
+ throw new Error(`Invalid '${resource.id}': plugin name, exact SemVer, or enabled flag is invalid`);
251
+ }
252
+ } else if (prefix === "asset") {
253
+ validateAssetFiles(name, value);
254
+ assetRoots.push(name);
255
+ }
256
+ }
257
+ checkSettingOverlap(settingIds);
258
+
259
+ const seenTombstones = new Set();
260
+ for (const tombstone of snapshot.tombstones) {
261
+ validateResourceId(tombstone);
262
+ if (seenTombstones.has(tombstone)) {
263
+ throw new Error(`Duplicate tombstone in snapshot: '${tombstone}'`);
264
+ }
265
+ if (seenIds.has(tombstone)) {
266
+ throw new Error(`Resource ID '${tombstone}' appears in both resources and tombstones`);
267
+ }
268
+ seenTombstones.add(tombstone);
269
+ }
270
+ for (let i = 0; i < assetRoots.length; i++) {
271
+ for (let j = i + 1; j < assetRoots.length; j++) {
272
+ if (assetRoots[i].startsWith(assetRoots[j] + "/") || assetRoots[j].startsWith(assetRoots[i] + "/")) {
273
+ throw new Error("Invalid archive snapshot: asset resource roots overlap");
274
+ }
275
+ }
276
+ }
277
+ return {
278
+ namespace: snapshot.namespace.trim(),
279
+ resources: snapshot.resources,
280
+ tombstones: snapshot.tombstones,
281
+ };
282
+ }
283
+
284
+ /**
285
+ * Inspects archive payload for version compatibility and adaptability.
286
+ */
287
+ export function inspectArchivePayload(snapshot) {
288
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) {
289
+ return {
290
+ compatible: false,
291
+ version: null,
292
+ adaptable: false,
293
+ reason: "Invalid archive snapshot: payload is not an object",
294
+ };
295
+ }
296
+ if (snapshot.v === 3) {
297
+ try {
298
+ validateSnapshot(snapshot);
299
+ return { compatible: true, version: 3 };
300
+ } catch (err) {
301
+ return {
302
+ compatible: false,
303
+ version: 3,
304
+ adaptable: false,
305
+ reason: err.message,
306
+ };
307
+ }
308
+ }
309
+ if (snapshot.v === 1 && Array.isArray(snapshot.files)) {
310
+ return { compatible: false, version: 1, adaptable: true };
311
+ }
312
+ if (
313
+ snapshot.v === 2 &&
314
+ (Array.isArray(snapshot.resources) || Array.isArray(snapshot.files))
315
+ ) {
316
+ return { compatible: false, version: 2, adaptable: true };
317
+ }
318
+ return {
319
+ compatible: false,
320
+ version: typeof snapshot.v === "number" ? snapshot.v : null,
321
+ adaptable: false,
322
+ reason: `unsupported archive payload: version ${snapshot.v}; expected v3`,
323
+ };
324
+ }
325
+
326
+ /**
327
+ * Adapts a legacy v1 or v2 snapshot into a valid v3 snapshot.
328
+ */
329
+ export function adaptLegacySnapshot(snapshot) {
330
+ const inspection = inspectArchivePayload(snapshot);
331
+ if (!inspection.adaptable) {
332
+ throw new Error(inspection.reason || "unsupported archive payload");
333
+ }
334
+
335
+ if (snapshot.v === 2 && Array.isArray(snapshot.resources)) {
336
+ if (snapshot.resources.length === 0) {
337
+ throw new Error("legacy archive could not be adapted: empty snapshot");
338
+ }
339
+ const namespace =
340
+ typeof snapshot.namespace === "string" && snapshot.namespace.trim()
341
+ ? snapshot.namespace.trim()
342
+ : "00000000-0000-4000-8000-0000000000v2";
343
+ const createdAt =
344
+ typeof snapshot.createdAt === "string" &&
345
+ Number.isFinite(Date.parse(snapshot.createdAt))
346
+ ? snapshot.createdAt
347
+ : new Date().toISOString();
348
+ const tombstones = Array.isArray(snapshot.tombstones)
349
+ ? snapshot.tombstones
350
+ : [];
351
+
352
+ const adapted = {
353
+ v: 3,
354
+ namespace,
355
+ createdAt,
356
+ resources: snapshot.resources,
357
+ tombstones,
358
+ legacy: { from: 2, unmapped: [] },
359
+ };
360
+
361
+ try {
362
+ validateSnapshot(adapted);
363
+ } catch (err) {
364
+ const match = err.message.match(/['"]([^'"]+)['"]/);
365
+ const reason = match ? match[1] : err.message;
366
+ throw new Error(`legacy archive could not be adapted: ${reason}`);
367
+ }
368
+
369
+ return adapted;
370
+ }
371
+
372
+ // snapshot with files (v1 or v2 files)
373
+ if (!Array.isArray(snapshot.files) || snapshot.files.length === 0) {
374
+ throw new Error("legacy archive could not be adapted: empty snapshot");
375
+ }
376
+
377
+ const defaultNs = snapshot.v === 2
378
+ ? "00000000-0000-4000-8000-0000000000v2"
379
+ : "00000000-0000-4000-8000-0000000000v1";
380
+ const namespace =
381
+ typeof snapshot.namespace === "string" && snapshot.namespace.trim()
382
+ ? snapshot.namespace.trim()
383
+ : defaultNs;
384
+ const fromVersion = snapshot.v === 2 ? 2 : 1;
385
+
386
+ const createdAt =
387
+ typeof snapshot.createdAt === "string" &&
388
+ Number.isFinite(Date.parse(snapshot.createdAt))
389
+ ? snapshot.createdAt
390
+ : new Date().toISOString();
391
+
392
+ const ymlProviders = new Map();
393
+ const localProviders = new Map();
394
+ const mcpServers = new Map();
395
+ const settings = new Map();
396
+ const assetFiles = new Map();
397
+ const unmapped = [];
398
+ let pkgFile = null;
399
+ let lockFile = null;
400
+
401
+ for (const file of snapshot.files) {
402
+ if (
403
+ !file ||
404
+ typeof file !== "object" ||
405
+ typeof file.path !== "string" ||
406
+ !file.path.trim()
407
+ ) {
408
+ throw new Error(`legacy archive could not be adapted: ${file?.path || "invalid"}`);
409
+ }
410
+ if (typeof file.data !== "string" || !STRICT_BASE64.test(file.data)) {
411
+ throw new Error(`legacy archive could not be adapted: ${file.path}`);
412
+ }
413
+ const buf = Buffer.from(file.data, "base64");
414
+ if (buf.toString("base64") !== file.data) {
415
+ throw new Error(`legacy archive could not be adapted: ${file.path}`);
416
+ }
417
+
418
+ const norm = file.path.replace(/\\/g, "/");
419
+ if (
420
+ norm.startsWith("/") ||
421
+ path.posix.isAbsolute(norm) ||
422
+ path.win32.isAbsolute(norm) ||
423
+ /^[a-zA-Z]:/.test(norm)
424
+ ) {
425
+ throw new Error(`legacy archive could not be adapted: ${file.path}`);
426
+ }
427
+ const parts = norm.split("/");
428
+ if (parts.some((p) => !p || p === "." || p === "..")) {
429
+ throw new Error(`legacy archive could not be adapted: ${file.path}`);
430
+ }
431
+
432
+ // Skip without error
433
+ if (norm.endsWith(".db") || norm.endsWith(".db-wal") || norm.endsWith(".db-shm")) {
434
+ continue;
435
+ }
436
+ if (/(?:^|\/)cache\//.test(norm) || /(?:^|\/)session\//.test(norm)) {
437
+ continue;
438
+ }
439
+
440
+ // models.local.json
441
+ if (norm === "models.local.json" || norm === "agent/models.local.json") {
442
+ try {
443
+ const parsed = JSON.parse(buf.toString("utf8"));
444
+ if (parsed?.providers && typeof parsed.providers === "object" && !Array.isArray(parsed.providers)) {
445
+ for (const [pName, pVal] of Object.entries(parsed.providers)) {
446
+ localProviders.set(pName, { value: pVal, file: file.path });
447
+ }
448
+ }
449
+ } catch {
450
+ // skip without error
451
+ }
452
+ continue;
453
+ }
454
+
455
+ // models.yml / models.yaml
456
+ if (
457
+ norm === "models.yml" ||
458
+ norm === "models.yaml" ||
459
+ norm === "agent/models.yml" ||
460
+ norm === "agent/models.yaml"
461
+ ) {
462
+ let doc;
463
+ try {
464
+ doc = parseYamlStrict(buf.toString("utf8"), norm);
465
+ } catch {
466
+ throw new Error(`legacy archive could not be adapted: ${file.path}`);
467
+ }
468
+ const provs = doc.get("providers");
469
+ let yamlMap = {};
470
+ if (provs && typeof provs.toJSON === "function") {
471
+ yamlMap = provs.toJSON() || {};
472
+ } else if (provs && typeof provs === "object") {
473
+ yamlMap = provs;
474
+ } else {
475
+ const top = typeof doc.toJSON === "function" ? doc.toJSON() : null;
476
+ if (top && typeof top === "object" && !Array.isArray(top)) {
477
+ yamlMap = top;
478
+ }
479
+ }
480
+ for (const [pName, pVal] of Object.entries(yamlMap)) {
481
+ if (!ymlProviders.has(pName)) {
482
+ ymlProviders.set(pName, { value: pVal, file: file.path });
483
+ }
484
+ }
485
+ continue;
486
+ }
487
+
488
+ // mcp.json
489
+ if (norm === "mcp.json" || norm === "agent/mcp.json") {
490
+ let data;
491
+ try {
492
+ data = JSON.parse(buf.toString("utf8"));
493
+ } catch {
494
+ throw new Error(`legacy archive could not be adapted: ${file.path}`);
495
+ }
496
+ if (data?.mcpServers && typeof data.mcpServers === "object" && !Array.isArray(data.mcpServers)) {
497
+ for (const [sName, sCfg] of Object.entries(data.mcpServers)) {
498
+ mcpServers.set(sName, { value: sCfg, file: file.path });
499
+ }
500
+ }
501
+ continue;
502
+ }
503
+
504
+ // config.yml / config.yaml
505
+ if (
506
+ norm === "config.yml" ||
507
+ norm === "config.yaml" ||
508
+ norm === "agent/config.yml" ||
509
+ norm === "agent/config.yaml"
510
+ ) {
511
+ let doc;
512
+ try {
513
+ doc = parseYamlStrict(buf.toString("utf8"), norm);
514
+ } catch {
515
+ throw new Error(`legacy archive could not be adapted: ${file.path}`);
516
+ }
517
+ const json = typeof doc.toJSON === "function" ? doc.toJSON() : {};
518
+ function collectLeaves(obj, tokens = []) {
519
+ if (obj === null || typeof obj !== "object" || Array.isArray(obj)) {
520
+ const ptr = tokensToPointer(tokens);
521
+ settings.set(ptr, { value: obj, file: file.path });
522
+ return;
523
+ }
524
+ for (const [k, v] of Object.entries(obj)) {
525
+ collectLeaves(v, [...tokens, k]);
526
+ }
527
+ }
528
+ collectLeaves(json);
529
+ continue;
530
+ }
531
+
532
+ // plugins/package.json
533
+ if (norm === "plugins/package.json") {
534
+ pkgFile = file;
535
+ continue;
536
+ }
537
+ if (norm === "plugins/omp-plugins.lock.json" || norm === "plugins/lock.json") {
538
+ lockFile = file;
539
+ continue;
540
+ }
541
+
542
+ // Top level instruction files
543
+ const topDocMatch = norm.match(/^(?:agent\/)?(AGENTS\.md|STYLE\.md|RULES\.md)$/);
544
+ if (topDocMatch) {
545
+ const docName = topDocMatch[1];
546
+ assetFiles.set(docName, [{ path: docName, data: file.data, mode: 0o644 }]);
547
+ continue;
548
+ }
549
+
550
+ // Asset directories: agent/skills, agent/managed-skills, agent/extensions, tools, hooks
551
+ const stripped = norm.startsWith("agent/") ? norm.slice(6) : norm;
552
+ const assetDirMatch = stripped.match(
553
+ /^(skills|managed-skills|extensions|tools|hooks)\/([^/]+)(?:\/(.*))?$/
554
+ );
555
+ if (assetDirMatch) {
556
+ const category = assetDirMatch[1];
557
+ const entryName = assetDirMatch[2];
558
+ const rootName = `${category}/${entryName}`;
559
+ if (!assetFiles.has(rootName)) {
560
+ assetFiles.set(rootName, []);
561
+ }
562
+ assetFiles.get(rootName).push({
563
+ path: stripped,
564
+ data: file.data,
565
+ mode: 0o644,
566
+ });
567
+ continue;
568
+ }
569
+
570
+ // Unmapped
571
+ unmapped.push(file.path);
572
+ }
573
+
574
+ const resources = [];
575
+
576
+ // 1. Providers: yml wins over local
577
+ const allProviders = new Set([...ymlProviders.keys(), ...localProviders.keys()]);
578
+ for (const pName of Array.from(allProviders).sort()) {
579
+ const entry = ymlProviders.has(pName) ? ymlProviders.get(pName) : localProviders.get(pName);
580
+ if (!entry.value || typeof entry.value !== "object" || Array.isArray(entry.value)) {
581
+ throw new Error(`legacy archive could not be adapted: provider:${pName}`);
582
+ }
583
+ resources.push({
584
+ id: `provider:${pName}`,
585
+ value: entry.value,
586
+ });
587
+ }
588
+
589
+ // 2. MCP
590
+ for (const [sName, entry] of mcpServers.entries()) {
591
+ if (!entry.value || typeof entry.value !== "object" || Array.isArray(entry.value)) {
592
+ throw new Error(`legacy archive could not be adapted: mcp:${sName}`);
593
+ }
594
+ resources.push({
595
+ id: `mcp:${sName}`,
596
+ value: entry.value,
597
+ });
598
+ }
599
+
600
+ // 3. Settings
601
+ for (const [ptr, entry] of settings.entries()) {
602
+ resources.push({
603
+ id: `setting:${ptr}`,
604
+ value: entry.value,
605
+ });
606
+ }
607
+
608
+ // 4. Plugins
609
+ if (pkgFile) {
610
+ let pkgJson;
611
+ try {
612
+ pkgJson = JSON.parse(Buffer.from(pkgFile.data, "base64").toString("utf8"));
613
+ } catch {
614
+ throw new Error(`legacy archive could not be adapted: ${pkgFile.path}`);
615
+ }
616
+ let lockJson = {};
617
+ if (lockFile) {
618
+ try {
619
+ lockJson = JSON.parse(Buffer.from(lockFile.data, "base64").toString("utf8"));
620
+ } catch {}
621
+ }
622
+ const deps =
623
+ pkgJson?.dependencies && typeof pkgJson.dependencies === "object"
624
+ ? pkgJson.dependencies
625
+ : {};
626
+ for (const [pkgName, versionSpec] of Object.entries(deps)) {
627
+ const lockEntry = lockJson?.plugins?.[pkgName];
628
+ let resolvedVersion = null;
629
+ if (isExactSemver(lockEntry?.version)) {
630
+ resolvedVersion = lockEntry.version;
631
+ } else if (isExactSemver(versionSpec)) {
632
+ resolvedVersion = versionSpec;
633
+ }
634
+ if (resolvedVersion) {
635
+ resources.push({
636
+ id: `plugin:${pkgName}`,
637
+ value: {
638
+ name: pkgName,
639
+ version: resolvedVersion,
640
+ enabled: lockEntry?.enabled !== false,
641
+ },
642
+ });
643
+ } else {
644
+ unmapped.push(pkgName);
645
+ }
646
+ }
647
+ }
648
+
649
+ // 5. Assets
650
+ for (const [rootName, files] of assetFiles.entries()) {
651
+ files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
652
+ resources.push({
653
+ id: `asset:${rootName}`,
654
+ value: files,
655
+ });
656
+ }
657
+
658
+ resources.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
659
+ unmapped.sort();
660
+
661
+ const adapted = {
662
+ v: 3,
663
+ namespace,
664
+ createdAt,
665
+ resources,
666
+ tombstones: [],
667
+ legacy: {
668
+ from: fromVersion,
669
+ unmapped,
670
+ },
671
+ };
672
+
673
+ try {
674
+ validateSnapshot(adapted);
675
+ } catch (err) {
676
+ const match = err.message.match(/['"]([^'"]+)['"]/);
677
+ const reason = match ? match[1] : err.message;
678
+ throw new Error(`legacy archive could not be adapted: ${reason}`);
679
+ }
680
+
681
+ return adapted;
682
+ }
683
+
684
+ /**
685
+ * Plans the 3-way synchronization between local environment, local baseline, and remote snapshot.
686
+ * Returns { namespace, actions, conflicts, blocked, prerequisites, writes }
687
+ */
688
+ export function planSync(snapshot, root = configRoot()) {
689
+ const validSnapshot = validateSnapshot(snapshot);
690
+ const policy = readSyncPolicy(root);
691
+ const state = readSyncState(root);
692
+ const readContext = createReadContext(root);
693
+ const inventory = inventoryResources(root);
694
+ // Observe configuration surfaces that can invalidate a rendered plan.
695
+ readContext.observe(path.join(root, STATE_FILE));
696
+ readContext.observe(path.join(root, "sync-policy.local.json"));
697
+ readContext.observe(path.join(root, "models.yml"));
698
+ readContext.observe(path.join(root, "models.yaml"));
699
+ readContext.observe(path.join(root, "models.local.json"));
700
+ readContext.observe(path.join(root, "mcp.json"));
701
+ readContext.observe(path.join(root, "config.yml"));
702
+ readContext.observe(path.join(root, "config.yaml"));
703
+ const pluginsRoot = path.join(ompHome(root), "plugins");
704
+ readContext.observe(path.join(pluginsRoot, "package.json"));
705
+ readContext.observe(path.join(pluginsRoot, "package-lock.json"));
706
+ for (const item of inventory) {
707
+ if (item.id.startsWith("plugin:")) {
708
+ const name = item.id.slice("plugin:".length);
709
+ readContext.observe(path.join(pluginsRoot, "node_modules", ...name.split("/"), "package.json"));
710
+ continue;
711
+ }
712
+ if (!item.id.startsWith("asset:")) continue;
713
+ const scope = resolveResourceScope(item.id, policy, state, item);
714
+ if (scope.scope === "private") continue;
715
+ const archiveRel = item.id.slice("asset:".length);
716
+ const destination = resolveDestination(archiveRel, root);
717
+ const observation = readContext.observe(destination);
718
+ if (observation.type !== "dir") continue;
719
+ const walk = (abs) => {
720
+ for (const entry of readContext.listDirectory(abs)) {
721
+ const childAbs = path.join(abs, entry.name);
722
+ if (entry.type === "dir") walk(childAbs);
723
+ else if (entry.type === "file") readContext.observe(childAbs);
724
+ else throw new Error(`Security violation: read path '${path.relative(root, childAbs).replace(/\\/g, "/")}' is a symlink or junction`);
725
+ }
726
+ };
727
+ walk(destination);
728
+ }
729
+
730
+
731
+
732
+ const conflicts = [];
733
+ const blocked = [];
734
+ const prerequisites = [];
735
+ const actions = [];
736
+
737
+ let localNamespace;
738
+ try {
739
+ localNamespace = resolveSyncNamespace(policy, state);
740
+ } catch (error) {
741
+ blocked.push({ reason: error.message });
742
+ return { namespace: validSnapshot.namespace, actions: [], conflicts: [], blocked, prerequisites: [], writes: {} };
743
+ }
744
+ if (localNamespace && localNamespace !== validSnapshot.namespace) {
745
+ blocked.push({
746
+ reason: `Namespace mismatch: remote is '${validSnapshot.namespace}', local is '${localNamespace}'. Cannot take over different configuration set.`,
747
+ });
748
+ return { namespace: validSnapshot.namespace, actions: [], conflicts: [], blocked, prerequisites: [], writes: {} };
749
+ }
750
+
751
+ // Build remote map
752
+ const remoteMap = new Map();
753
+ for (const r of validSnapshot.resources) {
754
+ remoteMap.set(r.id, { kind: "resource", value: r.value });
755
+ }
756
+ for (const t of validSnapshot.tombstones) {
757
+ remoteMap.set(t, { kind: "tombstone" });
758
+ }
759
+
760
+ // Build local inventory map
761
+ const inventoryMap = new Map();
762
+ for (const item of inventory) {
763
+ inventoryMap.set(item.id, item);
764
+ }
765
+
766
+ // Collect all unique IDs: local inventory + baseline state + remote resources/tombstones
767
+ const allIds = new Set([
768
+ ...Array.from(inventoryMap.keys()),
769
+ ...Object.keys(state.resources || {}),
770
+ ...Array.from(remoteMap.keys()),
771
+ ]);
772
+
773
+ const agentDir = root;
774
+ const ompDir = ompHome(root);
775
+ const pluginsDir = path.join(ompDir, "plugins");
776
+ const acceptedTransitions = new Map();
777
+
778
+ for (const id of Array.from(allIds).sort()) {
779
+ const invItem = inventoryMap.get(id);
780
+ const scopeInfo = resolveResourceScope(id, policy, state, invItem);
781
+ const remoteEntry = remoteMap.get(id);
782
+
783
+ let targetPath = id;
784
+ if (id.startsWith("provider:")) {
785
+ targetPath = fs.existsSync(path.join(agentDir, "models.yml")) ? "models.yml" : "models.yaml";
786
+ } else if (id.startsWith("mcp:")) {
787
+ targetPath = "mcp.json";
788
+ } else if (id.startsWith("setting:")) {
789
+ targetPath = fs.existsSync(path.join(agentDir, "config.yml")) ? "config.yml" : "config.yaml";
790
+ } else if (id.startsWith("plugin:")) {
791
+ targetPath = "plugins/package.json";
792
+ } else if (id.startsWith("asset:")) {
793
+ targetPath = id.slice("asset:".length);
794
+ }
795
+
796
+ if (scopeInfo.scope === "private") {
797
+ actions.push({ id, action: "keep", reason: "local-private-protected", targetPath, remapped: false });
798
+ continue;
799
+ }
800
+
801
+ let localPresent = false;
802
+ let rawLocalVal = null;
803
+ let localVal = null;
804
+ if (invItem) {
805
+ const readRes = readResource(root, id);
806
+ if (readRes) {
807
+ rawLocalVal = readRes.value;
808
+ localVal = canonicalResourceValue(id, rawLocalVal, root);
809
+ localPresent = true;
810
+ }
811
+ }
812
+ const localHash = localPresent ? canonicalHash(localVal) : SENTINEL_DELETED;
813
+
814
+ const isRemoteTombstone = remoteEntry?.kind === "tombstone";
815
+ const isRemoteResource = remoteEntry?.kind === "resource";
816
+ const remoteVal = isRemoteResource ? canonicalResourceValue(id, remoteEntry.value, root) : null;
817
+ const remoteHash = isRemoteResource ? canonicalHash(remoteVal) : (isRemoteTombstone ? SENTINEL_DELETED : null);
818
+
819
+ const baselineRecord = Object.hasOwn(state.resources || {}, id) ? state.resources[id] : null;
820
+ let baselineHash = baselineRecord?.hash !== undefined ? baselineRecord.hash : null;
821
+ let legacyBaselineUnverifiable = false;
822
+ if (baselineRecord && baselineRecord.hashFormat !== "portable-v1") {
823
+ const rawLocalHash = localPresent ? canonicalHash(rawLocalVal) : SENTINEL_DELETED;
824
+ if (baselineRecord.hash === rawLocalHash || baselineRecord.hash === localHash) {
825
+ baselineHash = localHash;
826
+ } else if (isRemoteResource && baselineRecord.hash === remoteHash) {
827
+ baselineHash = remoteHash;
828
+ } else if (baselineRecord.hash === SENTINEL_DELETED) {
829
+ baselineHash = SENTINEL_DELETED;
830
+ } else if (isRemoteTombstone || isRemoteResource) {
831
+ legacyBaselineUnverifiable = true;
832
+ }
833
+ }
834
+
835
+ let plannedAction = null;
836
+ let reason = null;
837
+ let effectiveValue = null;
838
+ let remapped = false;
839
+
840
+ if (baselineHash === null) {
841
+ if (isRemoteTombstone) {
842
+ plannedAction = "keep";
843
+ reason = "no-baseline-tombstone-ignored";
844
+ } else if (!localPresent) {
845
+ if (isRemoteResource) {
846
+ plannedAction = "add";
847
+ reason = "remote-new";
848
+ effectiveValue = remoteVal;
849
+ }
850
+ } else if (isRemoteResource) {
851
+ if (localHash === remoteHash) {
852
+ plannedAction = "keep";
853
+ reason = "initial-adopt-identical";
854
+ effectiveValue = localVal;
855
+ } else {
856
+ plannedAction = "conflict";
857
+ reason = "initial-conflict-both-exist-different";
858
+ }
859
+ } else {
860
+ plannedAction = "keep";
861
+ reason = "local-unmanaged";
862
+ }
863
+ } else if (isRemoteTombstone) {
864
+ if (!localPresent) {
865
+ plannedAction = "keep";
866
+ reason = "already-absent";
867
+ } else if (localHash === baselineHash) {
868
+ plannedAction = "delete";
869
+ reason = "remote-deleted";
870
+ } else {
871
+ plannedAction = "conflict";
872
+ reason = "conflict-local-modified-remote-deleted";
873
+ }
874
+ } else if (isRemoteResource) {
875
+ if (localHash === remoteHash) {
876
+ plannedAction = "keep";
877
+ reason = "identical-to-remote";
878
+ } else if (localHash === baselineHash) {
879
+ plannedAction = "update";
880
+ reason = "remote-updated";
881
+ effectiveValue = remoteVal;
882
+ } else if (remoteHash === baselineHash) {
883
+ plannedAction = "keep";
884
+ reason = "local-modified-remote-unchanged";
885
+ } else {
886
+ plannedAction = "conflict";
887
+ reason = "conflict-concurrent-modifications";
888
+ }
889
+ } else {
890
+ plannedAction = "keep";
891
+ reason = "not-in-remote-snapshot";
892
+ }
893
+
894
+ if (legacyBaselineUnverifiable) {
895
+ plannedAction = "conflict";
896
+ reason = "legacy-baseline-unverifiable";
897
+ effectiveValue = null;
898
+ } else if (plannedAction === "add" || plannedAction === "update") {
899
+ acceptedTransitions.set(id, { hash: remoteHash, tombstone: false });
900
+ } else if (reason === "initial-adopt-identical") {
901
+ acceptedTransitions.set(id, { hash: localHash, tombstone: false });
902
+ } else if (reason === "identical-to-remote") {
903
+ acceptedTransitions.set(id, { hash: remoteHash, tombstone: false });
904
+ } else if (reason === "local-modified-remote-unchanged") {
905
+ acceptedTransitions.set(id, { hash: baselineHash, tombstone: false });
906
+ } else if (reason === "remote-deleted" || reason === "already-absent") {
907
+ acceptedTransitions.set(id, { hash: SENTINEL_DELETED, tombstone: true });
908
+ }
909
+
910
+ // Check for plugin prerequisite if plannedAction is add or update
911
+ if ((plannedAction === "add" || plannedAction === "update") && id.startsWith("plugin:")) {
912
+ const pluginName = id.slice("plugin:".length);
913
+ const reqVersion = effectiveValue?.version;
914
+ const installedPkgPath = path.join(
915
+ pluginsDir,
916
+ "node_modules",
917
+ ...pluginName.split("/"),
918
+ "package.json"
919
+ );
920
+
921
+ let installedVer = null;
922
+ if (fs.existsSync(installedPkgPath)) {
923
+ installedVer = parseJsonStrict(
924
+ fs.readFileSync(installedPkgPath, "utf8"),
925
+ `${pluginName} package.json`
926
+ ).version;
927
+ }
928
+
929
+ if (!installedVer) {
930
+ plannedAction = "blocked";
931
+ reason = "plugin-not-installed";
932
+ prerequisites.push(
933
+ `Plugin '${pluginName}' is not installed. Run: omp plugin install ${pluginName}@${reqVersion}`
934
+ );
935
+ } else if (installedVer !== reqVersion) {
936
+ plannedAction = "blocked";
937
+ reason = "plugin-version-mismatch";
938
+ prerequisites.push(
939
+ `Plugin '${pluginName}' installed version (${installedVer}) does not match required version (${reqVersion}). Run: omp plugin install ${pluginName}@${reqVersion}`
940
+ );
941
+ }
942
+ }
943
+ if (plannedAction === "blocked") acceptedTransitions.delete(id);
944
+
945
+ // Path restoration on incoming values for add or update
946
+ if ((plannedAction === "add" || plannedAction === "update") && effectiveValue !== null) {
947
+ const { value: restoredVal, prerequisites: prereqs } = restoreResourceForImport(
948
+ id,
949
+ effectiveValue,
950
+ root
951
+ );
952
+ effectiveValue = restoredVal;
953
+ if (prereqs.length > 0) {
954
+ prerequisites.push(...prereqs);
955
+ }
956
+ remapped = true;
957
+ }
958
+
959
+ if (plannedAction === "add" || plannedAction === "update" || plannedAction === "delete") {
960
+ try {
961
+ const rootTarget = assertSafeTarget(root, targetPath);
962
+ if (id.startsWith("asset:") && plannedAction !== "delete") {
963
+ const archiveRel = id.slice("asset:".length);
964
+ const incomingDirectory = effectiveValue.some((file) => file.path !== archiveRel);
965
+ let currentStat;
966
+ try {
967
+ currentStat = fs.lstatSync(rootTarget.abs);
968
+ } catch (err) {
969
+ if (err?.code !== "ENOENT") throw err;
970
+ }
971
+ if (currentStat && ((currentStat.isDirectory() && !incomingDirectory) ||
972
+ (currentStat.isFile() && incomingDirectory) ||
973
+ (!currentStat.isDirectory() && !currentStat.isFile()))) {
974
+ throw new Error(`Asset type conversion is blocked for '${archiveRel}'`);
975
+ }
976
+ for (const file of effectiveValue) {
977
+ assertSafeTarget(root, file.path);
978
+ }
979
+ }
980
+ } catch (err) {
981
+ plannedAction = "blocked";
982
+ reason = err.message;
983
+ acceptedTransitions.delete(id);
984
+ }
985
+ }
986
+
987
+ if (plannedAction === "conflict") {
988
+ conflicts.push({
989
+ id,
990
+ reason,
991
+ targetPath,
992
+ });
993
+ }
994
+
995
+ if (plannedAction === "blocked") {
996
+ blocked.push({
997
+ id,
998
+ reason,
999
+ targetPath,
1000
+ });
1001
+ }
1002
+
1003
+ actions.push({
1004
+ id,
1005
+ action: plannedAction,
1006
+ reason,
1007
+ targetPath,
1008
+ remapped,
1009
+ value: effectiveValue,
1010
+ localHash,
1011
+ remoteHash,
1012
+ baselineHash,
1013
+ });
1014
+ }
1015
+
1016
+ const nextResources = cloneOwn(state.resources || {});
1017
+ const nextTombstones = new Set(state.tombstones || []);
1018
+ for (const [id, transition] of acceptedTransitions) {
1019
+ Object.defineProperty(nextResources, id, {
1020
+ value: { hash: transition.hash, hashFormat: "portable-v1" },
1021
+ enumerable: true,
1022
+ configurable: true,
1023
+ writable: true,
1024
+ });
1025
+ if (transition.tombstone) nextTombstones.add(id);
1026
+ else nextTombstones.delete(id);
1027
+ }
1028
+ const nextState = validateSyncState({
1029
+ ...cloneOwn(state),
1030
+ version: 1,
1031
+ namespace: validSnapshot.namespace,
1032
+ resources: nextResources,
1033
+ tombstones: Array.from(nextTombstones).sort(),
1034
+ });
1035
+
1036
+ const rendered = renderResourceChanges(root, actions, readContext);
1037
+ const publicActions = actions.map(({ id, action, reason, targetPath, remapped }) => ({
1038
+ id, action, reason, targetPath, remapped,
1039
+ }));
1040
+ const publicWrites = Array.from(rendered.values())
1041
+ .map(({ rel, operation }) => ({ path: rel, operation }))
1042
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
1043
+ const report = deepFreeze({
1044
+ namespace: validSnapshot.namespace,
1045
+ actions: publicActions,
1046
+ conflicts,
1047
+ blocked,
1048
+ prerequisites,
1049
+ writes: publicWrites,
1050
+ });
1051
+ planTransactions.set(report, {
1052
+ root: path.resolve(root),
1053
+ nextState,
1054
+ actions,
1055
+ entries: rendered,
1056
+ readContext,
1057
+ namespace: validSnapshot.namespace,
1058
+ needsCommit: rendered.size > 0 || JSON.stringify(state) !== JSON.stringify(nextState),
1059
+ consumed: false,
1060
+ });
1061
+ return report;
1062
+ }