@1agh/maude 1.7.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/apps/studio/acp/bridge.ts +15 -2
  2. package/apps/studio/acp/login-state.ts +1 -0
  3. package/apps/studio/acp/probe.ts +52 -1
  4. package/apps/studio/api.ts +431 -39
  5. package/apps/studio/asset-upload.ts +174 -0
  6. package/apps/studio/assets-s3.ts +37 -2
  7. package/apps/studio/bin/_curl-local.mjs +7 -0
  8. package/apps/studio/bin/_pdf-playwright.mjs +22 -1
  9. package/apps/studio/bin/_png-playwright.mjs +20 -1
  10. package/apps/studio/bin/_region.mjs +92 -0
  11. package/apps/studio/bin/annotate.mjs +16 -7
  12. package/apps/studio/bin/read-annotations.mjs +62 -4
  13. package/apps/studio/canvas-build.ts +59 -4
  14. package/apps/studio/canvas-lib.tsx +48 -1
  15. package/apps/studio/canvas-shell.tsx +28 -4
  16. package/apps/studio/client/app.jsx +441 -15903
  17. package/apps/studio/client/canvas-url.js +9 -0
  18. package/apps/studio/client/dialogs/asset-picker.jsx +331 -0
  19. package/apps/studio/client/dialogs/command-palette.jsx +112 -0
  20. package/apps/studio/client/dialogs/export-dialog.jsx +782 -0
  21. package/apps/studio/client/dialogs/help-modal.jsx +324 -0
  22. package/apps/studio/client/dialogs/shortcuts-overlay.jsx +144 -0
  23. package/apps/studio/client/embed-view.jsx +284 -0
  24. package/apps/studio/client/embed.js +101 -0
  25. package/apps/studio/client/export-center.jsx +2 -0
  26. package/apps/studio/client/github.js +36 -3
  27. package/apps/studio/client/hooks/use-canvas-bridge.jsx +2150 -0
  28. package/apps/studio/client/hooks/use-git-actions.jsx +236 -0
  29. package/apps/studio/client/hooks/use-keyboard-shortcuts.jsx +297 -0
  30. package/apps/studio/client/hooks/use-palette-and-panels.jsx +474 -0
  31. package/apps/studio/client/hooks/use-photo-and-timeline.jsx +901 -0
  32. package/apps/studio/client/hooks/use-project-data.jsx +90 -0
  33. package/apps/studio/client/hooks/use-shell-core.jsx +1212 -0
  34. package/apps/studio/client/hooks/use-tabs.jsx +723 -0
  35. package/apps/studio/client/hooks/use-web-socket.jsx +13 -0
  36. package/apps/studio/client/inspector/artboard-knobs.jsx +456 -0
  37. package/apps/studio/client/inspector/color-picker.jsx +196 -0
  38. package/apps/studio/client/inspector/color.js +92 -0
  39. package/apps/studio/client/inspector/css-knobs.jsx +1720 -0
  40. package/apps/studio/client/inspector/css-vocab.jsx +131 -0
  41. package/apps/studio/client/inspector/ds-tokens.js +90 -0
  42. package/apps/studio/client/inspector/grid-tracks-editor.jsx +97 -0
  43. package/apps/studio/client/inspector/inspect-computed.jsx +68 -0
  44. package/apps/studio/client/inspector/inspector-panel.jsx +769 -0
  45. package/apps/studio/client/inspector/layers.jsx +322 -0
  46. package/apps/studio/client/inspector/selection.js +65 -0
  47. package/apps/studio/client/inspector/token-popover.jsx +301 -0
  48. package/apps/studio/client/menus/menubar.jsx +856 -0
  49. package/apps/studio/client/report-bug.jsx +8 -2
  50. package/apps/studio/client/selection-scope.js +40 -0
  51. package/apps/studio/client/shell/banners.jsx +272 -0
  52. package/apps/studio/client/shell/collapsed-rail.jsx +23 -0
  53. package/apps/studio/client/shell/comments-panel.jsx +177 -0
  54. package/apps/studio/client/shell/constants.js +60 -0
  55. package/apps/studio/client/shell/dock.jsx +131 -0
  56. package/apps/studio/client/shell/icons.jsx +370 -0
  57. package/apps/studio/client/shell/status-bar.jsx +215 -0
  58. package/apps/studio/client/shell/util.js +332 -0
  59. package/apps/studio/client/shell/viewport.jsx +254 -0
  60. package/apps/studio/client/system/system-view.jsx +255 -0
  61. package/apps/studio/client/tree/tree.jsx +1243 -0
  62. package/apps/studio/comments-overlay.tsx +6 -4
  63. package/apps/studio/config.schema.json +5 -0
  64. package/apps/studio/context.ts +20 -0
  65. package/apps/studio/dist/client.bundle.js +2728 -2728
  66. package/apps/studio/dist/comment-mount.js +2 -2
  67. package/apps/studio/embed-origins.ts +52 -0
  68. package/apps/studio/export-dialog.tsx +55 -3
  69. package/apps/studio/exporters/_browser-bundles.ts +21 -2
  70. package/apps/studio/exporters/format-scopes.ts +11 -3
  71. package/apps/studio/exporters/index.ts +17 -2
  72. package/apps/studio/exporters/jobs.ts +91 -23
  73. package/apps/studio/exporters/pdf.ts +10 -2
  74. package/apps/studio/exporters/png.ts +10 -2
  75. package/apps/studio/exporters/scope.ts +89 -15
  76. package/apps/studio/format.ts +296 -0
  77. package/apps/studio/generation/runtime-probe.ts +1 -1
  78. package/apps/studio/git/service.ts +1 -0
  79. package/apps/studio/http.ts +399 -36
  80. package/apps/studio/input-router.tsx +7 -1
  81. package/apps/studio/path-containment.ts +72 -0
  82. package/apps/studio/paths.ts +14 -1
  83. package/apps/studio/read-only-mode.ts +53 -0
  84. package/apps/studio/server.ts +123 -25
  85. package/apps/studio/sync/accepted-link.ts +6 -0
  86. package/apps/studio/sync/agent.ts +9 -1
  87. package/apps/studio/sync/cold-start-apply.ts +29 -4
  88. package/apps/studio/sync/cold-start.ts +78 -0
  89. package/apps/studio/sync/file-plane.ts +61 -1
  90. package/apps/studio/sync/format-sync.ts +160 -0
  91. package/apps/studio/sync/index.ts +208 -23
  92. package/apps/studio/sync/journal-client.ts +25 -5
  93. package/apps/studio/sync/migrate-seed.ts +8 -1
  94. package/apps/studio/sync/park.ts +39 -0
  95. package/apps/studio/sync/presentation.ts +9 -3
  96. package/apps/studio/sync/status.ts +2 -0
  97. package/apps/studio/sync/transaction-client.ts +130 -13
  98. package/apps/studio/sync/writer-registry.ts +5 -0
  99. package/apps/studio/ui-prefs.ts +95 -10
  100. package/apps/studio/use-canvas-media-drop.tsx +8 -28
  101. package/apps/studio/whats-new.json +36 -0
  102. package/apps/studio/ws.ts +19 -4
  103. package/cli/bin/claude-design-server.mjs +0 -0
  104. package/cli/commands/design.mjs +9 -2
  105. package/cli/commands/hub-workspace.mjs +25 -0
  106. package/cli/lib/workspace-plan.mjs +51 -0
  107. package/package.json +11 -9
  108. package/plugins/design/templates/_shell.html +58 -0
@@ -69,16 +69,26 @@ import { createEchoGuard, hashBytes } from './echo-guard.ts';
69
69
  import { createFileLedger } from './file-ledger.ts';
70
70
  import { createFilePlane, MAX_DORUCEKA_ROWS } from './file-plane.ts';
71
71
  import { type FilePullResult, pullFiles } from './file-pull.ts';
72
+ import {
73
+ declaredFormat,
74
+ formatFromHub,
75
+ formatGated,
76
+ isFormatFirstSight,
77
+ learnHubFormat,
78
+ withFormatHeader,
79
+ withFormatParam,
80
+ } from './format-sync.ts';
72
81
  import { createFsReader, type FsReader } from './fs-mirror.ts';
73
82
  import { type HubDocRow, hubHolds, indexHubDocs } from './hub-listing.ts';
74
83
  import { getHubRecord } from './hubs-config.ts';
75
84
  import { loadJournal, type SyncJournal } from './journal.ts';
76
- import { hasAnnotationsV2, hasLedger, hubCapabilities } from './journal-client.ts';
85
+ import { hasAnnotationsV2, hasLedger, hubHealth } from './journal-client.ts';
77
86
  import { isLoopbackHost } from './loopback.ts';
78
87
  import { migrateFlatFallback } from './migrate-flat-fallback.ts';
79
88
  import { migrateSeed } from './migrate-seed.ts';
80
89
  import { ORIGINS } from './origins.ts';
81
90
  import {
91
+ fileLaneBusy,
82
92
  initialParkState,
83
93
  isLocalWorkRel,
84
94
  PARK_TIMINGS,
@@ -477,6 +487,8 @@ export type ProviderFactory = (args: {
477
487
  * `getDoc`. Default factory: `args.document ?? new Y.Doc()`.
478
488
  */
479
489
  document?: Y.Doc;
490
+ /** V2-1.12 §5.4 — the file format this studio writes (`maude-format`). */
491
+ format?: number;
480
492
  }) => SyncProvider | Promise<SyncProvider>;
481
493
 
482
494
  export interface SyncRuntime {
@@ -850,6 +862,60 @@ export function createSyncRuntime(
850
862
  return null;
851
863
  }
852
864
 
865
+ // ---- PROJECT FILE FORMAT (V2-1.12 §5.4 / §5.6, V2-2.18) ------------------
866
+ //
867
+ // The format view the sync side reasons about names THIS link's hub (a cell's
868
+ // pairing link is not in the tenant's config.json, but it is still the hub).
869
+ // A getter: `config.json` hot-reloads (fs:json → reloadConfig), and a
870
+ // marker written there must reach this view without a restart.
871
+ const formatCtx = {
872
+ get cfg() {
873
+ return { formatVersion: ctx.cfg.formatVersion, linkedHub: { url: linkedHub.url } };
874
+ },
875
+ paths: { designRoot: ctx.paths.designRoot },
876
+ };
877
+ /** The format this studio writes in — declared on every request + socket. */
878
+ const declared = (): number => declaredFormat(formatCtx);
879
+ /** True while this build does not edit the project: nothing goes up. */
880
+ const outboundPaused = (): boolean => formatGated(formatCtx);
881
+ /** Every studio → hub HTTP call declares the format (one wrapper). */
882
+ const hubFetch = withFormatHeader(undefined, declared);
883
+ /** §5.9 — set when this run first sees the hub's format raised past the mirror. */
884
+ let formatFirstSight = false;
885
+ /** Canvases whose first-sight cold start already ran (the row is one-shot). */
886
+ const firstSightSpent = new Set<string>();
887
+ const firstSightFor = (slug: string) => (): boolean => {
888
+ if (!formatFirstSight || firstSightSpent.has(slug)) return false;
889
+ firstSightSpent.add(slug);
890
+ return true;
891
+ };
892
+ /**
893
+ * What the hub said about the format (`/health`, `maude.mode`, bootstrap).
894
+ * First sight is judged BEFORE the mirror is written; a change makes shells
895
+ * refetch `/_config`, so the gate and the banner engage.
896
+ */
897
+ const noteHubFormatSeen = (formatVersion: number | null, epoch?: number): void => {
898
+ if (formatVersion === null) return;
899
+ if (isFormatFirstSight(formatCtx, formatVersion)) formatFirstSight = true;
900
+ let changed = false;
901
+ try {
902
+ changed = learnHubFormat(formatCtx, {
903
+ formatVersion,
904
+ ...(typeof epoch === 'number' ? { epoch } : {}),
905
+ });
906
+ } catch (err) {
907
+ console.warn(
908
+ `[sync] could not record the project format: ${String((err as Error)?.message ?? err).slice(0, 200)}`
909
+ );
910
+ }
911
+ if (changed) {
912
+ console.log(
913
+ `[sync] the project format is ${formatVersion}${outboundPaused() ? ' — newer than this build writes; open to look at, nothing goes up until Maude is updated' : ''}`
914
+ );
915
+ ctx.bus.emit('config-updated');
916
+ }
917
+ };
918
+
853
919
  // DDR-192 §5 — slug → wire documentName. Only the WIRE name is namespaced;
854
920
  // every local map (providers, agents, projections, _history/) stays keyed by
855
921
  // the flat slug. Opt-in for now (see createDocNameResolver's rollout rule);
@@ -950,10 +1016,13 @@ export function createSyncRuntime(
950
1016
  designRoot: ctx.paths.designRoot,
951
1017
  hubUrl: linkedHub.url,
952
1018
  token: () => token,
1019
+ fetchImpl: hubFetch,
953
1020
  })
954
1021
  : null;
955
1022
  const projectConfigUnsub = projectConfigPusher
956
- ? ctx.bus.on('config-updated', () => void projectConfigPusher.push())
1023
+ ? ctx.bus.on('config-updated', () => {
1024
+ if (!outboundPaused()) void projectConfigPusher.push();
1025
+ })
957
1026
  : null;
958
1027
 
959
1028
  // DDR-102 — the default factory multiplexes every provider over ONE shared
@@ -1016,13 +1085,21 @@ export function createSyncRuntime(
1016
1085
  token: () => token,
1017
1086
  designRoot: ctx.paths.designRoot,
1018
1087
  docNameFor: (slug) => docNameFor(slug),
1019
- fetchImpl: opts.transactionFetch,
1088
+ fetchImpl: withFormatHeader(opts.transactionFetch, declared),
1089
+ paused: outboundPaused,
1090
+ declaredFormat: declared,
1020
1091
  retryMs: opts.transactionRetryMs,
1021
1092
  onStats: (stats) => statusStore?.updateAccepted?.(stats),
1022
1093
  onStage: (summary) => statusStore?.updateAiAction?.(summary),
1023
1094
  onBootstrap: (b) => {
1095
+ noteHubFormatSeen(
1096
+ formatFromHub(b),
1097
+ typeof (b as { epoch?: unknown }).epoch === 'number'
1098
+ ? (b as { epoch: number }).epoch
1099
+ : undefined
1100
+ );
1024
1101
  noteProjectConfig(b.projectConfig);
1025
- void projectConfigPusher?.push();
1102
+ if (!outboundPaused()) void projectConfigPusher?.push();
1026
1103
  // F3 S17 — a save made as the socket died is held (the connection
1027
1104
  // was not writable). After the reconnect the handshake re-admits the
1028
1105
  // socket read-only BEFORE this peer learns the project now takes
@@ -1146,11 +1223,13 @@ export function createSyncRuntime(
1146
1223
  legacyPushAgain = true;
1147
1224
  return;
1148
1225
  }
1226
+ if (outboundPaused()) return; // V2-1.12 §5.6 — nothing goes up while gated
1149
1227
  legacyPushRunning = true;
1150
1228
  legacyPushCancel = false;
1151
1229
  pushAssets({
1152
1230
  designRoot: ctx.paths.designRoot,
1153
1231
  hubUrl,
1232
+ fetchImpl: hubFetch,
1154
1233
  // Read at call time — silent renewal swaps the credential in place.
1155
1234
  token: () => token,
1156
1235
  canvasGroups: ctx.cfg.canvasGroups,
@@ -1398,14 +1477,19 @@ export function createSyncRuntime(
1398
1477
  * `start()` only where parking is possible.
1399
1478
  */
1400
1479
  let parkedNow = false;
1480
+ /** When the file plane last delivered something — `fileLaneBusy`'s clock. */
1481
+ let lastFileProgressAt = 0;
1401
1482
  let parkDispatch: ((event: ParkEvent) => void) | null = null;
1402
1483
  let parkTimer: ReturnType<typeof setInterval> | null = null;
1403
1484
  let parkProbe: AbortController | null = null;
1404
1485
  let parkUiUnsub: (() => void) | null = null;
1405
1486
  const parkClock = opts.park?.now ?? (() => Date.now());
1406
1487
  /** A local edit, a doc update, a click: news for the park machine. */
1407
- const noteParkActivity = (type: 'localEdit' | 'uiActivity'): void => {
1408
- parkDispatch?.({ type, now: parkClock() });
1488
+ let lastActivitySource = 'start';
1489
+ const noteParkActivity = (type: 'localEdit' | 'uiActivity', source: string): void => {
1490
+ if (!parkDispatch) return;
1491
+ lastActivitySource = source;
1492
+ parkDispatch({ type, now: parkClock() });
1409
1493
  };
1410
1494
  /**
1411
1495
  * Cancels the boot-time capability probe. A `stop()` that leaves a `/health`
@@ -2786,7 +2870,7 @@ export function createSyncRuntime(
2786
2870
  // pass. `fs-watch.ts` still reports `_state/` to every OTHER subscriber.
2787
2871
  // Somebody's work, not the studio talking to itself: it keeps a desktop
2788
2872
  // awake, and unparks a parked one BEFORE the pass below is asked for.
2789
- if (isLocalWorkRel(rel)) noteParkActivity('localEdit');
2873
+ if (isLocalWorkRel(rel)) noteParkActivity('localEdit', `file ${rel.split('\\').join('/')}`);
2790
2874
  if (fileLedger && isLocalWorkRel(rel)) {
2791
2875
  fileLedger.noteChanged(rel.split('\\').join('/'));
2792
2876
  schedulePlanePass();
@@ -3282,6 +3366,7 @@ export function createSyncRuntime(
3282
3366
  }
3283
3367
  },
3284
3368
  onConflict: (info) => store.addConflict(info),
3369
+ formatFirstSight: firstSightFor(canvas.slug),
3285
3370
  // An unmergeable local candidate: keep both, and let the projection
3286
3371
  // report and hold it from the shared base (T2).
3287
3372
  onHold: (base) => projection.adoptBase(base),
@@ -3630,12 +3715,13 @@ export function createSyncRuntime(
3630
3715
  token,
3631
3716
  documentName: docNameFor(canvas.slug),
3632
3717
  document,
3718
+ format: declared(),
3633
3719
  });
3634
3720
  providers.set(canvas.slug, provider);
3635
3721
  // ANY change to a synced document is activity — a local edit unparks a
3636
3722
  // parked desktop, and a peer's edit arriving keeps a live collaboration
3637
3723
  // connected rather than parking under it.
3638
- const onDocUpdate = (): void => noteParkActivity('localEdit');
3724
+ const onDocUpdate = (): void => noteParkActivity('localEdit', `canvas ${canvas.slug}`);
3639
3725
  provider.document.on('update', onDocUpdate);
3640
3726
  noteDetach(statusDetaches, canvas.slug, () => provider.document.off('update', onDocUpdate));
3641
3727
  // Fix 5 (sync RCA 2026-08-10): stamp the canvas path BEFORE the
@@ -3842,12 +3928,14 @@ export function createSyncRuntime(
3842
3928
  }
3843
3929
  : {}),
3844
3930
  // A write the hub would drop is held, never made (see isWritable).
3931
+ // V2-1.12 §5.6 — and nothing goes up while the project uses a
3932
+ // format this build does not write (pulls continue).
3845
3933
  ...(provider.isWritable
3846
3934
  ? {
3847
- canWriteDoc: () => provider.isWritable?.() !== false,
3935
+ canWriteDoc: () => provider.isWritable?.() !== false && !outboundPaused(),
3848
3936
  onWriteBlocked: () => void refreshAcceptedMode(),
3849
3937
  }
3850
- : {}),
3938
+ : { canWriteDoc: () => !outboundPaused() }),
3851
3939
  onRecovered: () => store.clearSourceConflict(canvas.slug),
3852
3940
  onConflict: (info) => {
3853
3941
  store.addConflict(info);
@@ -3909,6 +3997,7 @@ export function createSyncRuntime(
3909
3997
  }
3910
3998
  },
3911
3999
  onConflict: (info) => store.addConflict(info),
4000
+ formatFirstSight: firstSightFor(canvas.slug),
3912
4001
  });
3913
4002
  agent.start();
3914
4003
  agents.set(canvas.slug, agent);
@@ -3923,6 +4012,28 @@ export function createSyncRuntime(
3923
4012
  // THE HUB SAYS THE SAVE MODE CHANGED — on this document's own
3924
4013
  // socket, ahead of closing it, so the switch is learned before any
3925
4014
  // further local change is made (DDR-241 §7 switch ordering).
4015
+ // V2-1.12 §5.5 — the same envelope carries the project FORMAT.
4016
+ // Heard on every link (legacy and accepted), since a flip is
4017
+ // independent of the save mode.
4018
+ if (provider.onStateless) {
4019
+ noteDetach(
4020
+ statusDetaches,
4021
+ canvas.slug,
4022
+ provider.onStateless((payload) => {
4023
+ let msg: { type?: unknown; formatVersion?: unknown; epoch?: unknown } | null =
4024
+ null;
4025
+ try {
4026
+ msg = JSON.parse(payload);
4027
+ } catch {
4028
+ return;
4029
+ }
4030
+ if (msg?.type !== 'maude.mode') return;
4031
+ const fv = formatFromHub(msg);
4032
+ if (fv !== null)
4033
+ noteHubFormatSeen(fv, typeof msg.epoch === 'number' ? msg.epoch : undefined);
4034
+ })
4035
+ );
4036
+ }
3926
4037
  if (acceptedLink && provider.onStateless) {
3927
4038
  noteDetach(
3928
4039
  statusDetaches,
@@ -4211,7 +4322,16 @@ export function createSyncRuntime(
4211
4322
  });
4212
4323
  return;
4213
4324
  }
4214
- void stateDocumentGone(linkedHub.url, token, docNameFor(slug), { revive }).then((ok) => {
4325
+ if (outboundPaused()) {
4326
+ console.warn(
4327
+ `[sync] not telling the project that ${slug} was ${revive ? 're-created' : 'deleted'}: it now uses a newer file format than this build writes.`
4328
+ );
4329
+ return;
4330
+ }
4331
+ void stateDocumentGone(linkedHub.url, token, docNameFor(slug), {
4332
+ revive,
4333
+ fetchImpl: hubFetch,
4334
+ }).then((ok) => {
4215
4335
  if (!ok) {
4216
4336
  console.warn(
4217
4337
  `[sync] could not tell the project that ${slug} was ${revive ? 're-created' : 'deleted'} — it stays ${revive ? 'buried' : 'in the project'} for other peers until this succeeds.`
@@ -4780,18 +4900,47 @@ export function createSyncRuntime(
4780
4900
  const parkFetch = opts.park?.fetch ?? fetch;
4781
4901
  let parkState: ParkState = initialParkState({ now: parkClock(), eligible: true });
4782
4902
  /** Outbound work that must land before the sockets may close. */
4783
- const hasPendingWork = (): boolean => {
4784
- if (planePassInFlight || filePassTimer !== null || remotePollSoonTimer !== null) {
4785
- return true;
4786
- }
4787
- for (const p of providers.values()) {
4903
+ /**
4904
+ * Why the link must stay up right now, or null. A reason, not a flag, so
4905
+ * an idle desktop that cannot park SAYS why (the v1.6.13 night was
4906
+ * diagnosable only from the cloud's request log).
4907
+ *
4908
+ * Every lane is judged by whether it is MOVING, not by whether something
4909
+ * is unfinished: a document whose change the hub never acknowledges, or
4910
+ * a file that never lands, would otherwise hold a cell awake forever. A
4911
+ * stalled lane resumes on the next edit, click, change signal or the 6 h
4912
+ * backstop.
4913
+ */
4914
+ const unsyncedSince = new Map<string, number>();
4915
+ const pendingReason = (): string | null => {
4916
+ if (planePassInFlight || filePassTimer !== null) return 'a file pass is running';
4917
+ if (remotePollSoonTimer !== null) return 'a catch-up poll is due';
4918
+ const now = Date.now();
4919
+ for (const [slug, p] of providers) {
4788
4920
  if ((p as unknown as { hasUnsyncedChanges?: boolean }).hasUnsyncedChanges === true) {
4789
- return true;
4921
+ const since = unsyncedSince.get(slug) ?? now;
4922
+ unsyncedSince.set(slug, since);
4923
+ if (now - since < timings.afterMs) return `canvas ${slug} has unsent changes`;
4924
+ } else {
4925
+ unsyncedSince.delete(slug);
4790
4926
  }
4791
4927
  }
4928
+ if (
4929
+ fileLedger &&
4930
+ fileLaneBusy(fileLedger.rows(), {
4931
+ now,
4932
+ lastProgressAt: lastFileProgressAt,
4933
+ windowMs: timings.afterMs,
4934
+ })
4935
+ ) {
4936
+ return 'files are still being delivered';
4937
+ }
4792
4938
  // Saves, uploads and retries the other lanes report (attacker F1).
4793
- return hasSelfRetryingWork(store.get());
4939
+ return hasSelfRetryingWork(store.get()) ? 'a save or upload is still in flight' : null;
4794
4940
  };
4941
+ const hasPendingWork = (): boolean => pendingReason() !== null;
4942
+ let lastHeldReason: string | null = null;
4943
+ let lastActivityReportAt = parkClock();
4795
4944
  const doPark = (): void => {
4796
4945
  parkedNow = true;
4797
4946
  // Flush what we know; the pending-work check already proved nothing is
@@ -4898,10 +5047,35 @@ export function createSyncRuntime(
4898
5047
  run(step.effects);
4899
5048
  };
4900
5049
  parkDispatch = dispatch;
4901
- parkUiUnsub = ctx.bus.on('ui:active', () => noteParkActivity('uiActivity'));
5050
+ parkUiUnsub = ctx.bus.on('ui:active', () => noteParkActivity('uiActivity', 'studio input'));
4902
5051
  parkTimer = setInterval(() => {
4903
5052
  const now = parkClock();
4904
- dispatch({ type: 'pendingChanged', pending: hasPendingWork(), now });
5053
+ const reason = pendingReason();
5054
+ // Idle long enough to park, but something holds the link: say what,
5055
+ // once per reason, so the next "why did it stay awake" has an answer
5056
+ // on this machine.
5057
+ if (
5058
+ reason &&
5059
+ parkState.phase === 'active' &&
5060
+ now - parkState.lastActivityAt >= timings.afterMs &&
5061
+ reason !== lastHeldReason
5062
+ ) {
5063
+ console.log(`[sync] idle, but staying connected: ${reason}.`);
5064
+ }
5065
+ lastHeldReason = reason;
5066
+ // A desktop that never even gets idle says what keeps waking it — at
5067
+ // most every 30 min, so a working session costs two log lines an hour.
5068
+ if (
5069
+ parkState.phase === 'active' &&
5070
+ now - parkState.lastActivityAt < timings.afterMs &&
5071
+ now - lastActivityReportAt >= 30 * 60_000
5072
+ ) {
5073
+ lastActivityReportAt = now;
5074
+ console.log(
5075
+ `[sync] park: active — last activity ${lastActivitySource}, ${Math.round((now - parkState.lastActivityAt) / 1000)} s ago.`
5076
+ );
5077
+ }
5078
+ dispatch({ type: 'pendingChanged', pending: reason !== null, now });
4905
5079
  dispatch({ type: 'tick', now });
4906
5080
  }, opts.park?.tickMs ?? 15_000);
4907
5081
  parkTimer.unref?.();
@@ -4922,9 +5096,11 @@ export function createSyncRuntime(
4922
5096
  // its job is healing the UI rather than triggering pulls.
4923
5097
  if (!cellPairing && ctx.cfg.linkedHub?.fileEvents !== false) {
4924
5098
  fileEventsProbe = new AbortController();
4925
- void hubCapabilities({ hubUrl: linkedHub.url, signal: fileEventsProbe.signal })
4926
- .then((caps) => {
5099
+ void hubHealth({ hubUrl: linkedHub.url, signal: fileEventsProbe.signal })
5100
+ .then(({ capabilities: caps, formatVersion: hubFormat }) => {
4927
5101
  if (stopped) return;
5102
+ // V2-1.12 §5.5 — `/health` names the project's format.
5103
+ noteHubFormatSeen(hubFormat);
4928
5104
  // DDR-242 — a hub that predates the annotations-v2 model still keeps
4929
5105
  // boards as SVG: its workspace checkout and kernel would not carry
4930
5106
  // this studio's `.annotations.json` edits. Say so loudly; the
@@ -4964,6 +5140,11 @@ export function createSyncRuntime(
4964
5140
  onAuthFailure: () => {
4965
5141
  void renewCredentialNow();
4966
5142
  },
5143
+ // V2-1.12 §5.4 — a 426 is the FORMAT door, never a credential
5144
+ // failure: mirror what the hub named; nothing is renewed.
5145
+ onFormatRefused: (fv) => noteHubFormatSeen(fv),
5146
+ outboundPaused,
5147
+ fetchImpl: hubFetch,
4967
5148
  // A DELIVERED FILE IS PROGRESS. `renewalsSinceProgress` counted
4968
5149
  // only doc handshakes, and a converged doc lane has none left to
4969
5150
  // land — so during a long seed the cap was reached and the
@@ -4971,6 +5152,7 @@ export function createSyncRuntime(
4971
5152
  // working.
4972
5153
  onProgress: () => {
4973
5154
  renewalsSinceProgress = 0;
5155
+ lastFileProgressAt = Date.now();
4974
5156
  },
4975
5157
  ledger: fileLedger,
4976
5158
  canvasGroups: ctx.cfg.canvasGroups,
@@ -6019,6 +6201,7 @@ export function createDefaultProviderFactory(
6019
6201
  token: string;
6020
6202
  documentName: string;
6021
6203
  document?: Y.Doc;
6204
+ format?: number;
6022
6205
  }): Promise<SyncProvider> => {
6023
6206
  if (!mod) {
6024
6207
  try {
@@ -6032,7 +6215,9 @@ export function createDefaultProviderFactory(
6032
6215
  // Hocuspocus accepts ws:// or wss://; the linked URL is http(s)://, so swap
6033
6216
  // the scheme. The provider also accepts http(s):// and upgrades internally
6034
6217
  // in newer versions, but ws:// is explicit + portable.
6035
- const wsUrl = toWsUrl(args.url);
6218
+ // V2-1.12 §5.4 — the socket declares the writer's file format; the hub
6219
+ // fences a writer of another format read-only.
6220
+ const wsUrl = withFormatParam(toWsUrl(args.url), args.format);
6036
6221
  // A DOCUMENT KEEPS ITS SOCKET; A FULL SOCKET TAKES NO NEW ONES.
6037
6222
  //
6038
6223
  // Hocuspocus (4.3+) closes a socket that has more than 100 documents
@@ -196,6 +196,19 @@ export async function hubCapabilities(opts: {
196
196
  */
197
197
  signal?: AbortSignal;
198
198
  }): Promise<string[] | null> {
199
+ return (await hubHealth(opts)).capabilities;
200
+ }
201
+
202
+ /**
203
+ * The protocol half of `/health` in ONE request: the capabilities above plus
204
+ * the project's file format (V2-1.12 §5.5 — `formatVersion`, null while the
205
+ * hub has not read its store, absent on a hub older than `format-v2`).
206
+ */
207
+ export async function hubHealth(opts: {
208
+ hubUrl: string;
209
+ fetchImpl?: typeof fetch;
210
+ signal?: AbortSignal;
211
+ }): Promise<{ capabilities: string[] | null; formatVersion: number | null }> {
199
212
  const fetchImpl = opts.fetchImpl ?? fetch;
200
213
  const base = opts.hubUrl.replace(/\/+$/, '');
201
214
  try {
@@ -203,12 +216,19 @@ export async function hubCapabilities(opts: {
203
216
  const res = await fetchImpl(`${base}/health`, {
204
217
  signal: opts.signal ? AbortSignal.any([opts.signal, timeout]) : timeout,
205
218
  });
206
- if (!res.ok) return null;
207
- const body = (await res.json()) as { capabilities?: unknown };
208
- if (!Array.isArray(body?.capabilities)) return null;
209
- return body.capabilities.filter((c): c is string => typeof c === 'string').slice(0, 32);
219
+ if (!res.ok) return { capabilities: null, formatVersion: null };
220
+ const body = (await res.json()) as { capabilities?: unknown; formatVersion?: unknown };
221
+ const fv = body?.formatVersion;
222
+ const formatVersion = typeof fv === 'number' && Number.isSafeInteger(fv) && fv >= 1 ? fv : null;
223
+ if (!Array.isArray(body?.capabilities)) return { capabilities: null, formatVersion };
224
+ return {
225
+ capabilities: body.capabilities
226
+ .filter((c): c is string => typeof c === 'string')
227
+ .slice(0, 32),
228
+ formatVersion,
229
+ };
210
230
  } catch {
211
- return null;
231
+ return { capabilities: null, formatVersion: null };
212
232
  }
213
233
  }
214
234
 
@@ -117,10 +117,12 @@ export interface MigrateSeedOptions {
117
117
  * conflict until a later save resolves it (audit 2026-09-13 P0 #1 / T2).
118
118
  */
119
119
  onHold?: (base: string) => void;
120
+ /** V2-1.12 §5.9 — is this the first cold start after a format flip? */
121
+ formatFirstSight?: () => boolean;
120
122
  /** DDR-102 — divergence notification, same contract as the agent's. */
121
123
  onConflict?: (info: {
122
124
  slug: string;
123
- kind: 'cold-start-diverged';
125
+ kind: 'cold-start-diverged' | 'format-flip-local-kept';
124
126
  winner?: 'local' | 'hub';
125
127
  snapshots?: { local?: string; hub?: string };
126
128
  /** DDR-102 fail-closed (F1) — local snapshot didn't land; hub-wins refused. */
@@ -263,12 +265,15 @@ export async function migrateSeed(opts: MigrateSeedOptions): Promise<MigrateSeed
263
265
 
264
266
  // Body resolution via the DDR-102 decision table.
265
267
  const docHtml = doc.getText(Y_SYNC_TYPES.html).toString();
268
+ // V2-1.12 §5.9 — asked ONCE per cold start, used by every lane below.
269
+ const firstSight = opts.formatFirstSight?.() === true;
266
270
  const decision = decideColdStart({
267
271
  localBody: localHtml,
268
272
  docBody: docHtml,
269
273
  journalHash: opts.journal?.get(slug)?.bodyHash ?? null,
270
274
  localMtimeMs: localMtimeMs(paths.html),
271
275
  docBodyEditAtMs: bodyEditAtFromDoc(doc),
276
+ formatFirstSight: firstSight,
272
277
  });
273
278
 
274
279
  /** Rebuild body (+ visually-coupled css) from local, in ONE MIGRATION
@@ -367,6 +372,7 @@ export async function migrateSeed(opts: MigrateSeedOptions): Promise<MigrateSeed
367
372
  localMtimeMs: localMtimeMs(paths.annotations),
368
373
  docEditAtMs: annotationsEditAtFromDoc(doc),
369
374
  bodyWinner: applied.bodyWinner,
375
+ formatFirstSight: firstSight,
370
376
  });
371
377
  if (annDecision.winner === 'local' && localAnnotations !== null) {
372
378
  console.warn(`[sync/${slug}] shared-doc cold-start annotations: ${annDecision.reason}`);
@@ -398,6 +404,7 @@ export async function migrateSeed(opts: MigrateSeedOptions): Promise<MigrateSeed
398
404
  journalHash: opts.journal?.get(slug)?.cssHash ?? null,
399
405
  hash: hashBytes,
400
406
  bodyWinner: applied.bodyWinner,
407
+ formatFirstSight: firstSight,
401
408
  });
402
409
  if (cssDecision.recoveredDuplication) {
403
410
  // Warn, don't snapshot — see the note on the same branch in agent.ts
@@ -286,3 +286,42 @@ export function parseCellState(
286
286
  typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : null;
287
287
  return { kind: 'state', state: p.state, changedAt: num(p.changedAt), at: num(p.at) };
288
288
  }
289
+
290
+ /** Rows already delivered, or parked on something only a person can change. */
291
+ const SETTLED_STATES = new Set([
292
+ 'on-hub',
293
+ 'durable',
294
+ 'at-peer',
295
+ 'ui-healed',
296
+ 'everywhere',
297
+ 'refused',
298
+ 'referenced-but-unoffered',
299
+ 'conflict',
300
+ 'stuck',
301
+ ]);
302
+
303
+ /**
304
+ * Is the file plane still delivering something a park would cut off?
305
+ *
306
+ * - A row being pushed right now always is.
307
+ * - Other outstanding rows (not yet sent, not backed off) are only while the
308
+ * plane is actually making progress: something landed within `windowMs`. A
309
+ * lane that has delivered nothing for that long is stalled, not moving, and
310
+ * holding a cell awake for it buys nothing — it resumes on the next edit,
311
+ * click, change signal or the backstop. (The night after v1.6.13: five
312
+ * `stuck` rows kept Alligators "seeding", and awake, until morning.)
313
+ */
314
+ export function fileLaneBusy(
315
+ rows: Record<string, { state?: string; nextAttemptAt?: number }>,
316
+ opts: { now: number; lastProgressAt: number; windowMs: number }
317
+ ): boolean {
318
+ let outstanding = false;
319
+ for (const row of Object.values(rows)) {
320
+ const state = row.state;
321
+ if (state === 'pushing') return true;
322
+ if (state && SETTLED_STATES.has(state)) continue;
323
+ if (Number.isFinite(row.nextAttemptAt) && (row.nextAttemptAt as number) > opts.now) continue;
324
+ outstanding = true;
325
+ }
326
+ return outstanding && opts.now - opts.lastProgressAt < opts.windowMs;
327
+ }
@@ -701,8 +701,8 @@ function readAiAction(raw: unknown): { state: 'open' | 'held'; canvases: number
701
701
  }
702
702
 
703
703
  /**
704
- * Work that finishes on its own if the link stays up — files or media still
705
- * moving or failed-and-retrying, a save waiting for the project's answer, an
704
+ * Work that finishes on its own if the link stays up — media still moving or
705
+ * failed-and-retrying, a save waiting for the project's answer, an
706
706
  * AI edit in progress. The desktop park waits for it (`sync/park.ts`): closing
707
707
  * the link over it would stop the retry and leave teammates without the work.
708
708
  * Held/blocked items wait on a PERSON, not on time, so they do not block a
@@ -712,7 +712,13 @@ function readAiAction(raw: unknown): { state: 'open' | 'held'; canvases: number
712
712
  export function hasSelfRetryingWork(status: SyncStatusLike | null | undefined): boolean {
713
713
  if (!status) return false;
714
714
  const lanes = readLanes(status);
715
- if (lanes.moving || lanes.failedFiles > 0 || lanes.failedMedia > 0) return true;
715
+ // THE FILE PLANE IS JUDGED FROM ITS LEDGER, not from here (`fileLaneBusy` in
716
+ // sync/park.ts). Its `seeding` phase counts a `stuck` row as remaining, so a
717
+ // project with five rows that never land is "seeding" forever — and reading
718
+ // that as work in flight kept Alligators awake all night after v1.6.13.
719
+ // Only the legacy media lane's own progress is read here.
720
+ const mediaMoving = lanes.moving !== null && 'media' in lanes.moving;
721
+ if (mediaMoving || lanes.failedMedia > 0) return true;
716
722
  if (readAcceptedPending(status.accepted)) return true;
717
723
  const ai = status.aiAction as { state?: unknown } | undefined;
718
724
  return ai?.state === 'open';
@@ -22,6 +22,8 @@ import type { SeedProgress } from './seed-progress.ts';
22
22
  export type ConflictKind =
23
23
  | 'cold-start-hub-wins'
24
24
  | 'cold-start-diverged'
25
+ /** V2-1.12 §5.9 — first sight of a format flip: hub won, local kept aside. */
26
+ | 'format-flip-local-kept'
25
27
  | 'git-pull'
26
28
  | 'body-rejected';
27
29