@log0u7/opencode-mesh 0.30.1 → 0.32.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,70 @@ All notable changes to this project are documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.32.0] - 2026-11-26
9
+
10
+ ### Fixed
11
+
12
+ - The flash single-flight (F1): the "already announced" decision lives in the
13
+ SHARED database instead of per-instance memory. Two plugin instances' wake
14
+ loops each iterate ALL boxes with their own pendingPrompt/lastPromptAt
15
+ maps — neither saw the other's gate, 6admin got prompted 13s apart and
16
+ answered twice (two identical DMs, live). deliveries.flashed_at (schema
17
+ v17) + claimFlash(): one atomic UPDATE claims the box's announceable
18
+ unreads; 0 claimed = another instance announced them. The fatigue reminder
19
+ re-claims rows flashed before the reminder TTL (the starved box still
20
+ reminds), and a prompt whose host refused RELEASES its claim (a kept claim
21
+ starves the mail silently). pendingPrompt/lastPromptAt/cooldown are gone:
22
+ per-instance memory no longer carries any routing decision.
23
+ - The 2-minute absolute collapse window (F2): an identical re-send within
24
+ 2 minutes collapses EVEN IF the original was already read — the wake
25
+ double-prompt re-sent 13s after the receiver drained, and the dedup's
26
+ active-ping rule delivered it fresh. Past the window the active-ping
27
+ contract is unchanged.
28
+ - The mesh_wait timeout names the clamp (F4): "requested 60s" returning
29
+ "within 30s" with no word about the clamp read as a mechanical abort or
30
+ an agent silence. The message now says "requested Ns, clamped at
31
+ MESH_WAIT_MAX_S=30 — send, end the turn, the wake brings the reply" and
32
+ carries the doctrine on every timeout.
33
+
34
+ ### Added
35
+
36
+ - mesh_status exposes plugin_version (F3): the LOADED plugin version — the
37
+ runtime truth the config pin only intends. The convergence survey asked
38
+ agents for their loaded version and got guesses; the process now names
39
+ its own package, and the debugWake flash line is prefixed with v=.
40
+
41
+ ## [0.31.0] - 2026-11-26
42
+
43
+ ### Fixed
44
+
45
+ - A federated name is never a local box (P1): mailboxByName/listMailboxes
46
+ filter node_id IS NULL — a caller deciding "does this box live here?" can
47
+ no longer answer yes for a foreign row and sink mail into a box no local
48
+ session drains; federatedByName carries the routing row; the sidebar and
49
+ mesh_pools count local boxes only.
50
+ - The registry merge is hardened (P2): a BOUND local name (bind_key set) is
51
+ never ceded even when its session went quiet; the per-row validation
52
+ tightens (session_id <= 128, role <= 64, every pool entry must match
53
+ team:<id>); the merge runs in one transaction.
54
+ - The reply correlation is server-side (P3): a bare answer (no reply_to)
55
+ auto-carries the pending question's id — lastUnansweredFrom(fromBox,
56
+ toBox, 30 min window), applied on the local, the federated and the peer
57
+ wire paths. The agents' reply discipline is no longer load-bearing (the
58
+ storm root cause dies at the source). Explicit reply_to always wins.
59
+ - mesh_wait is hard-capped at 30s and correlates on the sender (P4): the
60
+ matcher returns on the exact reply_to OR any message from the request's
61
+ recipient box arriving after it; the description states the contract
62
+ (only when the next step in THIS turn depends on the answer).
63
+
64
+ ### Changed
65
+
66
+ - The wake flash loses the reply id (P5): the auto-fill made it redundant —
67
+ ~50 tokens back on every wake of every agent.
68
+ - New option debugWake: one plugin.log line per flash (pid, box, fresh
69
+ count, PRAGMA data_version) — the ghost-counter hunt switch (frozen WAL
70
+ snapshot vs orphan instance).
71
+
8
72
  ## [0.30.1] - 2026-11-26
9
73
 
10
74
  ### Fixed
@@ -1 +1 @@
1
- {"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/lib/db.ts"],"names":[],"mappings":"AAGA,OAAO,EAAc,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAE1D,MAAM,MAAM,MAAM,GAAG;IACnB,IAAI,EAAE,UAAU,CAAC;IACjB,4DAA4D;IAC5D,IAAI,EAAE,MAAM,CAAC;IACb;4EACwE;IACxE,MAAM,IAAI,IAAI,CAAC;IACf,KAAK,IAAI,IAAI,CAAC;CACf,CAAC;AAqNF,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CA+D/C"}
1
+ {"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/lib/db.ts"],"names":[],"mappings":"AAGA,OAAO,EAAc,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAE1D,MAAM,MAAM,MAAM,GAAG;IACnB,IAAI,EAAE,UAAU,CAAC;IACjB,4DAA4D;IAC5D,IAAI,EAAE,MAAM,CAAC;IACb;4EACwE;IACxE,MAAM,IAAI,IAAI,CAAC;IACf,KAAK,IAAI,IAAI,CAAC;CACf,CAAC;AAiOF,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CA+D/C"}
package/dist/lib/db.js CHANGED
@@ -3,7 +3,7 @@ import { dirname } from "node:path";
3
3
  import { openSqlite } from "./sqlite.js";
4
4
  // Bump when a schema change needs a migration step; the version anchors future
5
5
  // migrations that cannot be expressed as idempotent `CREATE ... IF NOT EXISTS`.
6
- const SCHEMA_VERSION = 16;
6
+ const SCHEMA_VERSION = 17;
7
7
  const SCHEMA = `
8
8
  CREATE TABLE IF NOT EXISTS peers (
9
9
  node_id TEXT PRIMARY KEY,
@@ -145,6 +145,18 @@ function migrate(conn) {
145
145
  conn.exec("ALTER TABLE mailboxes ADD COLUMN registered_at INTEGER");
146
146
  conn.exec("UPDATE mailboxes SET registered_at = created_at WHERE registered_at IS NULL");
147
147
  }
148
+ // v17: deliveries.flashed_at — the flash single-flight (0.32.0). The claim
149
+ // "this delivery has been announced to its session" lives in the SHARED
150
+ // database instead of per-instance memory (two plugin instances' wake
151
+ // loops could not see each other's pendingPrompt maps: the double-flash
152
+ // class — 6admin re-prompted 13s apart, two identical replies). NULL =
153
+ // never flashed.
154
+ const deliveryColumns = conn
155
+ .all("PRAGMA table_info(deliveries)")
156
+ .map((row) => row.name);
157
+ if (!deliveryColumns.includes("flashed_at")) {
158
+ conn.exec("ALTER TABLE deliveries ADD COLUMN flashed_at INTEGER");
159
+ }
148
160
  // v5: messages.origin_id (cross-host broadcast dedup).
149
161
  if (!messageColumns.includes("origin_id")) {
150
162
  conn.exec("ALTER TABLE messages ADD COLUMN origin_id TEXT");
@@ -1 +1 @@
1
- {"version":3,"file":"db.js","sourceRoot":"","sources":["../../src/lib/db.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,UAAU,EAAmB,MAAM,aAAa,CAAC;AAY1D,+EAA+E;AAC/E,gFAAgF;AAChF,MAAM,cAAc,GAAG,EAAE,CAAC;AAE1B,MAAM,MAAM,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoFd,CAAC;AAEF,MAAM,UAAU,GAAG;;;;CAIlB,CAAC;AAEF,SAAS,OAAO,CAAC,IAAgB;IAC/B,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAA2B,qBAAqB,CAAC,EAAE,YAAY,IAAI,CAAC,CAAC;IAC7F,IAAI,OAAO,IAAI,cAAc,EAAE,CAAC;QAC9B,OAAO;IACT,CAAC;IACD,6EAA6E;IAC7E,0DAA0D;IAC1D,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAClB,6EAA6E;IAC7E,0EAA0E;IAC1E,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAmB,0BAA0B,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAClG,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC;QACxC,IAAI,CAAC,IAAI,CAAC,8CAA8C,CAAC,CAAC;IAC5D,CAAC;IACD,4EAA4E;IAC5E,+CAA+C;IAC/C,IAAI,CAAC,WAAW,CAAC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_MS: number;
67
67
  export declare const RESEND_WINDOW_MS: number;
68
+ /** The absolute collapse window (0.32.0): an identical re-send this fast is
69
+ * mechanical (the wake double-prompt), never a human ping — collapsed even
70
+ * when the original was already read. */
71
+ export declare const RESEND_ABSOLUTE_WINDOW_MS: number;
68
72
  export declare function registerMailbox(db: MeshDb, input: RegisterMailboxInput): Mailbox;
69
73
  export declare function mailboxByBindKey(db: MeshDb, bind_key: string): Mailbox[];
70
74
  export declare function mailboxBySession(db: MeshDb, session_id: string): Mailbox | null;
71
75
  /** Every mailbox bound to a session (a session may wear several hats). */
72
76
  export declare function mailboxesBySession(db: MeshDb, session_id: string): Mailbox[];
73
77
  export declare function mailboxByName(db: MeshDb, name: string): Mailbox | null;
78
+ /** The federated registry row for a name (node_id set, pushed by a peer):
79
+ * the routing record — WHICH node owns the name — never a local box. */
80
+ export declare function federatedByName(db: MeshDb, name: string): Mailbox | null;
74
81
  export declare function listMailboxes(db: MeshDb): Mailbox[];
75
82
  /** The LOCAL mailboxes only (node_id NULL): the delivery targets, the pool
76
83
  * members, the wake subjects. Federated rows (node_id set, pushed by a peer
@@ -111,6 +118,12 @@ export declare function inboxRead(db: MeshDb, session_id: string, ack: boolean):
111
118
  * inboxRead (same hot-swap race, same fix, same residual window).
112
119
  */
113
120
  export declare function waitReplyRead(db: MeshDb, reply_to: string, session_id: string): InboxRow | null;
121
+ /** The wait matcher (0.31.0): the exact reply_to match first, then the
122
+ * sender match — ANY message from the request's recipient box that arrived
123
+ * after the request. A reply that bypassed the auto-fill (a legacy wire
124
+ * path, a DB-level write) still returns the waiter: the correlation no
125
+ * longer depends on anyone's discipline. The matched row is acked. */
126
+ export declare function waitReplyBroad(db: MeshDb, reply_to: string, session_id: string): InboxRow | null;
114
127
  /** The unread rows that do NOT answer `reply_to` — the wake-path replies
115
128
  * (bare, reply_to NULL: the flash carries the subject, not the id) that would
116
129
  * otherwise starve a mesh_wait caller to its full timeout. Listed in the
@@ -132,11 +145,6 @@ export type WakeBoxStat = {
132
145
  wakeable: boolean;
133
146
  /** Subject of the box's OLDEST unread delivery (the wake preview). */
134
147
  subject: string;
135
- /** Id of that same OLDEST unread delivery: the wake flash carries it so the
136
- * woken agent can answer with reply_to=<id> — without it, wake-path replies
137
- * are invisible to mesh_wait's correlation (the 02:17 repro: the reply sat
138
- * in the box, the waiter starved to its full timeout). */
139
- id: string | null;
140
148
  };
141
149
  /** Per-box unread stats for the wake loop, in ONE grouped statement: before
142
150
  * 0.21.0 the tick ran two queries per mailbox (unread count + wake gate) plus
@@ -158,6 +166,30 @@ export type FederatedRegistryRow = {
158
166
  registered_at: number;
159
167
  };
160
168
  export declare function mergeFederatedRegistry(db: MeshDb, rows: FederatedRegistryRow[], senderNodeId: string): number;
169
+ /** The pending question a reply should answer, WITHOUT agent discipline:
170
+ * the last message `toBox` sent to `fromBox` (delivered in fromBox's box,
171
+ * inside the window) that no message from fromBox answers yet. The send
172
+ * path fills reply_to from it when the agent left it empty — the storm
173
+ * root cause (bare replies invisible to the correlation) dies at the
174
+ * source. Explicit reply_to always wins; nothing pending = NULL. */
175
+ export declare function lastUnansweredFrom(db: MeshDb, fromBox: string, toBox: string, sinceMs?: number): string | null;
176
+ /** The flash single-flight (0.32.0): claim the box's announceable unreads
177
+ * ATOMICALLY in the shared database — the decision "already flashed" lives
178
+ * in the store every instance sees, not in per-instance memory (two plugin
179
+ * instances' wake loops each iterate ALL boxes with their own pendingPrompt
180
+ * maps: neither saw the other's gate, 6admin got prompted 13s apart and
181
+ * answered twice). Returns the claimed row count: 0 = nothing fresh (or
182
+ * another instance just claimed it) — skip the prompt. Rows whose flash is
183
+ * older than staleAfterMs are RE-claimed: that is the reminder path (the
184
+ * fatigue mute re-prompts through it), 0 = first flash only. */
185
+ export declare function claimFlash(db: MeshDb, box: string, now: number, staleAfterMs: number): {
186
+ claimed: number;
187
+ at: number;
188
+ };
189
+ /** Release a flash claim whose prompt FAILED: the rows go back to NULL so
190
+ * the next tick re-claims them — a claimed-but-never-announced delivery is
191
+ * the silent-starvation class (the flash died, the mail looks announced). */
192
+ export declare function releaseFlash(db: MeshDb, box: string, at: number): void;
161
193
  /** The local registry rows this node owns (for the /registry-sync push). */
162
194
  export declare function localRegistryRows(db: MeshDb): FederatedRegistryRow[];
163
195
  //# sourceMappingURL=mail.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"mail.d.ts","sourceRoot":"","sources":["../../src/lib/mail.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEtC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAQpD,MAAM,MAAM,OAAO,GAAG;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB;;8BAE0B;IAC1B,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB;gFAC4E;IAC5E,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B;kFAC8E;IAC9E,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,OAAO,EAAE,M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const MESSAGE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
11
11
  // the burst retries were already covered, the interruption-resume class was
12
12
  // not. The rolling recent_mails purge bounds the rows.
13
13
  export const RESEND_WINDOW_MS = 6 * 60 * 60 * 1000;
14
+ /** The absolute collapse window (0.32.0): an identical re-send this fast is
15
+ * mechanical (the wake double-prompt), never a human ping — collapsed even
16
+ * when the original was already read. */
17
+ export const RESEND_ABSOLUTE_WINDOW_MS = 2 * 60 * 1000;
14
18
  // Content key of the re-send defense. to_box stays in the key so a broadcast
15
19
  // to one box never swallows the same text to another, and reply_to so an
16
20
  // identical reply to a different message is still a distinct delivery.
@@ -95,12 +99,23 @@ export function mailboxesBySession(db, session_id) {
95
99
  .map(rowToMailbox);
96
100
  }
97
101
  export function mailboxByName(db, name) {
98
- const row = db.conn.get("SELECT * FROM mailboxes WHERE name = ?", [name]);
102
+ // LOCAL only (0.31.0): a federated row (node_id set) is addressing-only —
103
+ // a caller deciding "does this box live here?" must answer no, or mail
104
+ // sinks into a box no local session drains (the P1 phantom-box class).
105
+ const row = db.conn.get("SELECT * FROM mailboxes WHERE name = ? AND node_id IS NULL", [name]);
106
+ return row ? rowToMailbox(row) : null;
107
+ }
108
+ /** The federated registry row for a name (node_id set, pushed by a peer):
109
+ * the routing record — WHICH node owns the name — never a local box. */
110
+ export function federatedByName(db, name) {
111
+ const row = db.conn.get("SELECT * FROM mailboxes WHERE name = ? AND node_id IS NOT NULL", [name]);
99
112
  return row ? rowToMailbox(row) : null;
100
113
  }
101
114
  export function listMailboxes(db) {
115
+ // LOCAL only (0.31.0): the sidebar, the counters and mesh_pools count the
116
+ // boxes that live HERE. Federated rows surface through the peers section.
102
117
  return db.conn
103
- .all("SELECT * FROM mailboxes ORDER BY created_at ASC")
118
+ .all("SELECT * FROM mailboxes WHERE node_id IS NULL ORDER BY created_at ASC")
104
119
  .map(rowToMailbox);
105
120
  }
106
121
  /** The LOCAL mailboxes only (node_id NULL): the delivery targets, the pool
@@ -166,8 +181,16 @@ export function deliverMessage(db, input) {
166
181
  // sender re-executed its sends following a local crash). Runs after the
167
182
  // origin_id check: cross-host replays dedup there, real re-sends here.
168
183
  const contentHash = mailContentHash(input);
169
- const resent = db.conn.get("SELECT message_id FROM recent_mails WHERE hash = ? AND ts > ?", [contentHash, created_at - RESEND_WINDOW_MS]);
184
+ const resent = db.conn.get("SELECT message_id, ts FROM recent_mails WHERE hash = ? AND ts > ?", [contentHash, created_at - RESEND_WINDOW_MS]);
170
185
  if (resent) {
186
+ // The absolute window (0.32.0): an identical re-send within 2 minutes
187
+ // collapses EVEN IF the original was already read. The wake double-prompt
188
+ // class re-sends 13s after the receiver drained — a genuine human ping
189
+ // never re-writes the identical bytes that fast, and the single-flight
190
+ // claim (F1) is the source fix; this window is the belt-and-braces net.
191
+ if (created_at - resent.ts < RESEND_ABSOLUTE_WINDOW_MS) {
192
+ return { ok: true, id: resent.message_id, recipients: [] };
193
+ }
171
194
  // The dedup protects the UNREAD backlog (the re-send burst class): an
172
195
  // identical re-send AFTER the original was read is an active ping —
173
196
  // deliver it fresh (0.29.0 review). The original's read state lives on
@@ -411,6 +434,31 @@ export function waitReplyRead(db, reply_to, session_id) {
411
434
  return row;
412
435
  });
413
436
  }
437
+ /** The wait matcher (0.31.0): the exact reply_to match first, then the
438
+ * sender match — ANY message from the request's recipient box that arrived
439
+ * after the request. A reply that bypassed the auto-fill (a legacy wire
440
+ * path, a DB-level write) still returns the waiter: the correlation no
441
+ * longer depends on anyone's discipline. The matched row is acked. */
442
+ export function waitReplyBroad(db, reply_to, session_id) {
443
+ return withTransaction(db, () => {
444
+ const exact = firstReply(db, reply_to, session_id);
445
+ if (exact) {
446
+ ackReply(db, exact);
447
+ return exact;
448
+ }
449
+ const request = db.conn.get("SELECT created_at FROM messages WHERE id = ?", [reply_to]);
450
+ const delivery = db.conn.get("SELECT to_box FROM deliveries WHERE message_id = ? ORDER BY created_at DESC LIMIT 1", [reply_to]);
451
+ const box = mailboxBySession(db, session_id);
452
+ if (!request || !delivery || !box)
453
+ return null;
454
+ const stray = deliveryRows(db, box.name).find((r) => r.from_box === delivery.to_box && r.created_at > request.created_at);
455
+ if (stray) {
456
+ ackReply(db, stray);
457
+ return stray;
458
+ }
459
+ return null;
460
+ });
461
+ }
414
462
  /** The unread rows that do NOT answer `reply_to` — the wake-path replies
415
463
  * (bare, reply_to NULL: the flash carries the subject, not the id) that would
416
464
  * otherwise starve a mesh_wait caller to its full timeout. Listed in the
@@ -472,10 +520,7 @@ export function wakeBoxStats(db) {
472
520
  THEN 1 ELSE 0 END) AS wakeable,
473
521
  (SELECT m3.subject FROM deliveries d3 JOIN messages m3 ON m3.id = d3.message_id
474
522
  WHERE d3.to_box = d.to_box AND d3.status = 'unread'
475
- ORDER BY d3.created_at ASC, d3.id ASC LIMIT 1) AS subject,
476
- (SELECT m4.id FROM deliveries d4 JOIN messages m4 ON m4.id = d4.message_id
477
- WHERE d4.to_box = d.to_box AND d4.status = 'unread'
478
- ORDER BY d4.created_at ASC, d4.id ASC LIMIT 1) AS id
523
+ ORDER BY d3.created_at ASC, d3.id ASC LIMIT 1) AS subject
479
524
  FROM deliveries d JOIN messages m ON m.id = d.message_id
480
525
  WHERE d.status = 'unread'
481
526
  AND d.to_box NOT IN (SELECT name FROM mailboxes WHERE node_id IS NOT NULL)
@@ -485,7 +530,6 @@ export function wakeBoxStats(db) {
485
530
  unread: row.unread,
486
531
  wakeable: row.wakeable === 1,
487
532
  subject: row.subject,
488
- id: row.id,
489
533
  }));
490
534
  }
491
535
  export function ackMessages(db, ids) {
@@ -519,10 +563,10 @@ function rowToMessage(row) {
519
563
  * foreign — sessionKnown false in the wake loop). The sender's own rows are
520
564
  * authoritative for its names: the merge is idempotent per row.
521
565
  */
522
- /** The inbound registered_at acceptance window (the PO fix 2): the sender's
523
- * clock must be within [now - 1h, now + 5 min skew] — an unbounded timestamp
524
- * (9e15, or a clock ahead) would steal every local name via the LWW. */
525
- const FEDERATED_AT_PAST_TOLERANCE = 60 * 60 * 1000;
566
+ /** The inbound registered_at acceptance bound (the PO fix 2): only the
567
+ * FUTURE side is bounded — an unbounded timestamp (9e15, a clock ahead)
568
+ * would steal every local name via the LWW. The past side is unbounded:
569
+ * registered_at is the original registration time and never moves. */
526
570
  const FEDERATED_AT_FUTURE_SKEW = 5 * 60 * 1000;
527
571
  /** A local box with a fresh last_seen is a LIVE session: its name cannot be
528
572
  * taken by a foreign registry row (the two-orq fight resolves: each keeps
@@ -536,10 +580,16 @@ function federatedRowValid(row, now) {
536
580
  return false;
537
581
  if (typeof row.session_id !== "string" || row.session_id.length === 0)
538
582
  return false;
583
+ if (row.session_id.length > 128)
584
+ return false;
539
585
  if (typeof row.registered_at !== "number" || !Number.isFinite(row.registered_at))
540
586
  return false;
541
- if (row.registered_at < now - FEDERATED_AT_PAST_TOLERANCE ||
542
- row.registered_at > now + FEDERATED_AT_FUTURE_SKEW) {
587
+ // Only the FUTURE skew is bounded (the 9e15 steal class). No past bound:
588
+ // registered_at is the ORIGINAL registration time and never moves — a
589
+ // long-lived box (orq, stable names) is older than any tolerance, and the
590
+ // takeover LWW guard (row.registered_at <= localAt) already refuses a
591
+ // backdated row for a name we own.
592
+ if (row.registered_at > now + FEDERATED_AT_FUTURE_SKEW) {
543
593
  return false;
544
594
  }
545
595
  if (typeof row.pools !== "string")
@@ -548,12 +598,19 @@ function federatedRowValid(row, now) {
548
598
  const parsed = JSON.parse(row.pools);
549
599
  if (!Array.isArray(parsed))
550
600
  return false;
601
+ // Every pool id is a full "team:<name>" — anything else would inject a
602
+ // phantom pool into the local membership view.
603
+ if (!parsed.every((p) => typeof p === "string" && /^team:[A-Za-z0-9._-]+$/.test(p))) {
604
+ return false;
605
+ }
551
606
  }
552
607
  catch {
553
608
  return false;
554
609
  }
555
610
  if (row.role !== null && typeof row.role !== "string")
556
611
  return false;
612
+ if (typeof row.role === "string" && row.role.length > 64)
613
+ return false;
557
614
  if (row.primary_pool !== null && typeof row.primary_pool !== "string")
558
615
  return false;
559
616
  return true;
@@ -563,66 +620,125 @@ export function mergeFederatedRegistry(db, rows, senderNodeId) {
563
620
  // The full-state replacement (the PO fix 4): each push carries the
564
621
  // sender's COMPLETE local registry — the federated rows owned by the
565
622
  // sender that are ABSENT from the push are stale (the box was deleted or
566
- // renamed there) and die here.
567
- const pushed = new Set(rows.filter((r) => federatedRowValid(r, now)).map((r) => r.name));
568
- db.conn.run("DELETE FROM mailboxes WHERE node_id = ? AND name NOT IN (" +
569
- (pushed.size > 0 ? Array.from(pushed, () => "?").join(",") : "NULL") +
570
- ")", [senderNodeId, ...pushed]);
571
- let applied = 0;
572
- for (const row of rows) {
573
- if (!federatedRowValid(row, now))
574
- continue;
575
- const local = db.conn.get("SELECT node_id, registered_at, last_seen FROM mailboxes WHERE name = ?", [row.name]);
576
- if (local) {
577
- if (local.node_id === null || local.node_id === "") {
578
- // This node owns the name. Two guards before a takeover: (1) a LIVE
579
- // local session (fresh last_seen) keeps its name — the two-orq fight
580
- // resolves: each keeps its own; (2) the inbound registration must be
581
- // strictly newer than the local one (the explicit rebind on the
582
- // other side transferred it).
583
- if (local.last_seen > now - LIVE_LOCAL_LAST_SEEN_MS)
584
- continue;
585
- const localAt = local.registered_at ?? 0;
586
- if (row.registered_at <= localAt)
587
- continue;
588
- }
589
- else if (local.node_id !== senderNodeId) {
590
- // A federated row owned by a THIRD node: the sender must be the owner
591
- // to update it — the third-party re-broadcast never overwrites.
592
- continue;
593
- }
594
- else if ((local.registered_at ?? 0) >= row.registered_at) {
595
- continue;
596
- }
597
- db.conn.run(`UPDATE mailboxes SET session_id = ?, role = ?, pools = ?, primary_pool = ?,
598
- registered_at = ?, last_seen = ?, bind_key = NULL, node_id = ? WHERE name = ?`, [
599
- row.session_id,
600
- row.role,
601
- row.pools,
602
- row.primary_pool,
603
- row.registered_at,
604
- Date.now(),
605
- senderNodeId,
606
- row.name,
607
- ]);
623
+ // renamed there) and die here. One transaction: a mid-merge crash never
624
+ // leaves half a batch (rows deleted, their replacements absent).
625
+ return withTransaction(db, () => {
626
+ const pushed = new Set(rows.filter((r) => federatedRowValid(r, now)).map((r) => r.name));
627
+ // An EMPTY push retires ALL of the sender's federated rows (the full-state
628
+ // contract): the name NOT IN (NULL) placeholder would compare NULL against
629
+ // every row and delete NOTHING — stale rows keep routing cross-node DMs
630
+ // to a dead box (the mr-review finding).
631
+ if (pushed.size === 0) {
632
+ db.conn.run("DELETE FROM mailboxes WHERE node_id = ?", [senderNodeId]);
608
633
  }
609
634
  else {
610
- db.conn.run(`INSERT INTO mailboxes (name, session_id, role, pools, bind_key, primary_pool, last_seen, created_at, registered_at, node_id)
611
- VALUES (?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)`, [
635
+ db.conn.run("DELETE FROM mailboxes WHERE node_id = ? AND name NOT IN (" +
636
+ Array.from(pushed, () => "?").join(",") +
637
+ ")", [senderNodeId, ...pushed]);
638
+ }
639
+ let applied = 0;
640
+ for (const row of rows) {
641
+ if (!federatedRowValid(row, now))
642
+ continue;
643
+ const local = db.conn.get("SELECT node_id, registered_at, last_seen, bind_key FROM mailboxes WHERE name = ?", [
612
644
  row.name,
613
- row.session_id,
614
- row.role,
615
- row.pools,
616
- row.primary_pool,
617
- Date.now(),
618
- Date.now(),
619
- row.registered_at,
620
- senderNodeId,
621
645
  ]);
646
+ if (local) {
647
+ if (local.node_id === null || local.node_id === "") {
648
+ // This node owns the name. Three guards before a takeover: (1) a LIVE
649
+ // local session (fresh last_seen) keeps its name — the two-orq fight
650
+ // resolves: each keeps its own; (2) a BOUND name (bind_key set — an
651
+ // instance binding) is never ceded, quiet session or not: the bind is
652
+ // the operator's claim, the staleness does not reopen it; (3) the
653
+ // inbound registration must be strictly newer than the local one (the
654
+ // explicit rebind on the other side transferred it).
655
+ if (local.bind_key !== null && local.bind_key !== "")
656
+ continue;
657
+ if (local.last_seen > now - LIVE_LOCAL_LAST_SEEN_MS)
658
+ continue;
659
+ const localAt = local.registered_at ?? 0;
660
+ if (row.registered_at <= localAt)
661
+ continue;
662
+ }
663
+ else if (local.node_id !== senderNodeId) {
664
+ // A federated row owned by a THIRD node: the sender must be the owner
665
+ // to update it — the third-party re-broadcast never overwrites.
666
+ continue;
667
+ }
668
+ else if ((local.registered_at ?? 0) >= row.registered_at) {
669
+ continue;
670
+ }
671
+ db.conn.run(`UPDATE mailboxes SET session_id = ?, role = ?, pools = ?, primary_pool = ?,
672
+ registered_at = ?, last_seen = ?, bind_key = NULL, node_id = ? WHERE name = ?`, [
673
+ row.session_id,
674
+ row.role,
675
+ row.pools,
676
+ row.primary_pool,
677
+ row.registered_at,
678
+ Date.now(),
679
+ senderNodeId,
680
+ row.name,
681
+ ]);
682
+ }
683
+ else {
684
+ db.conn.run(`INSERT INTO mailboxes (name, session_id, role, pools, bind_key, primary_pool, last_seen, created_at, registered_at, node_id)
685
+ VALUES (?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)`, [
686
+ row.name,
687
+ row.session_id,
688
+ row.role,
689
+ row.pools,
690
+ row.primary_pool,
691
+ Date.now(),
692
+ Date.now(),
693
+ row.registered_at,
694
+ senderNodeId,
695
+ ]);
696
+ }
697
+ applied += 1;
622
698
  }
623
- applied += 1;
624
- }
625
- return applied;
699
+ return applied;
700
+ });
701
+ }
702
+ /** The pending question a reply should answer, WITHOUT agent discipline:
703
+ * the last message `toBox` sent to `fromBox` (delivered in fromBox's box,
704
+ * inside the window) that no message from fromBox answers yet. The send
705
+ * path fills reply_to from it when the agent left it empty — the storm
706
+ * root cause (bare replies invisible to the correlation) dies at the
707
+ * source. Explicit reply_to always wins; nothing pending = NULL. */
708
+ export function lastUnansweredFrom(db, fromBox, toBox, sinceMs = 30 * 60 * 1000) {
709
+ const row = db.conn.get(`SELECT m.id FROM messages m
710
+ JOIN deliveries d ON d.message_id = m.id
711
+ WHERE d.to_box = ? AND m.from_box = ? AND m.created_at > ?
712
+ AND NOT EXISTS (
713
+ SELECT 1 FROM messages r WHERE r.reply_to = m.id AND r.from_box = ?
714
+ )
715
+ ORDER BY m.created_at DESC
716
+ LIMIT 1`, [fromBox, toBox, Date.now() - sinceMs, fromBox]);
717
+ return row?.id ?? null;
718
+ }
719
+ /** The flash single-flight (0.32.0): claim the box's announceable unreads
720
+ * ATOMICALLY in the shared database — the decision "already flashed" lives
721
+ * in the store every instance sees, not in per-instance memory (two plugin
722
+ * instances' wake loops each iterate ALL boxes with their own pendingPrompt
723
+ * maps: neither saw the other's gate, 6admin got prompted 13s apart and
724
+ * answered twice). Returns the claimed row count: 0 = nothing fresh (or
725
+ * another instance just claimed it) — skip the prompt. Rows whose flash is
726
+ * older than staleAfterMs are RE-claimed: that is the reminder path (the
727
+ * fatigue mute re-prompts through it), 0 = first flash only. */
728
+ export function claimFlash(db, box, now, staleAfterMs) {
729
+ const res = db.conn.run(`UPDATE deliveries SET flashed_at = ?
730
+ WHERE to_box = ? AND status = 'unread'
731
+ AND (flashed_at IS NULL OR flashed_at <= ?)`, [now, box, now - staleAfterMs]);
732
+ return { claimed: res.changes, at: now };
733
+ }
734
+ /** Release a flash claim whose prompt FAILED: the rows go back to NULL so
735
+ * the next tick re-claims them — a claimed-but-never-announced delivery is
736
+ * the silent-starvation class (the flash died, the mail looks announced). */
737
+ export function releaseFlash(db, box, at) {
738
+ db.conn.run("UPDATE deliveries SET flashed_at = NULL WHERE to_box = ? AND flashed_at = ?", [
739
+ box,
740
+ at,
741
+ ]);
626
742
  }
627
743
  /** The local registry rows this node owns (for the /registry-sync push). */
628
744
  export function localRegistryRows(db) {