@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 +1 @@
1
- {"name":"@murmurv2/cli","private":true,"version":"2.12.0","type":"module","main":"dist/src/index.js","types":"dist/src/index.d.ts"}
1
+ {"name":"@murmurv2/cli","private":true,"version":"2.13.0","type":"module","main":"dist/src/index.js","types":"dist/src/index.d.ts"}
@@ -0,0 +1,93 @@
1
+ import path from "node:path";
2
+ import { RosterStore, authorizeInbound, parseAddress } from "@murmurv2/federation";
3
+ import { readPrivateJson } from "./secure-state.mjs";
4
+
5
+ export function normalizeAuthSecurity(config = {}, env = process.env, dataDir = ".") {
6
+ const settings = config.authz ?? {};
7
+ const rawEnforce = env.MURMUR_ENFORCE_AUTH ?? settings.enforce;
8
+ let enforce = false;
9
+ if (rawEnforce !== undefined) {
10
+ if (env.MURMUR_ENFORCE_AUTH !== undefined) {
11
+ if (rawEnforce === "1" || rawEnforce === "true") enforce = true;
12
+ else if (rawEnforce === "0" || rawEnforce === "false") enforce = false;
13
+ else throw new Error("auth-security-invalid:enforce");
14
+ } else if (typeof rawEnforce === "boolean") {
15
+ enforce = rawEnforce;
16
+ } else {
17
+ throw new Error("auth-security-invalid:enforce");
18
+ }
19
+ }
20
+ const localOrg = String(env.MURMUR_AUTH_LOCAL_ORG ?? settings.localOrg ?? "local").trim();
21
+ const agentId = String(config.agentId ?? "probe").trim();
22
+ const audience = parseAddress(agentId, localOrg);
23
+ const explicitRoster = env.MURMUR_ROSTER_PATH ?? settings.rosterPath;
24
+ const rosterPath = explicitRoster
25
+ ? path.resolve(dataDir, String(explicitRoster))
26
+ : path.join(dataDir, "federation-roster.json");
27
+ const rawScopes = settings.requiredScopes ?? ["murmur:send"];
28
+ if (!Array.isArray(rawScopes) || rawScopes.length === 0 || !rawScopes.every((s) => typeof s === "string" && s.length > 0)) {
29
+ throw new Error("auth-security-invalid:requiredScopes");
30
+ }
31
+ return {
32
+ enforce,
33
+ localOrg,
34
+ audience,
35
+ rosterPath,
36
+ rosterExplicit: Boolean(explicitRoster),
37
+ requiredScopes: [...rawScopes],
38
+ };
39
+ }
40
+
41
+ export async function loadRosterStoreFromBundle(rosterPath) {
42
+ const bundle = await readPrivateJson(rosterPath);
43
+ if (!bundle || typeof bundle !== "object" || typeof bundle.pinnedOrgKeys !== "object" || bundle.pinnedOrgKeys === null || !Array.isArray(bundle.rosters)) {
44
+ throw new Error("auth-roster-bundle-invalid");
45
+ }
46
+ const store = new RosterStore(bundle.pinnedOrgKeys);
47
+ for (const roster of bundle.rosters) {
48
+ const offered = await store.offer(roster);
49
+ if (!offered.accepted) {
50
+ throw new Error(`auth-roster-rejected:${roster?.org ?? "unknown"}:${offered.reason ?? "denied"}`);
51
+ }
52
+ }
53
+ return store;
54
+ }
55
+
56
+ export async function createDaemonInboundAuthorizer({ config = {}, env = process.env, dataDir = ".", log = () => {} }) {
57
+ const policy = normalizeAuthSecurity(config, env, dataDir);
58
+ if (!policy.enforce && !policy.rosterExplicit) {
59
+ return {
60
+ summary: { enforce: false, active: false, localOrg: policy.localOrg },
61
+ authorize: undefined,
62
+ };
63
+ }
64
+ const rosters = await loadRosterStoreFromBundle(policy.rosterPath);
65
+ const authorize = async (envelope) => {
66
+ const verdict = await authorizeInbound(envelope, rosters, {
67
+ localOrg: policy.localOrg,
68
+ audience: policy.audience,
69
+ requiredScopes: policy.requiredScopes,
70
+ enforce: policy.enforce,
71
+ });
72
+ if (!verdict.accepted) {
73
+ // Never log envelope.authToken; record only msgId, sender, audience and reject reason.
74
+ log("warn", "Inbound authorization rejected", {
75
+ reason: verdict.reason ?? "denied",
76
+ senderId: envelope.senderAgentId,
77
+ msgId: envelope.msgId,
78
+ conversationId: envelope.conversationId,
79
+ });
80
+ }
81
+ return verdict;
82
+ };
83
+ return {
84
+ summary: {
85
+ enforce: policy.enforce,
86
+ active: true,
87
+ localOrg: policy.localOrg,
88
+ rosterPath: policy.rosterPath,
89
+ requiredScopes: policy.requiredScopes,
90
+ },
91
+ authorize,
92
+ };
93
+ }
@@ -13,6 +13,7 @@ const DEFAULT_TURN_COMPLETION_TIMEOUT_MS = 180000;
13
13
  const DEFAULT_UNOBSERVABLE_TIMEOUT_MS = 300000;
14
14
  const SESSION_LOG_POLL_INTERVAL_MS = 1000;
15
15
  const SESSION_LOG_TAIL_BYTES = 8 * 1024 * 1024;
16
+ export const NO_REPLY_REQUIRED = '[[MURMUR_NO_REPLY_REQUIRED]]';
16
17
 
17
18
  const shellQuote = (value) => `'${String(value ?? "").replace(/'/g, "'\\''")}'`;
18
19
 
@@ -23,6 +24,7 @@ const buildReplyHint = (payload, peer = {}) => {
23
24
  "[MURMUR REPLY RELAY]",
24
25
  "If this Murmur message asks for a reply, put only the reply body in your final answer.",
25
26
  "Do not call tools to send Murmur yourself; the local daemon will relay your final answer back through Murmur.",
27
+ `If the message requires no substantive reply under the existing owner instructions (for example ACK, thanks, or an explicit no-reply notice), return exactly ${NO_REPLY_REQUIRED} as your final answer. This is a local completion receipt and is never sent to the peer. Do not use it for an unanswered question, missing access, or a failed task.`,
26
28
  ];
27
29
  }
28
30
 
@@ -754,6 +756,17 @@ export const createCodexAppServerInjector = ({
754
756
  }
755
757
  if (!relayEnabled) return result;
756
758
  const finalText = String(result?.finalText || "").trim();
759
+ if (finalText === NO_REPLY_REQUIRED && result?.status !== 'completed') {
760
+ throw Object.assign(new Error('codex-app-server-no-reply-completion-unverified'), {retryable:false});
761
+ }
762
+ if (finalText === NO_REPLY_REQUIRED) {
763
+ const receipt = await turns.get(payload.msgId);
764
+ if (receipt) await turns.set({...receipt, outcome:'no_reply_required'});
765
+ log('info', 'Codex app-server wake completed without a reply by explicit decision', {
766
+ msgId: payload.msgId, threadId, turnId: result.turnId, source: result.source,
767
+ });
768
+ return { ...result, finalText: null, replyMsgId: null, outcome: 'no_reply_required' };
769
+ }
757
770
  if (!finalText) {
758
771
  // #106 — the turn ended and there is nothing to relay. That is not a relay;
759
772
  // logging it as one is how the peer waited six hours believing it was answered.
@@ -1,4 +1,4 @@
1
- import { AgentConfigCache } from '../packages/mcp-server/dist/src/agent-config.js';
1
+ import { AgentConfigCache } from '@murmurv2/mcp-server/dist/src/agent-config.js';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
3
 
4
4
  const key = value => typeof value === 'string' && Buffer.from(value, 'base64').length === 32
@@ -0,0 +1,140 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * murmur-auth-token.mjs — Mint and verify roster-backed MURMUR-AUTH bearer tokens.
4
+ * Private keys are read only from 0600 files; never pass private keys on argv.
5
+ */
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import {
10
+ decodeAuthToken,
11
+ encodeAuthToken,
12
+ formatAddress,
13
+ parseAddress,
14
+ signAuthToken,
15
+ verifyAuthToken,
16
+ } from "@murmurv2/federation";
17
+ import { readPrivateJson } from "./secure-state.mjs";
18
+ import { loadRosterStoreFromBundle } from "./auth-security.mjs";
19
+
20
+ const HERE = fileURLToPath(import.meta.url);
21
+
22
+ function parseArgs(argv) {
23
+ const [subcommand, ...rest] = argv;
24
+ const opts = {};
25
+ for (let i = 0; i < rest.length; i++) {
26
+ const arg = rest[i];
27
+ if (!arg.startsWith("--")) throw new Error(`Unexpected argument: ${arg}`);
28
+ const key = arg.slice(2);
29
+ if (key === "token-stdin") {
30
+ opts.tokenStdin = true;
31
+ continue;
32
+ }
33
+ const val = rest[++i];
34
+ if (!val || val.startsWith("--")) throw new Error(`Missing value for --${key}`);
35
+ opts[key] = val;
36
+ }
37
+ return { subcommand, opts };
38
+ }
39
+
40
+ export async function runAuthTokenCli(argv, stdinText = null) {
41
+ const { subcommand, opts } = parseArgs(argv);
42
+ if (subcommand === "mint") {
43
+ for (const req of ["issuer", "subject", "audience", "signing-key-file"]) {
44
+ if (!opts[req]) throw new Error(`Missing --${req}`);
45
+ }
46
+ const ttlSec = opts["ttl-seconds"] ? Number(opts["ttl-seconds"]) : 3600;
47
+ if (!Number.isInteger(ttlSec) || ttlSec <= 0 || ttlSec > 365 * 86400) {
48
+ throw new Error("Invalid --ttl-seconds");
49
+ }
50
+ const scopes = (opts.scopes ?? "murmur:send").split(",").map((s) => s.trim()).filter(Boolean);
51
+ const keyMaterial = await readPrivateJson(path.resolve(opts["signing-key-file"]));
52
+ const signingPrivateKey = keyMaterial?.signingPrivateKey ?? keyMaterial?.keys?.signing?.privateKey;
53
+ if (typeof signingPrivateKey !== "string" || signingPrivateKey.length === 0) {
54
+ throw new Error("signing-key-file missing signingPrivateKey");
55
+ }
56
+ const nowMs = opts.now ? Date.parse(opts.now) : Date.now();
57
+ if (!Number.isFinite(nowMs)) throw new Error("Invalid --now");
58
+ const localOrg = opts["local-org"] ?? "local";
59
+ const issuedAt = new Date(nowMs).toISOString();
60
+ const expiresAt = new Date(nowMs + ttlSec * 1000).toISOString();
61
+ const signed = await signAuthToken(
62
+ {
63
+ issuer: parseAddress(opts.issuer, localOrg),
64
+ subject: parseAddress(opts.subject, localOrg),
65
+ audience: parseAddress(opts.audience, localOrg),
66
+ scopes,
67
+ issuedAt,
68
+ expiresAt,
69
+ ...(opts.nonce ? { nonce: opts.nonce } : {}),
70
+ },
71
+ signingPrivateKey,
72
+ );
73
+ const token = encodeAuthToken(signed);
74
+ return {
75
+ exitCode: 0,
76
+ output: {
77
+ ok: true,
78
+ issuer: formatAddress(signed.issuer),
79
+ subject: formatAddress(signed.subject),
80
+ audience: formatAddress(signed.audience),
81
+ scopes: signed.scopes,
82
+ issuedAt: signed.issuedAt,
83
+ expiresAt: signed.expiresAt,
84
+ token,
85
+ },
86
+ };
87
+ }
88
+
89
+ if (subcommand === "verify") {
90
+ if (!opts["roster-file"]) throw new Error("Missing --roster-file");
91
+ const rawToken = (opts["token-file"]
92
+ ? fs.readFileSync(path.resolve(opts["token-file"]), "utf8")
93
+ : opts.tokenStdin
94
+ ? (stdinText ?? fs.readFileSync(0, "utf8"))
95
+ : "").trim();
96
+ if (!rawToken) throw new Error("Supply --token-stdin or --token-file");
97
+ const rosters = await loadRosterStoreFromBundle(path.resolve(opts["roster-file"]));
98
+ let decoded;
99
+ try {
100
+ decoded = decodeAuthToken(rawToken);
101
+ } catch {
102
+ return { exitCode: 1, output: { accepted: false, reason: "malformed" } };
103
+ }
104
+ const localOrg = opts["local-org"] ?? "local";
105
+ const scopes = opts.scopes ? opts.scopes.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
106
+ const verdict = await verifyAuthToken(decoded, rosters, {
107
+ ...(opts.audience ? { audience: parseAddress(opts.audience, localOrg) } : {}),
108
+ ...(opts.subject ? { requiredSubject: parseAddress(opts.subject, localOrg) } : {}),
109
+ ...(scopes ? { requiredScopes: scopes } : {}),
110
+ ...(opts.now ? { now: opts.now } : {}),
111
+ });
112
+ return {
113
+ exitCode: verdict.accepted ? 0 : 1,
114
+ output: verdict.accepted
115
+ ? {
116
+ accepted: true,
117
+ issuer: formatAddress(decoded.issuer),
118
+ subject: formatAddress(decoded.subject),
119
+ audience: formatAddress(decoded.audience),
120
+ scopes: decoded.scopes,
121
+ expiresAt: decoded.expiresAt,
122
+ }
123
+ : verdict,
124
+ };
125
+ }
126
+
127
+ throw new Error("Usage: node scripts/murmur-auth-token.mjs <mint|verify> [options]");
128
+ }
129
+
130
+ if (process.argv[1] && path.resolve(process.argv[1]) === HERE) {
131
+ runAuthTokenCli(process.argv.slice(2))
132
+ .then(({ exitCode, output }) => {
133
+ console.log(JSON.stringify(output));
134
+ process.exitCode = exitCode;
135
+ })
136
+ .catch((err) => {
137
+ console.error(JSON.stringify({ ok: false, error: err.message }));
138
+ process.exitCode = 1;
139
+ });
140
+ }
@@ -13,6 +13,8 @@ import {
13
13
  SQLiteMessageStore,
14
14
  stableAckPayload,
15
15
  stableEnvelopePayload,
16
+ resolveInstallation,
17
+ installationStorePath,
16
18
  } from "@murmurv2/core";
17
19
  import { decryptPayload, signEnvelope, verifyEnvelopeSignature } from "@murmurv2/security";
18
20
  import { NotifyQueue, flushNotifyQueue, normalizeNotifyTargets, enqueuePeerNotification } from "./notify-router.mjs";
@@ -26,6 +28,7 @@ import { flushTick } from "./daemon-flush-tick.mjs";
26
28
  import { createDaemonObservation } from "./daemon-observation.mjs";
27
29
  import { createLinkWatch } from "./daemon-link-watch.mjs";
28
30
  import { normalizeAckSecurity } from "./ack-security.mjs";
31
+ import { createDaemonInboundAuthorizer } from "./auth-security.mjs";
29
32
  import { classifyVerifiedDoctorMessage, createDoctorResponder } from "./doctor-protocol.mjs";
30
33
  // vault-guard: optional content policy hook (not included in OSS release)
31
34
 
@@ -38,7 +41,10 @@ const log = (level, msg, data) => {
38
41
  observeLog(level, msg, data);
39
42
  };
40
43
 
41
- const dataDir = process.env.DATA_DIR || ".data";
44
+ const { dataDir } = resolveInstallation({ env: process.env, requireConfig: true });
45
+ // Hooks inherit this process's pinned choice even if a person later selects another installation.
46
+ process.env.DATA_DIR = dataDir;
47
+ process.env.MURMUR_DATA_DIR = dataDir;
42
48
  const configPath = path.join(dataDir, "agent-config.json");
43
49
 
44
50
  let config;
@@ -53,8 +59,12 @@ try {
53
59
  process.exit(1);
54
60
  }
55
61
 
56
- const { agentId, natsUrl, natsToken, subject, keys } = config;
57
- const dbPath = path.join(dataDir, "murmur.db");
62
+ const { agentId, natsUrl, natsToken, natsUser, natsPassword, natsTls, subject, keys } = config;
63
+ const dbPath = installationStorePath(dataDir, 'murmur.db', process.env.MURMUR_STORE_PATH);
64
+ // Refuse conflicting installation paths before any SQLite store is opened.
65
+ const channelRosterConfig = config.channelRoster || {};
66
+ const channelRosterEnabled = channelRosterConfig.enabled ?? process.env.MURMUR_CHANNEL_ROSTER === "1";
67
+ const channelRosterPath = channelRosterConfig.path || installationStorePath(dataDir, 'channel-roster.db', process.env.MURMUR_CHANNEL_ROSTER_PATH);
58
68
  const flushIntervalMs = Number(process.env.FLUSH_INTERVAL_MS) || 2000;
59
69
  const jetstreamConfig = config.jetstream || {};
60
70
  const jetstreamEnabled = jetstreamConfig.enabled ?? process.env.MURMUR_JETSTREAM === "1";
@@ -85,6 +95,7 @@ const ackSecurityConfig = config.ackSecurity || {};
85
95
  const ackPolicy = normalizeAckSecurity(config, process.env, log);
86
96
  const emitSignedAcks = ackPolicy.emitSigned;
87
97
  const requireSignedAcks = ackPolicy.requireSigned;
98
+ const authPolicy = await createDaemonInboundAuthorizer({ config, env: process.env, dataDir, log });
88
99
  const maxAckAgeMs = optionalPositiveInteger(
89
100
  "ack-max-age-ms",
90
101
  firstDefined(ackSecurityConfig.maxAgeMs, process.env.MURMUR_ACK_MAX_AGE_MS),
@@ -130,6 +141,7 @@ log("info", "Daemon starting", {
130
141
  ...ackPolicy,
131
142
  maxAgeMs: maxAckAgeMs,
132
143
  },
144
+ authz: authPolicy.summary,
133
145
  ackWindow,
134
146
  wake: { enabled: wakeConfig.enabled, mode: wakeConfig.mode, hookConfigured: Boolean(config.onReceive) },
135
147
  notifyTargets: effectiveNotifyTargets.map((t) => `${t.type}:${t.channel}`),
@@ -155,9 +167,6 @@ const nativeLeaseGate = leaseStore
155
167
  : null;
156
168
  if (scopedChannelsEnabled) log("info", "Scoped-channels native lease gate enabled", { ttlMs: nativeLeaseTtlMs });
157
169
 
158
- const channelRosterConfig = config.channelRoster || {};
159
- const channelRosterEnabled = channelRosterConfig.enabled ?? process.env.MURMUR_CHANNEL_ROSTER === "1";
160
- const channelRosterPath = channelRosterConfig.path || process.env.MURMUR_CHANNEL_ROSTER_PATH || path.join(dataDir, "channel-roster.db");
161
170
  const channelRosterStore = channelRosterEnabled ? new ChannelRosterStore(channelRosterPath) : null;
162
171
  const subjectRoutes = channelSubjectRoutes(subject, agentId, config.subjectScoping);
163
172
  if (subjectRoutes.length > 1) {
@@ -198,7 +207,11 @@ const broker = new NatsBroker({
198
207
  connectBaseBackoffMs: 2000,
199
208
  url: natsUrl,
200
209
  token: natsToken,
210
+ user: natsUser,
211
+ password: natsPassword,
212
+ tls: natsTls,
201
213
  jetstream: jetstreamEnabled,
214
+ jetstreamProvisioning: jetstreamConfig.provisioning,
202
215
  stream: jetstreamEnabled ? jetstreamStream : undefined,
203
216
  streamSubjects: jetstreamSubjects,
204
217
  jetstreamMaxDeliver,
@@ -448,6 +461,7 @@ try {
448
461
  consumerId: agentId,
449
462
  dedupe: store,
450
463
  onMessage,
464
+ ...(authPolicy.authorize ? { authorize: authPolicy.authorize } : {}),
451
465
  ...(emitSignedAcks ? { signAck } : {}),
452
466
  });
453
467
  log("info", "Subscribed", route);
@@ -531,6 +545,8 @@ try {
531
545
  broker,
532
546
  outbox: store,
533
547
  jetstreamEnabled,
548
+ advisoryDlq: jetstreamConfig.advisoryDlq,
549
+ provisioning: jetstreamConfig.provisioning,
534
550
  log,
535
551
  });
536
552
 
@@ -1,10 +1,37 @@
1
+ // Advisory DLQ correlation subscribes to broker-wide `$JS.EVENT.ADVISORY.*` subjects and
2
+ // reads the dead message back with STREAM.MSG.GET. A restricted runtime role
3
+ // (`jetstream.provisioning: "client"`, see docs/nats-transport-security.md) has neither
4
+ // permission by design, so for that role the feature is off unless the operator turns it
5
+ // on explicitly with `jetstream.advisoryDlq: true` after granting those subjects.
6
+ export function resolveAdvisoryDlqEnabled({ advisoryDlq, provisioning } = {}) {
7
+ if (advisoryDlq === true) return { enabled: true, reason: "explicit" };
8
+ if (advisoryDlq === false) return { enabled: false, reason: "explicit" };
9
+ if (provisioning === "client") return { enabled: false, reason: "client-provisioning" };
10
+ return { enabled: true, reason: "default" };
11
+ }
12
+
1
13
  export async function startJetStreamAdvisoryDlqIfEnabled({
2
14
  broker,
3
15
  outbox,
4
16
  jetstreamEnabled,
17
+ advisoryDlqEnabled,
18
+ advisoryDlq,
19
+ provisioning,
5
20
  log = () => {},
6
21
  }) {
7
22
  if (!jetstreamEnabled) return undefined;
23
+ const decision =
24
+ advisoryDlqEnabled === undefined
25
+ ? resolveAdvisoryDlqEnabled({ advisoryDlq, provisioning })
26
+ : { enabled: Boolean(advisoryDlqEnabled), reason: "explicit" };
27
+ if (!decision.enabled) {
28
+ if (decision.reason === "client-provisioning") {
29
+ log("info", "JetStream advisory DLQ correlation disabled for client provisioning", {
30
+ hint: 'set jetstream.advisoryDlq: true after granting $JS.EVENT.ADVISORY.> and STREAM.MSG.GET to this role',
31
+ });
32
+ }
33
+ return undefined;
34
+ }
8
35
  const subscription = await broker.startJetStreamAdvisoryDlq({ outbox });
9
36
  log("info", "JetStream advisory DLQ correlation started");
10
37
  return subscription;
@@ -5,7 +5,7 @@
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { readFileSync } from "node:fs";
7
7
  import path from "node:path";
8
- import { SQLiteDedupeOutboxStore, SQLiteMessageStore, stableEnvelopePayload, resolveMessageSubject } from "@murmurv2/core";
8
+ import { SQLiteDedupeOutboxStore, SQLiteMessageStore, stableEnvelopePayload, resolveMessageSubject, resolveInstallation, installationStorePath } from "@murmurv2/core";
9
9
  import { encryptPayload, signEnvelope } from "@murmurv2/security";
10
10
  import { readPrivateJson } from "./secure-state.mjs";
11
11
 
@@ -51,9 +51,9 @@ if (!text) {
51
51
  process.exit(1);
52
52
  }
53
53
 
54
- const dataDir = process.env.DATA_DIR || ".data";
54
+ const { dataDir } = resolveInstallation({ env: process.env, requireConfig: true });
55
55
  const configPath = path.join(dataDir, "agent-config.json");
56
- const dbPath = process.env.MURMUR_STORE_PATH ?? path.join(dataDir, "murmur.db");
56
+ const dbPath = installationStorePath(dataDir, 'murmur.db', process.env.MURMUR_STORE_PATH);
57
57
 
58
58
  let cfg;
59
59
  try {
@@ -83,8 +83,31 @@
83
83
  // MURMUR_WAKE_SKIPPED_LOG append-only JSONL ledger of skipped rows
84
84
  // (default: ~/.murmur-wake-skipped.jsonl)
85
85
  //
86
- // All three filters are OFF by default: with no MURMUR_WAKE_SKIP_* set, every inbound row
87
- // is reported exactly as before.
86
+ // Session binding (AIM-5939). When a Claude Code session sends on a conversation, the MCP
87
+ // server records that session as the conversation's owner next to the store. A reply on
88
+ // that conversation then wakes only the owner; every other session skips it with reason
89
+ // "bound-to-other-session" (in the ledger, like any other skip). The binding is honoured
90
+ // while it is fresh, whether or not the owner is running: a closed or restarted session
91
+ // keeps its replies and takes them on resume (its SessionStart drain reads from its own
92
+ // cursor). Once the binding is older than the TTL, every session wakes, as before. A conversation nobody has sent on yet is never bound. `dm:a:b` and `dm:b:a`
93
+ // are one conversation. When the conversation is not bound, the sender is: the session that
94
+ // last wrote to a peer also owns that peer's new letters, under the same freshness rules.
95
+ // MURMUR_WAKE_BINDINGS_DIR binding directory (default: <store dir>/.claude-session-bindings)
96
+ // MURMUR_WAKE_BIND_TTL_SECONDS how long a binding holds after its last send (default 604800)
97
+ // MURMUR_WAKE_ONLY_BOUND "1": this session wakes only on replies in conversations
98
+ // bound to itself; every other row is skipped with reason
99
+ // "not-bound-to-this-session". Set it in the env of projects
100
+ // that should not take letters nobody asked them for.
101
+ // MURMUR_WAKE_CONVERSATION_PREFIX comma-separated conversation id prefixes this session
102
+ // answers for, e.g. "school:" or "school:,docs:".
103
+ // An unbound conversation with a matching prefix wakes this
104
+ // session even when a peer started it; an unbound one that
105
+ // matches none is skipped with reason "prefix-mismatch".
106
+ // A conversation bound to another live session stays with
107
+ // it; the peer binding does not override a prefix match.
108
+ //
109
+ // The three MURMUR_WAKE_SKIP_* filters are OFF by default: with none set, every inbound row
110
+ // that is not bound to another live session is reported exactly as before.
88
111
 
89
112
  import { DatabaseSync } from "node:sqlite";
90
113
  import {
@@ -103,7 +126,13 @@ const DB = (dbArgument > 0 && process.argv[dbArgument + 1]) || process.env.MURMU
103
126
  // the first session to reach the hook advances it past the message and every other live
104
127
  // session — including the one holding the conversation — never sees it (see
105
128
  // murmur-coldidle-watch.sh for the measurement that produced this).
106
- const SESSION_KEY = (process.env.MURMUR_WAKE_SESSION_KEY || process.env.CLAUDE_CODE_SESSION_ID || "").slice(0, 8);
129
+ const sessionArgument = process.argv.indexOf("--session-key");
130
+ const explicitSession = sessionArgument > 0 ? process.argv[sessionArgument + 1] : undefined;
131
+ if (sessionArgument > 0 && !/^[a-zA-Z0-9_-]{1,8}$/.test(explicitSession ?? "")) {
132
+ process.stderr.write("murmur wake: invalid --session-key\n");
133
+ process.exit(0);
134
+ }
135
+ const SESSION_KEY = (explicitSession || process.env.MURMUR_WAKE_SESSION_KEY || process.env.CLAUDE_CODE_SESSION_ID || "").slice(0, 8);
107
136
  const suffix = SESSION_KEY ? `-${SESSION_KEY}` : "";
108
137
  // Store key: cursor, lock and anchor describe one store. Shared between two profiles (or a
109
138
  // test next to a live profile), the store with larger rowids moves the other's anchor forward
@@ -145,6 +174,88 @@ const SKIP_SENDERS = new Set(parseList(process.env.MURMUR_WAKE_SKIP_SENDERS));
145
174
  const SKIP_CONVERSATIONS = new Set(parseList(process.env.MURMUR_WAKE_SKIP_CONVERSATIONS));
146
175
  const SKIP_INELIGIBLE = process.env.MURMUR_WAKE_SKIP_INELIGIBLE === "1";
147
176
 
177
+ // --- session binding (AIM-5939) -----------------------------------------------
178
+ const BINDINGS_DIR = process.env.MURMUR_WAKE_BINDINGS_DIR || join(dirname(STORE_PATH), ".claude-session-bindings");
179
+ // A week: a peer often answers the next working day, long after the 8-hour wake window.
180
+ const BIND_TTL_MS = count(process.env.MURMUR_WAKE_BIND_TTL_SECONDS, 604800) * 1000;
181
+ const bindingCache = new Map();
182
+
183
+ // Opt-in per project: a session with MURMUR_WAKE_ONLY_BOUND=1 wakes only on replies in
184
+ // conversations bound to itself. Letters nobody asked for go to the other sessions.
185
+ const ONLY_BOUND = process.env.MURMUR_WAKE_ONLY_BOUND === "1";
186
+
187
+ // Opt-in per project: conversation id prefixes this session takes when nobody holds them.
188
+ const CONVERSATION_PREFIXES = String(process.env.MURMUR_WAKE_CONVERSATION_PREFIX || "")
189
+ .split(",").map((p) => p.trim()).filter(Boolean);
190
+ const prefixMatches = (conversationId) =>
191
+ CONVERSATION_PREFIXES.some((p) => String(conversationId || "").startsWith(p));
192
+
193
+ // The two sides of one DM may name it `dm:a:b` and `dm:b:a`; both are one conversation.
194
+ function canonicalConversationId(conversationId) {
195
+ const dm = /^dm:([^:]+):([^:]+)$/.exec(conversationId);
196
+ return dm ? `dm:${[dm[1], dm[2]].sort().join(":")}` : conversationId;
197
+ }
198
+
199
+ /**
200
+ * The session key in one binding file if it is fresh, else null. The owner's MCP pid is not
201
+ * checked: it changes on every resume of the same session, and a dead pid used to hand the
202
+ * reply to every open session.
203
+ */
204
+ function readOwner(file, field, value) {
205
+ if (bindingCache.has(file)) return bindingCache.get(file);
206
+ let owner = null;
207
+ try {
208
+ const binding = JSON.parse(readFileSync(join(BINDINGS_DIR, file), "utf8"));
209
+ const key = String(binding.sessionId || "").slice(0, 8);
210
+ const age = Date.now() - Date.parse(binding.updatedAt);
211
+ if (binding[field] === value && key && age >= 0 && age <= BIND_TTL_MS) {
212
+ owner = key;
213
+ }
214
+ } catch {
215
+ // No binding, or an unreadable one: not bound.
216
+ }
217
+ bindingCache.set(file, owner);
218
+ return owner;
219
+ }
220
+
221
+ const digest = (value) => createHash("sha256").update(value).digest("hex");
222
+
223
+ /**
224
+ * The session that owns this row: the owner of its conversation, otherwise the session
225
+ * that last wrote to its sender (a new letter from a peer goes to whoever is talking to it).
226
+ * null when neither is bound.
227
+ */
228
+ function conversationOwner(conversationId) {
229
+ if (!conversationId) return null;
230
+ const canonical = canonicalConversationId(conversationId);
231
+ return readOwner(`${digest(canonical)}.json`, "conversationId", canonical)
232
+ // An MCP server from before the DM rule still writes the id as given.
233
+ || (canonical !== conversationId
234
+ ? readOwner(`${digest(conversationId)}.json`, "conversationId", conversationId) : null);
235
+ }
236
+
237
+ function boundOwner(conversationId, sender) {
238
+ return conversationOwner(conversationId)
239
+ || (sender ? readOwner(`peer-${digest(sender)}.json`, "peerId", sender) : null);
240
+ }
241
+
242
+ /** Why this session must not wake on the row, or null. */
243
+ function bindingSkip(row) {
244
+ if (CONVERSATION_PREFIXES.length) {
245
+ const owner = SESSION_KEY ? conversationOwner(row.conversationId) : null;
246
+ if (owner) return owner === SESSION_KEY ? null : "bound-to-other-session";
247
+ if (prefixMatches(row.conversationId)) return null;
248
+ if (SESSION_KEY && boundOwner(row.conversationId, row.sender) === SESSION_KEY) return null;
249
+ return "prefix-mismatch";
250
+ }
251
+ // Without its own key a drain cannot tell its conversations from anyone else's.
252
+ if (!SESSION_KEY) return ONLY_BOUND ? "not-bound-to-this-session" : null;
253
+ const owner = boundOwner(row.conversationId, row.sender);
254
+ if (owner && owner !== SESSION_KEY) return "bound-to-other-session";
255
+ if (ONLY_BOUND && owner !== SESSION_KEY) return "not-bound-to-this-session";
256
+ return null;
257
+ }
258
+
148
259
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
149
260
 
150
261
  function readCursor() {
@@ -279,6 +390,8 @@ function skipReason(row) {
279
390
  // Daemon-owned diagnostics are never AI work. Keep their skip in the same
280
391
  // durable ledger as explicit filters before advancing this session's cursor.
281
392
  if (Number(row.wakeEligible) === 0 && String(row.conversationId).startsWith("murmur:doctor:")) return "doctor-protocol";
393
+ const bound = bindingSkip(row);
394
+ if (bound) return bound;
282
395
  if (SKIP_SENDERS.has(row.sender)) return "sender-filtered";
283
396
  if (SKIP_CONVERSATIONS.has(row.conversationId)) return "conversation-filtered";
284
397
  if (SKIP_INELIGIBLE && Number(row.wakeEligible) === 0) return "wake-ineligible";
@@ -349,6 +462,8 @@ function firstStart(db, anchor) {
349
462
  * the last row of THIS result set, reported or recorded, and nothing beyond it.
350
463
  */
351
464
  function drainBatch(db, since) {
465
+ // A poll lives for hours; a binding written meanwhile must count on the next pass.
466
+ bindingCache.clear();
352
467
  const rows = newRows(db, since);
353
468
  if (!rows.length) return null;
354
469
  const { report, skipped } = partition(rows);
@@ -439,6 +554,12 @@ async function main() {
439
554
  // DB not present (daemon never started) → nothing to do, and say which path was tried.
440
555
  try { statSync(DB); } catch (err) { bail("store not readable", err); }
441
556
  const deadline = ONCE || SESSION ? 0 : Date.now() + MAX_SECONDS * 1000;
557
+ // Own the lane before any cursor initialization or legacy adoption: otherwise a
558
+ // losing reader can reset the winner's cursor and replay an already emitted row.
559
+ if ((!ONCE && !SESSION) || explicitSession) {
560
+ if (!acquireLock()) process.exit(0);
561
+ process.on("exit", releaseLock);
562
+ }
442
563
 
443
564
  if (legacyPending(ANCHOR, LEGACY_ANCHOR) || legacyPending(CURSOR, LEGACY_CURSOR)) {
444
565
  const tip = await readStore(maxInbound, deadline);
@@ -503,10 +624,6 @@ async function main() {
503
624
  process.exit(0);
504
625
  }
505
626
 
506
- // poll mode: only one poller at a time
507
- if (!acquireLock()) process.exit(0);
508
- process.on("exit", releaseLock);
509
-
510
627
  while (Date.now() < deadline) {
511
628
  const batch = await readStore(db => drainBatch(db, readCursor()), deadline);
512
629
  if (batch?.report.length) emitAndExit(batch.report, batch.examinedTo);