@1agh/maude 2.0.3 → 2.0.6

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 (242) hide show
  1. package/README.md +6 -5
  2. package/apps/hub/src/project-transactions/kernel.mjs +10 -1
  3. package/apps/studio/access/filters.ts +12 -5
  4. package/apps/studio/access/known-canvases.ts +24 -1
  5. package/apps/studio/access/refused-inputs.ts +89 -0
  6. package/apps/studio/access/request.ts +0 -1
  7. package/apps/studio/acp/adapter-stderr.ts +43 -13
  8. package/apps/studio/acp/background-tasks.ts +155 -0
  9. package/apps/studio/acp/bridge.ts +44 -5
  10. package/apps/studio/acp/connected-fact.ts +15 -4
  11. package/apps/studio/acp/index.ts +14 -5
  12. package/apps/studio/actions/agents.ts +10 -0
  13. package/apps/studio/actions/defs/app.ts +12 -0
  14. package/apps/studio/actions/defs/view.ts +12 -0
  15. package/apps/studio/actions.manifest.json +25 -1
  16. package/apps/studio/actions.parity.json +13 -1
  17. package/apps/studio/annotations/ui/element-node.tsx +139 -54
  18. package/apps/studio/annotations/ui/lod.tsx +1 -1
  19. package/apps/studio/annotations/ui/text-style.ts +1 -1
  20. package/apps/studio/annotations-layer.tsx +0 -12
  21. package/apps/studio/api.ts +73 -24
  22. package/apps/studio/artboard-live-gate.tsx +267 -0
  23. package/apps/studio/artboard-live.ts +336 -0
  24. package/apps/studio/artboard-webgl.ts +668 -0
  25. package/apps/studio/bin/_agent-browser-bin.mjs +8 -0
  26. package/apps/studio/bin/_agent-browser-safe.mjs +2 -1
  27. package/apps/studio/bin/_canvas-reasons.mjs +34 -0
  28. package/apps/studio/bin/_ds-check-live.mjs +37 -0
  29. package/apps/studio/bin/_ds-check.mjs +4 -1
  30. package/apps/studio/bin/_ds-prove-judge.mjs +167 -0
  31. package/apps/studio/bin/_ds-prove-playwright.mjs +183 -105
  32. package/apps/studio/bin/_import-asset.mjs +2 -1
  33. package/apps/studio/bin/_perf-probe.mjs +2 -1
  34. package/apps/studio/bin/_png-playwright.mjs +10 -1
  35. package/apps/studio/bin/_pw-launch.mjs +14 -0
  36. package/apps/studio/bin/_studio-verb.mjs +24 -3
  37. package/apps/studio/bin/_thumb-blank.mjs +70 -0
  38. package/apps/studio/bin/_thumb-cover.mjs +35 -0
  39. package/apps/studio/bin/_thumbs-playwright.mjs +93 -13
  40. package/apps/studio/bin/ds-check.sh +5 -1
  41. package/apps/studio/bin/perf.sh +11 -1
  42. package/apps/studio/bin/server-up.sh +7 -2
  43. package/apps/studio/bin/smoke.sh +19 -0
  44. package/apps/studio/boot-progress.ts +31 -0
  45. package/apps/studio/canvas-build-sandbox.ts +275 -42
  46. package/apps/studio/canvas-build-worker.ts +10 -0
  47. package/apps/studio/canvas-create.ts +24 -0
  48. package/apps/studio/canvas-lib.tsx +131 -12
  49. package/apps/studio/canvas-module-cache.ts +93 -0
  50. package/apps/studio/canvas-source/errors.ts +39 -0
  51. package/apps/studio/canvas-source/waiting.ts +290 -0
  52. package/apps/studio/client/actions/shell-key-handlers.js +5 -0
  53. package/apps/studio/client/app.jsx +19 -9
  54. package/apps/studio/client/canvas-url.js +13 -0
  55. package/apps/studio/client/github.js +23 -3
  56. package/apps/studio/client/home/HomeAccounts.jsx +262 -0
  57. package/apps/studio/client/home/Shelves.jsx +4 -3
  58. package/apps/studio/client/home/home-accounts-model.js +121 -0
  59. package/apps/studio/client/home/home-api.js +36 -19
  60. package/apps/studio/client/home/home-app.jsx +141 -40
  61. package/apps/studio/client/home/home-model.js +172 -6
  62. package/apps/studio/client/home/home.css +169 -5
  63. package/apps/studio/client/home/shell-mode.js +8 -1
  64. package/apps/studio/client/hooks/use-git-actions.jsx +2 -1
  65. package/apps/studio/client/hooks/use-project-data.jsx +2 -0
  66. package/apps/studio/client/hooks/use-shell-core.jsx +3 -0
  67. package/apps/studio/client/hooks/use-tabs.jsx +64 -35
  68. package/apps/studio/client/index-loader.ts +23 -3
  69. package/apps/studio/client/panels/ChatPanel.jsx +49 -57
  70. package/apps/studio/client/panels/CreateProject.jsx +19 -5
  71. package/apps/studio/client/panels/DiffView.jsx +314 -248
  72. package/apps/studio/client/panels/TeamProjects.jsx +119 -69
  73. package/apps/studio/client/panels/acp-runtime.js +25 -0
  74. package/apps/studio/client/panels/caps-cache.js +46 -0
  75. package/apps/studio/client/panels/chat-finish.js +66 -0
  76. package/apps/studio/client/shell/frame-cap.js +53 -0
  77. package/apps/studio/client/shell/viewport.jsx +45 -8
  78. package/apps/studio/client/styles/_index.css +2 -0
  79. package/apps/studio/client/tree/tree.jsx +48 -21
  80. package/apps/studio/client/v2/access/access-client.js +2 -0
  81. package/apps/studio/client/v2/access/access-host.jsx +12 -1
  82. package/apps/studio/client/v2/access/trashed-banner.jsx +6 -3
  83. package/apps/studio/client/v2/ai/Advanced.jsx +12 -0
  84. package/apps/studio/client/v2/ai/BackgroundStrip.jsx +120 -0
  85. package/apps/studio/client/v2/ai/Composer.jsx +27 -10
  86. package/apps/studio/client/v2/ai/StoppedDivider.jsx +2 -1
  87. package/apps/studio/client/v2/ai/ai-run.css +87 -3
  88. package/apps/studio/client/v2/ai/background-model.js +113 -0
  89. package/apps/studio/client/v2/ai/needs-you-store.js +2 -1
  90. package/apps/studio/client/v2/ai/run-api.js +7 -3
  91. package/apps/studio/client/v2/ai/runs-store.js +2 -1
  92. package/apps/studio/client/v2/annotations/vote-store.js +11 -5
  93. package/apps/studio/client/v2/assets/asset-state-lane.js +6 -3
  94. package/apps/studio/client/v2/assets/assets-bus.js +10 -8
  95. package/apps/studio/client/v2/assets/browse-view.jsx +2 -0
  96. package/apps/studio/client/v2/assets/ds-library-view.jsx +47 -0
  97. package/apps/studio/client/v2/assets/spotlight-model.js +75 -0
  98. package/apps/studio/client/v2/assets/spotlight.css +153 -0
  99. package/apps/studio/client/v2/assets/spotlight.jsx +199 -0
  100. package/apps/studio/client/v2/assets/tile-menu.jsx +3 -1
  101. package/apps/studio/client/v2/assets/tile.jsx +3 -0
  102. package/apps/studio/client/v2/assets/use-assets.js +2 -1
  103. package/apps/studio/client/v2/canvases/canvases-panel.jsx +13 -2
  104. package/apps/studio/client/v2/canvases/covers.js +11 -5
  105. package/apps/studio/client/v2/canvases/folder-ask.js +139 -0
  106. package/apps/studio/client/v2/canvases/folder-dialogs.jsx +150 -0
  107. package/apps/studio/client/v2/canvases/trash-canvas.js +10 -2
  108. package/apps/studio/client/v2/canvases/trash-queue.js +152 -0
  109. package/apps/studio/client/v2/canvases/use-canvas-index.js +42 -18
  110. package/apps/studio/client/v2/canvases/use-pins.js +2 -1
  111. package/apps/studio/client/v2/code/canvas-error-card.jsx +70 -5
  112. package/apps/studio/client/v2/code/canvas-imports-card.jsx +15 -14
  113. package/apps/studio/client/v2/code/canvas-imports-words.js +44 -0
  114. package/apps/studio/client/v2/code/canvas-waiting-card.jsx +128 -0
  115. package/apps/studio/client/v2/code/canvas-waiting.js +164 -0
  116. package/apps/studio/client/v2/code/code-bus.js +5 -0
  117. package/apps/studio/client/v2/code/code.css +67 -0
  118. package/apps/studio/client/v2/code/use-canvas-source.js +19 -4
  119. package/apps/studio/client/v2/create/NameDialog.jsx +4 -2
  120. package/apps/studio/client/v2/create/name-dialog.css +10 -0
  121. package/apps/studio/client/v2/ds/advanced-host.jsx +11 -23
  122. package/apps/studio/client/v2/ds/ds-refresh.js +161 -0
  123. package/apps/studio/client/v2/ds/library-host.jsx +45 -45
  124. package/apps/studio/client/v2/ds/make-host.jsx +13 -12
  125. package/apps/studio/client/v2/ds/off-system-host.jsx +18 -16
  126. package/apps/studio/client/v2/ds/review-host.jsx +7 -1
  127. package/apps/studio/client/v2/ds/truth-host.jsx +15 -14
  128. package/apps/studio/client/v2/ds/upgrade-host.jsx +26 -10
  129. package/apps/studio/client/v2/empty/arriving.jsx +29 -12
  130. package/apps/studio/client/v2/empty/empty-host.jsx +8 -2
  131. package/apps/studio/client/v2/empty/not-local.jsx +31 -1
  132. package/apps/studio/client/v2/empty/use-empty-canvas.js +10 -1
  133. package/apps/studio/client/v2/export/last-finished.js +2 -1
  134. package/apps/studio/client/v2/history/branch-actions.js +13 -9
  135. package/apps/studio/client/v2/history/git-advanced.jsx +8 -1
  136. package/apps/studio/client/v2/history/git-model.js +21 -5
  137. package/apps/studio/client/v2/history/git-parts.jsx +76 -43
  138. package/apps/studio/client/v2/history/history.css +6 -0
  139. package/apps/studio/client/v2/left-panel/assets-panel.jsx +87 -10
  140. package/apps/studio/client/v2/left-panel/use-trash.js +2 -1
  141. package/apps/studio/client/v2/onboarding/AdvancedSheets.jsx +100 -33
  142. package/apps/studio/client/v2/onboarding/HubSheet.jsx +51 -83
  143. package/apps/studio/client/v2/onboarding/onboarding-model.js +10 -6
  144. package/apps/studio/client/v2/presence/faces.jsx +42 -14
  145. package/apps/studio/client/v2/present/order-notes-artboards.js +2 -1
  146. package/apps/studio/client/v2/search/search-recent.js +3 -1
  147. package/apps/studio/client/v2/search/search-remote.js +6 -4
  148. package/apps/studio/client/v2/settings/connections-model.js +1 -1
  149. package/apps/studio/client/v2/shell/account-card.jsx +10 -4
  150. package/apps/studio/client/v2/shell/canvas-crash-guard.js +137 -0
  151. package/apps/studio/client/v2/shell/github-signin-host.jsx +42 -0
  152. package/apps/studio/client/v2/shell/menu-runner.js +12 -0
  153. package/apps/studio/client/v2/shell/occlusion-insets.js +14 -2
  154. package/apps/studio/client/v2/shell/project-account-card.jsx +203 -0
  155. package/apps/studio/client/v2/shell/project-account-model.js +182 -0
  156. package/apps/studio/client/v2/shell/recovery-store.js +2 -1
  157. package/apps/studio/client/v2/shell/served-routes.js +120 -0
  158. package/apps/studio/client/v2/shell/share-cluster-host.jsx +139 -11
  159. package/apps/studio/client/v2/shell/share-cluster.css +58 -0
  160. package/apps/studio/client/v2/shell/share-cluster.jsx +26 -7
  161. package/apps/studio/client/v2/shell/shell-activity.js +19 -0
  162. package/apps/studio/client/v2/shell/team-switch.js +94 -0
  163. package/apps/studio/client/v2/shell/too-heavy-card.jsx +38 -0
  164. package/apps/studio/client/v2/shell/use-account.js +8 -1
  165. package/apps/studio/client/v2/shell/use-occluded-insets.js +3 -0
  166. package/apps/studio/client/v2/sync-states/conflict-card.jsx +7 -2
  167. package/apps/studio/client/v2/undo/use-undo-projection.jsx +3 -1
  168. package/apps/studio/cloud/endpoints.ts +23 -1
  169. package/apps/studio/collab/persistence.ts +9 -1
  170. package/apps/studio/collab/registry.ts +32 -0
  171. package/apps/studio/collab/room.ts +8 -0
  172. package/apps/studio/config-reload-wire.ts +53 -0
  173. package/apps/studio/dist/client.bundle.js +1098 -1102
  174. package/apps/studio/dist/styles.css +1 -1
  175. package/apps/studio/ds/board/specimen.tsx +12 -1
  176. package/apps/studio/ds/canvas-cli.ts +58 -2
  177. package/apps/studio/ds/check.ts +26 -1
  178. package/apps/studio/ds/cli.ts +7 -3
  179. package/apps/studio/ds/convert.ts +34 -6
  180. package/apps/studio/ds/ds-verb.ts +13 -0
  181. package/apps/studio/ds/post-build.ts +38 -0
  182. package/apps/studio/ds/upgrade-apply.ts +27 -5
  183. package/apps/studio/ds/upgrade-cli.ts +22 -2
  184. package/apps/studio/ds/upgrade-prove.ts +198 -15
  185. package/apps/studio/ds/upgrade-stage.ts +4 -1
  186. package/apps/studio/editing/minimap-context.tsx +3 -3
  187. package/apps/studio/editing/page-activity.ts +251 -0
  188. package/apps/studio/editing/rotate-handle.tsx +9 -5
  189. package/apps/studio/editing/sticky-name.tsx +4 -4
  190. package/apps/studio/history/restore-artboard-action.ts +40 -0
  191. package/apps/studio/history/trash.ts +6 -0
  192. package/apps/studio/home/accounts.ts +87 -0
  193. package/apps/studio/home/hub.ts +77 -175
  194. package/apps/studio/home/index-reader.ts +24 -2
  195. package/apps/studio/home/routes.ts +66 -8
  196. package/apps/studio/http.ts +131 -68
  197. package/apps/studio/index-flight.ts +40 -0
  198. package/apps/studio/managed-projects.ts +52 -24
  199. package/apps/studio/migrate/hub.ts +7 -1
  200. package/apps/studio/routes/canvas-source.ts +44 -2
  201. package/apps/studio/routes/ds-convert.ts +18 -0
  202. package/apps/studio/routes/history.ts +28 -5
  203. package/apps/studio/routes/hub-signin.ts +115 -0
  204. package/apps/studio/routes/index.ts +4 -0
  205. package/apps/studio/routes/table.ts +7 -0
  206. package/apps/studio/routes/trash.ts +19 -1
  207. package/apps/studio/server.ts +19 -10
  208. package/apps/studio/sync/accepted-cold-start.ts +54 -16
  209. package/apps/studio/sync/accepted-link.ts +9 -4
  210. package/apps/studio/sync/asset-push.ts +146 -23
  211. package/apps/studio/sync/asset-state.ts +3 -2
  212. package/apps/studio/sync/code-module-consent.ts +74 -0
  213. package/apps/studio/sync/file-ledger.ts +35 -0
  214. package/apps/studio/sync/file-membership.ts +28 -3
  215. package/apps/studio/sync/file-plane.ts +483 -86
  216. package/apps/studio/sync/file-pull.ts +304 -33
  217. package/apps/studio/sync/hub-browser-signin.ts +377 -0
  218. package/apps/studio/sync/hub-link.ts +1 -2
  219. package/apps/studio/sync/hub-text-undo.ts +30 -10
  220. package/apps/studio/sync/index.ts +381 -161
  221. package/apps/studio/sync/journal-client.ts +94 -5
  222. package/apps/studio/sync/pending-deletes.ts +100 -0
  223. package/apps/studio/sync/projection.ts +121 -14
  224. package/apps/studio/sync/pull-pacer.ts +160 -0
  225. package/apps/studio/sync/pull-priority.ts +119 -0
  226. package/apps/studio/sync/seed-progress.ts +58 -3
  227. package/apps/studio/sync/status.ts +3 -1
  228. package/apps/studio/sync/transaction-client.ts +71 -6
  229. package/apps/studio/sync/workspace-signin.ts +6 -256
  230. package/apps/studio/sync/writer-registry.ts +5 -1
  231. package/apps/studio/thumbs/service.ts +12 -2
  232. package/apps/studio/thumbs/validate.ts +7 -0
  233. package/apps/studio/ui-prefs-migrate.ts +4 -0
  234. package/apps/studio/video-comp.tsx +23 -0
  235. package/apps/studio/video-links-overlay.tsx +3 -2
  236. package/apps/studio/whats-new.json +126 -0
  237. package/cli/lib/bash-guard.mjs +13 -1
  238. package/cli/lib/design-help.gen.mjs +1 -1
  239. package/cli/lib/design-hook.mjs +20 -0
  240. package/cli/lib/studio-locate.mjs +35 -10
  241. package/cli/lib/workspace-plan.mjs +14 -0
  242. package/package.json +8 -8
@@ -249,33 +249,111 @@ export async function hubHealth(opts: {
249
249
  hubUrl: string;
250
250
  fetchImpl?: typeof fetch;
251
251
  signal?: AbortSignal;
252
- }): Promise<{ capabilities: string[] | null; formatVersion: number | null }> {
252
+ /** Override the 4 s ceiling (the lane probe asks with a longer one). */
253
+ timeoutMs?: number;
254
+ }): Promise<{
255
+ capabilities: string[] | null;
256
+ formatVersion: number | null;
257
+ /**
258
+ * Did the HUB answer (2.0.5)? False for a timeout, a network error, a 5xx, a
259
+ * 429 or an unreadable body — none of which says anything about what the hub
260
+ * can do. `capabilities: null` with `answered: true` is a real answer: a hub
261
+ * that predates capabilities.
262
+ */
263
+ answered: boolean;
264
+ }> {
253
265
  const fetchImpl = opts.fetchImpl ?? fetch;
254
266
  const base = opts.hubUrl.replace(/\/+$/, '');
255
267
  try {
256
- const timeout = AbortSignal.timeout(HEALTH_TIMEOUT_MS);
268
+ const timeout = AbortSignal.timeout(opts.timeoutMs ?? HEALTH_TIMEOUT_MS);
257
269
  const res = await fetchImpl(`${base}/health`, {
258
270
  // a hub answers its own /health: a redirect is never followed (gate-b-sec1 A5 — a bounce to an internal
259
271
  // http address from a cell). The other sync requests do not follow one either (`redirect: 'manual'`).
260
272
  redirect: 'error',
261
273
  signal: opts.signal ? AbortSignal.any([opts.signal, timeout]) : timeout,
262
274
  });
263
- if (!res.ok) return { capabilities: null, formatVersion: null };
275
+ if (!res.ok) {
276
+ // A hub without the route (404) has answered: it has no capabilities. A
277
+ // server error or a rate limit has not.
278
+ const answered = res.status < 500 && res.status !== 429 && res.status !== 408;
279
+ return { capabilities: null, formatVersion: null, answered };
280
+ }
264
281
  const body = (await res.json()) as { capabilities?: unknown; formatVersion?: unknown };
265
282
  const fv = body?.formatVersion;
266
283
  const formatVersion = typeof fv === 'number' && Number.isSafeInteger(fv) && fv >= 1 ? fv : null;
267
- if (!Array.isArray(body?.capabilities)) return { capabilities: null, formatVersion };
284
+ if (!Array.isArray(body?.capabilities))
285
+ return { capabilities: null, formatVersion, answered: true };
268
286
  return {
269
287
  capabilities: body.capabilities
270
288
  .filter((c): c is string => typeof c === 'string')
271
289
  .slice(0, 32),
272
290
  formatVersion,
291
+ answered: true,
273
292
  };
274
293
  } catch {
275
- return { capabilities: null, formatVersion: null };
294
+ return { capabilities: null, formatVersion: null, answered: false };
276
295
  }
277
296
  }
278
297
 
298
+ /** The lane probe's patience: a longer ceiling than the 4 s boot probe. */
299
+ const LANE_PROBE_TIMEOUT_MS = 10_000;
300
+ /** Waits between attempts — a cold cell or a busy hub gets a moment. */
301
+ const LANE_PROBE_BACKOFF_MS = [2_000, 5_000] as const;
302
+
303
+ /**
304
+ * Which file lane this hub needs, decided only from an ANSWER (2.0.5).
305
+ *
306
+ * The boot used to ask `/health` once with a 4 s ceiling and read a timeout as
307
+ * "no journal here" — so a hub that was merely slow sent a 2.0 desktop down the
308
+ * legacy v1 lane on a ledger hub for the whole boot: no ledger, no held
309
+ * states, files the person had deleted pulled back, and (with the poll's
310
+ * overlapping passes) a core pinned at 2–4 GB. Now: up to `attempts` tries
311
+ * with a backoff and a longer ceiling; `legacy` only from a hub that answered
312
+ * without `ledger`; `unknown` when it never answered — the caller asks again
313
+ * later and runs no file lane meanwhile.
314
+ */
315
+ export async function probeFileLane(opts: {
316
+ hubUrl: string;
317
+ fetchImpl?: typeof fetch;
318
+ signal?: AbortSignal;
319
+ attempts?: number;
320
+ timeoutMs?: number;
321
+ backoffMs?: readonly number[];
322
+ sleep?: (ms: number) => Promise<void>;
323
+ }): Promise<{
324
+ lane: 'plane' | 'legacy' | 'unknown';
325
+ capabilities: string[] | null;
326
+ formatVersion: number | null;
327
+ }> {
328
+ const attempts = Math.max(1, opts.attempts ?? 3);
329
+ const backoff = opts.backoffMs ?? LANE_PROBE_BACKOFF_MS;
330
+ const sleep =
331
+ opts.sleep ??
332
+ ((ms: number) =>
333
+ new Promise<void>((r) => {
334
+ const t = setTimeout(r, ms);
335
+ (t as { unref?: () => void }).unref?.();
336
+ }));
337
+ for (let i = 0; i < attempts; i++) {
338
+ if (opts.signal?.aborted) break;
339
+ const h = await hubHealth({
340
+ hubUrl: opts.hubUrl,
341
+ ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),
342
+ ...(opts.signal ? { signal: opts.signal } : {}),
343
+ timeoutMs: opts.timeoutMs ?? LANE_PROBE_TIMEOUT_MS,
344
+ });
345
+ if (h.answered) {
346
+ return {
347
+ lane: hasLedger(h.capabilities) ? 'plane' : 'legacy',
348
+ capabilities: h.capabilities,
349
+ formatVersion: h.formatVersion,
350
+ };
351
+ }
352
+ if (i < attempts - 1) await sleep(backoff[Math.min(i, backoff.length - 1)] ?? 5_000);
353
+ }
354
+ return { lane: 'unknown', capabilities: null, formatVersion: null };
355
+ }
356
+
279
357
  /** Does this hub keep annotations as the v2 element model (DDR-242)? */
280
358
  export function hasAnnotationsV2(capabilities: string[] | null): boolean {
281
359
  return Array.isArray(capabilities) && capabilities.includes('annotations-v2');
@@ -297,3 +375,14 @@ export const FILE_CLASSES_V2_CAPABILITY = 'file-classes-v2';
297
375
  export function hasFileClassesV2(capabilities: string[] | null): boolean {
298
376
  return Array.isArray(capabilities) && capabilities.includes(FILE_CLASSES_V2_CAPABILITY);
299
377
  }
378
+
379
+ /** The capability a hub advertises when its doors take paths up to 32 segments deep (fix/205). */
380
+ export const FILE_DEPTH_V2_CAPABILITY = 'file-depth-v2';
381
+
382
+ /**
383
+ * Does this hub take paths deeper than 8 segments? Every hub before fix/205 answers them
384
+ * `400 invalid path`, so the desktop holds them for it with a reason (`olderDoorRefusesDepth`).
385
+ */
386
+ export function hasFileDepthV2(capabilities: string[] | null): boolean {
387
+ return Array.isArray(capabilities) && capabilities.includes(FILE_DEPTH_V2_CAPABILITY);
388
+ }
@@ -0,0 +1,100 @@
1
+ // sync/pending-deletes.ts — fix/ds-convert-hooks-cli #7: a deletion made while no studio runs.
2
+ //
3
+ // "This canvas is gone" travels only on the `canvas-deleted` bus event (sync/index.ts `noteToHub`):
4
+ // a file missing from disk is "this machine stopped carrying it", never a deletion. A verb that
5
+ // runs IN-PROCESS because no studio answers (`maude design ds convert <ds> --restore`,
6
+ // ds/ds-verb.ts) has no bus — so its deletion went nowhere, and the next boot's pull brought the
7
+ // hub's copy straight back (and with it, on the next convert, `ds-convert-exists`).
8
+ //
9
+ // So the in-process run writes the deletion down here, and the next sync boot (1) keeps the boot
10
+ // pull from fetching those canvases and (2) emits `canvas-deleted` for each one whose file is
11
+ // still absent — the same signal the routes send, so the hub hears it exactly as it would have.
12
+ // A canvas whose file is back by then (re-created offline) is not a deletion any more: dropped.
13
+ //
14
+ // `<designRoot>/_state/pending-deletes.json` — `_state/` is per-machine runtime state in every
15
+ // DDR-115 list, so this never syncs, never commits, and a clone never carries one.
16
+
17
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
18
+ import path from 'node:path';
19
+
20
+ const FILE = ['_state', 'pending-deletes.json'] as const;
21
+ const MAX = 256;
22
+ const SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,199}$/;
23
+
24
+ export interface PendingDelete {
25
+ slug: string;
26
+ /** The canvas file, design-root-relative, POSIX — checked for absence at boot. */
27
+ rel: string;
28
+ at: number;
29
+ }
30
+
31
+ const fileOf = (designRoot: string) => path.join(designRoot, ...FILE);
32
+
33
+ function safeRel(rel: unknown): rel is string {
34
+ return (
35
+ typeof rel === 'string' &&
36
+ rel.length > 0 &&
37
+ rel.length <= 1024 &&
38
+ !rel.startsWith('/') &&
39
+ !rel.split('/').some((s) => s === '..' || s === '' || s.startsWith('_'))
40
+ );
41
+ }
42
+
43
+ /** The recorded deletions; `[]` for none, a missing file or anything malformed. */
44
+ export function readPendingDeletes(designRoot: string): PendingDelete[] {
45
+ let doc: unknown;
46
+ try {
47
+ doc = JSON.parse(readFileSync(fileOf(designRoot), 'utf8'));
48
+ } catch {
49
+ return [];
50
+ }
51
+ const list = (doc as { v?: unknown; deletes?: unknown })?.deletes;
52
+ if ((doc as { v?: unknown })?.v !== 1 || !Array.isArray(list)) return [];
53
+ return list
54
+ .filter(
55
+ (d): d is PendingDelete =>
56
+ !!d &&
57
+ typeof d.slug === 'string' &&
58
+ SLUG_RE.test(d.slug) &&
59
+ safeRel(d.rel) &&
60
+ typeof d.at === 'number'
61
+ )
62
+ .slice(0, MAX);
63
+ }
64
+
65
+ /** Write one deletion down (deduplicated by slug, newest kept). Best-effort, never throws. */
66
+ export function recordPendingDelete(
67
+ designRoot: string,
68
+ d: { slug: string; rel: string },
69
+ now = Date.now()
70
+ ): boolean {
71
+ if (!SLUG_RE.test(d.slug) || !safeRel(d.rel)) return false;
72
+ try {
73
+ const next = [
74
+ ...readPendingDeletes(designRoot).filter((x) => x.slug !== d.slug),
75
+ { slug: d.slug, rel: d.rel, at: now },
76
+ ].slice(-MAX);
77
+ const abs = fileOf(designRoot);
78
+ mkdirSync(path.dirname(abs), { recursive: true });
79
+ const tmp = `${abs}.${process.pid}.tmp`;
80
+ writeFileSync(tmp, `${JSON.stringify({ v: 1, deletes: next })}\n`, { mode: 0o600 });
81
+ renameSync(tmp, abs);
82
+ return true;
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Boot: take the recorded deletions. Returns the ones still deletions (their file is absent) and
90
+ * clears the record — what it held is either told now or no longer true.
91
+ */
92
+ export function takePendingDeletes(designRoot: string): PendingDelete[] {
93
+ const all = readPendingDeletes(designRoot);
94
+ try {
95
+ rmSync(fileOf(designRoot), { force: true });
96
+ } catch {
97
+ /* a record we cannot clear is told again next boot — the hub's delete is idempotent */
98
+ }
99
+ return all.filter((d) => !existsSync(path.join(designRoot, ...d.rel.split('/'))));
100
+ }
@@ -77,6 +77,8 @@ export const ACCEPTED_FLUSH_MS = 30;
77
77
  export const MAX_OP_REPLAYS = 3;
78
78
  /** How long an announced API write may hold the doc→file writer at most. */
79
79
  export const LOCAL_WRITE_HOLD_MS = 3_000;
80
+ /** How long a restore waits for this disk's html proposals to be answered (`settleDisk`). */
81
+ export const SETTLE_DISK_MS = 8_000;
80
82
  /** `MAUDE_SYNC_DEBUG=1` — one line per proposal and per disk write (diagnosis). */
81
83
  const SYNC_DEBUG = process.env.MAUDE_SYNC_DEBUG === '1';
82
84
  export const CIRCUIT_MAX_STRIKES = 3;
@@ -261,8 +263,10 @@ export interface DocProjection {
261
263
  * Adopt `body` as the shared base before `reconcile()`. A restart that could
262
264
  * not merge a local candidate (cold start) hands the base back here, so the
263
265
  * write stays blocked with a visible conflict and a later save can merge.
266
+ * `remember` persists it as the recorded base (an accepted create — never a
267
+ * hold, whose base must stay unagreed so the next restart holds again).
264
268
  */
265
- adoptBase(body: string): void;
269
+ adoptBase(body: string, o?: { remember?: boolean }): void;
266
270
  /**
267
271
  * S6.13b — this Mac's canvas moved away from this path on purpose (its name
268
272
  * was taken while it was away): the file is gone by agreement, and what the
@@ -277,6 +281,12 @@ export interface DocProjection {
277
281
  * while this replica still shows the value before it.
278
282
  */
279
283
  adoptOwnAccepted(value: string): void;
284
+ /**
285
+ * #14 (2.0.5) — the css twin's `adoptOwnAccepted`: `value` is this disk's own css proposal a
286
+ * previous run left unanswered, which the outbox drain just had accepted. It is the css base
287
+ * (persisted), and the replica's older css is never written over it while its publication comes.
288
+ */
289
+ adoptOwnAcceptedCss(value: string): void;
280
290
  /**
281
291
  * Accepted-revisions mode: propose one lane value that did not come through
282
292
  * the watcher (a comment/annotation API write). Resolves with the outcome;
@@ -321,6 +331,18 @@ export interface DocProjection {
321
331
  * (false); then the doc→file writer is flushed, so an accepted action is on disk on return.
322
332
  */
323
333
  settleLane(lane: ProposalLane, value: string, ms?: number): Promise<boolean>;
334
+ /**
335
+ * F14 (2.0.4, #166) — a restore is about to splice onto the project's newest version: bring
336
+ * THIS disk's source up to the project first. A change on disk the watcher has not delivered
337
+ * yet (its quiet window) is proposed now, exactly as its file event would propose it, and every
338
+ * html proposal in flight is waited for (at most `ms`). Without this the restore was spliced onto
339
+ * a head that lacked the change the person was looking at; the change, proposed after it from
340
+ * the older base, overlapped the restore and was held here — the click answered ok and the file
341
+ * stayed as it was. `held`: this disk keeps a refused change (the restore must not land over
342
+ * it); `pending`: a proposal is still unanswered after `ms`; `settled`: the project's newest
343
+ * version is what this disk shows.
344
+ */
345
+ settleDisk(ms?: number): Promise<'settled' | 'held' | 'pending'>;
324
346
  /** Lanes with an unresolved proposal (status surfaces). */
325
347
  pendingCount(): number;
326
348
  /**
@@ -329,6 +351,11 @@ export interface DocProjection {
329
351
  * recovery slots. Returns false when nothing is held.
330
352
  */
331
353
  takeAccepted(): boolean;
354
+ /**
355
+ * #14 (2.0.5) — the css twin's held conflict, when its lane holds one: this disk's css and the
356
+ * project's. Keep mine proposes `mine` on top of `theirs`; `takeAccepted` takes `theirs`.
357
+ */
358
+ heldCss(): { mine: string | null; theirs: string } | null;
332
359
  /** T28 — current sides plus the first candidate and proven base (null when unknown). */
333
360
  conflictSides(): {
334
361
  mine: string | null;
@@ -400,6 +427,9 @@ export function createDocProjection(opts: DocProjectionOptions): DocProjection {
400
427
  });
401
428
  return;
402
429
  }
430
+ // #14 — the canvas's conflict is also its css twin's: an accepted html save is no answer to
431
+ // a held css, so the notice (and its dedupe key) stays until that lane is resolved too.
432
+ if (held.has('css') || pending.has('css')) return;
403
433
  if (rejectedKey !== null) opts.onRecovered?.();
404
434
  rejectedKey = null;
405
435
  }
@@ -421,6 +451,21 @@ export function createDocProjection(opts: DocProjectionOptions): DocProjection {
421
451
  }
422
452
  }
423
453
 
454
+ /**
455
+ * #14 — the css twin's agreed value, persisted like the body's (journal hash + recovery slot): a
456
+ * cold start judges a css edited while the studio was closed against it. Only ever a value the
457
+ * project accepted or wrote here — never a hold's base.
458
+ */
459
+ function rememberCssBase(css: string): void {
460
+ opts.journal?.record(slug, { cssHash: hashBytes(css) }); // DDR-102 checkpoint
461
+ if (!opts.historyDir || !paths.css) return;
462
+ try {
463
+ saveRecoveryBody(opts.historyDir, paths.css, 'base', css);
464
+ } catch {
465
+ /* the journal hash still covers the common case */
466
+ }
467
+ }
468
+
424
469
  function preserveLocal(body: string | null): void {
425
470
  if (opts.historyDir && body?.trim()) {
426
471
  // An invalid local draft can still contain authored work. Keep its raw
@@ -653,20 +698,19 @@ export function createDocProjection(opts: DocProjectionOptions): DocProjection {
653
698
  next = repeated.unit;
654
699
  }
655
700
  }
701
+ if (acceptedOwnCss !== null) {
702
+ // #14 — our own accepted css whose publication has not reached this replica: the replica's
703
+ // older css is never written over it. Once the replica moves (to it, or past it), it is over.
704
+ if (next === lastCss) return;
705
+ acceptedOwnCss = null;
706
+ }
656
707
  if (next === lastCss) return;
657
708
  lastCss = next;
658
709
  if (next === null) return; // doc carries no css yet — nothing to write
659
710
  if (!withinCap(paths.css, next, MAX_CSS_BYTES)) return;
660
711
  recordEcho(paths.css, next);
661
712
  writeAndAnnounce(paths.css, next);
662
- opts.journal?.record(slug, { cssHash: hashBytes(next) }); // DDR-102 checkpoint
663
- if (opts.historyDir) {
664
- try {
665
- saveRecoveryBody(opts.historyDir, paths.css, 'base', next);
666
- } catch {
667
- /* the journal hash still covers the common case */
668
- }
669
- }
713
+ rememberCssBase(next);
670
714
  }
671
715
 
672
716
  function writeMetaIfChanged(): void {
@@ -824,11 +868,13 @@ export function createDocProjection(opts: DocProjectionOptions): DocProjection {
824
868
  * overlaps an incoming change").
825
869
  */
826
870
  let acceptedOwn: string | null = null;
871
+ /** #14 — the css twin's `acceptedOwn`. */
872
+ let acceptedOwnCss: string | null = null;
827
873
 
828
874
  /** The value disk and the accepted replica last agreed on for `lane`. */
829
875
  function agreedValue(lane: ProposalLane): string {
830
876
  if (lane === 'html') return acceptedOwn ?? lastHtml ?? htmlFromDoc(doc);
831
- if (lane === 'css') return lastCss ?? cssFromDoc(doc) ?? '';
877
+ if (lane === 'css') return acceptedOwnCss ?? lastCss ?? cssFromDoc(doc) ?? '';
832
878
  return readLaneFromDoc(doc, lane);
833
879
  }
834
880
 
@@ -942,7 +988,16 @@ export function createDocProjection(opts: DocProjectionOptions): DocProjection {
942
988
  rememberBase(value);
943
989
  } else acceptedOwn = value;
944
990
  }
945
- if (lane === 'html') recovered();
991
+ if (lane === 'css' && !pending.has(lane)) {
992
+ // #14 — the css twin's accepted value is its base too, persisted at the ANSWER: a studio
993
+ // that closes before the publication comes back (or whose html writer is busy then)
994
+ // restarted with the base before this save, and its next closed-studio edit of the css
995
+ // was refused against its own accepted save — "changed here and in the cloud".
996
+ rememberCssBase(value);
997
+ if ((cssFromDoc(doc) ?? '') === value) lastCss = value;
998
+ else acceptedOwnCss = value;
999
+ }
1000
+ if (lane === 'html' || lane === 'css') recovered();
946
1001
  if (outcome.actionId) {
947
1002
  try {
948
1003
  opts.onAccepted?.({ lane, value, actionId: outcome.actionId });
@@ -1325,6 +1380,12 @@ export function createDocProjection(opts: DocProjectionOptions): DocProjection {
1325
1380
  // on disk now: the rest of its revision may show.
1326
1381
  const stamped = acceptedOn() ? stampedCohort() : null;
1327
1382
  if (stamped && !seenStamp) observeStamp(stamped);
1383
+ // fix/205-s515 — a publication that arrived before the cold start decided (the creator's own
1384
+ // `doc.create`, published over the socket before its HTTP answer) was refused by `flush`
1385
+ // (not ready) and is first seen HERE. It is on disk now: say it is applied, exactly as
1386
+ // `flush` would — or nothing else changes on this document and the replica's applied
1387
+ // revision stays one behind the head.
1388
+ if (stamped && !held.has('html') && !pending.has('html')) opts.onRevisionApplied?.(stamped[0]);
1328
1389
  }
1329
1390
 
1330
1391
  return {
@@ -1345,14 +1406,18 @@ export function createDocProjection(opts: DocProjectionOptions): DocProjection {
1345
1406
  applyFromFs,
1346
1407
  reconcile,
1347
1408
  flush,
1348
- adoptBase(body: string) {
1409
+ adoptBase(body: string, o?: { remember?: boolean }) {
1349
1410
  lastHtml = body;
1350
1411
  observedBody = body;
1412
+ // v2-204 — an accepted create IS agreement with the project: persist it like any other
1413
+ // accepted value, or the creator restarts with no base and its next offline edit is held.
1414
+ if (o?.remember) rememberBase(body);
1351
1415
  },
1352
1416
  vacate() {
1353
1417
  observedBody = null;
1354
1418
  lastHtml = null;
1355
1419
  lastCss = null;
1420
+ acceptedOwnCss = null;
1356
1421
  lastMeta = null;
1357
1422
  deferredBeforeReady.clear();
1358
1423
  },
@@ -1367,6 +1432,15 @@ export function createDocProjection(opts: DocProjectionOptions): DocProjection {
1367
1432
  }
1368
1433
  rememberBase(value);
1369
1434
  },
1435
+ adoptOwnAcceptedCss(value: string) {
1436
+ const replica = cssFromDoc(doc) ?? '';
1437
+ if (replica === value) lastCss = value;
1438
+ else {
1439
+ lastCss = cssFromDoc(doc);
1440
+ acceptedOwnCss = value;
1441
+ }
1442
+ rememberCssBase(value);
1443
+ },
1370
1444
  hold(lane, base, local) {
1371
1445
  held.add(lane);
1372
1446
  if (lane === 'html') {
@@ -1378,8 +1452,14 @@ export function createDocProjection(opts: DocProjectionOptions): DocProjection {
1378
1452
  reject('local-edit', local, readLaneFromDoc(doc, lane), pathOfLane(lane));
1379
1453
  },
1380
1454
  takeAccepted() {
1381
- if (!held.has('html') && rejectedKey === null) return false;
1455
+ if (!held.has('html') && !held.has('css') && rejectedKey === null) return false;
1382
1456
  held.delete('html');
1457
+ // #14 — the css twin's conflict is taken with it: the project's css returns to disk (the
1458
+ // local css is in its recovery slot since the refusal).
1459
+ if (held.delete('css')) {
1460
+ lastCss = null;
1461
+ acceptedOwnCss = null;
1462
+ }
1383
1463
  // The local-edit guard compares disk with `observedBody`; declaring the
1384
1464
  // current disk bytes observed lets the writer replace them.
1385
1465
  observedBody = readLocal(paths.html);
@@ -1388,8 +1468,12 @@ export function createDocProjection(opts: DocProjectionOptions): DocProjection {
1388
1468
  void flush();
1389
1469
  return true;
1390
1470
  },
1471
+ heldCss() {
1472
+ if (!paths.css || !held.has('css') || pending.has('css')) return null;
1473
+ return { mine: readLocal(paths.css), theirs: cssFromDoc(doc) ?? '' };
1474
+ },
1391
1475
  conflictSides() {
1392
- if (!held.has('html') && rejectedKey === null) return null;
1476
+ if (!held.has('html') && !held.has('css') && rejectedKey === null) return null;
1393
1477
  const candidate = opts.historyDir ? readRecoveryCandidate(opts.historyDir, paths.html) : null;
1394
1478
  return {
1395
1479
  mine: readLocal(paths.html),
@@ -1476,6 +1560,29 @@ export function createDocProjection(opts: DocProjectionOptions): DocProjection {
1476
1560
  if (text !== null) applyFromFs({ path: p, bytes: new TextEncoder().encode(text), hash });
1477
1561
  }
1478
1562
  },
1563
+ async settleDisk(ms = SETTLE_DISK_MS) {
1564
+ if (!acceptedOn() || stopped) return 'settled';
1565
+ if (held.has('html')) return 'held';
1566
+ if (ready && movedToFromDoc(doc) === null) {
1567
+ const str = readLocal(paths.html);
1568
+ // Only a change nobody proposed yet: what this projection wrote or proposed last is
1569
+ // `observedBody`, and an invalid source is left to its own file event (one strike each).
1570
+ if (
1571
+ str !== null &&
1572
+ str !== observedBody &&
1573
+ !isQuarantined(paths.html, hashBytes(str)) &&
1574
+ validation(str) === null
1575
+ ) {
1576
+ proposeFromFs({ path: paths.html, hash: hashBytes(str) }, str);
1577
+ }
1578
+ }
1579
+ const end = Date.now() + ms;
1580
+ while (pending.has('html') && !stopped && Date.now() < end) {
1581
+ await new Promise((r) => setTimeout(r, 20));
1582
+ }
1583
+ if (held.has('html')) return 'held';
1584
+ return pending.has('html') ? 'pending' : 'settled';
1585
+ },
1479
1586
  pendingCount() {
1480
1587
  let n = 0;
1481
1588
  for (const p of pending.values()) n += p.count;
@@ -0,0 +1,160 @@
1
+ // How fast the file plane talks to a hub — issue #204 (a 5 041-file cloud project took ≈ 1.5 h to
2
+ // reach a new Mac: 200 files per pass, ONE request at a time, and the next pass only on the 20 s
3
+ // tick — so the wall clock was the sum of every round trip plus the waits between passes).
4
+ //
5
+ // Two independent bounds, because they protect different things:
6
+ //
7
+ // CONCURRENCY — how many transfers are in flight at once. A cold cell fills every first read of a
8
+ // media file from its bucket with `MAX_CONCURRENT_FILLS = 4` slots and a 15 s deadline
9
+ // (apps/hub/src/materializer.mjs); more parallel GETs than that only queue inside the cell until
10
+ // they time out as `503 fetching from storage`. So we start AT the cell's fill width, may grow a
11
+ // little past it on a hub that keeps up (a warm cache or a self-hosted disk), halve on a 429 and
12
+ // step down on every storage miss — additive increase, multiplicative decrease.
13
+ //
14
+ // RATE — how many requests start in any rolling minute. The hub meters every file read AND every
15
+ // journal read against ONE per-label bucket of 600 a minute (`fileReadBuckets`, server.mjs), and
16
+ // writes against a separate one of the same size. Concurrency alone does not bound that: on a fast
17
+ // hub six parallel GETs of small files run past 600 in well under a minute, and a plane that then
18
+ // meets a 429 is a client manufacturing the limit it fails on (issue #109). We stay at 480, leaving
19
+ // the remaining fifth for the cursor reads, the presence report and anything else on the label.
20
+ //
21
+ // Leaf on purpose: no imports, a clock and a sleep injected, so the tests drive it without timers.
22
+
23
+ /** Transfers in flight at the start — the cold cell's bucket-fill width. */
24
+ export const PULL_CONCURRENCY_START = 4;
25
+ /** Never more than this, however well the hub keeps up. */
26
+ export const PULL_CONCURRENCY_MAX = 6;
27
+ /** Never fewer than one: a wall is a hold (the plane's job), not a zero. */
28
+ export const PULL_CONCURRENCY_MIN = 1;
29
+
30
+ /** Requests of one kind per rolling minute — under the hub's 600-per-label buckets. */
31
+ export const REQUESTS_PER_MINUTE = 480;
32
+ /**
33
+ * A hub that advertises its read ceiling (`/api/file-limits` `readsPerMinute`, #204 — 1 800 on a
34
+ * current hub) is paced at this share of it: the rest of the bucket is the cursor reads' and the
35
+ * presence report's. The advertised figure is hub-supplied (DDR-054), so it is clamped: a hub can
36
+ * slow its own sync down to `MIN_TRUSTED_READS_PER_MINUTE`, never talk us past the maximum.
37
+ */
38
+ export const ADVERTISED_SHARE = 0.8;
39
+ export const MIN_TRUSTED_READS_PER_MINUTE = 60;
40
+ export const MAX_TRUSTED_READS_PER_MINUTE = 6000;
41
+ const WINDOW_MS = 60_000;
42
+
43
+ export type RequestKind = 'read' | 'write';
44
+
45
+ export interface PullPacer {
46
+ /** How many transfers may be in flight right now. */
47
+ limit(): number;
48
+ /** The hub said slow down (a 429, a 5xx with Retry-After): halve. */
49
+ onBackpressure(): void;
50
+ /** The cell's bucket fill timed out for one file: one step down. */
51
+ onStorageMiss(): void;
52
+ /** A pass moved real work and met no wall: one step up. */
53
+ onCleanPass(): void;
54
+ /** The hub advertised its per-label read ceiling: pace reads at a share of it (clamped). */
55
+ setReadCeiling(perMinute: number): void;
56
+ /** Reads per rolling minute in force right now. */
57
+ readsPerMinute(): number;
58
+ /**
59
+ * Wait until one more request of this kind fits in the rolling minute, then charge it. Resolves
60
+ * at once while there is room — a pass that stays under the budget never waits at all.
61
+ */
62
+ admit(kind: RequestKind): Promise<void>;
63
+ }
64
+
65
+ export interface PullPacerOptions {
66
+ now?: () => number;
67
+ sleep?: (ms: number) => Promise<void>;
68
+ start?: number;
69
+ max?: number;
70
+ perMinute?: number;
71
+ }
72
+
73
+ export function createPullPacer(opts: PullPacerOptions = {}): PullPacer {
74
+ const now = opts.now ?? Date.now;
75
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
76
+ const max = Math.max(PULL_CONCURRENCY_MIN, opts.max ?? PULL_CONCURRENCY_MAX);
77
+ const writesPerMinute = Math.max(1, opts.perMinute ?? REQUESTS_PER_MINUTE);
78
+ let readsPerMinute = writesPerMinute;
79
+ let limit = Math.min(max, Math.max(PULL_CONCURRENCY_MIN, opts.start ?? PULL_CONCURRENCY_START));
80
+ // Start times of the requests inside the last minute, oldest first, per kind. Bounded by
81
+ // `perMinute` — `admit` never lets one in past the ceiling.
82
+ const starts: Record<RequestKind, number[]> = { read: [], write: [] };
83
+
84
+ const prune = (log: number[], at: number): void => {
85
+ while (log.length > 0 && at - (log[0] as number) >= WINDOW_MS) log.shift();
86
+ };
87
+
88
+ return {
89
+ limit: () => limit,
90
+ onBackpressure() {
91
+ limit = Math.max(PULL_CONCURRENCY_MIN, Math.floor(limit / 2));
92
+ },
93
+ onStorageMiss() {
94
+ limit = Math.max(PULL_CONCURRENCY_MIN, limit - 1);
95
+ },
96
+ onCleanPass() {
97
+ limit = Math.min(max, limit + 1);
98
+ },
99
+ setReadCeiling(advertised) {
100
+ if (!Number.isFinite(advertised) || advertised <= 0) return;
101
+ const clamped = Math.min(
102
+ MAX_TRUSTED_READS_PER_MINUTE,
103
+ Math.max(MIN_TRUSTED_READS_PER_MINUTE, advertised)
104
+ );
105
+ readsPerMinute = Math.max(1, Math.floor(clamped * ADVERTISED_SHARE));
106
+ },
107
+ readsPerMinute: () => readsPerMinute,
108
+ async admit(kind) {
109
+ const log = starts[kind];
110
+ const perMinute = kind === 'read' ? readsPerMinute : writesPerMinute;
111
+ for (;;) {
112
+ const at = now();
113
+ prune(log, at);
114
+ if (log.length < perMinute) {
115
+ log.push(at);
116
+ return;
117
+ }
118
+ // The oldest start leaves the window first; come back the moment it does.
119
+ await sleep(Math.max(1, WINDOW_MS - (at - (log[0] as number))));
120
+ }
121
+ },
122
+ };
123
+ }
124
+
125
+ /** The parts of a pass result the follow-up decision reads (a `FilePlaneResult` fits). */
126
+ export interface PassOutcome {
127
+ pulled: readonly unknown[];
128
+ pushed: readonly unknown[];
129
+ rateLimited?: unknown;
130
+ authRefused?: true;
131
+ formatRefused?: unknown;
132
+ reanchorHeld?: true;
133
+ requestsExhausted?: true;
134
+ filesCapped?: true;
135
+ budgetExhausted?: true;
136
+ nextAttemptInMs?: number;
137
+ }
138
+
139
+ /**
140
+ * When the NEXT plane pass should run, instead of waiting for the poll tick — issue #204.
141
+ *
142
+ * 0 — the pass moved files and stopped on a COUNT ceiling: there is more of the same, now.
143
+ * ms — a path is waiting out a short backoff (a storage miss): come back when it ends, never
144
+ * sooner than the pass floor.
145
+ * null — leave it to the tick: a wall (rate limit, credential, format, re-anchor storm), a pass
146
+ * that moved nothing (so a pass whose requests all fail can never spin — issue #109), and
147
+ * a byte-budget stop (the 2 GiB per-pass ceiling, DDR-226 F6, stays a per-tick bound).
148
+ */
149
+ export function followUpDelayMs(
150
+ r: PassOutcome,
151
+ timing: { pollMs: number; floorMs: number }
152
+ ): number | null {
153
+ if (r.rateLimited || r.authRefused || r.formatRefused || r.reanchorHeld) return null;
154
+ const moved = r.pulled.length + r.pushed.length;
155
+ if (moved > 0 && !r.budgetExhausted && (r.requestsExhausted || r.filesCapped)) return 0;
156
+ if (r.nextAttemptInMs !== undefined && r.nextAttemptInMs < timing.pollMs) {
157
+ return Math.max(timing.floorMs, r.nextAttemptInMs);
158
+ }
159
+ return null;
160
+ }