@murmurv2/cli 2.11.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 (69) hide show
  1. package/README.md +85 -19
  2. package/package.json +8 -6
  3. package/runtime/bin/murmur-svc.exe +0 -0
  4. package/runtime/npm-runtime-manifest.json +193 -81
  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 +6 -3
  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.d.ts +1 -1
  17. package/runtime/packages/setup/dist/src/cli.js +111 -14
  18. package/runtime/packages/setup/dist/src/clients.d.ts +28 -76
  19. package/runtime/packages/setup/dist/src/clients.js +166 -26
  20. package/runtime/packages/setup/dist/src/commands.d.ts +3 -1
  21. package/runtime/packages/setup/dist/src/commands.js +18 -7
  22. package/runtime/packages/setup/dist/src/config.d.ts +10 -0
  23. package/runtime/packages/setup/dist/src/config.js +119 -10
  24. package/runtime/packages/setup/dist/src/connect.d.ts +143 -0
  25. package/runtime/packages/setup/dist/src/connect.js +126 -0
  26. package/runtime/packages/setup/dist/src/doctor.d.ts +42 -0
  27. package/runtime/packages/setup/dist/src/doctor.js +89 -10
  28. package/runtime/packages/setup/dist/src/installation.d.ts +25 -0
  29. package/runtime/packages/setup/dist/src/installation.js +89 -0
  30. package/runtime/packages/setup/dist/src/invitation-server.d.ts +2 -0
  31. package/runtime/packages/setup/dist/src/invitation-server.js +45 -0
  32. package/runtime/packages/setup/dist/src/message-status.d.ts +5 -0
  33. package/runtime/packages/setup/dist/src/message-status.js +13 -0
  34. package/runtime/packages/setup/dist/src/onboarding.d.ts +28 -10
  35. package/runtime/packages/setup/dist/src/onboarding.js +129 -34
  36. package/runtime/packages/setup/dist/src/outbox-attention.js +3 -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 +241 -9
  41. package/runtime/packages/setup/dist/src/platform/linux.js +152 -17
  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 +89 -4
  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 +26 -2
  50. package/runtime/packages/setup/dist/src/status.js +84 -20
  51. package/runtime/packages/setup/dist/src/types.d.ts +21 -1
  52. package/runtime/packages/setup/dist/src/verdict.js +4 -2
  53. package/runtime/packages/setup/dist/src/wake-attention.d.ts +11 -0
  54. package/runtime/packages/setup/dist/src/wake-attention.js +44 -0
  55. package/runtime/packages/setup/dist/src/wake-readers.d.ts +12 -0
  56. package/runtime/packages/setup/dist/src/wake-readers.js +65 -0
  57. package/runtime/packages/setup/package.json +1 -1
  58. package/runtime/scripts/auth-security.mjs +93 -0
  59. package/runtime/scripts/codex-app-server-wake.mjs +182 -32
  60. package/runtime/scripts/daemon-contacts.mjs +56 -0
  61. package/runtime/scripts/daemon-flush-tick.mjs +25 -0
  62. package/runtime/scripts/daemon-link-watch.mjs +60 -0
  63. package/runtime/scripts/daemon-observation.mjs +74 -18
  64. package/runtime/scripts/murmur-auth-token.mjs +140 -0
  65. package/runtime/scripts/murmur-daemon.mjs +66 -36
  66. package/runtime/scripts/murmur-jetstream-advisory.mjs +27 -0
  67. package/runtime/scripts/murmur-shell-send.mjs +3 -3
  68. package/runtime/scripts/wake-drain-claude.mjs +193 -39
  69. package/runtime/scripts/wake-monitor.mjs +46 -18
@@ -1,5 +1,6 @@
1
1
  import { execFile } from 'node:child_process';
2
- import { realpath, stat } from 'node:fs/promises';
2
+ import { access, realpath, stat } from 'node:fs/promises';
3
+ import { constants } from 'node:fs';
3
4
  import { homedir } from 'node:os';
4
5
  import path from 'node:path';
5
6
  const paths = path.win32;
@@ -16,6 +17,13 @@ export function helperReason(stderr) {
16
17
  const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
17
18
  const natural = (v) => Number.isSafeInteger(v) && Number(v) >= 0;
18
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
+ ]);
19
27
  function absolute(value) {
20
28
  if (typeof value !== 'string' || !paths.isAbsolute(value) || paths.normalize(value) !== value || /[\x00-\x1f\x7f]/.test(value))
21
29
  fail('invalid-path');
@@ -76,7 +84,7 @@ export function createWindowsAdapter(options = {}) {
76
84
  }
77
85
  async function invoke(c, action) {
78
86
  validate(c);
79
- 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 });
80
88
  if (result.code !== 0)
81
89
  fail(helperReason(result.stderr));
82
90
  return result.stdout;
@@ -102,7 +110,10 @@ export function createWindowsAdapter(options = {}) {
102
110
  || !(v.lastExitCode === null || Number.isSafeInteger(v.lastExitCode))
103
111
  || !['since', 'lastFailureAt', 'observedStorePath', 'observedStoreUnknownReason', 'restartsUnknownReason'].every(k => textOrNull(v[k]))
104
112
  || !['since', 'lastFailureAt'].every(k => v[k] === null || Number.isFinite(Date.parse(v[k])))
105
- || v.restartsPerHourLimit !== 5)
113
+ || v.restartsPerHourLimit !== 5
114
+ // Older helpers omit foreignKind; it describes only a Service that is not this installation's.
115
+ || !(v.foreignKind === undefined || v.foreignKind === null
116
+ || v.manager === 'foreign' && ['previous-installation', 'not-murmur'].includes(v.foreignKind)))
106
117
  fail('native-response-invalid');
107
118
  if (!(v.restartCount === null && v.restartWindowMs === null || natural(v.restartCount) && natural(v.restartWindowMs) && v.restartWindowMs <= 3600000)
108
119
  || (v.restartWindowMs === 3600000 ? v.restartsLastHour !== v.restartCount : v.restartsLastHour !== null))
@@ -112,7 +123,12 @@ export function createWindowsAdapter(options = {}) {
112
123
  fail('native-response-invalid');
113
124
  return { snapshot: { ...empty('service.not-installed'), state: 'stopped' }, installed: false };
114
125
  }
115
- if (v.manager === 'foreign' || !object(v.profile))
126
+ // A Service left by another Murmur installation (a pilot or an earlier version) can be replaced
127
+ // on request; a name taken by another program never is. Anything else stays unverified.
128
+ if (v.manager === 'foreign')
129
+ fail(v.foreignKind === 'previous-installation' ? 'previous-installation'
130
+ : v.foreignKind === 'not-murmur' ? 'foreign-image' : 'profile-unverified');
131
+ if (!object(v.profile))
116
132
  fail('profile-unverified');
117
133
  const expected = { dataDir: c.dataDir, node: c.nodePath, workDir: c.repoRoot, entry: paths.join(c.repoRoot, 'scripts', 'murmur-daemon.mjs') };
118
134
  for (const [key, value] of Object.entries(expected)) {
@@ -151,8 +167,63 @@ export function createWindowsAdapter(options = {}) {
151
167
  || (action === 'stop' ? after.snapshot.state !== 'stopped' : after.snapshot.state !== 'running' || after.snapshot.pid === null))
152
168
  fail('action-unconfirmed');
153
169
  }
170
+ /** Removes only a Service that another Murmur installation registered under this name. */
171
+ async function removePrevious(c) {
172
+ validate(c);
173
+ const found = await inspect(c).then(() => null, (error) => error);
174
+ if (found === null)
175
+ return; // Absent or already this installation's: nothing to replace.
176
+ if (!(found instanceof Error && found.message === 'service.previous-installation'))
177
+ throw found;
178
+ if (await elevated() === false)
179
+ fail('elevation-required');
180
+ await invoke(c, 'remove-previous');
181
+ const after = await inspect(c).catch(() => null);
182
+ if (!after || after.installed)
183
+ fail('action-unconfirmed');
184
+ }
154
185
  return {
155
186
  manager: 'windows-service',
187
+ removePrevious,
188
+ async logDirectory(c) {
189
+ validate(c);
190
+ if (!(await inspect(c)).installed)
191
+ throw new Error('logs.service-not-installed');
192
+ const programData = Object.entries(env).find(([key]) => key.toLowerCase() === 'programdata')?.[1];
193
+ if (!programData || !paths.isAbsolute(programData))
194
+ throw new Error('logs.windows-native-location-unavailable');
195
+ // This is the native helper's ProgramData/Murmur/logs/<service> layout.
196
+ // Verify ownership above and containment after resolving junctions below.
197
+ try {
198
+ const root = await canonicalize(paths.join(programData, 'Murmur', 'logs'));
199
+ const logDir = await canonicalize(paths.join(programData, 'Murmur', 'logs', c.serviceName));
200
+ if (paths.relative(root, logDir) !== c.serviceName)
201
+ throw new Error('logs.path-outside-service');
202
+ if (!(await stat(logDir)).isDirectory())
203
+ throw new Error('logs.not-directory');
204
+ await access(logDir, constants.R_OK);
205
+ return logDir;
206
+ }
207
+ catch (error) {
208
+ if (error instanceof Error && error.message.startsWith('logs.'))
209
+ throw error;
210
+ const code = error.code;
211
+ throw new Error(code === 'ENOENT' ? 'logs.directory-missing' : code === 'EACCES' || code === 'EPERM' ? 'logs.directory-unreadable' : 'logs.path-unavailable');
212
+ }
213
+ },
214
+ async observeStore(c, pid) {
215
+ validate(c);
216
+ if (!natural(pid) || pid === 0)
217
+ return null;
218
+ const result = await run(await helper(c), ['observe-store', String(pid)], { env: selectedEnvironment(c), timeout: 8000 });
219
+ if (result.code !== 0)
220
+ return null; // Older helpers cannot provide this proof.
221
+ const v = JSON.parse(result.stdout);
222
+ if (!object(v) || v.schema !== 'murmur.store-proof/1' || v.pid !== pid || typeof v.observedStorePath !== 'string')
223
+ return null;
224
+ absolute(v.observedStorePath);
225
+ return await same(v.observedStorePath, c.storePath) ? canonicalize(v.observedStorePath) : null;
226
+ },
156
227
  async status(c) {
157
228
  try {
158
229
  return (await inspect(c)).snapshot;
@@ -163,6 +234,20 @@ export function createWindowsAdapter(options = {}) {
163
234
  }
164
235
  },
165
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
+ },
166
251
  async detectClients() {
167
252
  const rows = [];
168
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
+ }
@@ -6,6 +6,14 @@ export type Measurement = {
6
6
  };
7
7
  export declare const pairFingerprint: (config: AgentConfig, peerId: string) => string;
8
8
  export declare function validPairProof(proof: any, config: AgentConfig, peerId: string, now: number): boolean;
9
+ interface ContactReload {
10
+ state: "current" | "partial" | "retained";
11
+ count: number;
12
+ invalidCount: number;
13
+ lastSuccessAt: string | null;
14
+ lastError: string | null;
15
+ lastErrorAt: string | null;
16
+ }
9
17
  export interface StatusOptions {
10
18
  context: ServiceContext;
11
19
  adapter: PlatformAdapter;
@@ -14,9 +22,10 @@ export interface StatusOptions {
14
22
  export declare function readStatus({ context: c, adapter, now }: StatusOptions): Promise<{
15
23
  schema: "murmur.status/1";
16
24
  generatedAt: string;
17
- agentId: string | null;
25
+ agentId: any;
18
26
  serviceName: string;
19
27
  service: {
28
+ managed: boolean | null;
20
29
  lastFailureAt: null;
21
30
  restartsLastHour: number | null;
22
31
  restartFailureThreshold: number;
@@ -25,7 +34,7 @@ export declare function readStatus({ context: c, adapter, now }: StatusOptions):
25
34
  manager: Measurement;
26
35
  history: Measurement;
27
36
  };
28
- state: "running" | "stopped" | "failed" | "unknown";
37
+ state: "running" | "running-unmanaged" | "stopped" | "failed" | "unknown";
29
38
  manager: import("./types.js").ServiceManager;
30
39
  since: string | null;
31
40
  pid: number | null;
@@ -41,6 +50,8 @@ export declare function readStatus({ context: c, adapter, now }: StatusOptions):
41
50
  connectedAt: any;
42
51
  lastError: any;
43
52
  lastErrorAt: any;
53
+ disconnectedAt: any;
54
+ reconnectAttempts: any;
44
55
  unknownReason: string | null;
45
56
  measurements: {
46
57
  runtime: Measurement;
@@ -52,7 +63,10 @@ export declare function readStatus({ context: c, adapter, now }: StatusOptions):
52
63
  paired: boolean | null;
53
64
  lastInboundAt: string | null;
54
65
  lastOutboundAt: string | null;
66
+ lastExchangeAt: string | null;
67
+ connection: "connected" | "stale" | "unverified";
55
68
  }> | null;
69
+ reload: ContactReload | null;
56
70
  unknownReason: string | null;
57
71
  measurements: Record<string, Measurement>;
58
72
  };
@@ -105,6 +119,15 @@ export declare function readStatus({ context: c, adapter, now }: StatusOptions):
105
119
  };
106
120
  };
107
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
+ };
108
131
  config: {
109
132
  enabled: boolean | null;
110
133
  mode: "none" | "hook" | "monitor" | null;
@@ -135,3 +158,4 @@ export declare function readStatus({ context: c, adapter, now }: StatusOptions):
135
158
  };
136
159
  }>;
137
160
  export declare function configuredWakeMode(config: AgentConfig): "hook" | "monitor" | "none";
161
+ export {};
@@ -2,8 +2,10 @@ import { DatabaseSync } from "node:sqlite";
2
2
  import path from "node:path";
3
3
  import { realpath } from "node:fs/promises";
4
4
  import { createHash } from "node:crypto";
5
- import { loadConfig, readJson, safeError } from "./config.js";
5
+ import { loadConfig, readJson, safeError, validAgentId } from "./config.js";
6
6
  import { readOutboxAttention } from "./outbox-attention.js";
7
+ import { assistantRead, wakeColumns, personalInboxSql } from "./message-status.js";
8
+ import { readWakeReaders } from './wake-readers.js';
7
9
  const measured = (at) => ({ measuredAt: at, unknownReason: null });
8
10
  const unknown = (reason) => ({ measuredAt: null, unknownReason: reason });
9
11
  export const pairFingerprint = (config, peerId) => createHash("sha256").update(JSON.stringify([
@@ -11,10 +13,27 @@ export const pairFingerprint = (config, peerId) => createHash("sha256").update(J
11
13
  config.peers[peerId]?.signing.publicKey, config.peers[peerId]?.encryption.publicKey,
12
14
  ])).digest("hex");
13
15
  export function validPairProof(proof, config, peerId, now) {
14
- const at = Date.parse(proof?.verifiedAt);
16
+ const at = pairProofTime(proof, config, peerId, now);
17
+ return at !== null && now - Date.parse(at) <= 86400000;
18
+ }
19
+ function pairProofTime(proof, config, peerId, now) {
15
20
  return proof?.peerId === peerId && proof?.localAgentId === config.agentId
16
21
  && proof?.keyFingerprint === pairFingerprint(config, peerId)
17
- && Number.isFinite(at) && now - at >= -5000 && now - at <= 86400000;
22
+ ? exchangeTime(proof.verifiedAt, now) : null;
23
+ }
24
+ function exchangeTime(value, now) {
25
+ const timestamp = typeof value === "string" ? Date.parse(value) : NaN;
26
+ return Number.isFinite(timestamp) && timestamp <= now + 5000 ? new Date(timestamp).toISOString() : null;
27
+ }
28
+ function contactReload(raw, now) {
29
+ if (!raw || !["current", "partial", "retained"].includes(raw.state)
30
+ || !Number.isSafeInteger(raw.count) || raw.count < 0
31
+ || !Number.isSafeInteger(raw.invalidCount) || raw.invalidCount < 0
32
+ || (raw.lastError !== null && (typeof raw.lastError !== "string" || !/^agent-config-[a-z-]+$/.test(raw.lastError))))
33
+ return null;
34
+ return { state: raw.state, count: raw.count, invalidCount: raw.invalidCount,
35
+ lastSuccessAt: exchangeTime(raw.lastSuccessAt, now), lastError: raw.lastError,
36
+ lastErrorAt: exchangeTime(raw.lastErrorAt, now) };
18
37
  }
19
38
  export async function readStatus({ context: c, adapter, now = Date.now }) {
20
39
  const started = now();
@@ -46,13 +65,33 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
46
65
  const raw = await readJson(path.join(c.dataDir, "daemon-observation.json"));
47
66
  const timestamp = Date.parse(raw.measuredAt);
48
67
  const storePath = await realpath(c.storePath);
49
- if (raw.schema === "murmur.runtime/1" && service.state === "running" && raw.pid === service.pid
50
- && raw.agentId === config?.agentId && raw.storePath === storePath && service.observedStorePath === storePath
68
+ if (raw.schema === "murmur.runtime/1" && Number.isSafeInteger(raw.pid) && raw.pid > 0
69
+ // A rejected on-disk config must not hide an already running process's
70
+ // reload diagnostic. Fresh PID/open-store evidence still gates acceptance.
71
+ && validAgentId(raw.agentId) && (!config || raw.agentId === config.agentId) && raw.storePath === storePath
51
72
  && Number.isFinite(timestamp) && started - timestamp >= -5000 && started - timestamp <= 15000
52
- && ["connected", "disconnected", "unauthorized", "unknown"].includes(raw.broker?.state)
73
+ && ["connected", "disconnected", "unauthorized", "closed", "unknown"].includes(raw.broker?.state)
53
74
  && typeof raw.wake?.enabled === "boolean" && ["hook", "monitor", "none"].includes(raw.wake?.mode)) {
54
- observation = raw;
55
- runtimeMeasurement = measured(raw.measuredAt);
75
+ const managed = service.state === "running" && raw.pid === service.pid && service.observedStorePath === storePath;
76
+ // A fresh file alone cannot prove liveness: the OS must observe this PID's
77
+ // open database. Never use process arguments or the configured service name.
78
+ const independent = !managed && service.state !== "failed"
79
+ ? await adapter.observeStore?.(c, raw.pid).catch(() => null) : null;
80
+ if (managed || independent === storePath) {
81
+ // A Service of a previous Murmur installation keeps its own label: the live process is
82
+ // most likely its child, and "running outside this app" would hide the replacement.
83
+ const previous = service.detail === "service.previous-installation";
84
+ if (!managed && raw.pid !== service.pid && !previous)
85
+ service = { state: "running-unmanaged", manager: "none", pid: raw.pid,
86
+ observedStorePath: storePath, since: exchangeTime(raw.startedAt, started), lastExitCode: null,
87
+ restartCount: null, restartWindowMs: null, detail: "service.running-unmanaged" };
88
+ else if (independent === storePath)
89
+ service = { ...service, observedStorePath: storePath };
90
+ observation = raw;
91
+ runtimeMeasurement = measured(raw.measuredAt);
92
+ }
93
+ else
94
+ runtimeMeasurement = unknown("runtime.process-store-unverified");
56
95
  }
57
96
  else
58
97
  runtimeMeasurement = unknown("runtime.observation-unverified-or-stale");
@@ -70,7 +109,9 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
70
109
  lastFault: null, lastFaultAt: null, unknownReason: null,
71
110
  measurements: { store: unknown("store.unavailable"), runtime: runtimeMeasurement } };
72
111
  const peers = {
73
- list: config ? Object.keys(config.peers).map((agentId) => ({ agentId, paired: null, lastInboundAt: null, lastOutboundAt: null })) : null,
112
+ list: config ? Object.keys(config.peers).map((agentId) => ({ agentId, paired: null, lastInboundAt: null, lastOutboundAt: null,
113
+ lastExchangeAt: null, connection: "unverified" })) : null,
114
+ reload: contactReload(observation?.contacts, started),
74
115
  unknownReason: configError, measurements: { config: config ? measured(at) : unknown(configError ?? "config.unavailable"), store: unknown("store.unavailable"), proof: unknown("peers.proof-unavailable") },
75
116
  };
76
117
  let deliveries = null;
@@ -79,7 +120,9 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
79
120
  try {
80
121
  db = new DatabaseSync(c.storePath, { readOnly: true });
81
122
  db.exec("PRAGMA busy_timeout=1000; BEGIN");
82
- 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();
83
126
  inbox.total = Number(summary.total);
84
127
  inbox.lastAt = summary.lastAt;
85
128
  inbox.measurements.store = measured(at);
@@ -88,7 +131,7 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
88
131
  if (cursor.schema !== "murmur.read/1" || cursor.agentId !== config?.agentId || !Number.isSafeInteger(cursor.rowid)
89
132
  || cursor.rowid < 0 || cursor.rowid > Number(summary.tip))
90
133
  throw new Error("inbox.cursor-invalid");
91
- 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);
92
135
  inbox.measurements.cursor = measured(at);
93
136
  }
94
137
  catch { /* A missing cursor is not an empty inbox. */ }
@@ -116,7 +159,9 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
116
159
  wake.storedOnly = rows["stored-only"] ?? 0;
117
160
  wake.pendingUndelivered = (rows.pending ?? 0) + (rows.inflight ?? 0) + (rows.failed ?? 0);
118
161
  wake.lastDeliveredAt = db.prepare("SELECT MAX(wake_updated_at) AS at FROM local_messages WHERE direction='inbound' AND wake_status='handled'").get().at;
119
- const fault = db.prepare("SELECT wake_error,wake_updated_at FROM local_messages WHERE direction='inbound' AND wake_status IN ('failed','dlq') AND wake_error IS NOT NULL ORDER BY wake_updated_at DESC LIMIT 1").get();
162
+ const fault = db.prepare(`SELECT wake_error,wake_updated_at FROM local_messages WHERE direction='inbound'
163
+ AND (wake_status IN ('failed','dlq') OR (wake_status='inflight' AND wake_error='accepted-turn-unobservable'))
164
+ AND wake_error IS NOT NULL ORDER BY wake_updated_at DESC LIMIT 1`).get();
120
165
  wake.lastFault = fault ? safeError(fault.wake_error) : null;
121
166
  wake.lastFaultAt = fault?.wake_updated_at ?? null;
122
167
  wake.measurements.store = measured(at);
@@ -124,14 +169,20 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
124
169
  catch {
125
170
  wake.measurements.store = unknown("wake.store-schema-unavailable");
126
171
  }
172
+ const exchangeCutoff = new Date(started + 5000).toISOString();
127
173
  for (const peer of peers.list ?? []) {
128
- peer.lastInboundAt = db.prepare("SELECT MAX(created_at) AS at FROM local_messages WHERE direction='inbound' AND sender=?").get(peer.agentId).at;
129
- peer.lastOutboundAt = db.prepare("SELECT MAX(created_at) AS at FROM outbox WHERE json_extract(envelope_json,'$.recipients[0]')=?").get(peer.agentId).at;
174
+ peer.lastInboundAt = db.prepare("SELECT created_at AS at FROM local_messages WHERE direction='inbound' AND sender=? AND julianday(created_at)<=julianday(?) ORDER BY julianday(created_at) DESC LIMIT 1").get(peer.agentId, exchangeCutoff)?.at ?? null;
175
+ peer.lastOutboundAt = db.prepare("SELECT created_at AS at FROM outbox WHERE json_extract(envelope_json,'$.recipients[0]')=? AND julianday(created_at)<=julianday(?) ORDER BY julianday(created_at) DESC LIMIT 1").get(peer.agentId, exchangeCutoff)?.at ?? null;
176
+ const ackedAt = db.prepare("SELECT updated_at AS at FROM outbox WHERE status='acked' AND json_extract(envelope_json,'$.recipients[0]')=? AND julianday(updated_at)<=julianday(?) ORDER BY julianday(updated_at) DESC LIMIT 1").get(peer.agentId, exchangeCutoff)?.at ?? null;
177
+ peer.lastExchangeAt = [peer.lastInboundAt, ackedAt].map(value => exchangeTime(value, started)).filter((value) => value !== null).sort().at(-1) ?? null;
130
178
  }
131
179
  peers.measurements.store = measured(at);
132
180
  const outbound = db.prepare("SELECT msg_id AS msgId,json_extract(envelope_json,'$.recipients[0]') AS peer,'outbound' AS direction,CASE status WHEN 'acked' THEN 'delivered' WHEN 'sent' THEN 'inflight' ELSE status END AS state,updated_at AS at,attempts,last_error AS error FROM outbox ORDER BY updated_at DESC LIMIT 20").all();
133
- const inbound = db.prepare("SELECT msg_id AS msgId,sender AS peer,'inbound' AS direction,'delivered' AS state,created_at AS at,0 AS attempts,NULL AS error FROM local_messages WHERE direction='inbound' ORDER BY created_at DESC LIMIT 20").all();
134
- deliveries = [...outbound, ...inbound].sort((a, b) => String(b.at).localeCompare(String(a.at))).slice(0, 20).map((r) => ({ ...r, error: r.error ? safeError(r.error) : null }));
181
+ const inbound = db.prepare(`SELECT msg_id AS msgId,sender AS peer,'inbound' AS direction,'delivered' AS state,created_at AS at,0 AS attempts,NULL AS error,${wakeColumns(db)} FROM local_messages WHERE direction='inbound' ORDER BY created_at DESC LIMIT 20`).all();
182
+ deliveries = [...outbound, ...inbound].sort((a, b) => String(b.at).localeCompare(String(a.at))).slice(0, 20).map((r) => ({ ...r,
183
+ error: r.error ? safeError(r.error) : null, wake_status: r.wake_status ?? null,
184
+ wake_error: r.wake_error ? safeError(r.wake_error) : null,
185
+ wake_updated_at: r.wake_updated_at ?? null, assistantRead: assistantRead(r.wake_status) }));
135
186
  db.exec("COMMIT");
136
187
  }
137
188
  catch {
@@ -143,25 +194,37 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
143
194
  if (config) {
144
195
  try {
145
196
  const proofs = await readJson(path.join(c.dataDir, "pair-proofs.json"));
146
- for (const peer of peers.list ?? [])
197
+ for (const peer of peers.list ?? []) {
147
198
  peer.paired = validPairProof(proofs[peer.agentId], config, peer.agentId, started) ? true : null;
199
+ const proofAt = pairProofTime(proofs[peer.agentId], config, peer.agentId, started);
200
+ peer.lastExchangeAt = [peer.lastExchangeAt, proofAt].filter((value) => value !== null).sort().at(-1) ?? null;
201
+ }
148
202
  peers.measurements.proof = measured(at);
149
203
  }
150
204
  catch { /* No roundtrip evidence: every pairing stays unknown. */ }
151
205
  }
206
+ for (const peer of peers.list ?? [])
207
+ peer.connection = peer.lastExchangeAt === null ? "unverified"
208
+ : started - Date.parse(peer.lastExchangeAt) <= 86400000 ? "connected" : "stale";
152
209
  const reason = (sources) => Object.entries(sources).filter(([, v]) => v.unknownReason).map(([name, v]) => `${name}:${v.unknownReason}`).join("; ") || null;
153
210
  inbox.unknownReason = reason(inbox.measurements);
154
211
  outbox.unknownReason = reason(outbox.measurements);
155
212
  wake.unknownReason = reason(wake.measurements);
156
213
  peers.unknownReason = reason(peers.measurements);
157
214
  return {
158
- schema: "murmur.status/1", generatedAt: at, agentId: config?.agentId ?? null, serviceName: c.serviceName,
159
- service: { ...service, lastFailureAt: null, restartsLastHour, restartFailureThreshold: 5,
215
+ schema: "murmur.status/1", generatedAt: at, agentId: config?.agentId ?? observation?.agentId ?? null, serviceName: c.serviceName,
216
+ service: { ...service, managed: service.state === "running" ? true : service.state === "running-unmanaged" ? false : null, lastFailureAt: null,
217
+ restartsLastHour: service.state === "running-unmanaged" ? null : restartsLastHour, restartFailureThreshold: 5,
160
218
  unknownReason: service.state === "unknown" ? service.detail ?? "service.unavailable" : null,
161
219
  measurements: { manager: service.state === "unknown" ? unknown(service.detail ?? "service.unavailable") : measured(at), history: unknown("service.history-unavailable") } },
162
220
  broker: { url: config?.natsUrl ?? null, state: observation?.broker?.state ?? "unknown",
163
221
  connectedAt: observation?.broker?.connectedAt ?? null, lastError: observation?.broker?.lastError ?? null,
164
- lastErrorAt: observation?.broker?.lastErrorAt ?? null, unknownReason: runtimeMeasurement.unknownReason,
222
+ lastErrorAt: observation?.broker?.lastErrorAt ?? null,
223
+ // #276 — since when the link is lost and how many reconnect attempts failed meanwhile.
224
+ disconnectedAt: typeof observation?.broker?.disconnectedAt === "string" ? observation.broker.disconnectedAt : null,
225
+ reconnectAttempts: Number.isSafeInteger(observation?.broker?.reconnectAttempts) && observation.broker.reconnectAttempts >= 0
226
+ ? observation.broker.reconnectAttempts : null,
227
+ unknownReason: runtimeMeasurement.unknownReason,
165
228
  measurements: { runtime: runtimeMeasurement } },
166
229
  peers, inbox, deliveries,
167
230
  outbox: {
@@ -173,6 +236,7 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
173
236
  unknownReason: outbox.measurements.store.unknownReason, source: "durable-outbox" },
174
237
  },
175
238
  wake: {
239
+ readers: await readWakeReaders(c),
176
240
  config: { enabled: config ? config.wake?.enabled !== false : null,
177
241
  mode: config ? configuredWakeMode(config) : null,
178
242
  responder: config ? configuredWakeMode(config) === "monitor" ? "codex" : config.onReceive ? null : "none" : null,
@@ -7,10 +7,12 @@ 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 {
13
- state: "running" | "stopped" | "failed" | "unknown";
15
+ state: "running" | "running-unmanaged" | "stopped" | "failed" | "unknown";
14
16
  manager: ServiceManager;
15
17
  since: string | null;
16
18
  pid: number | null;
@@ -29,12 +31,30 @@ 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>;
43
+ /** Read-only proof that this PID currently holds the selected store open. */
44
+ observeStore?(context: ServiceContext, pid: number): Promise<string | null>;
35
45
  install(context: ServiceContext): Promise<void>;
36
46
  start(context: ServiceContext): Promise<void>;
37
47
  stop(context: ServiceContext): Promise<void>;
38
48
  uninstall?(context: ServiceContext): Promise<void>;
49
+ /**
50
+ * Removes a Service registered under this name by another installation of Murmur (a pilot or
51
+ * an earlier version), so that install can follow in the same elevated process. Resolves
52
+ * without change when there is none; refuses a Service that does not run Murmur.
53
+ */
54
+ removePrevious?(context: ServiceContext): Promise<void>;
39
55
  detectClients(context: ServiceContext): Promise<ClientDetection[]>;
56
+ /** Native log location, after verifying the selected service owns this profile. */
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>;
40
60
  }