@1agh/maude 1.8.1 → 1.9.1

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 +217 -23
  57. package/apps/studio/server.ts +141 -30
  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
@@ -427,6 +427,13 @@ function startServer(port: number): BunServer {
427
427
  status: 403,
428
428
  });
429
429
  }
430
+ // CSWSH (Phase 2 gate): a WS handshake bypasses SOP and every page in the
431
+ // browser sends a loopback Host to ws://localhost, so on a desktop a drive-by
432
+ // site could open this realm-'main' (ungated) socket. Same check as /_ws/acp.
433
+ // Not in a cell: the proxy authenticates and rewrites Host (D4).
434
+ if (!WORKSPACE && !isSameOriginWs(req)) {
435
+ return new Response('collab is same-origin only', { status: 403 });
436
+ }
430
437
  const ok = srv.upgrade(req, {
431
438
  data: {
432
439
  id: crypto.randomUUID(),
@@ -476,6 +483,11 @@ function startServer(port: number): BunServer {
476
483
 
477
484
  // Legacy inspector WS — JSON frames, designer-facing live tab state.
478
485
  if (pathname.startsWith('/_ws')) {
486
+ // CSWSH (Phase 2 gate) — the shell's own socket; a drive-by Origin is refused
487
+ // on a desktop like /_ws/acp and collab above (a cell's proxy vouches instead).
488
+ if (!WORKSPACE && !isSameOriginWs(req)) {
489
+ return new Response('inspector is same-origin only', { status: 403 });
490
+ }
479
491
  const ok = srv.upgrade(req, {
480
492
  data: {
481
493
  id: crypto.randomUUID(),
@@ -517,7 +529,89 @@ function startServer(port: number): BunServer {
517
529
  // /_sync-status, /_comments, or arbitrary repo files. Routes are a hard
518
530
  // allowlist: Bun matches `routes` before `fetch`, so we expose ONLY the two
519
531
  // gated API endpoints the runtime needs here and 403 everything else in fetch.
520
- function startCanvasServer(port: number): BunServer {
532
+ //
533
+ // V2-2.8 S9 (V2-1.16 L21) — `{ capture: true }` starts the CAPTURE origin: the
534
+ // same listener, a third port, for headless renders only (exports, `maude
535
+ // design screenshot`, smoke, perf, …). The main origin 307s every canvas-shell
536
+ // request to it (http.ts `captureRedirect`), so tenant canvas code in a capture
537
+ // runs here — read-only by construction — and never on the main origin, where
538
+ // its requests passed sameOriginWrite + isTrustedRequestHost.
539
+ function captureWriteRefusal(): Response {
540
+ return new Response('the capture origin is read-only', {
541
+ status: 405,
542
+ headers: { Allow: 'GET, HEAD', 'Cache-Control': 'no-store' },
543
+ });
544
+ }
545
+
546
+ /**
547
+ * What the capture origin refuses before anything else is consulted — applied
548
+ * to its `routes` entries AND its `fetch` (Bun matches `routes` first, so a
549
+ * gate on `fetch` alone would miss the route table). Read-only BY
550
+ * CONSTRUCTION: it is its own origin, so nothing a page runs can remove these
551
+ * properties (a restricting cookie or header could be stripped by
552
+ * `fetch(…, { credentials: 'omit' })`; a port cannot).
553
+ * - loopback only: it never sits behind a proxy, so a foreign Host is a
554
+ * DNS-rebound page;
555
+ * - no upgrade: no collab room, no HMR feed;
556
+ * - no service worker: in a reused browser session (agent-browser keeps one)
557
+ * it would answer the NEXT canvas's capture with whatever the first chose;
558
+ * - GET/HEAD only.
559
+ */
560
+ function captureRefusal(req: Request): Response | null {
561
+ if (!isLoopbackHost(req.headers.get('host')))
562
+ return new Response('local request required (DNS-rebinding guard)', { status: 403 });
563
+ if (req.headers.get('upgrade'))
564
+ return new Response('the capture origin accepts no upgrades', { status: 403 });
565
+ if (req.headers.get('service-worker'))
566
+ return new Response('the capture origin installs no service workers', { status: 403 });
567
+ if (req.method !== 'GET' && req.method !== 'HEAD') return captureWriteRefusal();
568
+ return null;
569
+ }
570
+
571
+ /** Each route behind the capture gate — the capture origin's copy of the ONE table. */
572
+ function readOnlyRoutes<R extends Record<string, unknown>>(routes: R): R {
573
+ const out: Record<string, unknown> = {};
574
+ for (const [path, handler] of Object.entries(routes)) {
575
+ const fn = handler as (req: Request) => Response | Promise<Response>;
576
+ out[path] = (req: Request) => captureRefusal(req) ?? fn(req);
577
+ }
578
+ return out as R;
579
+ }
580
+
581
+ function startCanvasServer(
582
+ port: number,
583
+ { capture = false }: { capture?: boolean } = {}
584
+ ): BunServer {
585
+ // Hard allowlist of route-table endpoints (Bun matches `routes` before
586
+ // `fetch`). Only the collab/display-data endpoints the canvas runtime needs
587
+ // — see http.isCanvasSafeRoute for the trust rationale. The dynamic
588
+ // /_api/comments/<id>/reply POST is fetch-handled + gated there.
589
+ const routes = {
590
+ '/_health': http.routes['/_health'],
591
+ '/_api/git-user': http.routes['/_api/git-user'],
592
+ '/_api/canvas-meta': http.routes['/_api/canvas-meta'],
593
+ '/_api/annotations': http.routes['/_api/annotations'],
594
+ '/_api/annotations/ops': http.routes['/_api/annotations/ops'],
595
+ // Phase 23 — capped binary image upload (magic-byte sniff + category cap +
596
+ // content-addressed name + traversal guard + no-SVG, in api.saveAsset).
597
+ // Bun matches `routes` BEFORE `fetch`, so the route must be listed here
598
+ // explicitly — the CANVAS_SAFE_API entry alone only opens the fetch
599
+ // fall-through (which serves files, not route handlers). See DDR (Task 9).
600
+ '/_api/asset': http.routes['/_api/asset'],
601
+ // Issue #126 — chunked upload; MIRROR of the CANVAS_SAFE_API entries (http.ts).
602
+ '/_api/asset/chunk-start': http.routes['/_api/asset/chunk-start'],
603
+ '/_api/asset/chunk': http.routes['/_api/asset/chunk'],
604
+ '/_api/asset/chunk-finish': http.routes['/_api/asset/chunk-finish'],
605
+ // feature-photo-editor — PhotoEdit sidecar GET/PUT. MUST be here AND in
606
+ // CANVAS_SAFE_API (http.ts): Bun matches `routes` before `fetch`, so a
607
+ // one-list entry 404s from the canvas iframe (the DDR-088 rollout bug).
608
+ '/_api/photo-edit': http.routes['/_api/photo-edit'],
609
+ // V2-2.8 S6 — NOT the main-origin handler: the canvas origin gets the
610
+ // no-e-mail projection (names + commit counts) for @mention suggestions.
611
+ '/_api/git-committers': http.canvasRoutes['/_api/git-committers'],
612
+ '/_api/ai': http.routes['/_api/ai'],
613
+ '/_comments': http.routes['/_comments'],
614
+ };
521
615
  return Bun.serve<WsData, never>({
522
616
  port,
523
617
  hostname: '127.0.0.1',
@@ -525,37 +619,19 @@ function startCanvasServer(port: number): BunServer {
525
619
  // DDR-088 follow-up — bound the pre-handler request buffer on the UNTRUSTED
526
620
  // canvas origin (the asset upload lives here). See MAX_REQUEST_BODY.
527
621
  maxRequestBodySize: MAX_REQUEST_BODY,
528
- // Hard allowlist of route-table endpoints (Bun matches `routes` before
529
- // `fetch`). Only the collab/display-data endpoints the canvas runtime needs
530
- // — see http.isCanvasSafeRoute for the trust rationale. The dynamic
531
- // /_api/comments/<id>/reply POST is fetch-handled + gated there.
532
- routes: {
533
- '/_health': http.routes['/_health'],
534
- '/_api/git-user': http.routes['/_api/git-user'],
535
- '/_api/canvas-meta': http.routes['/_api/canvas-meta'],
536
- '/_api/annotations': http.routes['/_api/annotations'],
537
- '/_api/annotations/ops': http.routes['/_api/annotations/ops'],
538
- // Phase 23 — capped binary image upload (magic-byte sniff + category cap +
539
- // content-addressed name + traversal guard + no-SVG, in api.saveAsset).
540
- // Bun matches `routes` BEFORE `fetch`, so the route must be listed here
541
- // explicitly — the CANVAS_SAFE_API entry alone only opens the fetch
542
- // fall-through (which serves files, not route handlers). See DDR (Task 9).
543
- '/_api/asset': http.routes['/_api/asset'],
544
- // Issue #126 — chunked upload; MIRROR of the CANVAS_SAFE_API entries (http.ts).
545
- '/_api/asset/chunk-start': http.routes['/_api/asset/chunk-start'],
546
- '/_api/asset/chunk': http.routes['/_api/asset/chunk'],
547
- '/_api/asset/chunk-finish': http.routes['/_api/asset/chunk-finish'],
548
- // feature-photo-editor — PhotoEdit sidecar GET/PUT. MUST be here AND in
549
- // CANVAS_SAFE_API (http.ts): Bun matches `routes` before `fetch`, so a
550
- // one-list entry 404s from the canvas iframe (the DDR-088 rollout bug).
551
- '/_api/photo-edit': http.routes['/_api/photo-edit'],
552
- '/_api/git-committers': http.routes['/_api/git-committers'],
553
- '/_api/ai': http.routes['/_api/ai'],
554
- '/_comments': http.routes['/_comments'],
555
- },
622
+ // The capture origin serves the SAME route table, each entry behind a
623
+ // GET/HEAD gate — never a third allowlist (V2-2.8 S9).
624
+ routes: capture ? readOnlyRoutes(routes) : routes,
556
625
  async fetch(req, srv) {
557
626
  const pathname = new URL(req.url).pathname;
558
627
 
628
+ // V2-2.8 S9 — the capture origin's gate (see captureRefusal), before
629
+ // anything else is consulted.
630
+ if (capture) {
631
+ const refused = captureRefusal(req);
632
+ if (refused) return refused;
633
+ }
634
+
559
635
  // Collab WS — shared registry, loopback-only (same gate as the main
560
636
  // origin), with the same workspace-mode vouched path: in a cell the hub's
561
637
  // canvas lane forwards the iframe's collab socket HERE, capability-
@@ -567,6 +643,12 @@ function startCanvasServer(port: number): BunServer {
567
643
  if (!isLoopbackHost(req.headers.get('host')) && !vouchedRole) {
568
644
  return new Response('cross-machine collab requires Phase 9 hub deploy', { status: 403 });
569
645
  }
646
+ // CSWSH (Phase 2 gate) — the canvas iframe keeps its own origin
647
+ // (`allow-same-origin`), so only a page ON this canvas origin passes; a drive-by
648
+ // site could otherwise read the Y-doc and write comments/annotations here.
649
+ if (!WORKSPACE && !isSameOriginWs(req)) {
650
+ return new Response('collab is same-origin only', { status: 403 });
651
+ }
570
652
  const ok = srv.upgrade(req, {
571
653
  data: {
572
654
  id: crypto.randomUUID(),
@@ -589,8 +671,12 @@ function startCanvasServer(port: number): BunServer {
589
671
  }
590
672
 
591
673
  // HMR-only socket — canvas iframes listen for `canvas-hmr` here. Carries
592
- // NO privileged inspector feed and ignores inbound messages (ws.ts).
674
+ // NO privileged inspector feed and ignores inbound messages (ws.ts) — but its
675
+ // frames name files (→ collab slugs), so a drive-by Origin is refused too.
593
676
  if (pathname.startsWith('/_ws')) {
677
+ if (!WORKSPACE && !isSameOriginWs(req)) {
678
+ return new Response('canvas socket is same-origin only', { status: 403 });
679
+ }
594
680
  const ok = srv.upgrade(req, {
595
681
  data: {
596
682
  id: crypto.randomUUID(),
@@ -743,6 +829,15 @@ const canvasOrigin = process.env.MAUDE_PUBLIC_CANVAS_ORIGIN?.replace(/\/+$/, '')
743
829
  ? `http://localhost:${canvasServer.port}`
744
830
  : undefined;
745
831
  if (canvasOrigin) ctx.canvasOrigin = canvasOrigin;
832
+ // V2-2.8 S9 — the read-only CAPTURE origin (see startCanvasServer). Desktop /
833
+ // plain server only: a cell renders nothing in-process (the render worker
834
+ // captures on the public canvas origin), and with the split OFF there is no
835
+ // segregated origin to mirror — captures stay on the main origin there, as do
836
+ // interactive canvases (a named residual). Not advertised in `_server.json`:
837
+ // callers reach it through the main origin's 307.
838
+ const captureServer =
839
+ CANVAS_ORIGIN_SPLIT && !WORKSPACE ? startCanvasServer(0, { capture: true }) : null;
840
+ if (captureServer) ctx.captureOrigin = `http://localhost:${captureServer.port}`;
746
841
 
747
842
  await Bun.write(
748
843
  ctx.paths.serverInfoFile,
@@ -862,8 +957,19 @@ if (!process.env.NO_OPEN && !WORKSPACE) {
862
957
  }
863
958
  }
864
959
 
960
+ const SHUTDOWN_WATCHDOG_MS = Number(process.env.MAUDE_SHUTDOWN_WATCHDOG_MS) || 5000;
961
+
865
962
  async function shutdown() {
866
963
  console.log('\n Stopping…');
964
+ // V2-2.8 B4: a teardown step that never settles (syncRuntime.stop, a collab flush) must not
965
+ // keep the process alive after a signal — 26 CI runs hung in figma-routes this way. Logged,
966
+ // then out; the JSON snapshots are the ground truth anyway.
967
+ setTimeout(() => {
968
+ console.error(' Shutdown did not finish within 5 s — exiting anyway.');
969
+ process.exit(0);
970
+ }, SHUTDOWN_WATCHDOG_MS).unref();
971
+ // Test seam (V2-2.8 B4 regression test only): simulate a teardown that never settles.
972
+ if (process.env.MAUDE_TEST_HANG_SHUTDOWN === '1') await new Promise(() => {});
867
973
  // DDR-166 — reap in-flight claude-provisioning grandchildren before this
868
974
  // process exits. Security-review finding: neither the SIGTERM/SIGINT path
869
975
  // here nor sidecar.rs's child.kill() on the Tauri side propagate to a
@@ -936,6 +1042,11 @@ async function shutdown() {
936
1042
  } catch {
937
1043
  /* best-effort */
938
1044
  }
1045
+ try {
1046
+ captureServer?.stop();
1047
+ } catch {
1048
+ /* best-effort */
1049
+ }
939
1050
  process.exit(0);
940
1051
  }
941
1052
 
@@ -35,6 +35,10 @@ export interface AcceptedLinkOptions {
35
35
  designRoot: string;
36
36
  docNameFor: (slug: string) => string;
37
37
  fetchImpl?: typeof fetch;
38
+ /** V2-1.12 §5.6 — hold proposals in the outbox while format-gated. */
39
+ paused?: () => boolean;
40
+ /** V2-1.12 §5.4 — the format a proposal is WRITTEN in (recorded per entry). */
41
+ declaredFormat?: () => number;
38
42
  log?: Pick<Console, 'log' | 'warn' | 'error'>;
39
43
  onPending?: (count: number) => void;
40
44
  onStats?: (stats: TransactionStats) => void;
@@ -67,6 +71,8 @@ export function createAcceptedLink(opts: AcceptedLinkOptions) {
67
71
  token: opts.token,
68
72
  designRoot: opts.designRoot,
69
73
  fetchImpl: opts.fetchImpl,
74
+ ...(opts.paused ? { paused: opts.paused } : {}),
75
+ ...(opts.declaredFormat ? { declaredFormat: opts.declaredFormat } : {}),
70
76
  log,
71
77
  onPending: opts.onPending,
72
78
  onStats: opts.onStats,
@@ -145,6 +145,8 @@ export interface CanvasSyncAgentOptions {
145
145
  * recovery snapshots (test-only constructions).
146
146
  */
147
147
  snapshot?: (content: string, reason: ColdStartSnapshotReason) => Promise<string | null>;
148
+ /** V2-1.12 §5.9 — is this the first cold start after a format flip? */
149
+ formatFirstSight?: () => boolean;
148
150
  /**
149
151
  * Called when a non-adopt reconcile (cold-start / post-git-pull) found
150
152
  * divergent non-empty content on both sides (DDR-102). `winner` is the side
@@ -154,7 +156,7 @@ export interface CanvasSyncAgentOptions {
154
156
  */
155
157
  onConflict?: (info: {
156
158
  slug: string;
157
- kind: 'cold-start-hub-wins' | 'cold-start-diverged';
159
+ kind: 'cold-start-hub-wins' | 'cold-start-diverged' | 'format-flip-local-kept';
158
160
  winner?: 'local' | 'hub';
159
161
  snapshots?: { local?: string; hub?: string };
160
162
  /** DDR-102 fail-closed (F1): the local snapshot didn't land, so the
@@ -530,6 +532,9 @@ export function createCanvasSyncAgent(opts: CanvasSyncAgentOptions): CanvasSyncA
530
532
  return;
531
533
  }
532
534
 
535
+ // V2-1.12 §5.9 — asked ONCE per cold start (the runtime's answer is
536
+ // per canvas and one-shot), then used by every lane below.
537
+ const firstSight = opts.formatFirstSight?.() === true;
533
538
  // ---- body: cold-start decision table (DDR-102; replaces v1.1 hub-wins) --
534
539
  const decision = decideColdStart({
535
540
  localBody: localHtml,
@@ -537,6 +542,7 @@ export function createCanvasSyncAgent(opts: CanvasSyncAgentOptions): CanvasSyncA
537
542
  journalHash: opts.journal?.get(slug)?.bodyHash ?? null,
538
543
  localMtimeMs: localMtimeMs(paths.html),
539
544
  docBodyEditAtMs: bodyEditAtFromDoc(doc),
545
+ formatFirstSight: firstSight,
540
546
  });
541
547
 
542
548
  const writeBodyFromDoc = (): void => {
@@ -628,6 +634,7 @@ export function createCanvasSyncAgent(opts: CanvasSyncAgentOptions): CanvasSyncA
628
634
  localMtimeMs: localMtimeMs(paths.annotations),
629
635
  docEditAtMs: annotationsEditAtFromDoc(doc),
630
636
  bodyWinner,
637
+ formatFirstSight: firstSight,
631
638
  });
632
639
  if (annDecision.winner === 'local' && localAnnotations !== null) {
633
640
  console.warn(`[sync/${slug}] cold-start annotations: ${annDecision.reason}`);
@@ -666,6 +673,7 @@ export function createCanvasSyncAgent(opts: CanvasSyncAgentOptions): CanvasSyncA
666
673
  journalHash: opts.journal?.get(slug)?.cssHash ?? null,
667
674
  hash: hashBytes,
668
675
  bodyWinner,
676
+ formatFirstSight: firstSight,
669
677
  });
670
678
  if (cssDecision.recoveredDuplication) {
671
679
  // WARN, BUT DO NOT SNAPSHOT — symmetric with the body's
@@ -46,11 +46,12 @@ import type { ColdStartAction, ColdStartDecision } from './cold-start.ts';
46
46
  * hold nothing the retained one doesn't — and `pruneSnapshots` evicts
47
47
  * oldest-first per slug, so a valueless snapshot on a hub-triggerable path is
48
48
  * an eviction lever against the copies that carry real bytes. */
49
- export type ColdStartSnapshotReason = 'pre-sync-local' | 'pre-sync-hub';
49
+ export type ColdStartSnapshotReason = 'pre-sync-local' | 'pre-sync-hub' | 'pre-format-flip-local';
50
50
 
51
51
  export interface ColdStartConflictInfo {
52
52
  slug: string;
53
- kind: 'cold-start-diverged';
53
+ /** `format-flip-local-kept` — the V2-1.12 §5.9 first-sight row. */
54
+ kind: 'cold-start-diverged' | 'format-flip-local-kept';
54
55
  winner?: 'local' | 'hub';
55
56
  snapshots?: { local?: string; hub?: string };
56
57
  /** DDR-102 fail-closed (F1) — local snapshot didn't land; hub-wins refused. */
@@ -161,7 +162,10 @@ export async function applyColdStart(input: ColdStartApplyInput): Promise<ColdSt
161
162
  if (input.snapshot) {
162
163
  snapshotAttempted = true;
163
164
  try {
164
- const localTs = await input.snapshot(localBody as string, 'pre-sync-local');
165
+ const localTs = await input.snapshot(
166
+ localBody as string,
167
+ decision.firstSight ? 'pre-format-flip-local' : 'pre-sync-local'
168
+ );
165
169
  if (localTs) snapshots.local = localTs;
166
170
  const hubTs = await input.snapshot(docBody, 'pre-sync-hub');
167
171
  if (hubTs) snapshots.hub = hubTs;
@@ -179,6 +183,27 @@ export async function applyColdStart(input: ColdStartApplyInput): Promise<ColdSt
179
183
  // standalone/test caller keeps plain newest-wins.
180
184
  const localSnapshotMissing = snapshotAttempted && !snapshots.local;
181
185
  let winner: 'local' | 'hub' = decision.winner ?? 'hub';
186
+ if (winner === 'hub' && localSnapshotMissing && decision.firstSight) {
187
+ // §5.9 + fail-closed: the local copy could not be kept aside, so it is
188
+ // NOT overwritten — and nothing is pushed either. Disk and doc stay as
189
+ // they are until the snapshot can land.
190
+ log.error(
191
+ `${prefix} format flip: the local snapshot FAILED — keeping local on disk untouched and pushing nothing (DDR-102 fail-closed).`
192
+ );
193
+ input.onConflict?.({
194
+ slug,
195
+ kind: 'format-flip-local-kept',
196
+ winner: 'local',
197
+ snapshotFailed: true,
198
+ });
199
+ // bodyWinner 'local': the coupled lanes keep their local bytes too
200
+ // (under first sight their tables never push them).
201
+ return {
202
+ action: decision.action,
203
+ bodyWinner: 'local',
204
+ conflict: { winner: 'local', snapshots, snapshotFailed: true },
205
+ };
206
+ }
182
207
  if (winner === 'hub' && localSnapshotMissing) {
183
208
  winner = 'local';
184
209
  log.error(
@@ -195,7 +220,7 @@ export async function applyColdStart(input: ColdStartApplyInput): Promise<ColdSt
195
220
  log.warn(`${prefix} cold-start divergence — ${decision.reason}`);
196
221
  input.onConflict?.({
197
222
  slug,
198
- kind: 'cold-start-diverged',
223
+ kind: decision.firstSight ? 'format-flip-local-kept' : 'cold-start-diverged',
199
224
  winner,
200
225
  ...(snapshots.local || snapshots.hub ? { snapshots } : {}),
201
226
  ...(localSnapshotMissing ? { snapshotFailed: true } : {}),
@@ -42,12 +42,21 @@ export interface ColdStartInput {
42
42
  /** Doc-side syncMeta.bodyEditAt stamp (ms epoch), or null when no peer ever
43
43
  * stamped (older peer interop) — falls back to hub-wins. */
44
44
  docBodyEditAtMs: number | null;
45
+ /**
46
+ * V2-1.12 §5.9 — the FIRST cold start after this Mac learns the project's
47
+ * format was raised (its `_state/hub-format.json` was absent or older than
48
+ * the hub's value). Evaluated before newest-wins: the hub wins, a divergent
49
+ * local copy is kept aside, and nothing is pushed.
50
+ */
51
+ formatFirstSight?: boolean;
45
52
  }
46
53
 
47
54
  export interface ColdStartDecision {
48
55
  action: ColdStartAction;
49
56
  /** Set only for `conflict`. */
50
57
  winner?: 'local' | 'hub';
58
+ /** V2-1.12 §5.9 — the conflict is the format-flip first-sight row. */
59
+ firstSight?: true;
51
60
  /** Human-readable, logged + recorded in the conflict entry. */
52
61
  reason: string;
53
62
  }
@@ -112,6 +121,41 @@ export function unionCommentsById(docList: unknown[], localList: unknown[]): unk
112
121
  }
113
122
 
114
123
  export function decideColdStart(input: ColdStartInput): ColdStartDecision {
124
+ const base = decideColdStartNewestWins(input);
125
+ return input.formatFirstSight ? firstSightRow(base) : base;
126
+ }
127
+
128
+ /**
129
+ * The §5.9 row over the DDR-102 table: on first sight of a format flip every
130
+ * canvas-owned lane is hub-wins and NOTHING is pushed. Rows that only read the
131
+ * hub (materialize, fast-forward, noop) stand; every row that would push local
132
+ * becomes a hub-wins conflict (the local copy snapshotted and reported), except
133
+ * an EMPTY hub body — there "hub wins" would be a blank canvas, so local stays
134
+ * on disk untouched and unpushed (emptiness never beats content, DDR-223).
135
+ */
136
+ function firstSightRow(d: ColdStartDecision): ColdStartDecision {
137
+ if (d.action === 'seed-local-up') {
138
+ return {
139
+ action: 'noop',
140
+ reason:
141
+ 'format flip, first sight — the hub holds no body; local kept on disk, nothing pushed',
142
+ };
143
+ }
144
+ // `recover-seed-dup` stands: it collapses a doubled body to the one copy the
145
+ // hub already holds (no new bytes), and turning it into a hub-wins would
146
+ // write the doubled, unbuildable body to disk (agent.ts keeps it a collapse).
147
+ if (d.action === 'conflict') {
148
+ return {
149
+ action: 'conflict',
150
+ winner: 'hub',
151
+ firstSight: true,
152
+ reason: `format flip, first sight — hub wins, the local copy is kept aside (${d.reason})`,
153
+ };
154
+ }
155
+ return d;
156
+ }
157
+
158
+ function decideColdStartNewestWins(input: ColdStartInput): ColdStartDecision {
115
159
  const localEmpty = isEmptyBody(input.localBody);
116
160
  const docEmpty = isEmptyBody(input.docBody);
117
161
 
@@ -217,6 +261,8 @@ export interface AnnotationsColdStartInput {
217
261
  /** The body lane's resolved winner — the legacy coupling, used only as the
218
262
  * fallback when both sides are non-empty and neither is stamped. */
219
263
  bodyWinner: 'local' | 'hub';
264
+ /** V2-1.12 §5.9 — first sight of a format flip: never push local. */
265
+ formatFirstSight?: boolean;
220
266
  }
221
267
 
222
268
  export interface AnnotationsColdStartDecision {
@@ -238,6 +284,31 @@ export interface AnnotationsColdStartDecision {
238
284
  */
239
285
  export function decideAnnotationsColdStart(
240
286
  input: AnnotationsColdStartInput
287
+ ): AnnotationsColdStartDecision {
288
+ const d = decideAnnotationsNewestWins(input);
289
+ return input.formatFirstSight ? neverPushLocal(d, 'annotations') : d;
290
+ }
291
+
292
+ /**
293
+ * §5.9 for the per-lane tables: on first sight nothing is pushed, so a lane
294
+ * that would seed local up keeps it on disk instead ('none'). It never becomes
295
+ * a hub overwrite here — these lanes take no snapshot, and the body row is the
296
+ * one that keeps a divergent copy aside.
297
+ */
298
+ function neverPushLocal<T extends { winner: 'local' | 'hub' | 'none'; reason: string }>(
299
+ d: T,
300
+ lane: string
301
+ ): T {
302
+ if (d.winner !== 'local') return d;
303
+ return {
304
+ ...d,
305
+ winner: 'none',
306
+ reason: `format flip, first sight — local ${lane} kept on disk, nothing pushed (${d.reason})`,
307
+ };
308
+ }
309
+
310
+ function decideAnnotationsNewestWins(
311
+ input: AnnotationsColdStartInput
241
312
  ): AnnotationsColdStartDecision {
242
313
  const { local, doc, isEmpty, localMtimeMs, docEditAtMs, bodyWinner } = input;
243
314
  const localEmpty = isEmpty(local);
@@ -308,6 +379,8 @@ export interface CssColdStartInput {
308
379
  hash: (s: string) => string;
309
380
  /** How the body lane resolved; the tie-break for a genuine divergence. */
310
381
  bodyWinner: 'local' | 'hub';
382
+ /** V2-1.12 §5.9 — first sight of a format flip: never push local. */
383
+ formatFirstSight?: boolean;
311
384
  }
312
385
 
313
386
  export interface CssColdStartDecision {
@@ -342,6 +415,11 @@ export interface CssColdStartDecision {
342
415
  * exact repeat, so this cannot clobber an edit.
343
416
  */
344
417
  export function decideCssColdStart(input: CssColdStartInput): CssColdStartDecision {
418
+ const d = decideCssNewestWins(input);
419
+ return input.formatFirstSight ? neverPushLocal(d, 'css') : d;
420
+ }
421
+
422
+ function decideCssNewestWins(input: CssColdStartInput): CssColdStartDecision {
345
423
  const { local, doc, journalHash, hash, bodyWinner } = input;
346
424
  const localEmpty = local === null || local === '';
347
425
  const docEmpty = doc === null || doc === '';
@@ -390,6 +390,14 @@ export interface FilePlaneResult {
390
390
  requestsExhausted?: true;
391
391
  /** The door refused our credential; a renewal was requested and the pass ended. */
392
392
  authRefused?: true;
393
+ /**
394
+ * V2-1.12 §5.4 — the door refused our FILE FORMAT (426): the project now
395
+ * uses a newer format than this build writes. Not a credential failure (no
396
+ * renewal) and not this file's fault (no backoff); the pass ended.
397
+ */
398
+ formatRefused?: { formatVersion: number | null };
399
+ /** Outbound changes held this pass because the project is format-gated. */
400
+ heldForFormat?: number;
393
401
  /**
394
402
  * Paths skipped this pass because they are inside their per-path backoff
395
403
  * window. NOT a failure and NOT converged — work that is deliberately
@@ -471,6 +479,17 @@ export interface FilePlaneOptions {
471
479
  * renewals/s storm.
472
480
  */
473
481
  onAuthFailure?: (rel: string, status: number) => void;
482
+ /**
483
+ * V2-1.12 §5.4 — a write door answered 426 (format). Called once per pass
484
+ * with the project format the hub named, so the runtime can mirror it and
485
+ * engage the gate. Never a credential renewal.
486
+ */
487
+ onFormatRefused?: (formatVersion: number | null) => void;
488
+ /**
489
+ * V2-1.12 §5.6 — while true nothing goes UP (no push, revive or delete);
490
+ * pulls continue. The runtime passes "this build does not edit the project".
491
+ */
492
+ outboundPaused?: () => boolean;
474
493
  /**
475
494
  * A pass delivered at least one file.
476
495
  *
@@ -710,6 +729,8 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
710
729
  let unreachableInARow = 0;
711
730
  /** The door refused our credential this pass. */
712
731
  let authRefused = false;
732
+ /** Set when a write door answered 426 (format) this pass. */
733
+ let formatRefused: { formatVersion: number | null } | null = null;
713
734
  /** Bytes this pass has successfully pushed, charged against the window. */
714
735
  let quotaSpentThisPass = 0;
715
736
  /** The door's own ceilings, learned once per boot. Null until asked. */
@@ -874,6 +895,24 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
874
895
  authRefused = true;
875
896
  return { ok: false, reason: 'The workspace did not accept this connection' };
876
897
  }
898
+ // V2-1.12 §5.4 — 426 is the hub's FORMAT door: this project now uses a
899
+ // newer format than this build writes. Deliberately NOT the branch above —
900
+ // the credential is fine, and renewing it would change nothing.
901
+ if (res.status === 426) {
902
+ // The CONTRACT's words (§5.8), never the hub's text — the hub is
903
+ // untrusted to peers (DDR-054), and this line reaches the Sync panel.
904
+ let fv: number | null = null;
905
+ try {
906
+ const text = await res.clone().text();
907
+ const body = text.length <= 4096 ? (JSON.parse(text) as { formatVersion?: unknown }) : null;
908
+ const v = body?.formatVersion;
909
+ if (typeof v === 'number' && Number.isSafeInteger(v) && v >= 1) fv = v;
910
+ } catch {
911
+ /* a bare 426 still means "format" */
912
+ }
913
+ formatRefused = { formatVersion: fv };
914
+ return { ok: false, reason: 'This project now uses Maude 2. Update Maude to edit it.' };
915
+ }
877
916
  const reason = await failureReason(res);
878
917
  // BACKPRESSURE, not just 429 — a cell that is starting answers 503 with a
879
918
  // Retry-After, and firing this pass's remaining request budget into that
@@ -1542,6 +1581,7 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
1542
1581
  hitRateLimit = null;
1543
1582
  unreachableInARow = 0;
1544
1583
  authRefused = false;
1584
+ formatRefused = null;
1545
1585
  quotaSpentThisPass = 0;
1546
1586
  await ensureHubLimits();
1547
1587
  requestsThisPass = 0;
@@ -2053,7 +2093,7 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2053
2093
  // it. A rate limit is excluded: that is the DOOR's state, not this
2054
2094
  // path's, and punishing the file for it would push a whole project into
2055
2095
  // backoff for something none of its files did.
2056
- if (hitRateLimit === null) {
2096
+ if (hitRateLimit === null && formatRefused === null) {
2057
2097
  if (out.failed.length > before.failed) {
2058
2098
  const delay = ledger.noteAttemptFailed(item.rel, now());
2059
2099
  log.warn?.(
@@ -2070,6 +2110,18 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2070
2110
  // A RATE LIMIT ENDS THE PASS. Every other refusal is about one file and
2071
2111
  // the next one is worth trying; this one is about the door, and the
2072
2112
  // remaining requests would do nothing but hold it shut for longer.
2113
+ // (A cast: TS cannot see the assignment inside `refusal()`.)
2114
+ const refusedFormat = formatRefused as { formatVersion: number | null } | null;
2115
+ if (refusedFormat !== null) {
2116
+ // ONE notification, and the pass ends: every other write would meet
2117
+ // the same door. No backoff is armed (the file did nothing wrong).
2118
+ opts.onFormatRefused?.(refusedFormat.formatVersion);
2119
+ out.formatRefused = refusedFormat;
2120
+ log.warn?.(
2121
+ `[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).`
2122
+ );
2123
+ break;
2124
+ }
2073
2125
  if (authRefused) {
2074
2126
  // ONE notification for the whole pass. `renewCredentialNow()` is
2075
2127
  // single-flight with a 60 s floor, so 803 refused paths collapse to one
@@ -2241,6 +2293,10 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2241
2293
  case 'push':
2242
2294
  case 'revive': {
2243
2295
  if (!here) return false;
2296
+ if (opts.outboundPaused?.()) {
2297
+ out.heldForFormat = (out.heldForFormat ?? 0) + 1;
2298
+ return false;
2299
+ }
2244
2300
  ledger.setState(rel, 'pushing');
2245
2301
  const expect = decision.action === 'revive' ? null : remoteHash;
2246
2302
  const res = await push(here, expect);
@@ -2386,6 +2442,10 @@ export function createFilePlane(opts: FilePlaneOptions): FilePlane {
2386
2442
  }
2387
2443
 
2388
2444
  case 'propagate-delete': {
2445
+ if (opts.outboundPaused?.()) {
2446
+ out.heldForFormat = (out.heldForFormat ?? 0) + 1;
2447
+ return false;
2448
+ }
2389
2449
  // Gone here, and the hub still holds exactly what we last reconciled —
2390
2450
  // the Syncthing rule. The CAS carries our ancestor, so an edit that
2391
2451
  // landed in between wins and this comes back as a conflict instead.