mason-context 0.18.0 → 0.19.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.
@@ -0,0 +1,337 @@
1
+ #!/usr/bin/env node
2
+ if (!import.meta.url.endsWith("/mason-runtime.js")) await import("./mason-runtime.js").then(m => m.registerRuntime());
3
+
4
+ // src/distribution/runtime.ts
5
+ import fs7 from "fs/promises";
6
+ import { unlinkSync } from "fs";
7
+ import os4 from "os";
8
+ import path7 from "path";
9
+ import { randomUUID as randomUUID3 } from "crypto";
10
+ import { z as z5 } from "zod";
11
+
12
+ // src/automation/store.ts
13
+ import { z } from "zod";
14
+
15
+ // src/utils/store-lock.ts
16
+ import fs3 from "fs/promises";
17
+ import os from "os";
18
+
19
+ // src/utils/storage.ts
20
+ import fs2 from "fs/promises";
21
+ import path3 from "path";
22
+ import { randomUUID } from "crypto";
23
+
24
+ // src/utils/paths.ts
25
+ import path from "path";
26
+ function normalizeRepoPath(value) {
27
+ const slash = value.replace(/\\/g, "/");
28
+ if (!slash || slash.includes("\0") || path.posix.isAbsolute(slash) || /^[A-Za-z]:/.test(slash)) return null;
29
+ if (slash.split("/").includes("..")) return null;
30
+ const normalized = path.posix.normalize(slash).replace(/\/$/, "");
31
+ return normalized === "." ? null : normalized;
32
+ }
33
+
34
+ // src/utils/git-read.ts
35
+ import { execFile } from "child_process";
36
+ import { promisify } from "util";
37
+
38
+ // src/utils/profile.ts
39
+ import { AsyncLocalStorage } from "async_hooks";
40
+ var profiles = new AsyncLocalStorage();
41
+
42
+ // src/utils/git-read.ts
43
+ var execute = promisify(execFile);
44
+
45
+ // src/utils/files.ts
46
+ import fs from "fs/promises";
47
+ import { constants } from "fs";
48
+ import path2 from "path";
49
+ import fg from "fast-glob";
50
+ var SOURCE_EXTENSIONS = ["ts", "tsx", "js", "jsx", "mts", "cts", "mjs", "cjs", "vue", "svelte", "kt", "kts", "java", "py", "go", "rs", "swift", "rb", "cs", "cpp", "c", "h", "hpp", "dart", "php"];
51
+ var SOURCE_GLOB = `**/*.{${SOURCE_EXTENSIONS.join(",")}}`;
52
+ var MAX_SOURCE_BYTES = 1024 * 1024;
53
+ async function readBoundedFile(file, maxBytes) {
54
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
55
+ try {
56
+ const stat = await handle.stat();
57
+ if (!stat.isFile() || stat.size > maxBytes) return null;
58
+ const buffer = Buffer.alloc(Math.min(maxBytes + 1, stat.size + 1));
59
+ let bytes = 0;
60
+ while (bytes < buffer.length) {
61
+ const result = await handle.read(buffer, bytes, buffer.length - bytes, null);
62
+ if (result.bytesRead === 0) break;
63
+ bytes += result.bytesRead;
64
+ }
65
+ return bytes === buffer.length ? null : buffer.subarray(0, bytes).toString("utf8");
66
+ } finally {
67
+ await handle.close();
68
+ }
69
+ }
70
+
71
+ // src/utils/storage.ts
72
+ async function storePath(root, relative, createParents = false) {
73
+ const normalized = normalizeRepoPath(relative);
74
+ if (!normalized) throw new Error(`Invalid store path: ${relative}`);
75
+ let current = await fs2.realpath(root);
76
+ const parts = normalized.split("/");
77
+ for (let i = 0; i < parts.length; i++) {
78
+ current = path3.join(current, parts[i]);
79
+ let stat;
80
+ try {
81
+ stat = await fs2.lstat(current);
82
+ } catch (error) {
83
+ if (error.code !== "ENOENT") throw error;
84
+ if (createParents && i < parts.length - 1) {
85
+ try {
86
+ await fs2.mkdir(current);
87
+ } catch (mkdirError) {
88
+ if (mkdirError.code !== "EEXIST") throw mkdirError;
89
+ }
90
+ stat = await fs2.lstat(current);
91
+ }
92
+ }
93
+ if (stat?.isSymbolicLink()) throw new Error(`Symlink in store path: ${relative}`);
94
+ }
95
+ return current;
96
+ }
97
+ async function readStoreJson(root, relative) {
98
+ try {
99
+ const file = await storePath(root, relative);
100
+ const raw = await readBoundedFile(file, 10 * 1024 * 1024);
101
+ if (raw === null) throw new Error("file is not regular or exceeds 10 MiB");
102
+ const parsed = JSON.parse(raw);
103
+ if (parsed === null) throw new Error("expected a JSON object, received null");
104
+ return parsed;
105
+ } catch (error) {
106
+ if (error.code === "ENOENT") return null;
107
+ throw new Error(`Invalid Mason store ${relative}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
108
+ }
109
+ }
110
+ async function writeStoreJson(root, relative, value) {
111
+ const payload = JSON.stringify(value, null, 2) + "\n";
112
+ if (Buffer.byteLength(payload) > 10 * 1024 * 1024) {
113
+ throw new Error(`Mason store ${relative} exceeds 10 MiB`);
114
+ }
115
+ const file = await storePath(root, relative, true);
116
+ const temporary = path3.join(path3.dirname(file), `.${path3.basename(file)}.${randomUUID()}.tmp`);
117
+ try {
118
+ const handle = await fs2.open(temporary, "wx", 384);
119
+ try {
120
+ await handle.writeFile(payload, "utf8");
121
+ await handle.sync();
122
+ } finally {
123
+ await handle.close();
124
+ }
125
+ await fs2.rename(temporary, file);
126
+ } finally {
127
+ await fs2.rm(temporary, { force: true });
128
+ }
129
+ }
130
+
131
+ // src/utils/store-lock.ts
132
+ async function lockDiagnostic(file) {
133
+ let reason;
134
+ try {
135
+ const owner = JSON.parse(await fs3.readFile(file, "utf8"));
136
+ if (!owner || typeof owner.host !== "string" || !Number.isInteger(owner.pid) || owner.pid <= 0) {
137
+ reason = "Lock owner data is incomplete or malformed.";
138
+ } else if (owner.host !== os.hostname()) {
139
+ reason = "The lock belongs to another host; its process cannot be checked locally.";
140
+ } else {
141
+ try {
142
+ process.kill(owner.pid, 0);
143
+ reason = `Local owner PID ${owner.pid} is still running.`;
144
+ } catch (error) {
145
+ reason = error.code === "ESRCH" ? `Local owner PID ${owner.pid} has exited, but lock recovery has not completed.` : `Local owner PID ${owner.pid} could not be checked.`;
146
+ }
147
+ }
148
+ } catch (error) {
149
+ reason = error instanceof SyntaxError ? "Lock owner data is incomplete or malformed." : "Lock owner data could not be read; the lock may have changed.";
150
+ }
151
+ if (await fs3.lstat(file + ".reclaim").then(() => true, () => false)) {
152
+ reason += " A recovery guard also needs inspection: " + file + ".reclaim.";
153
+ }
154
+ return reason + " Retry if a writer is active. For manual recovery, stop all Mason writers for this checkout, confirm they have exited (including other hosts), then remove only confirmed abandoned lock and lock.reclaim files. See docs/reference.md#snapshot-repairs-and-verification.";
155
+ }
156
+ async function withStoreLock(root, directory, run, waitMs = 5e3, label = "Mason store") {
157
+ const file = await storePath(root, directory + "/lock", true);
158
+ const deadline = Date.now() + waitMs;
159
+ let handle;
160
+ while (!handle) {
161
+ try {
162
+ handle = await fs3.open(file, "wx", 384);
163
+ try {
164
+ await handle.writeFile(JSON.stringify({ pid: process.pid, host: os.hostname() }));
165
+ } catch (error) {
166
+ await handle.close().catch(() => {
167
+ });
168
+ handle = void 0;
169
+ await fs3.rm(file, { force: true }).catch(() => {
170
+ });
171
+ throw error;
172
+ }
173
+ } catch (error) {
174
+ if (error.code !== "EEXIST") throw error;
175
+ try {
176
+ const owner = JSON.parse(await fs3.readFile(file, "utf8"));
177
+ if (owner.host === os.hostname() && Number.isInteger(owner.pid) && owner.pid > 0) {
178
+ try {
179
+ process.kill(owner.pid, 0);
180
+ } catch (probe) {
181
+ if (probe.code === "ESRCH") {
182
+ const reclaim = file + ".reclaim";
183
+ let guard;
184
+ try {
185
+ guard = await fs3.open(reclaim, "wx", 384);
186
+ const current = JSON.parse(await fs3.readFile(file, "utf8"));
187
+ if (current.pid === owner.pid && current.host === owner.host) await fs3.unlink(file);
188
+ } finally {
189
+ if (guard) {
190
+ await guard.close();
191
+ await fs3.rm(reclaim, { force: true });
192
+ }
193
+ }
194
+ }
195
+ }
196
+ }
197
+ } catch {
198
+ }
199
+ if (Date.now() >= deadline) throw new Error(label + " is busy or its lock needs inspection: " + file + ". " + await lockDiagnostic(file));
200
+ await new Promise((resolve) => setTimeout(resolve, 40));
201
+ }
202
+ }
203
+ try {
204
+ return await run();
205
+ } finally {
206
+ await handle.close();
207
+ await fs3.unlink(file);
208
+ }
209
+ }
210
+
211
+ // src/automation/store.ts
212
+ var hostSchema = z.enum(["claude", "codex"]);
213
+ var stateSchema = z.object({
214
+ version: z.literal(1),
215
+ root: z.string(),
216
+ gitDir: z.string(),
217
+ branch: z.string(),
218
+ baselines: z.array(z.object({ path: z.string(), at: z.string(), event: z.string(), fingerprint: z.string() })).max(128),
219
+ sessions: z.record(z.object({
220
+ host: hostSchema,
221
+ seen: z.string().nullable(),
222
+ continued: z.boolean(),
223
+ initialIssues: z.array(z.string()),
224
+ initialDocs: z.record(z.string().nullable()),
225
+ lastUsed: z.string(),
226
+ mutationObserved: z.boolean(),
227
+ pending: z.record(z.string()),
228
+ coverageGaps: z.array(z.string()),
229
+ events: z.record(z.object({ at: z.string(), count: z.number().int().positive() }))
230
+ })),
231
+ updatedAt: z.string(),
232
+ fingerprint: z.string().nullable(),
233
+ latest: z.string().nullable(),
234
+ analysis: z.object({ id: z.string(), fingerprint: z.string(), completedAt: z.number(), path: z.string() }).optional()
235
+ });
236
+ function withLock(root, directory, run, waitMs = 5e3) {
237
+ return withStoreLock(root, directory, run, waitMs, "Automation");
238
+ }
239
+
240
+ // src/distribution/state.ts
241
+ import os3 from "os";
242
+ import path5 from "path";
243
+ import { fileURLToPath } from "url";
244
+ import fs5 from "fs/promises";
245
+ import { z as z3 } from "zod";
246
+
247
+ // src/distribution/path.ts
248
+ import fs4 from "fs/promises";
249
+ import os2 from "os";
250
+ import path4 from "path";
251
+ import { execFile as execFile2 } from "child_process";
252
+ import { promisify as promisify2 } from "util";
253
+ import { createHash, randomUUID as randomUUID2 } from "crypto";
254
+ import { z as z2 } from "zod";
255
+ var execute2 = promisify2(execFile2);
256
+ var pathChangeSchema = z2.discriminatedUnion("kind", [
257
+ z2.object({ kind: z2.literal("profile"), file: z2.string(), block: z2.string(), created: z2.boolean() }),
258
+ z2.object({ kind: z2.literal("windows"), entry: z2.string(), created: z2.boolean() })
259
+ ]);
260
+
261
+ // src/distribution/state.ts
262
+ var releaseVersion = z3.string().regex(/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/);
263
+ var bundleId = z3.string().regex(/^[a-f0-9]{24}$/);
264
+ var updatePolicySchema = z3.object({
265
+ enabled: z3.boolean(),
266
+ revision: z3.string(),
267
+ pinnedVersion: releaseVersion.optional(),
268
+ mirror: z3.string().optional()
269
+ });
270
+ var recordSchema = z3.object({
271
+ format: z3.literal(1),
272
+ home: z3.string(),
273
+ bin: z3.string(),
274
+ current: bundleId,
275
+ version: releaseVersion,
276
+ launchers: z3.record(z3.string()),
277
+ previousLaunchers: z3.record(z3.string()).optional(),
278
+ pathChanges: z3.array(pathChangeSchema).optional(),
279
+ updates: updatePolicySchema.optional(),
280
+ previous: z3.object({ id: bundleId, version: releaseVersion }).optional(),
281
+ pending: z3.object({ id: bundleId, version: releaseVersion, policyRevision: z3.string() }).optional()
282
+ });
283
+ async function readInstallation(home) {
284
+ const raw = await readStoreJson(home, "install.json");
285
+ if (!raw) throw new Error("Run this command from a standalone installation. npm users can upgrade with npm.");
286
+ const record = recordSchema.parse(raw);
287
+ if (record.home !== await fs5.realpath(home)) throw new Error("Invalid standalone installation receipt.");
288
+ return record;
289
+ }
290
+ function standaloneLocation() {
291
+ const bundle = path5.resolve(path5.dirname(fileURLToPath(import.meta.url)), "../..");
292
+ const home = path5.dirname(path5.dirname(bundle));
293
+ if (path5.dirname(bundle) !== path5.join(home, "versions") || !/^[a-f0-9]{24}$/.test(path5.basename(bundle))) {
294
+ return null;
295
+ }
296
+ return { home, bundle };
297
+ }
298
+
299
+ // src/distribution/bundle.ts
300
+ import fs6 from "fs/promises";
301
+ import path6 from "path";
302
+ import { createHash as createHash2 } from "crypto";
303
+ import { z as z4 } from "zod";
304
+ var targets = ["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64", "win32-arm64", "win32-x64"];
305
+ var digest = z4.string().regex(/^[a-f0-9]{64}$/);
306
+ var bundleSchema = z4.object({
307
+ format: z4.literal(1),
308
+ version: z4.string().regex(/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/),
309
+ target: z4.enum(targets),
310
+ nodeVersion: z4.string(),
311
+ files: z4.record(digest)
312
+ }).strict();
313
+
314
+ // src/distribution/runtime.ts
315
+ var leaseSchema = z5.object({ pid: z5.number().int().positive(), host: z5.string(), bundle: z5.string().regex(/^[a-f0-9]{24}$/) });
316
+ async function registerRuntime() {
317
+ const location = standaloneLocation();
318
+ if (!location) return;
319
+ const { home, bundle } = location;
320
+ const name = `runtimes/${randomUUID3()}.json`;
321
+ await withLock(home, ".install-lock", async () => {
322
+ await readInstallation(home);
323
+ await fs7.access(bundle);
324
+ await writeStoreJson(home, name, { pid: process.pid, host: os4.hostname(), bundle: path7.basename(bundle) });
325
+ });
326
+ const file = await storePath(home, name);
327
+ process.once("exit", () => {
328
+ try {
329
+ unlinkSync(file);
330
+ } catch {
331
+ }
332
+ });
333
+ }
334
+ export {
335
+ registerRuntime
336
+ };
337
+ //# sourceMappingURL=mason-runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/distribution/runtime.ts","../src/automation/store.ts","../src/utils/store-lock.ts","../src/utils/storage.ts","../src/utils/paths.ts","../src/utils/git-read.ts","../src/utils/profile.ts","../src/utils/files.ts","../src/distribution/state.ts","../src/distribution/path.ts","../src/distribution/bundle.ts"],"sourcesContent":["import fs from \"node:fs/promises\";\nimport { unlinkSync } from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { withLock } from \"../automation/store.js\";\nimport { readStoreJson, storePath, writeStoreJson } from \"../utils/storage.js\";\nimport { readInstallation, standaloneLocation } from \"./state.js\";\nimport { verifyBundle } from \"./bundle.js\";\n\nconst leaseSchema = z.object({ pid: z.number().int().positive(), host: z.string(), bundle: z.string().regex(/^[a-f0-9]{24}$/) });\n\n/** Every standalone entry point registers before executing application code. */\nexport async function registerRuntime() {\n const location = standaloneLocation();\n if (!location) return;\n const { home, bundle } = location;\n const name = `runtimes/${randomUUID()}.json`;\n await withLock(home, \".install-lock\", async () => {\n await readInstallation(home);\n await fs.access(bundle);\n await writeStoreJson(home, name, { pid: process.pid, host: os.hostname(), bundle: path.basename(bundle) });\n });\n const file = await storePath(home, name);\n process.once(\"exit\", () => { try { unlinkSync(file); } catch { /* Stale leases are recovered by the next worker. */ } });\n}\n\n/** Caller holds the update lock, before staging starts; startup shares the install lock. */\nexport async function pruneUnusedVersions(home: string) {\n // Full bundle verification and recursive deletion can be slow. Keep them\n // outside the lock needed by commands and new MCP sessions.\n const versions = await storePath(home, \"versions\");\n const candidates: { id: string; directory: string; retired: boolean }[] = [];\n const initial = await readInstallation(home);\n const initialKeep = new Set([initial.current, initial.previous?.id, initial.pending?.id]);\n for (const name of await fs.readdir(versions)) {\n const retired = /^\\.retired-([a-f0-9]{24})-[a-f0-9-]+$/.exec(name);\n const id = retired?.[1] ?? name;\n if (!/^[a-f0-9]{24}$/.test(id) || initialKeep.has(id)) continue;\n try {\n const directory = await storePath(home, `versions/${name}`);\n await fs.access(await storePath(directory, \"app/dist/mason-runtime.js\"));\n const bundle = await verifyBundle(directory);\n if (bundle.manifestHash.slice(0, 24) === id && bundle.manifest.files[\"app/dist/mason-runtime.js\"])\n candidates.push({ id, directory, retired: !!retired });\n } catch { /* Legacy, edited, or unknown bundles remain untouched. */ }\n }\n if (!candidates.length) return;\n const garbage: string[] = [];\n await withLock(home, \".install-lock\", async () => {\n const record = await readInstallation(home);\n const keep = new Set([record.current, record.previous?.id, record.pending?.id]);\n const directory = await storePath(home, \"runtimes\");\n const leases = await fs.readdir(directory).catch(error => { if (error.code === \"ENOENT\") return []; throw error; });\n for (const name of leases) {\n if (!/^[a-f0-9-]+\\.json$/.test(name)) return;\n try {\n const raw = await readStoreJson(home, `runtimes/${name}`);\n if (raw === null) continue;\n const lease = leaseSchema.parse(raw);\n if (lease.host !== os.hostname()) return;\n try { process.kill(lease.pid, 0); keep.add(lease.bundle); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") return;\n await fs.rm(await storePath(home, `runtimes/${name}`), { force: true });\n }\n } catch { return; } // Uncertain process ownership means no deletion.\n }\n for (const candidate of candidates) {\n if (keep.has(candidate.id)) continue;\n try {\n const retired = candidate.retired ? candidate.directory\n : await storePath(home, `versions/.retired-${candidate.id}-${randomUUID()}`);\n if (!candidate.retired) await fs.rename(candidate.directory, retired);\n garbage.push(retired);\n } catch { /* Busy files remain available for the next check. */ }\n }\n });\n for (const directory of garbage) await fs.rm(directory, { recursive: true }).catch(() => {});\n}\n","import { z } from \"zod\";\nimport { withStoreLock } from \"../utils/store-lock.js\";\n\nexport const hostSchema = z.enum([\"claude\", \"codex\"]);\nexport type Host = z.infer<typeof hostSchema>;\nexport const events = [\"session_start\", \"turn_start\", \"before_tool\", \"after_tool\", \"task_end\"] as const;\nexport type Event = typeof events[number];\nexport const stateSchema = z.object({\n version: z.literal(1), root: z.string(), gitDir: z.string(), branch: z.string(),\n baselines: z.array(z.object({ path: z.string(), at: z.string(), event: z.string(), fingerprint: z.string() })).max(128),\n sessions: z.record(z.object({\n host: hostSchema, seen: z.string().nullable(), continued: z.boolean(),\n initialIssues: z.array(z.string()), initialDocs: z.record(z.string().nullable()),\n lastUsed: z.string(), mutationObserved: z.boolean(),\n pending: z.record(z.string()), coverageGaps: z.array(z.string()),\n events: z.record(z.object({ at: z.string(), count: z.number().int().positive() })),\n })),\n updatedAt: z.string(), fingerprint: z.string().nullable(),\n latest: z.string().nullable(),\n analysis: z.object({ id: z.string(), fingerprint: z.string(), completedAt: z.number(), path: z.string() }).optional(),\n});\nexport type State = z.infer<typeof stateSchema>;\nexport function parseState(raw: unknown): State {\n try { return stateSchema.parse(raw); }\n catch (error) { throw new Error(\"Invalid automation state; original evidence was retained.\", { cause: error }); }\n}\n\n/** Preserve the automation lock location and diagnostics for existing callers. */\nexport function withLock<T>(root: string, directory: string, run: () => Promise<T>, waitMs = 5000): Promise<T> {\n return withStoreLock(root, directory, run, waitMs, \"Automation\");\n}\n","import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport { storePath } from \"./storage.js\";\n\nasync function lockDiagnostic(file: string): Promise<string> {\n let reason: string;\n try {\n const owner = JSON.parse(await fs.readFile(file, \"utf8\"));\n if (!owner || typeof owner.host !== \"string\" || !Number.isInteger(owner.pid) || owner.pid <= 0) {\n reason = \"Lock owner data is incomplete or malformed.\";\n } else if (owner.host !== os.hostname()) {\n reason = \"The lock belongs to another host; its process cannot be checked locally.\";\n } else {\n try { process.kill(owner.pid, 0); reason = `Local owner PID ${owner.pid} is still running.`; }\n catch (error) {\n reason = (error as NodeJS.ErrnoException).code === \"ESRCH\"\n ? `Local owner PID ${owner.pid} has exited, but lock recovery has not completed.`\n : `Local owner PID ${owner.pid} could not be checked.`;\n }\n }\n } catch (error) {\n reason = error instanceof SyntaxError ? \"Lock owner data is incomplete or malformed.\" : \"Lock owner data could not be read; the lock may have changed.\";\n }\n if (await fs.lstat(file + \".reclaim\").then(() => true, () => false)) {\n reason += \" A recovery guard also needs inspection: \" + file + \".reclaim.\";\n }\n return reason + \" Retry if a writer is active. For manual recovery, stop all Mason writers for this checkout, confirm they have exited (including other hosts), then remove only confirmed abandoned lock and lock.reclaim files. See docs/reference.md#snapshot-repairs-and-verification.\";\n}\n\n/** Cross-process lock: a killed writer's lock is reclaimed only after its local PID is gone. */\nexport async function withStoreLock<T>(root: string, directory: string, run: () => Promise<T>, waitMs = 5000, label = \"Mason store\"): Promise<T> {\n const file = await storePath(root, directory + \"/lock\", true);\n const deadline = Date.now() + waitMs;\n let handle;\n while (!handle) {\n try {\n handle = await fs.open(file, \"wx\", 0o600);\n try { await handle.writeFile(JSON.stringify({ pid: process.pid, host: os.hostname() })); }\n catch (error) {\n await handle.close().catch(() => {});\n handle = undefined;\n await fs.rm(file, { force: true }).catch(() => {});\n throw error;\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n // Do not steal malformed, remote, or live locks on a time-based guess.\n try {\n const owner = JSON.parse(await fs.readFile(file, \"utf8\"));\n if (owner.host === os.hostname() && Number.isInteger(owner.pid) && owner.pid > 0) {\n try { process.kill(owner.pid, 0); }\n catch (probe) {\n if ((probe as NodeJS.ErrnoException).code === \"ESRCH\") {\n // A separate guard arbitrates reclamation; recheck the owner before unlinking.\n const reclaim = file + \".reclaim\";\n let guard;\n try {\n guard = await fs.open(reclaim, \"wx\", 0o600);\n const current = JSON.parse(await fs.readFile(file, \"utf8\"));\n if (current.pid === owner.pid && current.host === owner.host) await fs.unlink(file);\n } finally { if (guard) { await guard.close(); await fs.rm(reclaim, { force: true }); } }\n }\n }\n }\n } catch { /* Another writer may be creating/releasing/reclaiming it. */ }\n if (Date.now() >= deadline) throw new Error(label + \" is busy or its lock needs inspection: \" + file + \". \" + await lockDiagnostic(file));\n await new Promise(resolve => setTimeout(resolve, 40));\n }\n }\n try { return await run(); }\n finally { await handle.close(); await fs.unlink(file); }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { normalizeRepoPath } from \"./paths.js\";\nimport { readBoundedFile } from \"./files.js\";\n\nexport interface StoreDiagnostic { path: string; message: string }\n\n/** Metadata paths may not contain symlinks, including their parent directories. */\nexport async function storePath(root: string, relative: string, createParents = false): Promise<string> {\n const normalized = normalizeRepoPath(relative);\n if (!normalized) throw new Error(`Invalid store path: ${relative}`);\n let current = await fs.realpath(root);\n const parts = normalized.split(\"/\");\n for (let i = 0; i < parts.length; i++) {\n current = path.join(current, parts[i]);\n let stat;\n try { stat = await fs.lstat(current); } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n if (createParents && i < parts.length - 1) {\n try { await fs.mkdir(current); } catch (mkdirError) {\n if ((mkdirError as NodeJS.ErrnoException).code !== \"EEXIST\") throw mkdirError;\n }\n stat = await fs.lstat(current);\n }\n }\n if (stat?.isSymbolicLink()) throw new Error(`Symlink in store path: ${relative}`);\n }\n return current;\n}\n\nexport async function readStoreJson(root: string, relative: string): Promise<unknown | null> {\n try {\n const file = await storePath(root, relative);\n const raw = await readBoundedFile(file, 10 * 1024 * 1024);\n if (raw === null) throw new Error(\"file is not regular or exceeds 10 MiB\");\n const parsed: unknown = JSON.parse(raw);\n if (parsed === null) throw new Error(\"expected a JSON object, received null\");\n return parsed;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw new Error(`Invalid Mason store ${relative}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n}\n\nexport async function writeStoreJson(root: string, relative: string, value: unknown): Promise<void> {\n const payload = JSON.stringify(value, null, 2) + \"\\n\";\n if (Buffer.byteLength(payload) > 10 * 1024 * 1024) {\n throw new Error(`Mason store ${relative} exceeds 10 MiB`);\n }\n const file = await storePath(root, relative, true);\n const temporary = path.join(path.dirname(file), `.${path.basename(file)}.${randomUUID()}.tmp`);\n try {\n const handle = await fs.open(temporary, \"wx\", 0o600);\n try { await handle.writeFile(payload, \"utf8\"); await handle.sync(); }\n finally { await handle.close(); }\n await fs.rename(temporary, file);\n } finally { await fs.rm(temporary, { force: true }); }\n}\n","import path from \"node:path\";\n\n/** One canonical representation for stored paths and decision anchors. */\nexport function normalizeRepoPath(value: string): string | null {\n const slash = value.replace(/\\\\/g, \"/\");\n if (!slash || slash.includes(\"\\0\") || path.posix.isAbsolute(slash) || /^[A-Za-z]:/.test(slash)) return null;\n if (slash.split(\"/\").includes(\"..\")) return null;\n const normalized = path.posix.normalize(slash).replace(/\\/$/, \"\");\n return normalized === \".\" ? null : normalized;\n}\n\nexport function sanitizeRepoPaths(files: string[]): string[] {\n return [...new Set(files.map(normalizeRepoPath).filter((p): p is string => p !== null))];\n}\n\nexport function isWithinRoot(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative !== \"..\" && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);\n}\n\nexport function anchorMatches(anchor: string, file: string): boolean {\n const a = normalizeRepoPath(anchor);\n const f = normalizeRepoPath(file);\n return a !== null && f !== null && (a === f || f.startsWith(`${a}/`));\n}\n\nexport function matchingPaths(anchors: string[], files: Iterable<string>): string[] {\n return [...new Set(files)].filter(file => anchors.some(anchor => anchorMatches(anchor, file)));\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { profilePhase } from \"./profile.js\";\n\nconst execute = promisify(execFile);\nconst commands = new Set([\"rev-parse\", \"symbolic-ref\", \"for-each-ref\", \"ls-files\", \"check-ignore\", \"status\", \"log\", \"diff\", \"ls-tree\", \"show\", \"merge-base\"]);\nexport interface GitReadOptions { cwd: string; maxBuffer?: number; timeout?: number; input?: string }\n\n/** Fixed command labels only: profiling never includes arguments or repository paths. */\nexport function execGit(args: string[], options: GitReadOptions) {\n const command = args.find(arg => !arg.startsWith(\"-\")) ?? \"other\";\n return profilePhase(\"git.\" + (commands.has(command) ? command : \"other\"), async () => {\n const { input, ...processOptions } = options;\n const operation = execute(\"git\", args, processOptions);\n if (input !== undefined) {\n operation.child.stdin!.on(\"error\", () => { /* The child exit reports a failed query. */ });\n operation.child.stdin!.end(input);\n }\n return operation;\n });\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\ntype Timing = { calls: number; totalMs: number };\nconst profiles = new AsyncLocalStorage<Record<string, Timing>>();\n\n/** Opt-in, invocation-local timings. Labels are fixed in source; no repository data. */\nexport async function profilePhase<T>(label: string, run: () => Promise<T>): Promise<T> {\n const phases = profiles.getStore();\n if (!phases) return run();\n const start = performance.now();\n try { return await run(); }\n finally {\n const timing = phases[label] ??= { calls: 0, totalMs: 0 };\n timing.calls++;\n timing.totalMs += performance.now() - start;\n }\n}\n\nexport async function withProfile<T>(run: () => Promise<T>, emit: (json: string) => void): Promise<T> {\n const phases: Record<string, Timing> = {};\n const start = performance.now();\n return profiles.run(phases, async () => {\n try { return await run(); }\n finally {\n emit(JSON.stringify({ kind: \"mason-profile\", version: 1, totalMs: performance.now() - start, phases }));\n }\n });\n}\n","import { execGit } from \"./git-read.js\";\nimport fs from \"node:fs/promises\";\nimport { constants } from \"node:fs\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport { isWithinRoot, normalizeRepoPath } from \"./paths.js\";\n\nexport const SOURCE_EXTENSIONS = [\"ts\", \"tsx\", \"js\", \"jsx\", \"mts\", \"cts\", \"mjs\", \"cjs\", \"vue\", \"svelte\", \"kt\", \"kts\", \"java\", \"py\", \"go\", \"rs\", \"swift\", \"rb\", \"cs\", \"cpp\", \"c\", \"h\", \"hpp\", \"dart\", \"php\"];\nexport const SOURCE_GLOB = `**/*.{${SOURCE_EXTENSIONS.join(\",\")}}`;\nexport const SOURCE_IGNORE = [\n \"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \"**/.gradle/**\",\n \"**/target/**\", \"**/.git/**\", \"**/.mason/**\", \"**/vendor/**\", \"**/__pycache__/**\",\n \"**/venv/**\", \"**/.venv/**\", \"**/*.min.*\", \"**/*.map\", \"**/*.lock\",\n \"**/generated/**\", \"**/*.generated.*\", \"**/R.java\", \"**/BuildConfig.java\",\n \"**/package-lock.json\", \"**/yarn.lock\", \"**/pnpm-lock.yaml\",\n];\nexport const MAX_SOURCE_BYTES = 1024 * 1024;\nexport interface ProjectConfig { patterns?: string[]; alwaysInclude?: string[]; ignore?: string[] }\nexport interface SourceFile { path: string; content: string; totalLines: number }\n\nexport function isSensitiveFile(file: string): boolean {\n return file.split(/[\\\\/]/).some(part =>\n /^(?:\\.env(?:\\..*)?|id_rsa.*|id_ed25519.*)$|\\.(?:pem|key|p12|pfx|jks|keystore)$|credentials\\.|secret|^local\\.properties$/i.test(part)\n );\n}\n\n/** Bound reads even if a file grows after stat. Only read regular files. */\nexport async function readBoundedFile(file: string, maxBytes: number): Promise<string | null> {\n // Do not block on a FIFO or follow a symlink substituted after resolution.\n const handle = await fs.open(file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);\n try {\n const stat = await handle.stat();\n if (!stat.isFile() || stat.size > maxBytes) return null;\n const buffer = Buffer.alloc(Math.min(maxBytes + 1, stat.size + 1));\n let bytes = 0;\n while (bytes < buffer.length) {\n const result = await handle.read(buffer, bytes, buffer.length - bytes, null);\n if (result.bytesRead === 0) break;\n bytes += result.bytesRead;\n }\n return bytes === buffer.length ? null : buffer.subarray(0, bytes).toString(\"utf8\");\n } finally { await handle.close(); }\n}\n\nexport async function loadProjectConfig(root: string): Promise<ProjectConfig> {\n try {\n const canonicalRoot = await fs.realpath(root);\n const configPath = await fs.realpath(path.join(root, \".mason/config.json\"));\n if (!isWithinRoot(canonicalRoot, configPath)) throw new Error(\"Project configuration resolves outside the repository\");\n const raw = await readBoundedFile(configPath, 64 * 1024);\n if (raw === null) throw new Error(\"Project configuration is not a regular file or exceeds 64 KiB\");\n const value = JSON.parse(raw);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Expected a configuration object\");\n const config: ProjectConfig = {};\n for (const key of [\"patterns\", \"alwaysInclude\", \"ignore\"] as const) {\n if (value[key] === undefined) continue;\n if (!Array.isArray(value[key]) || !value[key].every((s: unknown) => typeof s === \"string\")) {\n throw new Error(`Configuration ${key} must be an array of strings`);\n }\n config[key] = value[key];\n }\n return config;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return {};\n throw new Error(`Cannot apply project file policy: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/** Scoped to one operation, so a later tool call sees newly edited files/ignores. */\nexport async function createFileAccess(rootDir: string) {\n const root = path.resolve(rootDir);\n const canonicalRoot = await fs.realpath(root).catch(() => root);\n const config = await loadProjectConfig(root);\n const ignore = [...SOURCE_IGNORE, ...(config.ignore ?? [])];\n let gitFiles: Set<string> | null = null;\n try {\n const { stdout } = await execGit([\"ls-files\", \"-z\", \"--cached\", \"--others\", \"--exclude-standard\"], { cwd: root, maxBuffer: 50 * 1024 * 1024 });\n gitFiles = new Set(stdout.split(\"\\0\").filter(Boolean));\n } catch {\n // File-system projects are supported. Fail closed if this IS a Git repo.\n let inGit = false;\n try { await execGit([\"rev-parse\", \"--git-dir\"], { cwd: root }); inGit = true; } catch { /* no Git */ }\n if (inGit) throw new Error(\"Cannot enumerate Git files safely\");\n }\n\n async function resolve(file: string): Promise<string | null> {\n const relative = normalizeRepoPath(file);\n if (!relative || isSensitiveFile(relative) || (gitFiles && !gitFiles.has(relative))) return null;\n const candidate = path.join(root, relative);\n try {\n const real = await fs.realpath(candidate);\n if (!isWithinRoot(canonicalRoot, real) || isSensitiveFile(path.relative(canonicalRoot, real))) return null;\n const stat = await fs.stat(real);\n if (!stat.isFile() || stat.size > MAX_SOURCE_BYTES) return null;\n // A symlink must not bypass the target's ignore policy either.\n if (gitFiles && !gitFiles.has(path.relative(canonicalRoot, real).split(path.sep).join(\"/\"))) return null;\n return real;\n } catch { return null; }\n }\n\n async function list(patterns: string | string[] = SOURCE_GLOB, options: { deep?: number; dot?: boolean } = {}): Promise<string[]> {\n const found = await fg(patterns, { cwd: root, ignore, followSymbolicLinks: false, ...options });\n const safe = await Promise.all(found.map(async f => (await resolve(f)) ? f : null));\n return safe.filter((f): f is string => f !== null).sort();\n }\n\n async function read(file: string): Promise<SourceFile | null> {\n const relative = normalizeRepoPath(file);\n if (!relative) return null;\n const real = await resolve(relative);\n if (!real) return null;\n // Apply the same glob exclusions to explicit reads and symlink targets.\n for (const rel of new Set([relative, path.relative(canonicalRoot, real).split(path.sep).join(\"/\")])) {\n if (!(await fg(fg.escapePath(rel), { cwd: root, ignore, dot: true })).length) return null;\n }\n try {\n const content = await readBoundedFile(real, MAX_SOURCE_BYTES);\n return content === null ? null : { path: relative, content, totalLines: content.split(\"\\n\").length };\n } catch { return null; }\n }\n return { root, config, list, read };\n}\n","import os from \"node:os\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport fs from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { readStoreJson } from \"../utils/storage.js\";\nimport { pathChangeSchema } from \"./path.js\";\n\nexport const releaseVersion = z.string().regex(/^\\d+\\.\\d+\\.\\d+(?:-[A-Za-z0-9.-]+)?$/);\nconst bundleId = z.string().regex(/^[a-f0-9]{24}$/);\nexport const updatePolicySchema = z.object({\n enabled: z.boolean(), revision: z.string(), pinnedVersion: releaseVersion.optional(), mirror: z.string().optional(),\n});\nexport const recordSchema = z.object({\n format: z.literal(1), home: z.string(), bin: z.string(), current: bundleId, version: releaseVersion,\n launchers: z.record(z.string()), previousLaunchers: z.record(z.string()).optional(),\n pathChanges: z.array(pathChangeSchema).optional(), updates: updatePolicySchema.optional(),\n previous: z.object({ id: bundleId, version: releaseVersion }).optional(),\n pending: z.object({ id: bundleId, version: releaseVersion, policyRevision: z.string() }).optional(),\n});\nexport type InstallRecord = z.infer<typeof recordSchema>;\nexport const defaultHome = () => process.env.MASON_HOME ?? (process.platform === \"win32\"\n ? path.join(process.env.LOCALAPPDATA ?? os.homedir(), \"Mason\") : path.join(os.homedir(), \".local/share/mason\"));\n\nexport async function readInstallation(home: string): Promise<InstallRecord> {\n const raw = await readStoreJson(home, \"install.json\");\n if (!raw) throw new Error(\"Run this command from a standalone installation. npm users can upgrade with npm.\");\n const record = recordSchema.parse(raw);\n if (record.home !== await fs.realpath(home)) throw new Error(\"Invalid standalone installation receipt.\");\n return record;\n}\n\nexport function standaloneLocation() {\n // Distribution modules are bundled into app/dist/mason.js (or mason-mcp.js).\n const bundle = path.resolve(path.dirname(fileURLToPath(import.meta.url)), \"../..\");\n const home = path.dirname(path.dirname(bundle));\n if (path.dirname(bundle) !== path.join(home, \"versions\") || !/^[a-f0-9]{24}$/.test(path.basename(bundle))) {\n return null;\n }\n return { home, bundle };\n}\n\nexport async function currentInstallation() {\n const location = standaloneLocation();\n if (!location) throw new Error(\"Run this command from a standalone installation. npm users can upgrade with npm.\");\n const { home, bundle } = location;\n const record = await readInstallation(home);\n return { home, bundle, record };\n}\n\nexport function automaticUpdatesAllowed(record: InstallRecord, env: NodeJS.ProcessEnv = process.env): boolean {\n return record.updates?.enabled === true && !record.updates.pinnedVersion && !record.updates.mirror\n && !env.CI && env.MASON_NO_AUTO_UPDATE !== \"1\" && !env.MASON_RELEASE_BASE && !env.MASON_VERSION;\n}\n\n/** Automatic updates accept stable releases only and never downgrade. */\nexport function newerStableVersion(candidate: string, installed: string): boolean {\n if (!/^\\d+\\.\\d+\\.\\d+$/.test(candidate)) return false;\n const a = candidate.split(\".\").map(BigInt), b = installed.split(\"-\")[0].split(\".\").map(BigInt);\n for (let i = 0; i < 3; i++) { if (a[i] !== b[i]) return a[i] > b[i]; }\n return installed.includes(\"-\");\n}\n","import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\n\nconst execute = promisify(execFile);\nexport const pathChangeSchema = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"profile\"), file: z.string(), block: z.string(), created: z.boolean() }),\n z.object({ kind: z.literal(\"windows\"), entry: z.string(), created: z.boolean() }),\n]);\nexport type PathChange = z.infer<typeof pathChangeSchema>;\nexport type PathResult = { status: \"configured\" | \"manual\"; message: string; changes: PathChange[] };\nexport type PathOptions = { platform?: NodeJS.Platform; userHome?: string; env?: NodeJS.ProcessEnv };\nconst quote = (s: string) => \"'\" + s.replace(/'/g, \"'\\\\''\") + \"'\";\n\n// Store the ownership intent before changing settings, so interrupted installs\n// can resume and uninstall can distinguish our addition from existing settings.\nexport async function configurePath(bin: string, previous: PathChange[], save: (changes: PathChange[]) => Promise<void>, options: PathOptions = {}): Promise<PathResult> {\n const env = options.env ?? process.env, platform = options.platform ?? process.platform;\n const changes = [...previous];\n // Profile/registry changes affect future shells. The inherited PATH tells us\n // whether this terminal already has the installation directory available.\n const currentPath = platform === \"win32\" ? Object.entries(env).find(([key]) => key.toLowerCase() === \"path\")?.[1] : env.PATH;\n const alreadyOnPath = platform === \"win32\" ? hasWindowsEntry(currentPath ?? null, bin, env)\n : (currentPath ?? \"\").split(\":\").some(entry => path.posix.isAbsolute(entry) && path.posix.resolve(entry) === path.posix.resolve(bin));\n const setupHint = \"To connect a project, run one of these inside its directory:\\n Codex: mason setup --host codex\\n Claude Code: mason setup --host claude\";\n const message = (alreadyOnPath ? \"\" : \"Open a new terminal to use mason.\\n\") + setupHint;\n const manual = (reason: string): PathResult => ({ status: \"manual\", changes, message: `${reason}\\n${alreadyOnPath ? \"\" : `Add ${bin} to your PATH.\\n`}${setupHint}` });\n if (env.MASON_NO_MODIFY_PATH === \"1\") return manual(\"Automatic PATH setup is disabled (MASON_NO_MODIFY_PATH=1).\");\n if (/[\\r\\n\\0]/.test(bin) || bin.includes(platform === \"win32\" ? \";\" : \":\")) return manual(\"This installation path cannot be represented safely in PATH.\");\n try {\n if (platform === \"win32\") {\n const current = await windowsPath(\"read\");\n if (!hasWindowsEntry(current.value, bin)) {\n if (!changes.some(c => c.kind === \"windows\" && c.entry === bin)) {\n changes.push({ kind: \"windows\", entry: bin, created: current.value === null }); await save(changes);\n }\n await windowsPath(\"add\", bin, current);\n }\n return { status: \"configured\", changes, message };\n }\n const shell = path.basename(env.SHELL ?? os.userInfo().shell ?? \"\");\n const userHome = options.userHome ?? os.homedir();\n let profiles: string[];\n if (![\"bash\", \"zsh\", \"sh\"].includes(shell)) return manual(`Automatic PATH setup is unavailable for ${shell || \"an unknown shell\"}.`);\n if (env.MASON_PROFILE) profiles = [path.resolve(env.MASON_PROFILE)];\n else if (shell === \"zsh\") profiles = [path.join(env.ZDOTDIR || userHome, \".zshrc\")];\n else if (shell === \"sh\") profiles = [path.join(userHome, \".profile\")];\n else {\n const candidates = [\".bash_profile\", \".bash_login\", \".profile\"].map(name => path.join(userHome, name));\n let login = candidates[2];\n for (const file of candidates) if (await fs.lstat(file).then(() => true, error => { if (error.code === \"ENOENT\") return false; throw error; })) { login = file; break; }\n profiles = [path.join(userHome, \".bashrc\"), login];\n }\n const marker = `# >>> mason PATH ${createHash(\"sha256\").update(bin).digest(\"hex\").slice(0, 12)} >>>`;\n for (const profile of profiles) {\n // Preserve symlinked dotfiles by updating their target. A dangling link is\n // an error, not permission to replace the link with an unrelated file.\n const stat = await fs.lstat(profile).catch(error => { if (error.code === \"ENOENT\") return null; throw error; });\n const file = stat?.isSymbolicLink() ? await fs.realpath(profile) : path.resolve(profile);\n const original = await fs.readFile(file).catch(error => { if (error.code === \"ENOENT\" && !stat) return null; throw error; });\n if (original && !Buffer.from(original.toString(\"utf8\")).equals(original)) return manual(`Shell profile is not UTF-8: ${profile}.`);\n const text = original?.toString(\"utf8\") ?? \"\";\n const owned = changes.find((c): c is Extract<PathChange, { kind: \"profile\" }> => c.kind === \"profile\" && c.file === file);\n if (owned && text.includes(owned.block)) continue;\n if (text.includes(marker) || (owned && text.includes(\"# <<< mason PATH\"))) return manual(`Mason's PATH block was edited; retained ${profile}.`);\n const newline = text.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const block = owned?.block ?? (\"\\n\" + marker + \"\\ncase \\\":${PATH-}:\\\" in\\n *:\" + quote(bin) + \":*) ;;\\n *) export PATH=\" + quote(bin) + \":\\\"${PATH-}\\\" ;;\\nesac\\n# <<< mason PATH <<<\\n\").replaceAll(\"\\n\", newline);\n if (!owned) { changes.push({ kind: \"profile\", file, block, created: original === null }); await save(changes); }\n await fs.mkdir(path.dirname(file), { recursive: true });\n // Append without rewriting existing bytes, modes or symlinks. Recheck the\n // bytes on the opened file to detect edits since the preflight read.\n const handle = await fs.open(file, original === null ? \"ax+\" : \"a+\", 0o600);\n try {\n if (!(await handle.readFile()).equals(original ?? Buffer.alloc(0))) throw new Error(`Shell profile changed during installation: ${profile}`);\n await handle.writeFile(block); await handle.sync();\n } finally { await handle.close(); }\n }\n return { status: \"configured\", changes, message };\n } catch (error) { return manual(`Could not configure PATH: ${error instanceof Error ? error.message : String(error)}`); }\n}\n\nexport async function removePath(changes: PathChange[]): Promise<string[]> {\n const warnings: string[] = [];\n for (const change of changes) {\n try {\n if (change.kind === \"windows\") {\n const current = await windowsPath(\"read\");\n if (!(current.value ?? \"\").split(\";\").includes(change.entry) && hasWindowsEntry(current.value, change.entry)) throw new Error(\"PATH entry was edited\");\n await windowsPath(\"remove\", change.entry, current, change.created); continue;\n }\n const stat = await fs.lstat(change.file).catch(error => { if (error.code === \"ENOENT\") return null; throw error; });\n if (!stat) continue;\n if (!stat.isFile()) throw new Error(\"profile type changed\");\n const bytes = await fs.readFile(change.file), text = bytes.toString(\"utf8\");\n if (!Buffer.from(text).equals(bytes)) throw new Error(\"profile encoding changed\");\n const index = text.indexOf(change.block);\n if (index < 0 || text.indexOf(change.block, index + change.block.length) >= 0) throw new Error(\"PATH block was edited or removed\");\n const prefix = text.slice(0, index), suffix = text.slice(index + change.block.length);\n const separator = prefix && suffix && !prefix.endsWith(\"\\n\") ? (change.block.startsWith(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\") : \"\";\n const next = Buffer.from(prefix + separator + suffix);\n const temporary = change.file + \".mason-\" + randomUUID();\n try {\n if (stat.nlink > 1) throw new Error(\"profile has multiple hard links\");\n const handle = await fs.open(temporary, \"wx\", stat.mode & 0o777);\n try {\n await handle.writeFile(next); await handle.chmod(stat.mode & 0o777);\n if (process.platform !== \"win32\") await handle.chown(stat.uid, stat.gid);\n await handle.sync();\n } finally { await handle.close(); }\n const current = await fs.lstat(change.file);\n if (!current.isFile() || current.ino !== stat.ino || !(await fs.readFile(change.file)).equals(bytes)) throw new Error(\"profile changed during uninstall\");\n await fs.rename(temporary, change.file);\n } finally { await fs.rm(temporary, { force: true }); }\n // Empty created profiles are harmless; retain them to avoid masking any\n // dotfile another process created or linked since installation.\n } catch (error) { warnings.push(`Retained PATH setting ${change.kind === \"profile\" ? change.file : change.entry}: ${error instanceof Error ? error.message : String(error)}`); }\n }\n return warnings;\n}\n\nexport type WindowsPath = { value: string | null; kind: string | null };\nconst normalizeWindowsEntry = (value: string) => path.win32.normalize(value.trim().replace(/^\"(.*)\"$/, \"$1\")).replace(/[\\\\/]+$/, \"\").toLowerCase();\nexport const hasWindowsEntry = (value: string | null, entry: string, env: NodeJS.ProcessEnv = process.env) => {\n const variables = new Map(Object.entries(env).map(([key, value]) => [key.toLowerCase(), value]));\n const expand = (part: string) => part.replace(/%([^%]+)%/g, (match, key: string) => variables.get(key.toLowerCase()) ?? match);\n return (value ?? \"\").split(\";\").some(part => normalizeWindowsEntry(expand(part)) === normalizeWindowsEntry(entry));\n};\n\n// Read unexpanded registry text and preserve its value kind. No machine PATH,\n// setx truncation, or expanded copy of the process environment is written.\nexport async function windowsPath(action: \"read\" | \"add\" | \"remove\", entry = \"\", expected?: WindowsPath, removeEmpty = false): Promise<WindowsPath> {\n const payload = Buffer.from(JSON.stringify({ action, entry, expected, removeEmpty })).toString(\"base64\");\n const script = `$ErrorActionPreference = 'Stop'\n[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)\n$p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${payload}')) | ConvertFrom-Json\n$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')\ntry {\n $value = $key.GetValue('Path', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)\n $kind = if ($null -eq $value) { $null } else { $key.GetValueKind('Path').ToString() }\n if ($null -ne $kind -and $kind -notin @('String','ExpandString')) { throw 'User PATH is not a string.' }\n if ($p.action -eq 'read') { @{ value = $value; kind = $kind } | ConvertTo-Json -Compress; exit 0 }\n if ($p.expected -and ($value -cne $p.expected.value -or $kind -cne $p.expected.kind)) { throw 'User PATH changed concurrently; retry the operation.' }\n $parts = if ($null -eq $value -or $value -eq '') { @() } else { @($value.Split(';')) }\n if ($p.action -eq 'add') { $next = (@($p.entry) + $parts) -join ';' }\n else { $next = (@($parts | Where-Object { $_ -cne $p.entry })) -join ';' }\n if ($next -cne $value) {\n $writeKind = if ($kind) { [Microsoft.Win32.RegistryValueKind]$kind } else { [Microsoft.Win32.RegistryValueKind]::ExpandString }\n if ($p.action -eq 'remove' -and $p.removeEmpty -and $next -eq '') { $key.DeleteValue('Path', $false) }\n else { $key.SetValue('Path', $next, $writeKind) }\n Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class MasonEnvironment { [DllImport(\"user32.dll\", CharSet=CharSet.Unicode, SetLastError=true)] public static extern IntPtr SendMessageTimeout(IntPtr h, uint m, UIntPtr w, string l, uint f, uint t, out UIntPtr r); }'\n $result = [UIntPtr]::Zero\n [void][MasonEnvironment]::SendMessageTimeout([IntPtr]0xffff, 0x1a, [UIntPtr]::Zero, 'Environment', 2, 1000, [ref]$result)\n }\n @{ value = $next; kind = $kind } | ConvertTo-Json -Compress\n} finally { $key.Dispose() }\n`;\n const { stdout } = await execute(\"powershell.exe\", [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-EncodedCommand\", Buffer.from(script, \"utf16le\").toString(\"base64\")], { windowsHide: true, timeout: 15000, maxBuffer: 1024 * 1024 });\n return JSON.parse(stdout.replace(/^\\uFEFF/, \"\").trim());\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { storePath } from \"../utils/storage.js\";\n\nexport const targets = [\"darwin-arm64\", \"darwin-x64\", \"linux-arm64\", \"linux-x64\", \"win32-arm64\", \"win32-x64\"] as const;\nconst digest = z.string().regex(/^[a-f0-9]{64}$/);\nexport const bundleSchema = z.object({\n format: z.literal(1), version: z.string().regex(/^\\d+\\.\\d+\\.\\d+(?:-[A-Za-z0-9.-]+)?$/),\n target: z.enum(targets), nodeVersion: z.string(), files: z.record(digest),\n}).strict();\nexport const sha256 = (bytes: Buffer | string) => createHash(\"sha256\").update(bytes).digest(\"hex\");\n\nexport async function readBundle(root: string) {\n const bytes = await fs.readFile(await storePath(root, \"bundle.json\"));\n const manifest = bundleSchema.parse(JSON.parse(bytes.toString(\"utf8\")));\n const windows = manifest.target.startsWith(\"win32-\");\n for (const file of Object.keys(manifest.files)) {\n if (file.includes(\"\\\\\") || file.split(\"/\").some(p => !p || p === \".\" || p === \"..\") || path.isAbsolute(file)) {\n throw new Error(\"Unsafe path in Mason bundle: \" + file);\n }\n }\n for (const required of [windows ? \"node.exe\" : \"node\", \"app/package.json\", \"app/dist/mason.js\", \"app/dist/mason-auto.js\", \"app/dist/mason-mcp.js\"]) {\n if (!manifest.files[required]) throw new Error(\"Incomplete Mason bundle: \" + required);\n }\n return { manifest, manifestHash: sha256(bytes) };\n}\n\n/** Verify every shipped file before copying or selecting a standalone distribution. */\nexport async function verifyBundle(root: string, expectedHash?: string) {\n const bundle = await readBundle(root);\n if (expectedHash && bundle.manifestHash !== expectedHash) throw new Error(\"Mason bundle manifest changed.\");\n if (bundle.manifest.target !== `${process.platform}-${process.arch}`) throw new Error(\"Mason bundle is for another platform. Install this platform's bundle and rerun setup.\");\n const files = Object.keys(bundle.manifest.files);\n // Bound concurrent reads; Node itself is a large file.\n for (let i = 0; i < files.length; i += 8) await Promise.all(files.slice(i, i + 8).map(async file => {\n if (sha256(await fs.readFile(await storePath(root, file))) !== bundle.manifest.files[file]) throw new Error(\"Mason bundle checksum mismatch: \" + file);\n }));\n return bundle;\n}\n"],"mappings":";;;;AAAA,OAAOA,SAAQ;AACf,SAAS,kBAAkB;AAC3B,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,KAAAC,UAAS;;;ACLlB,SAAS,SAAS;;;ACAlB,OAAOC,SAAQ;AACf,OAAO,QAAQ;;;ACDf,OAAOC,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,kBAAkB;;;ACF3B,OAAO,UAAU;AAGV,SAAS,kBAAkB,OAA8B;AAC9D,QAAM,QAAQ,MAAM,QAAQ,OAAO,GAAG;AACtC,MAAI,CAAC,SAAS,MAAM,SAAS,IAAI,KAAK,KAAK,MAAM,WAAW,KAAK,KAAK,aAAa,KAAK,KAAK,EAAG,QAAO;AACvG,MAAI,MAAM,MAAM,GAAG,EAAE,SAAS,I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AS,MAAM,iBAAiB,YAAY;AAChD,UAAM,iBAAiB,IAAI;AAC3B,UAAMC,IAAG,OAAO,MAAM;AACtB,UAAM,eAAe,MAAM,MAAM,EAAE,KAAK,QAAQ,KAAK,MAAMC,IAAG,SAAS,GAAG,QAAQC,MAAK,SAAS,MAAM,EAAE,CAAC;AAAA,EAC3G,CAAC;AACD,QAAM,OAAO,MAAM,UAAU,MAAM,IAAI;AACvC,UAAQ,KAAK,QAAQ,MAAM;AAAE,QAAI;AAAE,iBAAW,IAAI;AAAA,IAAG,QAAQ;AAAA,IAAuD;AAAA,EAAE,CAAC;AACzH;","names":["fs","os","path","randomUUID","z","fs","fs","path","path","fs","path","fs","os","path","fs","z","fs","os","path","execFile","promisify","randomUUID","z","execute","z","fs","path","fs","path","createHash","z","z","z","randomUUID","fs","os","path"]}