@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
@@ -71,7 +71,10 @@ import {
71
71
  classifyProjectFile,
72
72
  type FileClass,
73
73
  isFilePlaneClass,
74
+ MAX_SEGMENTS,
75
+ OLDER_HUB_DEPTH_REASON,
74
76
  olderDoorRefuses,
77
+ olderDoorRefusesDepth,
75
78
  } from './file-membership.ts';
76
79
  import {
77
80
  fetchJournal,
@@ -81,7 +84,10 @@ import {
81
84
  } from './journal-client.ts';
82
85
  import { LFS_POINTER_REASON, readLfsPointer } from './lfs-pointer.ts';
83
86
  import { createPullBudget } from './pull-budget.ts';
87
+ import { createPullPacer, type PullPacer } from './pull-pacer.ts';
88
+ import { activeCanvasWants } from './pull-priority.ts';
84
89
  import { failureReason, isBackpressure, refusalWords, retryAfterMs } from './retry-after.ts';
90
+ import { DELETED_HERE_HELD_REASON } from './seed-progress.ts';
85
91
  import { classifyTransportError } from './transport-error.ts';
86
92
 
87
93
  /** How long to wait for one file's bytes. Generous — these run to videos. */
@@ -100,8 +106,11 @@ export const MAX_FILE_BYTES = (() => {
100
106
  })();
101
107
 
102
108
  /** T18 — above this a download streams to disk (and resumes) instead of
103
- * being held in memory. */
104
- export const STREAM_DOWNLOAD_ABOVE_BYTES = 32 * 1024 * 1024;
109
+ * being held in memory. Issue #204: it was 32 MB, so every photo and clip of a
110
+ * first sync was collected chunk by chunk and then copied into one buffer of
111
+ * its full size (twice the file per download); below the threshold that still
112
+ * happens, so it is kept at a size where twice the file does not matter. */
113
+ export const STREAM_DOWNLOAD_ABOVE_BYTES = 1024 * 1024;
105
114
 
106
115
  /** sha256 of a file, read in 1 MiB chunks (T18 — a video is never held whole). */
107
116
  export function sha256File(abs: string): string {
@@ -179,7 +188,28 @@ export const HUB_LIMITS_RETRY_MS = 30_000;
179
188
  export const MAX_TRUSTED_QUOTA_PAUSE_MS = 2 * 60 * 60_000;
180
189
 
181
190
  /** How many files one pass will move. The remainder is the next pass's work. */
182
- const MAX_FILES_PER_PASS = 200;
191
+ export const MAX_FILES_PER_PASS = 200;
192
+
193
+ /**
194
+ * Issue #204 — write the ledger at most every this many landings while a pass runs (it is always
195
+ * written at the end of the pass). A crash in between loses only the adoption of those files, which
196
+ * the next pass recovers by hashing them — never by downloading them again.
197
+ */
198
+ export const LEDGER_FLUSH_EVERY_LANDINGS = 250;
199
+ /** …or after this long, so a slow pass of large files still leaves a recent ledger behind. */
200
+ export const LEDGER_FLUSH_EVERY_MS = 15_000;
201
+
202
+ /**
203
+ * Issue #204 — this many `fetching from storage` misses IN A ROW is no longer one slow file but a
204
+ * bucket that is not answering: the plane holds for the hub's Retry-After, as it does for any wall.
205
+ */
206
+ export const STORAGE_MISS_STREAK_LIMIT = 4;
207
+
208
+ /** A staged partial download untouched this long, for bytes no pass wants, is removed. */
209
+ export const STALE_PART_MS = 24 * 60 * 60_000;
210
+
211
+ /** Issue #204 — the most body bytes concurrent downloads may hold in memory at once (see the pool). */
212
+ export const MAX_BUFFERED_IN_FLIGHT_BYTES = 64 * 1024 * 1024;
183
213
 
184
214
  /**
185
215
  * How many HTTP REQUESTS one pass will issue. Issue #109.
@@ -349,8 +379,8 @@ function deliveryRank(state: DeliveryState): number {
349
379
  }
350
380
  }
351
381
 
352
- /** Walk depth ceiling — matches the classifier's own shape cap. */
353
- const MAX_WALK_DEPTH = 8;
382
+ /** Walk depth ceiling — the classifier's own shape cap (32 since fix/205). */
383
+ const MAX_WALK_DEPTH = MAX_SEGMENTS;
354
384
 
355
385
  /** Directories no plane path can live under. */
356
386
  const SKIPPED_DIRS = new Set(['_trash', '_history', '_untrusted', '_smoke', 'node_modules']);
@@ -395,6 +425,19 @@ export interface FilePlaneResult {
395
425
  };
396
426
  /** The pass stopped because it had spent its request ceiling. */
397
427
  requestsExhausted?: true;
428
+ /** The pass stopped because it had moved `MAX_FILES_PER_PASS` files (issue #204). */
429
+ filesCapped?: true;
430
+ /**
431
+ * Issue #204 — files whose bytes the hub is still FETCHING FROM ITS BUCKET (a cold cell's
432
+ * `503 fetching from storage`). Not delivered, not failed, not stuck: each is backed off for the
433
+ * hub's `Retry-After` and asked again, while the rest of the pass carries on.
434
+ */
435
+ storageMisses?: number;
436
+ /**
437
+ * The soonest a path skipped for its backoff window may be tried again, in ms from the end of
438
+ * this pass. Lets the runtime come back for it then rather than on the next 20 s tick.
439
+ */
440
+ nextAttemptInMs?: number;
398
441
  /** The door refused our credential; a renewal was requested and the pass ended. */
399
442
  authRefused?: true;
400
443
  /**
@@ -542,6 +585,22 @@ export interface FilePlaneOptions {
542
585
  * true (every caller before this option, and every test hub, takes them).
543
586
  */
544
587
  hubTakesV2Files?: boolean;
588
+ /**
589
+ * fix/205 — the hub advertises `file-depth-v2` (`hasFileDepthV2`). False ⇒ a path deeper than
590
+ * 8 segments (`olderDoorRefusesDepth`) is held here with a reason and never offered. Absent ⇒
591
+ * true, like `hubTakesV2Files`.
592
+ */
593
+ hubTakesDeepPaths?: boolean;
594
+ /**
595
+ * Issue #204 — how fast this plane talks to the hub (concurrency + requests per minute). One per
596
+ * plane so the adaptive width survives from pass to pass. Default: `createPullPacer()`.
597
+ */
598
+ pacer?: PullPacer;
599
+ /**
600
+ * Issue #204 — paths to fetch FIRST: the open canvas's own files, imports and assets. Read once
601
+ * per pass. Default: the active canvas named in `_active.json` (`activeCanvasWants`).
602
+ */
603
+ priorityPaths?: () => ReadonlySet<string>;
545
604
  }
546
605
 
547
606
  interface SyncableLocalFile {
@@ -700,6 +759,9 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
700
759
  })();
701
760
 
702
761
  const auth = () => ({ authorization: `Bearer ${opts.token()}` });
762
+ /** Issue #204 — concurrency + requests per minute, adaptive across passes. */
763
+ const pacer = opts.pacer ?? createPullPacer({ now });
764
+ const priorityPaths = opts.priorityPaths ?? (() => activeCanvasWants(designRoot));
703
765
 
704
766
  /**
705
767
  * A thrown transfer error, in words a PERSON can act on.
@@ -770,6 +832,12 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
770
832
  } | null = null;
771
833
  /** Consecutive `unreachable` classifications this pass. */
772
834
  let unreachableInARow = 0;
835
+ /** Consecutive `fetching from storage` misses this pass (#204). */
836
+ let storageMissesInARow = 0;
837
+ /** The last failure reason logged per path, so a file that keeps failing is named once. */
838
+ const failureSaid = new Map<string, string>();
839
+ /** The soonest a path this pass put in (or found in) a backoff window may go again (#204). */
840
+ let soonestRetryAt = Number.POSITIVE_INFINITY;
773
841
  /** The door refused our credential this pass. */
774
842
  let authRefused = false;
775
843
  /** Set when a write door answered 426 (format) this pass. */
@@ -834,7 +902,12 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
834
902
  uploadSessions?: unknown;
835
903
  maxSessionBytes?: unknown;
836
904
  partBytes?: unknown;
905
+ readsPerMinute?: unknown;
837
906
  };
907
+ // Issue #204 — the hub's per-label READ ceiling, when it says (a pre-2.0.4 hub does not, and
908
+ // the pacer's 480 stays under that hub's 600). Clamped inside the pacer (DDR-054).
909
+ if (Number.isFinite(body?.readsPerMinute))
910
+ pacer.setReadCeiling(body.readsPerMinute as number);
838
911
  if (
839
912
  Number.isFinite(body?.maxFileBytes) &&
840
913
  (body.maxFileBytes as number) >= MIN_TRUSTED_MAX_FILE_BYTES
@@ -981,19 +1054,28 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
981
1054
  return { ok: false, reason, rateLimited: true };
982
1055
  }
983
1056
 
984
- /** Fetch one file's bytes and verify them against the hash we were promised. */
1057
+ /**
1058
+ * Fetch one file's bytes and verify them against the hash we were promised — resuming a staged
1059
+ * partial download (T18) when there is one.
1060
+ *
1061
+ * A STAGED PART ALWAYS RESUMES OR RESTARTS, NEVER WEDGES (#204 follow-up: a self-hosted
1062
+ * workspace sat at "7614 / 7617 delivered · 3 waiting" for good, all three large videos). The
1063
+ * staging file is keyed by content hash and outlives the pass, so every way it can disagree with
1064
+ * the hub is handled inside this one attempt rather than as a failure the next pass meets again:
1065
+ * - already whole (the size the journal names): verified on disk and landed with NO request;
1066
+ * overgrown or whole-but-wrong: discarded, fetched fresh;
1067
+ * - the hub cannot honour the range (416), answers it from a different offset, or ignores it
1068
+ * (200): discarded, fetched fresh — at most one restart per attempt;
1069
+ * - resumed bytes that do not hash right (a bad prefix): discarded, fetched fresh once.
1070
+ * What still fails is a real failure: it reaches `failed` with a reason and the path backs off.
1071
+ */
985
1072
  async function fetchVerified(
986
1073
  rel: string,
987
1074
  expectHash: string,
988
- ceiling: number
989
- ): Promise<
990
- | { ok: true; bytes: Uint8Array; file?: undefined; size: number }
991
- | { ok: true; file: string; bytes?: undefined; size: number }
992
- | { ok: false; reason: string; overCap?: true; rateLimited?: true }
993
- > {
994
- let res: Response;
995
- requestsThisPass += 1;
996
- // T18 — a partial download of these exact bytes resumes where it stopped.
1075
+ ceiling: number,
1076
+ /** The size the journal names, when it does — lets a whole staged part land without a request. */
1077
+ sizeHint = 0
1078
+ ): Promise<Exclude<Awaited<ReturnType<typeof fetchOnce>>, { restart: true }>> {
997
1079
  const staged = path.join(designRoot, '_state', 'downloads', `${expectHash}.part`);
998
1080
  let resumeFrom = 0;
999
1081
  try {
@@ -1001,6 +1083,54 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
1001
1083
  } catch {
1002
1084
  /* nothing staged */
1003
1085
  }
1086
+ if (resumeFrom > 0 && sizeHint > 0 && resumeFrom >= sizeHint) {
1087
+ if (resumeFrom === sizeHint) {
1088
+ let got: string | null = null;
1089
+ try {
1090
+ got = await sha256FileAsync(staged);
1091
+ } catch {
1092
+ got = null;
1093
+ }
1094
+ if (got === expectHash) return { ok: true, file: staged, size: resumeFrom };
1095
+ }
1096
+ rmSync(staged, { force: true });
1097
+ resumeFrom = 0;
1098
+ }
1099
+ const first = await fetchOnce(rel, expectHash, ceiling, staged, resumeFrom);
1100
+ if (!('restart' in first) || resumeFrom === 0) {
1101
+ if ('restart' in first) return { ok: false, reason: first.reason };
1102
+ return first;
1103
+ }
1104
+ log.warn?.(`[sync/files] ${rel}: ${first.reason} — fetching it from the start`);
1105
+ rmSync(staged, { force: true });
1106
+ const again = await fetchOnce(rel, expectHash, ceiling, staged, 0);
1107
+ return 'restart' in again ? { ok: false, reason: again.reason } : again;
1108
+ }
1109
+
1110
+ /** One request for `rel`, resuming at `resumeFrom` (0 = whole file). `restart` = discard the part. */
1111
+ async function fetchOnce(
1112
+ rel: string,
1113
+ expectHash: string,
1114
+ ceiling: number,
1115
+ staged: string,
1116
+ resumeFrom: number
1117
+ ): Promise<
1118
+ | { ok: true; bytes: Uint8Array; file?: undefined; size: number }
1119
+ | { ok: true; file: string; bytes?: undefined; size: number }
1120
+ | {
1121
+ ok: false;
1122
+ reason: string;
1123
+ overCap?: true;
1124
+ rateLimited?: true;
1125
+ /** The hub is still filling these bytes from its bucket (#204). */
1126
+ storageMiss?: true;
1127
+ restart?: undefined;
1128
+ }
1129
+ | { ok: false; restart: true; reason: string }
1130
+ > {
1131
+ let res: Response;
1132
+ requestsThisPass += 1;
1133
+ await pacer.admit('read');
1004
1134
  try {
1005
1135
  res = await fetchImpl(
1006
1136
  `${base}/_project-file/${rel.split('/').map(encodeURIComponent).join('/')}`,
@@ -1014,11 +1144,59 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
1014
1144
  }
1015
1145
  if (res.status === 416) {
1016
1146
  // The staged part is not a prefix of what the hub holds now: start over.
1147
+ await res.body?.cancel().catch(() => {});
1017
1148
  rmSync(staged, { force: true });
1018
- return { ok: false, reason: 'the partial download no longer matches — restarting it' };
1149
+ return {
1150
+ ok: false,
1151
+ restart: true,
1152
+ reason: 'the partial download no longer matches — restarting it',
1153
+ };
1154
+ }
1155
+ // ISSUE #204 — A COLD CELL STILL FETCHING THESE BYTES FROM ITS BUCKET. The materializer answers
1156
+ // `503 Retry-After {"error":"fetching from storage"}` once its 15 s deadline passes, and keeps
1157
+ // the fill going for the next caller. That is about ONE file, not the door: the whole plane used
1158
+ // to hold on it (a Retry-After 5xx is backpressure) and the pass ended, so one slow video cost
1159
+ // every other file the rest of the pass and the wait for the next tick. Now the file waits out
1160
+ // the hub's Retry-After on its own and the pass carries on; a RUN of them is still a wall
1161
+ // (`STORAGE_MISS_STREAK_LIMIT`). The body is hub-supplied (DDR-054) — misreading it as a miss
1162
+ // buys a per-file backoff instead of a plane hold, both bounded.
1163
+ if (res.status === 503 && res.headers?.get?.('retry-after')) {
1164
+ const words = await failureReason(res);
1165
+ if (/fetching from storage/.test(words)) {
1166
+ storageMissesInARow += 1;
1167
+ if (storageMissesInARow >= STORAGE_MISS_STREAK_LIMIT) {
1168
+ const wait = retryAfterMs(res.headers.get('retry-after'));
1169
+ if (hitRateLimit === null || wait > hitRateLimit.retryAfterMs) {
1170
+ hitRateLimit = { retryAfterMs: wait, cause: 'hub-asked' };
1171
+ }
1172
+ }
1173
+ return { ok: false, reason: words, storageMiss: true };
1174
+ }
1175
+ // Any other 503 with a Retry-After keeps its meaning: a starting cell, hold the plane.
1176
+ const wait = retryAfterMs(res.headers.get('retry-after'));
1177
+ if (hitRateLimit === null || wait > hitRateLimit.retryAfterMs) {
1178
+ hitRateLimit = { retryAfterMs: wait, cause: 'hub-asked' };
1179
+ }
1180
+ return { ok: false, reason: words, rateLimited: true };
1019
1181
  }
1020
1182
  if (!res.ok) return await refusal(res);
1183
+ storageMissesInARow = 0;
1021
1184
  const resumed = res.status === 206 && resumeFrom > 0;
1185
+ // A 206 must continue EXACTLY where the part ends — appending any other offset is a corrupt
1186
+ // file that only the hash would catch, after the whole download.
1187
+ if (resumed) {
1188
+ const range = /^bytes\s+(\d+)-/.exec(res.headers?.get?.('content-range') ?? '');
1189
+ if (!range || Number(range[1]) !== resumeFrom) {
1190
+ await res.body?.cancel().catch(() => {});
1191
+ return {
1192
+ ok: false,
1193
+ restart: true,
1194
+ reason: 'the server resumed from a different place — restarting it',
1195
+ };
1196
+ }
1197
+ }
1198
+ // Asked to resume and answered with the whole file (no range support): the part is stale.
1199
+ if (resumeFrom > 0 && !resumed) rmSync(staged, { force: true });
1022
1200
 
1023
1201
  // The cap is consulted BEFORE the body exists, and again as it arrives.
1024
1202
  // Buffering first and measuring after is not a cap at all: a hub answering
@@ -1073,7 +1251,10 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
1073
1251
  }
1074
1252
  if (got !== expectHash) {
1075
1253
  rmSync(staged, { force: true });
1076
- return { ok: false, reason: 'content hash mismatch (racing a write?)' };
1254
+ // A resumed file that does not hash right had a bad prefix: one fresh fetch settles it.
1255
+ return resumed
1256
+ ? { ok: false, restart: true, reason: 'the resumed download did not verify' }
1257
+ : { ok: false, reason: 'content hash mismatch (racing a write?)' };
1077
1258
  }
1078
1259
  return { ok: true, file: staged, size: total };
1079
1260
  }
@@ -1259,6 +1440,33 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
1259
1440
  return isFilePlaneClass(cls);
1260
1441
  }
1261
1442
 
1443
+ /**
1444
+ * Drop staged partial downloads nobody is waiting for (#204 follow-up). A part is keyed by content
1445
+ * hash, so once the hub's file moves on (or the file lands another way) its part is dead weight
1446
+ * that nothing would ever resume. Only parts untouched for `STALE_PART_MS` go, and never one whose
1447
+ * hash this pass still wants — a slow download of a big video keeps its progress.
1448
+ */
1449
+ function sweepStaleParts(wanted: ReadonlySet<string>): void {
1450
+ const dir = path.join(designRoot, '_state', 'downloads');
1451
+ let names: string[];
1452
+ try {
1453
+ names = readdirSync(dir);
1454
+ } catch {
1455
+ return;
1456
+ }
1457
+ for (const name of names.slice(0, 500)) {
1458
+ const m = /^([0-9a-f]{64})\.part$/.exec(name);
1459
+ if (!m || wanted.has(m[1] as string)) continue;
1460
+ const abs = path.join(dir, name);
1461
+ try {
1462
+ if (now() - statSync(abs).mtimeMs < STALE_PART_MS) continue;
1463
+ rmSync(abs, { force: true });
1464
+ } catch {
1465
+ /* gone already */
1466
+ }
1467
+ }
1468
+ }
1469
+
1262
1470
  /** Land bytes at `rel`, atomically. Throws on failure — `adoptAfter` catches.
1263
1471
  * A streamed download (T18) is moved into place from its staging file. */
1264
1472
  function materialize(rel: string, payload: { bytes?: Uint8Array; file?: string }): void {
@@ -1362,6 +1570,7 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
1362
1570
  // rather than as a remote change we must react to.
1363
1571
  ledger.outboxAdd(local.hash);
1364
1572
  requestsThisPass += 1;
1573
+ await pacer.admit('write');
1365
1574
  try {
1366
1575
  const res = await fetchImpl(
1367
1576
  `${base}/api/file/${local.rel.split('/').map(encodeURIComponent).join('/')}`,
@@ -1409,6 +1618,7 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
1409
1618
  (await res.json().catch(() => ({}))) as Record<string, unknown>;
1410
1619
  ledger.outboxAdd(local.hash);
1411
1620
  requestsThisPass += 1;
1621
+ await pacer.admit('write');
1412
1622
  try {
1413
1623
  const created = await fetchImpl(`${base}/api/file-uploads`, {
1414
1624
  method: 'POST',
@@ -1510,6 +1720,7 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
1510
1720
  { ok: true } | { ok: false; conflict: true } | { ok: false; reason: string; rateLimited?: true }
1511
1721
  > {
1512
1722
  requestsThisPass += 1;
1723
+ await pacer.admit('write');
1513
1724
  try {
1514
1725
  const res = await fetchImpl(
1515
1726
  `${base}/api/file/${rel.split('/').map(encodeURIComponent).join('/')}`,
@@ -1663,7 +1874,15 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
1663
1874
  }
1664
1875
 
1665
1876
  async function reconcile(): Promise<FilePlaneResult> {
1666
- const out = await reconcilePass();
1877
+ // ONE ledger write per batch (#204): the pass writes it every N landings and at its end
1878
+ // (`ledger.flush()` in step 5); nothing in between re-arms the 1 s debounce per file.
1879
+ const release = ledger.deferFlush();
1880
+ let out: FilePlaneResult;
1881
+ try {
1882
+ out = await reconcilePass();
1883
+ } finally {
1884
+ release();
1885
+ }
1667
1886
  const refused = hubRefusedRows();
1668
1887
  if (refused.length > 0) out.hubRefused = refused;
1669
1888
  return out;
@@ -1700,6 +1919,8 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
1700
1919
  }
1701
1920
  hitRateLimit = null;
1702
1921
  unreachableInARow = 0;
1922
+ storageMissesInARow = 0;
1923
+ soonestRetryAt = Number.POSITIVE_INFINITY;
1703
1924
  authRefused = false;
1704
1925
  formatRefused = null;
1705
1926
  quotaSpentThisPass = 0;
@@ -2046,11 +2267,17 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2046
2267
  // answers `400 invalid path` to every 2.0-only file; asking costs a
2047
2268
  // request and tells nobody anything. Held with a reason instead — and
2048
2269
  // offered again the pass this hub advertises `file-classes-v2`.
2270
+ // fix/205 — the same for a path deeper than an older door takes (8 segments).
2271
+ const olderHubReason =
2272
+ here && remoteHash === null
2273
+ ? opts.hubTakesV2Files === false && olderDoorRefuses(rel)
2274
+ ? OLDER_HUB_REASON
2275
+ : opts.hubTakesDeepPaths === false && olderDoorRefusesDepth(rel)
2276
+ ? OLDER_HUB_DEPTH_REASON
2277
+ : null
2278
+ : null;
2049
2279
  if (
2050
- here &&
2051
- remoteHash === null &&
2052
- opts.hubTakesV2Files === false &&
2053
- olderDoorRefuses(rel) &&
2280
+ olderHubReason !== null &&
2054
2281
  isFilePlaneClass(
2055
2282
  classifyProjectFile(rel, {
2056
2283
  canvasGroups: opts.canvasGroups,
@@ -2062,17 +2289,17 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2062
2289
  !(
2063
2290
  kept?.state === 'refused' &&
2064
2291
  kept.blockedClass === 'refused' &&
2065
- kept.reason === OLDER_HUB_REASON &&
2292
+ kept.reason === olderHubReason &&
2066
2293
  kept.refusedHash === undefined
2067
2294
  )
2068
2295
  ) {
2069
2296
  ledger.setState(rel, 'refused', {
2070
- reason: OLDER_HUB_REASON,
2297
+ reason: olderHubReason,
2071
2298
  blockedClass: 'refused',
2072
2299
  refusedHash: undefined,
2073
2300
  });
2074
2301
  }
2075
- out.dropped.push({ rel, reason: OLDER_HUB_REASON });
2302
+ out.dropped.push({ rel, reason: olderHubReason });
2076
2303
  continue;
2077
2304
  }
2078
2305
 
@@ -2116,6 +2343,21 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2116
2343
  state: remoteHash !== null ? 'on-hub' : 'local-only',
2117
2344
  });
2118
2345
  out.synced += 1;
2346
+ } else if (
2347
+ !here &&
2348
+ remoteHash !== null &&
2349
+ !opts.propagateDeletes &&
2350
+ state.ancestor === remoteHash
2351
+ ) {
2352
+ // 2.0.5 rule (a) — DELETED HERE, KEPT THERE, AND SAID SO. With delete
2353
+ // sync off this is a deliberate hold (no resurrection, no delete), but
2354
+ // the row still read `on-hub` from the pass that once delivered it:
2355
+ // the field ledger claimed 7 614 of 7 617 delivered while 1 814 of
2356
+ // those files were not on the disk. Held with a reason instead; a
2357
+ // copy that comes back with the same bytes is agreement again.
2358
+ if (!(kept?.state === 'stuck' && kept.reason === DELETED_HERE_HELD_REASON)) {
2359
+ ledger.setState(rel, 'stuck', { reason: DELETED_HERE_HELD_REASON });
2360
+ }
2119
2361
  }
2120
2362
  continue;
2121
2363
  }
@@ -2219,13 +2461,23 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2219
2461
 
2220
2462
  // ── 4. Apply ─────────────────────────────────────────────────────────
2221
2463
  //
2222
- // Referenced assets first (DDR-223's strokes→bytes coupling): a picture a
2223
- // just-arrived annotation points at is the one a person is staring at.
2464
+ // The open canvas first (#204): its own files, imports and assets are what a person is looking
2465
+ // at. Then referenced assets (DDR-223's strokes→bytes coupling): a picture a just-arrived
2466
+ // annotation points at is the one a person is staring at.
2224
2467
  const referenced = referencedAssetNames(designRoot);
2468
+ let wanted: ReadonlySet<string> = new Set();
2469
+ try {
2470
+ wanted = priorityPaths();
2471
+ } catch {
2472
+ /* ordering only — never a reason to stop a pass */
2473
+ }
2225
2474
  // …then smallest first (T19): one 1 GB master never makes the forty
2226
2475
  // images a canvas needs wait behind it; big media fills in last.
2227
2476
  const sizeOf = (w: (typeof work)[number]) => Math.max(claimedSize(w.row), w.local?.size ?? 0);
2228
- work.sort((a, b) => rank(a.rel, referenced) - rank(b.rel, referenced) || sizeOf(a) - sizeOf(b));
2477
+ work.sort(
2478
+ (a, b) =>
2479
+ rank(a.rel, referenced, wanted) - rank(b.rel, referenced, wanted) || sizeOf(a) - sizeOf(b)
2480
+ );
2229
2481
 
2230
2482
  const budget = createPullBudget({
2231
2483
  label: 'sync/files',
@@ -2233,17 +2485,123 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2233
2485
  ...(opts.maxPassBytes !== undefined ? { maxBytes: opts.maxPassBytes } : {}),
2234
2486
  });
2235
2487
 
2488
+ /**
2489
+ * ISSUE #204 — DOWNLOADS RUN SIDE BY SIDE. One request at a time made the wall clock of a first
2490
+ * sync the SUM of every round trip: 200 files per pass at one cold-cell bucket fill each was the
2491
+ * 2–4 minutes a pass took on a 5 041-file project. A `pull` now runs in a pool `pacer.limit()`
2492
+ * wide; everything else (an upload, a delete, a conflict that parks a copy) still runs alone,
2493
+ * after the pool drains, because those decide against the hub's CAS and their order matters.
2494
+ *
2495
+ * The pool is ONE wide until a transfer of this pass has come back healthy: the first request of
2496
+ * a pass is the probe, so a door that is shut (a starting cell, a 429 window) sees one request,
2497
+ * not `limit` of them.
2498
+ *
2499
+ * The ceilings count what is DISPATCHED, so concurrency never lets a pass past them: requests are
2500
+ * charged at dispatch (`requestsThisPass`), files as `moved + in flight`, bytes are reserved
2501
+ * against the budget before the request leaves.
2502
+ */
2236
2503
  let moved = 0;
2237
2504
  let seen = 0;
2505
+ let probed = false;
2506
+ let landedSinceFlush = 0;
2507
+ let lastFlushAt = now();
2508
+ const inFlight = new Set<Promise<void>>();
2509
+ /**
2510
+ * Content hashes being downloaded right now. A large body streams to `_state/downloads/<sha>.part`
2511
+ * — keyed by HASH, so the resume finds it — and a project holding the same video at two paths
2512
+ * would have two transfers appending to one staging file. The second copy waits its turn.
2513
+ */
2514
+ const hashesInFlight = new Set<string>();
2515
+ /**
2516
+ * Bytes being BUFFERED in memory by downloads in flight. A body up to
2517
+ * `STREAM_DOWNLOAD_ABOVE_BYTES` is read into memory before it is verified and landed, so six
2518
+ * 30 MB videos at once would hold ~360 MB (twice that while the chunks are joined). The pool
2519
+ * admits another buffered body only while the total stays under `MAX_BUFFERED_IN_FLIGHT_BYTES`;
2520
+ * a streamed (larger) body costs one chunk and is not counted. One transfer always runs.
2521
+ */
2522
+ let bufferedInFlight = 0;
2523
+ const buffered = (w: (typeof work)[number]): number => {
2524
+ const n = claimedSize(w.row);
2525
+ return n <= STREAM_DOWNLOAD_ABOVE_BYTES ? n : 0;
2526
+ };
2527
+ const wall = () => hitRateLimit !== null || formatRefused !== null || authRefused;
2528
+
2529
+ const settle = (
2530
+ item: (typeof work)[number],
2531
+ handled: boolean,
2532
+ mark: { failed: number; pushed: number; pulled: number }
2533
+ ): void => {
2534
+ if (handled) moved += 1;
2535
+ if (handled && !probed && !wall()) probed = true;
2536
+ // Arm or clear this path's window from what the pass actually did with
2537
+ // it. A rate limit is excluded: that is the DOOR's state, not this
2538
+ // path's, and punishing the file for it would push a whole project into
2539
+ // backoff for something none of its files did. Scanned from the marks
2540
+ // taken at dispatch, because other transfers append to the same lists.
2541
+ if (hitRateLimit === null && formatRefused === null) {
2542
+ const failedHere = out.failed.slice(mark.failed).some((f) => f.rel === item.rel);
2543
+ if (failedHere) {
2544
+ const delay = ledger.noteAttemptFailed(item.rel, now());
2545
+ // ONE LINE PER FAILING FILE, naming it and why — said again only when the reason
2546
+ // changes, not on every retry of a file that keeps failing the same way.
2547
+ const why = out.failed.slice(mark.failed).find((f) => f.rel === item.rel)?.reason;
2548
+ if (why !== undefined && failureSaid.get(item.rel) !== why) {
2549
+ failureSaid.set(item.rel, why);
2550
+ log.warn?.(
2551
+ `[sync/files] ${item.rel}: ${why} — trying again in ${Math.round(delay / 1000)}s, then less often`
2552
+ );
2553
+ }
2554
+ } else if (
2555
+ handled ||
2556
+ out.pushed.slice(mark.pushed).includes(item.rel) ||
2557
+ out.pulled.slice(mark.pulled).includes(item.rel)
2558
+ ) {
2559
+ ledger.noteAttemptOk(item.rel);
2560
+ failureSaid.delete(item.rel);
2561
+ }
2562
+ }
2563
+ // ONE ledger write per batch, not one per landing (#204).
2564
+ if (handled) landedSinceFlush += 1;
2565
+ if (
2566
+ landedSinceFlush >= LEDGER_FLUSH_EVERY_LANDINGS ||
2567
+ (landedSinceFlush > 0 && now() - lastFlushAt >= LEDGER_FLUSH_EVERY_MS)
2568
+ ) {
2569
+ landedSinceFlush = 0;
2570
+ lastFlushAt = now();
2571
+ ledger.flush();
2572
+ }
2573
+ };
2574
+
2575
+ const run = async (item: (typeof work)[number]): Promise<void> => {
2576
+ const mark = {
2577
+ failed: out.failed.length,
2578
+ pushed: out.pushed.length,
2579
+ pulled: out.pulled.length,
2580
+ };
2581
+ let handled = false;
2582
+ try {
2583
+ handled = await applyOne(item, out, budget);
2584
+ } finally {
2585
+ settle(item, handled, mark);
2586
+ }
2587
+ };
2588
+ const drain = async (): Promise<void> => {
2589
+ while (inFlight.size > 0) await Promise.race(inFlight);
2590
+ };
2591
+
2238
2592
  for (const item of work) {
2239
2593
  // TWO CEILINGS, because they bound different things and only one of them
2240
2594
  // survives a bad day. `moved` bounds what LANDS — disk writes, parked
2241
2595
  // copies, ledger churn — and it is the one a healthy pass hits. Requests
2242
2596
  // bound what we ASK, and it is the one that matters when nothing is
2243
2597
  // landing, which is precisely when the first counter stops moving
2244
- // (issue #109).
2245
- if (moved >= MAX_FILES_PER_PASS || requestsThisPass >= MAX_REQUESTS_PER_PASS) {
2598
+ // (issue #109). Both count transfers still in flight.
2599
+ if (
2600
+ moved + inFlight.size >= MAX_FILES_PER_PASS ||
2601
+ requestsThisPass >= MAX_REQUESTS_PER_PASS
2602
+ ) {
2246
2603
  if (requestsThisPass >= MAX_REQUESTS_PER_PASS) out.requestsExhausted = true;
2604
+ else out.filesCapped = true;
2247
2605
  log.warn?.(
2248
2606
  `[sync/files] ${work.length - seen} more path(s) to reconcile; taking them next pass.`
2249
2607
  );
@@ -2253,6 +2611,8 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2253
2611
  out.budgetExhausted = true;
2254
2612
  break;
2255
2613
  }
2614
+ // A wall met by a transfer in flight ends the dispatch; what is in flight finishes.
2615
+ if (wall()) break;
2256
2616
  // A PATH INSIDE ITS BACKOFF WINDOW COSTS NOTHING.
2257
2617
  //
2258
2618
  // Checked BEFORE the ceilings deliberately: charging a skipped path
@@ -2262,64 +2622,86 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2262
2622
  if (ledger.isBackedOff(item.rel, now())) {
2263
2623
  seen += 1;
2264
2624
  out.backedOff = (out.backedOff ?? 0) + 1;
2625
+ const at = ledger.row(item.rel)?.nextAttemptAt;
2626
+ if (Number.isFinite(at)) soonestRetryAt = Math.min(soonestRetryAt, at as number);
2265
2627
  continue;
2266
2628
  }
2267
2629
  seen += 1;
2268
- const before = {
2269
- failed: out.failed.length,
2270
- pushed: out.pushed.length,
2271
- pulled: out.pulled.length,
2272
- };
2273
- const handled = await applyOne(item, out, budget);
2274
- if (handled) moved += 1;
2275
- // Arm or clear this path's window from what the pass actually did with
2276
- // it. A rate limit is excluded: that is the DOOR's state, not this
2277
- // path's, and punishing the file for it would push a whole project into
2278
- // backoff for something none of its files did.
2279
- if (hitRateLimit === null && formatRefused === null) {
2280
- if (out.failed.length > before.failed) {
2281
- const delay = ledger.noteAttemptFailed(item.rel, now());
2282
- log.warn?.(
2283
- `[sync/files] ${item.rel}: backing off ${Math.round(delay / 1000)}s before the next attempt`
2284
- );
2285
- } else if (
2286
- out.pushed.length > before.pushed ||
2287
- out.pulled.length > before.pulled ||
2288
- handled
2630
+ if (item.decision.action === 'pull' && !hashesInFlight.has(item.remoteHash ?? '')) {
2631
+ // Room in the pool: one until the probe came back, then the pacer's width.
2632
+ while (
2633
+ inFlight.size >= (probed ? pacer.limit() : 1) ||
2634
+ (inFlight.size > 0 && bufferedInFlight + buffered(item) > MAX_BUFFERED_IN_FLIGHT_BYTES)
2289
2635
  ) {
2290
- ledger.noteAttemptOk(item.rel);
2636
+ await Promise.race(inFlight);
2637
+ if (wall()) break;
2291
2638
  }
2639
+ if (wall()) {
2640
+ seen -= 1;
2641
+ break;
2642
+ }
2643
+ const hash = item.remoteHash ?? '';
2644
+ const held = buffered(item);
2645
+ hashesInFlight.add(hash);
2646
+ bufferedInFlight += held;
2647
+ const p: Promise<void> = run(item).finally(() => {
2648
+ inFlight.delete(p);
2649
+ hashesInFlight.delete(hash);
2650
+ bufferedInFlight -= held;
2651
+ });
2652
+ inFlight.add(p);
2653
+ continue;
2292
2654
  }
2293
- // A RATE LIMIT ENDS THE PASS. Every other refusal is about one file and
2294
- // the next one is worth trying; this one is about the door, and the
2295
- // remaining requests would do nothing but hold it shut for longer.
2296
- // (A cast: TS cannot see the assignment inside `refusal()`.)
2297
- const refusedFormat = formatRefused as { formatVersion: number | null } | null;
2298
- if (refusedFormat !== null) {
2299
- // ONE notification, and the pass ends: every other write would meet
2300
- // the same door. No backoff is armed (the file did nothing wrong).
2301
- opts.onFormatRefused?.(refusedFormat.formatVersion);
2302
- out.formatRefused = refusedFormat;
2303
- log.warn?.(
2304
- `[sync/files] the project now uses a newer file format than this build writes; nothing more goes up until Maude is updated (${work.length - seen} path(s) still to do).`
2305
- );
2306
- break;
2307
- }
2308
- if (authRefused) {
2309
- // ONE notification for the whole pass. `renewCredentialNow()` is
2310
- // single-flight with a 60 s floor, so 803 refused paths collapse to one
2311
- // renewal — but there is no reason to call it 803 times to find out.
2312
- opts.onAuthFailure?.(item.rel, 401);
2313
- out.authRefused = true;
2314
- log.warn?.(
2315
- `[sync/files] the workspace did not accept this connection; asking for a fresh credential and stopping this pass (${work.length - seen} path(s) still to do).`
2316
- );
2317
- break;
2318
- }
2319
- if (hitRateLimit !== null) {
2320
- holdIfRateLimited(out, work.length - seen);
2655
+ // Anything that is not a plain download — or a second copy of bytes already on their way —
2656
+ // runs alone, in order.
2657
+ await drain();
2658
+ if (wall()) {
2659
+ seen -= 1;
2321
2660
  break;
2322
2661
  }
2662
+ await run(item);
2663
+ }
2664
+ await drain();
2665
+ sweepStaleParts(
2666
+ new Set(work.map((w) => w.remoteHash).filter((h): h is string => typeof h === 'string'))
2667
+ );
2668
+
2669
+ // A RATE LIMIT ENDS THE PASS. Every other refusal is about one file and
2670
+ // the next one is worth trying; this one is about the door, and the
2671
+ // remaining requests would do nothing but hold it shut for longer.
2672
+ // (A cast: TS cannot see the assignment inside `refusal()`.)
2673
+ const refusedFormat = formatRefused as { formatVersion: number | null } | null;
2674
+ if (refusedFormat !== null) {
2675
+ // ONE notification, and the pass ends: every other write would meet
2676
+ // the same door. No backoff is armed (the file did nothing wrong).
2677
+ opts.onFormatRefused?.(refusedFormat.formatVersion);
2678
+ out.formatRefused = refusedFormat;
2679
+ log.warn?.(
2680
+ `[sync/files] the project now uses a newer file format than this build writes; nothing more goes up until Maude is updated (${work.length - seen} path(s) still to do).`
2681
+ );
2682
+ } else if (authRefused) {
2683
+ // ONE notification for the whole pass. `renewCredentialNow()` is
2684
+ // single-flight with a 60 s floor, so 803 refused paths collapse to one
2685
+ // renewal — but there is no reason to call it 803 times to find out.
2686
+ opts.onAuthFailure?.(out.failed.at(-1)?.rel ?? '', 401);
2687
+ out.authRefused = true;
2688
+ log.warn?.(
2689
+ `[sync/files] the workspace did not accept this connection; asking for a fresh credential and stopping this pass (${work.length - seen} path(s) still to do).`
2690
+ );
2691
+ } else if (hitRateLimit !== null) {
2692
+ holdIfRateLimited(out, work.length - seen);
2693
+ }
2694
+
2695
+ // ADAPT THE WIDTH for the next pass (#204): a wall halves it, storage misses already stepped it
2696
+ // down one by one, and a pass that moved a pool's worth of files cleanly earns one step up.
2697
+ const metWall = hitRateLimit as { cause: string } | null;
2698
+ if (metWall !== null && metWall.cause === 'hub-asked') {
2699
+ pacer.onBackpressure();
2700
+ } else if (!out.storageMisses && out.pulled.length >= pacer.limit() && !wall()) {
2701
+ pacer.onCleanPass();
2702
+ }
2703
+ if (Number.isFinite(soonestRetryAt)) {
2704
+ out.nextAttemptInMs = Math.max(0, soonestRetryAt - now());
2323
2705
  }
2324
2706
  if (out.pushed.length > 0 || out.pulled.length > 0) opts.onProgress?.();
2325
2707
 
@@ -2407,7 +2789,7 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2407
2789
  out.budgetExhausted = true;
2408
2790
  return false;
2409
2791
  }
2410
- const got = await fetchVerified(rel, remoteHash, budget.remaining() + claim);
2792
+ const got = await fetchVerified(rel, remoteHash, budget.remaining() + claim, claim);
2411
2793
  if (!got.ok) {
2412
2794
  if (got.overCap && budget.remaining() + claim < MAX_FILE_BYTES) {
2413
2795
  out.budgetExhausted = true;
@@ -2445,7 +2827,18 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2445
2827
  out.budgetExhausted = true;
2446
2828
  return false;
2447
2829
  }
2448
- const got = await fetchVerified(rel, remoteHash, budget.remaining() + claim);
2830
+ const got = await fetchVerified(rel, remoteHash, budget.remaining() + claim, claim);
2831
+ if (!got.ok && got.storageMiss) {
2832
+ // NOT A FAILURE AND NOT DELIVERED (#204): the hub is still fetching these bytes from its
2833
+ // bucket. The row keeps its state (still on its way) and the path waits out a backoff
2834
+ // window before it is asked again — never at once, which only queues another fill behind
2835
+ // the one already running. Its byte reservation stays spent, like any failed transfer's:
2836
+ // a budget that refunds is one a hub can spin.
2837
+ out.storageMisses = (out.storageMisses ?? 0) + 1;
2838
+ soonestRetryAt = Math.min(soonestRetryAt, now() + ledger.noteAttemptFailed(rel, now()));
2839
+ pacer.onStorageMiss();
2840
+ return false;
2841
+ }
2449
2842
  if (!got.ok) {
2450
2843
  out.failed.push({ rel, reason: got.reason });
2451
2844
  ledger.setState(rel, 'stuck', { reason: got.reason });
@@ -2597,7 +2990,7 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2597
2990
  });
2598
2991
  return false;
2599
2992
  }
2600
- const got = await fetchVerified(rel, remoteHash, budget.remaining() + claim);
2993
+ const got = await fetchVerified(rel, remoteHash, budget.remaining() + claim, claim);
2601
2994
  if (!got.ok) {
2602
2995
  out.failed.push({ rel, reason: got.reason });
2603
2996
  if (got.overCap && budget.remaining() + claim < MAX_FILE_BYTES) {
@@ -2824,9 +3217,13 @@ function referencedAssetNames(designRoot: string): Set<string> {
2824
3217
  return out;
2825
3218
  }
2826
3219
 
2827
- /** 0 = a referenced asset (front of the queue), 1 = everything else. */
2828
- function rank(rel: string, referenced: Set<string>): number {
3220
+ /**
3221
+ * 0 = the open canvas's own files, imports and assets (#204), 1 = an annotation-referenced asset,
3222
+ * 2 = everything else.
3223
+ */
3224
+ function rank(rel: string, referenced: Set<string>, wanted: ReadonlySet<string>): number {
3225
+ if (wanted.has(rel)) return 0;
2829
3226
  const slash = rel.lastIndexOf('/');
2830
3227
  const base = slash === -1 ? rel : rel.slice(slash + 1);
2831
- return referenced.has(base) ? 0 : 1;
3228
+ return referenced.has(base) ? 1 : 2;
2832
3229
  }