@murmurv2/cli 2.12.0 → 2.14.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.
Files changed (64) hide show
  1. package/README.md +65 -24
  2. package/package.json +7 -6
  3. package/runtime/bin/murmur-svc.exe +0 -0
  4. package/runtime/npm-runtime-manifest.json +175 -79
  5. package/runtime/package.json +1 -1
  6. package/runtime/packages/mcp-server/dist/src/agent-config.js +1 -0
  7. package/runtime/packages/setup/bin/murmur.mjs +3 -2
  8. package/runtime/packages/setup/dist/src/autoreply.d.ts +23 -0
  9. package/runtime/packages/setup/dist/src/autoreply.js +71 -0
  10. package/runtime/packages/setup/dist/src/backups.d.ts +36 -0
  11. package/runtime/packages/setup/dist/src/backups.js +128 -0
  12. package/runtime/packages/setup/dist/src/broker-input.d.ts +24 -0
  13. package/runtime/packages/setup/dist/src/broker-input.js +98 -0
  14. package/runtime/packages/setup/dist/src/broker-migration.d.ts +35 -0
  15. package/runtime/packages/setup/dist/src/broker-migration.js +138 -0
  16. package/runtime/packages/setup/dist/src/cli-error.d.ts +2 -0
  17. package/runtime/packages/setup/dist/src/cli-error.js +30 -0
  18. package/runtime/packages/setup/dist/src/cli.js +113 -10
  19. package/runtime/packages/setup/dist/src/clients.d.ts +33 -81
  20. package/runtime/packages/setup/dist/src/clients.js +159 -25
  21. package/runtime/packages/setup/dist/src/commands.d.ts +1 -0
  22. package/runtime/packages/setup/dist/src/commands.js +18 -6
  23. package/runtime/packages/setup/dist/src/config.d.ts +8 -0
  24. package/runtime/packages/setup/dist/src/config.js +58 -10
  25. package/runtime/packages/setup/dist/src/connect.d.ts +143 -0
  26. package/runtime/packages/setup/dist/src/connect.js +128 -0
  27. package/runtime/packages/setup/dist/src/conversations.d.ts +193 -0
  28. package/runtime/packages/setup/dist/src/conversations.js +674 -0
  29. package/runtime/packages/setup/dist/src/doctor.d.ts +30 -0
  30. package/runtime/packages/setup/dist/src/doctor.js +72 -10
  31. package/runtime/packages/setup/dist/src/installation.d.ts +25 -0
  32. package/runtime/packages/setup/dist/src/installation.js +89 -0
  33. package/runtime/packages/setup/dist/src/message-status.d.ts +1 -0
  34. package/runtime/packages/setup/dist/src/message-status.js +3 -0
  35. package/runtime/packages/setup/dist/src/onboarding.d.ts +11 -6
  36. package/runtime/packages/setup/dist/src/onboarding.js +92 -21
  37. package/runtime/packages/setup/dist/src/paths.d.ts +7 -0
  38. package/runtime/packages/setup/dist/src/paths.js +39 -24
  39. package/runtime/packages/setup/dist/src/platform/darwin.d.ts +3 -0
  40. package/runtime/packages/setup/dist/src/platform/darwin.js +247 -9
  41. package/runtime/packages/setup/dist/src/platform/linux.js +156 -12
  42. package/runtime/packages/setup/dist/src/platform/profile-usage.d.ts +20 -0
  43. package/runtime/packages/setup/dist/src/platform/profile-usage.js +89 -0
  44. package/runtime/packages/setup/dist/src/platform/windows.js +48 -8
  45. package/runtime/packages/setup/dist/src/private-file.d.ts +4 -1
  46. package/runtime/packages/setup/dist/src/private-file.js +39 -3
  47. package/runtime/packages/setup/dist/src/state.d.ts +4 -0
  48. package/runtime/packages/setup/dist/src/state.js +65 -1
  49. package/runtime/packages/setup/dist/src/status.d.ts +9 -0
  50. package/runtime/packages/setup/dist/src/status.js +7 -3
  51. package/runtime/packages/setup/dist/src/types.d.ts +11 -1
  52. package/runtime/packages/setup/dist/src/wake-readers.d.ts +12 -0
  53. package/runtime/packages/setup/dist/src/wake-readers.js +65 -0
  54. package/runtime/packages/setup/package.json +1 -1
  55. package/runtime/scripts/auth-security.mjs +93 -0
  56. package/runtime/scripts/codex-app-server-wake.mjs +36 -4
  57. package/runtime/scripts/daemon-contacts.mjs +1 -1
  58. package/runtime/scripts/murmur-auth-token.mjs +140 -0
  59. package/runtime/scripts/murmur-daemon.mjs +27 -8
  60. package/runtime/scripts/murmur-jetstream-advisory.mjs +27 -0
  61. package/runtime/scripts/murmur-shell-send.mjs +7 -3
  62. package/runtime/scripts/owner-review-store.mjs +54 -0
  63. package/runtime/scripts/wake-drain-claude.mjs +124 -7
  64. package/runtime/scripts/wake-monitor.mjs +49 -10
@@ -2,40 +2,55 @@ import path from "node:path";
2
2
  import { homedir } from "node:os";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { createHash } from "node:crypto";
5
+ import { accessSync, constants, realpathSync } from "node:fs";
6
+ import { resolveInstallation } from '@murmurv2/core';
7
+ /** Homebrew resolves process.execPath into a versioned Cellar. Persist a stable
8
+ * executable only when it is executable and resolves to this very same Node. */
9
+ export function stableNodeExecutable(executable, platform = process.platform, inspect = (candidate) => { accessSync(candidate, constants.X_OK); return realpathSync(candidate); }) {
10
+ if (platform !== "darwin")
11
+ return executable;
12
+ const brew = /^(\/opt\/homebrew|\/usr\/local)\/Cellar\/(node(?:@\d+)?)\/[^/]+\/bin\/node$/.exec(executable);
13
+ if (!brew)
14
+ return executable;
15
+ const [, prefix, formula] = brew;
16
+ const candidates = formula === "node" ? [`${prefix}/bin/node`, `${prefix}/opt/node/bin/node`]
17
+ : [`${prefix}/opt/${formula}/bin/node`];
18
+ for (const candidate of candidates) {
19
+ try {
20
+ if (inspect(candidate) === executable)
21
+ return candidate;
22
+ }
23
+ catch { /* missing or different installation */ }
24
+ }
25
+ return executable;
26
+ }
5
27
  export function resolveContext(options = {}) {
6
28
  const env = options.env ?? process.env;
7
29
  const platform = options.platform ?? process.platform;
8
30
  const home = options.home ?? homedir();
9
31
  const paths = platform === "win32" ? path.win32 : path.posix;
10
- const defaultDir = platform === "darwin" ? paths.join(home, "Library", "Application Support", "Murmur")
11
- : platform === "win32" ? paths.join(env.LOCALAPPDATA || paths.join(home, "AppData", "Local"), "Murmur")
12
- : paths.join(env.XDG_STATE_HOME || paths.join(home, ".local", "state"), "murmur");
13
- let selected = options.dataDir;
14
- if (selected === undefined) {
15
- if (env.DATA_DIR !== undefined) {
16
- if (!env.DATA_DIR)
17
- throw new Error("config.data-dir-empty");
18
- if (env.MURMUR_DATA_DIR && paths.normalize(env.DATA_DIR) !== paths.normalize(env.MURMUR_DATA_DIR))
19
- throw new Error("config.data-dir-conflict");
20
- selected = env.DATA_DIR;
21
- }
22
- else
23
- selected = env.MURMUR_DATA_DIR ?? defaultDir;
24
- }
25
- const dataDir = paths.normalize(selected);
26
- if (!paths.isAbsolute(dataDir))
27
- throw new Error("config.data-dir-must-be-absolute");
28
- // The default service name hashes the path as written (see AGENTS.md), and shell completion appends
29
- // a separator to folders: refuse it rather than silently select a second service for one profile.
30
- if (dataDir.length > paths.parse(dataDir).root.length && /[\\/]$/.test(dataDir))
31
- throw new Error("profile.trailing-separator");
32
+ const { dataDir } = resolveInstallation({ ...options, platform, home, env });
32
33
  const repoRoot = paths.normalize(options.repoRoot ?? fileURLToPath(new URL("../../../../", import.meta.url))).replace(/[\\/]$/, "");
33
- const nodePath = paths.normalize(options.nodePath ?? process.execPath);
34
+ const nodePath = paths.normalize(options.nodePath ?? stableNodeExecutable(process.execPath, platform));
34
35
  if (!paths.isAbsolute(repoRoot) || !paths.isAbsolute(nodePath))
35
36
  throw new Error("config.runtime-path-must-be-absolute");
36
37
  const serviceName = options.serviceName ?? `murmur-${createHash("sha256").update(dataDir).digest("hex").slice(0, 12)}`;
37
38
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,100}$/.test(serviceName))
38
39
  throw new Error("config.invalid-service-name");
40
+ const clientProjectDir = options.clientProjectDir;
41
+ if (clientProjectDir !== undefined && (!paths.isAbsolute(clientProjectDir) || paths.normalize(clientProjectDir) !== clientProjectDir
42
+ || /[\x00-\x1f\x7f]/.test(clientProjectDir)))
43
+ throw new Error("client.project-path-invalid");
39
44
  return { dataDir, repoRoot, nodePath, serviceName, configPath: paths.join(dataDir, "agent-config.json"),
40
- storePath: paths.join(dataDir, "murmur.db"), logDir: paths.join(dataDir, "logs") };
45
+ storePath: paths.join(dataDir, "murmur.db"), logDir: paths.join(dataDir, "logs"),
46
+ ...(clientProjectDir !== undefined ? { clientProjectDir } : {}) };
47
+ }
48
+ /** New CLI profiles live beside, not inside, any selected installation. */
49
+ export function defaultProfileDir(agentId, platform = process.platform, home = homedir(), env = process.env) {
50
+ if (platform === 'win32')
51
+ return path.win32.join(env.LOCALAPPDATA || path.win32.join(home, 'AppData', 'Local'), 'Murmur', 'profiles', agentId);
52
+ if (platform === 'darwin')
53
+ return path.posix.join(home, 'Library', 'Application Support', 'Murmur', 'profiles', agentId);
54
+ const dataHome = env.XDG_DATA_HOME && path.posix.isAbsolute(env.XDG_DATA_HOME) ? env.XDG_DATA_HOME : path.posix.join(home, '.local', 'share');
55
+ return path.posix.join(dataHome, 'murmur', 'profiles', agentId);
41
56
  }
@@ -3,6 +3,7 @@ export interface CommandResult {
3
3
  code: number;
4
4
  stdout: string;
5
5
  stderr: string;
6
+ pid?: number;
6
7
  }
7
8
  export type CommandRunner = (file: string, args: string[]) => Promise<CommandResult>;
8
9
  export interface DarwinOptions {
@@ -10,6 +11,8 @@ export interface DarwinOptions {
10
11
  uid?: number;
11
12
  env?: NodeJS.ProcessEnv;
12
13
  run?: CommandRunner;
14
+ /** Uses a larger, still bounded output buffer for the profile-wide lsof probe. */
15
+ profileRun?: CommandRunner;
13
16
  applicationDirs?: string[];
14
17
  /** Fully replaces executable search roots, primarily for hermetic tests. */
15
18
  executableDirs?: string[];
@@ -4,6 +4,7 @@ import * as fs from "node:fs/promises";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { randomUUID } from "node:crypto";
7
+ import { classifyProfilePath, ProfileUsageUnknown, verifiedProfileRoot } from "./profile-usage.js";
7
8
  const marker = "<!-- Managed by Murmur setup: darwin-v1 -->";
8
9
  const launchctl = "/bin/launchctl";
9
10
  const xml = (s) => s.replace(/[&<>"']/g, c => ({
@@ -22,7 +23,7 @@ function validate(ctx) {
22
23
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(ctx.serviceName)) {
23
24
  throw new Error("darwin-invalid-service-name");
24
25
  }
25
- // The current daemon resolves both paths from DATA_DIR, ignoring STORE_PATH.
26
+ // The daemon pins DATA_DIR and requires derived store paths to agree.
26
27
  // Refuse an inconsistent context instead of starting against the wrong DB.
27
28
  if (ctx.configPath !== path.join(ctx.dataDir, "agent-config.json") ||
28
29
  ctx.storePath !== path.join(ctx.dataDir, "murmur.db") ||
@@ -30,15 +31,17 @@ function validate(ctx) {
30
31
  throw new Error("darwin-daemon-path-contract-mismatch");
31
32
  }
32
33
  }
33
- const defaultRun = (file, args) => new Promise(resolve => {
34
- execFile(file, args, {
35
- encoding: "utf8", timeout: 8_000, maxBuffer: 512 * 1024,
34
+ const commandRunner = (maxBuffer) => (file, args) => new Promise(resolve => {
35
+ const child = execFile(file, args, {
36
+ encoding: "utf8", timeout: 8_000, maxBuffer,
36
37
  env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
37
38
  }, (error, stdout, stderr) => resolve({
38
39
  code: error ? (typeof error.code === "number" ? error.code : -1) : 0,
39
- stdout: String(stdout), stderr: String(stderr),
40
+ stdout: String(stdout), stderr: String(stderr), pid: child.pid,
40
41
  }));
41
42
  });
43
+ const defaultRun = commandRunner(512 * 1024);
44
+ const defaultProfileRun = commandRunner(8 * 1024 * 1024);
42
45
  const absent = (r) => r.code !== 0 &&
43
46
  /Could not find service|Could not find specified service/.test(r.stderr + r.stdout);
44
47
  const baseSnapshot = () => ({
@@ -62,6 +65,7 @@ export function createDarwinAdapter(options = {}) {
62
65
  throw new Error("darwin-invalid-user-id");
63
66
  const env = options.env ?? process.env;
64
67
  const run = options.run ?? defaultRun;
68
+ const profileRun = options.profileRun ?? options.run ?? defaultProfileRun;
65
69
  const domain = `gui/${uid}`;
66
70
  const plistPath = (ctx) => path.join(home, "Library", "LaunchAgents", `${ctx.serviceName}.plist`);
67
71
  const target = (ctx) => `${domain}/${ctx.serviceName}`;
@@ -70,6 +74,8 @@ export function createDarwinAdapter(options = {}) {
70
74
  const args = [ctx.nodePath, path.join(ctx.repoRoot, "scripts", "murmur-daemon.mjs")];
71
75
  const environment = {
72
76
  DATA_DIR: ctx.dataDir,
77
+ MURMUR_DATA_DIR: ctx.dataDir,
78
+ MURMUR_CHANNEL_ROSTER_PATH: path.join(ctx.dataDir, "channel-roster.db"),
73
79
  MURMUR_STORE_PATH: ctx.storePath,
74
80
  PATH: [path.dirname(ctx.nodePath), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].join(":"),
75
81
  };
@@ -129,6 +135,190 @@ export function createDarwinAdapter(options = {}) {
129
135
  }
130
136
  return null;
131
137
  }
138
+ const usageUnknown = (reason = "profile-usage.probe-unavailable") => ({ state: "unknown", reason });
139
+ function lsofSnapshot(output) {
140
+ if (output.includes("\0") || !output.endsWith("\n"))
141
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
142
+ const lines = output.split("\n");
143
+ if (lines.at(-1) === "")
144
+ lines.pop();
145
+ if (lines.some(line => line === ""))
146
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
147
+ const records = [];
148
+ let pid = null, descriptor = null, type = null;
149
+ let processHasRecord = false;
150
+ const seen = new Set();
151
+ for (const line of lines) {
152
+ if (line.startsWith("p")) {
153
+ if (descriptor !== null || type !== null || pid !== null && !processHasRecord || !/^p[1-9]\d*$/.test(line)) {
154
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
155
+ }
156
+ pid = Number(line.slice(1));
157
+ if (!Number.isSafeInteger(pid) || seen.has(pid))
158
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
159
+ seen.add(pid);
160
+ processHasRecord = false;
161
+ }
162
+ else if (line.startsWith("f")) {
163
+ if (pid === null || descriptor !== null || type !== null || line.length < 2 || /[\0\r\n]/.test(line)) {
164
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
165
+ }
166
+ descriptor = line.slice(1);
167
+ }
168
+ else if (line.startsWith("t")) {
169
+ if (pid === null || descriptor === null || type !== null || line.length < 2 || /[\0\r\n]/.test(line)) {
170
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
171
+ }
172
+ type = line.slice(1);
173
+ }
174
+ else if (line.startsWith("n")) {
175
+ if (pid === null || descriptor === null || type === null) {
176
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
177
+ }
178
+ // Apple's process_netpolicy() sets NPOLICY but no name. Native lsof also
179
+ // emits unnamed NEXUS FDs; XNU gives that Skywalk controller its own
180
+ // fileops, separate from vnodes. Darwin process_pipe_common() leaves
181
+ // NAME empty when an anonymous pipe has no peer handle or byte count.
182
+ // PIPE is distinct from a filesystem FIFO. Only these numeric FD types may
183
+ // have an empty n; missing n, other empty types and pseudo-FDs refuse.
184
+ // https://github.com/apple-opensource/lsof/blob/da09c8c6436286e5bd8c400b42e86b54404f12a7/lsof/dialects/darwin/libproc/dnetpolicy.c
185
+ // https://github.com/apple-oss-distributions/xnu/blob/f6217f891ac0bb64f3d375211650a4c1ff8ca1ea/bsd/skywalk/nexus/nexus_syscalls.c
186
+ // https://github.com/lsof-org/lsof/blob/1ebf257c64db1b2ece5e4d5e922ed711c692f161/lib/dialects/darwin/dfile.c#L306-L340
187
+ if (line.length === 1 && !((type === "NPOLICY" || type === "NEXUS" || type === "PIPE") && /^\d+$/.test(descriptor))) {
188
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
189
+ }
190
+ records.push({ pid, descriptor, type, name: line.slice(1) });
191
+ descriptor = type = null;
192
+ processHasRecord = true;
193
+ }
194
+ else {
195
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
196
+ }
197
+ }
198
+ if (descriptor !== null || type !== null || pid !== null && !processHasRecord) {
199
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
200
+ }
201
+ return { pids: seen, records };
202
+ }
203
+ function processSnapshot(result) {
204
+ if (result.code !== 0 || result.stderr.trim() !== "" || !Number.isSafeInteger(result.pid) || result.pid <= 0) {
205
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
206
+ }
207
+ const observations = new Map();
208
+ const lines = result.stdout.split("\n");
209
+ if (lines.at(-1) === "")
210
+ lines.pop();
211
+ for (const line of lines) {
212
+ const match = /^\s*([1-9]\d*)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(line);
213
+ if (!match)
214
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
215
+ const pid = Number(match[1]), uid = Number(match[2]);
216
+ if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(uid) || observations.has(pid)) {
217
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
218
+ }
219
+ observations.set(pid, { uid, start: match[4], zombie: match[3].startsWith("Z") });
220
+ }
221
+ // /bin/ps is setuid-root on macOS, so its exact child PID may have UID 0.
222
+ // Verify and remove only that exact observer from the full process set.
223
+ if (!observations.has(result.pid) || !observations.has(process.pid)) {
224
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
225
+ }
226
+ observations.delete(result.pid);
227
+ for (const anchor of new Set([1, process.ppid])) {
228
+ if (!observations.has(anchor))
229
+ throw new ProfileUsageUnknown("profile-usage.process-visibility-incomplete");
230
+ }
231
+ return observations;
232
+ }
233
+ async function profileUsage(ctx) {
234
+ validate(ctx);
235
+ try {
236
+ const profile = await verifiedProfileRoot(ctx);
237
+ let control;
238
+ try {
239
+ control = await fs.open(ctx.configPath, constants.O_RDONLY | constants.O_NOFOLLOW);
240
+ const [opened, selected, canonical] = await Promise.all([
241
+ control.stat(), fs.lstat(ctx.configPath), fs.realpath(ctx.configPath),
242
+ ]);
243
+ const currentUid = process.getuid?.();
244
+ if (currentUid === undefined || !opened.isFile() || !selected.isFile() || selected.isSymbolicLink()
245
+ || opened.uid !== currentUid || selected.uid !== currentUid
246
+ || (opened.mode & 0o077) !== 0 || (selected.mode & 0o077) !== 0
247
+ || opened.dev !== selected.dev || opened.ino !== selected.ino || canonical !== ctx.configPath)
248
+ return usageUnknown();
249
+ // Apple's lsof 4.91 makes every +D entry a required search argument,
250
+ // so an unopened entry forces exit 1. Scan all processes and prove
251
+ // lsof coverage with stable ps snapshots around the observation.
252
+ const psArgs = ["-axo", "pid=,uid=,stat=,lstart="];
253
+ const before = processSnapshot(await profileRun("/bin/ps", psArgs));
254
+ const result = await profileRun("/usr/sbin/lsof", ["-n", "-P", "-Fpftn"]);
255
+ if (result.code !== 0 || result.stderr.trim() !== "")
256
+ return usageUnknown();
257
+ const snapshot = lsofSnapshot(result.stdout);
258
+ const after = processSnapshot(await profileRun("/bin/ps", psArgs));
259
+ const stable = new Set();
260
+ if (before.size !== after.size)
261
+ return usageUnknown("profile-usage.process-unverifiable");
262
+ for (const [pid, first] of before) {
263
+ const second = after.get(pid);
264
+ if (!second || first.uid !== second.uid || first.start !== second.start || first.zombie !== second.zombie) {
265
+ return usageUnknown("profile-usage.process-unverifiable");
266
+ }
267
+ if (!first.zombie)
268
+ stable.add(pid);
269
+ }
270
+ if ([...stable].some(pid => !snapshot.pids.has(pid))) {
271
+ return usageUnknown("profile-usage.process-unverifiable");
272
+ }
273
+ let controlSeen = false, held = false;
274
+ const filesystemTypes = new Set(["REG", "DIR", "LINK"]);
275
+ const otherTypes = new Set(["ATALK", "BLK", "CHR", "FIFO", "FSEVENTS", "IPv4", "IPv6", "KQUEUE",
276
+ "NPOLICY", "NEXUS", "PIPE", "PSXSEM", "PSXSHM", "key", "ndrv", "ppp", "rte", "sock", "systm", "unix",
277
+ "vsock", "vsockp"]);
278
+ const classifications = new Map();
279
+ for (const record of snapshot.records) {
280
+ if (!filesystemTypes.has(record.type)) {
281
+ if (!otherTypes.has(record.type))
282
+ return usageUnknown("profile-usage.process-unverifiable");
283
+ continue;
284
+ }
285
+ let classificationPromise = classifications.get(record.name);
286
+ if (!classificationPromise) {
287
+ classificationPromise = classifyProfilePath(profile.root, record.name);
288
+ classifications.set(record.name, classificationPromise);
289
+ }
290
+ const classification = await classificationPromise;
291
+ if (classification === "unknown")
292
+ return usageUnknown("profile-usage.process-unverifiable");
293
+ if (classification === "outside")
294
+ continue;
295
+ if (record.pid === process.pid) {
296
+ const [recordPath, recordInfo] = await Promise.all([fs.realpath(record.name), fs.stat(record.name)]);
297
+ if (recordPath === canonical && recordInfo.dev === opened.dev && recordInfo.ino === opened.ino)
298
+ controlSeen = true;
299
+ }
300
+ else {
301
+ held = true;
302
+ }
303
+ }
304
+ if (!controlSeen)
305
+ return usageUnknown("profile-usage.control-unobserved");
306
+ if (held)
307
+ return { state: "in-use", reason: "profile-usage.open-file" };
308
+ const profileAfter = await verifiedProfileRoot(ctx);
309
+ if (profileAfter.root !== profile.root || profileAfter.proof !== profile.proof) {
310
+ return usageUnknown("profile-usage.profile-changed");
311
+ }
312
+ return { state: "free", reason: "profile-usage.no-open-files" };
313
+ }
314
+ finally {
315
+ await control?.close();
316
+ }
317
+ }
318
+ catch (error) {
319
+ return usageUnknown(error instanceof ProfileUsageUnknown ? error.reason : undefined);
320
+ }
321
+ }
132
322
  async function status(ctx) {
133
323
  validate(ctx);
134
324
  const value = baseSnapshot();
@@ -219,7 +409,20 @@ export function createDarwinAdapter(options = {}) {
219
409
  if (loaded.code !== 0)
220
410
  throw new Error("darwin-cannot-inspect-service-before-stop");
221
411
  requireSameLoadedPath(ctx, loaded);
222
- if (await readOwned(ctx) !== plist(ctx))
412
+ let owned = await readOwned(ctx);
413
+ // Upgrading from a Cellar-bound Node must still allow Stop before Install.
414
+ // Accept only the known Homebrew spelling change; all profile/runtime fields
415
+ // and the ownership marker must otherwise match byte for byte.
416
+ const oldNode = owned?.match(/<key>ProgramArguments<\/key><array><string>((?:\/opt\/homebrew|\/usr\/local)\/Cellar\/(node(?:@\d+)?)\/[^<\/]+\/bin\/node)<\/string>/);
417
+ if (oldNode) {
418
+ const prefix = oldNode[1].split('/Cellar/')[0], formula = oldNode[2];
419
+ const stable = [`${prefix}/opt/${formula}/bin/node`, ...(formula === 'node' ? [`${prefix}/bin/node`] : [])];
420
+ if (stable.includes(ctx.nodePath))
421
+ owned = owned
422
+ .replace(`<array><string>${oldNode[1]}</string>`, `<array><string>${xml(ctx.nodePath)}</string>`)
423
+ .replace(`<key>PATH</key><string>${path.dirname(oldNode[1])}:`, `<key>PATH</key><string>${path.dirname(ctx.nodePath)}:`);
424
+ }
425
+ if (owned !== plist(ctx))
223
426
  throw new Error("darwin-stop-profile-mismatch");
224
427
  const result = await run(launchctl, ["bootout", target(ctx)]);
225
428
  if (result.code !== 0 && !absent(result))
@@ -258,15 +461,50 @@ export function createDarwinAdapter(options = {}) {
258
461
  // Do not guess a writable MCP target for non-default Claude profiles.
259
462
  // Shared setup may resolve it by a client-supported configuration query.
260
463
  const claudeConfig = env.CLAUDE_CONFIG_DIR ? null : path.join(home, ".claude.json");
464
+ const claudeDesktop = await hasApp(["Claude.app"], "com.anthropic.claudefordesktop");
465
+ async function hasBundledClaudeCode() {
466
+ if (!claudeDesktop)
467
+ return false;
468
+ const root = path.join(home, "Library", "Application Support", "Claude", "claude-code");
469
+ const directories = async (dir) => (await fs.readdir(dir, { withFileTypes: true }).catch(() => []))
470
+ .filter(entry => entry.isDirectory()).map(entry => path.join(dir, entry.name));
471
+ // Known desktop layouts: version/claude and version/build/claude.app/Contents/MacOS/claude.
472
+ // Inspect metadata only; never run a discovered binary or recurse through user files.
473
+ for (const version of await directories(root)) {
474
+ const builds = [version, ...await directories(version)];
475
+ for (const build of builds)
476
+ for (const candidate of [path.join(build, "claude"),
477
+ path.join(build, "claude.app", "Contents", "MacOS", "claude")]) {
478
+ if (await accessible(candidate, constants.X_OK) && await fs.stat(candidate).then(s => s.isFile(), () => false))
479
+ return true;
480
+ }
481
+ }
482
+ return false;
483
+ }
484
+ const claudeCli = await hasExecutable("claude");
485
+ const bundledCode = !claudeCli && await hasBundledClaudeCode();
486
+ const hasDirectory = async (dirPath) => (await fs.stat(dirPath).catch(() => null))?.isDirectory() === true;
487
+ let cursorApp = false;
488
+ for (const dir of appDirs) {
489
+ if (await hasDirectory(path.join(absolute(dir, "applicationDir"), "Cursor.app"))) {
490
+ cursorApp = true;
491
+ break;
492
+ }
493
+ }
261
494
  return [
262
- { id: "claude-code", installed: await hasExecutable("claude"), configPath: claudeConfig, format: "json",
495
+ { id: "claude-code", installed: claudeCli || bundledCode, configPath: claudeConfig, format: "json",
496
+ ...(bundledCode ? { detail: "Claude Code in the Claude desktop application" } : {}),
263
497
  ...(claudeConfig === null ? { detail: "Custom CLAUDE_CONFIG_DIR detected; MCP config target requires client verification" } : {}) },
264
- { id: "claude-desktop", installed: await hasApp(["Claude.app"], "com.anthropic.claudefordesktop"), configPath: path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"), format: "json" },
498
+ { id: "claude-desktop", installed: claudeDesktop, configPath: path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"), format: "json" },
265
499
  { id: "codex-cli", installed: await hasExecutable("codex"), configPath: codexConfig, format: "toml" },
266
500
  { id: "codex-desktop", installed: await hasApp(["Codex.app", "ChatGPT.app"], "com.openai.codex"), configPath: codexConfig, format: "toml" },
501
+ { id: "cursor", installed: (await hasExecutable("cursor")) || (await hasExecutable("agent")) || cursorApp || (await hasDirectory(path.join(home, ".cursor"))),
502
+ configPath: path.join(home, ".cursor", "mcp.json"), format: "json" },
503
+ { id: "gemini", installed: (await hasExecutable("agy")) || (await hasExecutable("gemini")) || (await hasDirectory(path.join(home, ".gemini"))),
504
+ configPath: path.join(home, ".gemini", "config", "mcp_config.json"), format: "json" },
267
505
  ];
268
506
  }
269
- return { manager: "launchd", status, install, start, stop, detectClients,
507
+ return { manager: "launchd", status, install, start, stop, detectClients, profileUsage,
270
508
  async observeStore(ctx, pid) {
271
509
  validate(ctx);
272
510
  if (!Number.isSafeInteger(pid) || pid <= 0)
@@ -1,10 +1,11 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import { constants } from "node:fs";
4
- import { access, mkdir, open, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
4
+ import { access, mkdir, open, readFile, readdir, readlink, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
6
  import { randomUUID } from "node:crypto";
7
7
  import path from "node:path";
8
+ import { classifyProfilePath, ProfileUsageUnknown, verifiedProfileRoot } from "./profile-usage.js";
8
9
  const exec = promisify(execFile);
9
10
  const marker = "# Managed by Murmur setup: systemd-v1\n";
10
11
  const unit = (c) => `${c.serviceName}.service`;
@@ -24,10 +25,11 @@ export function renderLinuxUnit(c) {
24
25
  check(c);
25
26
  // ExecStart expands $ independently from specifiers; Environment values do not.
26
27
  const arg = (v) => q(v.replaceAll("$", () => "$$"));
27
- return `${marker}[Unit]\nDescription=Murmur agent daemon\nStartLimitIntervalSec=60\nStartLimitBurst=5\n\n[Service]\nType=simple\nWorkingDirectory=${c.repoRoot.replaceAll("%", "%%")}\nEnvironment=${q(`DATA_DIR=${c.dataDir}`)}\nExecStart=${arg(c.nodePath)} ${arg(path.join(c.repoRoot, "scripts", "murmur-daemon.mjs"))}\nStandardOutput=append:${path.join(c.logDir, `${c.serviceName}.out.log`).replaceAll("%", "%%")}\nStandardError=append:${path.join(c.logDir, `${c.serviceName}.err.log`).replaceAll("%", "%%")}\nRestart=on-failure\nRestartSec=5\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`;
28
+ return `${marker}[Unit]\nDescription=Murmur agent daemon\nStartLimitIntervalSec=60\nStartLimitBurst=5\n\n[Service]\nType=simple\nWorkingDirectory=${c.repoRoot.replaceAll("%", "%%")}\nEnvironment=${q(`DATA_DIR=${c.dataDir}`)} ${q(`MURMUR_DATA_DIR=${c.dataDir}`)} ${q(`MURMUR_STORE_PATH=${c.storePath}`)} ${q(`MURMUR_CHANNEL_ROSTER_PATH=${path.join(c.dataDir, "channel-roster.db")}`)}\nExecStart=${arg(c.nodePath)} ${arg(path.join(c.repoRoot, "scripts", "murmur-daemon.mjs"))}\nStandardOutput=append:${path.join(c.logDir, `${c.serviceName}.out.log`).replaceAll("%", "%%")}\nStandardError=append:${path.join(c.logDir, `${c.serviceName}.err.log`).replaceAll("%", "%%")}\nRestart=on-failure\nRestartSec=5\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`;
28
29
  }
29
30
  export function createLinuxAdapter(options = {}) {
30
31
  const env = options.env ?? process.env, home = options.homeDir ?? homedir();
32
+ const procRoot = options.procDir ?? "/proc";
31
33
  const run = options.run ?? (async (args) => {
32
34
  try {
33
35
  return (await exec("systemctl", ["--user", ...args], { timeout: 5000, maxBuffer: 256 * 1024 })).stdout;
@@ -93,6 +95,133 @@ export function createLinuxAdapter(options = {}) {
93
95
  catch { /* Inaccessible or exited processes are not liveness evidence. */ }
94
96
  return null;
95
97
  }
98
+ const usageUnknown = (reason = "profile-usage.probe-unavailable") => ({ state: "unknown", reason });
99
+ const processUnknown = (reason = "profile-usage.process-unverifiable") => { throw new ProfileUsageUnknown(reason); };
100
+ function startTime(pid, value) {
101
+ if (!value.startsWith(`${pid} (`))
102
+ return processUnknown();
103
+ const close = value.lastIndexOf(")");
104
+ if (close < pid.length + 2)
105
+ return processUnknown();
106
+ const fields = value.slice(close + 1).trim().split(/\s+/);
107
+ const started = fields[19];
108
+ if (fields.length < 20 || !/^\d+$/.test(started ?? ""))
109
+ return processUnknown();
110
+ return started;
111
+ }
112
+ function credentialUids(status) {
113
+ const matches = [...status.matchAll(/^Uid:[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]*$/gm)];
114
+ if (matches.length !== 1)
115
+ return processUnknown();
116
+ const uids = matches[0].slice(1).map(Number);
117
+ if (uids.length !== 4 || uids.some(uid => !Number.isSafeInteger(uid) || uid < 0))
118
+ return processUnknown();
119
+ return uids;
120
+ }
121
+ async function processIdentity(pid) {
122
+ try {
123
+ const statFile = path.join(procRoot, pid, "stat");
124
+ const before = startTime(pid, await readFile(statFile, "utf8"));
125
+ const statusFile = path.join(procRoot, pid, "status");
126
+ const firstUids = credentialUids(await readFile(statusFile, "utf8"));
127
+ const secondUids = credentialUids(await readFile(statusFile, "utf8"));
128
+ const after = startTime(pid, await readFile(statFile, "utf8"));
129
+ if (before !== after)
130
+ return processUnknown("profile-usage.process-set-changed");
131
+ if (firstUids.some((uid, index) => uid !== secondUids[index])) {
132
+ return processUnknown("profile-usage.process-identity-changed");
133
+ }
134
+ return { uids: firstUids, started: before, proof: `${before}:${firstUids.join(":")}` };
135
+ }
136
+ catch (error) {
137
+ if (error instanceof ProfileUsageUnknown)
138
+ throw error;
139
+ return processUnknown();
140
+ }
141
+ }
142
+ async function visibleProcesses() {
143
+ let entries;
144
+ try {
145
+ entries = await readdir(procRoot, { withFileTypes: true });
146
+ }
147
+ catch {
148
+ return processUnknown();
149
+ }
150
+ const result = new Map();
151
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name, "en"))) {
152
+ if (!/^\d+$/.test(entry.name))
153
+ continue;
154
+ if (!entry.isDirectory())
155
+ return processUnknown();
156
+ if (entry.name === String(process.pid))
157
+ continue;
158
+ const identity = await processIdentity(entry.name);
159
+ result.set(entry.name, identity.proof);
160
+ }
161
+ for (const anchor of new Set(["1", String(process.ppid)])) {
162
+ if (!result.has(anchor))
163
+ return processUnknown("profile-usage.process-visibility-incomplete");
164
+ }
165
+ return result;
166
+ }
167
+ const sameProcesses = (a, b) => a.size === b.size && [...a].every(([pid, proof]) => b.get(pid) === proof);
168
+ async function profileUsage(c) {
169
+ check(c);
170
+ try {
171
+ const uid = process.getuid?.();
172
+ if (!Number.isSafeInteger(uid) || uid < 0)
173
+ return usageUnknown();
174
+ const profile = await verifiedProfileRoot(c);
175
+ const before = await visibleProcesses();
176
+ let held = false;
177
+ for (const [pid, identity] of before) {
178
+ if ((await processIdentity(pid)).proof !== identity)
179
+ return usageUnknown("profile-usage.process-identity-changed");
180
+ let descriptors;
181
+ try {
182
+ descriptors = (await readdir(path.join(procRoot, pid, "fd"))).sort();
183
+ }
184
+ catch {
185
+ return usageUnknown("profile-usage.process-unverifiable");
186
+ }
187
+ for (const descriptor of descriptors) {
188
+ if (!/^\d+$/.test(descriptor))
189
+ return usageUnknown("profile-usage.process-unverifiable");
190
+ let target;
191
+ try {
192
+ target = await readlink(path.join(procRoot, pid, "fd", descriptor));
193
+ }
194
+ catch {
195
+ return usageUnknown("profile-usage.process-unverifiable");
196
+ }
197
+ if (/^(?:socket|pipe):\[\d+\]$/.test(target) || /^anon_inode:\[[^\]\r\n]+\]$/.test(target))
198
+ continue;
199
+ if (/^\/memfd:[^\r\n]+(?: \(deleted\))?$/.test(target))
200
+ continue;
201
+ const classification = await classifyProfilePath(profile.root, target);
202
+ if (classification === "unknown")
203
+ return usageUnknown("profile-usage.process-unverifiable");
204
+ if (classification === "inside")
205
+ held = true;
206
+ }
207
+ if ((await processIdentity(pid)).proof !== identity)
208
+ return usageUnknown("profile-usage.process-identity-changed");
209
+ }
210
+ if (held)
211
+ return { state: "in-use", reason: "profile-usage.open-file" };
212
+ const after = await visibleProcesses();
213
+ if (!sameProcesses(before, after))
214
+ return usageUnknown("profile-usage.process-set-changed");
215
+ const profileAfter = await verifiedProfileRoot(c);
216
+ if (profileAfter.root !== profile.root || profileAfter.proof !== profile.proof) {
217
+ return usageUnknown("profile-usage.profile-changed");
218
+ }
219
+ return { state: "free", reason: "profile-usage.no-open-files" };
220
+ }
221
+ catch (error) {
222
+ return usageUnknown(error instanceof ProfileUsageUnknown ? error.reason : undefined);
223
+ }
224
+ }
96
225
  return {
97
226
  manager: "systemd",
98
227
  observeStore,
@@ -154,28 +283,43 @@ export function createLinuxAdapter(options = {}) {
154
283
  await run(["stop", unit(c)]);
155
284
  },
156
285
  async detectClients() {
157
- const rows = [];
158
- for (const [id, command, configPath, format] of [
159
- ["claude-code", "claude", env.CLAUDE_CONFIG_DIR ? null : path.join(home, ".claude.json"), "json"],
160
- ["codex-cli", "codex", path.join(env.CODEX_HOME || path.join(home, ".codex"), "config.toml"), "toml"],
161
- ]) {
162
- let installed = false;
286
+ const hasExecutable = async (command) => {
163
287
  for (const candidate of (env.PATH ?? "").split(path.delimiter)) {
164
288
  if (!path.isAbsolute(candidate))
165
289
  continue;
166
290
  try {
167
291
  const file = path.join(candidate, command);
168
292
  await access(file, constants.X_OK);
169
- if ((await stat(file)).isFile()) {
170
- installed = true;
171
- break;
172
- }
293
+ if ((await stat(file)).isFile())
294
+ return true;
173
295
  }
174
296
  catch { }
175
297
  }
298
+ return false;
299
+ };
300
+ const hasDirectory = async (dirPath) => (await stat(dirPath).catch(() => null))?.isDirectory() === true;
301
+ const rows = [];
302
+ for (const [id, command, configPath, format] of [
303
+ ["claude-code", "claude", env.CLAUDE_CONFIG_DIR ? null : path.join(home, ".claude.json"), "json"],
304
+ ["codex-cli", "codex", path.join(env.CODEX_HOME || path.join(home, ".codex"), "config.toml"), "toml"],
305
+ ]) {
306
+ const installed = await hasExecutable(command);
176
307
  rows.push({ id, installed, configPath, format, ...(configPath === null ? { detail: "Custom Claude profile requires client verification" } : {}) });
177
308
  }
309
+ rows.push({
310
+ id: "cursor",
311
+ installed: (await hasExecutable("cursor")) || (await hasExecutable("agent")) || (await hasDirectory(path.join(home, ".cursor"))),
312
+ configPath: path.join(home, ".cursor", "mcp.json"),
313
+ format: "json",
314
+ });
315
+ rows.push({
316
+ id: "gemini",
317
+ installed: (await hasExecutable("agy")) || (await hasExecutable("gemini")) || (await hasDirectory(path.join(home, ".gemini"))),
318
+ configPath: path.join(home, ".gemini", "config", "mcp_config.json"),
319
+ format: "json",
320
+ });
178
321
  return rows;
179
322
  },
323
+ profileUsage,
180
324
  };
181
325
  }
@@ -0,0 +1,20 @@
1
+ import type { ServiceContext } from "../types.js";
2
+ export interface VerifiedProfileRoot {
3
+ root: string;
4
+ /** Opaque tree identity used only to reject changes during a free snapshot. */
5
+ proof: string;
6
+ }
7
+ export declare class ProfileUsageUnknown extends Error {
8
+ readonly reason: string;
9
+ constructor(reason: string);
10
+ }
11
+ export declare function isWithinProfile(root: string, candidate: string): boolean;
12
+ /**
13
+ * Require an owner-only selected root, then inspect its tree without following
14
+ * aliases. Platform probes must still cover every visible process because a
15
+ * privileged foreign UID can traverse the root. Aliases, mount crossings,
16
+ * unsupported entries, hardlinks, or concurrent changes make the snapshot incomplete.
17
+ */
18
+ export declare function verifiedProfileRoot(context: ServiceContext): Promise<VerifiedProfileRoot>;
19
+ /** Classify one kernel/tool pathname after the profile tree passed verification. */
20
+ export declare function classifyProfilePath(root: string, raw: string): Promise<"inside" | "outside" | "unknown">;