@bastani/atomic 0.9.89-alpha.1 → 0.9.89-alpha.2

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 (152) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +8 -0
  3. package/dist/builtin/intercom/broker/broker-instance.ts +15 -1
  4. package/dist/builtin/intercom/broker/broker.ts +25 -8
  5. package/dist/builtin/intercom/broker/client.ts +29 -14
  6. package/dist/builtin/intercom/broker/multinode-router.ts +193 -52
  7. package/dist/builtin/intercom/broker/multinode-state-store.ts +6 -2
  8. package/dist/builtin/intercom/broker/restoring-recipients.ts +5 -0
  9. package/dist/builtin/intercom/broker/sql-outbox-store.ts +3 -2
  10. package/dist/builtin/intercom/index.bundle.mjs +19 -12
  11. package/dist/builtin/intercom/package.json +1 -1
  12. package/dist/builtin/intercom/types.ts +6 -2
  13. package/dist/builtin/mcp/package.json +1 -1
  14. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  15. package/dist/builtin/subagents/package.json +1 -1
  16. package/dist/builtin/subagents/src/extension/index.bundle.mjs +17 -6
  17. package/dist/builtin/web-access/package.json +1 -1
  18. package/dist/builtin/workflows/CHANGELOG.md +12 -0
  19. package/dist/builtin/workflows/package.json +1 -1
  20. package/dist/builtin/workflows/src/extension/index.bundle.mjs +310 -344
  21. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +99 -17
  22. package/dist/builtin/workflows/src/index.js +99 -17
  23. package/dist/builtin/workflows/src/local-worker-entry.mjs +99 -17
  24. package/dist/cli/storage-command.js +8 -0
  25. package/dist/cli/storage-command.js.map +1 -1
  26. package/dist/core/auth-storage-backends.d.ts.map +1 -1
  27. package/dist/core/auth-storage-backends.js +1 -0
  28. package/dist/core/auth-storage-backends.js.map +1 -1
  29. package/dist/core/keybindings.d.ts +8 -0
  30. package/dist/core/keybindings.d.ts.map +1 -1
  31. package/dist/core/keybindings.js +4 -0
  32. package/dist/core/keybindings.js.map +1 -1
  33. package/dist/core/process-start-token.d.ts.map +1 -1
  34. package/dist/core/process-start-token.js +8 -1
  35. package/dist/core/process-start-token.js.map +1 -1
  36. package/dist/core/resume/blueprint/build-lock.d.ts.map +1 -1
  37. package/dist/core/resume/blueprint/build-lock.js +2 -1
  38. package/dist/core/resume/blueprint/build-lock.js.map +1 -1
  39. package/dist/core/storage/errors.d.ts +4 -2
  40. package/dist/core/storage/errors.d.ts.map +1 -1
  41. package/dist/core/storage/errors.js +6 -1
  42. package/dist/core/storage/errors.js.map +1 -1
  43. package/dist/core/tasks/completion.d.ts +5 -0
  44. package/dist/core/tasks/completion.d.ts.map +1 -1
  45. package/dist/core/tasks/completion.js +13 -0
  46. package/dist/core/tasks/completion.js.map +1 -1
  47. package/dist/core/tools/shell-task-render.d.ts +1 -2
  48. package/dist/core/tools/shell-task-render.d.ts.map +1 -1
  49. package/dist/core/tools/shell-task-render.js +3 -7
  50. package/dist/core/tools/shell-task-render.js.map +1 -1
  51. package/dist/core/tools/windows-directory-security.d.ts.map +1 -1
  52. package/dist/core/tools/windows-directory-security.js +3 -11
  53. package/dist/core/tools/windows-directory-security.js.map +1 -1
  54. package/dist/core/worktree-snapshot/capture.d.ts.map +1 -1
  55. package/dist/core/worktree-snapshot/capture.js +25 -1
  56. package/dist/core/worktree-snapshot/capture.js.map +1 -1
  57. package/dist/core/worktree-snapshot/restore.d.ts.map +1 -1
  58. package/dist/core/worktree-snapshot/restore.js +38 -9
  59. package/dist/core/worktree-snapshot/restore.js.map +1 -1
  60. package/dist/index.d.ts +2 -1
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +2 -1
  63. package/dist/index.js.map +1 -1
  64. package/dist/modes/interactive/components/agent-panel.d.ts +5 -0
  65. package/dist/modes/interactive/components/agent-panel.d.ts.map +1 -1
  66. package/dist/modes/interactive/components/agent-panel.js +13 -0
  67. package/dist/modes/interactive/components/agent-panel.js.map +1 -1
  68. package/dist/modes/interactive/components/chat-transcript.d.ts.map +1 -1
  69. package/dist/modes/interactive/components/chat-transcript.js +5 -2
  70. package/dist/modes/interactive/components/chat-transcript.js.map +1 -1
  71. package/dist/modes/interactive/components/custom-message.js +1 -1
  72. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  73. package/dist/modes/interactive/components/heartbeat-block.d.ts +34 -0
  74. package/dist/modes/interactive/components/heartbeat-block.d.ts.map +1 -0
  75. package/dist/modes/interactive/components/heartbeat-block.js +50 -0
  76. package/dist/modes/interactive/components/heartbeat-block.js.map +1 -0
  77. package/dist/modes/interactive/components/input-label.d.ts.map +1 -1
  78. package/dist/modes/interactive/components/input-label.js +8 -3
  79. package/dist/modes/interactive/components/input-label.js.map +1 -1
  80. package/dist/modes/interactive/components/main-composer-keys.d.ts.map +1 -1
  81. package/dist/modes/interactive/components/main-composer-keys.js +3 -7
  82. package/dist/modes/interactive/components/main-composer-keys.js.map +1 -1
  83. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  84. package/dist/modes/interactive/components/mermaid.js +13 -7
  85. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  86. package/dist/modes/interactive/components/notice-line.d.ts +10 -2
  87. package/dist/modes/interactive/components/notice-line.d.ts.map +1 -1
  88. package/dist/modes/interactive/components/notice-line.js +13 -3
  89. package/dist/modes/interactive/components/notice-line.js.map +1 -1
  90. package/dist/modes/interactive/components/provider-brand.d.ts.map +1 -1
  91. package/dist/modes/interactive/components/provider-brand.js +3 -0
  92. package/dist/modes/interactive/components/provider-brand.js.map +1 -1
  93. package/dist/modes/interactive/components/task-heartbeat-message.d.ts +9 -4
  94. package/dist/modes/interactive/components/task-heartbeat-message.d.ts.map +1 -1
  95. package/dist/modes/interactive/components/task-heartbeat-message.js +33 -27
  96. package/dist/modes/interactive/components/task-heartbeat-message.js.map +1 -1
  97. package/dist/modes/interactive/components/task-inspector.d.ts +16 -0
  98. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
  99. package/dist/modes/interactive/components/task-inspector.js +95 -4
  100. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  101. package/dist/modes/interactive/components/task-list.d.ts +5 -1
  102. package/dist/modes/interactive/components/task-list.d.ts.map +1 -1
  103. package/dist/modes/interactive/components/task-list.js +20 -3
  104. package/dist/modes/interactive/components/task-list.js.map +1 -1
  105. package/dist/modes/interactive/components/task-transcript-page.d.ts +1 -1
  106. package/dist/modes/interactive/components/task-transcript-page.d.ts.map +1 -1
  107. package/dist/modes/interactive/components/task-transcript-page.js +10 -7
  108. package/dist/modes/interactive/components/task-transcript-page.js.map +1 -1
  109. package/dist/modes/interactive/interactive-startup.js +1 -2
  110. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  111. package/dist/modes/interactive/theme/color-utils.d.ts +29 -1
  112. package/dist/modes/interactive/theme/color-utils.d.ts.map +1 -1
  113. package/dist/modes/interactive/theme/color-utils.js +81 -7
  114. package/dist/modes/interactive/theme/color-utils.js.map +1 -1
  115. package/dist/modes/interactive/theme/global-theme.d.ts.map +1 -1
  116. package/dist/modes/interactive/theme/global-theme.js +3 -0
  117. package/dist/modes/interactive/theme/global-theme.js.map +1 -1
  118. package/dist/modes/interactive/theme/theme-class.d.ts +22 -2
  119. package/dist/modes/interactive/theme/theme-class.d.ts.map +1 -1
  120. package/dist/modes/interactive/theme/theme-class.js +64 -18
  121. package/dist/modes/interactive/theme/theme-class.js.map +1 -1
  122. package/dist/modes/interactive/theme/theme.d.ts +1 -0
  123. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  124. package/dist/modes/interactive/theme/theme.js +1 -0
  125. package/dist/modes/interactive/theme/theme.js.map +1 -1
  126. package/dist/utils/clipboard-image.d.ts.map +1 -1
  127. package/dist/utils/clipboard-image.js +2 -0
  128. package/dist/utils/clipboard-image.js.map +1 -1
  129. package/dist/utils/clipboard.d.ts.map +1 -1
  130. package/dist/utils/clipboard.js +2 -1
  131. package/dist/utils/clipboard.js.map +1 -1
  132. package/dist/utils/tools-manager.d.ts +6 -0
  133. package/dist/utils/tools-manager.d.ts.map +1 -1
  134. package/dist/utils/tools-manager.js +170 -15
  135. package/dist/utils/tools-manager.js.map +1 -1
  136. package/dist/utils/windows-powershell.d.ts +9 -0
  137. package/dist/utils/windows-powershell.d.ts.map +1 -0
  138. package/dist/utils/windows-powershell.js +16 -0
  139. package/dist/utils/windows-powershell.js.map +1 -0
  140. package/docs/background-tasks.md +6 -6
  141. package/docs/getting-started/installation.md +4 -2
  142. package/docs/keybindings.md +3 -0
  143. package/docs/storage.md +24 -5
  144. package/docs/subagents.md +1 -1
  145. package/docs/themes/reference.md +7 -0
  146. package/docs/tui/reference.md +1 -1
  147. package/docs/windows.md +1 -1
  148. package/docs/workflows/api-reference.md +9 -1
  149. package/docs/workflows/operations.md +1 -1
  150. package/npm-shrinkwrap.json +49 -49
  151. package/package.json +6 -6
  152. package/schemas/keybindings.schema.json +4 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,51 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.9.89-alpha.2] - 2026-11-18
6
+
7
+ `NO_COLOR` now gives plain output everywhere, compact notices replace chat cards, and installs, shared libSQL servers and multi-node Intercom recover from interrupted and concurrent work.
8
+
9
+ **Interface**
10
+
11
+ - **Plain output under `NO_COLOR`.** `NO_COLOR` and `FORCE_COLOR=0` turn off every theme color, bold and italic in chats, tool blocks, `/tasks`, pickers, the workflow graph and run details. `FORCE_COLOR=1` or `2` limits colors to 256, and extensions follow the same rules with `hexColorAnsi()` ([#5435](https://github.com/bastani-inc/atomic/pull/5435), [#5441](https://github.com/bastani-inc/atomic/pull/5441), [#5454](https://github.com/bastani-inc/atomic/pull/5454))
12
+ - **Notices instead of cards.** Task and workflow heartbeats, workflow question and undelivered-message notices, and a stage chat's own notices use the chat's compact notice form instead of cards, and Ctrl+O expands their details ([#5440](https://github.com/bastani-inc/atomic/pull/5440), [#5453](https://github.com/bastani-inc/atomic/pull/5453))
13
+ - **Waiting subagents show as waiting.** A released subagent's launch card shows `◌ Waiting on <tool>` instead of reading as paused, and Alt+W opens the shell it waits on ([#5438](https://github.com/bastani-inc/atomic/pull/5438))
14
+ - **Shell counts in stage and subagent chats.** Their running background shells show as one count, such as `2 shells`, as in the main chat ([#5448](https://github.com/bastani-inc/atomic/pull/5448))
15
+
16
+ **Install and Windows**
17
+
18
+ - **Install scripts survive rate limits and interruptions.** A pinned version installs without the GitHub API, a rate limit names `GITHUB_TOKEN` as the fix, and an interrupted or concurrent install no longer leaves `atomic` unable to start ([#5443](https://github.com/bastani-inc/atomic/pull/5443), [#5452](https://github.com/bastani-inc/atomic/pull/5452))
19
+ - **Tool and Git installs.** Downloaded tools install when Atomic starts from PowerShell 7, and processes waiting on a killed Git install take over its lock without failing ([#5436](https://github.com/bastani-inc/atomic/pull/5436), [#4322](https://github.com/bastani-inc/atomic/issues/4322), [#5434](https://github.com/bastani-inc/atomic/pull/5434))
20
+ - **Busy Windows machines.** A supervised command that ran to completion, such as a named worktree's Git command, no longer fails with `Windows stdin worker stop was not confirmed` ([#5202](https://github.com/bastani-inc/atomic/issues/5202), [#5450](https://github.com/bastani-inc/atomic/pull/5450))
21
+
22
+ **Storage, workflows and Intercom**
23
+
24
+ - **Shared libSQL servers.** Statements that sqld answers with `SQLITE_SCHEMA` or `no such table` while other stores change the schema run again, and workflow journals wait for the write lock and refuse corrupt counters without writing ([#5456](https://github.com/bastani-inc/atomic/pull/5456), [#5462](https://github.com/bastani-inc/atomic/pull/5462), [#5464](https://github.com/bastani-inc/atomic/issues/5464), [#5467](https://github.com/bastani-inc/atomic/pull/5467), [#5439](https://github.com/bastani-inc/atomic/pull/5439))
25
+ - **PostgreSQL on Azure.** `atomic storage migrate` says when `pg_trgm` is missing, the storage guide covers Azure flexible servers and HorizonDB, and Atomic retries a write that a briefly read-only server refuses after a failover ([#5444](https://github.com/bastani-inc/atomic/pull/5444))
26
+ - **Multi-node Intercom.** A message to a subagent starting on another machine waits for it instead of failing with `Session not found`, a reply after a broker crash stays retryable when the database is slow, and a send to a session that just quit is reported as queued for its return instead of uncertain ([#5352](https://github.com/bastani-inc/atomic/issues/5352), [#5458](https://github.com/bastani-inc/atomic/pull/5458), [#5461](https://github.com/bastani-inc/atomic/pull/5461), [#4997](https://github.com/bastani-inc/atomic/issues/4997), [#5455](https://github.com/bastani-inc/atomic/pull/5455), [#5457](https://github.com/bastani-inc/atomic/pull/5457))
27
+ - **Fallback stages stop the session they replace.** After a context overflow, the old session no longer keeps calling tools in the stage's worktree next to the new one ([#5446](https://github.com/bastani-inc/atomic/pull/5446))
28
+ - **Faster worktree restores.** Restoring a worktree snapshot, such as when a workflow resumes in a fresh worktree, starts fewer Git processes, which cost tens of milliseconds each on Windows ([#5447](https://github.com/bastani-inc/atomic/pull/5447))
29
+
30
+ ### Added
31
+
32
+ - `hexColorAnsi(hex, "fg" | "bg")` returns the escape sequence for a `#rrggbb` color that follows `NO_COLOR` and `FORCE_COLOR` the way theme colors do, for extensions that paint their own colors
33
+
34
+ ### Changed
35
+
36
+ - A task heartbeat in chat is now a notice like the others instead of a shaded card: one `♥ Task heartbeat · N tasks still running` line, a `⎿` row per task (up to five, the rest counted in one row), and `/tasks to inspect` under them. Expanding it (Ctrl+O) adds each task's status and last output lines. The text the model reads is unchanged. For extensions, `NoticeStatus` gains `heartbeat` (the `♥` mark), and `HeartbeatBlock` draws a heartbeat in this form
37
+ - A waiting subagent's launch card in the parent's chat shows the same still `◌` mark and `Waiting on <tool>` as `/tasks`, instead of `⏸ Released · waiting`, which read as paused, and it shows the subagent running or finished again once it wakes or ends. Alt+W (`app.tasks.openWaited`) opens the output of the shell a waiting subagent waits on, from its chat or its `/tasks` row, and ← goes back; the chat's note and the `/tasks` hint name the key. `ToolBlock` and `NoticeLine` take the new `waiting` status, so code that switches over `ToolBlockStatus` or `NoticeStatus` should handle `waiting`.
38
+ - Workflow stage chats and subagent chats count their running background shells below their agent rows, for example `2 shells`, as the main chat's footer does, instead of listing each shell as a row. With no subagent rows the line adds `/tasks to manage`. `/tasks` still lists every shell
39
+ - Restoring a worktree snapshot, such as when a workflow resumes in a fresh worktree, starts fewer Git processes: the store is asked once whether it already holds the snapshot's commit before fetching it, several missing commits are looked up together, and the restored worktree's Git directory is read from its `.git` file. Each Git process costs tens of milliseconds on Windows
40
+
41
+ ### Fixed
42
+
43
+ - On Windows, installing a downloaded tool (such as `rg`, `fd` or Git) no longer fails when Atomic was started from PowerShell 7 and `tar.exe` cannot extract the zip archive: the Windows PowerShell fallback's `Expand-Archive` no longer inherits PowerShell 7's module path, which made it fail with `Cannot find an overload for "ExtractToDirectory"`. Every Windows PowerShell command Atomic runs for its own work now starts this way; the `powershell` tool and blueprint steps still run with your environment unchanged
44
+ - `NO_COLOR` now turns off every theme color. Chat messages, tool blocks, the agent panel, `/tasks`, pickers, scrollbars, the OpenRouter row in `/login` and Mermaid diagrams used to keep their foreground and background colors while it was set. `FORCE_COLOR=0` turns colors off too, and `FORCE_COLOR=1` or `2` limits them to 256 colors. Under `NO_COLOR` or `FORCE_COLOR=0`, the name in a stage or subagent chat's input rule is no longer bold either
45
+ - When an Atomic process installing git was killed while others waited for it, a waiter no longer fails with "Git is unavailable: ... could not be staged ... install lock" because the lock it had just taken was removed by another waiter. A waiter now moves an abandoned lock aside in one atomic rename and puts back at once any lock it moved that another installer had just taken, so a waiter that was paused while taking over no longer makes a second installer download git. A waiter whose new lock disappears before it is stamped tries for the lock again, and later installs remove what a waiter killed during a takeover left behind ([#4322](https://github.com/bastani-inc/atomic/issues/4322))
46
+ - `atomic storage migrate` on PostgreSQL now says when the `pg_trgm` extension is not installed and the role could not install it, as on Azure Database for PostgreSQL and Azure HorizonDB until `pg_trgm` is added to `azure.extensions`. Without it, searches of session history read each session a page at a time instead of using their index. The storage guide now covers Azure flexible servers (direct and through the built-in PgBouncer) and Azure HorizonDB. A write the server refuses because it accepts reads only (SQLSTATE `25006`) is now retried as `StorageTransientError` with the new code `read-only-server`, so a failover that leaves the old primary read-only for a moment recovers; a call still refused after its retries fails with a message that names both causes, a URL naming a read replica or read-only endpoint, or a server that is read-only for now, instead of a generic `StorageUnavailableError`
47
+ - The install scripts install a pinned `ATOMIC_VERSION` (or `--ref`/`-Ref`) without the GitHub API. They confirm the release on github.com, so a network that used up GitHub's 60 unauthenticated API requests an hour no longer fails with `curl: (56) The requested URL returned error: 403` and `failed to resolve the GitHub release`. When the API is still needed and refuses, the installer says why: a release that does not exist is reported as not found, and a rate limit names `GITHUB_TOKEN` as the fix. A pinned rerun of a release that is already installed and healthy makes no request at all, and the installers now record the launcher's hash at install time: an installed launcher that is empty or no longer matches it is reinstalled instead of being kept
48
+ - The install scripts no longer leave `atomic` unable to start when they are interrupted or run twice at once. Only one installer works on an install directory at a time, and a second one waits for the first (`ATOMIC_INSTALL_LOCK_TIMEOUT`, 30 minutes by default). On macOS and Linux the switch to a new version is a single rename, so `atomic` always starts a complete version even if the installer is killed partway, including a `--force` reinstall of the version in use. A later run removes the partial files a killed installer left. On Windows, the installer no longer runs the installed `atomic.exe` to read its version, keeps `%VAR%` entries in your User PATH as written, and does not pass `GITHUB_TOKEN` or `GH_TOKEN` to the programs it starts
49
+
5
50
  ## [0.9.89-alpha.1] - 2026-11-18
6
51
 
7
52
  Compaction clears the context and lets the agent recover from history, `model: "auto"` runs your default model, and a new agent panel keeps subagents and workflows in view while the interface stays responsive under load.
@@ -4,6 +4,14 @@ All notable changes to the `pi-intercom` extension will be documented in this fi
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.9.89-alpha.2] - 2026-11-18
8
+
9
+ ### Fixed
10
+
11
+ - With multi-node routing, a reply sent right after the broker that kept its question's only route crashed is refused as retryable again (`route_unavailable`, "try again") when the shared database is slow. Before, a slow lookup skipped that check, so the reply got the final "Pending question route does not authorize this public reply" and was never retried. If the database stops answering during that check, the reply is refused as retryable within 5 s, where before it could wait for good. A reply that no route could authorize is still refused for good ([#4997](https://github.com/bastani-inc/atomic/issues/4997)).
12
+ - Fixed a message to a subagent that was still starting under a supervisor on another machine sometimes failing with `Session not found` instead of waiting for the subagent. With multi-node routing, the broker confirmed the subagent's reservation to its supervisor before other machines' brokers could see it, so a session that sent to the subagent right away, on another machine, found nothing to wait for. The broker now waits up to 2.5 s for other machines to be able to find the reservation, and that of a released subagent, before it confirms it. If the shared database fails the write or does not answer in that time, the confirmation says the reservation is not published yet: it holds sends on the supervisor's machine at once, and the broker writes it again at each lease renewal (every 10 s) until other machines can find it, unless first the subagent connects, the reservation is released, or a newer reservation of the subagent replaces it. Such a reservation is not written afterwards, and a retry that was already writing when that happened ends what it wrote. Before, a failed write was never tried again, so sessions on other machines kept getting `Session not found` for that subagent ([#5352](https://github.com/bastani-inc/atomic/issues/5352))
13
+ - With multi-node routing, a send to a session on another broker that quit cleanly just before is again reported as queued for its return, instead of waiting out the receipt wait and being reported uncertain. The recipient's broker could claim the message for the session in the moment it left, and that claim, which never reached the session, counted as an attempt to deliver it.
14
+
7
15
  ## [0.9.89-alpha.1] - 2026-11-18
8
16
 
9
17
  ### Added
@@ -52,6 +52,20 @@ async function hostCommandOutput(
52
52
  return undefined;
53
53
  }
54
54
 
55
+ /**
56
+ * The environment for a host command. Windows PowerShell started from a PowerShell 7 parent inherits PowerShell 7's
57
+ * `PSModulePath`, finds PowerShell 7's copies of its built-in modules first and fails to load them, so `Get-Process`
58
+ * and `Get-CimInstance` fail. Without the variable Windows PowerShell uses its own module path; the other host commands
59
+ * do not read it.
60
+ */
61
+ export function hostCommandEnvironment(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
62
+ const result: NodeJS.ProcessEnv = {};
63
+ for (const [key, value] of Object.entries(env)) {
64
+ if (key.toLowerCase() !== "psmodulepath") result[key] = value;
65
+ }
66
+ return result;
67
+ }
68
+
55
69
  /** What the identity sources read from the host; tests pass fakes. */
56
70
  export interface HostIdentitySources {
57
71
  readonly platform: NodeJS.Platform;
@@ -74,7 +88,7 @@ export const systemSources = (configDir: string = getIntercomDirPath()): HostIde
74
88
  const child = execFile(
75
89
  command,
76
90
  [...args],
77
- { encoding: "utf8", timeout: HOST_COMMAND_TIMEOUT_MS, windowsHide: true },
91
+ { encoding: "utf8", env: hostCommandEnvironment(), timeout: HOST_COMMAND_TIMEOUT_MS, windowsHide: true },
78
92
  (error, stdout) => (error ? reject(error) : resolve(stdout)),
79
93
  );
80
94
  child.stdin?.end();
@@ -2548,7 +2548,7 @@ class IntercomBroker {
2548
2548
  });
2549
2549
  break;
2550
2550
  }
2551
- this.reserveRestoringRecipient(
2551
+ const published = this.reserveRestoringRecipient(
2552
2552
  clientMessage.capability,
2553
2553
  currentId,
2554
2554
  childName,
@@ -2560,7 +2560,12 @@ class IntercomBroker {
2560
2560
  },
2561
2561
  );
2562
2562
  this.dispatchHeldSends(this.departedChildren.supersede(currentId, childName));
2563
- writeMessageIfOpen(socket, { type: "restoring_recipient_ack", requestId: clientMessage.requestId });
2563
+ // #5352: acknowledged once senders on other brokers can find the reservation (bounded by the router).
2564
+ const requestId = clientMessage.requestId;
2565
+ // `published: false`: reserved here, and written for other brokers once the shared database takes it.
2566
+ void published.then((visible) =>
2567
+ writeMessageIfOpen(socket, { type: "restoring_recipient_ack", requestId, ...(visible ? {} : { published: false }) }),
2568
+ );
2564
2569
  break;
2565
2570
  }
2566
2571
 
@@ -2650,8 +2655,9 @@ class IntercomBroker {
2650
2655
  writeMessageIfOpen(socket, { type: "released_children_ack", requestId: clientMessage.requestId, refusal });
2651
2656
  break;
2652
2657
  }
2658
+ const published: Promise<boolean>[] = [];
2653
2659
  for (const child of validation.children) {
2654
- this.reserveReleasedChild(currentId, owner.registrationGroup, child);
2660
+ published.push(this.reserveReleasedChild(currentId, owner.registrationGroup, child));
2655
2661
  this.releasedAskerReplies.attach(child.childName, currentId);
2656
2662
  // #4751: a failed ask kept for the child wakes it again, so it is delivered.
2657
2663
  if (
@@ -2662,7 +2668,15 @@ class IntercomBroker {
2662
2668
  this.wakeRestoringRecipientOwner({ ownerSessionId: currentId, childName: child.childName });
2663
2669
  this.dispatchHeldSends(this.departedChildren.supersede(currentId, child.childName));
2664
2670
  }
2665
- writeMessageIfOpen(socket, { type: "released_children_ack", requestId: clientMessage.requestId });
2671
+ // #5352: acknowledged once senders on other brokers can find the reservations (bounded by the router).
2672
+ const requestId = clientMessage.requestId;
2673
+ void Promise.all(published).then((visible) =>
2674
+ writeMessageIfOpen(socket, {
2675
+ type: "released_children_ack",
2676
+ requestId,
2677
+ ...(visible.every(Boolean) ? {} : { published: false }),
2678
+ }),
2679
+ );
2666
2680
  break;
2667
2681
  }
2668
2682
 
@@ -3433,6 +3447,7 @@ class IntercomBroker {
3433
3447
  },
3434
3448
  dispatch: (socket, clientMessage, senderId) => this.dispatchSend(socket, clientMessage, senderId),
3435
3449
  revokeReleasedReservation: (key, ownerSessionId) => this.revokeReleasedReservation(key, ownerSessionId),
3450
+ holdsReservation: (key, ownerSessionId) => this.restoringRecipients.holds(key, ownerSessionId),
3436
3451
  },
3437
3452
  });
3438
3453
  } catch (error) {
@@ -3596,17 +3611,19 @@ class IntercomBroker {
3596
3611
  group: string,
3597
3612
  aliases: readonly string[],
3598
3613
  options: { readonly dormant: boolean; readonly wake?: boolean; readonly replaceAliases?: true; readonly holdMs?: number },
3599
- ): void {
3614
+ ): Promise<boolean> {
3600
3615
  const wake = this.restoringRecipients.reserve(key, ownerSessionId, childName, group, aliases, options);
3601
- this.multiNode?.restoringReserved(key, ownerSessionId, childName, group, aliases, options.dormant, {
3616
+ const published = this.multiNode?.restoringReserved(key, ownerSessionId, childName, group, aliases, options.dormant, {
3602
3617
  wake: options.wake === true,
3603
3618
  ...(options.replaceAliases === true ? { replaceAliases: true } : {}),
3604
3619
  });
3605
3620
  if (wake !== undefined) this.wakeRestoringRecipientOwner(wake);
3621
+ return published ?? Promise.resolve(true);
3606
3622
  }
3607
3623
 
3608
- private reserveReleasedChild(ownerSessionId: string, ownerGroup: string, child: ParsedReleasedChild): void {
3609
- this.reserveRestoringRecipient(
3624
+ /** Resolves true once senders on other brokers can find the reservation, false while its write is retried. */
3625
+ private reserveReleasedChild(ownerSessionId: string, ownerGroup: string, child: ParsedReleasedChild): Promise<boolean> {
3626
+ return this.reserveRestoringRecipient(
3610
3627
  releasedReservationKey(child.childName),
3611
3628
  ownerSessionId,
3612
3629
  child.childName,
@@ -534,7 +534,10 @@ export class IntercomClient extends EventEmitter {
534
534
  resolve: (authorization: SupervisorAuthorization) => void;
535
535
  reject: (error: Error) => void;
536
536
  }>();
537
- private pendingRestoringRecipientRequests = new Map<string, { resolve(): void; reject(error: Error): void }>();
537
+ private pendingRestoringRecipientRequests = new Map<
538
+ string,
539
+ { resolve(published?: boolean): void; reject(error: Error): void }
540
+ >();
538
541
  private pendingHostedSessionRequests = new Map<
539
542
  string,
540
543
  { resolve(sessions: readonly HostedSessionAssignment[]): void; reject(error: Error): void }
@@ -1317,27 +1320,35 @@ export class IntercomClient extends EventEmitter {
1317
1320
  break;
1318
1321
  }
1319
1322
  case "released_children_ack": {
1320
- const { requestId, refusal } = brokerMessage;
1323
+ const { requestId, refusal, published } = brokerMessage;
1321
1324
  const parsed = refusal === undefined ? undefined : readReleasedChildRefusal(refusal);
1322
- if (typeof requestId !== "string" || (refusal !== undefined && parsed === undefined)) {
1325
+ if (
1326
+ typeof requestId !== "string" ||
1327
+ (refusal !== undefined && parsed === undefined) ||
1328
+ (published !== undefined && typeof published !== "boolean")
1329
+ ) {
1323
1330
  throw new Error("Invalid released_children_ack message");
1324
1331
  }
1325
1332
  const pending = this.pendingRestoringRecipientRequests.get(requestId);
1326
1333
  if (!pending) return;
1327
1334
  this.pendingRestoringRecipientRequests.delete(requestId);
1328
- if (parsed === undefined) pending.resolve();
1335
+ if (parsed === undefined) pending.resolve(published !== false);
1329
1336
  else pending.reject(releasedChildErrorFor(parsed));
1330
1337
  break;
1331
1338
  }
1332
1339
  case "restoring_recipient_ack": {
1333
- const { requestId, error } = brokerMessage;
1334
- if (typeof requestId !== "string" || (error !== undefined && typeof error !== "string")) {
1340
+ const { requestId, error, published } = brokerMessage;
1341
+ if (
1342
+ typeof requestId !== "string" ||
1343
+ (error !== undefined && typeof error !== "string") ||
1344
+ (published !== undefined && typeof published !== "boolean")
1345
+ ) {
1335
1346
  throw new Error("Invalid restoring_recipient_ack message");
1336
1347
  }
1337
1348
  const pending = this.pendingRestoringRecipientRequests.get(requestId);
1338
1349
  if (!pending) return;
1339
1350
  this.pendingRestoringRecipientRequests.delete(requestId);
1340
- if (error === undefined) pending.resolve();
1351
+ if (error === undefined) pending.resolve(published !== false);
1341
1352
  else pending.reject(new Error(error));
1342
1353
  break;
1343
1354
  }
@@ -1751,12 +1762,14 @@ export class IntercomClient extends EventEmitter {
1751
1762
  * #3760: hold sends to the child that `capability` (issued to this session by `authorizeSupervisorChild`)
1752
1763
  * names, and to its `aliases`, until the child registers with that capability. Calling again adds aliases.
1753
1764
  * A `dormant` hold keeps the child addressable until the supervisor that restores it takes the hold over.
1765
+ * #5352: with multi-node routing, `published` is false when the hold is in force on this broker but brokers on other
1766
+ * hosts could not find it yet: the broker keeps publishing it until it can, or until the hold ends.
1754
1767
  */
1755
- reserveRestoringRecipient(
1768
+ async reserveRestoringRecipient(
1756
1769
  capability: string,
1757
1770
  options: { group?: string; aliases?: readonly string[]; dormant?: boolean; holdMs?: number } = {},
1758
- ): Promise<void> {
1759
- return this.restoringRecipientRequest({
1771
+ ): Promise<{ readonly published: boolean }> {
1772
+ const published = await this.restoringRecipientRequest({
1760
1773
  type: "reserve_restoring_recipient",
1761
1774
  capability,
1762
1775
  ...(options.group === undefined ? {} : { group: options.group }),
@@ -1764,6 +1777,7 @@ export class IntercomClient extends EventEmitter {
1764
1777
  ...(options.dormant === true ? { dormant: true } : {}),
1765
1778
  ...(options.holdMs === undefined ? {} : { holdMs: options.holdMs }),
1766
1779
  });
1780
+ return { published };
1767
1781
  }
1768
1782
 
1769
1783
  /**
@@ -1778,7 +1792,7 @@ export class IntercomClient extends EventEmitter {
1778
1792
  capability,
1779
1793
  ...(gone === undefined ? {} : { gone }),
1780
1794
  ...(refusal === undefined ? {} : { refusal }),
1781
- });
1795
+ }).then(() => undefined);
1782
1796
  }
1783
1797
 
1784
1798
  /**
@@ -1864,7 +1878,7 @@ export class IntercomClient extends EventEmitter {
1864
1878
  } catch (error) {
1865
1879
  return Promise.reject(toError(error));
1866
1880
  }
1867
- return this.restoringRecipientRequest({ type: "acknowledge_released_child_wake", childName });
1881
+ return this.restoringRecipientRequest({ type: "acknowledge_released_child_wake", childName }).then(() => undefined);
1868
1882
  }
1869
1883
 
1870
1884
  acknowledgeReleasedChildReply(reply: ReleasedChildReply, accepted: boolean, deliverToChild = false): boolean {
@@ -1979,7 +1993,8 @@ export class IntercomClient extends EventEmitter {
1979
1993
  });
1980
1994
  }
1981
1995
 
1982
- private restoringRecipientRequest(frame: Record<string, unknown>): Promise<void> {
1996
+ /** Resolves false when the broker reserved with `published: false` (#5352), true for every other success. */
1997
+ private restoringRecipientRequest(frame: Record<string, unknown>): Promise<boolean> {
1983
1998
  let socket: net.Socket;
1984
1999
  try {
1985
2000
  socket = this.requireActiveSocket();
@@ -1993,7 +2008,7 @@ export class IntercomClient extends EventEmitter {
1993
2008
  void this.requestTimeout(socket, new Error("Restoring-recipient request timeout")).then(reject);
1994
2009
  }, RESTORING_RECIPIENT_REQUEST_TIMEOUT_MS);
1995
2010
  this.pendingRestoringRecipientRequests.set(requestId, {
1996
- resolve: () => { clearTimeout(timeout); resolve(); },
2011
+ resolve: (published = true) => { clearTimeout(timeout); resolve(published); },
1997
2012
  reject: (error) => { clearTimeout(timeout); reject(error); },
1998
2013
  });
1999
2014
  try {
@@ -152,6 +152,12 @@ export const SESSION_ID_CLAIM_BOUND_MS = 2_500;
152
152
  * locally, with the local accepted-delivery cache as its duplicate protection.
153
153
  */
154
154
  export const LOCAL_RETRY_LOOKUP_BOUND_MS = 300;
155
+ /**
156
+ * The longest a reservation's acknowledgement waits for the shared database to record it, so a sender on another broker
157
+ * that learns of the child after the acknowledgement finds it held. The client's reserve request gives up after 5 s; past
158
+ * this bound the reservation is still written when the database answers.
159
+ */
160
+ export const RESERVATION_PUBLISH_BOUND_MS = 2_500;
155
161
  /** The longest `list` waits for other nodes' sessions; the client's list request gives up after 5 s. */
156
162
  const REMOTE_SESSIONS_BOUND_MS = 2_000;
157
163
  const MAX_SUPERSEDED_HOPS = 8;
@@ -225,6 +231,11 @@ export interface MultiNodeHost {
225
231
  /** Route a held send again as its sender, exactly like a new send (local delivery or the outbox). */
226
232
  dispatch(socket: BrokerConnectedSession["socket"], clientMessage: SendClientMessage, senderId: string): void;
227
233
  revokeReleasedReservation(reservationKey: string, ownerSessionId: string): void;
234
+ /**
235
+ * #5352: whether this broker still holds the reservation the owner made under `capability` (its capability or
236
+ * released-child key): false once it was released, taken by its child, or replaced by a newer reservation of the child.
237
+ */
238
+ holdsReservation(capability: string, ownerSessionId: string): boolean;
228
239
  }
229
240
 
230
241
  export interface MultiNodeRouterOptions {
@@ -364,6 +375,24 @@ interface MirroredReservation {
364
375
  * handed on when the child consumes it (#4488).
365
376
  */
366
377
  readonly superseded?: readonly string[];
378
+ /** #5352: what was written, to write it again if a stale retry of an older reservation of the child ends it. */
379
+ readonly publication?: UnpublishedReservation;
380
+ }
381
+
382
+ /**
383
+ * A reservation made here that the shared database does not hold yet: its write failed, or has not answered. It is
384
+ * written again at each renewal until it lands, or until it is released, consumed or made again (#5352).
385
+ */
386
+ interface UnpublishedReservation {
387
+ readonly capability: string;
388
+ readonly ownerSessionId: string;
389
+ /** The owner's connection when it reserved: a reservation it no longer holds is not written. */
390
+ readonly owner: BrokerConnectedSession | undefined;
391
+ readonly childName: string;
392
+ readonly group: string;
393
+ readonly aliases: readonly string[];
394
+ readonly dormant: boolean;
395
+ readonly options: ReservationOptions;
367
396
  }
368
397
 
369
398
  /** How a mirrored reservation differs from a plain restoring one. */
@@ -474,6 +503,11 @@ export class MultiNodeRouter {
474
503
  this.fail(request, "Pending question route does not authorize this public reply");
475
504
  return;
476
505
  }
506
+ this.refuseRouteUnavailable(request);
507
+ }
508
+
509
+ /** #4997: refuse a reply as retryable (`route_unavailable`): a route that would authorize it may be unreachable. */
510
+ private refuseRouteUnavailable(request: RemoteSendRequest): void {
477
511
  this.host.write(request.socket, {
478
512
  type: "delivery_failed",
479
513
  messageId: request.message.id,
@@ -500,6 +534,9 @@ export class MultiNodeRouter {
500
534
  private readonly mirrored = new Map<string, MirroredReservation>();
501
535
  /** Reservations with a backup-poll wake check queued or running: one each while the store stalls, not a backlog. */
502
536
  private readonly pendingWakeChecks = new Set<string>();
537
+ /** #5352: reservations made here whose shared write has not landed, by reservation key. */
538
+ private readonly unpublished = new Map<string, UnpublishedReservation>();
539
+ private readonly pendingPublishRetries = new Set<string>();
503
540
  private readonly heldIdentities = new Set<string>();
504
541
  private readonly scanning = new Map<string, { rescan: boolean }>();
505
542
  private readonly serials = new Map<string, Promise<void>>();
@@ -1283,6 +1320,11 @@ export class MultiNodeRouter {
1283
1320
  // ---------------------------------------------------------------------------------------------------------
1284
1321
  // Restoring reservations (§5.7): mirror this broker's reservations so senders on any host hold their sends.
1285
1322
 
1323
+ /**
1324
+ * Resolves true once other brokers can find the reservation, or false when its shared write failed or did not answer
1325
+ * within `RESERVATION_PUBLISH_BOUND_MS`: the reservation then holds sends on this broker, and the write is retried at
1326
+ * each renewal until it lands or the reservation ends.
1327
+ */
1286
1328
  restoringReserved(
1287
1329
  capability: string,
1288
1330
  ownerSessionId: string,
@@ -1291,60 +1333,127 @@ export class MultiNodeRouter {
1291
1333
  aliases: readonly string[],
1292
1334
  dormant: boolean,
1293
1335
  options: ReservationOptions = {},
1294
- ): void {
1295
- if (this.closed) return;
1336
+ ): Promise<boolean> {
1337
+ if (this.closed) return Promise.resolve(true);
1296
1338
  const reservationKey = reservationKeyFor(capability);
1297
- const owner = this.host.sessions.get(ownerSessionId);
1298
- const wake = options.wake === true;
1299
- this.serial(`reservation:${reservationKey}`, async () => {
1300
- const previous = this.mirrored.get(reservationKey);
1301
- const reserved = await this.state.reservations.reserve({
1302
- reservationKey,
1303
- ownerSessionId,
1304
- ownerBrokerId: this.brokerId,
1305
- childName,
1306
- childTarget: normalizeTarget(childName),
1307
- aliases: aliases.map(normalizeTarget).filter((alias) => alias.length > 0),
1308
- group,
1309
- dormant,
1310
- wake,
1311
- ...(options.replaceAliases === true ? { replaceAliases: true } : {}),
1312
- staleAfterMs: BROKER_LEASE_STALE_AFTER_MS,
1313
- });
1314
- if (reserved.status === "not-owner") {
1315
- this.host.revokeReleasedReservation(reservationKey, ownerSessionId);
1316
- return;
1317
- }
1318
- if (reserved.status !== "reserved") return;
1319
- // The owner left (or its id was taken over) while the reserve was being written: its departure scanned the
1320
- // mirrors before this one existed, so end the reservation here instead of renewing it for a gone owner.
1321
- if (this.host.sessions.get(ownerSessionId) !== owner) {
1322
- await this.state.reservations.release(reserved.lease);
1323
- await this.wakeHeldOrigins(reservationKey);
1324
- return;
1325
- }
1326
- const woken =
1327
- wake && previous?.woken === true && previous.lease.fencingToken === reserved.lease.fencingToken;
1328
- const superseded = new Set(
1329
- previous?.lease.fencingToken === reserved.lease.fencingToken ? previous.superseded : undefined,
1330
- );
1331
- for (const key of reserved.superseded) {
1332
- superseded.add(key);
1333
- for (const earlier of this.mirrored.get(key)?.superseded ?? []) superseded.add(earlier);
1334
- }
1335
- this.mirrored.set(reservationKey, {
1336
- lease: reserved.lease,
1337
- wake,
1338
- aliases,
1339
- group,
1340
- ...(woken ? { woken } : {}),
1341
- ...(superseded.size > 0 ? { superseded: [...superseded] } : {}),
1342
- ...(isReleasedReservationKey(capability) ? {} : { capability }),
1339
+ const pending: UnpublishedReservation = {
1340
+ capability,
1341
+ ownerSessionId,
1342
+ owner: this.host.sessions.get(ownerSessionId),
1343
+ childName,
1344
+ group,
1345
+ aliases,
1346
+ dormant,
1347
+ options,
1348
+ };
1349
+ this.unpublished.set(reservationKey, pending);
1350
+ this.serial(`reservation:${reservationKey}`, () => this.publishReservation(reservationKey, pending, false));
1351
+ // #5352: the owner is acknowledged once other brokers can find the reservation, so a sender that learns of the
1352
+ // child afterwards is held rather than told it is not found. A database that does not answer is waited for only
1353
+ // up to `RESERVATION_PUBLISH_BOUND_MS`.
1354
+ const written = this.serials.get(`reservation:${reservationKey}`) ?? Promise.resolve();
1355
+ return new Promise<boolean>((resolve) => {
1356
+ const settle = () => resolve(this.unpublished.get(reservationKey) !== pending);
1357
+ const bound = setTimeout(settle, RESERVATION_PUBLISH_BOUND_MS);
1358
+ bound.unref?.();
1359
+ void written.finally(() => {
1360
+ clearTimeout(bound);
1361
+ settle();
1343
1362
  });
1344
- await this.wakeWaitingChild(reservationKey);
1345
1363
  });
1346
1364
  }
1347
1365
 
1366
+ /**
1367
+ * Write a reservation made here to the shared database. It stays unpublished, for the renewal to write again, only
1368
+ * while the write fails. The first write runs in its key's order, so a release or departure after it ends what it
1369
+ * wrote; a `retry` writes nothing once the reservation was released, consumed, replaced or made again, or its owner
1370
+ * left, and ends what it wrote when that happened while it was writing.
1371
+ */
1372
+ private async publishReservation(reservationKey: string, pending: UnpublishedReservation, retry: boolean): Promise<void> {
1373
+ const { capability, ownerSessionId, owner, childName, group, aliases, dormant, options } = pending;
1374
+ if (
1375
+ retry &&
1376
+ (this.unpublished.get(reservationKey) !== pending ||
1377
+ this.host.sessions.get(ownerSessionId) !== owner ||
1378
+ !this.host.holdsReservation(capability, ownerSessionId))
1379
+ ) {
1380
+ if (this.unpublished.get(reservationKey) === pending) this.unpublished.delete(reservationKey);
1381
+ return;
1382
+ }
1383
+ const settled = () => {
1384
+ if (this.unpublished.get(reservationKey) === pending) this.unpublished.delete(reservationKey);
1385
+ };
1386
+ const wake = options.wake === true;
1387
+ const previous = this.mirrored.get(reservationKey);
1388
+ const reserved = await this.state.reservations.reserve({
1389
+ reservationKey,
1390
+ ownerSessionId,
1391
+ ownerBrokerId: this.brokerId,
1392
+ childName,
1393
+ childTarget: normalizeTarget(childName),
1394
+ aliases: aliases.map(normalizeTarget).filter((alias) => alias.length > 0),
1395
+ group,
1396
+ dormant,
1397
+ wake,
1398
+ ...(options.replaceAliases === true ? { replaceAliases: true } : {}),
1399
+ staleAfterMs: BROKER_LEASE_STALE_AFTER_MS,
1400
+ });
1401
+ settled();
1402
+ if (reserved.status === "not-owner") {
1403
+ this.host.revokeReleasedReservation(reservationKey, ownerSessionId);
1404
+ return;
1405
+ }
1406
+ if (reserved.status !== "reserved") return;
1407
+ // The owner left (or its id was taken over) while the reserve was being written: its departure scanned the
1408
+ // mirrors before this one existed, so end the reservation here instead of renewing it for a gone owner. A retry
1409
+ // likewise ends what it wrote for a reservation its child took, or a newer one replaced, meanwhile: those ran
1410
+ // outside this key's order.
1411
+ if (
1412
+ this.host.sessions.get(ownerSessionId) !== owner ||
1413
+ (retry && !this.host.holdsReservation(capability, ownerSessionId))
1414
+ ) {
1415
+ await this.state.reservations.release(reserved.lease);
1416
+ await this.wakeHeldOrigins(reservationKey);
1417
+ if (retry) this.republishSuperseded(reserved.superseded);
1418
+ return;
1419
+ }
1420
+ const woken =
1421
+ wake && previous?.woken === true && previous.lease.fencingToken === reserved.lease.fencingToken;
1422
+ const superseded = new Set(
1423
+ previous?.lease.fencingToken === reserved.lease.fencingToken ? previous.superseded : undefined,
1424
+ );
1425
+ for (const key of reserved.superseded) {
1426
+ superseded.add(key);
1427
+ for (const earlier of this.mirrored.get(key)?.superseded ?? []) superseded.add(earlier);
1428
+ }
1429
+ this.mirrored.set(reservationKey, {
1430
+ lease: reserved.lease,
1431
+ wake,
1432
+ aliases,
1433
+ group,
1434
+ ...(woken ? { woken } : {}),
1435
+ ...(superseded.size > 0 ? { superseded: [...superseded] } : {}),
1436
+ ...(isReleasedReservationKey(capability) ? {} : { capability }),
1437
+ publication: pending,
1438
+ });
1439
+ await this.wakeWaitingChild(reservationKey);
1440
+ }
1441
+
1442
+ /**
1443
+ * #5352: a stale retry ended the newer reservations of its child that it superseded as it wrote: the ones this broker
1444
+ * still holds are written again, in their keys' order.
1445
+ */
1446
+ private republishSuperseded(keys: readonly string[]): void {
1447
+ for (const key of keys) {
1448
+ const publication = this.mirrored.get(key)?.publication;
1449
+ if (publication === undefined || !this.host.holdsReservation(publication.capability, publication.ownerSessionId))
1450
+ continue;
1451
+ this.mirrored.delete(key);
1452
+ this.unpublished.set(key, publication);
1453
+ this.serial(`reservation:${key}`, () => this.publishReservation(key, publication, true));
1454
+ }
1455
+ }
1456
+
1348
1457
  /**
1349
1458
  * #4401: ask the owner to wake a released child it reserved here while sends wait for it, once per reservation.
1350
1459
  * Derived from the shared state on every reserve and backup poll, so a broker that restarted, or a new owner
@@ -1420,6 +1529,8 @@ export class MultiNodeRouter {
1420
1529
  restoringReleased(capability: string, ownerSessionId: string, gone?: string, refusal?: string): void {
1421
1530
  if (this.closed) return;
1422
1531
  const reservationKey = reservationKeyFor(capability);
1532
+ // #5352: a reservation whose write has not landed is not written after its release.
1533
+ if (this.unpublished.get(reservationKey)?.ownerSessionId === ownerSessionId) this.unpublished.delete(reservationKey);
1423
1534
  // Behind the reserve on the same key: a release while the reserve is still being written ends what it wrote.
1424
1535
  this.serial(`reservation:${reservationKey}`, async () => {
1425
1536
  // #4386: asks parked for a released subagent its owner no longer holds end here, as its local ones do; #4992:
@@ -1444,6 +1555,8 @@ export class MultiNodeRouter {
1444
1555
  ? undefined
1445
1556
  : releasedReservationKey(consumed.childName);
1446
1557
  if (reservationKey === undefined) return;
1558
+ // #5352: the child took its reservation; one whose write has not landed is not written now.
1559
+ this.unpublished.delete(reservationKey);
1447
1560
  const result = await this.state.reservations.consume(
1448
1561
  reservationKey,
1449
1562
  consumed.childName === undefined
@@ -1646,8 +1759,21 @@ export class MultiNodeRouter {
1646
1759
  if (this.host.deliveredMessages.lookupForTarget(request.message.id, request.signature, deliveryTargetIdentity(target)) !== "miss")
1647
1760
  return false;
1648
1761
  const asker = { sessionId: target.info.id, identity: deliveryTargetIdentity(target) };
1649
- if (!(await this.routeMayBeElsewhere(request, asker.sessionId, asker.identity).catch(() => false))) return false;
1650
- await this.refuseUnauthorizedReply(request, asker);
1762
+ const elsewhere = this.routeMayBeElsewhere(request, asker.sessionId, asker.identity).catch(() => false);
1763
+ // A shared database that stops answering leaves the reply undecided: it is refused as retryable, once, within the
1764
+ // bound, so neither it nor the sender's later replies wait on that database for good. It authorizes nothing.
1765
+ let bound: ReturnType<typeof setTimeout> | undefined;
1766
+ const expired = new Promise<"expired">((resolve) => {
1767
+ bound = setTimeout(() => resolve("expired"), PRESENCE_REGISTRATION_BOUND_MS);
1768
+ bound.unref?.();
1769
+ });
1770
+ try {
1771
+ const decided = await Promise.race([elsewhere, expired]);
1772
+ if (decided === false) return false;
1773
+ } finally {
1774
+ clearTimeout(bound);
1775
+ }
1776
+ this.refuseRouteUnavailable(request);
1651
1777
  return true;
1652
1778
  }
1653
1779
 
@@ -1928,6 +2054,9 @@ export class MultiNodeRouter {
1928
2054
  if (existing === "expired") {
1929
2055
  lookup.catch((error: Error) => this.report(error));
1930
2056
  await this.adoptSharedRouteWithin(request, target);
2057
+ // #4997: a reply whose ask's route may be on a broker that is down is refused as retryable here too, not by
2058
+ // the local path's final refusal just because the outbox lookup was slow.
2059
+ if (await this.routeUnreachable(request, target)) return;
1931
2060
  request.notFound();
1932
2061
  return;
1933
2062
  }
@@ -2538,7 +2667,11 @@ export class MultiNodeRouter {
2538
2667
  for (const { row, claim } of claimed.rows) {
2539
2668
  const session = this.localSessionFor(identity);
2540
2669
  if (session === undefined) {
2541
- await this.state.outbox.releaseClaim(claim);
2670
+ // The recipient left while the claim was on its way to the database: the row was never written to it, so it
2671
+ // goes back as never claimed. Its sender's broker then still queues it for the recipient's return
2672
+ // (`positionIfRecipientLeft`), instead of reporting the send uncertain once its receipt wait ends.
2673
+ const released = await this.state.outbox.releaseClaim(claim, { unwritten: true });
2674
+ if (released.status === "released") await this.wakeOrigin(row);
2542
2675
  continue;
2543
2676
  }
2544
2677
  if (row.frame.type === "released_child_reply") {
@@ -2985,6 +3118,14 @@ export class MultiNodeRouter {
2985
3118
  const renewed = await this.state.reservations.renew(mirror.lease);
2986
3119
  if (renewed.status !== "renewed" && this.mirrored.get(key) === mirror) this.mirrored.delete(key);
2987
3120
  }
3121
+ // #5352: a reservation whose write failed or did not answer is written again, in order behind its key's steps.
3122
+ for (const [key, pending] of this.unpublished) {
3123
+ if (this.pendingPublishRetries.has(key)) continue;
3124
+ this.pendingPublishRetries.add(key);
3125
+ this.serial(`reservation:${key}`, () =>
3126
+ this.publishReservation(key, pending, true).finally(() => this.pendingPublishRetries.delete(key)),
3127
+ );
3128
+ }
2988
3129
  for (const identity of [...this.heldIdentities]) this.scanIdentity(identity);
2989
3130
  }
2990
3131