@marver-design/marver 0.27.2 → 0.29.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 (91) hide show
  1. package/CHANGELOG.md +160 -0
  2. package/README.md +6 -4
  3. package/dist/{anchor-check-gkxkPAIv.mjs → anchor-check-DhlpKl2K.mjs} +1 -1
  4. package/dist/{audio-Dw1lfMdb.mjs → audio-DX4POHAj.mjs} +39 -4
  5. package/dist/{boards-BqUqKNW8.mjs → boards-BeWtjGUM.mjs} +49 -4
  6. package/dist/boards-EH2onUXM.mjs +995 -0
  7. package/dist/{build-VgNg4rr8.mjs → build-CWbrb2bl.mjs} +9 -5
  8. package/dist/{capture-vadKjuCo.mjs → capture-DEtM4qm5.mjs} +259 -34
  9. package/dist/cli.mjs +40 -19
  10. package/dist/{comments-YEU1Zhv9.mjs → comments-XNhMmSSu.mjs} +4 -4
  11. package/dist/config-BezZTiov.mjs +182 -0
  12. package/dist/conn-BMiHS42T.mjs +222 -0
  13. package/dist/connectors-DekQvKt9.mjs +292 -0
  14. package/dist/{context-Ccjrhr1J.mjs → context-BUnFiyA3.mjs} +2 -2
  15. package/dist/{daemon-Dc9AH0M3.mjs → daemon-Sc_z8gT6.mjs} +2209 -205
  16. package/dist/{dev-ri6nAlRp.mjs → dev-DWBKQhxf.mjs} +31 -15
  17. package/dist/{init-W0nxR1OY.mjs → init-CYlFaRzG.mjs} +7 -2
  18. package/dist/jam-Cj5gBvwD.mjs +373 -0
  19. package/dist/{link-CdTgn94Y.mjs → link-BFFRgrMt.mjs} +3 -3
  20. package/dist/listener-DdLEM79A.mjs +80 -0
  21. package/dist/logo-CXY-1yrn.mjs +305 -0
  22. package/dist/{ls-BZ5TAtd5.mjs → ls-NqmePKOf.mjs} +1 -1
  23. package/dist/{manifest-aFyDmL8C.mjs → manifest-DPZ3WNg_.mjs} +1 -1
  24. package/dist/{marks-CnCCfAbD.mjs → marks-BnNANic9.mjs} +22 -3
  25. package/dist/{marks-BF9pNEgH.mjs → marks-DBp3h1Mc.mjs} +3 -6
  26. package/dist/{marver-id-gate-D-R0hSt_.mjs → marver-id-gate-vBLb_Icb.mjs} +1 -1
  27. package/dist/{perf-DkAUFT6W.mjs → perf-Denssrko.mjs} +45 -27
  28. package/dist/{perf-jam-BaH3Lg0m.mjs → perf-jam-CLkERSHo.mjs} +9 -2
  29. package/dist/permit-DDa6wqOs.mjs +187 -0
  30. package/dist/{plugin-B8UghYuF.mjs → plugin-DqoZB-D6.mjs} +849 -789
  31. package/dist/{poster-BNgafWMK.mjs → poster-CrsjqhY4.mjs} +1 -1
  32. package/dist/{profile-jIS6BcAs.mjs → profile-B1FKOM1e.mjs} +1 -1
  33. package/dist/{publish-bakes-38Nja78p.mjs → publish-bakes-DW-NDgU2.mjs} +3 -3
  34. package/dist/{queue-CAM_vNmX.mjs → queue-DeSQm24g.mjs} +189 -35
  35. package/dist/{recover-B8AiI29B.mjs → recover-GtJ9UDAB.mjs} +2 -2
  36. package/dist/{serve-Dp3nHstu.mjs → serve-DQv3Ti6X.mjs} +8 -4
  37. package/dist/{session-BAaJsK5c.mjs → session-VDJfXEEm.mjs} +1 -1
  38. package/dist/{share-Ce4tP7ji.mjs → share-Bu_kuOKL.mjs} +1 -1
  39. package/dist/{shot-CMQgMVZm.mjs → shot-DBWN8hPP.mjs} +1 -1
  40. package/dist/{shot-Ch24tiMO.mjs → shot-T04Ixrvq.mjs} +7 -6
  41. package/dist/sizes-wjXDev3b.mjs +139 -0
  42. package/dist/{slots-CFNnegCc.mjs → slots-Dn4Onb0V.mjs} +101 -3
  43. package/dist/speech-worker.mjs +23 -3
  44. package/dist/{sync-CQdGARJ9.mjs → sync-CMozOwZ0.mjs} +1 -1
  45. package/dist/transport-C5FnY9ni.mjs +203 -0
  46. package/dist/{work-Bxz-ObF3.mjs → work-BYWD_1Zf.mjs} +3 -3
  47. package/dist/{work-CNhFF9pU.mjs → work-DJxH7cCX.mjs} +1 -1
  48. package/docs/boards-and-folders.md +11 -0
  49. package/docs/jam-session.md +52 -18
  50. package/docs/live-jam.md +95 -10
  51. package/docs/performance.md +1 -1
  52. package/docs/publish.md +7 -0
  53. package/package.json +1 -1
  54. package/src/client/shell/Comments.tsx +5 -4
  55. package/src/client/shell/ContextMenu.tsx +5 -4
  56. package/src/client/shell/JamSurface.tsx +135 -29
  57. package/src/client/shell/Play.tsx +16 -4
  58. package/src/client/shell/api.ts +7 -3
  59. package/src/client/shell/app-bridge.ts +11 -3
  60. package/src/client/shell/comments-store.ts +14 -0
  61. package/src/client/shell/goto.ts +4 -3
  62. package/src/client/shell/icons.tsx +1 -0
  63. package/src/client/shell/jam-capture.ts +136 -37
  64. package/src/client/shell/jam-keys.ts +170 -18
  65. package/src/client/shell/jam-lane.tsx +14 -5
  66. package/src/client/shell/jam-lines.ts +76 -10
  67. package/src/client/shell/jam-panel.tsx +58 -4
  68. package/src/client/shell/jam-queue.ts +55 -8
  69. package/src/client/shell/jam-session.tsx +55 -6
  70. package/src/client/shell/jam-state.ts +19 -4
  71. package/src/client/shell/jam-surface-parts.tsx +6 -3
  72. package/src/client/shell/jam-ui.tsx +10 -1
  73. package/src/client/shell/jam-voice-wait.ts +21 -0
  74. package/src/client/shell/jam-voice.ts +14 -5
  75. package/src/client/shell/live-picture.ts +134 -0
  76. package/src/client/shell/open-item.ts +83 -0
  77. package/src/client/shell/open-resolve.ts +50 -0
  78. package/src/client/shell/store.ts +6 -2
  79. package/src/client/shell/styles.css +29 -11
  80. package/src/client/shell/tidy.ts +3 -2
  81. package/src/client/stage/main.tsx +30 -8
  82. package/src/shared/app-api.ts +173 -3
  83. package/src/shared/app-perf.ts +4 -2
  84. package/src/shared/approval.ts +20 -0
  85. package/src/shared/events.ts +1 -1
  86. package/templates/AGENTS-embedded.md +28 -1
  87. package/templates/AGENTS-studio.md +28 -1
  88. package/templates/instructions/boards.md +7 -1
  89. package/templates/instructions/jam.md +94 -0
  90. package/dist/boards-BHKP5yhI.mjs +0 -342
  91. package/dist/live-Cgzsicwi.mjs +0 -4
@@ -1,186 +1,26 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
2
  import { a as ROUTE, i as PKG, r as NAME } from "./cli.mjs";
3
- import { c as nodeExists, d as readMembership, f as readRegistry, h as hash, i as checkBoardsDir, l as parseBoard, m as withRegistryLock, o as isRegularFile, r as boardFields, s as listBoardFiles, t as AUTHOR_FIELDS, u as pinFrames } from "./boards-BHKP5yhI.mjs";
3
+ import { a as checkBoardsDir, c as listBoardFiles, d as pinFrames, g as tryFileLock, h as takeFileLock, i as boardLock, l as nodeExists, m as readRegistry, p as readMembership, r as boardFields, s as isRegularFile, t as AUTHOR_FIELDS, u as parseBoard, v as withRegistryLock, y as hash } from "./boards-EH2onUXM.mjs";
4
4
  import { A as resolveType, D as readReason, E as readCapability, O as readStatusWord, S as HAS_STATUS, _ as validateWire, a as buildTree, c as folderMap, g as readTitle, h as readDescription, j as settableStatuses, k as readType, n as BOARD_NAME, r as FOLDERS_FILE, t as ALL_SCENES, v as wireKids } from "./board-tree-BXR8dw4b.mjs";
5
- import { c as setSceneTitle, d as annotateBoards, f as planNames, m as readContextFacts, n as isNoteFile, o as rendersDoc, p as planWithStage, r as layoutDocSource, s as scanFrames, t as affectedFrameIds, u as writeManifest } from "./manifest-aFyDmL8C.mjs";
6
- import { r as boardsChanged } from "./work-CNhFF9pU.mjs";
7
- import { h as workspaceId, i as marverHome, o as originOf } from "./slots-CFNnegCc.mjs";
8
- import { n as localProfile, t as isConnected } from "./profile-jIS6BcAs.mjs";
9
- import { i as onPath, n as AGENT_NAMES, r as detectAgent, t as AGENT_BIN } from "./agent-BsieQGTD.mjs";
10
- import { a as observe, n as docRevs, r as initMarks, s as recordChanged, t as docRev } from "./marks-CnCCfAbD.mjs";
11
- import { a as appendRun, f as tidyPerfDir, i as PAGE_BODY_MAX, o as logPage, s as logReload } from "./perf-jam-BaH3Lg0m.mjs";
12
- import { c as pool, d as withBrowser, f as Browser, l as shotConcurrency, m as launchFlags, r as SURFACE, t as AREA } from "./shot-Ch24tiMO.mjs";
13
- import { closeSync, constants, copyFileSync, existsSync, fstatSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, utimesSync, watch, writeFileSync } from "node:fs";
5
+ import { c as setSceneTitle, d as annotateBoards, f as planNames, m as readContextFacts, n as isNoteFile, p as planWithStage, s as scanFrames, t as affectedFrameIds, u as writeManifest } from "./manifest-DPZ3WNg_.mjs";
6
+ import { a as workActivity, r as boardsChanged } from "./work-DJxH7cCX.mjs";
7
+ import { r as replay, t as asks } from "./events-CLH4ijKP.mjs";
8
+ import { a as readLog, i as listBoards } from "./comments-0BSbb04K.mjs";
9
+ import { g as LIVE_WIRE, h as LIVE_BOUNDS, i as marverHome, o as originOf, v as workspaceId } from "./slots-Dn4Onb0V.mjs";
10
+ import { n as localProfile, t as isConnected } from "./profile-B1FKOM1e.mjs";
11
+ import { c as recordChanged, i as initMarks, n as docRevs, o as observe, r as freshFrames, t as docRev } from "./marks-BnNANic9.mjs";
12
+ import { a as appendRun, f as tidyPerfDir, i as PAGE_BODY_MAX, o as logPage, s as logReload } from "./perf-jam-CLkERSHo.mjs";
13
+ import { n as loadConfig } from "./config-BezZTiov.mjs";
14
+ import { a as mergeSizes, c as serializeSizes, i as measuringFrames, l as sizesPath, n as autoWidthOf, o as readSizes, r as keptSizes, s as readSizesFile } from "./sizes-wjXDev3b.mjs";
15
+ import { c as pool, d as withBrowser, f as Browser, l as shotConcurrency, m as launchFlags, r as SURFACE, t as AREA } from "./shot-T04Ixrvq.mjs";
16
+ import { a as appProofOk, o as proofHeaders, r as logoRoute } from "./logo-CXY-1yrn.mjs";
17
+ import { closeSync, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, utimesSync, watch, writeFileSync } from "node:fs";
14
18
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
15
- import { fileURLToPath, pathToFileURL } from "node:url";
16
- import { createHash, createHmac, randomBytes } from "node:crypto";
19
+ import { fileURLToPath } from "node:url";
20
+ import { createHash, randomBytes } from "node:crypto";
17
21
  import { arch, cpus, totalmem } from "node:os";
18
22
  import { execFile } from "node:child_process";
19
23
  import { stat } from "node:fs/promises";
20
- //#region src/server/config.ts
21
- const DEFAULTS = {
22
- mode: "studio",
23
- theme: null,
24
- viewports: {
25
- mobile: {
26
- width: 390,
27
- height: 844
28
- },
29
- tablet: {
30
- width: 768,
31
- height: 1024
32
- },
33
- laptop: {
34
- width: 1280,
35
- height: 800
36
- },
37
- monitor: {
38
- width: 1920,
39
- height: 1080
40
- }
41
- },
42
- themes: ["light", "dark"],
43
- port: 5199,
44
- zoomSpeed: 1,
45
- share: { branding: true }
46
- };
47
- /** Load design/config.ts via native TS import (Node >= 22.18). Missing or broken fields fall back to defaults. */
48
- async function loadConfig(root) {
49
- const file = join(root, "design", "config.ts");
50
- if (!existsSync(file)) return {
51
- ...DEFAULTS,
52
- ...jamFields(void 0)
53
- };
54
- try {
55
- const user = (await import(`${pathToFileURL(file).href}?t=${Date.now()}`)).default ?? {};
56
- return {
57
- ...DEFAULTS,
58
- ...user,
59
- viewports: validViewports(user.viewports) ?? DEFAULTS.viewports,
60
- themes: Array.isArray(user.themes) && user.themes.length ? user.themes.map(String) : DEFAULTS.themes,
61
- port: validPort(user.port) ?? DEFAULTS.port,
62
- zoomSpeed: validZoom(user.zoomSpeed) ?? DEFAULTS.zoomSpeed,
63
- description: readDescription(user.description),
64
- share: {
65
- branding: user.share?.branding !== false,
66
- name: typeof user.share?.name === "string" ? user.share.name : void 0,
67
- logo: typeof user.share?.logo === "string" ? user.share.logo : void 0,
68
- frontDoor: user.share?.frontDoor !== false && user.share?.front_door !== false,
69
- notify: user.share?.notify !== false
70
- },
71
- ...jamFields(user.jam)
72
- };
73
- } catch (err) {
74
- console.error(`[marver] design/config.ts failed to load, using defaults and leaving Live Jam OFF:\n ${err.message}`);
75
- return {
76
- ...DEFAULTS,
77
- jamOff: "unreadable"
78
- };
79
- }
80
- }
81
- const validDim = (n) => typeof n === "number" && Number.isFinite(n) && n >= 1 && n <= 2e4;
82
- function validPort(n) {
83
- return typeof n === "number" && Number.isInteger(n) && n > 0 && n < 65536 ? n : null;
84
- }
85
- function validZoom(n) {
86
- return typeof n === "number" && Number.isFinite(n) && n >= .1 && n <= 10 ? n : null;
87
- }
88
- /** Six frames at once is what a jam actually feels like - at 3, half of a multi-frame
89
- * ask sat waiting on the other half while the human watched. */
90
- const DEFAULT_CONCURRENCY = 6;
91
- /** A config value, printable in a warning. Never throws - a formatter that can crash inside an
92
- * error path (JSON.stringify does, on a BigInt) turns a clear message into a mystery. */
93
- const show = (v) => {
94
- try {
95
- return JSON.stringify(v) ?? String(v);
96
- } catch {
97
- return String(v);
98
- }
99
- };
100
- /** A `{...}` written by hand, not a Date/Map/class instance that merely types as "object". */
101
- const plainObject = (v) => {
102
- if (!v || typeof v !== "object") return false;
103
- const proto = Object.getPrototypeOf(v);
104
- return proto === Object.prototype || proto === null;
105
- };
106
- /** The agent to arm with - or, when the human NAMED one we cannot use, why not (said once,
107
- * here, because a bad `jam.agent` is a config-file error like any other).
108
- *
109
- * A named agent is never quietly swapped for another: running a different tool than the one
110
- * asked for is worse than not running. Nor is one armed that cannot be spawned - that would
111
- * claim every @marver mention, fail it, and never retry. */
112
- function resolveAgent(named) {
113
- if (named === void 0) return detectAgent() ?? "no-agent";
114
- if (typeof named !== "string" || !Object.hasOwn(AGENT_BIN, named)) {
115
- console.warn(`[marver] design/config.ts: jam.agent ${show(named)} is not an agent marver can spawn - Live Jam is off. Use ${AGENT_NAMES}.`);
116
- return "bad-agent";
117
- }
118
- const agent = named;
119
- if (!onPath(AGENT_BIN[agent])) {
120
- console.warn(`[marver] design/config.ts names jam.agent "${agent}", but \`${AGENT_BIN[agent]}\` is not on PATH - Live Jam is off until it is installed.`);
121
- return "bad-agent";
122
- }
123
- return agent;
124
- }
125
- /** Resolve the jam block. Live Jam is ON by default: an absent or partial `jam` resolves
126
- * to whatever agent CLI this machine has, so a fresh workspace jams with nothing
127
- * configured and an old one needs no re-init. `jam: false` is the off switch. */
128
- function resolveJam(v) {
129
- if (v === false) return "opted-out";
130
- const shape = v === void 0 || v === true ? {} : typeof v === "string" ? { agent: v } : plainObject(v) ? v : null;
131
- if (!shape) {
132
- console.warn(`[marver] design/config.ts: jam must be false, an agent name, or an options object - got ${show(v)}. Live Jam is off.`);
133
- return "bad-agent";
134
- }
135
- const j = shape;
136
- const agent = resolveAgent(j.agent);
137
- if (agent === "no-agent" || agent === "bad-agent") return agent;
138
- const c = j.concurrency;
139
- const pick = (key, v, ok, fallback, want) => {
140
- if (v === void 0) return fallback;
141
- if (ok(v)) return v;
142
- console.warn(`[marver] design/config.ts: jam.${key} must be ${want} - got ${show(v)}. Using ${JSON.stringify(fallback)}.`);
143
- return fallback;
144
- };
145
- const bool = (v) => typeof v === "boolean";
146
- return {
147
- agent,
148
- concurrency: typeof c === "number" && Number.isInteger(c) && c >= 1 && c <= 16 ? c : DEFAULT_CONCURRENCY,
149
- subagents: j.subagents !== false,
150
- proactive: j.proactive === true,
151
- chime: pick("chime", j.chime, bool, true, "true or false"),
152
- capture: pick("capture", j.capture, (v) => v === "confirm" || v === "at-once", "confirm", `'confirm' or 'at-once'`),
153
- loc: pick("loc", j.loc, bool, true, "true or false"),
154
- names: pick("names", j.names, bool, true, "true or false")
155
- };
156
- }
157
- /** Exactly one of `jam` (armed) or `jamOff` (why not) - so the dev server can speak up about
158
- * the one off-state nothing has reported yet, and stay quiet about the rest. BOTH keys are
159
- * always written: these spread over the user's own `jam`, and a raw `jam: false` reaching the
160
- * server as config would arm the daemon against a truthy object check. */
161
- function jamFields(v) {
162
- const r = resolveJam(v);
163
- return typeof r === "string" ? {
164
- jam: void 0,
165
- jamOff: r
166
- } : {
167
- jam: r,
168
- jamOff: void 0
169
- };
170
- }
171
- function validViewports(v) {
172
- if (!v || typeof v !== "object") return null;
173
- const out = {};
174
- for (const [k, val] of Object.entries(v)) {
175
- const vp = val;
176
- if (validDim(vp?.width) && validDim(vp?.height)) out[k] = {
177
- width: Math.round(vp.width),
178
- height: Math.round(vp.height)
179
- };
180
- }
181
- return Object.keys(out).length ? out : null;
182
- }
183
- //#endregion
184
24
  //#region src/shared/frames.ts
185
25
  /** A canvas made of content frames alone (Doc, Md, Diagram ship their own styling) needs no theme -
186
26
  * only an app frame does (#4). Empty counts as not content-only: the warning still helps there. */
@@ -310,122 +150,6 @@ function guardUpdates(server, root, manifest, hooks) {
310
150
  });
311
151
  }
312
152
  //#endregion
313
- //#region src/server/sizes.ts
314
- /**
315
- * Content-frame heights - `design/boards/_sizes.json`, committed.
316
- *
317
- * A content frame (a Doc: markdown, diagrams, images) is as tall as its content, which only a
318
- * render can tell. Measured live, every load started from a guess (3/4 of the width) and grew
319
- * frame by frame, and each growth re-flowed the rows below - the board swam for seconds. The
320
- * height a frame measured at its own width is a fact about the FRAME at that width, not about a
321
- * board (one doc sits on several boards) and not something to write into the frame's source: so
322
- * it lives here, one line per `scene/frame@width`, written by the dev server when the shell
323
- * reports a settled measurement, read before the first layout - dev, `marver build` and the
324
- * published canvas alike. A stale entry is still the best first guess; the live measurement
325
- * corrects it and the file follows. Underscore = infrastructure, never a board (board-tree.ts).
326
- */
327
- const SIZES_FILE = "_sizes.json";
328
- /** `scene/frame@width` - the frame id grammar the focus route accepts, then the width it was measured at. */
329
- const SIZE_KEY = /^([\w./-]{1,200})@(\d{2,4})$/;
330
- const ABOUT = "Written by marver dev: the height each content frame measured at its width, so boards open at their final size. Commit it; never edit it by hand.";
331
- const sizesPath = (root) => join(root, "design", "boards", SIZES_FILE);
332
- /** A valid entry: a well-formed key whose frame is not a traversal, and a height in the shell's clamp. */
333
- function validEntry(key, h) {
334
- if (typeof key !== "string" || typeof h !== "number" || !Number.isInteger(h) || h < 80 || h > 4e4) return false;
335
- const m = SIZE_KEY.exec(key);
336
- return !!m && !m[1].split("/").some((p) => p === ".." || p === "." || p === "");
337
- }
338
- function readSizesFile(root) {
339
- const file = sizesPath(root);
340
- if (!existsSync(file)) return {
341
- state: "absent",
342
- heights: {}
343
- };
344
- try {
345
- const raw = JSON.parse(readFileSync(file, "utf8"));
346
- if (!raw || typeof raw !== "object" || !raw.heights || typeof raw.heights !== "object" || Array.isArray(raw.heights)) return {
347
- state: "invalid",
348
- heights: {}
349
- };
350
- const out = {};
351
- for (const [k, v] of Object.entries(raw.heights)) if (validEntry(k, v)) out[k] = v;
352
- return {
353
- state: "ok",
354
- heights: out
355
- };
356
- } catch {
357
- return {
358
- state: "invalid",
359
- heights: {}
360
- };
361
- }
362
- }
363
- /** Lenient read for the readers (the shell's first layout, the build): an absent or invalid file is
364
- * no heights - every frame opens at its placeholder, as before. Never throws. */
365
- const readSizes = (root) => readSizesFile(root).heights;
366
- /** The file's text for a set of heights: sorted keys, one entry per line - a changed height is a
367
- * one-line diff, and two branches that measured different frames merge without a conflict. */
368
- function serializeSizes(heights) {
369
- const sorted = {};
370
- for (const k of Object.keys(heights).sort()) sorted[k] = heights[k];
371
- return JSON.stringify({
372
- about: ABOUT,
373
- heights: sorted
374
- }, null, 2) + "\n";
375
- }
376
- const keeps = (key, autoWidth) => {
377
- const m = SIZE_KEY.exec(key);
378
- return !!m && autoWidth(m[1]) === Number(m[2]);
379
- };
380
- /** Merge incoming heights into the current ones, keeping only what a board can use: a content frame
381
- * that still exists, at the width it measures at on its own. Everything else is pruned - a deleted
382
- * frame, a Doc that went from document to wide. Returns the next map and the keys taken. Pruning
383
- * reads only the manifest: whether a frame still renders a Doc is asked on READ (keptSizes), so a
384
- * source caught mid-write can hide an entry for one load, never delete it. */
385
- function mergeSizes(current, incoming, autoWidth) {
386
- const next = Object.fromEntries(Object.entries(current).filter(([k]) => keeps(k, autoWidth)));
387
- const accepted = [];
388
- for (const [k, v] of Object.entries(incoming)) {
389
- if (!validEntry(k, v) || !keeps(k, autoWidth)) continue;
390
- next[k] = v;
391
- accepted.push(k);
392
- }
393
- return {
394
- next,
395
- accepted
396
- };
397
- }
398
- /** The entries a board can use - what the GET and the build hand the shell: a content frame at its
399
- * own width that MEASURES (renders a Doc). A frame that went from a Doc to a bare Md keeps the size
400
- * its board gives it, never an old measurement. */
401
- const keptSizes = (heights, autoWidth, measuring) => Object.fromEntries(Object.entries(heights).filter(([k]) => keeps(k, autoWidth) && measuring.has(k.slice(0, k.lastIndexOf("@")))));
402
- /** The auto width rule over a manifest's frames (the shell's defaultSize, store.ts). */
403
- function autoWidthOf(frames, viewports) {
404
- const byId = new Map(frames.map((f) => [f.id, f]));
405
- return (id) => {
406
- const f = byId.get(id);
407
- if (!f?.contentWidth) return null;
408
- return viewports[f.viewport ?? ""]?.width ?? f.contentWidth;
409
- };
410
- }
411
- /** The content frames that measure: the frame renders a Doc, or a `_layout` it renders inside does
412
- * (manifest.ts layoutDocSource - the same rule the manifest's width follows). A source that cannot
413
- * be read, or reads empty (an editor mid-write), gets the benefit of the doubt - this only decides
414
- * what a load is handed, never what the file keeps. */
415
- function measuringFrames(root, frames) {
416
- const out = /* @__PURE__ */ new Set();
417
- const memo = /* @__PURE__ */ new Map();
418
- for (const f of frames) {
419
- if (!f.contentWidth || f.kind === "html" || !f.file || f.file.split("/").includes("..")) continue;
420
- let src = "";
421
- try {
422
- src = readFileSync(join(root, f.file), "utf8");
423
- } catch {}
424
- if (!src.trim() || rendersDoc(src) || layoutDocSource(root, f.file, memo) !== null) out.add(f.id);
425
- }
426
- return out;
427
- }
428
- //#endregion
429
153
  //#region src/shared/perf-run.ts
430
154
  /** A run's own generated id: the same in the URL, the request headers and the output line (A3.4). */
431
155
  const RUN_ID = /^[0-9a-f]{16}$/;
@@ -2699,6 +2423,32 @@ function readBody(req, limit = BODY_LIMIT) {
2699
2423
  req.on("error", () => done(null));
2700
2424
  });
2701
2425
  }
2426
+ /** A raw body (A4.6 #37): `limit` counted as the bytes arrive, never trusting `content-length` - past it `large`, and
2427
+ * nothing more is kept; `stop` ends the read where it stands. The socket is left alone, so the answer still goes out. */
2428
+ function readBytes(req, limit, stop) {
2429
+ return new Promise((done) => {
2430
+ let size = 0, settled = false;
2431
+ const chunks = [];
2432
+ const end = (v) => {
2433
+ if (!settled) {
2434
+ settled = true;
2435
+ chunks.length = 0;
2436
+ done(v);
2437
+ }
2438
+ };
2439
+ req.on("data", (c) => {
2440
+ if (settled) return;
2441
+ size += c.length;
2442
+ if (size > limit) end("large");
2443
+ else chunks.push(c);
2444
+ });
2445
+ req.on("end", () => end(Buffer.concat(chunks)));
2446
+ req.on("error", () => end("error"));
2447
+ stop?.addEventListener("abort", () => end("stopped"), { once: true });
2448
+ });
2449
+ }
2450
+ /** A live picture's bytes at most (A4.6 #37): a 4096 px image of a design is well under it. */
2451
+ const LIVE_PICTURE_MAX = 8388608;
2702
2452
  /** Atomic write: random temp name (no predictable symlink target), rename, and a
2703
2453
  * copy-fallback only for the Windows rename errors - anything else rethrows. */
2704
2454
  function atomicWrite(file, content) {
@@ -2788,6 +2538,31 @@ function apiMiddleware(root, opts = {}) {
2788
2538
  try {
2789
2539
  for (const f of readdirSync(boardsDir)) if (f.endsWith(".tmp")) rmSync(join(boardsDir, f), { force: true });
2790
2540
  } catch {}
2541
+ /** `POST jam/picture/live?capture=&frame=` (A4.6 #37), in order: a PNG body, a capture id, a frame of the manifest, a
2542
+ * capture not sealed; then the bytes, 8 MB at most as they arrive, their signature and the whole PNG; and the capture
2543
+ * still not sealed, just before it is stored. Nothing is stored once `stop` (the deadline) has fired. */
2544
+ const livePicture = async (req, url, stop) => {
2545
+ const { CAPTURE_ID, addPictureBytes, checkPng, isPng, readCapture, sweepPictures } = await import("./capture-DEtM4qm5.mjs").then((n) => n.i);
2546
+ if (String(req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase() !== "image/png") return [415, { error: "expected image/png" }];
2547
+ const capture = url.searchParams.get("capture") ?? "", frame = url.searchParams.get("frame") ?? "";
2548
+ if (!CAPTURE_ID.test(capture)) return [400, { error: "bad capture id" }];
2549
+ if (!devFrames().some((f) => f.id === frame)) return [404, { error: "unknown frame" }];
2550
+ if (readCapture(root, capture)) return [409, { error: "that capture is sealed" }];
2551
+ const png = await readBytes(req, LIVE_PICTURE_MAX, stop);
2552
+ if (png === "large") return [413, { error: `a live picture is ${LIVE_PICTURE_MAX / 2 ** 20} MB at most` }];
2553
+ if (typeof png === "string") return [400, { error: "the picture did not arrive whole" }];
2554
+ if (!isPng(png)) return [415, { error: "not a PNG" }];
2555
+ const checked = await checkPng(png);
2556
+ if (typeof checked === "string") return [400, { error: `not a picture it takes: ${checked}` }];
2557
+ if (stop.aborted) return [408, { error: "the picture took too long" }];
2558
+ if (readCapture(root, capture)) return [409, { error: "that capture is sealed" }];
2559
+ sweepPictures(root);
2560
+ return [200, { id: addPictureBytes(root, png, {
2561
+ frame,
2562
+ capture,
2563
+ source: "live"
2564
+ }) }];
2565
+ };
2791
2566
  return async (req, res, next) => {
2792
2567
  const url = new URL(req.url ?? "/", "http://x");
2793
2568
  if (!url.pathname.startsWith(`/__mv/api/`)) return next();
@@ -2864,126 +2639,136 @@ function apiMiddleware(root, opts = {}) {
2864
2639
  const file = boardPath(name);
2865
2640
  if (!file) return json(res, 400, { error: "invalid board name" });
2866
2641
  if (!existsSync(file)) return json(res, 404, { error: `board "${name}" does not exist` });
2867
- if (!notSymlink(file)) return json(res, 400, { error: "refusing to write a symlinked board file" });
2868
- const current = readFileSync(file, "utf8");
2869
- if (baseHash !== void 0 && baseHash !== hash(current)) return json(res, 409, {
2870
- error: "board changed on disk",
2871
- sha256: hash(current)
2642
+ const unlock = await takeFileLock(boardLock(boardsDir, name), 2e3).catch((e) => {
2643
+ if (e.code === "EACCES" || e.code === "EPERM" || e.code === "EROFS") return () => {};
2644
+ throw e;
2872
2645
  });
2873
- let obj;
2646
+ if (!unlock) return json(res, 503, { error: "the board is being written - try again" });
2874
2647
  try {
2875
- obj = JSON.parse(current);
2876
- } catch {
2877
- return json(res, 422, { error: `board "${name}" is not valid JSON - fix the file` });
2878
- }
2879
- if (!obj || typeof obj !== "object" || Array.isArray(obj)) return json(res, 422, { error: `board "${name}" is not a JSON object - fix the file` });
2880
- const reg = readRegistry(boardsDir);
2881
- const regFolders = reg.state === "ok" ? reg.folders : [];
2882
- const all = listBoardFiles(boardsDir).boards;
2883
- const fm = folderMap(buildTree(all.map((b) => ({
2884
- name: b.name,
2885
- ...boardFields(b.json, validName)
2886
- })), regFolders));
2887
- const folder = regFolders.find((f) => f.name === fm.get(name));
2888
- const parent = folder?.parent ? regFolders.find((f) => f.name === folder.parent) : void 0;
2889
- const type = resolveType(obj.type, folder?.type, parent?.type);
2890
- if (!HAS_STATUS.includes(type)) return json(res, 422, { error: `a ${type} board carries no status - only feature and project boards do` });
2891
- const facts = readContextFacts(root);
2892
- const capability = readCapability(obj.capability) ?? name;
2893
- const plans = facts.present ? facts.plans.get(capability) ?? [] : [];
2894
- if (status !== null && !settableStatuses(facts.present, plans.length > 0).includes(status)) return json(res, 422, { error: status === "done" ? "Done is never set by hand - it comes from context/shipped.md" : status === "building" || status === "in-progress" ? `${status === "building" ? "Building" : "In progress"} needs an open plan naming ${capability} - context/plans/` : `with context/, ${status} is read from the evidence - a plan, a contract, the shipped record` });
2895
- const writes = [];
2896
- if (facts.present && (status === "building" || status === "in-progress")) {
2897
- for (const p of plans.filter((x, i) => plans.findIndex((y) => y.where === x.where) === i)) {
2898
- const file = join(root, p.where);
2899
- if (!notSymlink(file)) return json(res, 400, { error: `refusing to write a symlinked plan (${p.where})` });
2900
- const raw = readFileSync(file, "utf8");
2901
- if (!planNames(raw, capability)) return json(res, 409, { error: `${p.where} changed on disk - try again` });
2902
- const r = planWithStage(raw, status === "building" ? "build" : null);
2903
- if ("error" in r) return json(res, 422, { error: `${p.where} ${r.error} - fix the file` });
2904
- writes.push({
2905
- file,
2906
- raw,
2907
- next: r.text,
2908
- plan: p.where
2909
- });
2910
- }
2911
- delete obj.status;
2912
- delete obj.reason;
2913
- } else {
2914
- if (status === null) delete obj.status;
2915
- else obj.status = status;
2916
- if (status === "blocked") obj.reason = reason;
2917
- else delete obj.reason;
2918
- }
2919
- const next = JSON.stringify(obj, null, 2) + "\n";
2920
- writes.push({
2921
- file,
2922
- raw: current,
2923
- next
2924
- });
2925
- const current_ = (f) => {
2648
+ if (!existsSync(file)) return json(res, 404, { error: `board "${name}" does not exist` });
2649
+ if (!notSymlink(file)) return json(res, 400, { error: "refusing to write a symlinked board file" });
2650
+ const current = readFileSync(file, "utf8");
2651
+ if (baseHash !== void 0 && baseHash !== hash(current)) return json(res, 409, {
2652
+ error: "board changed on disk",
2653
+ sha256: hash(current)
2654
+ });
2655
+ let obj;
2926
2656
  try {
2927
- return readFileSync(f, "utf8");
2657
+ obj = JSON.parse(current);
2928
2658
  } catch {
2929
- return null;
2659
+ return json(res, 422, { error: `board "${name}" is not valid JSON - fix the file` });
2930
2660
  }
2931
- };
2932
- const done = [];
2933
- const undo = () => {
2934
- const stuck = [];
2935
- for (const w of done.reverse()) {
2936
- const label = w.plan ?? `design/boards/${name}.json`;
2937
- let tmp;
2661
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) return json(res, 422, { error: `board "${name}" is not a JSON object - fix the file` });
2662
+ const reg = readRegistry(boardsDir);
2663
+ const regFolders = reg.state === "ok" ? reg.folders : [];
2664
+ const all = listBoardFiles(boardsDir).boards;
2665
+ const fm = folderMap(buildTree(all.map((b) => ({
2666
+ name: b.name,
2667
+ ...boardFields(b.json, validName)
2668
+ })), regFolders));
2669
+ const folder = regFolders.find((f) => f.name === fm.get(name));
2670
+ const parent = folder?.parent ? regFolders.find((f) => f.name === folder.parent) : void 0;
2671
+ const type = resolveType(obj.type, folder?.type, parent?.type);
2672
+ if (!HAS_STATUS.includes(type)) return json(res, 422, { error: `a ${type} board carries no status - only feature and project boards do` });
2673
+ const facts = readContextFacts(root);
2674
+ const capability = readCapability(obj.capability) ?? name;
2675
+ const plans = facts.present ? facts.plans.get(capability) ?? [] : [];
2676
+ if (status !== null && !settableStatuses(facts.present, plans.length > 0).includes(status)) return json(res, 422, { error: status === "done" ? "Done is never set by hand - it comes from context/shipped.md" : status === "building" || status === "in-progress" ? `${status === "building" ? "Building" : "In progress"} needs an open plan naming ${capability} - context/plans/` : `with context/, ${status} is read from the evidence - a plan, a contract, the shipped record` });
2677
+ const writes = [];
2678
+ if (facts.present && (status === "building" || status === "in-progress")) {
2679
+ for (const p of plans.filter((x, i) => plans.findIndex((y) => y.where === x.where) === i)) {
2680
+ const file = join(root, p.where);
2681
+ if (!notSymlink(file)) return json(res, 400, { error: `refusing to write a symlinked plan (${p.where})` });
2682
+ const raw = readFileSync(file, "utf8");
2683
+ if (!planNames(raw, capability)) return json(res, 409, { error: `${p.where} changed on disk - try again` });
2684
+ const r = planWithStage(raw, status === "building" ? "build" : null);
2685
+ if ("error" in r) return json(res, 422, { error: `${p.where} ${r.error} - fix the file` });
2686
+ writes.push({
2687
+ file,
2688
+ raw,
2689
+ next: r.text,
2690
+ plan: p.where
2691
+ });
2692
+ }
2693
+ delete obj.status;
2694
+ delete obj.reason;
2695
+ } else {
2696
+ if (status === null) delete obj.status;
2697
+ else obj.status = status;
2698
+ if (status === "blocked") obj.reason = reason;
2699
+ else delete obj.reason;
2700
+ }
2701
+ const next = JSON.stringify(obj, null, 2) + "\n";
2702
+ writes.push({
2703
+ file,
2704
+ raw: current,
2705
+ next
2706
+ });
2707
+ const current_ = (f) => {
2938
2708
  try {
2939
- tmp = stageWrite(w.file, w.raw);
2709
+ return readFileSync(f, "utf8");
2940
2710
  } catch {
2941
- stuck.push(label);
2942
- continue;
2711
+ return null;
2943
2712
  }
2944
- if (current_(w.file) !== w.next) {
2945
- discard(tmp);
2946
- stuck.push(`${label} (edited since - kept)`);
2947
- continue;
2713
+ };
2714
+ const done = [];
2715
+ const undo = () => {
2716
+ const stuck = [];
2717
+ for (const w of done.reverse()) {
2718
+ const label = w.plan ?? `design/boards/${name}.json`;
2719
+ let tmp;
2720
+ try {
2721
+ tmp = stageWrite(w.file, w.raw);
2722
+ } catch {
2723
+ stuck.push(label);
2724
+ continue;
2725
+ }
2726
+ if (current_(w.file) !== w.next) {
2727
+ discard(tmp);
2728
+ stuck.push(`${label} (edited since - kept)`);
2729
+ continue;
2730
+ }
2731
+ try {
2732
+ renameSync(tmp, w.file);
2733
+ } catch {
2734
+ discard(tmp);
2735
+ stuck.push(label);
2736
+ }
2948
2737
  }
2738
+ return stuck;
2739
+ };
2740
+ for (const w of writes) {
2741
+ if (w.next === w.raw) continue;
2742
+ let tmp = null;
2949
2743
  try {
2744
+ tmp = stageWrite(w.file, w.next);
2745
+ const now = current_(w.file);
2746
+ if (now !== w.raw) {
2747
+ discard(tmp);
2748
+ const stuck = undo();
2749
+ if (stuck.length) return json(res, 500, { error: `${w.plan ?? `board "${name}"`} changed on disk mid-write, and ${stuck.join(", ")} still ${stuck.length === 1 ? "holds" : "hold"} this change - check by hand` });
2750
+ return json(res, 409, {
2751
+ error: `${w.plan ?? `board "${name}"`} changed on disk - try again`,
2752
+ ...w.plan || now === null ? {} : { sha256: hash(now) }
2753
+ });
2754
+ }
2950
2755
  renameSync(tmp, w.file);
2951
- } catch {
2952
- discard(tmp);
2953
- stuck.push(label);
2954
- }
2955
- }
2956
- return stuck;
2957
- };
2958
- for (const w of writes) {
2959
- if (w.next === w.raw) continue;
2960
- let tmp = null;
2961
- try {
2962
- tmp = stageWrite(w.file, w.next);
2963
- const now = current_(w.file);
2964
- if (now !== w.raw) {
2965
- discard(tmp);
2756
+ done.push(w);
2757
+ } catch (err) {
2758
+ if (tmp) discard(tmp);
2966
2759
  const stuck = undo();
2967
- if (stuck.length) return json(res, 500, { error: `${w.plan ?? `board "${name}"`} changed on disk mid-write, and ${stuck.join(", ")} still ${stuck.length === 1 ? "holds" : "hold"} this change - check by hand` });
2968
- return json(res, 409, {
2969
- error: `${w.plan ?? `board "${name}"`} changed on disk - try again`,
2970
- ...w.plan || now === null ? {} : { sha256: hash(now) }
2971
- });
2760
+ const off = writes.filter((x) => x.next !== x.raw && current_(x.file) !== x.raw).map((x) => x.plan ?? `design/boards/${name}.json`);
2761
+ const named = [.../* @__PURE__ */ new Set([...stuck, ...off.filter((o) => !stuck.some((s) => s.startsWith(o)))])];
2762
+ return json(res, 500, { error: named.length ? `could not write the status (${err.message}), and ${named.join(", ")} ${named.length === 1 ? "is" : "are"} not as before - check by hand` : `could not write the status (${err.message}) - nothing changed` });
2972
2763
  }
2973
- renameSync(tmp, w.file);
2974
- done.push(w);
2975
- } catch (err) {
2976
- if (tmp) discard(tmp);
2977
- const stuck = undo();
2978
- const off = writes.filter((x) => x.next !== x.raw && current_(x.file) !== x.raw).map((x) => x.plan ?? `design/boards/${name}.json`);
2979
- const named = [.../* @__PURE__ */ new Set([...stuck, ...off.filter((o) => !stuck.some((s) => s.startsWith(o)))])];
2980
- return json(res, 500, { error: named.length ? `could not write the status (${err.message}), and ${named.join(", ")} ${named.length === 1 ? "is" : "are"} not as before - check by hand` : `could not write the status (${err.message}) - nothing changed` });
2981
2764
  }
2765
+ return json(res, 200, {
2766
+ name,
2767
+ sha256: hash(next)
2768
+ });
2769
+ } finally {
2770
+ unlock();
2982
2771
  }
2983
- return json(res, 200, {
2984
- name,
2985
- sha256: hash(next)
2986
- });
2987
2772
  }
2988
2773
  const readManifestFrames = () => {
2989
2774
  try {
@@ -3006,7 +2791,7 @@ function apiMiddleware(root, opts = {}) {
3006
2791
  const str = (v) => typeof v === "string" ? v.slice(0, 200) : void 0;
3007
2792
  const num = (v) => typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
3008
2793
  if (!str(b?.kind)) return json(res, 400, { error: "kind required" });
3009
- (await import("./perf-jam-BaH3Lg0m.mjs").then((n) => n.c)).logReload(root, {
2794
+ (await import("./perf-jam-CLkERSHo.mjs").then((n) => n.c)).logReload(root, {
3010
2795
  kind: str(b.kind),
3011
2796
  tab: str(b.tab),
3012
2797
  node: str(b.node),
@@ -3028,7 +2813,7 @@ function apiMiddleware(root, opts = {}) {
3028
2813
  return json(res, 400, { error: "malformed JSON" });
3029
2814
  }
3030
2815
  if (!b || b.kind !== "capture" && b.kind !== "upload") return json(res, 400, { error: "kind must be capture or upload" });
3031
- (await import("./perf-jam-BaH3Lg0m.mjs").then((n) => n.n)).logJam(root, b);
2816
+ (await import("./perf-jam-CLkERSHo.mjs").then((n) => n.n)).logJam(root, b);
3032
2817
  return json(res, 200, { ok: true });
3033
2818
  }
3034
2819
  if (path === "perf/page" && req.method === "POST") {
@@ -3053,7 +2838,7 @@ function apiMiddleware(root, opts = {}) {
3053
2838
  });
3054
2839
  }
3055
2840
  if (path === "perf/run" && req.method === "POST" || path === "perf/inputs" && req.method === "GET") {
3056
- const { readDevInfo } = await import("./work-CNhFF9pU.mjs").then((n) => n.o);
2841
+ const { readDevInfo } = await import("./work-DJxH7cCX.mjs").then((n) => n.o);
3057
2842
  const token = readDevInfo(root)?.token;
3058
2843
  if (!ownerGated(req) && !(token && req.headers["x-mv-work"] === token)) return json(res, 403, { error: "forbidden" });
3059
2844
  if (path === "perf/inputs") {
@@ -3193,56 +2978,63 @@ function apiMiddleware(root, opts = {}) {
3193
2978
  const fromPath = boardPath(from), toPath = boardPath(to);
3194
2979
  if (!fromPath || !toPath) return json(res, 400, { error: "invalid board name" });
3195
2980
  if (!existsSync(fromPath)) return json(res, 404, { error: `board "${from}" does not exist` });
3196
- if (!notSymlink(fromPath)) return json(res, 400, { error: "refusing to rename a symlinked board file" });
3197
- const current = readFileSync(fromPath, "utf8");
3198
- if (baseHash !== void 0 && baseHash !== hash(current)) return json(res, 409, {
3199
- error: "board changed on disk",
3200
- sha256: hash(current)
3201
- });
3202
- let obj = null;
3203
- if (titleRaw !== void 0) {
3204
- let parsedBoard;
3205
- try {
3206
- parsedBoard = JSON.parse(current);
3207
- } catch {
3208
- return json(res, 422, { error: `board "${from}" is not valid JSON - fix the file` });
2981
+ const unlock = await takeFileLock(boardLock(boardsDir, from), 2e3);
2982
+ if (!unlock) return json(res, 503, { error: "the board is being written - try again" });
2983
+ try {
2984
+ if (!existsSync(fromPath)) return json(res, 404, { error: `board "${from}" does not exist` });
2985
+ if (!notSymlink(fromPath)) return json(res, 400, { error: "refusing to rename a symlinked board file" });
2986
+ const current = readFileSync(fromPath, "utf8");
2987
+ if (baseHash !== void 0 && baseHash !== hash(current)) return json(res, 409, {
2988
+ error: "board changed on disk",
2989
+ sha256: hash(current)
2990
+ });
2991
+ let obj = null;
2992
+ if (titleRaw !== void 0) {
2993
+ let parsedBoard;
2994
+ try {
2995
+ parsedBoard = JSON.parse(current);
2996
+ } catch {
2997
+ return json(res, 422, { error: `board "${from}" is not valid JSON - fix the file` });
2998
+ }
2999
+ if (!parsedBoard || typeof parsedBoard !== "object" || Array.isArray(parsedBoard)) return json(res, 422, { error: `board "${from}" is not a JSON object - fix the file` });
3000
+ obj = parsedBoard;
3209
3001
  }
3210
- if (!parsedBoard || typeof parsedBoard !== "object" || Array.isArray(parsedBoard)) return json(res, 422, { error: `board "${from}" is not a JSON object - fix the file` });
3211
- obj = parsedBoard;
3212
- }
3213
- let next;
3214
- if (obj) {
3215
- const title = readTitle(titleRaw);
3216
- if (title) obj.title = title;
3217
- else delete obj.title;
3218
- next = JSON.stringify(obj, null, 2) + "\n";
3219
- }
3220
- if (to !== from) {
3221
- if (isConnected(root)) return json(res, 409, { error: "disconnect before renaming boards - comment sync is board-keyed" });
3222
- if (existsSync(join(root, "design", "comments", `${from}.jsonl`))) return json(res, 409, { error: "rename a board before commenting on it - this board has threads" });
3223
- if (nodeExists$1(toPath)) return json(res, 409, { error: `a board named "${to}" already exists` });
3224
- try {
3225
- if (next !== void 0) writeFileSync(toPath, next, { flag: "wx" });
3226
- else linkSync(fromPath, toPath);
3227
- } catch (err) {
3228
- const code = err.code;
3229
- if (code === "EEXIST") return json(res, 409, { error: `a board named "${to}" already exists` });
3230
- if (next !== void 0 || code !== "EPERM" && code !== "ENOSYS" && code !== "ENOTSUP" && code !== "EOPNOTSUPP") throw err;
3002
+ let next;
3003
+ if (obj) {
3004
+ const title = readTitle(titleRaw);
3005
+ if (title) obj.title = title;
3006
+ else delete obj.title;
3007
+ next = JSON.stringify(obj, null, 2) + "\n";
3008
+ }
3009
+ if (to !== from) {
3010
+ if (isConnected(root)) return json(res, 409, { error: "disconnect before renaming boards - comment sync is board-keyed" });
3011
+ if (existsSync(join(root, "design", "comments", `${from}.jsonl`))) return json(res, 409, { error: "rename a board before commenting on it - this board has threads" });
3231
3012
  if (nodeExists$1(toPath)) return json(res, 409, { error: `a board named "${to}" already exists` });
3232
- renameSync(fromPath, toPath);
3233
- return json(res, 200, { name: to });
3013
+ try {
3014
+ if (next !== void 0) writeFileSync(toPath, next, { flag: "wx" });
3015
+ else linkSync(fromPath, toPath);
3016
+ } catch (err) {
3017
+ const code = err.code;
3018
+ if (code === "EEXIST") return json(res, 409, { error: `a board named "${to}" already exists` });
3019
+ if (next !== void 0 || code !== "EPERM" && code !== "ENOSYS" && code !== "ENOTSUP" && code !== "EOPNOTSUPP") throw err;
3020
+ if (nodeExists$1(toPath)) return json(res, 409, { error: `a board named "${to}" already exists` });
3021
+ renameSync(fromPath, toPath);
3022
+ return json(res, 200, { name: to });
3023
+ }
3024
+ rmSync(fromPath);
3025
+ return json(res, 200, {
3026
+ name: to,
3027
+ ...next !== void 0 ? { sha256: hash(next) } : {}
3028
+ });
3234
3029
  }
3235
- rmSync(fromPath);
3030
+ atomicWrite(toPath, next);
3236
3031
  return json(res, 200, {
3237
3032
  name: to,
3238
- ...next !== void 0 ? { sha256: hash(next) } : {}
3033
+ sha256: hash(next)
3239
3034
  });
3035
+ } finally {
3036
+ unlock();
3240
3037
  }
3241
- atomicWrite(toPath, next);
3242
- return json(res, 200, {
3243
- name: to,
3244
- sha256: hash(next)
3245
- });
3246
3038
  }
3247
3039
  if (path === "scenes/rename" && req.method === "POST") {
3248
3040
  if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
@@ -3380,41 +3172,54 @@ function apiMiddleware(root, opts = {}) {
3380
3172
  stale
3381
3173
  });
3382
3174
  const sha256 = {};
3383
- for (const w of plan) {
3384
- if (w.obj.order === w.order && (w.folder ? w.obj.folder === w.folder : w.obj.folder === void 0)) continue;
3385
- if (hash(readFileSync(w.path, "utf8")) !== b.boards[w.name]) return reply(409, {
3386
- error: "boards changed on disk",
3387
- stale: [w.name]
3175
+ const writes = plan.filter((w) => !(w.obj.order === w.order && (w.folder ? w.obj.folder === w.folder : w.obj.folder === void 0)));
3176
+ const unlocks = [];
3177
+ try {
3178
+ for (const w of writes) {
3179
+ const u = tryFileLock(boardLock(boardsDir, w.name));
3180
+ if (!u) return reply(409, {
3181
+ error: "boards changed on disk",
3182
+ stale: [w.name]
3183
+ });
3184
+ unlocks.push(u);
3185
+ }
3186
+ for (const w of writes) {
3187
+ if (hash(readFileSync(w.path, "utf8")) !== b.boards[w.name]) return reply(409, {
3188
+ error: "boards changed on disk",
3189
+ stale: [w.name]
3190
+ });
3191
+ w.obj.order = w.order;
3192
+ if (w.folder) w.obj.folder = w.folder;
3193
+ else delete w.obj.folder;
3194
+ const next = JSON.stringify(w.obj, null, 2) + "\n";
3195
+ atomicWrite(w.path, next);
3196
+ sha256[w.name] = hash(next);
3197
+ }
3198
+ mkdirSync(boardsDir, { recursive: true });
3199
+ if ((nodeExists(foldersPath) ? hash(readFileSync(foldersPath, "utf8")) : null) !== b.folders) return reply(409, {
3200
+ error: "folders changed on disk",
3201
+ stale: [FOLDERS_FILE]
3202
+ });
3203
+ let foldersSha = null;
3204
+ if (folders.length) {
3205
+ const version = folders.some((f) => f.parent) ? 2 : 1;
3206
+ const next = JSON.stringify({
3207
+ version,
3208
+ folders
3209
+ }, null, 2) + "\n";
3210
+ atomicWrite(foldersPath, next);
3211
+ foldersSha = hash(next);
3212
+ } else rmSync(foldersPath, { force: true });
3213
+ return reply(200, {
3214
+ ok: true,
3215
+ sha256: {
3216
+ boards: sha256,
3217
+ folders: foldersSha
3218
+ }
3388
3219
  });
3389
- w.obj.order = w.order;
3390
- if (w.folder) w.obj.folder = w.folder;
3391
- else delete w.obj.folder;
3392
- const next = JSON.stringify(w.obj, null, 2) + "\n";
3393
- atomicWrite(w.path, next);
3394
- sha256[w.name] = hash(next);
3220
+ } finally {
3221
+ for (const u of unlocks) u();
3395
3222
  }
3396
- mkdirSync(boardsDir, { recursive: true });
3397
- if ((nodeExists(foldersPath) ? hash(readFileSync(foldersPath, "utf8")) : null) !== b.folders) return reply(409, {
3398
- error: "folders changed on disk",
3399
- stale: [FOLDERS_FILE]
3400
- });
3401
- let foldersSha = null;
3402
- if (folders.length) {
3403
- const version = folders.some((f) => f.parent) ? 2 : 1;
3404
- const next = JSON.stringify({
3405
- version,
3406
- folders
3407
- }, null, 2) + "\n";
3408
- atomicWrite(foldersPath, next);
3409
- foldersSha = hash(next);
3410
- } else rmSync(foldersPath, { force: true });
3411
- return reply(200, {
3412
- ok: true,
3413
- sha256: {
3414
- boards: sha256,
3415
- folders: foldersSha
3416
- }
3417
- });
3418
3223
  });
3419
3224
  if (!locked) return json(res, 409, {
3420
3225
  error: "folders changed on disk",
@@ -3450,32 +3255,39 @@ function apiMiddleware(root, opts = {}) {
3450
3255
  error: "board no longer exists on disk",
3451
3256
  gone: true
3452
3257
  });
3453
- const current = existsSync(p) ? readFileSync(p, "utf8") : "";
3454
- if (current && body.baseHash !== hash(current)) {
3455
- let disk = null;
3456
- try {
3457
- disk = JSON.parse(current);
3258
+ mkdirSync(boardsDir, { recursive: true });
3259
+ const unlock = await takeFileLock(boardLock(boardsDir, boardMatch[1]), 2e3);
3260
+ if (!unlock) return json(res, 503, { error: "the board is being written - try again" });
3261
+ try {
3262
+ const current = existsSync(p) ? readFileSync(p, "utf8") : "";
3263
+ if (current && body.baseHash !== hash(current)) {
3264
+ let disk = null;
3265
+ try {
3266
+ disk = JSON.parse(current);
3267
+ } catch {}
3268
+ return json(res, 409, {
3269
+ error: "board changed on disk",
3270
+ board: disk,
3271
+ sha256: hash(current)
3272
+ });
3273
+ }
3274
+ mkdirSync(boardsDir, { recursive: true });
3275
+ const incoming = body.board;
3276
+ if (incoming && typeof incoming === "object" && current) try {
3277
+ const disk = JSON.parse(current);
3278
+ const valid = boardFields(disk, validName);
3279
+ for (const k of AUTHOR_FIELDS) if (incoming[k] === void 0 && valid[k] !== void 0) incoming[k] = disk[k];
3458
3280
  } catch {}
3459
- return json(res, 409, {
3460
- error: "board changed on disk",
3461
- board: disk,
3462
- sha256: hash(current)
3463
- });
3281
+ const next2 = JSON.stringify(body.board, null, 2) + "\n";
3282
+ atomicWrite(p, next2);
3283
+ return json(res, 200, { sha256: hash(next2) });
3284
+ } finally {
3285
+ unlock();
3464
3286
  }
3465
- mkdirSync(boardsDir, { recursive: true });
3466
- const incoming = body.board;
3467
- if (incoming && typeof incoming === "object" && current) try {
3468
- const disk = JSON.parse(current);
3469
- const valid = boardFields(disk, validName);
3470
- for (const k of AUTHOR_FIELDS) if (incoming[k] === void 0 && valid[k] !== void 0) incoming[k] = disk[k];
3471
- } catch {}
3472
- const next2 = JSON.stringify(body.board, null, 2) + "\n";
3473
- atomicWrite(p, next2);
3474
- return json(res, 200, { sha256: hash(next2) });
3475
3287
  }
3476
3288
  }
3477
3289
  if (path === "shot" && req.method === "GET") {
3478
- const { readDevInfo } = await import("./work-CNhFF9pU.mjs").then((n) => n.o);
3290
+ const { readDevInfo } = await import("./work-DJxH7cCX.mjs").then((n) => n.o);
3479
3291
  const token = readDevInfo(root)?.token;
3480
3292
  if (!ownerGated(req) && !(token && req.headers["x-mv-work"] === token)) return json(res, 403, { error: "forbidden" });
3481
3293
  const frameId = url.searchParams.get("frame") ?? "";
@@ -3491,7 +3303,7 @@ function apiMiddleware(root, opts = {}) {
3491
3303
  };
3492
3304
  const asPng = url.searchParams.get("format") === "png";
3493
3305
  const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
3494
- const { shootFrame } = await import("./shot-Ch24tiMO.mjs").then((n) => n.u);
3306
+ const { shootFrame } = await import("./shot-T04Ixrvq.mjs").then((n) => n.u);
3495
3307
  const r = await shootFrame({
3496
3308
  root,
3497
3309
  viewports: opts.viewports ?? {},
@@ -3525,7 +3337,7 @@ function apiMiddleware(root, opts = {}) {
3525
3337
  return res.end(png);
3526
3338
  }
3527
3339
  if (path === "shots" && req.method === "POST") {
3528
- const { readDevInfo } = await import("./work-CNhFF9pU.mjs").then((n) => n.o);
3340
+ const { readDevInfo } = await import("./work-DJxH7cCX.mjs").then((n) => n.o);
3529
3341
  const token = readDevInfo(root)?.token;
3530
3342
  if (!ownerGated(req) && !(token && req.headers["x-mv-work"] === token)) return json(res, 403, { error: "forbidden" });
3531
3343
  const raw = await readBody(req);
@@ -3542,7 +3354,7 @@ function apiMiddleware(root, opts = {}) {
3542
3354
  if (typeof theme !== "string" || !/^[a-z0-9-]+$/i.test(theme)) return json(res, 400, { error: "invalid theme" });
3543
3355
  const scale = body.scale === void 0 ? void 0 : body.scale;
3544
3356
  if (scale !== void 0 && !(Number.isInteger(scale) && scale >= 1 && scale <= 4)) return json(res, 400, { error: "invalid scale" });
3545
- const { resolveFrames, shootBatch } = await import("./shot-Ch24tiMO.mjs").then((n) => n.u);
3357
+ const { resolveFrames, shootBatch } = await import("./shot-T04Ixrvq.mjs").then((n) => n.u);
3546
3358
  const sel = resolveFrames(root, body);
3547
3359
  if (!sel.ok) return json(res, sel.status, { error: sel.error });
3548
3360
  const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
@@ -3560,7 +3372,7 @@ function apiMiddleware(root, opts = {}) {
3560
3372
  }
3561
3373
  }
3562
3374
  if (path === "anchor" && req.method === "POST") {
3563
- const { readDevInfo } = await import("./work-CNhFF9pU.mjs").then((n) => n.o);
3375
+ const { readDevInfo } = await import("./work-DJxH7cCX.mjs").then((n) => n.o);
3564
3376
  const token = readDevInfo(root)?.token;
3565
3377
  if (!ownerGated(req) && !(token && req.headers["x-mv-work"] === token)) return json(res, 403, { error: "forbidden" });
3566
3378
  const raw = await readBody(req);
@@ -3576,7 +3388,7 @@ function apiMiddleware(root, opts = {}) {
3576
3388
  if (typeof target === "string") return json(res, 400, { error: target });
3577
3389
  const others = Array.isArray(b.others) ? b.others.filter((o) => typeof o?.key === "string").slice(0, 200) : [];
3578
3390
  const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
3579
- const { checkAnchor, CheckInputError } = await import("./anchor-check-gkxkPAIv.mjs");
3391
+ const { checkAnchor, CheckInputError } = await import("./anchor-check-DhlpKl2K.mjs");
3580
3392
  try {
3581
3393
  return json(res, 200, await checkAnchor({
3582
3394
  root,
@@ -3626,7 +3438,7 @@ function apiMiddleware(root, opts = {}) {
3626
3438
  });
3627
3439
  docs.push(typeof a?.doc === "string" ? a.doc : void 0);
3628
3440
  }
3629
- const { docRev } = await import("./marks-CnCCfAbD.mjs").then((n) => n.i);
3441
+ const { docRev } = await import("./marks-BnNANic9.mjs").then((n) => n.a);
3630
3442
  const all = devManifest().frames;
3631
3443
  const pending = opts.settled ? !opts.settled() : false;
3632
3444
  const behind = docs.map((d, i) => d !== void 0 && (pending || d !== docRev(root, all, asks[i].frame)));
@@ -3684,8 +3496,8 @@ function apiMiddleware(root, opts = {}) {
3684
3496
  return json(res, 400, { error: "malformed JSON" });
3685
3497
  }
3686
3498
  const src = typeof b?.src === "string" ? b.src : "";
3687
- const { ensurePoster, isLocalClip } = await import("./poster-BNgafWMK.mjs");
3688
- const { isLocalAssetRef } = await import("./build-VgNg4rr8.mjs");
3499
+ const { ensurePoster, isLocalClip } = await import("./poster-CrsjqhY4.mjs");
3500
+ const { isLocalAssetRef } = await import("./build-CWbrb2bl.mjs");
3689
3501
  if (!isLocalAssetRef(src) || !isLocalClip(src)) return json(res, 400, { error: "src must be a clip under design/assets/" });
3690
3502
  const r = await ensurePoster(join(root, "design", "assets"), src);
3691
3503
  if (!r.ok) return json(res, r.error.includes("does not exist") ? 404 : 503, { error: r.error });
@@ -3728,7 +3540,7 @@ function apiMiddleware(root, opts = {}) {
3728
3540
  }
3729
3541
  if (path === "marks" || path === "marks/seen") {
3730
3542
  if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
3731
- const { readMarks, markSeen } = await import("./marks-CnCCfAbD.mjs").then((n) => n.i);
3543
+ const { readMarks, markSeen } = await import("./marks-BnNANic9.mjs").then((n) => n.a);
3732
3544
  const manifest = devManifest();
3733
3545
  if (path === "marks" && req.method === "GET") return json(res, 200, readMarks(root, manifest));
3734
3546
  if (path === "marks/seen" && req.method === "POST") {
@@ -3748,14 +3560,14 @@ function apiMiddleware(root, opts = {}) {
3748
3560
  return json(res, 405, { error: "method not allowed" });
3749
3561
  }
3750
3562
  if (path === "work") {
3751
- const { workActivity, readDevInfo, WORK_TTL_DEFAULT, WORK_TTL_MAX } = await import("./work-CNhFF9pU.mjs").then((n) => n.o);
3563
+ const { workActivity, readDevInfo, WORK_TTL_DEFAULT, WORK_TTL_MAX } = await import("./work-DJxH7cCX.mjs").then((n) => n.o);
3752
3564
  const tokenOk = () => {
3753
3565
  const t = readDevInfo(root)?.token;
3754
3566
  return !!t && req.headers["x-mv-work"] === t;
3755
3567
  };
3756
3568
  if (req.method === "GET") {
3757
3569
  if (!ownerGated(req) && !tokenOk()) return json(res, 403, { error: "forbidden" });
3758
- const { boardsShowing, activityClock } = await import("./work-CNhFF9pU.mjs").then((n) => n.o);
3570
+ const { boardsShowing, activityClock } = await import("./work-DJxH7cCX.mjs").then((n) => n.o);
3759
3571
  const frames = workActivity.active();
3760
3572
  return json(res, 200, {
3761
3573
  frames,
@@ -3778,7 +3590,7 @@ function apiMiddleware(root, opts = {}) {
3778
3590
  if (!on && b.all === true) {
3779
3591
  const done = workActivity.active().filter((f) => workActivity.has(f, "cli"));
3780
3592
  if (done.length) {
3781
- (await import("./marks-CnCCfAbD.mjs").then((n) => n.i)).recordChanged(root, devFrames(), done, { doc: false });
3593
+ (await import("./marks-BnNANic9.mjs").then((n) => n.a)).recordChanged(root, devFrames(), done, { doc: false });
3782
3594
  opts.notify?.("sh:marks");
3783
3595
  }
3784
3596
  workActivity.clearAll("cli");
@@ -3798,7 +3610,7 @@ function apiMiddleware(root, opts = {}) {
3798
3610
  for (const f of frames) on ? workActivity.mark(f, ttl, "cli") : workActivity.clear(f, "cli");
3799
3611
  saveHolds(root, workActivity);
3800
3612
  if (!on) {
3801
- (await import("./marks-CnCCfAbD.mjs").then((n) => n.i)).recordChanged(root, devFrames(), frames, { doc: false });
3613
+ (await import("./marks-BnNANic9.mjs").then((n) => n.a)).recordChanged(root, devFrames(), frames, { doc: false });
3802
3614
  opts.notify?.("sh:marks");
3803
3615
  return json(res, 200, { frames: workActivity.active() });
3804
3616
  }
@@ -3834,10 +3646,11 @@ function apiMiddleware(root, opts = {}) {
3834
3646
  }
3835
3647
  if (path === "jam/queue" && req.method === "GET") {
3836
3648
  if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
3837
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
3649
+ const { jamLive } = await Promise.resolve().then(() => live_exports);
3838
3650
  return json(res, 200, jamLive.view?.() ?? {
3839
3651
  agent: null,
3840
- cards: []
3652
+ cards: [],
3653
+ unavailable: true
3841
3654
  });
3842
3655
  }
3843
3656
  if (path === "jam/card" && req.method === "POST") {
@@ -3850,23 +3663,23 @@ function apiMiddleware(root, opts = {}) {
3850
3663
  } catch {
3851
3664
  return json(res, 400, { error: "malformed JSON" });
3852
3665
  }
3853
- const { ACTIONS } = await import("./queue-CAM_vNmX.mjs");
3666
+ const { ACTIONS } = await import("./queue-DeSQm24g.mjs");
3854
3667
  if (!b || typeof b.id !== "string" || !Number.isInteger(b.rev) || !ACTIONS.includes(b.action) || b.body !== void 0 && typeof b.body !== "string") return json(res, 400, { error: "expected { id, rev, action, body? }" });
3855
3668
  if ("kind" in b) return json(res, 400, { error: "a capture has no category" });
3856
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
3669
+ const { jamLive } = await Promise.resolve().then(() => live_exports);
3857
3670
  if (!jamLive.act) return json(res, 409, { error: "jam is not running here" });
3858
3671
  const r = await jamLive.act(b.id, b.rev, b.action, b.body);
3859
3672
  return json(res, r.ok ? 200 : 409, r);
3860
3673
  }
3861
3674
  if (path === "jam/audio-ticket" && req.method === "POST") {
3862
3675
  if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
3863
- const { issueTicket, speechLive } = await import("./audio-Dw1lfMdb.mjs");
3676
+ const { issueTicket, speechLive } = await import("./audio-DX4POHAj.mjs");
3864
3677
  if (!speechLive.svc) return json(res, 409, { error: "jam is not running here" });
3865
3678
  return json(res, 200, { ticket: issueTicket() });
3866
3679
  }
3867
3680
  if (path === "jam/voice" && (req.method === "GET" || req.method === "POST")) {
3868
3681
  if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
3869
- const { speechLive } = await import("./audio-Dw1lfMdb.mjs");
3682
+ const { speechLive } = await import("./audio-DX4POHAj.mjs");
3870
3683
  const { downloadModels, downloadState, DOWNLOAD_MB } = await import("./speech-models-DomiLQcY.mjs");
3871
3684
  if (!speechLive.svc) return json(res, 409, { error: "jam is not running here" });
3872
3685
  if (req.method === "POST") {
@@ -3891,11 +3704,11 @@ function apiMiddleware(root, opts = {}) {
3891
3704
  }
3892
3705
  if (path === "jam/session" && (req.method === "GET" || req.method === "POST")) {
3893
3706
  if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
3894
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
3707
+ const { jamLive } = await Promise.resolve().then(() => live_exports);
3895
3708
  if (!jamLive.session || !jamLive.view) return json(res, 409, { error: "jam is not running here" });
3896
3709
  if (req.method === "GET") {
3897
3710
  const ses = jamLive.view().session ?? null;
3898
- const { readTalk, talkMinutes, recordFile } = await import("./session-BAaJsK5c.mjs").then((n) => n.s);
3711
+ const { readTalk, talkMinutes, recordFile } = await import("./session-VDJfXEEm.mjs").then((n) => n.s);
3899
3712
  const folder = ses ? recordFile(root, ses.since, ses.id).replace(/[^/]+$/, "") : null;
3900
3713
  return json(res, 200, {
3901
3714
  session: ses,
@@ -3926,7 +3739,7 @@ function apiMiddleware(root, opts = {}) {
3926
3739
  });
3927
3740
  }
3928
3741
  if (b.action !== "start") {
3929
- const { speechLive } = await import("./audio-Dw1lfMdb.mjs");
3742
+ const { speechLive } = await import("./audio-DX4POHAj.mjs");
3930
3743
  if (!await (speechLive.svc?.finishTalk(b.id) ?? Promise.resolve(true)).catch(() => false) && b.action === "wrapup" && b.includeTalk !== false) return json(res, 409, {
3931
3744
  ok: false,
3932
3745
  error: "what was said is still being written down - write the record again in a moment (or leave what was said out)"
@@ -3943,8 +3756,95 @@ function apiMiddleware(root, opts = {}) {
3943
3756
  action: b.action,
3944
3757
  id: b.id
3945
3758
  });
3759
+ if (r.ok && b.action === "start") {
3760
+ const { ensureConnectors } = await import("./connectors-DekQvKt9.mjs");
3761
+ const connectors = ensureConnectors(root);
3762
+ jamLive.connectors = connectors;
3763
+ return json(res, 200, {
3764
+ ...r,
3765
+ connectors
3766
+ });
3767
+ }
3946
3768
  return json(res, r.ok ? 200 : 409, r);
3947
3769
  }
3770
+ if (path === "jam/run" && req.method === "POST") {
3771
+ if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
3772
+ const raw = await readBody(req);
3773
+ if (raw == null) return json(res, 400, { error: "body too large" });
3774
+ let b;
3775
+ try {
3776
+ b = JSON.parse(raw);
3777
+ } catch {
3778
+ return json(res, 400, { error: "malformed JSON" });
3779
+ }
3780
+ if (!b || typeof b.batch !== "string" || !Number.isInteger(b.gen) || ![
3781
+ "again",
3782
+ "background",
3783
+ "drop"
3784
+ ].includes(b.action)) return json(res, 400, { error: "expected { batch, gen, action }" });
3785
+ const { jamLive } = await Promise.resolve().then(() => live_exports);
3786
+ if (!jamLive.runAct) return json(res, 409, { error: "jam is not running here" });
3787
+ const r = await jamLive.runAct(b.batch, b.gen, b.action);
3788
+ jamLive.refresh?.();
3789
+ return json(res, r.ok ? 200 : 409, r);
3790
+ }
3791
+ if (path === "jam/prefs" && (req.method === "GET" || req.method === "POST")) {
3792
+ if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
3793
+ const { readPrefs, writePrefs, validConnId } = await import("./conn-BMiHS42T.mjs").then((n) => n.a);
3794
+ const { ensureConnectors, present } = await import("./connectors-DekQvKt9.mjs");
3795
+ const { jamLive } = await Promise.resolve().then(() => live_exports);
3796
+ const tools = [
3797
+ "claude",
3798
+ "codex",
3799
+ "cursor"
3800
+ ].filter((a) => present(a));
3801
+ if (req.method === "GET") return json(res, 200, {
3802
+ prefs: readPrefs(root),
3803
+ tools,
3804
+ connectors: jamLive.connectors ?? []
3805
+ });
3806
+ const raw = await readBody(req);
3807
+ if (raw == null) return json(res, 400, { error: "body too large" });
3808
+ let b;
3809
+ try {
3810
+ b = JSON.parse(raw);
3811
+ } catch {
3812
+ return json(res, 400, { error: "malformed JSON" });
3813
+ }
3814
+ if (!b || typeof b !== "object") return json(res, 400, { error: "expected { mcp?, skills?, context?, others?, pick?, tool? }" });
3815
+ const p = readPrefs(root);
3816
+ for (const k of [
3817
+ "mcp",
3818
+ "skills",
3819
+ "others"
3820
+ ]) if (typeof b[k] === "boolean") p[k] = b[k];
3821
+ if (b.context === "fork" || b.context === "fresh") p.context = b.context;
3822
+ if (b.pick === null) delete p.pick;
3823
+ else if (validConnId(b.pick)) p.pick = b.pick;
3824
+ let force = [];
3825
+ if (b.tool && [
3826
+ "claude",
3827
+ "codex",
3828
+ "cursor"
3829
+ ].includes(b.tool.agent) && typeof b.tool.on === "boolean") {
3830
+ p.off = {
3831
+ ...p.off ?? {},
3832
+ [b.tool.agent]: !b.tool.on
3833
+ };
3834
+ if (b.tool.on) {
3835
+ delete p.off[b.tool.agent];
3836
+ force = [b.tool.agent];
3837
+ }
3838
+ }
3839
+ writePrefs(root, p);
3840
+ if (force.length) jamLive.connectors = ensureConnectors(root, { force });
3841
+ jamLive.refresh?.();
3842
+ return json(res, 200, {
3843
+ prefs: p,
3844
+ tools,
3845
+ connectors: jamLive.connectors ?? []
3846
+ });
3847
+ }
3948
3848
  if (path === "jam/capture-open" && req.method === "POST") {
3949
3849
  if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
3950
3850
  const raw = await readBody(req);
@@ -3954,7 +3854,7 @@ function apiMiddleware(root, opts = {}) {
3954
3854
  } catch {
3955
3855
  return json(res, 400, { error: "malformed JSON" });
3956
3856
  }
3957
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
3857
+ const { jamLive } = await Promise.resolve().then(() => live_exports);
3958
3858
  if (!jamLive.captureOpen) return json(res, 409, { error: "jam is not running here" });
3959
3859
  if (typeof b?.capture !== "string" || typeof b?.session !== "string") return json(res, 400, { error: "expected { capture, session, on }" });
3960
3860
  return jamLive.captureOpen(b.capture, b.session, b.on === true) === "ended" ? json(res, 409, {
@@ -3965,7 +3865,7 @@ function apiMiddleware(root, opts = {}) {
3965
3865
  }
3966
3866
  if (path === "jam/record" && req.method === "GET") {
3967
3867
  if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
3968
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
3868
+ const { jamLive } = await Promise.resolve().then(() => live_exports);
3969
3869
  const r = jamLive.record?.(url.searchParams.get("id") ?? "");
3970
3870
  return r ? json(res, 200, r) : json(res, 404, { error: "no such record" });
3971
3871
  }
@@ -3980,18 +3880,18 @@ function apiMiddleware(root, opts = {}) {
3980
3880
  return json(res, 400, { error: "malformed JSON" });
3981
3881
  }
3982
3882
  if (b?.workspace !== void 0 && b.workspace !== ws) return json(res, 409, { error: "this capture was made in another workspace" });
3983
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
3883
+ const { jamLive } = await Promise.resolve().then(() => live_exports);
3984
3884
  if (!jamLive.capture) return json(res, 409, { error: "jam is not running here" });
3985
3885
  const r = await jamLive.capture(b?.record);
3986
3886
  return json(res, r.ok ? 200 : 400, r);
3987
3887
  }
3988
3888
  if (path === "jam/capture" && req.method === "GET") {
3989
3889
  if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
3990
- const { readCapture } = await import("./capture-vadKjuCo.mjs").then((n) => n.i);
3890
+ const { readCapture } = await import("./capture-DEtM4qm5.mjs").then((n) => n.i);
3991
3891
  const id = url.searchParams.get("id") ?? "";
3992
3892
  const cap = readCapture(root, id);
3993
3893
  if (!cap) return json(res, 404, { error: "no such capture" });
3994
- const { jamLive } = await import("./live-Cgzsicwi.mjs");
3894
+ const { jamLive } = await Promise.resolve().then(() => live_exports);
3995
3895
  const card = jamLive.view?.().cards.find((c) => c.id === id);
3996
3896
  return json(res, 200, {
3997
3897
  record: cap.record,
@@ -4010,11 +3910,11 @@ function apiMiddleware(root, opts = {}) {
4010
3910
  } catch {
4011
3911
  return json(res, 400, { error: "malformed JSON" });
4012
3912
  }
4013
- const { CAPTURE_ID, readCapture, addPicture, sweepPictures } = await import("./capture-vadKjuCo.mjs").then((n) => n.i);
3913
+ const { CAPTURE_ID, readCapture, addPicture, sweepPictures } = await import("./capture-DEtM4qm5.mjs").then((n) => n.i);
4014
3914
  if (!b || typeof b.capture !== "string" || !CAPTURE_ID.test(b.capture) || typeof b.frame !== "string") return json(res, 400, { error: "expected { capture, frame, theme?, viewport? }" });
4015
3915
  if (readCapture(root, b.capture)) return json(res, 409, { error: "that capture is sealed" });
4016
3916
  const theme = typeof b.theme === "string" && /^[a-z0-9-]+$/i.test(b.theme) ? b.theme : "light";
4017
- const { shootFrame } = await import("./shot-Ch24tiMO.mjs").then((n) => n.u);
3917
+ const { shootFrame } = await import("./shot-T04Ixrvq.mjs").then((n) => n.u);
4018
3918
  const origin = opts.origin?.() ?? `http://${req.headers.host ?? "localhost"}`;
4019
3919
  const vp = typeof b.viewport === "string" ? opts.viewports?.[b.viewport] : void 0;
4020
3920
  const dim = (v) => typeof v === "number" && Number.isFinite(v) ? Math.round(v) : void 0;
@@ -4031,6 +3931,7 @@ function apiMiddleware(root, opts = {}) {
4031
3931
  frameId: b.frame,
4032
3932
  theme,
4033
3933
  origin,
3934
+ lane: "picture",
4034
3935
  ...size ? { size } : {}
4035
3936
  });
4036
3937
  if (!r.ok) return json(res, r.error.startsWith("unknown frame") ? 404 : 503, { error: r.error });
@@ -4045,10 +3946,24 @@ function apiMiddleware(root, opts = {}) {
4045
3946
  ...unchecked ? { unchecked: true } : {}
4046
3947
  });
4047
3948
  }
3949
+ if (path === "jam/picture/live" && req.method === "POST") {
3950
+ if (!ownerGated(req)) return json(res, 403, { error: "forbidden" });
3951
+ const stop = new AbortController();
3952
+ let timer;
3953
+ const late = new Promise((done) => {
3954
+ timer = setTimeout(() => {
3955
+ stop.abort();
3956
+ done([408, { error: "the picture took too long" }]);
3957
+ }, opts.livePictureMs ?? 1e4);
3958
+ });
3959
+ const [status, body] = await Promise.race([livePicture(req, url, stop.signal), late]).finally(() => clearTimeout(timer));
3960
+ if (status === 408 || status === 413) res.setHeader("connection", "close");
3961
+ return json(res, status, body);
3962
+ }
4048
3963
  if (path === "jam/picture" && req.method === "GET") {
4049
3964
  const site = String(req.headers["sec-fetch-site"] ?? "");
4050
3965
  if (!ownerGated(req) && !(cookie(req, "mv_c") && (site === "same-origin" || site === "none"))) return json(res, 403, { error: "forbidden" });
4051
- const { picturePath } = await import("./capture-vadKjuCo.mjs").then((n) => n.i);
3966
+ const { picturePath } = await import("./capture-DEtM4qm5.mjs").then((n) => n.i);
4052
3967
  const p = picturePath(root, url.searchParams.get("id") ?? "");
4053
3968
  if (!p) return json(res, 404, { error: "no such picture" });
4054
3969
  const png = readFileSync(p.path);
@@ -4099,13 +4014,13 @@ function apiMiddleware(root, opts = {}) {
4099
4014
  const fresh = appendEvents(dir, cm[1], stamped);
4100
4015
  const { record } = await import("./ledger-D54iROST.mjs").then((n) => n.n);
4101
4016
  for (const ev of fresh) if (ev.type === "create" || ev.type === "reply" || ev.type === "edit") record(root, cm[1], ev.id);
4102
- (await import("./live-Cgzsicwi.mjs")).jamLive.poke?.();
4017
+ (await Promise.resolve().then(() => live_exports)).jamLive.poke?.();
4103
4018
  backgroundPush(root);
4104
4019
  return json(res, 200, { accepted: fresh.length });
4105
4020
  }
4106
4021
  }
4107
4022
  if (path === "sync" && req.method === "POST") {
4108
- const { loadCollab, syncOnce } = await import("./sync-CQdGARJ9.mjs").then((n) => n.o);
4023
+ const { loadCollab, syncOnce } = await import("./sync-CMozOwZ0.mjs").then((n) => n.o);
4109
4024
  const collab = loadCollab(root);
4110
4025
  if (!collab) return json(res, 200, { connected: false });
4111
4026
  try {
@@ -4134,42 +4049,13 @@ function backgroundPush(root) {
4134
4049
  pushTimer = setTimeout(async () => {
4135
4050
  pushTimer = null;
4136
4051
  try {
4137
- const { loadCollab, syncOnce } = await import("./sync-CQdGARJ9.mjs").then((n) => n.o);
4052
+ const { loadCollab, syncOnce } = await import("./sync-CMozOwZ0.mjs").then((n) => n.o);
4138
4053
  const collab = loadCollab(root);
4139
4054
  if (collab) await syncOnce(root, collab);
4140
4055
  } catch {}
4141
4056
  }, 1500);
4142
4057
  }
4143
4058
  //#endregion
4144
- //#region src/server/proof.ts
4145
- /**
4146
- * The document proof (spec 28 A1.4). The Mac app puts a fresh nonce on every main-frame request to a
4147
- * local canvas (`x-mv-nonce`) and checks the answer before the document commits; only the canvas
4148
- * holding the slot file's key can sign it, so the privileges the app grants belong to that exact
4149
- * document. The proof rides the very response the app commits - the check and the load can never
4150
- * reach different listeners.
4151
- *
4152
- * Pinned exactly, so the app (A2.3 `proof.ts`) computes the same: the key is the slot file's 32 bytes
4153
- * (base64url there), HMAC-SHA256 over UTF-8 `doc|<nonce>|<port>` (port in decimal), base64url without
4154
- * padding. Requests from the app itself carry `app|<port>` the same way, and the logo the app fetches
4155
- * (`GET /__mv/logo`, spec 28 A2.4) `logo|<nonce>|<port>`: a listener that took the port after the tab was
4156
- * verified can never hand it a logo.
4157
- */
4158
- /** 16-64 base64url characters - anything else is not a nonce, and is ignored. */
4159
- const NONCE = /^[A-Za-z0-9_-]{16,64}$/;
4160
- const sign$1 = (key, msg) => createHmac("sha256", key).update(msg, "utf8").digest("base64url");
4161
- const docProof = (key, nonce, port) => sign$1(key, `doc|${nonce}|${port}`);
4162
- const logoProof = (key, nonce, port) => sign$1(key, `logo|${nonce}|${port}`);
4163
- /** The two headers for a request carrying a well-formed `x-mv-nonce`, else null: over the shell's document
4164
- * (`doc`), or over the logo (`logo`). */
4165
- function proofHeaders(p, nonce, kind = "doc") {
4166
- if (!p || typeof nonce !== "string" || !NONCE.test(nonce)) return null;
4167
- return {
4168
- "x-mv-instance": p.instance,
4169
- "x-mv-proof": (kind === "logo" ? logoProof : docProof)(p.key, nonce, p.port)
4170
- };
4171
- }
4172
- //#endregion
4173
4059
  //#region src/server/routes.ts
4174
4060
  function routesMiddleware(server, clientDir, stamps, proof) {
4175
4061
  const page = (dir) => {
@@ -4238,229 +4124,6 @@ function routesMiddleware(server, clientDir, stamps, proof) {
4238
4124
  }
4239
4125
  };
4240
4126
  }
4241
- /** The type each sniffed logo is served with. */
4242
- const LOGO_MIME = {
4243
- png: "image/png",
4244
- ico: "image/x-icon",
4245
- svg: "image/svg+xml"
4246
- };
4247
- const PNG = [
4248
- 137,
4249
- 80,
4250
- 78,
4251
- 71,
4252
- 13,
4253
- 10,
4254
- 26,
4255
- 10
4256
- ];
4257
- /** The logo type these bytes are, or null when they are none of the three. */
4258
- function sniffLogo(b) {
4259
- if (b.length >= PNG.length && PNG.every((x, i) => b[i] === x)) return "png";
4260
- if (b.length >= 4 && b[0] === 0 && b[1] === 0 && b[2] === 1 && b[3] === 0) return "ico";
4261
- return svgRoot(b) ? "svg" : null;
4262
- }
4263
- /** Is this UTF-8 text an SVG document: its root element `<svg`, with only the prolog A2.14 #24 allows before it? */
4264
- function svgRoot(b) {
4265
- let s;
4266
- try {
4267
- s = new TextDecoder("utf-8", { fatal: true }).decode(b);
4268
- } catch {
4269
- return false;
4270
- }
4271
- let i = s.charCodeAt(0) === 65279 ? 1 : 0;
4272
- const space = () => {
4273
- while (i < s.length && /\s/.test(s[i])) i++;
4274
- };
4275
- space();
4276
- if (s.startsWith("<?xml", i) && /[\s?]/.test(s[i + 5] ?? "")) {
4277
- const end = s.indexOf("?>", i);
4278
- if (end < 0) return false;
4279
- i = end + 2;
4280
- }
4281
- let doctype = false;
4282
- for (;;) {
4283
- space();
4284
- if (s.startsWith("<!--", i)) {
4285
- const end = s.indexOf("-->", i + 4);
4286
- if (end < 0) return false;
4287
- i = end + 3;
4288
- continue;
4289
- }
4290
- if (s.startsWith("<!DOCTYPE", i)) {
4291
- if (doctype) return false;
4292
- doctype = true;
4293
- const end = doctypeEnd(s, i + 9);
4294
- if (end < 0) return false;
4295
- i = end;
4296
- continue;
4297
- }
4298
- break;
4299
- }
4300
- return s.startsWith("<svg", i) && /[\s>/]/.test(s[i + 4] ?? "");
4301
- }
4302
- /** Just past the `>` that closes a `<!DOCTYPE svg ...>` whose body starts at `i`, or -1: another root name, an
4303
- * internal subset (`[` outside quotes) or no end. Quoted public and system ids may hold anything but their quote. */
4304
- function doctypeEnd(s, i) {
4305
- if (!/\s/.test(s[i] ?? "")) return -1;
4306
- while (i < s.length && /\s/.test(s[i])) i++;
4307
- if (!s.startsWith("svg", i) || !/[\s>]/.test(s[i + 3] ?? "")) return -1;
4308
- i += 3;
4309
- while (i < s.length) {
4310
- const c = s[i];
4311
- if (c === ">") return i + 1;
4312
- if (c === "[") return -1;
4313
- if (c === "\"" || c === "'") {
4314
- const close = s.indexOf(c, i + 1);
4315
- if (close < 0) return -1;
4316
- i = close + 1;
4317
- continue;
4318
- }
4319
- i++;
4320
- }
4321
- return -1;
4322
- }
4323
- //#endregion
4324
- //#region src/server/logo.ts
4325
- const LOGO_LADDER = [
4326
- "design/logo.svg",
4327
- "design/logo.png",
4328
- "public/logo.svg",
4329
- "public/logo.png",
4330
- "public/favicon.svg",
4331
- "public/favicon.png",
4332
- "public/favicon.ico"
4333
- ];
4334
- /** The first candidate that passes every check, read whole; null when none does. `warn` hears why a `share.logo`
4335
- * was ignored (the ladder's own entries are tried quietly: most repos have none of them). */
4336
- function findLogo(root, shareLogo, warn) {
4337
- let realRoot;
4338
- try {
4339
- realRoot = realpathSync(root);
4340
- } catch {
4341
- return null;
4342
- }
4343
- const own = typeof shareLogo === "string" && shareLogo !== "" ? shareLogo : null;
4344
- for (const cand of new Set(own ? [own, ...LOGO_LADDER] : LOGO_LADDER)) {
4345
- const r = readLogo(realRoot, resolve(realRoot, cand));
4346
- if (typeof r !== "string") return {
4347
- ...r,
4348
- from: cand
4349
- };
4350
- if (cand === own) warn?.(`share.logo ${own} is ignored: ${r}`);
4351
- }
4352
- return null;
4353
- }
4354
- /** One candidate: its bytes and type, or why it does not count. */
4355
- function readLogo(realRoot, file) {
4356
- let st;
4357
- try {
4358
- st = lstatSync(file);
4359
- } catch (e) {
4360
- return e.code === "ENOENT" || e.code === "ENOTDIR" ? "no such file" : "unreadable";
4361
- }
4362
- if (st.isSymbolicLink()) return "a symlink";
4363
- if (!st.isFile()) return "not a file";
4364
- if (!/\.(svg|png|ico)$/i.test(file)) return "not .svg, .png or .ico";
4365
- if (st.size > 262144) return "over 256 KB";
4366
- let real;
4367
- try {
4368
- real = realpathSync(file);
4369
- } catch {
4370
- return "unreadable";
4371
- }
4372
- if (!real.startsWith(realRoot + sep)) return "outside the repo";
4373
- let fd;
4374
- try {
4375
- fd = openSync(real, constants.O_RDONLY | constants.O_NOFOLLOW);
4376
- } catch {
4377
- return "unreadable";
4378
- }
4379
- try {
4380
- const f = fstatSync(fd);
4381
- if (!f.isFile() || f.ino !== st.ino || f.dev !== st.dev) return "changed while it was read";
4382
- const buf = Buffer.alloc(262145);
4383
- let n = 0;
4384
- for (let k = 1; k > 0 && n < buf.length; n += k) k = readSync(fd, buf, n, buf.length - n, null);
4385
- if (n > 262144) return "over 256 KB";
4386
- const bytes = Buffer.from(buf.subarray(0, n));
4387
- const type = sniffLogo(bytes);
4388
- return type ? {
4389
- type,
4390
- bytes
4391
- } : "not an image (PNG, ICO or SVG)";
4392
- } catch {
4393
- return "unreadable";
4394
- } finally {
4395
- closeSync(fd);
4396
- }
4397
- }
4398
- /** `marver build`: the logo into `<outDir>/__mv/logo.<type>` (an `.ico` as `logo.ico`), by its bytes - never a copy
4399
- * that follows a link. Its published path, or undefined when the repo has none. */
4400
- function publishLogo(root, shareLogo, outDir, warn) {
4401
- const logo = findLogo(root, shareLogo, warn);
4402
- if (!logo) return void 0;
4403
- const dir = join(outDir, ROUTE.slice(1));
4404
- mkdirSync(dir, { recursive: true });
4405
- writeFileSync(join(dir, `logo.${logo.type}`), logo.bytes);
4406
- return `${ROUTE}/logo.${logo.type}`;
4407
- }
4408
- /** A strong `ETag` for these bytes. */
4409
- const logoTag = (bytes) => `"${createHash("sha256").update(bytes).digest("base64url").slice(0, 22)}"`;
4410
- /** Does an `If-None-Match` name this tag (a list, a weak tag, or `*`)? */
4411
- function matches(header, tag) {
4412
- if (typeof header !== "string") return false;
4413
- return header.split(",").map((t) => t.trim().replace(/^W\//, "")).some((t) => t === "*" || t === tag);
4414
- }
4415
- /**
4416
- * `marver dev`'s `GET|HEAD /__mv/logo`. Read once per request (256 KB at most), checked, and answered with its sniffed
4417
- * type, an `ETag` and `Cache-Control: no-cache`; `x-content-type-options: nosniff` and a CSP that runs nothing, so an
4418
- * SVG opened as a page is a picture. A request carrying a well-formed `x-mv-nonce` gets the logo proof
4419
- * (`x-mv-instance`, `x-mv-proof` over `logo|<nonce>|<port>`), on a 200 and a 304 alike. 404 when the repo has none.
4420
- */
4421
- function logoRoute(root, shareLogo, proof) {
4422
- const warned = /* @__PURE__ */ new Set();
4423
- const warn = (m) => {
4424
- if (warned.has(m)) return;
4425
- warned.add(m);
4426
- console.warn(` marver: ${m}`);
4427
- };
4428
- return (req, res, next) => {
4429
- let path;
4430
- try {
4431
- path = new URL(req.url ?? "/", "http://x").pathname;
4432
- } catch {
4433
- return next();
4434
- }
4435
- if (path !== `/__mv/logo`) return next();
4436
- if (req.method !== "GET" && req.method !== "HEAD") {
4437
- res.statusCode = 405;
4438
- res.setHeader("allow", "GET, HEAD");
4439
- return res.end();
4440
- }
4441
- const logo = findLogo(root, shareLogo(), warn);
4442
- if (!logo) {
4443
- res.statusCode = 404;
4444
- res.setHeader("cache-control", "no-store");
4445
- return res.end();
4446
- }
4447
- const tag = logoTag(logo.bytes);
4448
- res.setHeader("content-type", LOGO_MIME[logo.type]);
4449
- res.setHeader("etag", tag);
4450
- res.setHeader("cache-control", "no-cache");
4451
- res.setHeader("vary", "x-mv-nonce");
4452
- res.setHeader("x-content-type-options", "nosniff");
4453
- res.setHeader("content-security-policy", "default-src 'none'; style-src 'unsafe-inline'");
4454
- const signed = proofHeaders(proof, req.headers["x-mv-nonce"], "logo");
4455
- if (signed) for (const [k, v] of Object.entries(signed)) res.setHeader(k, v);
4456
- if (matches(req.headers["if-none-match"], tag)) {
4457
- res.statusCode = 304;
4458
- return res.end();
4459
- }
4460
- res.setHeader("content-length", String(logo.bytes.length));
4461
- res.end(req.method === "HEAD" ? void 0 : logo.bytes);
4462
- };
4463
- }
4464
4127
  //#endregion
4465
4128
  //#region src/server/guard.ts
4466
4129
  /** A workspace key as marver writes it: 16 hex. A frame's own `ws` query in another shape is the
@@ -4545,6 +4208,337 @@ function elsewhere(res) {
4545
4208
  res.end(JSON.stringify({ error: "another workspace" }));
4546
4209
  }
4547
4210
  //#endregion
4211
+ //#region src/server/app-live.ts
4212
+ /**
4213
+ * The live stream (spec 28 A4.1, A4.6 #4-#15): what waits on the owner in this canvas, for the Mac app's marks and
4214
+ * notices. `GET /__mv/app/live` is an event stream of whole snapshots (`LiveEvent` v1, src/shared/app-api.ts), proved
4215
+ * both ways - the request by `x-mv-app`, the answer by `liveProof` over the app's fresh nonce - so only the slot key's
4216
+ * holder is answered, and a listener that took the port after a canvas stopped can never put words into a notice.
4217
+ *
4218
+ * Four parts, each pure or nearly: the selector `liveSnapshot(input)` (#7-#11), the id hash (#9), the encoder with its
4219
+ * byte budget (#11, r1 #4), and the hub `createLiveHub` with its clients (#14), behind the route `liveRoute` (#5, #6).
4220
+ * The adapters that read the real sources - the comment logs, the marks, the Jam view, `marver work`'s leases - stay in
4221
+ * plugin.ts as the hub's `read()`. Erasable TypeScript, no Vite, only `node:crypto`, `./proof.ts` and the shared
4222
+ * contracts: the Mac app's fake canvas runs it under Node's type stripping over a scripted `read()`, so the app's cases
4223
+ * meet this code, not a copy (#4).
4224
+ */
4225
+ /** An item's id (#9): its kind and the first 20 hex of a sha256 over the occurrence's persisted parts, NUL-joined. */
4226
+ const liveId = (kind, ...parts) => `${kind}:${createHash("sha256").update(parts.map(String).join("\0")).digest("hex").slice(0, 20)}`;
4227
+ /** One line of at most `max` UTF-16 units: whitespace collapsed, control characters gone, never cut inside a pair. A
4228
+ * log is data: a body that is not a string (a hand edit, a dev POST) reads as none, never stopping the stream. */
4229
+ function oneLine(s, max = LIVE_BOUNDS.title) {
4230
+ const t = (typeof s === "string" ? s : "").replace(/\s+/g, " ").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
4231
+ if (t.length <= max) return t;
4232
+ const cut = t.slice(0, max);
4233
+ return /[\ud800-\udbff]$/.test(cut) ? cut.slice(0, -1) : cut;
4234
+ }
4235
+ /** Every ref an item carries is at most `LIVE_BOUNDS.ref`: one past it can never be shown, so it is counted, never sent. */
4236
+ const refsFit = (i) => [
4237
+ i.board,
4238
+ i.frame,
4239
+ i.thread,
4240
+ i.msg,
4241
+ i.batch,
4242
+ ...i.cards ?? []
4243
+ ].every((r) => r === void 0 || r.length <= LIVE_BOUNDS.ref);
4244
+ const byMade = (a, b) => a.made - b.made || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
4245
+ const firstFrame = (c) => c.frames[0];
4246
+ /**
4247
+ * What waits on the owner now (#7, #8, #10, #12): one item per need, newest first, at most `LIVE_BOUNDS.items`, with
4248
+ * exact counts. Pure and deterministic - the same input gives the same bytes. `ask` from the threads alone (a Jam card
4249
+ * in `asks` is the same question, carried as its target); `review`, `failed` and `stalled` from Jam's view, each
4250
+ * failed or stalled run one item; unseen frames a count; `working` from `marver work`'s leases and the runs at work.
4251
+ */
4252
+ function liveSnapshot(input) {
4253
+ const view = input.jam;
4254
+ const cards = view?.cards ?? [];
4255
+ const threadOf = /* @__PURE__ */ new Map();
4256
+ for (const { board, threads } of input.boards) for (const t of threads) threadOf.set(`${board}\0${t.id}`, t);
4257
+ const items = [];
4258
+ for (const { board, threads } of input.boards) for (const t of threads) {
4259
+ if (t.resolved || !(t.agent || t.replies.some((r) => r.agent))) continue;
4260
+ const last = t.replies.length ? t.replies[t.replies.length - 1] : t;
4261
+ if (!last.agent || !asks(last, last === t)) continue;
4262
+ const msg = last === t ? t.id : last.id;
4263
+ const card = cards.filter((c) => c.state === "asks" && c.board === board && c.thread === t.id).sort(byMade).map((c) => c.id);
4264
+ items.push({
4265
+ id: liveId("ask", board, t.id, msg),
4266
+ kind: "ask",
4267
+ board,
4268
+ title: oneLine(last.body),
4269
+ at: last.ts,
4270
+ ...t.frame ? { frame: t.frame } : {},
4271
+ thread: t.id,
4272
+ msg,
4273
+ ...card.length ? { cards: card.slice(0, LIVE_BOUNDS.cards) } : {}
4274
+ });
4275
+ }
4276
+ const titleOf = (c) => oneLine(c.kind === "comment" ? (c.thread ? threadOf.get(`${c.board}\0${c.thread}`)?.body : void 0) ?? c.title : c.title);
4277
+ const thread = (c) => c.kind === "comment" && c.thread ? { thread: c.thread } : {};
4278
+ for (const c of cards.filter((x) => x.state === "review").sort(byMade)) {
4279
+ const occ = c.att ?? 0;
4280
+ items.push({
4281
+ id: liveId("review", c.id, occ),
4282
+ kind: "review",
4283
+ board: c.board,
4284
+ title: titleOf(c),
4285
+ at: c.at,
4286
+ ...firstFrame(c) ? { frame: firstFrame(c) } : {},
4287
+ ...thread(c),
4288
+ cards: [c.id],
4289
+ ...c.batch ? { batch: c.batch } : {},
4290
+ occ
4291
+ });
4292
+ }
4293
+ const failed = /* @__PURE__ */ new Map();
4294
+ for (const c of cards.filter((x) => x.state === "failed").sort(byMade)) {
4295
+ const k = c.batch ? `b\0${c.batch}` : `c\0${c.id}`;
4296
+ failed.set(k, [...failed.get(k) ?? [], c]);
4297
+ }
4298
+ for (const [k, group] of failed) {
4299
+ const c = group[0];
4300
+ const run = k.startsWith("b\0");
4301
+ const occ = run ? c.fails ?? 0 : c.att ?? 0;
4302
+ items.push({
4303
+ id: run ? liveId("failed", c.batch, occ) : liveId("failed", c.id, occ),
4304
+ kind: "failed",
4305
+ board: c.board,
4306
+ title: titleOf(c),
4307
+ ...c.note ? { note: oneLine(c.note, LIVE_BOUNDS.note) } : {},
4308
+ at: Math.max(...group.map((x) => x.at)),
4309
+ ...firstFrame(c) ? { frame: firstFrame(c) } : {},
4310
+ ...thread(c),
4311
+ cards: group.map((x) => x.id).slice(0, LIVE_BOUNDS.cards),
4312
+ ...run ? { batch: c.batch } : {},
4313
+ occ
4314
+ });
4315
+ }
4316
+ const stalled = /* @__PURE__ */ new Map();
4317
+ for (const c of cards.filter((x) => x.state === "working" && x.runner?.kind === "session" && x.runner.state === "stalled").sort(byMade)) {
4318
+ const k = c.runner.batch;
4319
+ stalled.set(k, [...stalled.get(k) ?? [], c]);
4320
+ }
4321
+ for (const [batch, group] of stalled) {
4322
+ const c = group[0];
4323
+ const gen = c.runner.gen ?? 0, occ = c.runner.stalls ?? 0;
4324
+ items.push({
4325
+ id: liveId("stalled", batch, gen, occ),
4326
+ kind: "stalled",
4327
+ board: c.board,
4328
+ title: titleOf(c),
4329
+ at: Math.max(...group.map((x) => x.at)),
4330
+ ...firstFrame(c) ? { frame: firstFrame(c) } : {},
4331
+ ...thread(c),
4332
+ cards: group.map((x) => x.id).slice(0, LIVE_BOUNDS.cards),
4333
+ batch,
4334
+ gen,
4335
+ occ
4336
+ });
4337
+ }
4338
+ const counts = {
4339
+ ask: 0,
4340
+ review: 0,
4341
+ failed: 0,
4342
+ stalled: 0
4343
+ };
4344
+ for (const i of items) counts[i.kind]++;
4345
+ const shown = items.filter(refsFit).sort((a, b) => b.at - a.at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
4346
+ const working = input.cli.length > 0 || cards.some((c) => c.state === "working" && (!c.runner || !c.runner.state || c.runner.state === "claimed"));
4347
+ return {
4348
+ jam: view ? "on" : "off",
4349
+ items: shown.slice(0, LIVE_BOUNDS.items),
4350
+ cut: Math.max(0, shown.length - LIVE_BOUNDS.items),
4351
+ counts,
4352
+ unseen: input.fresh.length,
4353
+ working,
4354
+ session: !!view?.session
4355
+ };
4356
+ }
4357
+ const block = (e) => `event: ${LIVE_WIRE.event}\ndata: ${JSON.stringify(e)}\n\n`;
4358
+ /**
4359
+ * The event as written (#11, r1 #4): `event: live`, one `data:` line, a blank line - within `LIVE_BOUNDS.eventBytes`
4360
+ * in UTF-8. While it is over, the oldest whole items go (the end of `items`), counted in `cut`; `counts` stay exact.
4361
+ */
4362
+ function encodeLive(e) {
4363
+ let text = block(e);
4364
+ if (Buffer.byteLength(text) <= LIVE_BOUNDS.eventBytes) return text;
4365
+ const sizes = e.items.map((i) => Buffer.byteLength(JSON.stringify(i)) + 1);
4366
+ let over = Buffer.byteLength(text) - LIVE_BOUNDS.eventBytes;
4367
+ let keep = e.items.length;
4368
+ while (keep > 0 && over > 0) over -= sizes[--keep];
4369
+ for (;;) {
4370
+ text = block({
4371
+ ...e,
4372
+ items: e.items.slice(0, keep),
4373
+ cut: e.cut + e.items.length - keep
4374
+ });
4375
+ if (keep === 0 || Buffer.byteLength(text) <= LIVE_BOUNDS.eventBytes) return text;
4376
+ keep--;
4377
+ }
4378
+ }
4379
+ /** `seq`: per server process, rising across Vite restarts - one counter for every hub this module makes (#11, #14). */
4380
+ const SEQ = { n: 0 };
4381
+ const hubs = /* @__PURE__ */ new Set();
4382
+ /** A source the stream reads changed - beside each place the server already tells pages (#13). Pokes every open hub. */
4383
+ function liveChanged() {
4384
+ for (const h of hubs) h.changed();
4385
+ }
4386
+ const LIVE_DEBOUNCE_MAX_MS = 1e3;
4387
+ /**
4388
+ * One hub per server (#14). It computes only while a client is connected, and writes only a snapshot that differs
4389
+ * from the last one written, `seq` one higher. A new client gets the snapshot at once - alone, when nothing changed.
4390
+ * A heartbeat `: hb` every 30 s recomputes too, so a missed hook costs 30 s at most. A fifth client ends the oldest; a
4391
+ * client with more than 64 KiB unsent is destroyed before the next write (it reconnects for a fresh snapshot). `on`
4392
+ * subscribes the hub to a source that tells it of changes itself (workActivity), unsubscribed at close.
4393
+ */
4394
+ function createLiveHub(o) {
4395
+ const now = o.clock ?? Date.now;
4396
+ const seq = o.seq ?? SEQ;
4397
+ const clients = [];
4398
+ let last = null;
4399
+ let text = "";
4400
+ let timer;
4401
+ let first = 0;
4402
+ let beat;
4403
+ let closed = false;
4404
+ /** no client left: no timer runs */
4405
+ const idle = () => {
4406
+ if (!clients.length) {
4407
+ clearInterval(beat);
4408
+ beat = void 0;
4409
+ clearTimeout(timer);
4410
+ timer = void 0;
4411
+ }
4412
+ };
4413
+ const remove = (res) => {
4414
+ const i = clients.indexOf(res);
4415
+ if (i >= 0) clients.splice(i, 1);
4416
+ idle();
4417
+ };
4418
+ const write = (res, chunk) => {
4419
+ if (res.writableLength > LIVE_WIRE.slowBytes) {
4420
+ remove(res);
4421
+ res.destroy();
4422
+ return;
4423
+ }
4424
+ res.write(chunk);
4425
+ };
4426
+ /** Read the sources; a changed snapshot goes to every client. False when the read failed (nothing written). */
4427
+ const recompute = () => {
4428
+ let body;
4429
+ try {
4430
+ body = o.read();
4431
+ } catch {
4432
+ return false;
4433
+ }
4434
+ const key = JSON.stringify(body);
4435
+ if (key === last) return true;
4436
+ last = key;
4437
+ text = encodeLive({
4438
+ v: 1,
4439
+ instance: o.instance,
4440
+ seq: ++seq.n,
4441
+ ...body
4442
+ });
4443
+ for (const c of [...clients]) write(c, text);
4444
+ return true;
4445
+ };
4446
+ const fire = () => {
4447
+ timer = void 0;
4448
+ if (clients.length && !closed) recompute();
4449
+ };
4450
+ const hub = {
4451
+ changed() {
4452
+ if (closed || !clients.length) return;
4453
+ const t = now();
4454
+ if (timer === void 0) first = t;
4455
+ clearTimeout(timer);
4456
+ timer = setTimeout(fire, Math.max(0, Math.min(150, first + LIVE_DEBOUNCE_MAX_MS - t)));
4457
+ },
4458
+ push() {
4459
+ clearTimeout(timer);
4460
+ timer = void 0;
4461
+ if (!closed) recompute();
4462
+ },
4463
+ add(res) {
4464
+ if (closed) {
4465
+ res.end();
4466
+ return;
4467
+ }
4468
+ while (clients.length >= LIVE_WIRE.clients) clients.shift().end();
4469
+ clients.push(res);
4470
+ res.on("close", () => remove(res));
4471
+ res.on("error", () => remove(res));
4472
+ const was = last;
4473
+ if (recompute() && last === was && text) write(res, text);
4474
+ beat ??= setInterval(() => {
4475
+ recompute();
4476
+ for (const c of [...clients]) write(c, `${LIVE_WIRE.heartbeat}\n\n`);
4477
+ }, LIVE_WIRE.heartbeatMs);
4478
+ beat.unref?.();
4479
+ },
4480
+ clients: () => clients.length,
4481
+ drop() {
4482
+ for (const c of clients.splice(0)) c.destroy();
4483
+ idle();
4484
+ },
4485
+ close() {
4486
+ if (closed) return;
4487
+ closed = true;
4488
+ hubs.delete(hub);
4489
+ off?.();
4490
+ for (const c of clients.splice(0)) try {
4491
+ c.end();
4492
+ } catch {}
4493
+ clearInterval(beat);
4494
+ beat = void 0;
4495
+ clearTimeout(timer);
4496
+ timer = void 0;
4497
+ }
4498
+ };
4499
+ const off = o.on?.(() => hub.changed());
4500
+ hubs.add(hub);
4501
+ return hub;
4502
+ }
4503
+ const refuse = (res, status, extra = {}) => {
4504
+ res.writeHead(status, {
4505
+ "content-type": "text/plain; charset=utf-8",
4506
+ "cache-control": "no-store",
4507
+ ...extra
4508
+ });
4509
+ res.end(String(status));
4510
+ };
4511
+ /**
4512
+ * `GET /__mv/app/live` (#5, #6): mounted right after the workspace guard (an `x-mv-ws` naming another workspace is a
4513
+ * 409 before anything is read) and the perf barrier. Another method 405; an `x-mv-app` that is not `appProof(key,
4514
+ * port)` 403, and a missing or malformed `x-mv-nonce` 400 - before anything is read or computed. The 200 carries
4515
+ * `x-mv-instance` and `x-mv-proof` = `liveProof`. No hub or no proof (no slot: an in-process plugin, a test server):
4516
+ * 404. Proved, the stream admits nothing else: it never makes a document trusted.
4517
+ */
4518
+ function liveRoute(hub, proof) {
4519
+ return (req, res, next) => {
4520
+ if ((req.url ?? "").split("?")[0] !== LIVE_WIRE.path) return next();
4521
+ if (!hub || !proof) return refuse(res, 404);
4522
+ if (req.method !== "GET") return refuse(res, 405, { allow: "GET" });
4523
+ if (!appProofOk(proof, req.headers["x-mv-app"])) return refuse(res, 403);
4524
+ const signed = proofHeaders(proof, req.headers["x-mv-nonce"], "live");
4525
+ if (!signed) return refuse(res, 400);
4526
+ res.writeHead(200, {
4527
+ "content-type": `${LIVE_WIRE.type}; charset=utf-8`,
4528
+ "cache-control": "no-store",
4529
+ "x-content-type-options": "nosniff",
4530
+ ...signed
4531
+ });
4532
+ res.socket?.setNoDelay(true);
4533
+ res.flushHeaders?.();
4534
+ hub.add(res);
4535
+ };
4536
+ }
4537
+ //#endregion
4538
+ //#region src/server/jam/live.ts
4539
+ var live_exports = /* @__PURE__ */ __exportAll({ jamLive: () => jamLive });
4540
+ const jamLive = {};
4541
+ //#endregion
4548
4542
  //#region src/server/plugin.ts
4549
4543
  const VIRTUAL_THEME = "virtual:sh-theme";
4550
4544
  const VIRTUAL_CONFIG = "virtual:sh-config";
@@ -4586,6 +4580,7 @@ function marverPlugin(ctx) {
4586
4580
  return s ? loadedFiles(urls, s.config.root, s.environments?.client?.moduleGraph ?? null, s.config.base) : [];
4587
4581
  }
4588
4582
  };
4583
+ const live = liveSources(root);
4589
4584
  const bootId = String(process.hrtime.bigint());
4590
4585
  let invRev = 0;
4591
4586
  const pendingInv = /* @__PURE__ */ new Set();
@@ -4660,7 +4655,10 @@ function marverPlugin(ctx) {
4660
4655
  };
4661
4656
  const observeMarks = () => observed(observe(root, manifest.frames));
4662
4657
  const observeLater = () => whenSettled(() => {
4663
- if (observeMarks()) devServer?.ws.send("sh:marks", {});
4658
+ if (observeMarks()) {
4659
+ devServer?.ws.send("sh:marks", {});
4660
+ liveChanged();
4661
+ }
4664
4662
  });
4665
4663
  const hooks = {
4666
4664
  onFrames: (t, cause) => {
@@ -4684,7 +4682,10 @@ function marverPlugin(ctx) {
4684
4682
  const reload = [.../* @__PURE__ */ new Set([...seen.doc, ...t.doc])];
4685
4683
  for (const id of reload) pendingInv.add(id);
4686
4684
  flushInv();
4687
- if (reload.length || touched.length || seen.note.length) devServer?.ws.send("sh:marks", {});
4685
+ if (reload.length || touched.length || seen.note.length) {
4686
+ devServer?.ws.send("sh:marks", {});
4687
+ liveChanged();
4688
+ }
4688
4689
  logReload(root, {
4689
4690
  kind: "update",
4690
4691
  cause,
@@ -4811,6 +4812,13 @@ function marverPlugin(ctx) {
4811
4812
  }
4812
4813
  server.middlewares.use(guardMiddleware(ws));
4813
4814
  server.middlewares.use(perfRunBarrier());
4815
+ const hub = ctx.proof ? createLiveHub({
4816
+ instance: ctx.proof.instance,
4817
+ read: () => liveSnapshot(live.read(manifest.frames)),
4818
+ on: (fn) => workActivity.onChange(fn)
4819
+ }) : null;
4820
+ if (hub) onClose(() => hub.close());
4821
+ server.middlewares.use(liveRoute(hub, ctx.proof));
4814
4822
  const viteWatcher = server.watcher;
4815
4823
  watching.server = server;
4816
4824
  watching.watcher = viteWatcher;
@@ -4852,7 +4860,10 @@ function marverPlugin(ctx) {
4852
4860
  viewports: config.viewports,
4853
4861
  origin: listeningOrigin,
4854
4862
  bakeGen: () => bakeGen,
4855
- notify: (event) => server.ws.send(event, {}),
4863
+ notify: (event) => {
4864
+ server.ws.send(event, {});
4865
+ liveChanged();
4866
+ },
4856
4867
  manifest: () => manifest,
4857
4868
  settled,
4858
4869
  workspace: ws,
@@ -4885,8 +4896,10 @@ function marverPlugin(ctx) {
4885
4896
  const changed = writeManifest(root, manifest);
4886
4897
  observeLater();
4887
4898
  const key = JSON.stringify(manifest.frames), sKey = JSON.stringify(manifest.scenes);
4888
- if (changed && key !== framesKey) server.ws.send("sh:manifest", manifest);
4889
- else if (changed && sKey !== scenesKey) server.ws.send("sh:scenes", { scenes: manifest.scenes });
4899
+ if (changed && key !== framesKey) {
4900
+ server.ws.send("sh:manifest", manifest);
4901
+ liveChanged();
4902
+ } else if (changed && sKey !== scenesKey) server.ws.send("sh:scenes", { scenes: manifest.scenes });
4890
4903
  framesKey = key;
4891
4904
  scenesKey = sKey;
4892
4905
  }, 150);
@@ -5118,7 +5131,7 @@ function marverPlugin(ctx) {
5118
5131
  });
5119
5132
  return;
5120
5133
  }
5121
- const { shootFrame, shootBatch, resolveFrames } = await import("./shot-Ch24tiMO.mjs").then((n) => n.u);
5134
+ const { shootFrame, shootBatch, resolveFrames } = await import("./shot-T04Ixrvq.mjs").then((n) => n.u);
5122
5135
  if (ways[0] === "frame") {
5123
5136
  if (typeof spec.frame !== "string") {
5124
5137
  write({
@@ -5188,6 +5201,53 @@ function marverPlugin(ctx) {
5188
5201
  }
5189
5202
  }, updatesPlugin(root, () => manifest, () => devServer && hooks, landed)];
5190
5203
  }
5204
+ /**
5205
+ * The live stream's four adapters (spec 28 A4.6 #7), the hub's `read()`: every board's comment log replayed - cached by
5206
+ * its `size:mtimeMs`, so a recompute re-reads only a log that changed (the logs only grow); the frames new now, from the
5207
+ * running server's marks (`freshFrames`); Jam's view (`jamLive.view()`, absent when Jam is off or its lock is held
5208
+ * elsewhere); and `marver work`'s own leases - never `active()`, which holds the Jam daemon's too (A4.6 r2 #3).
5209
+ */
5210
+ function liveSources(root) {
5211
+ const dir = join(root, "design", "comments");
5212
+ const cache = /* @__PURE__ */ new Map();
5213
+ let reads = 0;
5214
+ return {
5215
+ read(frames) {
5216
+ const names = listBoards(dir);
5217
+ for (const b of cache.keys()) if (!names.includes(b)) cache.delete(b);
5218
+ const boards = [];
5219
+ for (const board of names) {
5220
+ let key;
5221
+ try {
5222
+ const st = statSync(join(dir, `${board}.jsonl`));
5223
+ key = `${st.size}:${st.mtimeMs}`;
5224
+ } catch {
5225
+ continue;
5226
+ }
5227
+ let c = cache.get(board);
5228
+ if (c?.key !== key) {
5229
+ reads++;
5230
+ c = {
5231
+ key,
5232
+ threads: replay(readLog(dir, board))
5233
+ };
5234
+ cache.set(board, c);
5235
+ }
5236
+ boards.push({
5237
+ board,
5238
+ threads: c.threads
5239
+ });
5240
+ }
5241
+ return {
5242
+ boards,
5243
+ fresh: freshFrames(root, frames),
5244
+ jam: jamLive.view?.(),
5245
+ cli: workActivity.leases("cli").map(([f]) => f)
5246
+ };
5247
+ },
5248
+ reads: () => reads
5249
+ };
5250
+ }
5191
5251
  /** The marks look at the frames on disk; true when they recorded something. */
5192
5252
  function observed(r) {
5193
5253
  return r.doc.length + r.note.length > 0;
@@ -5239,4 +5299,4 @@ async function tailwind3Css(root) {
5239
5299
  return null;
5240
5300
  }
5241
5301
  //#endregion
5242
- export { installedVersion as a, autoWidthOf as c, readSizes as d, loadConfig as f, publishLogo as i, keptSizes as l, tailwind3Css as n, ASK_MAX as o, tailwind4Plugin as r, bakeBatch as s, marverPlugin as t, measuringFrames as u };
5302
+ export { live_exports as a, ASK_MAX as c, jamLive as i, bakeBatch as l, tailwind3Css as n, liveChanged as o, tailwind4Plugin as r, installedVersion as s, marverPlugin as t };