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,621 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { parseDocument } from "yaml";
6
+
7
+ const WINDOWS_DEVICE = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i;
8
+
9
+ export function configRoot() {
10
+ return process.env.OMP_CFG_ROOT || path.join(os.homedir(), ".omp", "agent");
11
+ }
12
+
13
+ export function ompHome(root = configRoot()) {
14
+ return process.env.OMP_HOME || path.dirname(root);
15
+ }
16
+
17
+ export function resolveDestination(rel, root = configRoot()) {
18
+ const norm = rel.replace(/\\/g, "/");
19
+ if (norm.startsWith("plugins/") || norm.startsWith("tools/") || norm.startsWith("hooks/")) {
20
+ return path.join(ompHome(root), norm);
21
+ }
22
+ return path.join(root, norm);
23
+ }
24
+
25
+ export function validatePortablePath(relPath) {
26
+ if (typeof relPath !== "string" || !relPath) {
27
+ throw new Error("Invalid asset path: path must be a non-empty string");
28
+ }
29
+ if (relPath.includes("\\")) {
30
+ throw new Error("Invalid asset path: backslashes are prohibited");
31
+ }
32
+ if (relPath.includes("\0") || path.posix.isAbsolute(relPath) || path.win32.isAbsolute(relPath)) {
33
+ throw new Error("Invalid asset path: absolute paths and NUL bytes are prohibited");
34
+ }
35
+ const parts = relPath.split("/");
36
+ for (const part of parts) {
37
+ if (!part || part === "." || part === "..") {
38
+ throw new Error("Invalid asset path: empty and dot segments are prohibited");
39
+ }
40
+ if (/[<>:"|?*\x00-\x1f]/.test(part)) {
41
+ throw new Error("Invalid asset path: control characters, ADS, and reserved characters are prohibited");
42
+ }
43
+ if (/[. ]$/.test(part) || WINDOWS_DEVICE.test(part)) {
44
+ throw new Error("Invalid asset path: Windows device names and trailing dots/spaces are prohibited");
45
+ }
46
+ }
47
+ return parts;
48
+ }
49
+
50
+ export const MAX_FILE_SIZE = 10 * 1024 * 1024;
51
+ export const STRICT_BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
52
+
53
+ export function validateAssetFiles(resourceRoot, value) {
54
+ if (!Array.isArray(value) || value.length === 0) {
55
+ throw new Error(`Invalid asset '${resourceRoot}': value must be a non-empty file array`);
56
+ }
57
+ const paths = new Set();
58
+ const caseFolded = new Map();
59
+ for (const file of value) {
60
+ if (!file || typeof file !== "object" || Array.isArray(file)) {
61
+ throw new Error(`Invalid asset '${resourceRoot}': every file entry must be an object`);
62
+ }
63
+ const keys = Object.keys(file).sort();
64
+ if (keys.join(",") !== "data,mode,path") {
65
+ throw new Error(`Invalid asset '${resourceRoot}': file entries require exactly path, data, and mode`);
66
+ }
67
+ validatePortablePath(file.path);
68
+ if (file.path !== resourceRoot && !file.path.startsWith(resourceRoot + "/")) {
69
+ throw new Error(`Invalid asset '${resourceRoot}': file path escapes the declared resource root`);
70
+ }
71
+ if (paths.has(file.path)) {
72
+ throw new Error(`Invalid asset '${resourceRoot}': duplicate file path`);
73
+ }
74
+ const folded = file.path.toLowerCase();
75
+ if (caseFolded.has(folded)) {
76
+ throw new Error(`Invalid asset '${resourceRoot}': case-folding path collision`);
77
+ }
78
+ paths.add(file.path);
79
+ caseFolded.set(folded, file.path);
80
+ if (typeof file.data !== "string" || !STRICT_BASE64.test(file.data)) {
81
+ throw new Error(`Invalid asset '${resourceRoot}': file data must be strict base64`);
82
+ }
83
+ if (file.data.length > Math.ceil(MAX_FILE_SIZE / 3) * 4 + 4) {
84
+ throw new Error(`Invalid asset '${resourceRoot}': file exceeds 10 MiB limit`);
85
+ }
86
+ const bytes = Buffer.from(file.data, "base64");
87
+ if (bytes.length > MAX_FILE_SIZE || bytes.toString("base64") !== file.data) {
88
+ throw new Error(`Invalid asset '${resourceRoot}': invalid base64 or file exceeds 10 MiB limit`);
89
+ }
90
+ if (!Number.isInteger(file.mode) || file.mode < 0 || file.mode > 0o777) {
91
+ throw new Error(`Invalid asset '${resourceRoot}': mode must be an integer from 0 to 0777`);
92
+ }
93
+ }
94
+ for (const filePath of paths) {
95
+ const parts = filePath.split("/");
96
+ for (let i = 1; i < parts.length; i++) {
97
+ if (paths.has(parts.slice(0, i).join("/"))) {
98
+ throw new Error(`Invalid asset '${resourceRoot}': file/directory prefix collision`);
99
+ }
100
+ }
101
+ }
102
+ if (/^(?:skills|managed-skills)\//.test(resourceRoot) && !paths.has(`${resourceRoot}/SKILL.md`)) {
103
+ throw new Error(`Invalid skill '${resourceRoot}': root SKILL.md is required`);
104
+ }
105
+ return value;
106
+ }
107
+
108
+ function lstatIfPresent(abs) {
109
+ try {
110
+ return fs.lstatSync(abs);
111
+ } catch (err) {
112
+ if (err?.code === "ENOENT") return undefined;
113
+ throw err;
114
+ }
115
+ }
116
+
117
+ function isInside(abs, root) {
118
+ const rel = path.relative(root, abs);
119
+ return rel === "" || (!rel.startsWith(".." + path.sep) && rel !== ".." && !path.isAbsolute(rel));
120
+ }
121
+
122
+ export function assertSafeTarget(root, relPath) {
123
+ const parts = validatePortablePath(relPath);
124
+ const norm = parts.join("/");
125
+ const rootKind = /^(?:plugins|tools|hooks)\//.test(norm) ? "omp" : "agent";
126
+ const allowedRoot = path.resolve(rootKind === "omp" ? ompHome(root) : root);
127
+ const abs = path.resolve(allowedRoot, ...parts);
128
+ if (!isInside(abs, allowedRoot)) {
129
+ throw new Error("Security violation: target escapes its allowed configuration root");
130
+ }
131
+
132
+ const filesystemRoot = path.parse(abs).root;
133
+ let current = filesystemRoot;
134
+ for (const part of abs.slice(filesystemRoot.length).split(path.sep).filter(Boolean)) {
135
+ current = path.join(current, part);
136
+ const stat = lstatIfPresent(current);
137
+ if (!stat) continue;
138
+ if (stat.isSymbolicLink()) {
139
+ throw new Error(`Security violation: symlink or junction ancestor is prohibited for '${norm}'`);
140
+ }
141
+ if (current !== abs && !stat.isDirectory()) {
142
+ throw new Error(`Security violation: non-directory ancestor blocks '${norm}'`);
143
+ }
144
+ }
145
+
146
+ let nearest = path.dirname(abs);
147
+ let nearestStat = lstatIfPresent(nearest);
148
+ while (!nearestStat) {
149
+ const parent = path.dirname(nearest);
150
+ if (parent === nearest) break;
151
+ nearest = parent;
152
+ nearestStat = lstatIfPresent(nearest);
153
+ }
154
+ const rootStat = lstatIfPresent(allowedRoot);
155
+ if (rootStat && nearestStat) {
156
+ const realRoot = fs.realpathSync(allowedRoot);
157
+ const realNearest = fs.realpathSync(nearest);
158
+ if (!isInside(realNearest, realRoot)) {
159
+ throw new Error(`Security violation: target parent resolves outside its allowed root for '${norm}'`);
160
+ }
161
+ }
162
+ return { abs, rel: norm, root: rootKind };
163
+ }
164
+
165
+ export function pointerToTokens(pointer) {
166
+ if (pointer === "") return [];
167
+ if (typeof pointer !== "string" || !pointer.startsWith("/")) {
168
+ throw new Error("Invalid JSON pointer: must start with '/'");
169
+ }
170
+ return pointer.slice(1).split("/").map((segment) => {
171
+ if (/~(?:[^01]|$)/.test(segment)) {
172
+ throw new Error("Invalid JSON pointer: only ~0 and ~1 escapes are allowed");
173
+ }
174
+ return segment.replace(/~1/g, "/").replace(/~0/g, "~");
175
+ });
176
+ }
177
+
178
+ function errorLocation(error) {
179
+ const pos = error?.linePos?.[0];
180
+ if (pos && Number.isInteger(pos.line) && Number.isInteger(pos.col)) {
181
+ return ` at line ${pos.line}, column ${pos.col}`;
182
+ }
183
+ const match = /line (\d+) column (\d+)/i.exec(String(error?.message || ""));
184
+ return match ? ` at line ${match[1]}, column ${match[2]}` : "";
185
+ }
186
+
187
+ export function parseYamlStrict(str, filename = "YAML") {
188
+ const doc = parseDocument(str, { uniqueKeys: true, customTags: [] });
189
+ const customTag = (doc.warnings || []).find((warning) => warning.code === "TAG_RESOLVE_FAILED");
190
+ if ((doc.errors && doc.errors.length > 0) || customTag) {
191
+ const error = doc.errors?.[0] || customTag;
192
+ const code = error?.code || "PARSE_ERROR";
193
+ throw new Error(`Invalid YAML in ${filename}: ${code}${errorLocation(error)}`);
194
+ }
195
+ return doc;
196
+ }
197
+
198
+ export function parseJsonStrict(str, filename = "JSON") {
199
+ try {
200
+ return JSON.parse(str);
201
+ } catch (error) {
202
+ throw new Error(`Invalid JSON in ${filename}: ${errorLocation(error)}`.trimEnd());
203
+ }
204
+ }
205
+
206
+ function bufferHash(buffer) {
207
+ return createHash("sha256").update(buffer).digest("hex");
208
+ }
209
+
210
+ export function createReadContext(root) {
211
+ const base = path.resolve(root);
212
+ const observations = new Map();
213
+
214
+ function relative(abs) {
215
+ const rel = path.relative(base, abs);
216
+ return rel && !rel.startsWith("..") ? rel.replace(/\\/g, "/") : path.basename(abs);
217
+ }
218
+
219
+ function observe(abs) {
220
+ const target = path.resolve(abs);
221
+ if (observations.has(target)) return observations.get(target);
222
+ const stat = lstatIfPresent(target);
223
+ if (!stat) {
224
+ const observation = { type: "missing", mode: null, hash: null, entries: null };
225
+ observations.set(target, observation);
226
+ return observation;
227
+ }
228
+ if (stat.isSymbolicLink()) {
229
+ throw new Error(`Security violation: read path '${relative(target)}' is a symlink or junction`);
230
+ }
231
+ if (stat.isFile()) {
232
+ const bytes = fs.readFileSync(target);
233
+ const observation = { type: "file", mode: stat.mode & 0o777, hash: bufferHash(bytes), bytes, entries: null };
234
+ observations.set(target, observation);
235
+ return observation;
236
+ }
237
+ if (stat.isDirectory()) {
238
+ const entries = fs.readdirSync(target, { withFileTypes: true })
239
+ .map((entry) => ({
240
+ name: entry.name,
241
+ type: entry.isSymbolicLink() ? "symlink" : entry.isDirectory() ? "dir" : entry.isFile() ? "file" : "other",
242
+ }))
243
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
244
+ const observation = { type: "dir", mode: stat.mode & 0o777, hash: null, bytes: null, entries };
245
+ observations.set(target, observation);
246
+ return observation;
247
+ }
248
+ throw new Error(`Unsupported file type at '${relative(target)}'`);
249
+ }
250
+
251
+ return {
252
+ root: base,
253
+ observe,
254
+ readFile(abs) {
255
+ const observation = observe(abs);
256
+ if (observation.type === "missing") return undefined;
257
+ if (observation.type !== "file") throw new Error(`Expected a file at '${relative(abs)}'`);
258
+ return observation.bytes;
259
+ },
260
+ fileMode(abs) {
261
+ const observation = observe(abs);
262
+ return observation.type === "file" ? observation.mode : null;
263
+ },
264
+ listDirectory(abs) {
265
+ const observation = observe(abs);
266
+ if (observation.type === "missing") return undefined;
267
+ if (observation.type !== "dir") throw new Error(`Expected a directory at '${relative(abs)}'`);
268
+ return observation.entries.map((entry) => ({ ...entry }));
269
+ },
270
+ verify() {
271
+ for (const [target, observed] of observations) {
272
+ const stat = lstatIfPresent(target);
273
+ const rel = relative(target);
274
+ if (!stat) {
275
+ if (observed.type !== "missing") {
276
+ throw new Error(`Concurrent modification detected: '${rel}' was removed`);
277
+ }
278
+ continue;
279
+ }
280
+ if (observed.type === "missing") {
281
+ throw new Error(`Concurrent modification detected: '${rel}' was created`);
282
+ }
283
+ if (stat.isSymbolicLink() || (observed.type === "file" && !stat.isFile()) ||
284
+ (observed.type === "dir" && !stat.isDirectory())) {
285
+ throw new Error(`Concurrent modification detected: '${rel}' changed type`);
286
+ }
287
+ if (observed.type === "file") {
288
+ const current = fs.readFileSync(target);
289
+ if ((stat.mode & 0o777) !== observed.mode || bufferHash(current) !== observed.hash) {
290
+ throw new Error(`Concurrent modification detected: '${rel}' changed`);
291
+ }
292
+ } else if (observed.type === "dir") {
293
+ const current = fs.readdirSync(target, { withFileTypes: true })
294
+ .map((entry) => ({
295
+ name: entry.name,
296
+ type: entry.isSymbolicLink() ? "symlink" : entry.isDirectory() ? "dir" : entry.isFile() ? "file" : "other",
297
+ }))
298
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
299
+ if (JSON.stringify(current) !== JSON.stringify(observed.entries)) {
300
+ throw new Error(`Concurrent modification detected: directory '${rel}' changed`);
301
+ }
302
+ }
303
+ }
304
+ },
305
+ paths() {
306
+ return Array.from(observations.keys());
307
+ },
308
+ };
309
+ }
310
+
311
+ export function renderResourceChanges(root, changes, readContext) {
312
+ const writes = new Map();
313
+ const folded = new Map();
314
+
315
+ function register(rel, abs, operation, content = null, mode = 0o600) {
316
+ const safe = assertSafeTarget(root, rel);
317
+ const foldedRel = safe.rel.toLowerCase();
318
+ if (folded.has(foldedRel) && folded.get(foldedRel) !== safe.rel) {
319
+ throw new Error(`Case-folding conflict detected for '${safe.rel}'`);
320
+ }
321
+ folded.set(foldedRel, safe.rel);
322
+ const existing = readContext.readFile(abs);
323
+ const existingMode = existing === undefined ? null : readContext.fileMode(abs);
324
+ if (operation === "write") {
325
+ if (existing !== undefined && existing.equals(content) && existingMode === mode) return;
326
+ } else if (existing === undefined) {
327
+ return;
328
+ }
329
+ writes.set(safe.rel, { rel: safe.rel, abs: safe.abs, operation, content, mode });
330
+ }
331
+
332
+ const byPrefix = (prefix) => changes.filter((change) => change.id.startsWith(prefix) &&
333
+ (change.action === "add" || change.action === "update" || change.action === "delete"));
334
+
335
+ function chooseYaml(primary, alternate) {
336
+ if (readContext.readFile(path.join(root, primary)) !== undefined) return primary;
337
+ if (readContext.readFile(path.join(root, alternate)) !== undefined) return alternate;
338
+ return primary;
339
+ }
340
+
341
+ const providerChanges = byPrefix("provider:");
342
+ if (providerChanges.length > 0) {
343
+ const rel = chooseYaml("models.yml", "models.yaml");
344
+ const abs = path.join(root, rel);
345
+ const existing = readContext.readFile(abs);
346
+ const doc = existing === undefined ? parseYamlStrict("providers: {}\n", rel) : parseYamlStrict(existing.toString("utf8"), rel);
347
+ if (!doc.has("providers") || !doc.get("providers")) doc.set("providers", {});
348
+ for (const change of providerChanges) {
349
+ const name = change.id.slice("provider:".length);
350
+ if (change.action === "delete") doc.deleteIn(["providers", name]);
351
+ else doc.setIn(["providers", name], change.value);
352
+ }
353
+ register(rel, abs, "write", Buffer.from(doc.toString(), "utf8"), readContext.fileMode(abs) ?? 0o600);
354
+ }
355
+
356
+ const mcpChanges = byPrefix("mcp:");
357
+ if (mcpChanges.length > 0) {
358
+ const rel = "mcp.json";
359
+ const abs = path.join(root, rel);
360
+ const existing = readContext.readFile(abs);
361
+ const data = existing === undefined ? { mcpServers: {} } : parseJsonStrict(existing.toString("utf8"), rel);
362
+ if (!data.mcpServers || typeof data.mcpServers !== "object" || Array.isArray(data.mcpServers)) data.mcpServers = {};
363
+ for (const change of mcpChanges) {
364
+ const name = change.id.slice("mcp:".length);
365
+ if (change.action === "delete") delete data.mcpServers[name];
366
+ else Object.defineProperty(data.mcpServers, name, { value: change.value, enumerable: true, configurable: true, writable: true });
367
+ }
368
+ register(rel, abs, "write", Buffer.from(JSON.stringify(data, null, 2) + "\n", "utf8"), readContext.fileMode(abs) ?? 0o600);
369
+ }
370
+
371
+ const settingChanges = byPrefix("setting:");
372
+ if (settingChanges.length > 0) {
373
+ const rel = chooseYaml("config.yml", "config.yaml");
374
+ const abs = path.join(root, rel);
375
+ const existing = readContext.readFile(abs);
376
+ const doc = existing === undefined ? parseYamlStrict("", rel) : parseYamlStrict(existing.toString("utf8"), rel);
377
+ for (const change of settingChanges) {
378
+ const tokens = pointerToTokens(change.id.slice("setting:".length));
379
+ if (change.action === "delete") doc.deleteIn(tokens);
380
+ else doc.setIn(tokens, change.value);
381
+ }
382
+ register(rel, abs, "write", Buffer.from(doc.toString(), "utf8"), readContext.fileMode(abs) ?? 0o600);
383
+ }
384
+
385
+ const pluginChanges = byPrefix("plugin:");
386
+ if (pluginChanges.length > 0) {
387
+ const pluginsDir = path.join(ompHome(root), "plugins");
388
+ const pkgRel = "plugins/package.json";
389
+ const lockRel = "plugins/omp-plugins.lock.json";
390
+ const pkgAbs = path.join(pluginsDir, "package.json");
391
+ const lockAbs = path.join(pluginsDir, "omp-plugins.lock.json");
392
+ const pkgExisting = readContext.readFile(pkgAbs);
393
+ const pkg = pkgExisting === undefined
394
+ ? { name: "omp-plugins", private: true, dependencies: {} }
395
+ : parseJsonStrict(pkgExisting.toString("utf8"), "plugins/package.json");
396
+ if (!pkg.dependencies || typeof pkg.dependencies !== "object" || Array.isArray(pkg.dependencies)) pkg.dependencies = {};
397
+ const lockExisting = readContext.readFile(lockAbs);
398
+ const lock = lockExisting === undefined ? { plugins: {} } : parseJsonStrict(lockExisting.toString("utf8"), "omp-plugins.lock.json");
399
+ if (!lock.plugins || typeof lock.plugins !== "object" || Array.isArray(lock.plugins)) lock.plugins = {};
400
+ for (const change of pluginChanges) {
401
+ const name = change.id.slice("plugin:".length);
402
+ if (change.action === "delete") {
403
+ delete pkg.dependencies[name];
404
+ delete lock.plugins[name];
405
+ } else {
406
+ Object.defineProperty(pkg.dependencies, name, { value: change.value.version, enumerable: true, configurable: true, writable: true });
407
+ Object.defineProperty(lock.plugins, name, {
408
+ value: { ...(lock.plugins[name] || {}), version: change.value.version, enabled: change.value.enabled !== false },
409
+ enumerable: true,
410
+ configurable: true,
411
+ writable: true,
412
+ });
413
+ }
414
+ }
415
+ register(pkgRel, pkgAbs, "write", Buffer.from(JSON.stringify(pkg, null, 2) + "\n", "utf8"), readContext.fileMode(pkgAbs) ?? 0o600);
416
+ register(lockRel, lockAbs, "write", Buffer.from(JSON.stringify(lock, null, 2) + "\n", "utf8"), readContext.fileMode(lockAbs) ?? 0o600);
417
+ }
418
+
419
+ for (const change of byPrefix("asset:")) {
420
+ const archiveRel = change.id.slice("asset:".length);
421
+ const destination = resolveDestination(archiveRel, root);
422
+ if (change.action === "delete") {
423
+ const observation = readContext.observe(destination);
424
+ if (observation.type === "file") {
425
+ register(archiveRel, destination, "delete");
426
+ } else if (observation.type === "dir") {
427
+ const walk = (abs, rel) => {
428
+ for (const entry of readContext.listDirectory(abs)) {
429
+ const childRel = `${rel}/${entry.name}`;
430
+ const childAbs = path.join(abs, entry.name);
431
+ if (entry.type === "dir") walk(childAbs, childRel);
432
+ else if (entry.type === "file") register(childRel, childAbs, "delete");
433
+ else throw new Error(`Asset '${archiveRel}' contains an unsupported link or file type`);
434
+ }
435
+ };
436
+ walk(destination, archiveRel);
437
+ }
438
+ } else {
439
+ const incoming = new Set();
440
+ for (const file of change.value) {
441
+ incoming.add(file.path);
442
+ register(file.path, resolveDestination(file.path, root), "write", Buffer.from(file.data, "base64"), file.mode);
443
+ }
444
+ const observation = readContext.observe(destination);
445
+ if (observation.type === "dir") {
446
+ const walk = (abs, rel) => {
447
+ for (const entry of readContext.listDirectory(abs)) {
448
+ const childRel = `${rel}/${entry.name}`;
449
+ const childAbs = path.join(abs, entry.name);
450
+ if (entry.type === "dir") walk(childAbs, childRel);
451
+ else if (entry.type === "file") {
452
+ if (!incoming.has(childRel)) register(childRel, childAbs, "delete");
453
+ } else {
454
+ throw new Error(`Asset '${archiveRel}' contains an unsupported link or file type`);
455
+ }
456
+ }
457
+ };
458
+ walk(destination, archiveRel);
459
+ }
460
+ }
461
+ }
462
+
463
+ return new Map(Array.from(writes.entries()).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
464
+ }
465
+
466
+ export const LOCK_FILE = ".sync.local.lock";
467
+ export const RECOVERY_LOCK_FILE = ".sync-recovery.local.lock";
468
+
469
+ function writeLockContent(lockPath, content) {
470
+ fs.writeFileSync(lockPath, `${JSON.stringify(content)}\n`, "utf8");
471
+ }
472
+
473
+ export function readLockFile(root) {
474
+ const lockPath = path.join(root, LOCK_FILE);
475
+ if (!fs.existsSync(lockPath)) return null;
476
+ const raw = fs.readFileSync(lockPath, "utf8");
477
+ try {
478
+ const parsed = JSON.parse(raw);
479
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
480
+ throw new Error("invalid root");
481
+ }
482
+ if (parsed.version !== 1 || typeof parsed.transactionId !== "string" || !parsed.transactionId) {
483
+ throw new Error("invalid version/transactionId");
484
+ }
485
+ if (!Number.isInteger(parsed.pid) || parsed.pid <= 0) {
486
+ throw new Error("invalid pid");
487
+ }
488
+ if (typeof parsed.createdAt !== "string" || !parsed.createdAt) {
489
+ throw new Error("invalid createdAt");
490
+ }
491
+ if (!(parsed.backupDir === null || typeof parsed.backupDir === "string")) {
492
+ throw new Error("invalid backupDir");
493
+ }
494
+ return { path: lockPath, content: parsed, raw };
495
+ } catch (error) {
496
+ const err = new Error(`Sync lock at ${lockPath} is corrupt or unknown; manual recovery required`);
497
+ err.cause = error;
498
+ throw err;
499
+ }
500
+ }
501
+
502
+ export function isPidAlive(pid) {
503
+ if (!Number.isInteger(pid) || pid <= 0) return false;
504
+ try {
505
+ process.kill(pid, 0);
506
+ return true;
507
+ } catch (error) {
508
+ if (error && error.code === "EPERM") return true;
509
+ return false;
510
+ }
511
+ }
512
+
513
+ export function withSyncLock(root, operation, options = {}) {
514
+ const agentDir = path.resolve(root);
515
+ if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true });
516
+ const lockPath = path.join(agentDir, LOCK_FILE);
517
+ const recoveryPath = path.join(agentDir, RECOVERY_LOCK_FILE);
518
+ if (fs.existsSync(recoveryPath) && !options.allowDuringRecovery) {
519
+ throw new Error(`Sync recovery lock active at ${recoveryPath}; manual recovery required`);
520
+ }
521
+
522
+ const transactionId = options.transactionId || randomUUID();
523
+ let fd;
524
+ try {
525
+ fd = fs.openSync(lockPath, "wx");
526
+ } catch (error) {
527
+ if (error && (error.code === "EACCES" || error.code === "EPERM")) {
528
+ throw new Error(
529
+ `Sync lock could not be created at ${lockPath}: permission denied (${error.code}). Check directory ACL/permissions; manual recovery may be required.`
530
+ );
531
+ }
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
+ );
535
+ }
536
+
537
+ const content = {
538
+ version: 1,
539
+ transactionId,
540
+ pid: process.pid,
541
+ createdAt: new Date().toISOString(),
542
+ backupDir: null,
543
+ };
544
+ try {
545
+ fs.writeSync(fd, `${JSON.stringify(content)}\n`);
546
+ fs.fsyncSync(fd);
547
+ } finally {
548
+ fs.closeSync(fd);
549
+ }
550
+
551
+ if (fs.existsSync(recoveryPath) && !options.allowDuringRecovery) {
552
+ try { fs.unlinkSync(lockPath); } catch {}
553
+ throw new Error(`Sync recovery lock active at ${recoveryPath}; manual recovery required`);
554
+ }
555
+
556
+ const handle = {
557
+ transactionId,
558
+ path: lockPath,
559
+ _preserve: false,
560
+ preserveForRecovery() {
561
+ this._preserve = true;
562
+ },
563
+ setBackupDir(rel) {
564
+ if (typeof rel !== "string" || !rel || rel.includes("/") || rel.includes("\\") || rel.includes("..")) {
565
+ throw new Error("Invalid lock backupDir");
566
+ }
567
+ content.backupDir = rel;
568
+ writeLockContent(lockPath, content);
569
+ },
570
+ };
571
+
572
+ const release = () => {
573
+ if (handle._preserve) return;
574
+ try {
575
+ const current = JSON.parse(fs.readFileSync(lockPath, "utf8"));
576
+ if (current.transactionId === transactionId) fs.unlinkSync(lockPath);
577
+ } catch {}
578
+ };
579
+
580
+ try {
581
+ const result = operation(handle);
582
+ if (result && typeof result.then === "function") {
583
+ return Promise.resolve(result).then(
584
+ (value) => {
585
+ release();
586
+ return value;
587
+ },
588
+ (error) => {
589
+ release();
590
+ throw error;
591
+ }
592
+ );
593
+ }
594
+ release();
595
+ return result;
596
+ } catch (error) {
597
+ release();
598
+ throw error;
599
+ }
600
+ }
601
+
602
+ export function atomicWriteFile(absPath, content, mode = 0o600) {
603
+ const dir = path.dirname(absPath);
604
+ const base = path.basename(absPath);
605
+ const tmp = path.join(dir, `.${base}.tmp-${randomUUID()}`);
606
+ const data = Buffer.isBuffer(content) ? content : Buffer.from(String(content), "utf8");
607
+ fs.writeFileSync(tmp, data, { mode });
608
+ try {
609
+ const fd = fs.openSync(tmp, "r+");
610
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
611
+ } catch {}
612
+ try {
613
+ fs.renameSync(tmp, absPath);
614
+ } catch (error) {
615
+ try { fs.unlinkSync(tmp); } catch {}
616
+ throw error;
617
+ }
618
+ try { fs.chmodSync(absPath, mode); } catch {}
619
+ return tmp;
620
+ }
621
+