agent-relay 17.2.0 → 18.0.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 (244) hide show
  1. package/README.md +45 -270
  2. package/dist/cli/agent-relay-mcp.d.ts.map +1 -1
  3. package/dist/cli/agent-relay-mcp.js +6 -5
  4. package/dist/cli/agent-relay-mcp.js.map +1 -1
  5. package/dist/cli/bootstrap.d.ts +1 -1
  6. package/dist/cli/bootstrap.d.ts.map +1 -1
  7. package/dist/cli/bootstrap.js +11 -29
  8. package/dist/cli/bootstrap.js.map +1 -1
  9. package/dist/cli/commands/agent.d.ts.map +1 -1
  10. package/dist/cli/commands/agent.js +3 -2
  11. package/dist/cli/commands/agent.js.map +1 -1
  12. package/dist/cli/commands/cloud-integration.d.ts.map +1 -1
  13. package/dist/cli/commands/cloud-integration.js +2 -1
  14. package/dist/cli/commands/cloud-integration.js.map +1 -1
  15. package/dist/cli/commands/cloud-room.d.ts.map +1 -1
  16. package/dist/cli/commands/cloud-room.js +2 -1
  17. package/dist/cli/commands/cloud-room.js.map +1 -1
  18. package/dist/cli/commands/cloud-v1-deprecations.d.ts +4 -6
  19. package/dist/cli/commands/cloud-v1-deprecations.d.ts.map +1 -1
  20. package/dist/cli/commands/cloud-v1-deprecations.js +4 -6
  21. package/dist/cli/commands/cloud-v1-deprecations.js.map +1 -1
  22. package/dist/cli/commands/cloud-worker.d.ts +1 -1
  23. package/dist/cli/commands/cloud-worker.d.ts.map +1 -1
  24. package/dist/cli/commands/cloud-worker.js +42 -31
  25. package/dist/cli/commands/cloud-worker.js.map +1 -1
  26. package/dist/cli/commands/cloud.d.ts.map +1 -1
  27. package/dist/cli/commands/cloud.js +6 -7
  28. package/dist/cli/commands/cloud.js.map +1 -1
  29. package/dist/cli/commands/core.d.ts +3 -91
  30. package/dist/cli/commands/core.d.ts.map +1 -1
  31. package/dist/cli/commands/core.js +5 -254
  32. package/dist/cli/commands/core.js.map +1 -1
  33. package/dist/cli/commands/fleet-agent.d.ts +9 -54
  34. package/dist/cli/commands/fleet-agent.d.ts.map +1 -1
  35. package/dist/cli/commands/fleet-agent.js +105 -314
  36. package/dist/cli/commands/fleet-agent.js.map +1 -1
  37. package/dist/cli/commands/fleet.d.ts +0 -3
  38. package/dist/cli/commands/fleet.d.ts.map +1 -1
  39. package/dist/cli/commands/fleet.js +48 -267
  40. package/dist/cli/commands/fleet.js.map +1 -1
  41. package/dist/cli/commands/init.js +1 -1
  42. package/dist/cli/commands/init.js.map +1 -1
  43. package/dist/cli/commands/integration-cleanup-journal.d.ts +6 -2
  44. package/dist/cli/commands/integration-cleanup-journal.d.ts.map +1 -1
  45. package/dist/cli/commands/integration-cleanup-journal.js +611 -134
  46. package/dist/cli/commands/integration-cleanup-journal.js.map +1 -1
  47. package/dist/cli/commands/integration-recipient.d.ts +0 -17
  48. package/dist/cli/commands/integration-recipient.d.ts.map +1 -1
  49. package/dist/cli/commands/integration-recipient.js +1 -104
  50. package/dist/cli/commands/integration-recipient.js.map +1 -1
  51. package/dist/cli/commands/integration.d.ts +7 -3
  52. package/dist/cli/commands/integration.d.ts.map +1 -1
  53. package/dist/cli/commands/integration.js +37 -82
  54. package/dist/cli/commands/integration.js.map +1 -1
  55. package/dist/cli/commands/local-workflow.d.ts +1 -1
  56. package/dist/cli/commands/local-workflow.d.ts.map +1 -1
  57. package/dist/cli/commands/local-workflow.js +20 -6
  58. package/dist/cli/commands/local-workflow.js.map +1 -1
  59. package/dist/cli/commands/node.d.ts +18 -20
  60. package/dist/cli/commands/node.d.ts.map +1 -1
  61. package/dist/cli/commands/node.js +42 -272
  62. package/dist/cli/commands/node.js.map +1 -1
  63. package/dist/cli/commands/product-surfaces.js +4 -4
  64. package/dist/cli/commands/product-surfaces.js.map +1 -1
  65. package/dist/cli/commands/session.d.ts.map +1 -1
  66. package/dist/cli/commands/session.js +2 -1
  67. package/dist/cli/commands/session.js.map +1 -1
  68. package/dist/cli/commands/skills.d.ts.map +1 -1
  69. package/dist/cli/commands/skills.js +2 -1
  70. package/dist/cli/commands/skills.js.map +1 -1
  71. package/dist/cli/commands/status.d.ts +1 -7
  72. package/dist/cli/commands/status.d.ts.map +1 -1
  73. package/dist/cli/commands/status.js +2 -28
  74. package/dist/cli/commands/status.js.map +1 -1
  75. package/dist/cli/commands/workspace.d.ts.map +1 -1
  76. package/dist/cli/commands/workspace.js +2 -2
  77. package/dist/cli/commands/workspace.js.map +1 -1
  78. package/dist/cli/index.d.ts.map +1 -1
  79. package/dist/cli/index.js +1 -3
  80. package/dist/cli/index.js.map +1 -1
  81. package/dist/cli/lib/agent-relay-cli-reentry.d.ts +37 -0
  82. package/dist/cli/lib/agent-relay-cli-reentry.d.ts.map +1 -0
  83. package/dist/cli/lib/agent-relay-cli-reentry.js +40 -0
  84. package/dist/cli/lib/agent-relay-cli-reentry.js.map +1 -0
  85. package/dist/cli/lib/agent-tools-mcp.d.ts.map +1 -1
  86. package/dist/cli/lib/agent-tools-mcp.js +3 -2
  87. package/dist/cli/lib/agent-tools-mcp.js.map +1 -1
  88. package/dist/cli/lib/core-maintenance.d.ts +2 -3
  89. package/dist/cli/lib/core-maintenance.d.ts.map +1 -1
  90. package/dist/cli/lib/core-maintenance.js +3 -37
  91. package/dist/cli/lib/core-maintenance.js.map +1 -1
  92. package/dist/cli/lib/desktop-presence.js +1 -1
  93. package/dist/cli/lib/desktop-presence.js.map +1 -1
  94. package/dist/cli/lib/install-paths.d.ts +100 -0
  95. package/dist/cli/lib/install-paths.d.ts.map +1 -0
  96. package/dist/cli/lib/install-paths.js +157 -0
  97. package/dist/cli/lib/install-paths.js.map +1 -0
  98. package/dist/cli/lib/product-surface-store.d.ts.map +1 -1
  99. package/dist/cli/lib/product-surface-store.js +4 -1
  100. package/dist/cli/lib/product-surface-store.js.map +1 -1
  101. package/dist/cli/lib/relay-node.d.ts +7 -34
  102. package/dist/cli/lib/relay-node.d.ts.map +1 -1
  103. package/dist/cli/lib/relay-node.js +7 -182
  104. package/dist/cli/lib/relay-node.js.map +1 -1
  105. package/dist/cli/lib/removed-broker-command.d.ts +7 -0
  106. package/dist/cli/lib/removed-broker-command.d.ts.map +1 -0
  107. package/dist/cli/lib/removed-broker-command.js +13 -0
  108. package/dist/cli/lib/removed-broker-command.js.map +1 -0
  109. package/dist/cli/lib/sdk-client.d.ts +4 -4
  110. package/dist/cli/lib/sdk-client.js +4 -4
  111. package/dist/cli/lib/self-update.d.ts +8 -19
  112. package/dist/cli/lib/self-update.d.ts.map +1 -1
  113. package/dist/cli/lib/self-update.js +14 -28
  114. package/dist/cli/lib/self-update.js.map +1 -1
  115. package/dist/cli/lib/skills-install.d.ts.map +1 -1
  116. package/dist/cli/lib/skills-install.js +3 -2
  117. package/dist/cli/lib/skills-install.js.map +1 -1
  118. package/dist/cli/telemetry/events.d.ts +4 -1
  119. package/dist/cli/telemetry/events.d.ts.map +1 -1
  120. package/package.json +10 -15
  121. package/dist/auto/classifier.d.ts +0 -29
  122. package/dist/auto/classifier.d.ts.map +0 -1
  123. package/dist/auto/classifier.js +0 -126
  124. package/dist/auto/classifier.js.map +0 -1
  125. package/dist/auto/composer.d.ts +0 -105
  126. package/dist/auto/composer.d.ts.map +0 -1
  127. package/dist/auto/composer.js +0 -454
  128. package/dist/auto/composer.js.map +0 -1
  129. package/dist/auto/director-prompt.d.ts +0 -25
  130. package/dist/auto/director-prompt.d.ts.map +0 -1
  131. package/dist/auto/director-prompt.js +0 -53
  132. package/dist/auto/director-prompt.js.map +0 -1
  133. package/dist/auto/index.d.ts +0 -15
  134. package/dist/auto/index.d.ts.map +0 -1
  135. package/dist/auto/index.js +0 -13
  136. package/dist/auto/index.js.map +0 -1
  137. package/dist/cli/commands/local-agent.d.ts +0 -74
  138. package/dist/cli/commands/local-agent.d.ts.map +0 -1
  139. package/dist/cli/commands/local-agent.js +0 -969
  140. package/dist/cli/commands/local-agent.js.map +0 -1
  141. package/dist/cli/lib/attach-broker.d.ts +0 -17
  142. package/dist/cli/lib/attach-broker.d.ts.map +0 -1
  143. package/dist/cli/lib/attach-broker.js +0 -27
  144. package/dist/cli/lib/attach-broker.js.map +0 -1
  145. package/dist/cli/lib/attach-drive.d.ts +0 -376
  146. package/dist/cli/lib/attach-drive.d.ts.map +0 -1
  147. package/dist/cli/lib/attach-drive.js +0 -1212
  148. package/dist/cli/lib/attach-drive.js.map +0 -1
  149. package/dist/cli/lib/attach-fleet-node.d.ts +0 -85
  150. package/dist/cli/lib/attach-fleet-node.d.ts.map +0 -1
  151. package/dist/cli/lib/attach-fleet-node.js +0 -1347
  152. package/dist/cli/lib/attach-fleet-node.js.map +0 -1
  153. package/dist/cli/lib/attach-input-recovery.d.ts +0 -190
  154. package/dist/cli/lib/attach-input-recovery.d.ts.map +0 -1
  155. package/dist/cli/lib/attach-input-recovery.js +0 -559
  156. package/dist/cli/lib/attach-input-recovery.js.map +0 -1
  157. package/dist/cli/lib/attach-mode.d.ts +0 -2
  158. package/dist/cli/lib/attach-mode.d.ts.map +0 -1
  159. package/dist/cli/lib/attach-mode.js +0 -2
  160. package/dist/cli/lib/attach-mode.js.map +0 -1
  161. package/dist/cli/lib/attach-native.d.ts +0 -27
  162. package/dist/cli/lib/attach-native.d.ts.map +0 -1
  163. package/dist/cli/lib/attach-native.js +0 -267
  164. package/dist/cli/lib/attach-native.js.map +0 -1
  165. package/dist/cli/lib/attach-passthrough.d.ts +0 -193
  166. package/dist/cli/lib/attach-passthrough.d.ts.map +0 -1
  167. package/dist/cli/lib/attach-passthrough.js +0 -778
  168. package/dist/cli/lib/attach-passthrough.js.map +0 -1
  169. package/dist/cli/lib/attach-remote-node.d.ts +0 -21
  170. package/dist/cli/lib/attach-remote-node.d.ts.map +0 -1
  171. package/dist/cli/lib/attach-remote-node.js +0 -133
  172. package/dist/cli/lib/attach-remote-node.js.map +0 -1
  173. package/dist/cli/lib/attach-view.d.ts +0 -177
  174. package/dist/cli/lib/attach-view.d.ts.map +0 -1
  175. package/dist/cli/lib/attach-view.js +0 -455
  176. package/dist/cli/lib/attach-view.js.map +0 -1
  177. package/dist/cli/lib/attach.d.ts +0 -555
  178. package/dist/cli/lib/attach.d.ts.map +0 -1
  179. package/dist/cli/lib/attach.js +0 -1180
  180. package/dist/cli/lib/attach.js.map +0 -1
  181. package/dist/cli/lib/broker-connection.d.ts +0 -65
  182. package/dist/cli/lib/broker-connection.d.ts.map +0 -1
  183. package/dist/cli/lib/broker-connection.js +0 -144
  184. package/dist/cli/lib/broker-connection.js.map +0 -1
  185. package/dist/cli/lib/broker-lifecycle.d.ts +0 -220
  186. package/dist/cli/lib/broker-lifecycle.d.ts.map +0 -1
  187. package/dist/cli/lib/broker-lifecycle.js +0 -2290
  188. package/dist/cli/lib/broker-lifecycle.js.map +0 -1
  189. package/dist/cli/lib/broker-process-identity.d.ts +0 -38
  190. package/dist/cli/lib/broker-process-identity.d.ts.map +0 -1
  191. package/dist/cli/lib/broker-process-identity.js +0 -304
  192. package/dist/cli/lib/broker-process-identity.js.map +0 -1
  193. package/dist/cli/lib/client-factory.d.ts +0 -44
  194. package/dist/cli/lib/client-factory.d.ts.map +0 -1
  195. package/dist/cli/lib/client-factory.js +0 -64
  196. package/dist/cli/lib/client-factory.js.map +0 -1
  197. package/dist/cli/lib/collect-with-retry.d.ts +0 -24
  198. package/dist/cli/lib/collect-with-retry.d.ts.map +0 -1
  199. package/dist/cli/lib/collect-with-retry.js +0 -33
  200. package/dist/cli/lib/collect-with-retry.js.map +0 -1
  201. package/dist/cli/lib/fleet-attach-target.d.ts +0 -18
  202. package/dist/cli/lib/fleet-attach-target.d.ts.map +0 -1
  203. package/dist/cli/lib/fleet-attach-target.js +0 -57
  204. package/dist/cli/lib/fleet-attach-target.js.map +0 -1
  205. package/dist/cli/lib/fleet-hint.d.ts +0 -49
  206. package/dist/cli/lib/fleet-hint.d.ts.map +0 -1
  207. package/dist/cli/lib/fleet-hint.js +0 -113
  208. package/dist/cli/lib/fleet-hint.js.map +0 -1
  209. package/dist/cli/lib/fleet-sidecar.d.ts +0 -43
  210. package/dist/cli/lib/fleet-sidecar.d.ts.map +0 -1
  211. package/dist/cli/lib/fleet-sidecar.js +0 -84
  212. package/dist/cli/lib/fleet-sidecar.js.map +0 -1
  213. package/dist/cli/lib/join-ticket.d.ts +0 -22
  214. package/dist/cli/lib/join-ticket.d.ts.map +0 -1
  215. package/dist/cli/lib/join-ticket.js +0 -96
  216. package/dist/cli/lib/join-ticket.js.map +0 -1
  217. package/dist/cli/lib/node-claim.d.ts +0 -468
  218. package/dist/cli/lib/node-claim.d.ts.map +0 -1
  219. package/dist/cli/lib/node-claim.js +0 -1349
  220. package/dist/cli/lib/node-claim.js.map +0 -1
  221. package/dist/cli/lib/node-definition-loader.d.ts +0 -19
  222. package/dist/cli/lib/node-definition-loader.d.ts.map +0 -1
  223. package/dist/cli/lib/node-definition-loader.js +0 -143
  224. package/dist/cli/lib/node-definition-loader.js.map +0 -1
  225. package/dist/cli/lib/node-provider-child.d.ts +0 -129
  226. package/dist/cli/lib/node-provider-child.d.ts.map +0 -1
  227. package/dist/cli/lib/node-provider-child.js +0 -755
  228. package/dist/cli/lib/node-provider-child.js.map +0 -1
  229. package/dist/cli/lib/predictive-echo-screen.d.ts +0 -48
  230. package/dist/cli/lib/predictive-echo-screen.d.ts.map +0 -1
  231. package/dist/cli/lib/predictive-echo-screen.js +0 -74
  232. package/dist/cli/lib/predictive-echo-screen.js.map +0 -1
  233. package/dist/cli/lib/project-broker-client.d.ts +0 -4
  234. package/dist/cli/lib/project-broker-client.d.ts.map +0 -1
  235. package/dist/cli/lib/project-broker-client.js +0 -12
  236. package/dist/cli/lib/project-broker-client.js.map +0 -1
  237. package/dist/cli/lib/reflex-capture.d.ts +0 -41
  238. package/dist/cli/lib/reflex-capture.d.ts.map +0 -1
  239. package/dist/cli/lib/reflex-capture.js +0 -128
  240. package/dist/cli/lib/reflex-capture.js.map +0 -1
  241. package/dist/cli/lib/workspace-env.d.ts +0 -8
  242. package/dist/cli/lib/workspace-env.d.ts.map +0 -1
  243. package/dist/cli/lib/workspace-env.js +0 -16
  244. package/dist/cli/lib/workspace-env.js.map +0 -1
@@ -1,9 +1,9 @@
1
- import { spawn } from 'node:child_process';
2
- import { createHash } from 'node:crypto';
1
+ import { randomUUID } from 'node:crypto';
3
2
  import fs from 'node:fs';
3
+ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { getProjectPaths } from '@agent-relay/config';
6
- import { formatBrokerNotFoundError, getBrokerBinaryPath } from '@agent-relay/harness-driver/broker-path';
6
+ import { describeError } from '../lib/describe-error.js';
7
7
  export class CleanupJournalError extends Error {
8
8
  code;
9
9
  constructor(code, message) {
@@ -107,149 +107,627 @@ function parseEntries(raw, file) {
107
107
  }
108
108
  return parsed;
109
109
  }
110
- async function beginJournalTransaction(lockFile, journalFile) {
111
- const binary = getBrokerBinaryPath();
112
- if (!binary) {
113
- throw new CleanupJournalError('io', formatBrokerNotFoundError());
114
- }
115
- const child = spawn(binary, [
116
- 'journal-lock',
117
- '--file',
118
- lockFile,
119
- '--journal-file',
120
- journalFile,
121
- '--timeout-ms',
122
- String(LOCK_TIMEOUT_MS),
123
- ], { stdio: ['pipe', 'pipe', 'pipe'] });
124
- const exit = new Promise((resolve) => {
125
- child.on('exit', (code) => resolve(code));
126
- child.on('error', () => resolve(null));
127
- });
128
- let exited = false;
129
- void exit.then(() => {
130
- exited = true;
131
- });
132
- // Exact framed handshake: buffer stdout until the first newline and demand
133
- // the line be precisely `locked` — no substring matching, and a hard
134
- // startup deadline that kills a wedged helper.
135
- await new Promise((resolve, reject) => {
136
- let settled = false;
137
- let buffer = '';
138
- const settle = (fn) => {
139
- if (settled)
140
- return;
141
- settled = true;
142
- clearTimeout(deadline);
143
- fn();
110
+ /** How often a holder refreshes its lease while a transaction is open. */
111
+ const LOCK_HEARTBEAT_MS = 5_000;
112
+ /**
113
+ * A lock held from ANOTHER host (a shared data directory) whose heartbeat is
114
+ * older than this is abandoned: its pid cannot be probed from here.
115
+ */
116
+ const LOCK_LEASE_MS = 60_000;
117
+ /**
118
+ * A holder on THIS host is broken as soon as its pid is gone. While its pid
119
+ * still answers it is broken only once its heartbeat is older than this: a live
120
+ * holder refreshes every few seconds, so a heartbeat this old means the pid was
121
+ * reused by an unrelated process after a crash. The window is far longer than
122
+ * any stalled fsync, so a live writer keeps exclusive ownership through its
123
+ * commit.
124
+ */
125
+ const LOCK_LOCAL_REUSE_MS = 15 * 60_000;
126
+ /** A lock directory with no readable owner (crash between mkdir and write). */
127
+ const LOCK_ORPHAN_MS = 30_000;
128
+ const LOCK_RETRY_MS = 25;
129
+ const LOCK_OWNER_FILE = 'owner.json';
130
+ function sleep(ms) {
131
+ return new Promise((resolve) => setTimeout(resolve, ms));
132
+ }
133
+ function errorCode(error) {
134
+ return error?.code;
135
+ }
136
+ function isLockContention(error) {
137
+ const code = errorCode(error);
138
+ if (code === 'EEXIST')
139
+ return true;
140
+ // Windows can report a racing directory create/remove as a sharing violation.
141
+ return process.platform === 'win32' && (code === 'EACCES' || code === 'EBUSY' || code === 'EPERM');
142
+ }
143
+ function readLockOwner(lockDir) {
144
+ const ownerFile = path.join(lockDir, LOCK_OWNER_FILE);
145
+ try {
146
+ const parsed = JSON.parse(fs.readFileSync(ownerFile, 'utf8'));
147
+ if (typeof parsed.pid !== 'number' ||
148
+ !Number.isInteger(parsed.pid) ||
149
+ parsed.pid <= 0 ||
150
+ !isNonEmptyString(parsed.host) ||
151
+ !isNonEmptyString(parsed.token)) {
152
+ return undefined;
153
+ }
154
+ return {
155
+ owner: { pid: parsed.pid, host: parsed.host, token: parsed.token },
156
+ heartbeatAt: fs.statSync(ownerFile).mtimeMs,
144
157
  };
145
- const deadline = setTimeout(() => {
146
- settle(() => {
147
- child.kill('SIGKILL');
148
- reject(new CleanupJournalError('io', `The journal-lock helper did not complete its handshake for ${lockFile} in time and was killed.`));
149
- });
150
- }, LOCK_TIMEOUT_MS + 2_000);
151
- child.stdout.on('data', (chunk) => {
152
- buffer += chunk.toString('utf8');
153
- const newline = buffer.indexOf('\n');
154
- if (newline < 0)
155
- return;
156
- const line = buffer.slice(0, newline);
157
- if (line === 'locked') {
158
- settle(resolve);
158
+ }
159
+ catch {
160
+ return undefined;
161
+ }
162
+ }
163
+ function processIsAlive(pid) {
164
+ try {
165
+ process.kill(pid, 0);
166
+ return true;
167
+ }
168
+ catch (error) {
169
+ // EPERM: the pid exists but belongs to someone else — still alive.
170
+ return error.code !== 'ESRCH';
171
+ }
172
+ }
173
+ /**
174
+ * The token of an abandoned lock (holder on this host exited or its pid was
175
+ * reused, a holder on another host let its lease expire, or an ownerless
176
+ * directory older than the orphan window), or undefined while the lock is
177
+ * live. An ownerless stale lock yields the empty token.
178
+ */
179
+ function staleLockToken(lockDir, now) {
180
+ const current = readLockOwner(lockDir);
181
+ if (current) {
182
+ const { owner, heartbeatAt } = current;
183
+ if (owner.host === os.hostname()) {
184
+ if (!processIsAlive(owner.pid))
185
+ return owner.token;
186
+ return now - heartbeatAt >= LOCK_LOCAL_REUSE_MS ? owner.token : undefined;
187
+ }
188
+ return now - heartbeatAt >= LOCK_LEASE_MS ? owner.token : undefined;
189
+ }
190
+ try {
191
+ return now - fs.statSync(lockDir).mtimeMs >= LOCK_ORPHAN_MS ? '' : undefined;
192
+ }
193
+ catch {
194
+ return undefined; // already gone; the next mkdir attempt decides
195
+ }
196
+ }
197
+ /** Whether this process still owns `lockDir` under `token`. */
198
+ function ownsLock(lockDir, token) {
199
+ return readLockOwner(lockDir)?.owner.token === token;
200
+ }
201
+ /**
202
+ * Create the lock directory `dir` carrying `owner`. False when another holder
203
+ * has it; throws on any other error. The owner record is created exclusively
204
+ * (`wx`): if a recoverer put a lock back onto our just-created, still empty
205
+ * directory, that lock's owner is already there and is never overwritten.
206
+ */
207
+ function createLockDir(dir, owner) {
208
+ try {
209
+ fs.mkdirSync(dir, { mode: 0o700 });
210
+ }
211
+ catch (err) {
212
+ if (isLockContention(err))
213
+ return false;
214
+ throw err;
215
+ }
216
+ const ownerFile = path.join(dir, LOCK_OWNER_FILE);
217
+ try {
218
+ fs.writeFileSync(ownerFile, JSON.stringify(owner), { mode: 0o600, flag: 'wx' });
219
+ }
220
+ catch (err) {
221
+ if (errorCode(err) === 'EEXIST')
222
+ return false;
223
+ // Remove only what is provably ours: our partial owner file, then the
224
+ // directory if it is empty. Never a recursive delete here.
225
+ try {
226
+ fs.rmSync(ownerFile, { force: true });
227
+ fs.rmdirSync(dir);
228
+ }
229
+ catch {
230
+ // Not empty (not ours) or already gone.
231
+ }
232
+ throw err;
233
+ }
234
+ return true;
235
+ }
236
+ /**
237
+ * Move the abandoned lock `dir` (judged stale under `staleToken`) aside and
238
+ * delete it. Callers hold the recovery lock, so no other recoverer can move or
239
+ * replace it concurrently; the moved directory is still judged again, because
240
+ * a holder judged stale may have been a slow live process that released and
241
+ * let a new writer in between the check and the rename. A directory that
242
+ * turns out not to be the stale one is put back, and if that fails it is left
243
+ * as a tombstone: its owner then finds its lock lost and refuses to commit,
244
+ * which is safe, whereas deleting it would not be.
245
+ */
246
+ function moveAsideIfStale(dir, staleToken) {
247
+ const tombstone = `${dir}.stale-${process.pid}-${randomUUID()}`;
248
+ try {
249
+ fs.renameSync(dir, tombstone);
250
+ }
251
+ catch (err) {
252
+ // Only a lock that actually disappeared earns an immediate retry. A
253
+ // transient Windows sharing violation backs off under the deadline; any
254
+ // other refusal (e.g. a parent directory that does not allow renames) is
255
+ // an I/O error, never a reason to spin.
256
+ if (errorCode(err) === 'ENOENT')
257
+ return 'retry';
258
+ if (isLockContention(err))
259
+ return 'wait';
260
+ throw new CleanupJournalError('io', `Could not recover the abandoned pending-cleanup journal lock at ${dir}: ${describeError(err)}`);
261
+ }
262
+ const moved = readLockOwner(tombstone);
263
+ if ((moved?.owner.token ?? '') === staleToken && staleLockToken(tombstone, Date.now()) === staleToken) {
264
+ fs.rmSync(tombstone, { recursive: true, force: true });
265
+ return 'retry';
266
+ }
267
+ try {
268
+ fs.renameSync(tombstone, dir);
269
+ }
270
+ catch {
271
+ // A newer lock already sits at `dir`; keep the tombstone (see above).
272
+ }
273
+ return 'wait';
274
+ }
275
+ /**
276
+ * Break an abandoned journal lock observed with `staleToken`.
277
+ *
278
+ * Recovery is serialized by a second lock directory, `<lockDir>.recover`, so
279
+ * an observation made before another recoverer broke the lock and a new writer
280
+ * took it can never move that writer's live lock: under the recovery lock the
281
+ * owner is read again and the lock is moved only if it is still the stale one.
282
+ * A recoverer holds the recovery lock for a few synchronous filesystem calls;
283
+ * one it left behind by crashing is judged by the same staleness rules (dead
284
+ * pid on this host, expired lease from another host, ownerless past the
285
+ * orphan window) and moved aside the same way.
286
+ */
287
+ function breakStaleLock(lockDir, staleToken) {
288
+ const recoverDir = `${lockDir}.recover`;
289
+ const recoverer = { pid: process.pid, host: os.hostname(), token: randomUUID() };
290
+ let held;
291
+ try {
292
+ held = createLockDir(recoverDir, recoverer);
293
+ }
294
+ catch (err) {
295
+ throw new CleanupJournalError('io', `Could not take the pending-cleanup journal recovery lock at ${recoverDir}: ${describeError(err)}`);
296
+ }
297
+ if (!held) {
298
+ const staleRecoverer = staleLockToken(recoverDir, Date.now());
299
+ if (staleRecoverer !== undefined)
300
+ moveAsideIfStale(recoverDir, staleRecoverer);
301
+ return 'wait';
302
+ }
303
+ try {
304
+ if (staleLockToken(lockDir, Date.now()) !== staleToken) {
305
+ // Released, broken by another recoverer, or re-taken since we looked.
306
+ return fs.existsSync(lockDir) ? 'wait' : 'retry';
307
+ }
308
+ return moveAsideIfStale(lockDir, staleToken);
309
+ }
310
+ finally {
311
+ if (ownsLock(recoverDir, recoverer.token)) {
312
+ fs.rmSync(recoverDir, { recursive: true, force: true });
313
+ }
314
+ }
315
+ }
316
+ class LockLostError extends Error {
317
+ }
318
+ /**
319
+ * Replace `journal` durably: exclusive 0600 temp file, fsync, atomic rename,
320
+ * then fsync the parent directory so the rename itself survives a crash.
321
+ */
322
+ function replaceJournalDurably(journal, payload, stillOwned) {
323
+ const tmp = `${journal}.tmp-${process.pid}-${randomUUID()}`;
324
+ let fd;
325
+ try {
326
+ fd = fs.openSync(tmp, 'wx', 0o600);
327
+ fs.writeFileSync(fd, payload, 'utf8');
328
+ fs.fsyncSync(fd);
329
+ fs.closeSync(fd);
330
+ fd = undefined;
331
+ // Re-checked after the (possibly slow) fsync, immediately before the one
332
+ // step that changes the journal.
333
+ if (!stillOwned())
334
+ throw new LockLostError();
335
+ fs.renameSync(tmp, journal);
336
+ }
337
+ catch (err) {
338
+ if (fd !== undefined) {
339
+ try {
340
+ fs.closeSync(fd);
159
341
  }
160
- else {
161
- settle(() => {
162
- child.kill('SIGKILL');
163
- reject(new CleanupJournalError('io', `The journal-lock helper sent an unexpected handshake for ${lockFile}.`));
164
- });
342
+ catch {
343
+ // already failing
165
344
  }
166
- });
167
- child.on('error', (err) => settle(() => reject(new CleanupJournalError('io', `Could not spawn the journal-lock helper (${binary}): ${err.message}`))));
168
- void exit.then((code) => {
169
- settle(() => {
170
- if (code === 4) {
171
- reject(new CleanupJournalError('locked', `Timed out waiting for the pending-cleanup journal lock at ${lockFile}: another agent-relay process holds it. The kernel releases it automatically when that process exits; retry afterwards.`));
172
- }
173
- else if (code === 3) {
174
- reject(new CleanupJournalError('locked', `The pending-cleanup journal lock at ${lockFile} contains an unrecognized sentinel from an older format. Nothing was swept or overwritten; inspect and remove the file to continue.`));
175
- }
176
- else if (code === 2) {
177
- // clap usage error: this broker binary predates the journal-lock
178
- // helper (version skew), or the invocation is malformed.
179
- reject(new CleanupJournalError('io', `The resolved agent-relay-broker binary (${binary}) does not support the journal-lock helper; upgrade the broker (or set AGENT_RELAY_BIN to a current build) and retry.`));
180
- }
181
- else {
182
- reject(new CleanupJournalError('io', `The journal-lock helper exited unexpectedly (code ${code ?? 'unknown'}) before acquiring ${lockFile}.`));
183
- }
184
- });
185
- });
186
- });
187
- const finish = async (payload, failure) => {
188
- const committing = payload !== undefined;
189
- if (exited) {
190
- if (committing) {
191
- // The lock (and with it transactional isolation) is already gone; the
192
- // journal is untouched — surface instead of committing blind.
193
- throw new CleanupJournalError('io', failure);
345
+ }
346
+ fs.rmSync(tmp, { force: true });
347
+ throw err;
348
+ }
349
+ // The journal is in place from here on: a failed directory fsync weakens
350
+ // crash durability of the rename but must not report the committed update as
351
+ // failed (callers treat a failure as "nothing changed" and would redo it).
352
+ // Windows cannot open or fsync a directory handle this way at all.
353
+ let dirFd;
354
+ try {
355
+ dirFd = fs.openSync(path.dirname(journal), 'r');
356
+ fs.fsyncSync(dirFd);
357
+ }
358
+ catch {
359
+ // Best-effort, see above.
360
+ }
361
+ finally {
362
+ if (dirFd !== undefined) {
363
+ try {
364
+ fs.closeSync(dirFd);
365
+ }
366
+ catch {
367
+ // Best-effort.
194
368
  }
195
- return; // abort: nothing left to release
196
369
  }
197
- // The helper can die between the `exited` check and (or during) the
198
- // stdin write: swallow the stream error (EPIPE would otherwise be an
199
- // unhandled 'error' event) and never hang on an end-callback that will
200
- // no longer fire — the authoritative verdict is the exit code below.
201
- await new Promise((resolve) => {
202
- let settled = false;
203
- const settle = () => {
204
- if (settled)
205
- return;
206
- settled = true;
207
- resolve();
208
- };
209
- const stdin = child.stdin;
210
- stdin.once('error', settle);
211
- void exit.then(settle);
370
+ }
371
+ }
372
+ /*
373
+ * Legacy lock (CLI releases up to 17.2.1).
374
+ *
375
+ * Those releases serialized the journal through the retired broker's hidden
376
+ * `journal-lock` helper: it opens `pending-cleanups.json.lock` (created 0600,
377
+ * a stable inode that is never renamed or unlinked) and takes an exclusive
378
+ * kernel lock on it with Rust's `File::try_lock`, i.e. flock(2) with
379
+ * LOCK_EX|LOCK_NB on Linux and macOS and LockFileEx over the whole file on
380
+ * Windows, retrying every 100 ms for 5 s (then exit 4, "locked"). Holding the
381
+ * lock it reads the file: empty or a strict prefix of the v2 marker is
382
+ * (re)stamped with the marker, anything else makes it exit 3 ("sentinel",
383
+ * reported as "locked") without touching the journal. Only then does it
384
+ * replace the journal, and the kernel drops the lock when it exits.
385
+ *
386
+ * Node and Bun have no flock(2)/LockFileEx API and this module must not load a
387
+ * native addon (the Bun standalone cannot) or spawn a helper (the standalone
388
+ * install ships none), so a newer transaction excludes older writers as
389
+ * strongly as each platform allows, for the whole transaction, after taking
390
+ * the lock directory:
391
+ *
392
+ * - macOS and FreeBSD: open(2) with O_EXLOCK|O_NONBLOCK takes the very same
393
+ * flock(2) lock, so this is the legacy lock itself: older helpers wait for
394
+ * it (and time out as "locked"), and the kernel releases it if we die.
395
+ * - Windows: libuv's UV_FS_O_EXLOCK opens the file with share mode 0. An older
396
+ * helper cannot open it while we hold it (it exits with an error, never
397
+ * touching the journal), and our open fails while a helper has it open,
398
+ * which covers the whole time it holds LockFileEx.
399
+ * - Both are verified once per process on a scratch file next to the lock
400
+ * (never by reopening the lock file): a second open asking for the same
401
+ * exclusivity must be refused. If the runtime ignores the flag, the marker
402
+ * exclusion below is used instead.
403
+ * - Linux (and any runtime where the above is unavailable): the file is
404
+ * stamped with a token-bearing sentinel that is not a prefix of the v2
405
+ * marker, so any older helper that acquires the flock afterwards reads it
406
+ * and exits 3 without touching the journal. A helper that took the flock
407
+ * BEFORE the stamp is still holding it when we look, so after stamping we
408
+ * read /proc/locks and wait while any FLOCK lock is held on the file's
409
+ * inode (a lock on an unrelated file with the same inode number elsewhere
410
+ * only makes us wait longer). Order matters: stamp, then look; a helper
411
+ * that overwrote the stamp while healing it was holding the lock and is
412
+ * seen, and the stamp is rewritten on the next round. On release the v2
413
+ * marker is written back, only while the file still holds OUR sentinel.
414
+ * Limits: a helper in another pid namespace is hidden from /proc/locks, and
415
+ * without /proc only newly arriving helpers are excluded. If we crash while
416
+ * holding, older CLIs keep failing closed ("locked") until the next newer
417
+ * transaction restores the marker.
418
+ * - A file holding anything else (neither empty, a marker prefix nor a
419
+ * sentinel) is left exactly as it is: older helpers already refuse to run on
420
+ * it.
421
+ */
422
+ const LEGACY_LOCK_MARKER = 'agent-relay-cleanup-lock v2\n';
423
+ const LEGACY_SENTINEL_PREFIX = '{"agent-relay-cleanup-lock":"held by a newer agent-relay CLI","token":"';
424
+ /** O_EXLOCK on macOS and FreeBSD (not exported by fs.constants). */
425
+ const O_EXLOCK_BSD = 0x20;
426
+ /** libuv's UV_FS_O_EXLOCK on Windows: open with share mode 0. */
427
+ const UV_FS_O_EXLOCK_WIN = 0x10000000;
428
+ function legacyLockTimeout(lockFile) {
429
+ return new CleanupJournalError('locked', `Timed out waiting for the pending-cleanup journal lock at ${lockFile}: an older agent-relay CLI (17.2.1 or earlier) holds it. It is released when that process finishes; retry afterwards.`);
430
+ }
431
+ function isWindowsLockViolation(error) {
432
+ const code = errorCode(error);
433
+ return process.platform === 'win32' && (code === 'EBUSY' || code === 'EACCES' || code === 'EPERM');
434
+ }
435
+ /** macOS/FreeBSD/Windows: how to open a file exclusively on this platform. */
436
+ function exclusiveOpen() {
437
+ const windows = process.platform === 'win32';
438
+ return {
439
+ flags: windows ? UV_FS_O_EXLOCK_WIN : O_EXLOCK_BSD | fs.constants.O_NONBLOCK,
440
+ contended(err) {
441
+ const code = errorCode(err);
442
+ return windows ? isWindowsLockViolation(err) : code === 'EAGAIN' || code === 'EWOULDBLOCK';
443
+ },
444
+ };
445
+ }
446
+ /** Open `file` once, returning `busy` if another descriptor holds it exclusively. */
447
+ function openUnlessContended(file, flags, exclusive) {
448
+ try {
449
+ return fs.openSync(file, flags, 0o600);
450
+ }
451
+ catch (err) {
452
+ if (exclusive.contended(err))
453
+ return 'busy';
454
+ throw err;
455
+ }
456
+ }
457
+ /** Whether this runtime honours the exclusive-open flag; probed once per process. */
458
+ let exclusiveOpenHonoured;
459
+ /**
460
+ * Probe whether the runtime honours the exclusive-open flag, on a scratch file
461
+ * of our own (random name, created with O_EXCL next to the lock file) rather
462
+ * than the lock file itself, so the lock file is opened exactly once: hold the
463
+ * scratch file exclusively, then a second open asking for the same exclusivity
464
+ * (Windows: any open, as share mode 0 refuses them all) must be refused. The
465
+ * answer is a property of the runtime, so it is kept for the process.
466
+ */
467
+ function exclusiveOpenSupported(dir, exclusive) {
468
+ if (exclusiveOpenHonoured !== undefined)
469
+ return exclusiveOpenHonoured;
470
+ const { O_RDONLY, O_RDWR, O_CREAT, O_EXCL } = fs.constants;
471
+ const scratch = path.join(dir, `.legacy-lock-probe-${process.pid}-${randomUUID()}`);
472
+ const held = openUnlessContended(scratch, O_RDWR | O_CREAT | O_EXCL | exclusive.flags, exclusive);
473
+ if (held === 'busy') {
474
+ // Nobody else can know a fresh random name; treat it as unsupported.
475
+ return false;
476
+ }
477
+ try {
478
+ const probe = openUnlessContended(scratch, process.platform === 'win32' ? O_RDONLY : O_RDONLY | exclusive.flags, exclusive);
479
+ if (probe !== 'busy')
480
+ fs.closeSync(probe);
481
+ exclusiveOpenHonoured = probe === 'busy';
482
+ return exclusiveOpenHonoured;
483
+ }
484
+ finally {
485
+ try {
486
+ fs.closeSync(held);
487
+ }
488
+ catch {
489
+ // Best-effort.
490
+ }
491
+ try {
492
+ fs.rmSync(scratch, { force: true });
493
+ }
494
+ catch {
495
+ // Best-effort: a leftover probe file is harmless.
496
+ }
497
+ }
498
+ }
499
+ /**
500
+ * macOS/FreeBSD/Windows: hold the legacy lock with an exclusive open. Returns
501
+ * the held descriptor, `busy` while an older helper holds it, or `unsupported`
502
+ * if the runtime ignores the flag. The lock file itself is opened only once.
503
+ */
504
+ function tryKernelLegacyLock(lockFile) {
505
+ const exclusive = exclusiveOpen();
506
+ if (!exclusiveOpenSupported(path.dirname(lockFile), exclusive))
507
+ return 'unsupported';
508
+ const { O_RDWR, O_CREAT } = fs.constants;
509
+ return openUnlessContended(lockFile, O_RDWR | O_CREAT | exclusive.flags, exclusive);
510
+ }
511
+ /** Linux: whether any process holds a flock(2) lock on inode `ino`; undefined
512
+ * when /proc/locks cannot be read. */
513
+ function legacyFlockHeld(ino) {
514
+ if (process.platform !== 'linux')
515
+ return undefined;
516
+ let table;
517
+ try {
518
+ table = fs.readFileSync('/proc/locks', 'utf8');
519
+ }
520
+ catch {
521
+ return undefined;
522
+ }
523
+ for (const line of table.split('\n')) {
524
+ // `<n>: FLOCK ADVISORY WRITE <pid> <major>:<minor>:<inode> <start> <end>`.
525
+ // Blocked waiters read `<n>: -> FLOCK ...` and hold nothing.
526
+ const fields = line.trim().split(/\s+/);
527
+ if (fields[1] !== 'FLOCK')
528
+ continue;
529
+ const id = fields[5] ?? '';
530
+ if (id.slice(id.lastIndexOf(':') + 1) === ino)
531
+ return true;
532
+ }
533
+ return false;
534
+ }
535
+ function readWholeFile(fd) {
536
+ const size = fs.fstatSync(fd).size;
537
+ const buffer = Buffer.alloc(size);
538
+ let offset = 0;
539
+ while (offset < size) {
540
+ const read = fs.readSync(fd, buffer, offset, size - offset, offset);
541
+ if (read === 0)
542
+ break;
543
+ offset += read;
544
+ }
545
+ return buffer.subarray(0, offset).toString('utf8');
546
+ }
547
+ async function stampLegacyLock(lockFile, token, deadline) {
548
+ const sentinel = `${LEGACY_SENTINEL_PREFIX}${token}"}\n`;
549
+ const fd = fs.openSync(lockFile, fs.constants.O_RDWR | fs.constants.O_CREAT, 0o600);
550
+ let stamped = false;
551
+ let closed = false;
552
+ const release = () => {
553
+ if (closed)
554
+ return;
555
+ closed = true;
556
+ try {
557
+ if (stamped && readWholeFile(fd) === sentinel) {
558
+ // Marker first, then trim: the file is never empty in between.
559
+ fs.writeSync(fd, LEGACY_LOCK_MARKER, 0);
560
+ fs.ftruncateSync(fd, Buffer.byteLength(LEGACY_LOCK_MARKER));
561
+ fs.fsyncSync(fd);
562
+ }
563
+ }
564
+ catch {
565
+ // Best-effort: older CLIs then fail closed until the next newer run.
566
+ }
567
+ try {
568
+ fs.closeSync(fd);
569
+ }
570
+ catch {
571
+ // Best-effort.
572
+ }
573
+ };
574
+ try {
575
+ const ino = fs.fstatSync(fd, { bigint: true }).ino.toString();
576
+ for (;;) {
577
+ let contended = false;
212
578
  try {
213
- if (committing) {
214
- stdin.end(payload, settle);
215
- }
216
- else {
217
- stdin.end(settle);
579
+ const content = readWholeFile(fd);
580
+ if (LEGACY_LOCK_MARKER.startsWith(content) || content.startsWith(LEGACY_SENTINEL_PREFIX)) {
581
+ // In place, never by rename: older helpers lock this inode.
582
+ fs.writeSync(fd, sentinel, 0);
583
+ fs.ftruncateSync(fd, Buffer.byteLength(sentinel));
584
+ stamped = true;
218
585
  }
219
586
  }
220
- catch {
221
- settle();
587
+ catch (err) {
588
+ // Windows enforces LockFileEx against our read/write: a holder.
589
+ if (!isWindowsLockViolation(err))
590
+ throw err;
591
+ contended = true;
592
+ }
593
+ if (!contended)
594
+ contended = legacyFlockHeld(ino) === true;
595
+ if (!contended)
596
+ return { release };
597
+ if (Date.now() >= deadline)
598
+ throw legacyLockTimeout(lockFile);
599
+ await sleep(LOCK_RETRY_MS);
600
+ }
601
+ }
602
+ catch (err) {
603
+ release();
604
+ throw err;
605
+ }
606
+ }
607
+ /** Exclude older CLI writers from the journal; see the comment above. */
608
+ async function acquireLegacyLock(lockFile, token) {
609
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
610
+ try {
611
+ if (process.platform === 'darwin' || process.platform === 'freebsd' || process.platform === 'win32') {
612
+ for (;;) {
613
+ const held = tryKernelLegacyLock(lockFile);
614
+ if (typeof held === 'number') {
615
+ let closed = false;
616
+ return {
617
+ release() {
618
+ if (closed)
619
+ return;
620
+ closed = true;
621
+ try {
622
+ fs.closeSync(held);
623
+ }
624
+ catch {
625
+ // Best-effort.
626
+ }
627
+ },
628
+ };
629
+ }
630
+ if (held === 'unsupported')
631
+ break;
632
+ if (Date.now() >= deadline)
633
+ throw legacyLockTimeout(lockFile);
634
+ await sleep(LOCK_RETRY_MS);
222
635
  }
223
- });
224
- const code = await exit;
225
- if (committing && code !== 0) {
226
- throw new CleanupJournalError('io', failure);
636
+ }
637
+ return await stampLegacyLock(lockFile, token, deadline);
638
+ }
639
+ catch (err) {
640
+ if (err instanceof CleanupJournalError)
641
+ throw err;
642
+ throw new CleanupJournalError('io', `Could not take the legacy pending-cleanup journal lock at ${lockFile}: ${describeError(err)}`);
643
+ }
644
+ }
645
+ async function beginJournalTransaction(lockDir, legacyLockFile, journalFile) {
646
+ const token = randomUUID();
647
+ const owner = { pid: process.pid, host: os.hostname(), token };
648
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
649
+ for (;;) {
650
+ let acquired;
651
+ try {
652
+ acquired = createLockDir(lockDir, owner);
653
+ }
654
+ catch (err) {
655
+ throw new CleanupJournalError('io', `Could not take the pending-cleanup journal lock at ${lockDir}: ${describeError(err)}`);
656
+ }
657
+ if (acquired)
658
+ break;
659
+ const staleToken = staleLockToken(lockDir, Date.now());
660
+ // Retry at once only after an abandoned lock was actually removed (or
661
+ // vanished). Everything else — a live lock, a lock put back, a busy
662
+ // recovery lock — falls through to the deadline and back-off, so a lock
663
+ // that keeps being judged stale and then live cannot spin past the
664
+ // timeout. Recovery I/O errors propagate.
665
+ if (staleToken !== undefined && breakStaleLock(lockDir, staleToken) === 'retry') {
666
+ continue;
667
+ }
668
+ if (Date.now() >= deadline) {
669
+ throw new CleanupJournalError('locked', `Timed out waiting for the pending-cleanup journal lock at ${lockDir}: another agent-relay process holds it. It is released when that process finishes (or broken automatically once that process has exited); retry afterwards. If no agent-relay process is running, remove ${lockDir} and retry.`);
670
+ }
671
+ await sleep(LOCK_RETRY_MS);
672
+ }
673
+ const ownerFile = path.join(lockDir, LOCK_OWNER_FILE);
674
+ const heartbeat = setInterval(() => {
675
+ // Never refresh a lock this transaction no longer owns: that would keep a
676
+ // successor's abandoned lock looking alive.
677
+ if (!ownsLock(lockDir, token)) {
678
+ clearInterval(heartbeat);
679
+ return;
680
+ }
681
+ try {
682
+ const now = new Date();
683
+ fs.utimesSync(ownerFile, now, now);
684
+ }
685
+ catch {
686
+ // A lost lock is detected at commit; the heartbeat itself is best-effort.
687
+ }
688
+ }, LOCK_HEARTBEAT_MS);
689
+ heartbeat.unref?.();
690
+ let legacy;
691
+ let released = false;
692
+ const release = () => {
693
+ if (released)
694
+ return;
695
+ released = true;
696
+ clearInterval(heartbeat);
697
+ legacy?.release();
698
+ if (ownsLock(lockDir, token)) {
699
+ fs.rmSync(lockDir, { recursive: true, force: true });
227
700
  }
228
701
  };
702
+ try {
703
+ legacy = await acquireLegacyLock(legacyLockFile, token);
704
+ }
705
+ catch (err) {
706
+ release();
707
+ throw err;
708
+ }
229
709
  return {
230
710
  async abort() {
231
- if (exited)
232
- return;
233
- await finish(undefined, '');
711
+ release();
234
712
  },
235
713
  async commit(payload) {
236
- // Framed envelope: magic/version + declared byte length + SHA-256 of
237
- // the payload. The helper commits ONLY after both validate exactly, so
238
- // a parent dying mid-write (partial bytes + clean EOF) can never
239
- // replace good journal contents with a truncated payload. Frame
240
- // construction failures release the lock (abort) instead of leaving
241
- // the helper's stdin open.
242
- let framed;
243
714
  try {
244
- const body = Buffer.from(payload, 'utf8');
245
- const digest = createHash('sha256').update(body).digest('hex');
246
- framed = Buffer.concat([Buffer.from(`ARJL1\n${body.byteLength}\n${digest}\n`, 'utf8'), body]);
715
+ if (released || !ownsLock(lockDir, token)) {
716
+ throw new CleanupJournalError('io', `The pending-cleanup journal lock at ${lockDir} was lost before ${journalFile} could be committed; the journal was left unmodified.`);
717
+ }
718
+ try {
719
+ replaceJournalDurably(journalFile, payload, () => ownsLock(lockDir, token));
720
+ }
721
+ catch (err) {
722
+ if (err instanceof LockLostError) {
723
+ throw new CleanupJournalError('io', `The pending-cleanup journal lock at ${lockDir} was lost before ${journalFile} could be committed; the journal was left unmodified.`);
724
+ }
725
+ throw new CleanupJournalError('io', `Could not commit the pending-cleanup journal at ${journalFile}: ${describeError(err)}`);
726
+ }
247
727
  }
248
- catch (err) {
249
- await finish(undefined, '');
250
- throw new CleanupJournalError('io', `Could not frame the pending-cleanup journal payload: ${err instanceof Error ? err.message : String(err)}`);
728
+ finally {
729
+ release();
251
730
  }
252
- await finish(framed, `The journal-lock helper was lost before the pending-cleanup journal at ${journalFile} could be committed; the journal was left unmodified.`);
253
731
  },
254
732
  };
255
733
  }
@@ -265,7 +743,7 @@ export function fileCleanupJournal(dataDirOverride) {
265
743
  catch (err) {
266
744
  if (err.code === 'ENOENT')
267
745
  return [];
268
- throw new CleanupJournalError('io', `Could not read the pending-cleanup journal at ${file}: ${err instanceof Error ? err.message : String(err)}`);
746
+ throw new CleanupJournalError('io', `Could not read the pending-cleanup journal at ${file}: ${describeError(err)}`);
269
747
  }
270
748
  return parseEntries(raw, file);
271
749
  };
@@ -276,11 +754,10 @@ export function fileCleanupJournal(dataDirOverride) {
276
754
  async update(mutate) {
277
755
  const file = journalFile();
278
756
  fs.mkdirSync(path.dirname(file), { recursive: true });
279
- const transaction = await beginJournalTransaction(`${file}.lock`, file);
757
+ const transaction = await beginJournalTransaction(`${file}.lock.d`, `${file}.lock`, file);
280
758
  // EVERYTHING that can throw before the commit — the read, the mutator,
281
759
  // and the serialization itself — runs inside the abort-protected block,
282
- // or a failure would leave the helper's stdin open and the lock held
283
- // until this process exits.
760
+ // or a failure would leave the lock held until this process exits.
284
761
  let payload;
285
762
  try {
286
763
  const next = await mutate(read(file));
@@ -290,8 +767,8 @@ export function fileCleanupJournal(dataDirOverride) {
290
767
  await transaction.abort();
291
768
  throw err;
292
769
  }
293
- // The helper performs the durable replacement (temp + fsync + atomic
294
- // rename + dir fsync) while it still holds the kernel lock.
770
+ // The durable replacement (temp + fsync + atomic rename + dir fsync)
771
+ // runs while this transaction still holds the lock.
295
772
  await transaction.commit(payload);
296
773
  },
297
774
  };