@1agh/maude 1.8.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 (73) hide show
  1. package/apps/studio/acp/bridge.ts +14 -2
  2. package/apps/studio/acp/probe.ts +51 -1
  3. package/apps/studio/api.ts +19 -4
  4. package/apps/studio/bin/_curl-local.mjs +7 -0
  5. package/apps/studio/bin/annotate.mjs +16 -7
  6. package/apps/studio/bin/read-annotations.mjs +62 -4
  7. package/apps/studio/client/app.jsx +428 -15977
  8. package/apps/studio/client/dialogs/asset-picker.jsx +331 -0
  9. package/apps/studio/client/dialogs/command-palette.jsx +112 -0
  10. package/apps/studio/client/dialogs/export-dialog.jsx +782 -0
  11. package/apps/studio/client/dialogs/help-modal.jsx +324 -0
  12. package/apps/studio/client/dialogs/shortcuts-overlay.jsx +144 -0
  13. package/apps/studio/client/hooks/use-canvas-bridge.jsx +2150 -0
  14. package/apps/studio/client/hooks/use-git-actions.jsx +236 -0
  15. package/apps/studio/client/hooks/use-keyboard-shortcuts.jsx +297 -0
  16. package/apps/studio/client/hooks/use-palette-and-panels.jsx +474 -0
  17. package/apps/studio/client/hooks/use-photo-and-timeline.jsx +901 -0
  18. package/apps/studio/client/hooks/use-project-data.jsx +90 -0
  19. package/apps/studio/client/hooks/use-shell-core.jsx +1212 -0
  20. package/apps/studio/client/hooks/use-tabs.jsx +723 -0
  21. package/apps/studio/client/hooks/use-web-socket.jsx +13 -0
  22. package/apps/studio/client/inspector/artboard-knobs.jsx +456 -0
  23. package/apps/studio/client/inspector/color-picker.jsx +196 -0
  24. package/apps/studio/client/inspector/color.js +92 -0
  25. package/apps/studio/client/inspector/css-knobs.jsx +1720 -0
  26. package/apps/studio/client/inspector/css-vocab.jsx +131 -0
  27. package/apps/studio/client/inspector/ds-tokens.js +90 -0
  28. package/apps/studio/client/inspector/grid-tracks-editor.jsx +97 -0
  29. package/apps/studio/client/inspector/inspect-computed.jsx +68 -0
  30. package/apps/studio/client/inspector/inspector-panel.jsx +769 -0
  31. package/apps/studio/client/inspector/layers.jsx +322 -0
  32. package/apps/studio/client/inspector/selection.js +65 -0
  33. package/apps/studio/client/inspector/token-popover.jsx +301 -0
  34. package/apps/studio/client/menus/menubar.jsx +856 -0
  35. package/apps/studio/client/selection-scope.js +40 -0
  36. package/apps/studio/client/shell/banners.jsx +272 -0
  37. package/apps/studio/client/shell/collapsed-rail.jsx +23 -0
  38. package/apps/studio/client/shell/comments-panel.jsx +177 -0
  39. package/apps/studio/client/shell/constants.js +60 -0
  40. package/apps/studio/client/shell/dock.jsx +131 -0
  41. package/apps/studio/client/shell/icons.jsx +370 -0
  42. package/apps/studio/client/shell/status-bar.jsx +215 -0
  43. package/apps/studio/client/shell/util.js +332 -0
  44. package/apps/studio/client/shell/viewport.jsx +254 -0
  45. package/apps/studio/client/system/system-view.jsx +255 -0
  46. package/apps/studio/client/tree/tree.jsx +1243 -0
  47. package/apps/studio/comments-overlay.tsx +6 -4
  48. package/apps/studio/config.schema.json +5 -0
  49. package/apps/studio/context.ts +13 -0
  50. package/apps/studio/dist/client.bundle.js +1337 -1337
  51. package/apps/studio/dist/comment-mount.js +2 -2
  52. package/apps/studio/exporters/_browser-bundles.ts +21 -2
  53. package/apps/studio/exporters/jobs.ts +75 -15
  54. package/apps/studio/exporters/scope.ts +15 -12
  55. package/apps/studio/format.ts +296 -0
  56. package/apps/studio/http.ts +213 -23
  57. package/apps/studio/server.ts +118 -29
  58. package/apps/studio/sync/accepted-link.ts +6 -0
  59. package/apps/studio/sync/agent.ts +9 -1
  60. package/apps/studio/sync/cold-start-apply.ts +29 -4
  61. package/apps/studio/sync/cold-start.ts +78 -0
  62. package/apps/studio/sync/file-plane.ts +61 -1
  63. package/apps/studio/sync/format-sync.ts +160 -0
  64. package/apps/studio/sync/index.ts +134 -10
  65. package/apps/studio/sync/journal-client.ts +25 -5
  66. package/apps/studio/sync/migrate-seed.ts +8 -1
  67. package/apps/studio/sync/status.ts +2 -0
  68. package/apps/studio/sync/transaction-client.ts +130 -13
  69. package/apps/studio/ui-prefs.ts +95 -10
  70. package/apps/studio/whats-new.json +9 -0
  71. package/apps/studio/ws.ts +19 -4
  72. package/cli/bin/claude-design-server.mjs +0 -0
  73. package/package.json +10 -8
@@ -0,0 +1,160 @@
1
+ // The sync runtime's side of the project file format — V2-1.12 §5.4, §5.6,
2
+ // §5.7 P1 (V2-2.18).
3
+ //
4
+ // • DECLARE: every studio → hub request carries `X-Maude-Format: <n>` and
5
+ // every socket `maude-format=<n>`, so the hub can fence a writer of another
6
+ // format (426 on its doors, a read-only connection on the doc lanes).
7
+ // • LEARN: the hub's format arrives on `/health` and on the `maude.mode`
8
+ // notice; it is mirrored raise-only into `_state/hub-format.json`
9
+ // (`format.ts` noteHubFormat), and a change makes shells refetch
10
+ // `/_config` so the gate and the banner engage.
11
+ // • PAUSE: while this build does not edit the project, nothing goes up —
12
+ // no fs → doc imports, no file-plane pushes, no proposals. Pulls continue.
13
+ // • 426 IS NOT A CREDENTIAL FAILURE: a format refusal never renews a token.
14
+ //
15
+ // Pure helpers + the decisions; `sync/index.ts` wires them.
16
+
17
+ import {
18
+ asFormat,
19
+ type FormatCtx,
20
+ type FormatGateOptions,
21
+ formatGate,
22
+ formatHubUrl,
23
+ noteHubFormat,
24
+ projectFormat,
25
+ readHubFormatCache,
26
+ STAGED_FORMAT_GATE_OPTS,
27
+ SUPPORTED_FORMAT,
28
+ } from '../format.ts';
29
+
30
+ /**
31
+ * The gate the studio enforces — the SAME options `http.ts` passes
32
+ * (`STAGED_FORMAT_GATE_OPTS`: only a project newer than this build is
33
+ * gated). Pinned against http.ts by test/format-sync.test.ts so the sync
34
+ * runtime and the HTTP gate can never disagree about whether a project is
35
+ * editable here.
36
+ */
37
+ export const SYNC_FORMAT_GATE_OPTS: FormatGateOptions = STAGED_FORMAT_GATE_OPTS;
38
+
39
+ /** Does this build NOT edit the project right now? (Outbound is paused.) */
40
+ export function formatGated(ctx: FormatCtx): boolean {
41
+ if (formatGate(ctx, SYNC_FORMAT_GATE_OPTS) !== null) return true;
42
+ // The owner moved the project back (an unflip) and this copy's config.json
43
+ // still says the newer format: every write would be refused by the hub, so
44
+ // none is made until the two agree (the copy's own `--reverse`, or git).
45
+ const hub = formatHubUrl(ctx);
46
+ const mirror = hub ? readHubFormatCache(ctx.paths.designRoot, hub) : null;
47
+ return mirror !== null && mirror.formatVersion < asFormat(ctx.cfg.formatVersion);
48
+ }
49
+
50
+ /**
51
+ * The format this studio WRITES in, for the hub's fence. While the project is
52
+ * editable here that is the project's format (under the staged gate a v2 build
53
+ * still writes a format-1 project as a format-1 writer); while it is gated it
54
+ * is this build's own format, so a mismatch is exactly what the hub sees.
55
+ */
56
+ export function declaredFormat(ctx: FormatCtx): number {
57
+ return formatGated(ctx) ? SUPPORTED_FORMAT : projectFormat(ctx).value;
58
+ }
59
+
60
+ /** `ws(s)://host[/path]` + `maude-format=<n>` (keeps any existing query). */
61
+ export function withFormatParam(wsUrl: string, format: number | undefined): string {
62
+ if (format === undefined) return wsUrl;
63
+ try {
64
+ const u = new URL(wsUrl);
65
+ u.searchParams.set('maude-format', String(asFormat(format)));
66
+ return u.toString();
67
+ } catch {
68
+ return wsUrl;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * A fetch that declares the format on every request. The base fetch is
74
+ * resolved at CALL time (`globalThis.fetch` when none is given), so a test
75
+ * that swaps the global still sees every request.
76
+ */
77
+ export function withFormatHeader(
78
+ base: typeof fetch | undefined,
79
+ format: () => number
80
+ ): typeof fetch {
81
+ const wrapped = (input: RequestInfo | URL, init?: RequestInit) => {
82
+ const fn = base ?? globalThis.fetch;
83
+ const from =
84
+ init?.headers ??
85
+ (typeof Request !== 'undefined' && input instanceof Request ? input.headers : undefined);
86
+ const headers = new Headers(from);
87
+ // A request that already names its format keeps it: a queued proposal
88
+ // declares the format it was WRITTEN in, not whatever this build is now.
89
+ if (!headers.has('x-maude-format')) headers.set('x-maude-format', String(asFormat(format())));
90
+ return fn(input, { ...init, headers });
91
+ };
92
+ return wrapped as typeof fetch;
93
+ }
94
+
95
+ /** A hub's answer is a FORMAT refusal (V2-1.12 §5.4) — not a credential one. */
96
+ export function isFormatRefusal(status: number, body?: unknown): boolean {
97
+ if (status !== 426) return false;
98
+ if (!body || typeof body !== 'object') return true;
99
+ const b = body as { reason?: unknown; code?: unknown };
100
+ return (
101
+ b.reason === 'format' || b.code === 'format' || (b.reason === undefined && b.code === undefined)
102
+ );
103
+ }
104
+
105
+ /** The project format a `/health` body or a `maude.mode` notice states, or null. */
106
+ export function formatFromHub(body: unknown): number | null {
107
+ const v = (body as { formatVersion?: unknown } | null)?.formatVersion;
108
+ return typeof v === 'number' && Number.isSafeInteger(v) && v >= 1 ? v : null;
109
+ }
110
+
111
+ /**
112
+ * Record what the hub said. Returns true when the mirrored value changed, so
113
+ * the caller emits `config-updated` (shells refetch `/_config`, the gate and
114
+ * banner engage within the reload — §5.14 "≤ 1 s after the notice").
115
+ */
116
+ export function learnHubFormat(
117
+ ctx: FormatCtx,
118
+ seen: { formatVersion: number | null; epoch?: number }
119
+ ): boolean {
120
+ const hub = formatHubUrl(ctx);
121
+ if (!hub || seen.formatVersion === null) return false;
122
+ // An epoch is a non-negative safe integer or it is not one: a hostile hub
123
+ // sending 1e308 must not freeze this mirror against every later unflip.
124
+ const epoch =
125
+ typeof seen.epoch === 'number' && Number.isSafeInteger(seen.epoch) && seen.epoch >= 0
126
+ ? seen.epoch
127
+ : undefined;
128
+ // RAISE-ONLY, with one exception: the owner's unflip (`--reverse`) reaches
129
+ // peers as a `maude.mode` notice carrying a NEWER epoch than the one this
130
+ // mirror recorded — a later decision by the authority, not a stale hub.
131
+ // `/health` carries no public epoch, so it can only ever raise.
132
+ const cached = readHubFormatCache(ctx.paths.designRoot, hub);
133
+ const newerDecision = epoch !== undefined && cached !== null && epoch > cached.epoch;
134
+ return noteHubFormat(
135
+ ctx.paths.designRoot,
136
+ {
137
+ hub,
138
+ formatVersion: seen.formatVersion,
139
+ ...(epoch !== undefined ? { epoch } : {}),
140
+ },
141
+ { allowLower: newerDecision }
142
+ );
143
+ }
144
+
145
+ /**
146
+ * §5.9 FIRST SIGHT of a flip: this Mac's mirror is absent or older than what
147
+ * the hub now says. Evaluated BEFORE `learnHubFormat` writes the mirror. A
148
+ * format-1 hub is never a flip (nothing to have missed).
149
+ */
150
+ export function isFormatFirstSight(ctx: FormatCtx, hubFormat: number | null): boolean {
151
+ const hub = formatHubUrl(ctx);
152
+ if (!hub || hubFormat === null || hubFormat <= 1) return false;
153
+ const cached = readHubFormatCache(ctx.paths.designRoot, hub);
154
+ return (
155
+ cached === null ||
156
+ cached.formatVersion < hubFormat ||
157
+ // A mirror an OLDER build wrote: this build has not seen the flip itself.
158
+ (cached.writtenBy ?? 1) < SUPPORTED_FORMAT
159
+ );
160
+ }
@@ -69,11 +69,20 @@ 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';
@@ -478,6 +487,8 @@ export type ProviderFactory = (args: {
478
487
  * `getDoc`. Default factory: `args.document ?? new Y.Doc()`.
479
488
  */
480
489
  document?: Y.Doc;
490
+ /** V2-1.12 §5.4 — the file format this studio writes (`maude-format`). */
491
+ format?: number;
481
492
  }) => SyncProvider | Promise<SyncProvider>;
482
493
 
483
494
  export interface SyncRuntime {
@@ -851,6 +862,60 @@ export function createSyncRuntime(
851
862
  return null;
852
863
  }
853
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
+
854
919
  // DDR-192 §5 — slug → wire documentName. Only the WIRE name is namespaced;
855
920
  // every local map (providers, agents, projections, _history/) stays keyed by
856
921
  // the flat slug. Opt-in for now (see createDocNameResolver's rollout rule);
@@ -951,10 +1016,13 @@ export function createSyncRuntime(
951
1016
  designRoot: ctx.paths.designRoot,
952
1017
  hubUrl: linkedHub.url,
953
1018
  token: () => token,
1019
+ fetchImpl: hubFetch,
954
1020
  })
955
1021
  : null;
956
1022
  const projectConfigUnsub = projectConfigPusher
957
- ? ctx.bus.on('config-updated', () => void projectConfigPusher.push())
1023
+ ? ctx.bus.on('config-updated', () => {
1024
+ if (!outboundPaused()) void projectConfigPusher.push();
1025
+ })
958
1026
  : null;
959
1027
 
960
1028
  // DDR-102 — the default factory multiplexes every provider over ONE shared
@@ -1017,13 +1085,21 @@ export function createSyncRuntime(
1017
1085
  token: () => token,
1018
1086
  designRoot: ctx.paths.designRoot,
1019
1087
  docNameFor: (slug) => docNameFor(slug),
1020
- fetchImpl: opts.transactionFetch,
1088
+ fetchImpl: withFormatHeader(opts.transactionFetch, declared),
1089
+ paused: outboundPaused,
1090
+ declaredFormat: declared,
1021
1091
  retryMs: opts.transactionRetryMs,
1022
1092
  onStats: (stats) => statusStore?.updateAccepted?.(stats),
1023
1093
  onStage: (summary) => statusStore?.updateAiAction?.(summary),
1024
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
+ );
1025
1101
  noteProjectConfig(b.projectConfig);
1026
- void projectConfigPusher?.push();
1102
+ if (!outboundPaused()) void projectConfigPusher?.push();
1027
1103
  // F3 S17 — a save made as the socket died is held (the connection
1028
1104
  // was not writable). After the reconnect the handshake re-admits the
1029
1105
  // socket read-only BEFORE this peer learns the project now takes
@@ -1147,11 +1223,13 @@ export function createSyncRuntime(
1147
1223
  legacyPushAgain = true;
1148
1224
  return;
1149
1225
  }
1226
+ if (outboundPaused()) return; // V2-1.12 §5.6 — nothing goes up while gated
1150
1227
  legacyPushRunning = true;
1151
1228
  legacyPushCancel = false;
1152
1229
  pushAssets({
1153
1230
  designRoot: ctx.paths.designRoot,
1154
1231
  hubUrl,
1232
+ fetchImpl: hubFetch,
1155
1233
  // Read at call time — silent renewal swaps the credential in place.
1156
1234
  token: () => token,
1157
1235
  canvasGroups: ctx.cfg.canvasGroups,
@@ -3288,6 +3366,7 @@ export function createSyncRuntime(
3288
3366
  }
3289
3367
  },
3290
3368
  onConflict: (info) => store.addConflict(info),
3369
+ formatFirstSight: firstSightFor(canvas.slug),
3291
3370
  // An unmergeable local candidate: keep both, and let the projection
3292
3371
  // report and hold it from the shared base (T2).
3293
3372
  onHold: (base) => projection.adoptBase(base),
@@ -3636,6 +3715,7 @@ export function createSyncRuntime(
3636
3715
  token,
3637
3716
  documentName: docNameFor(canvas.slug),
3638
3717
  document,
3718
+ format: declared(),
3639
3719
  });
3640
3720
  providers.set(canvas.slug, provider);
3641
3721
  // ANY change to a synced document is activity — a local edit unparks a
@@ -3848,12 +3928,14 @@ export function createSyncRuntime(
3848
3928
  }
3849
3929
  : {}),
3850
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).
3851
3933
  ...(provider.isWritable
3852
3934
  ? {
3853
- canWriteDoc: () => provider.isWritable?.() !== false,
3935
+ canWriteDoc: () => provider.isWritable?.() !== false && !outboundPaused(),
3854
3936
  onWriteBlocked: () => void refreshAcceptedMode(),
3855
3937
  }
3856
- : {}),
3938
+ : { canWriteDoc: () => !outboundPaused() }),
3857
3939
  onRecovered: () => store.clearSourceConflict(canvas.slug),
3858
3940
  onConflict: (info) => {
3859
3941
  store.addConflict(info);
@@ -3915,6 +3997,7 @@ export function createSyncRuntime(
3915
3997
  }
3916
3998
  },
3917
3999
  onConflict: (info) => store.addConflict(info),
4000
+ formatFirstSight: firstSightFor(canvas.slug),
3918
4001
  });
3919
4002
  agent.start();
3920
4003
  agents.set(canvas.slug, agent);
@@ -3929,6 +4012,28 @@ export function createSyncRuntime(
3929
4012
  // THE HUB SAYS THE SAVE MODE CHANGED — on this document's own
3930
4013
  // socket, ahead of closing it, so the switch is learned before any
3931
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
+ }
3932
4037
  if (acceptedLink && provider.onStateless) {
3933
4038
  noteDetach(
3934
4039
  statusDetaches,
@@ -4217,7 +4322,16 @@ export function createSyncRuntime(
4217
4322
  });
4218
4323
  return;
4219
4324
  }
4220
- 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) => {
4221
4335
  if (!ok) {
4222
4336
  console.warn(
4223
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.`
@@ -4982,9 +5096,11 @@ export function createSyncRuntime(
4982
5096
  // its job is healing the UI rather than triggering pulls.
4983
5097
  if (!cellPairing && ctx.cfg.linkedHub?.fileEvents !== false) {
4984
5098
  fileEventsProbe = new AbortController();
4985
- void hubCapabilities({ hubUrl: linkedHub.url, signal: fileEventsProbe.signal })
4986
- .then((caps) => {
5099
+ void hubHealth({ hubUrl: linkedHub.url, signal: fileEventsProbe.signal })
5100
+ .then(({ capabilities: caps, formatVersion: hubFormat }) => {
4987
5101
  if (stopped) return;
5102
+ // V2-1.12 §5.5 — `/health` names the project's format.
5103
+ noteHubFormatSeen(hubFormat);
4988
5104
  // DDR-242 — a hub that predates the annotations-v2 model still keeps
4989
5105
  // boards as SVG: its workspace checkout and kernel would not carry
4990
5106
  // this studio's `.annotations.json` edits. Say so loudly; the
@@ -5024,6 +5140,11 @@ export function createSyncRuntime(
5024
5140
  onAuthFailure: () => {
5025
5141
  void renewCredentialNow();
5026
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,
5027
5148
  // A DELIVERED FILE IS PROGRESS. `renewalsSinceProgress` counted
5028
5149
  // only doc handshakes, and a converged doc lane has none left to
5029
5150
  // land — so during a long seed the cap was reached and the
@@ -6080,6 +6201,7 @@ export function createDefaultProviderFactory(
6080
6201
  token: string;
6081
6202
  documentName: string;
6082
6203
  document?: Y.Doc;
6204
+ format?: number;
6083
6205
  }): Promise<SyncProvider> => {
6084
6206
  if (!mod) {
6085
6207
  try {
@@ -6093,7 +6215,9 @@ export function createDefaultProviderFactory(
6093
6215
  // Hocuspocus accepts ws:// or wss://; the linked URL is http(s)://, so swap
6094
6216
  // the scheme. The provider also accepts http(s):// and upgrades internally
6095
6217
  // in newer versions, but ws:// is explicit + portable.
6096
- 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);
6097
6221
  // A DOCUMENT KEEPS ITS SOCKET; A FULL SOCKET TAKES NO NEW ONES.
6098
6222
  //
6099
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
@@ -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