@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
@@ -29,6 +29,8 @@
29
29
 
30
30
  import { type RefObject, useEffect } from 'react';
31
31
 
32
+ import { isEmbedCanvas } from './read-only-mode.ts';
33
+
32
34
  // ─────────────────────────────────────────────────────────────────────────────
33
35
  // Drag-vs-click threshold (T25)
34
36
  //
@@ -732,7 +734,11 @@ export function useInputRouter(opts: UseInputRouterOptions): void {
732
734
  );
733
735
  if (
734
736
  action.kind === 'tool' ||
735
- action.kind === 'escape' ||
737
+ // DDR-247 — in an embed, the router's catch-all Escape (drop the
738
+ // selection) does not CONSUME the key: left unprevented, it reaches
739
+ // the embed's relay and closes the app's dialog around it. Anything
740
+ // that genuinely owns Escape (a menu, an inline edit) still prevents it.
741
+ (action.kind === 'escape' && !isEmbedCanvas()) ||
736
742
  action.kind === 'undo' ||
737
743
  action.kind === 'redo'
738
744
  ) {
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Path containment that holds on Windows as well as POSIX (#145).
3
+ *
4
+ * The studio used to answer "is this file under that root?" with a string
5
+ * prefix — `${child}/`.startsWith(`${root}/`) — and to build the static route's
6
+ * file path with `posix.join(repoRoot, urlPath)`. On Windows the root is native
7
+ * (`C:\proj\.design`) while the joined path was mixed (`C:\proj/.design/a.tsx`),
8
+ * so the prefix never matched: every canvas `.tsx` skipped the transpile branch,
9
+ * went out as `text/plain`, and the iframe died on "Failed to fetch dynamically
10
+ * imported module".
11
+ *
12
+ * Both helpers take the `node:path` flavour as a parameter so the win32 case is
13
+ * testable from a Mac (`path.win32`); production callers use the default.
14
+ */
15
+ import nodePath from 'node:path';
16
+
17
+ type PathImpl = Pick<typeof nodePath, 'isAbsolute' | 'relative' | 'resolve' | 'sep'>;
18
+
19
+ /**
20
+ * True when `child` is `root` itself or lies inside it. `path.relative`, never a
21
+ * string prefix: a prefix compare also matches `/repo-evil` against `/repo`, and
22
+ * cannot see that `C:\proj\x` and `C:\proj/x` are the same file. Win32 compares
23
+ * case-insensitively, like the filesystem does — approximately: `toLowerCase`
24
+ * is Unicode folding, NTFS uses its own upcase table (U+212A KELVIN SIGN folds
25
+ * to `k` here and does not there). That can only matter for a look-alike
26
+ * sibling directory reached by `..`, which `resolveUrlPathUnder` refuses.
27
+ */
28
+ export function isUnderOrEqual(child: string, root: string, p: PathImpl = nodePath): boolean {
29
+ const fold = (s: string) => (p.sep === '\\' ? s.toLowerCase() : s);
30
+ const rel = p.relative(fold(root), fold(child));
31
+ if (rel === '') return true;
32
+ if (p.isAbsolute(rel)) return false; // another drive on win32
33
+ return rel !== '..' && !rel.startsWith(`..${p.sep}`);
34
+ }
35
+
36
+ /** DOS device names, with or without an extension (`NUL`, `con.css`, `con .css`, `COM1.tsx`). */
37
+ const WIN32_DEVICE = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³]|conin\$|conout\$)\s*(\..*)?$/i;
38
+
39
+ /**
40
+ * Map an already-DECODED URL pathname (`/.design/ui/a.tsx`) onto a native
41
+ * absolute path under `root`, or null when it would leave `root`.
42
+ *
43
+ * On win32 a backslash or a colon in the URL is refused outright: the canvas-
44
+ * origin gate (`isCanvasSafeRoute`) normalizes with POSIX rules, so a `\` it
45
+ * reads as an ordinary character would become a separator here — `..%5c`
46
+ * climbing out of the design root while still under the repo (the DDR-060 A1/A2
47
+ * decode-mismatch class). A colon would name a drive or an NTFS stream. Neither
48
+ * can appear in a legitimate Windows file name anyway. Also refused on win32: a
49
+ * segment ending in `.` or a space (Windows silently trims it, so the name on
50
+ * disk differs from the one checked) and a DOS device name (`con.css`, `COM1`).
51
+ *
52
+ * A `..` segment is refused everywhere. The URL parser has already resolved
53
+ * every literal and `%2e` dot segment, so one that survives decoding came from
54
+ * an encoded `%2f` — never a link the studio builds, and the only way to reach
55
+ * a look-alike sibling directory through case folding.
56
+ */
57
+ export function resolveUrlPathUnder(
58
+ pathname: string,
59
+ root: string,
60
+ p: PathImpl = nodePath
61
+ ): string | null {
62
+ if (pathname.includes('\0')) return null;
63
+ const segments = pathname.split('/');
64
+ if (segments.includes('..')) return null;
65
+ if (p.sep === '\\') {
66
+ if (pathname.includes('\\') || pathname.includes(':')) return null;
67
+ if (segments.some((s) => s !== '' && s !== '.' && (/[. ]$/.test(s) || WIN32_DEVICE.test(s))))
68
+ return null;
69
+ }
70
+ const abs = p.resolve(root, `.${pathname.startsWith('/') ? '' : '/'}${pathname}`);
71
+ return isUnderOrEqual(abs, root, p) ? abs : null;
72
+ }
@@ -177,13 +177,26 @@ function isDevServerDir(dir: string): boolean {
177
177
  return existsSync(join(dir, 'http.ts'));
178
178
  }
179
179
 
180
+ /**
181
+ * `\\?\C:\x` → `C:\x` and `\\?\UNC\srv\share` → `\\srv\share`; anything else
182
+ * unchanged. Mirrors `strip_verbatim` in apps/desktop/src-tauri/src/win_process.rs.
183
+ */
184
+ export function stripWin32Verbatim(p: string): string {
185
+ if (p.startsWith('\\\\?\\UNC\\')) return `\\\\${p.slice(8)}`;
186
+ if (/^\\\\\?\\[a-zA-Z]:/.test(p)) return p.slice(4);
187
+ return p;
188
+ }
189
+
180
190
  function resolveDevServerRoot(): string {
181
191
  // (0) Explicit override. Used when the runtime can't be found by walk-up — e.g.
182
192
  // the Tauri desktop bundle (DDR-106) ships apps/studio/ as an app resource and
183
193
  // sets MAUDE_DEV_SERVER_ROOT to it, because the sidecar binary sits alone in
184
194
  // Maude.app/Contents/MacOS/ with no apps/studio/ up-tree (the bundle ships the
185
195
  // full source, so `http.ts` is present at the resource root).
186
- const override = process.env.MAUDE_DEV_SERVER_ROOT;
196
+ // #141 — a verbatim `\\?\C:\…` root (what Tauri's resource_dir is on Windows)
197
+ // propagates into the ACP adapter's entry path, and `node \\?\C:\…` cannot
198
+ // start a script (nodejs/node#62446). The shell strips it; so do we.
199
+ const override = stripWin32Verbatim(process.env.MAUDE_DEV_SERVER_ROOT ?? '');
187
200
  // Require the same `http.ts` anchor walk-up uses (not merely a `dist/` dir) so a
188
201
  // planted dist-only directory can't hijack the runtime root (security review F4).
189
202
  if (override && !isVirtualBunfsPath(override) && isDevServerDir(override)) {
@@ -30,7 +30,60 @@ export function isReadOnlyCanvas(): boolean {
30
30
  return cached;
31
31
  }
32
32
 
33
+ let embedCached: boolean | null = null;
34
+
35
+ /**
36
+ * DDR-247 — is this canvas the chromeless view another app frames
37
+ * (`client/embed-view.jsx` appends `?embed=1`)? Boot-static for the same reason
38
+ * as `isReadOnlyCanvas`. An embed pans and zooms, but never persists its
39
+ * camera: the designer's own view of the canvas is not the embed's to move.
40
+ */
41
+ export function isEmbedCanvas(): boolean {
42
+ if (typeof window === 'undefined') return false;
43
+ if (embedCached === null) {
44
+ try {
45
+ embedCached = new URLSearchParams(window.location.search).get('embed') === '1';
46
+ } catch {
47
+ embedCached = false;
48
+ }
49
+ }
50
+ return embedCached;
51
+ }
52
+
53
+ /**
54
+ * DDR-247 — Escape inside an embedded canvas belongs to the app around it.
55
+ * Keys pressed in this frame never reach the embedding page, so an embed shown
56
+ * in a dialog would trap a keyboard user: the dialog's own Escape stops
57
+ * working. When nothing in the canvas consumed the key (`defaultPrevented`,
58
+ * read after every listener has run), tell the studio page, which relays it to
59
+ * the embedder as the contract's `escape`. Never in the studio itself.
60
+ */
61
+ export function installEmbedEscapeRelay(win: Window = window): () => void {
62
+ let embed = false;
63
+ try {
64
+ embed = new URLSearchParams(win.location?.search ?? '').get('embed') === '1';
65
+ } catch {
66
+ /* not a canvas URL */
67
+ }
68
+ if (!embed || win.parent === win) return () => {};
69
+ const onKey = (e: KeyboardEvent) => {
70
+ if (e.key !== 'Escape' || e.isComposing) return;
71
+ setTimeout(() => {
72
+ if (e.defaultPrevented) return;
73
+ try {
74
+ // The studio page checks origin + source before relaying anything.
75
+ win.parent.postMessage({ dgn: 'embed-escape' }, '*');
76
+ } catch {
77
+ /* parent gone */
78
+ }
79
+ }, 0);
80
+ };
81
+ win.addEventListener('keydown', onKey);
82
+ return () => win.removeEventListener('keydown', onKey);
83
+ }
84
+
33
85
  /** Test seam — reset the module cache (bun:test re-uses the module registry). */
34
86
  export function _resetReadOnlyCache(): void {
35
87
  cached = null;
88
+ embedCached = null;
36
89
  }
@@ -28,6 +28,7 @@ import { createGitLifecycle } from './collab/git-lifecycle.ts';
28
28
  import { createCollab } from './collab/index.ts';
29
29
  import { createContext, reloadConfig } from './context.ts';
30
30
  import { installLogRing } from './debug-bundle.ts';
31
+ import { parseEmbedOrigins } from './embed-origins.ts';
31
32
  import { createExportJobQueue } from './exporters/jobs.ts';
32
33
  import { createFsWatch } from './fs-watch.ts';
33
34
  import { createGenerationJobQueue } from './generation/jobs.ts';
@@ -516,7 +517,89 @@ function startServer(port: number): BunServer {
516
517
  // /_sync-status, /_comments, or arbitrary repo files. Routes are a hard
517
518
  // allowlist: Bun matches `routes` before `fetch`, so we expose ONLY the two
518
519
  // gated API endpoints the runtime needs here and 403 everything else in fetch.
519
- function startCanvasServer(port: number): BunServer {
520
+ //
521
+ // V2-2.8 S9 (V2-1.16 L21) — `{ capture: true }` starts the CAPTURE origin: the
522
+ // same listener, a third port, for headless renders only (exports, `maude
523
+ // design screenshot`, smoke, perf, …). The main origin 307s every canvas-shell
524
+ // request to it (http.ts `captureRedirect`), so tenant canvas code in a capture
525
+ // runs here — read-only by construction — and never on the main origin, where
526
+ // its requests passed sameOriginWrite + isTrustedRequestHost.
527
+ function captureWriteRefusal(): Response {
528
+ return new Response('the capture origin is read-only', {
529
+ status: 405,
530
+ headers: { Allow: 'GET, HEAD', 'Cache-Control': 'no-store' },
531
+ });
532
+ }
533
+
534
+ /**
535
+ * What the capture origin refuses before anything else is consulted — applied
536
+ * to its `routes` entries AND its `fetch` (Bun matches `routes` first, so a
537
+ * gate on `fetch` alone would miss the route table). Read-only BY
538
+ * CONSTRUCTION: it is its own origin, so nothing a page runs can remove these
539
+ * properties (a restricting cookie or header could be stripped by
540
+ * `fetch(…, { credentials: 'omit' })`; a port cannot).
541
+ * - loopback only: it never sits behind a proxy, so a foreign Host is a
542
+ * DNS-rebound page;
543
+ * - no upgrade: no collab room, no HMR feed;
544
+ * - no service worker: in a reused browser session (agent-browser keeps one)
545
+ * it would answer the NEXT canvas's capture with whatever the first chose;
546
+ * - GET/HEAD only.
547
+ */
548
+ function captureRefusal(req: Request): Response | null {
549
+ if (!isLoopbackHost(req.headers.get('host')))
550
+ return new Response('local request required (DNS-rebinding guard)', { status: 403 });
551
+ if (req.headers.get('upgrade'))
552
+ return new Response('the capture origin accepts no upgrades', { status: 403 });
553
+ if (req.headers.get('service-worker'))
554
+ return new Response('the capture origin installs no service workers', { status: 403 });
555
+ if (req.method !== 'GET' && req.method !== 'HEAD') return captureWriteRefusal();
556
+ return null;
557
+ }
558
+
559
+ /** Each route behind the capture gate — the capture origin's copy of the ONE table. */
560
+ function readOnlyRoutes<R extends Record<string, unknown>>(routes: R): R {
561
+ const out: Record<string, unknown> = {};
562
+ for (const [path, handler] of Object.entries(routes)) {
563
+ const fn = handler as (req: Request) => Response | Promise<Response>;
564
+ out[path] = (req: Request) => captureRefusal(req) ?? fn(req);
565
+ }
566
+ return out as R;
567
+ }
568
+
569
+ function startCanvasServer(
570
+ port: number,
571
+ { capture = false }: { capture?: boolean } = {}
572
+ ): BunServer {
573
+ // Hard allowlist of route-table endpoints (Bun matches `routes` before
574
+ // `fetch`). Only the collab/display-data endpoints the canvas runtime needs
575
+ // — see http.isCanvasSafeRoute for the trust rationale. The dynamic
576
+ // /_api/comments/<id>/reply POST is fetch-handled + gated there.
577
+ const routes = {
578
+ '/_health': http.routes['/_health'],
579
+ '/_api/git-user': http.routes['/_api/git-user'],
580
+ '/_api/canvas-meta': http.routes['/_api/canvas-meta'],
581
+ '/_api/annotations': http.routes['/_api/annotations'],
582
+ '/_api/annotations/ops': http.routes['/_api/annotations/ops'],
583
+ // Phase 23 — capped binary image upload (magic-byte sniff + category cap +
584
+ // content-addressed name + traversal guard + no-SVG, in api.saveAsset).
585
+ // Bun matches `routes` BEFORE `fetch`, so the route must be listed here
586
+ // explicitly — the CANVAS_SAFE_API entry alone only opens the fetch
587
+ // fall-through (which serves files, not route handlers). See DDR (Task 9).
588
+ '/_api/asset': http.routes['/_api/asset'],
589
+ // Issue #126 — chunked upload; MIRROR of the CANVAS_SAFE_API entries (http.ts).
590
+ '/_api/asset/chunk-start': http.routes['/_api/asset/chunk-start'],
591
+ '/_api/asset/chunk': http.routes['/_api/asset/chunk'],
592
+ '/_api/asset/chunk-finish': http.routes['/_api/asset/chunk-finish'],
593
+ // feature-photo-editor — PhotoEdit sidecar GET/PUT. MUST be here AND in
594
+ // CANVAS_SAFE_API (http.ts): Bun matches `routes` before `fetch`, so a
595
+ // one-list entry 404s from the canvas iframe (the DDR-088 rollout bug).
596
+ '/_api/photo-edit': http.routes['/_api/photo-edit'],
597
+ // V2-2.8 S6 — NOT the main-origin handler: the canvas origin gets the
598
+ // no-e-mail projection (names + commit counts) for @mention suggestions.
599
+ '/_api/git-committers': http.canvasRoutes['/_api/git-committers'],
600
+ '/_api/ai': http.routes['/_api/ai'],
601
+ '/_comments': http.routes['/_comments'],
602
+ };
520
603
  return Bun.serve<WsData, never>({
521
604
  port,
522
605
  hostname: '127.0.0.1',
@@ -524,33 +607,19 @@ function startCanvasServer(port: number): BunServer {
524
607
  // DDR-088 follow-up — bound the pre-handler request buffer on the UNTRUSTED
525
608
  // canvas origin (the asset upload lives here). See MAX_REQUEST_BODY.
526
609
  maxRequestBodySize: MAX_REQUEST_BODY,
527
- // Hard allowlist of route-table endpoints (Bun matches `routes` before
528
- // `fetch`). Only the collab/display-data endpoints the canvas runtime needs
529
- // — see http.isCanvasSafeRoute for the trust rationale. The dynamic
530
- // /_api/comments/<id>/reply POST is fetch-handled + gated there.
531
- routes: {
532
- '/_health': http.routes['/_health'],
533
- '/_api/git-user': http.routes['/_api/git-user'],
534
- '/_api/canvas-meta': http.routes['/_api/canvas-meta'],
535
- '/_api/annotations': http.routes['/_api/annotations'],
536
- '/_api/annotations/ops': http.routes['/_api/annotations/ops'],
537
- // Phase 23 — capped binary image upload (magic-byte sniff + category cap +
538
- // content-addressed name + traversal guard + no-SVG, in api.saveAsset).
539
- // Bun matches `routes` BEFORE `fetch`, so the route must be listed here
540
- // explicitly — the CANVAS_SAFE_API entry alone only opens the fetch
541
- // fall-through (which serves files, not route handlers). See DDR (Task 9).
542
- '/_api/asset': http.routes['/_api/asset'],
543
- // feature-photo-editor — PhotoEdit sidecar GET/PUT. MUST be here AND in
544
- // CANVAS_SAFE_API (http.ts): Bun matches `routes` before `fetch`, so a
545
- // one-list entry 404s from the canvas iframe (the DDR-088 rollout bug).
546
- '/_api/photo-edit': http.routes['/_api/photo-edit'],
547
- '/_api/git-committers': http.routes['/_api/git-committers'],
548
- '/_api/ai': http.routes['/_api/ai'],
549
- '/_comments': http.routes['/_comments'],
550
- },
610
+ // The capture origin serves the SAME route table, each entry behind a
611
+ // GET/HEAD gate — never a third allowlist (V2-2.8 S9).
612
+ routes: capture ? readOnlyRoutes(routes) : routes,
551
613
  async fetch(req, srv) {
552
614
  const pathname = new URL(req.url).pathname;
553
615
 
616
+ // V2-2.8 S9 — the capture origin's gate (see captureRefusal), before
617
+ // anything else is consulted.
618
+ if (capture) {
619
+ const refused = captureRefusal(req);
620
+ if (refused) return refused;
621
+ }
622
+
554
623
  // Collab WS — shared registry, loopback-only (same gate as the main
555
624
  // origin), with the same workspace-mode vouched path: in a cell the hub's
556
625
  // canvas lane forwards the iframe's collab socket HERE, capability-
@@ -698,6 +767,10 @@ const extraShellOrigins = (process.env.MAUDE_EXTRA_SHELL_ORIGINS ?? '')
698
767
  .map((o) => ` ${o}`)
699
768
  .join('');
700
769
  ctx.mainOrigin = `http://localhost:${server.port} http://127.0.0.1:${server.port}${publicShellOrigin}${extraShellOrigins}`;
770
+ // DDR-247 — apps that may FRAME the studio for the read-only `?embed=1` view.
771
+ // Deliberately NOT folded into `mainOrigin` above: those are shells, and the
772
+ // hub's canvas door accepts shells as writers. An embedder only gets framing.
773
+ ctx.embedOrigins = parseEmbedOrigins(process.env.MAUDE_EMBED_ORIGINS);
701
774
 
702
775
  // T2 (9.1-A) — segregated canvas-content origin. ON BY DEFAULT (opt-OUT) since
703
776
  // phase-9.1: a second listener binds an OS-assigned free port, advertised as
@@ -734,6 +807,15 @@ const canvasOrigin = process.env.MAUDE_PUBLIC_CANVAS_ORIGIN?.replace(/\/+$/, '')
734
807
  ? `http://localhost:${canvasServer.port}`
735
808
  : undefined;
736
809
  if (canvasOrigin) ctx.canvasOrigin = canvasOrigin;
810
+ // V2-2.8 S9 — the read-only CAPTURE origin (see startCanvasServer). Desktop /
811
+ // plain server only: a cell renders nothing in-process (the render worker
812
+ // captures on the public canvas origin), and with the split OFF there is no
813
+ // segregated origin to mirror — captures stay on the main origin there, as do
814
+ // interactive canvases (a named residual). Not advertised in `_server.json`:
815
+ // callers reach it through the main origin's 307.
816
+ const captureServer =
817
+ CANVAS_ORIGIN_SPLIT && !WORKSPACE ? startCanvasServer(0, { capture: true }) : null;
818
+ if (captureServer) ctx.captureOrigin = `http://localhost:${captureServer.port}`;
737
819
 
738
820
  await Bun.write(
739
821
  ctx.paths.serverInfoFile,
@@ -853,8 +935,19 @@ if (!process.env.NO_OPEN && !WORKSPACE) {
853
935
  }
854
936
  }
855
937
 
938
+ const SHUTDOWN_WATCHDOG_MS = Number(process.env.MAUDE_SHUTDOWN_WATCHDOG_MS) || 5000;
939
+
856
940
  async function shutdown() {
857
941
  console.log('\n Stopping…');
942
+ // V2-2.8 B4: a teardown step that never settles (syncRuntime.stop, a collab flush) must not
943
+ // keep the process alive after a signal — 26 CI runs hung in figma-routes this way. Logged,
944
+ // then out; the JSON snapshots are the ground truth anyway.
945
+ setTimeout(() => {
946
+ console.error(' Shutdown did not finish within 5 s — exiting anyway.');
947
+ process.exit(0);
948
+ }, SHUTDOWN_WATCHDOG_MS).unref();
949
+ // Test seam (V2-2.8 B4 regression test only): simulate a teardown that never settles.
950
+ if (process.env.MAUDE_TEST_HANG_SHUTDOWN === '1') await new Promise(() => {});
858
951
  // DDR-166 — reap in-flight claude-provisioning grandchildren before this
859
952
  // process exits. Security-review finding: neither the SIGTERM/SIGINT path
860
953
  // here nor sidecar.rs's child.kill() on the Tauri side propagate to a
@@ -927,6 +1020,11 @@ async function shutdown() {
927
1020
  } catch {
928
1021
  /* best-effort */
929
1022
  }
1023
+ try {
1024
+ captureServer?.stop();
1025
+ } catch {
1026
+ /* best-effort */
1027
+ }
930
1028
  process.exit(0);
931
1029
  }
932
1030
 
@@ -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 === '';