@murmurv2/cli 2.12.0 → 2.13.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 (57) 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 +151 -75
  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/backups.d.ts +36 -0
  9. package/runtime/packages/setup/dist/src/backups.js +128 -0
  10. package/runtime/packages/setup/dist/src/broker-input.d.ts +24 -0
  11. package/runtime/packages/setup/dist/src/broker-input.js +98 -0
  12. package/runtime/packages/setup/dist/src/broker-migration.d.ts +35 -0
  13. package/runtime/packages/setup/dist/src/broker-migration.js +138 -0
  14. package/runtime/packages/setup/dist/src/cli-error.d.ts +2 -0
  15. package/runtime/packages/setup/dist/src/cli-error.js +30 -0
  16. package/runtime/packages/setup/dist/src/cli.js +67 -10
  17. package/runtime/packages/setup/dist/src/clients.d.ts +28 -76
  18. package/runtime/packages/setup/dist/src/clients.js +159 -25
  19. package/runtime/packages/setup/dist/src/commands.js +3 -3
  20. package/runtime/packages/setup/dist/src/config.d.ts +8 -0
  21. package/runtime/packages/setup/dist/src/config.js +58 -10
  22. package/runtime/packages/setup/dist/src/connect.d.ts +143 -0
  23. package/runtime/packages/setup/dist/src/connect.js +126 -0
  24. package/runtime/packages/setup/dist/src/doctor.d.ts +30 -0
  25. package/runtime/packages/setup/dist/src/doctor.js +72 -10
  26. package/runtime/packages/setup/dist/src/installation.d.ts +25 -0
  27. package/runtime/packages/setup/dist/src/installation.js +89 -0
  28. package/runtime/packages/setup/dist/src/message-status.d.ts +1 -0
  29. package/runtime/packages/setup/dist/src/message-status.js +3 -0
  30. package/runtime/packages/setup/dist/src/onboarding.d.ts +11 -6
  31. package/runtime/packages/setup/dist/src/onboarding.js +92 -21
  32. package/runtime/packages/setup/dist/src/paths.d.ts +7 -0
  33. package/runtime/packages/setup/dist/src/paths.js +39 -24
  34. package/runtime/packages/setup/dist/src/platform/darwin.d.ts +3 -0
  35. package/runtime/packages/setup/dist/src/platform/darwin.js +235 -9
  36. package/runtime/packages/setup/dist/src/platform/linux.js +132 -2
  37. package/runtime/packages/setup/dist/src/platform/profile-usage.d.ts +20 -0
  38. package/runtime/packages/setup/dist/src/platform/profile-usage.js +89 -0
  39. package/runtime/packages/setup/dist/src/platform/windows.js +22 -1
  40. package/runtime/packages/setup/dist/src/private-file.d.ts +4 -1
  41. package/runtime/packages/setup/dist/src/private-file.js +39 -3
  42. package/runtime/packages/setup/dist/src/state.d.ts +4 -0
  43. package/runtime/packages/setup/dist/src/state.js +65 -1
  44. package/runtime/packages/setup/dist/src/status.d.ts +9 -0
  45. package/runtime/packages/setup/dist/src/status.js +7 -3
  46. package/runtime/packages/setup/dist/src/types.d.ts +10 -0
  47. package/runtime/packages/setup/dist/src/wake-readers.d.ts +12 -0
  48. package/runtime/packages/setup/dist/src/wake-readers.js +65 -0
  49. package/runtime/packages/setup/package.json +1 -1
  50. package/runtime/scripts/auth-security.mjs +93 -0
  51. package/runtime/scripts/codex-app-server-wake.mjs +13 -0
  52. package/runtime/scripts/daemon-contacts.mjs +1 -1
  53. package/runtime/scripts/murmur-auth-token.mjs +140 -0
  54. package/runtime/scripts/murmur-daemon.mjs +22 -6
  55. package/runtime/scripts/murmur-jetstream-advisory.mjs +27 -0
  56. package/runtime/scripts/murmur-shell-send.mjs +3 -3
  57. package/runtime/scripts/wake-drain-claude.mjs +124 -7
@@ -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,
@@ -177,5 +306,6 @@ export function createLinuxAdapter(options = {}) {
177
306
  }
178
307
  return rows;
179
308
  },
309
+ profileUsage,
180
310
  };
181
311
  }
@@ -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">;
@@ -0,0 +1,89 @@
1
+ import * as fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ const maximumEntries = 10_000;
4
+ export class ProfileUsageUnknown extends Error {
5
+ reason;
6
+ constructor(reason) {
7
+ super(reason);
8
+ this.reason = reason;
9
+ }
10
+ }
11
+ const unknown = (reason) => { throw new ProfileUsageUnknown(reason); };
12
+ export function isWithinProfile(root, candidate) {
13
+ const relative = path.relative(root, candidate);
14
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
15
+ }
16
+ /**
17
+ * Require an owner-only selected root, then inspect its tree without following
18
+ * aliases. Platform probes must still cover every visible process because a
19
+ * privileged foreign UID can traverse the root. Aliases, mount crossings,
20
+ * unsupported entries, hardlinks, or concurrent changes make the snapshot incomplete.
21
+ */
22
+ export async function verifiedProfileRoot(context) {
23
+ let root;
24
+ try {
25
+ const selected = await fs.lstat(context.dataDir);
26
+ if (selected.isSymbolicLink() || !selected.isDirectory() || (selected.mode & 0o077) !== 0) {
27
+ return unknown("profile-usage.profile-unverifiable");
28
+ }
29
+ const uid = process.getuid?.();
30
+ if (uid === undefined || selected.uid !== uid)
31
+ return unknown("profile-usage.profile-unverifiable");
32
+ root = await fs.realpath(context.dataDir);
33
+ if (root !== context.dataDir)
34
+ return unknown("profile-usage.profile-unverifiable");
35
+ const rootInfo = await fs.stat(root);
36
+ if (selected.dev !== rootInfo.dev || selected.ino !== rootInfo.ino || rootInfo.uid !== uid || (rootInfo.mode & 0o077) !== 0) {
37
+ return unknown("profile-usage.profile-unverifiable");
38
+ }
39
+ const directories = [{ absolute: root, relative: "" }];
40
+ const proof = [["", rootInfo.dev, rootInfo.ino, rootInfo.mode, rootInfo.uid, rootInfo.gid, rootInfo.nlink]];
41
+ let seen = 0;
42
+ while (directories.length) {
43
+ const directory = directories.pop();
44
+ const names = [];
45
+ for await (const entry of await fs.opendir(directory.absolute)) {
46
+ if (++seen > maximumEntries)
47
+ return unknown("profile-usage.profile-unverifiable");
48
+ names.push(entry.name);
49
+ }
50
+ names.sort();
51
+ for (const name of names) {
52
+ const file = path.join(directory.absolute, name);
53
+ const relative = path.join(directory.relative, name);
54
+ const info = await fs.lstat(file);
55
+ if (info.isSymbolicLink() || info.dev !== rootInfo.dev)
56
+ return unknown("profile-usage.profile-unverifiable");
57
+ if (info.isFile() && info.nlink !== 1)
58
+ return unknown("profile-usage.profile-hard-linked");
59
+ proof.push([relative, info.dev, info.ino, info.mode, info.uid, info.gid, info.nlink]);
60
+ if (info.isDirectory())
61
+ directories.push({ absolute: file, relative });
62
+ else if (!info.isFile())
63
+ return unknown("profile-usage.profile-unverifiable");
64
+ }
65
+ }
66
+ return { root, proof: JSON.stringify(proof) };
67
+ }
68
+ catch (error) {
69
+ if (error instanceof ProfileUsageUnknown)
70
+ throw error;
71
+ return unknown("profile-usage.profile-unverifiable");
72
+ }
73
+ }
74
+ /** Classify one kernel/tool pathname after the profile tree passed verification. */
75
+ export async function classifyProfilePath(root, raw) {
76
+ if (!path.isAbsolute(raw) || /[\0\r\n]/.test(raw))
77
+ return "unknown";
78
+ const deleted = raw.endsWith(" (deleted)");
79
+ const candidate = path.normalize(deleted ? raw.slice(0, -" (deleted)".length) : raw);
80
+ if (deleted)
81
+ return "unknown";
82
+ try {
83
+ const canonical = await fs.realpath(candidate);
84
+ return isWithinProfile(root, canonical) ? "inside" : "outside";
85
+ }
86
+ catch {
87
+ return "unknown";
88
+ }
89
+ }
@@ -17,6 +17,13 @@ export function helperReason(stderr) {
17
17
  const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
18
18
  const natural = (v) => Number.isSafeInteger(v) && Number(v) >= 0;
19
19
  const textOrNull = (v) => v === null || typeof v === 'string';
20
+ const usageUnknown = () => ({ state: 'unknown', reason: 'profile.probe-unavailable' });
21
+ const profileUsageReasons = new Map([
22
+ ['profile.store-held', 'in-use'], ['profile.store-unheld', 'free'],
23
+ ['profile.store-missing', 'unknown'], ['profile.store-invalid', 'unknown'],
24
+ ['profile.probe-unavailable', 'unknown'], ['profile.managed-running-unobserved', 'unknown'],
25
+ ['profile.service-unverifiable', 'unknown'],
26
+ ]);
20
27
  function absolute(value) {
21
28
  if (typeof value !== 'string' || !paths.isAbsolute(value) || paths.normalize(value) !== value || /[\x00-\x1f\x7f]/.test(value))
22
29
  fail('invalid-path');
@@ -77,7 +84,7 @@ export function createWindowsAdapter(options = {}) {
77
84
  }
78
85
  async function invoke(c, action) {
79
86
  validate(c);
80
- const result = await run(await helper(c), [action], { env: selectedEnvironment(c), timeout: action === 'status' ? 8000 : 55000 });
87
+ const result = await run(await helper(c), [action], { env: selectedEnvironment(c), timeout: action === 'status' || action === 'profile-usage' ? 8000 : 55000 });
81
88
  if (result.code !== 0)
82
89
  fail(helperReason(result.stderr));
83
90
  return result.stdout;
@@ -227,6 +234,20 @@ export function createWindowsAdapter(options = {}) {
227
234
  }
228
235
  },
229
236
  install: c => mutate(c, 'install'), start: c => mutate(c, 'start'), stop: c => mutate(c, 'stop'), uninstall: c => mutate(c, 'uninstall'),
237
+ async profileUsage(c) {
238
+ try {
239
+ const value = JSON.parse(await invoke(c, 'profile-usage'));
240
+ if (!object(value) || Object.keys(value).sort().join(',') !== 'reason,schema,state'
241
+ || value.schema !== 'murmur.windows-profile-usage/1'
242
+ || !['free', 'in-use', 'unknown'].includes(value.state)
243
+ || typeof value.reason !== 'string' || profileUsageReasons.get(value.reason) !== value.state)
244
+ return usageUnknown();
245
+ return { state: value.state, reason: value.reason };
246
+ }
247
+ catch {
248
+ return usageUnknown();
249
+ }
250
+ },
230
251
  async detectClients() {
231
252
  const rows = [];
232
253
  for (const [id, command, configPath, format] of [
@@ -1,5 +1,8 @@
1
1
  import { type FileHandle } from 'node:fs/promises';
2
+ import type { BigIntStats } from 'node:fs';
2
3
  /** Protect a newly created, still-empty setup output before writing credentials. */
3
4
  export declare function protectPrivateFile(file: string, handle: FileHandle): Promise<void>;
4
- /** Existing Windows files keep their access policy, including intentional sandbox readers. */
5
+ /** Existing Windows files keep their owner and access policy, including intentional sandbox readers. */
5
6
  export declare function preparePrivateReplacement(file: string, handle: FileHandle, previous: string): Promise<void>;
7
+ /** Read-only verification for backup cleanup; never repair an unexpectedly public backup. */
8
+ export declare function verifyPrivateFileAccess(file: string, info: BigIntStats): Promise<void>;
@@ -28,7 +28,11 @@ if ($source) {
28
28
  $expected = $original.GetSecurityDescriptorSddlForm($section)
29
29
  $security.SetSecurityDescriptorSddlForm($expected, $section)
30
30
  $expectedPolicy = AccessPolicy $original
31
+ $expectedOwner = $original.GetOwner([System.Security.Principal.SecurityIdentifier])
31
32
  } else {
33
+ # An elevated token may default new files to the Administrators group owner.
34
+ # Pin this still-empty output to its actual creator before writing any secrets.
35
+ $expectedOwner = New-Object System.Security.Principal.SecurityIdentifier($user)
32
36
  $security.SetAccessRuleProtection($true, $false)
33
37
  foreach ($id in $allowed) {
34
38
  $sid = New-Object System.Security.Principal.SecurityIdentifier($id)
@@ -36,11 +40,15 @@ if ($source) {
36
40
  $security.AddAccessRule($rule)
37
41
  }
38
42
  }
43
+ $security.SetOwner($expectedOwner)
39
44
  Set-Acl -LiteralPath $file -AclObject $security
40
45
  $actual = Get-Acl -LiteralPath $file
46
+ if ($actual.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -ne $expectedOwner.Value) { throw 'unexpected owner' }
41
47
  if ($source) {
48
+ $sourceAfter = Get-Acl -LiteralPath $source
42
49
  if ((AccessPolicy $actual) -cne $expectedPolicy -or
43
- (AccessPolicy (Get-Acl -LiteralPath $source)) -cne $expectedPolicy) { throw 'changed access policy' }
50
+ (AccessPolicy $sourceAfter) -cne $expectedPolicy -or
51
+ $sourceAfter.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -ne $expectedOwner.Value) { throw 'changed access policy' }
44
52
  exit 0
45
53
  }
46
54
  if (!$actual.AreAccessRulesProtected) { throw 'unprotected ACL' }
@@ -76,7 +84,7 @@ async function prepareFile(file, handle, accessSource) {
76
84
  catch (error) {
77
85
  // Keep paths, command text and arbitrary PowerShell stderr out of diagnostics.
78
86
  const failure = error;
79
- const rejection = ['changed access policy', 'unprotected ACL', 'unexpected ACL entries', 'unexpected ACL']
87
+ const rejection = ['changed access policy', 'unprotected ACL', 'unexpected ACL entries', 'unexpected ACL', 'unexpected owner']
80
88
  .find(reason => failure.stderr?.includes(reason));
81
89
  const reason = failure.killed ? 'timeout' : failure.code === 'ENOENT' ? 'powershell-unavailable'
82
90
  : rejection?.replaceAll(' ', '-') ?? 'command-failed';
@@ -95,7 +103,35 @@ async function prepareFile(file, handle, accessSource) {
95
103
  export async function protectPrivateFile(file, handle) {
96
104
  return prepareFile(file, handle);
97
105
  }
98
- /** Existing Windows files keep their access policy, including intentional sandbox readers. */
106
+ /** Existing Windows files keep their owner and access policy, including intentional sandbox readers. */
99
107
  export async function preparePrivateReplacement(file, handle, previous) {
100
108
  return prepareFile(file, handle, previous);
101
109
  }
110
+ /** Read-only verification for backup cleanup; never repair an unexpectedly public backup. */
111
+ export async function verifyPrivateFileAccess(file, info) {
112
+ if (process.platform !== 'win32') {
113
+ if ((info.mode & 63n) !== 0n)
114
+ throw new Error('backups.permissions-invalid');
115
+ return;
116
+ }
117
+ const script = `
118
+ $ErrorActionPreference = 'Stop'
119
+ $env:PSModulePath = [System.IO.Path]::Combine($PSHOME, 'Modules')
120
+ $acl = Get-Acl -LiteralPath $env:MURMUR_SETUP_PRIVATE_FILE
121
+ $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
122
+ $allowed = @($user, 'S-1-5-18') | Select-Object -Unique
123
+ if (!$acl.AreAccessRulesProtected -or $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -ne $user) { throw 'invalid' }
124
+ $rules = @($acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]))
125
+ if ($rules.Count -ne $allowed.Count) { throw 'invalid' }
126
+ foreach ($rule in $rules) {
127
+ if ($allowed -notcontains $rule.IdentityReference.Value -or $rule.AccessControlType -ne 'Allow' -or
128
+ $rule.FileSystemRights -ne [System.Security.AccessControl.FileSystemRights]::FullControl -or $rule.IsInherited) { throw 'invalid' }
129
+ }
130
+ `;
131
+ try {
132
+ await exec(path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'), ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { env: { ...process.env, MURMUR_SETUP_PRIVATE_FILE: file }, windowsHide: true, timeout: 60_000, maxBuffer: 64 * 1024 });
133
+ }
134
+ catch {
135
+ throw new Error('backups.permissions-invalid');
136
+ }
137
+ }
@@ -1,3 +1,7 @@
1
1
  import type { ServiceContext } from "./types.js";
2
2
  /** Reuse the runtime's existing private-state writer; setup ships with that runtime. */
3
3
  export declare function writeState(c: ServiceContext, file: string, value: unknown): Promise<void>;
4
+ /** Create a byte-exact, private, non-overwriting recovery file beside the profile. */
5
+ export declare function writeExactBackup(c: ServiceContext, file: string, bytes: Buffer): Promise<void>;
6
+ /** Restore exact reviewed bytes atomically while retaining the backup until verification succeeds. */
7
+ export declare function restoreExactBackup(c: ServiceContext, backup: string, target: string, bytes: Buffer): Promise<void>;
@@ -1,6 +1,9 @@
1
+ import { constants } from "node:fs";
2
+ import { open, rename, unlink } from "node:fs/promises";
3
+ import { randomUUID } from "node:crypto";
1
4
  import path from "node:path";
2
5
  import { pathToFileURL } from "node:url";
3
- import { preparePrivateReplacement } from "./private-file.js";
6
+ import { preparePrivateReplacement, protectPrivateFile } from "./private-file.js";
4
7
  /** Reuse the runtime's existing private-state writer; setup ships with that runtime. */
5
8
  export async function writeState(c, file, value) {
6
9
  if (path.dirname(file) !== c.dataDir)
@@ -10,3 +13,64 @@ export async function writeState(c, file, value) {
10
13
  beforeWrite: (temporary, handle) => preparePrivateReplacement(temporary, handle, file),
11
14
  });
12
15
  }
16
+ async function syncDirectory(dir) {
17
+ if (process.platform === "win32")
18
+ return;
19
+ const handle = await open(dir, constants.O_RDONLY | constants.O_DIRECTORY);
20
+ try {
21
+ await handle.sync();
22
+ }
23
+ finally {
24
+ await handle.close();
25
+ }
26
+ }
27
+ /** Create a byte-exact, private, non-overwriting recovery file beside the profile. */
28
+ export async function writeExactBackup(c, file, bytes) {
29
+ if (path.dirname(file) !== c.dataDir || bytes.length > 4 * 1024 * 1024)
30
+ throw new Error("state.backup-invalid");
31
+ let handle;
32
+ let created = false;
33
+ try {
34
+ handle = await open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
35
+ created = true;
36
+ await protectPrivateFile(file, handle);
37
+ await handle.writeFile(bytes);
38
+ await handle.sync();
39
+ await handle.close();
40
+ handle = undefined;
41
+ await syncDirectory(c.dataDir);
42
+ }
43
+ catch (error) {
44
+ if (handle)
45
+ await handle.close().catch(() => { });
46
+ if (created)
47
+ await unlink(file).catch(() => { });
48
+ throw error;
49
+ }
50
+ }
51
+ /** Restore exact reviewed bytes atomically while retaining the backup until verification succeeds. */
52
+ export async function restoreExactBackup(c, backup, target, bytes) {
53
+ if (path.dirname(backup) !== c.dataDir || target !== c.configPath)
54
+ throw new Error("state.restore-invalid");
55
+ const temp = path.join(c.dataDir, `.agent-config.restore-${process.pid}-${randomUUID()}.tmp`);
56
+ let handle;
57
+ let created = false;
58
+ try {
59
+ handle = await open(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
60
+ created = true;
61
+ await preparePrivateReplacement(temp, handle, target);
62
+ await handle.writeFile(bytes);
63
+ await handle.sync();
64
+ await handle.close();
65
+ handle = undefined;
66
+ await rename(temp, target);
67
+ await syncDirectory(c.dataDir);
68
+ }
69
+ catch (error) {
70
+ if (handle)
71
+ await handle.close().catch(() => { });
72
+ if (created)
73
+ await unlink(temp).catch(() => { });
74
+ throw error;
75
+ }
76
+ }
@@ -119,6 +119,15 @@ export declare function readStatus({ context: c, adapter, now }: StatusOptions):
119
119
  };
120
120
  };
121
121
  wake: {
122
+ readers: {
123
+ active: number | null;
124
+ measuredAt: string;
125
+ unknownReason: string;
126
+ } | {
127
+ active: number;
128
+ measuredAt: string;
129
+ unknownReason: null;
130
+ };
122
131
  config: {
123
132
  enabled: boolean | null;
124
133
  mode: "none" | "hook" | "monitor" | null;
@@ -4,7 +4,8 @@ import { realpath } from "node:fs/promises";
4
4
  import { createHash } from "node:crypto";
5
5
  import { loadConfig, readJson, safeError, validAgentId } from "./config.js";
6
6
  import { readOutboxAttention } from "./outbox-attention.js";
7
- import { assistantRead, wakeColumns } from "./message-status.js";
7
+ import { assistantRead, wakeColumns, personalInboxSql } from "./message-status.js";
8
+ import { readWakeReaders } from './wake-readers.js';
8
9
  const measured = (at) => ({ measuredAt: at, unknownReason: null });
9
10
  const unknown = (reason) => ({ measuredAt: null, unknownReason: reason });
10
11
  export const pairFingerprint = (config, peerId) => createHash("sha256").update(JSON.stringify([
@@ -119,7 +120,9 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
119
120
  try {
120
121
  db = new DatabaseSync(c.storePath, { readOnly: true });
121
122
  db.exec("PRAGMA busy_timeout=1000; BEGIN");
122
- const summary = db.prepare("SELECT COUNT(*) AS total, MAX(created_at) AS lastAt, COALESCE(MAX(rowid),0) AS tip FROM local_messages WHERE direction='inbound'").get();
123
+ const summary = db.prepare(`SELECT COUNT(CASE WHEN ${personalInboxSql} THEN 1 END) AS total,
124
+ MAX(CASE WHEN ${personalInboxSql} THEN created_at END) AS lastAt,
125
+ COALESCE(MAX(rowid),0) AS tip FROM local_messages WHERE direction='inbound'`).get();
123
126
  inbox.total = Number(summary.total);
124
127
  inbox.lastAt = summary.lastAt;
125
128
  inbox.measurements.store = measured(at);
@@ -128,7 +131,7 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
128
131
  if (cursor.schema !== "murmur.read/1" || cursor.agentId !== config?.agentId || !Number.isSafeInteger(cursor.rowid)
129
132
  || cursor.rowid < 0 || cursor.rowid > Number(summary.tip))
130
133
  throw new Error("inbox.cursor-invalid");
131
- inbox.unread = Number(db.prepare("SELECT COUNT(*) AS n FROM local_messages WHERE direction='inbound' AND rowid>?").get(cursor.rowid).n);
134
+ inbox.unread = Number(db.prepare(`SELECT COUNT(*) AS n FROM local_messages WHERE direction='inbound' AND ${personalInboxSql} AND rowid>?`).get(cursor.rowid).n);
132
135
  inbox.measurements.cursor = measured(at);
133
136
  }
134
137
  catch { /* A missing cursor is not an empty inbox. */ }
@@ -233,6 +236,7 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
233
236
  unknownReason: outbox.measurements.store.unknownReason, source: "durable-outbox" },
234
237
  },
235
238
  wake: {
239
+ readers: await readWakeReaders(c),
236
240
  config: { enabled: config ? config.wake?.enabled !== false : null,
237
241
  mode: config ? configuredWakeMode(config) : null,
238
242
  responder: config ? configuredWakeMode(config) === "monitor" ? "codex" : config.onReceive ? null : "none" : null,
@@ -7,6 +7,8 @@ export interface ServiceContext {
7
7
  nodePath: string;
8
8
  logDir: string;
9
9
  serviceName: string;
10
+ /** Explicit project-scoped Claude Code connection; never inferred from cwd. */
11
+ clientProjectDir?: string;
10
12
  }
11
13
  export type ServiceManager = "windows-service" | "scheduled-task" | "launchd" | "systemd" | "none";
12
14
  export interface ServiceSnapshot {
@@ -29,6 +31,12 @@ export interface ClientDetection {
29
31
  format: "json" | "toml";
30
32
  detail?: string;
31
33
  }
34
+ /** Point-in-time, read-only evidence about use of one resolved profile. */
35
+ export interface ProfileUsageSnapshot {
36
+ state: "free" | "in-use" | "unknown";
37
+ /** Stable, non-secret reason code. Callers must not treat it as proof beyond this observation. */
38
+ reason: string;
39
+ }
32
40
  export interface PlatformAdapter {
33
41
  manager: ServiceManager;
34
42
  status(context: ServiceContext): Promise<ServiceSnapshot>;
@@ -47,4 +55,6 @@ export interface PlatformAdapter {
47
55
  detectClients(context: ServiceContext): Promise<ClientDetection[]>;
48
56
  /** Native log location, after verifying the selected service owns this profile. */
49
57
  logDirectory?(context: ServiceContext): Promise<string>;
58
+ /** Optional until a platform has an independently reviewed native profile-usage probe. */
59
+ profileUsage?(context: ServiceContext): Promise<ProfileUsageSnapshot>;
50
60
  }
@@ -0,0 +1,12 @@
1
+ import type { ServiceContext } from './types.js';
2
+ /** A lock alone is not a live reader. Verify its PID and the drain's selected DB.
3
+ * Unknown process inspection stays unknown; this never deletes stale locks. */
4
+ export declare function readWakeReaders(c: ServiceContext, home?: string): Promise<{
5
+ active: number | null;
6
+ measuredAt: string;
7
+ unknownReason: string;
8
+ } | {
9
+ active: number;
10
+ measuredAt: string;
11
+ unknownReason: null;
12
+ }>;
@@ -0,0 +1,65 @@
1
+ import { readdir, readFile, lstat } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ import { execFile } from 'node:child_process';
6
+ import { promisify } from 'node:util';
7
+ const run = promisify(execFile);
8
+ /** A lock alone is not a live reader. Verify its PID and the drain's selected DB.
9
+ * Unknown process inspection stays unknown; this never deletes stale locks. */
10
+ export async function readWakeReaders(c, home = homedir()) {
11
+ const measuredAt = new Date().toISOString();
12
+ const unknown = (reason) => ({ active: null, measuredAt, unknownReason: reason });
13
+ if (!['linux', 'darwin'].includes(process.platform))
14
+ return unknown('wake.readers-platform-unavailable');
15
+ const store = path.resolve(c.storePath);
16
+ const key = createHash('sha256').update(store).digest('hex').slice(0, 8);
17
+ let files;
18
+ try {
19
+ files = (await readdir(home)).filter(name => new RegExp(`^\\.murmur-wake-lock-${key}(?:-[A-Za-z0-9_-]{1,8})?$`).test(name));
20
+ }
21
+ catch {
22
+ return unknown('wake.readers-directory-unavailable');
23
+ }
24
+ let active = 0;
25
+ for (const name of files) {
26
+ const file = path.join(home, name);
27
+ try {
28
+ const info = await lstat(file);
29
+ if (!info.isFile() || info.size > 64)
30
+ return unknown('wake.reader-lock-unverified');
31
+ const raw = await readFile(file, 'utf8'), pid = Number(raw.trim());
32
+ if (!Number.isSafeInteger(pid) || pid <= 0)
33
+ return unknown('wake.reader-lock-unverified');
34
+ try {
35
+ process.kill(pid, 0);
36
+ }
37
+ catch (error) {
38
+ if (error.code === 'ESRCH')
39
+ continue;
40
+ return unknown('wake.reader-process-unavailable');
41
+ }
42
+ let matches = false;
43
+ if (process.platform === 'linux') {
44
+ const args = (await readFile(`/proc/${pid}/cmdline`, 'utf8')).split('\0');
45
+ matches = args.some(arg => arg.endsWith('/wake-drain-claude.mjs'))
46
+ && args[args.indexOf('--db') + 1] === store;
47
+ }
48
+ else {
49
+ const { stdout } = await run('/bin/ps', ['-p', String(pid), '-o', 'command='], { timeout: 2000, maxBuffer: 32768 });
50
+ matches = stdout.includes('/wake-drain-claude.mjs ') && stdout.includes(`--db ${store} `);
51
+ }
52
+ if (await readFile(file, 'utf8') !== raw)
53
+ return unknown('wake.reader-lock-changed');
54
+ if (!matches)
55
+ return unknown('wake.reader-process-unverified');
56
+ active++;
57
+ }
58
+ catch (error) {
59
+ if (error.code !== 'ENOENT')
60
+ return unknown('wake.reader-inspection-failed');
61
+ // The reader can finish between listing its lock and inspecting the process.
62
+ }
63
+ }
64
+ return { active, measuredAt, unknownReason: null };
65
+ }