@murmurv2/cli 2.12.0 → 2.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +65 -24
  2. package/package.json +7 -6
  3. package/runtime/bin/murmur-svc.exe +0 -0
  4. package/runtime/npm-runtime-manifest.json +175 -79
  5. package/runtime/package.json +1 -1
  6. package/runtime/packages/mcp-server/dist/src/agent-config.js +1 -0
  7. package/runtime/packages/setup/bin/murmur.mjs +3 -2
  8. package/runtime/packages/setup/dist/src/autoreply.d.ts +23 -0
  9. package/runtime/packages/setup/dist/src/autoreply.js +71 -0
  10. package/runtime/packages/setup/dist/src/backups.d.ts +36 -0
  11. package/runtime/packages/setup/dist/src/backups.js +128 -0
  12. package/runtime/packages/setup/dist/src/broker-input.d.ts +24 -0
  13. package/runtime/packages/setup/dist/src/broker-input.js +98 -0
  14. package/runtime/packages/setup/dist/src/broker-migration.d.ts +35 -0
  15. package/runtime/packages/setup/dist/src/broker-migration.js +138 -0
  16. package/runtime/packages/setup/dist/src/cli-error.d.ts +2 -0
  17. package/runtime/packages/setup/dist/src/cli-error.js +30 -0
  18. package/runtime/packages/setup/dist/src/cli.js +113 -10
  19. package/runtime/packages/setup/dist/src/clients.d.ts +33 -81
  20. package/runtime/packages/setup/dist/src/clients.js +159 -25
  21. package/runtime/packages/setup/dist/src/commands.d.ts +1 -0
  22. package/runtime/packages/setup/dist/src/commands.js +18 -6
  23. package/runtime/packages/setup/dist/src/config.d.ts +8 -0
  24. package/runtime/packages/setup/dist/src/config.js +58 -10
  25. package/runtime/packages/setup/dist/src/connect.d.ts +143 -0
  26. package/runtime/packages/setup/dist/src/connect.js +128 -0
  27. package/runtime/packages/setup/dist/src/conversations.d.ts +193 -0
  28. package/runtime/packages/setup/dist/src/conversations.js +674 -0
  29. package/runtime/packages/setup/dist/src/doctor.d.ts +30 -0
  30. package/runtime/packages/setup/dist/src/doctor.js +72 -10
  31. package/runtime/packages/setup/dist/src/installation.d.ts +25 -0
  32. package/runtime/packages/setup/dist/src/installation.js +89 -0
  33. package/runtime/packages/setup/dist/src/message-status.d.ts +1 -0
  34. package/runtime/packages/setup/dist/src/message-status.js +3 -0
  35. package/runtime/packages/setup/dist/src/onboarding.d.ts +11 -6
  36. package/runtime/packages/setup/dist/src/onboarding.js +92 -21
  37. package/runtime/packages/setup/dist/src/paths.d.ts +7 -0
  38. package/runtime/packages/setup/dist/src/paths.js +39 -24
  39. package/runtime/packages/setup/dist/src/platform/darwin.d.ts +3 -0
  40. package/runtime/packages/setup/dist/src/platform/darwin.js +247 -9
  41. package/runtime/packages/setup/dist/src/platform/linux.js +156 -12
  42. package/runtime/packages/setup/dist/src/platform/profile-usage.d.ts +20 -0
  43. package/runtime/packages/setup/dist/src/platform/profile-usage.js +89 -0
  44. package/runtime/packages/setup/dist/src/platform/windows.js +48 -8
  45. package/runtime/packages/setup/dist/src/private-file.d.ts +4 -1
  46. package/runtime/packages/setup/dist/src/private-file.js +39 -3
  47. package/runtime/packages/setup/dist/src/state.d.ts +4 -0
  48. package/runtime/packages/setup/dist/src/state.js +65 -1
  49. package/runtime/packages/setup/dist/src/status.d.ts +9 -0
  50. package/runtime/packages/setup/dist/src/status.js +7 -3
  51. package/runtime/packages/setup/dist/src/types.d.ts +11 -1
  52. package/runtime/packages/setup/dist/src/wake-readers.d.ts +12 -0
  53. package/runtime/packages/setup/dist/src/wake-readers.js +65 -0
  54. package/runtime/packages/setup/package.json +1 -1
  55. package/runtime/scripts/auth-security.mjs +93 -0
  56. package/runtime/scripts/codex-app-server-wake.mjs +36 -4
  57. package/runtime/scripts/daemon-contacts.mjs +1 -1
  58. package/runtime/scripts/murmur-auth-token.mjs +140 -0
  59. package/runtime/scripts/murmur-daemon.mjs +27 -8
  60. package/runtime/scripts/murmur-jetstream-advisory.mjs +27 -0
  61. package/runtime/scripts/murmur-shell-send.mjs +7 -3
  62. package/runtime/scripts/owner-review-store.mjs +54 -0
  63. package/runtime/scripts/wake-drain-claude.mjs +124 -7
  64. package/runtime/scripts/wake-monitor.mjs +49 -10
@@ -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);
@@ -17,6 +17,10 @@ export const normalizeWakeConfig = (config = {}) => {
17
17
  if (!Number.isSafeInteger(hookTimeoutMs) || hookTimeoutMs < 1 || hookTimeoutMs > 2147483647) {
18
18
  throw new Error("wake-hook-timeout-invalid");
19
19
  }
20
+ const auditHookTimeoutMs = wake.auditHookTimeoutMs === undefined ? 10000 : wake.auditHookTimeoutMs;
21
+ if (!Number.isSafeInteger(auditHookTimeoutMs) || auditHookTimeoutMs < 1 || auditHookTimeoutMs > 2147483647) {
22
+ throw new Error("wake-audit-hook-timeout-invalid");
23
+ }
20
24
  const peers = Object.fromEntries(
21
25
  Object.entries(ensureObject(wake.peers)).map(([agentId, peer]) => {
22
26
  const value = ensureObject(peer);
@@ -30,6 +34,7 @@ export const normalizeWakeConfig = (config = {}) => {
30
34
  if (typeof value.murmurRoot === "string" && value.murmurRoot.trim()) normalized.murmurRoot = value.murmurRoot.trim();
31
35
  if (typeof value.dataDir === "string" && value.dataDir.trim()) normalized.dataDir = value.dataDir.trim();
32
36
  if (typeof value.storePath === "string" && value.storePath.trim()) normalized.storePath = value.storePath.trim();
37
+ if (value.ownerReviewOnly === true) normalized.ownerReviewOnly = true;
33
38
  if (value.relayFinalToMurmur === true) normalized.relayFinalToMurmur = true;
34
39
  // Without this the injector's `peer.resume === false` opt-out is unreachable
35
40
  // from a real config: normalization used to drop the field entirely.
@@ -59,6 +64,7 @@ export const normalizeWakeConfig = (config = {}) => {
59
64
  return {
60
65
  enabled: wake.enabled !== false,
61
66
  hookTimeoutMs,
67
+ auditHookTimeoutMs,
62
68
  mode: validMode(wake.mode) ? wake.mode : "stateless",
63
69
  peers,
64
70
  auditHook: typeof wake.auditHook === "string" && wake.auditHook.trim() ? wake.auditHook.trim() : null,
@@ -129,12 +135,15 @@ export const createAuditShellHook = ({ command, timeoutMs = 10000, baseEnv = pro
129
135
  };
130
136
  execFile("sh", ["-c", command], { env, timeout: timeoutMs }, (err, stdout) => {
131
137
  if (err) {
132
- log("warn", "wake audit hook failed", { error: err.message, msgId: payload.msgId });
133
- resolve("deny");
138
+ // execFile's message contains the command and captured output. A timeout
139
+ // means admission is unknown; retain durable work without running it.
140
+ const timedOut = err.killed === true && err.signal === "SIGTERM";
141
+ log("warn", "wake audit hook failed", { error: timedOut ? "audit-hook-timeout" : "audit-hook-failed", msgId: payload.msgId });
142
+ resolve(timedOut ? "retry" : "deny");
134
143
  return;
135
144
  }
136
145
  const verdict = String(stdout || "").split(/\r?\n/, 1)[0]?.trim();
137
- resolve(verdict === "deny" || verdict === "require_approval" || verdict === "allow" ? verdict : "deny");
146
+ resolve(["deny", "require_approval", "allow", "retry"].includes(verdict) ? verdict : "deny");
138
147
  });
139
148
  });
140
149
  };
@@ -376,12 +385,24 @@ export class WakeMonitor {
376
385
  }
377
386
 
378
387
  this.seen.set(key, now);
379
- if (!prepareOnly && await this.isLoopBreakerBlocked(payload, now)) {
380
- await settle("muted", { error: "loop-breaker" });
381
- return;
382
- }
383
-
384
388
  const verdict = await this.audit(payload);
389
+ if (verdict === "retry") {
390
+ // Admission never reached an allow decision. Use the existing durable
391
+ // attempt/deadline fields; no turn, lease, or wake effect has happened.
392
+ const attempts = claim?.attempts ?? 1;
393
+ const retryable = durable && attempts < this.maxAttempts;
394
+ const delayMs = wakeRetryBackoffMs(attempts, this.retryBackoffMs, this.retryBackoffMaxMs);
395
+ await settle(retryable ? "failed" : "dlq", {
396
+ error: "audit-retry",
397
+ ...(retryable ? { nextAttemptAt: new Date(this.now() + delayMs).toISOString() } : {}),
398
+ });
399
+ this.log("warn", "WakeMonitor audit admission deferred", {
400
+ msgId: payload.msgId, attempt: attempts, status: retryable ? "failed" : "dlq",
401
+ ...(retryable ? { retryInMs: delayMs } : {}),
402
+ });
403
+ if (!retryable) await this.notify?.(payload, durable ? "wake-dlq" : "audit-retry-unavailable");
404
+ return prepareOnly ? { auditRetry: true } : undefined;
405
+ }
385
406
  if (verdict === "deny") {
386
407
  this.log("warn", "WakeMonitor audit denied wake", { msgId: payload.msgId, conversationId: payload.conversationId, from: payload.from });
387
408
  await settle("muted", { error: "audit-deny" });
@@ -393,6 +414,10 @@ export class WakeMonitor {
393
414
  await settle("muted", { error: "audit-require-approval" });
394
415
  return;
395
416
  }
417
+ if (!prepareOnly && await this.isLoopBreakerBlocked(payload, now)) {
418
+ await settle("muted", { error: "loop-breaker" });
419
+ return;
420
+ }
396
421
 
397
422
  // Scoped-channels lease gate (#82): the native daemon wake is a fallback owner.
398
423
  // If a live chat session already owns this conversation, mute the native wake so it
@@ -525,9 +550,23 @@ export class WakeMonitor {
525
550
  this.enqueuedAt.delete(this.keyFor(payload));
526
551
  }
527
552
  const ready = [];
553
+ const deferred = [];
528
554
  for (const payload of payloads) {
529
555
  const run = await this.processPayload(payload, { prepareOnly: true });
530
- if (run) ready.push({ payload, run });
556
+ if (typeof run === "function") ready.push({ payload, run });
557
+ else if (run?.auditRetry) deferred.push(payload);
558
+ }
559
+ if (previousBatch && deferred.length && ready.length + deferred.length === payloads.length) {
560
+ // A saved batch is one effect. A temporarily unavailable member must not
561
+ // turn its already grouped siblings into permanent policy mutes.
562
+ const attempts = Math.max(...payloads.map((payload) => payload.attempt));
563
+ const retryable = attempts < this.maxAttempts;
564
+ const outcome = { status: retryable ? "failed" : "dlq", error: "audit-retry", now: this.nowIso(),
565
+ ...(retryable ? { nextAttemptAt: new Date(this.now() + wakeRetryBackoffMs(attempts, this.retryBackoffMs, this.retryBackoffMaxMs)).toISOString() } : {}) };
566
+ await this.deliveries.settleWakeBatch(payloads.map((payload) => ({ msgId: payload.msgId, input: outcome })));
567
+ await this.advanceCursor(first);
568
+ if (!retryable) for (const { payload } of ready) await this.notify?.(payload, "wake-dlq");
569
+ return;
531
570
  }
532
571
  if (ready.length === 0) return;
533
572
  if (previousBatch && ready.length !== payloads.length) {
@@ -620,7 +659,7 @@ export class WakeMonitor {
620
659
  async audit(payload) {
621
660
  if (!this.auditHook) return "allow";
622
661
  const verdict = await this.auditHook(payload);
623
- return verdict === "allow" || verdict === "require_approval" || verdict === "deny" ? verdict : "deny";
662
+ return ["allow", "require_approval", "deny", "retry"].includes(verdict) ? verdict : "deny";
624
663
  }
625
664
 
626
665
  async advanceCursor(payload) {