@marver-design/marver 0.25.0 → 0.26.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 (92) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +3 -1
  3. package/dist/{anchor-DVV732zR.mjs → anchor-5H1vnoLu.mjs} +6 -1
  4. package/dist/{anchor-check-BE5VVN6Q.mjs → anchor-check-Dg5xpNnU.mjs} +1 -1
  5. package/dist/audio-CmSRYFEs.mjs +429 -0
  6. package/dist/{auth-DdUKeVKt.mjs → auth-Dix8wrXV.mjs} +1 -1
  7. package/dist/{bake-D8byeRzB.mjs → bake-DtVlm0_F.mjs} +45 -6
  8. package/dist/{boards-Csxj2WJn.mjs → boards-DYG22tOe.mjs} +2 -2
  9. package/dist/{build-BHoWLvSj.mjs → build-C_gUgcdC.mjs} +16 -9
  10. package/dist/capture-CrqvU_jh.mjs +729 -0
  11. package/dist/cli.mjs +23 -17
  12. package/dist/{collab-gqNdScUE.mjs → collab-Dxg2trOK.mjs} +4 -3
  13. package/dist/{comments-Zoch254k.mjs → comments-0BSbb04K.mjs} +14 -3
  14. package/dist/{comments-pTLlhjh4.mjs → comments-BqXua-XL.mjs} +7 -7
  15. package/dist/{config-cKgZBRj0.mjs → config-Cf7EjAMf.mjs} +12 -1
  16. package/dist/{context-D2ugHqwO.mjs → context-HQ4Giw58.mjs} +1 -1
  17. package/dist/daemon-DZo6o3rU.mjs +2445 -0
  18. package/dist/{dev-DJdgow47.mjs → dev-_Nlsc6v9.mjs} +189 -18
  19. package/dist/dev-lock-DWSpa6nj.mjs +179 -0
  20. package/dist/{events-DnK_AnrW.mjs → events-CLH4ijKP.mjs} +14 -4
  21. package/dist/{init-DO4DhUt_.mjs → init-D8DtrK_F.mjs} +2 -2
  22. package/dist/{ledger-BNXW14Xw.mjs → ledger-D54iROST.mjs} +17 -1
  23. package/dist/{link-C-qUIuKU.mjs → link-BNzLvdhI.mjs} +2 -2
  24. package/dist/live-Cgzsicwi.mjs +4 -0
  25. package/dist/{manifest-DnAte_fB.mjs → manifest-Nl3KSVOk.mjs} +1 -1
  26. package/dist/{marks-koRsbHfe.mjs → marks-CKgzucHZ.mjs} +2 -2
  27. package/dist/{marks-DFuintmJ.mjs → marks-NQi0wZJ4.mjs} +23 -5
  28. package/dist/{marver-id-gate-DGANtVyC.mjs → marver-id-gate-BjF6v4bT.mjs} +4 -4
  29. package/dist/{perf-QJIWtTw1.mjs → perf-D6VmmJ2q.mjs} +1 -1
  30. package/dist/{perf-CCisg-ny.mjs → perf-DPbLGhhO.mjs} +1 -1
  31. package/dist/{plugin-CTyhjwoJ.mjs → plugin-CTD0rydA.mjs} +279 -38
  32. package/dist/{poster-D0cbV7hi.mjs → poster-ChjXGTS5.mjs} +1 -1
  33. package/dist/{profile-Do0nGkXO.mjs → profile-WU9qcbIo.mjs} +1 -1
  34. package/dist/{publish-bakes--l8ot2eQ.mjs → publish-bakes-CEP_2NRc.mjs} +3 -3
  35. package/dist/queue-BuiCKSX1.mjs +1319 -0
  36. package/dist/reserve-BURNQ2Y3.mjs +53 -0
  37. package/dist/{rolldown-runtime-D7D4PA-g.mjs → rolldown-runtime-8H4AJuhK.mjs} +1 -0
  38. package/dist/{serve-wv2QWdxB.mjs → serve-C8rVheYk.mjs} +12 -12
  39. package/dist/session-qZWKt_VA.mjs +191 -0
  40. package/dist/{share-ScamJcks.mjs → share--oFJ1bCI.mjs} +2 -2
  41. package/dist/{shot-jdO_B6Qw.mjs → shot-CNbHoZ6H.mjs} +1 -1
  42. package/dist/{shot-CckrGW-J.mjs → shot-DqcxJibP.mjs} +4 -3
  43. package/dist/speech-models-DomiLQcY.mjs +299 -0
  44. package/dist/speech-worker.mjs +319 -0
  45. package/dist/{summary-CrW88e3q.mjs → summary-Y8MY1Wuc.mjs} +2 -2
  46. package/dist/{sync-C3035OnJ.mjs → sync-DKk-yT1V.mjs} +9 -8
  47. package/dist/{work-GE88wb_3.mjs → work-F5u-twpJ.mjs} +28 -5
  48. package/dist/{work-CpJn1gwY.mjs → work-VvX_JIgl.mjs} +2 -2
  49. package/docs/jam-session.md +177 -0
  50. package/docs/live-jam.md +21 -3
  51. package/package.json +7 -1
  52. package/src/client/frame-host/bridge.js +20 -2
  53. package/src/client/frame-host/inspect.d.ts +4 -0
  54. package/src/client/frame-host/inspect.js +88 -3
  55. package/src/client/frame-host/keys.d.ts +6 -0
  56. package/src/client/frame-host/keys.js +55 -0
  57. package/src/client/frame-host/trail.d.ts +7 -0
  58. package/src/client/frame-host/trail.js +204 -0
  59. package/src/client/shell/App.tsx +45 -5
  60. package/src/client/shell/Comments.tsx +20 -6
  61. package/src/client/shell/JamSurface.tsx +340 -0
  62. package/src/client/shell/Play.tsx +22 -3
  63. package/src/client/shell/Tip.tsx +8 -3
  64. package/src/client/shell/canvas/Canvas.tsx +12 -2
  65. package/src/client/shell/canvas/FrameNode.tsx +11 -2
  66. package/src/client/shell/canvas/sleep.ts +19 -1
  67. package/src/client/shell/comments-store.ts +23 -16
  68. package/src/client/shell/icons.tsx +15 -0
  69. package/src/client/shell/jam-capture.ts +939 -0
  70. package/src/client/shell/jam-keys.ts +329 -0
  71. package/src/client/shell/jam-lane.tsx +208 -0
  72. package/src/client/shell/jam-lines.ts +115 -0
  73. package/src/client/shell/jam-panel.tsx +506 -0
  74. package/src/client/shell/jam-queue.ts +126 -0
  75. package/src/client/shell/jam-session.tsx +389 -0
  76. package/src/client/shell/jam-state.ts +61 -0
  77. package/src/client/shell/jam-surface-parts.tsx +102 -0
  78. package/src/client/shell/jam-ui.tsx +104 -0
  79. package/src/client/shell/jam-voice.ts +479 -0
  80. package/src/client/shell/sound.ts +22 -0
  81. package/src/client/shell/stage-size.ts +11 -0
  82. package/src/client/shell/store.ts +34 -13
  83. package/src/client/shell/styles.css +544 -2
  84. package/src/client/stage/main.tsx +16 -2
  85. package/src/shared/capture-frames.ts +41 -0
  86. package/src/shared/events.ts +19 -4
  87. package/src/shared/speech.ts +16 -0
  88. package/templates/AGENTS-embedded.md +10 -2
  89. package/templates/AGENTS-studio.md +10 -2
  90. package/templates/instructions/iterate.md +8 -6
  91. package/templates/instructions/jam.md +129 -59
  92. package/dist/daemon-Cl8KXGW4.mjs +0 -1523
@@ -0,0 +1,2445 @@
1
+ import { l as toFrameId } from "./manifest-Nl3KSVOk.mjs";
2
+ import { a as workActivity } from "./work-F5u-twpJ.mjs";
3
+ import { r as replay } from "./events-CLH4ijKP.mjs";
4
+ import { a as readLog, t as appendEvents } from "./comments-0BSbb04K.mjs";
5
+ import { n as localProfile } from "./profile-WU9qcbIo.mjs";
6
+ import { r as uncheckedAnchor } from "./anchor-5H1vnoLu.mjs";
7
+ import { i as record, t as has } from "./ledger-D54iROST.mjs";
8
+ import { _ as packetPath, a as checkRecord, c as firstPoint, d as picturePath, f as readCapture, g as goalText, h as buildPacket, n as captureFrames, o as continues, p as storeCapture, r as captureWords, t as CAPTURE_ID, v as parseAgentText, x as sharedFile, y as parseMembers } from "./capture-CrqvU_jh.mjs";
9
+ import { a as recordFile, c as storeWrapup, i as readWrapup, n as buildWrapup, o as recordPathProblem, r as moreOf, t as SESSION_ID } from "./session-qZWKt_VA.mjs";
10
+ import { act, addCapture, addWrapup, answeredSince, beginStep, captureComment, captureIntact, conflictStep, createQueue, ctxFor, endSession, endStep, fail, form, looksGood, moreWrapup, n as releaseLock, payloadKey, pending, prune, redelivering, sameComment, settle, startSession, stillOwned, t as acquireLock, textOf, undelivered, wrapupIntact, wrapupOf } from "./queue-BuiCKSX1.mjs";
11
+ import { jamReservations, restoreHolds } from "./reserve-BURNQ2Y3.mjs";
12
+ import { jamLive } from "./live-Cgzsicwi.mjs";
13
+ import { lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
14
+ import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
15
+ import { createHash } from "node:crypto";
16
+ import { tmpdir } from "node:os";
17
+ import { spawn } from "node:child_process";
18
+ import { StringDecoder } from "node:string_decoder";
19
+ //#region src/server/jam/adapter/claude.ts
20
+ /**
21
+ * The Claude Code adapter. Spawns
22
+ * `claude -p` headless with STREAM-JSON output, so the daemon can post the agent's first
23
+ * message the moment it exists (the real quick ack / clarifying question - not a canned fake),
24
+ * and the final `result` event as the completion reply.
25
+ */
26
+ /** First key of an object, or undefined. */
27
+ const firstKey = (o) => o && typeof o === "object" ? Object.keys(o)[0] : void 0;
28
+ const cleanModel$1 = (raw) => typeof raw === "string" ? raw.replace(/\[[^\]]*\]$/, "") || void 0 : void 0;
29
+ const claudeAdapter = {
30
+ name: "claude",
31
+ supportsSubagents: true,
32
+ spawnArgs(goal) {
33
+ return {
34
+ cmd: "claude",
35
+ args: [
36
+ "-p",
37
+ goal,
38
+ "--permission-mode",
39
+ "acceptEdits",
40
+ "--allowedTools",
41
+ "Read,Edit,Write,Glob,Grep,WebSearch,WebFetch",
42
+ "--disallowedTools",
43
+ "Bash",
44
+ "--output-format",
45
+ "stream-json",
46
+ "--verbose"
47
+ ]
48
+ };
49
+ },
50
+ namerArgs(prompt) {
51
+ return {
52
+ cmd: "claude",
53
+ args: [
54
+ "-p",
55
+ prompt,
56
+ "--model",
57
+ "haiku",
58
+ "--tools",
59
+ "",
60
+ "--strict-mcp-config",
61
+ "--settings",
62
+ "{\"disableAllHooks\":true}",
63
+ "--no-session-persistence",
64
+ "--output-format",
65
+ "text"
66
+ ]
67
+ };
68
+ },
69
+ earlyText(line) {
70
+ try {
71
+ const o = JSON.parse(line);
72
+ if (o.type !== "assistant") return null;
73
+ const text = (o.message?.content ?? []).find((c) => c?.type === "text" && typeof c.text === "string" && c.text.trim());
74
+ return text ? {
75
+ text: String(text.text).trim(),
76
+ model: cleanModel$1(o.message?.model)
77
+ } : null;
78
+ } catch {
79
+ return null;
80
+ }
81
+ },
82
+ parse(stdout, code) {
83
+ let text = "";
84
+ let model;
85
+ let failed = false;
86
+ let sawEvents = false;
87
+ for (const line of stdout.split("\n")) {
88
+ const t = line.trim();
89
+ if (!t) continue;
90
+ try {
91
+ const o = JSON.parse(t);
92
+ sawEvents = true;
93
+ if (o.type === "result") {
94
+ if (typeof o.result === "string") text = o.result.trim();
95
+ if (o.is_error) failed = true;
96
+ model ??= cleanModel$1(firstKey(o.modelUsage));
97
+ } else if (o.type === "assistant") model ??= cleanModel$1(o.message?.model);
98
+ } catch {}
99
+ }
100
+ if (!text) try {
101
+ const j = JSON.parse(stdout);
102
+ if (typeof j.result === "string") text = j.result.trim();
103
+ model ??= cleanModel$1((typeof j.model === "string" ? j.model : void 0) ?? j.canonicalModel ?? firstKey(j.modelUsage));
104
+ } catch {
105
+ if (!sawEvents) text = stdout.trim();
106
+ }
107
+ const { reply, asks, reanchors, said } = parseAgentText(text);
108
+ return {
109
+ reply,
110
+ model,
111
+ asks,
112
+ reanchors,
113
+ said,
114
+ ok: code === 0 && !failed && !!reply
115
+ };
116
+ }
117
+ };
118
+ //#endregion
119
+ //#region src/server/jam/adapter/codex.ts
120
+ /**
121
+ * The Codex adapter. Spawns `codex exec --json`
122
+ * workspace-jailed. Codex emits JSONL events (thread.started, item.completed, turn.completed);
123
+ * the final agent_message is the reply.
124
+ *
125
+ * Subagents are ON: `codex exec` carries collaboration.spawn_agent / list_agents / wait_agent,
126
+ * so a multi-frame job fans out the same way Claude Code's does. The job prompt only ever says
127
+ * "you MAY", so an older codex without those tools simply works serially instead of failing.
128
+ */
129
+ const codexAdapter = {
130
+ name: "codex",
131
+ supportsSubagents: true,
132
+ spawnArgs(goal) {
133
+ return {
134
+ cmd: "codex",
135
+ args: [
136
+ "exec",
137
+ "--json",
138
+ "-s",
139
+ "workspace-write",
140
+ "--skip-git-repo-check",
141
+ goal
142
+ ]
143
+ };
144
+ },
145
+ earlyText(line) {
146
+ try {
147
+ const o = JSON.parse(line);
148
+ if (o.type === "item.completed" && o.item?.type === "agent_message" && typeof o.item.text === "string" && o.item.text.trim()) return { text: o.item.text.trim() };
149
+ } catch {}
150
+ return null;
151
+ },
152
+ parse(stdout, code) {
153
+ let text = "";
154
+ let model;
155
+ let failed = false;
156
+ for (const line of stdout.split("\n")) {
157
+ const t = line.trim();
158
+ if (!t) continue;
159
+ try {
160
+ const o = JSON.parse(t);
161
+ if (o.type === "item.completed" && o.item?.type === "agent_message" && typeof o.item.text === "string") text = o.item.text.trim();
162
+ else if (o.type === "turn.failed" || o.type === "error") failed = true;
163
+ if (typeof o.model === "string") model = o.model;
164
+ } catch {}
165
+ }
166
+ const { reply, asks, reanchors, said } = parseAgentText(text);
167
+ return {
168
+ reply,
169
+ model,
170
+ asks,
171
+ reanchors,
172
+ said,
173
+ ok: code === 0 && !failed && !!reply
174
+ };
175
+ }
176
+ };
177
+ //#endregion
178
+ //#region src/server/jam/adapter/cursor.ts
179
+ /**
180
+ * The Cursor adapter. Spawns `cursor-agent -p` headless with stream-json output - a
181
+ * Claude-Code-shaped stream (system/init carries the model, assistant events carry complete
182
+ * messages, a terminal `result` event carries the reply).
183
+ *
184
+ * The long binary name is deliberate: cursor's installer ships BOTH `cursor-agent` and a bare
185
+ * `agent`, and grok's installer symlinks `agent` too - on a machine with both, the short name
186
+ * is whichever installed last. `cursor-agent` is unambiguous.
187
+ *
188
+ * Jail: codex-parity, not claude-parity - cursor's print mode carries write AND shell
189
+ * tools, and the CLI has no per-run flag that removes the shell outright. So the OS
190
+ * sandbox is switched ON (`--sandbox enabled`, overriding any config that turned it off)
191
+ * to bound what commands can touch, and `--force` is never passed, so nothing gets blanket
192
+ * command approval. The packet carries untrusted text (synced collaborators' comments);
193
+ * the sandbox is what stands between it and the machine.
194
+ */
195
+ const assistantText$2 = (o) => {
196
+ if (o.type !== "assistant") return void 0;
197
+ const t = (o.message?.content ?? []).find((c) => c?.type === "text" && typeof c.text === "string" && c.text.trim());
198
+ return t ? String(t.text).trim() : void 0;
199
+ };
200
+ const cursorAdapter = {
201
+ name: "cursor",
202
+ supportsSubagents: false,
203
+ spawnArgs(goal) {
204
+ return {
205
+ cmd: "cursor-agent",
206
+ args: [
207
+ "-p",
208
+ goal,
209
+ "--output-format",
210
+ "stream-json",
211
+ "--sandbox",
212
+ "enabled",
213
+ "--trust"
214
+ ]
215
+ };
216
+ },
217
+ earlyText(line) {
218
+ try {
219
+ const o = JSON.parse(line);
220
+ const text = assistantText$2(o);
221
+ return text ? { text } : null;
222
+ } catch {
223
+ return null;
224
+ }
225
+ },
226
+ parse(stdout, code) {
227
+ let text = "";
228
+ let lastAssistant = "";
229
+ let model;
230
+ let failed = false;
231
+ for (const line of stdout.split("\n")) {
232
+ const t = line.trim();
233
+ if (!t) continue;
234
+ try {
235
+ const o = JSON.parse(t);
236
+ if (o.type === "result") {
237
+ if (typeof o.result === "string" && o.result.trim()) text = o.result.trim();
238
+ if (o.is_error) failed = true;
239
+ } else if (o.type === "system" && o.subtype === "init" && typeof o.model === "string" && o.model !== "unknown") model = o.model;
240
+ else {
241
+ const at = assistantText$2(o);
242
+ if (at) lastAssistant = at;
243
+ }
244
+ } catch {}
245
+ }
246
+ if (!text) text = lastAssistant;
247
+ const { reply, asks, reanchors, said } = parseAgentText(text);
248
+ return {
249
+ reply,
250
+ model,
251
+ asks,
252
+ reanchors,
253
+ said,
254
+ ok: code === 0 && !failed && !!reply
255
+ };
256
+ }
257
+ };
258
+ //#endregion
259
+ //#region src/server/jam/adapter/droid.ts
260
+ /**
261
+ * The Factory droid adapter. Spawns `droid exec -o stream-json` headless - a
262
+ * Claude-Code-shaped stream (system/init carries the model, a terminal `result` event
263
+ * carries the reply and `is_error`). Factory marks stream-json deprecated but it works
264
+ * (v0.200.0); parse() also reads the `-o json` single-envelope shape, so if a future droid
265
+ * drops the stream the switch is one argv word, not a parser rewrite.
266
+ *
267
+ * Jail: `--auto low` approves file creation/edit, and `--disabled-tools` then REMOVES the
268
+ * shell (`Execute`) and the outbound connectors (Slack posting, connector search) outright -
269
+ * the packet carries untrusted text, and both are exfiltration channels. Tool names come
270
+ * from droid's own `--list-tools` (v0.200.0). Claude-parity: edits yes, shell no.
271
+ */
272
+ const droidAdapter = {
273
+ name: "droid",
274
+ supportsSubagents: false,
275
+ spawnArgs(goal) {
276
+ return {
277
+ cmd: "droid",
278
+ args: [
279
+ "exec",
280
+ "-o",
281
+ "stream-json",
282
+ "--auto",
283
+ "low",
284
+ "--disabled-tools",
285
+ "Execute,Task,ProposeMission,StartMissionRun,GenerateDroid,slack_post_message,slack_post_file,ConnectorSearch",
286
+ "--disable-builtin-skills",
287
+ goal
288
+ ]
289
+ };
290
+ },
291
+ earlyText(line) {
292
+ try {
293
+ const o = JSON.parse(line);
294
+ if (o.type !== "assistant") return null;
295
+ const t = (o.message?.content ?? []).find((c) => c?.type === "text" && typeof c.text === "string" && c.text.trim());
296
+ return t ? { text: String(t.text).trim() } : null;
297
+ } catch {
298
+ return null;
299
+ }
300
+ },
301
+ parse(stdout, code) {
302
+ let text = "";
303
+ let model;
304
+ let failed = false;
305
+ let sawEvents = false;
306
+ for (const line of stdout.split("\n")) {
307
+ const t = line.trim();
308
+ if (!t) continue;
309
+ try {
310
+ const o = JSON.parse(t);
311
+ sawEvents = true;
312
+ if (o.type === "result") {
313
+ if (typeof o.result === "string") text = o.result.trim();
314
+ if (o.is_error) failed = true;
315
+ } else if (o.type === "system" && o.subtype === "init" && typeof o.model === "string") model = o.model;
316
+ else if (o.type === "error") failed = true;
317
+ } catch {}
318
+ }
319
+ if (!sawEvents) try {
320
+ const j = JSON.parse(stdout);
321
+ if (typeof j.result === "string") text = j.result.trim();
322
+ if (j.is_error) failed = true;
323
+ } catch {}
324
+ const { reply, asks, reanchors, said } = parseAgentText(text);
325
+ return {
326
+ reply,
327
+ model,
328
+ asks,
329
+ reanchors,
330
+ said,
331
+ ok: code === 0 && !failed && !!reply
332
+ };
333
+ }
334
+ };
335
+ //#endregion
336
+ //#region src/server/jam/adapter/grok.ts
337
+ /**
338
+ * The grok adapter (xAI's Grok Build CLI). Spawns `grok -p` headless with
339
+ * streaming-messages-json - an Anthropic-Messages-shaped stream: system/init and assistant
340
+ * frames name the model, a terminal `result` event carries the reply and `is_error`.
341
+ *
342
+ * Jail: an explicit `--tools` ALLOWLIST of read/edit primitives only - so the shell, web,
343
+ * X-search, subagents, scheduler, MCP, and image tools are all simply absent, not denied by
344
+ * name. (A deny-list is a footgun: grok's real shell tool is `run_terminal_command`, and an
345
+ * earlier `--disallowed-tools run_terminal_cmd` left the shell fully live - verified. An
346
+ * allowlist can't miss a tool it doesn't name.) `--permission-mode acceptEdits` auto-applies
347
+ * those edits so the headless run never stalls; `--no-subagents` is belt-and-braces (the
348
+ * allowlist already omits spawn_subagent). The packet carries untrusted text, so this is the
349
+ * no-shell, no-network posture.
350
+ *
351
+ * grok injects NO env marker into processes it spawns (verified in the grok-build source),
352
+ * so detection finds it by PATH order only - naming `jam: "grok"` in config always works.
353
+ */
354
+ const cleanModel = (raw) => typeof raw === "string" && raw && raw !== "unknown" ? raw : void 0;
355
+ const assistantText$1 = (o) => {
356
+ if (o.type !== "assistant") return void 0;
357
+ const t = (o.message?.content ?? []).find((c) => c?.type === "text" && typeof c.text === "string" && c.text.trim());
358
+ return t ? String(t.text).trim() : void 0;
359
+ };
360
+ const grokAdapter = {
361
+ name: "grok",
362
+ supportsSubagents: false,
363
+ spawnArgs(goal) {
364
+ return {
365
+ cmd: "grok",
366
+ args: [
367
+ "-p",
368
+ goal,
369
+ "--output-format",
370
+ "streaming-messages-json",
371
+ "--permission-mode",
372
+ "acceptEdits",
373
+ "--no-subagents",
374
+ "--tools",
375
+ "read_file,search_replace,list_dir,grep,todo_write"
376
+ ]
377
+ };
378
+ },
379
+ earlyText(line) {
380
+ try {
381
+ const o = JSON.parse(line);
382
+ const text = assistantText$1(o);
383
+ return text ? {
384
+ text,
385
+ model: cleanModel(o.message?.model)
386
+ } : null;
387
+ } catch {
388
+ return null;
389
+ }
390
+ },
391
+ parse(stdout, code) {
392
+ let text = "";
393
+ let lastAssistant = "";
394
+ let model;
395
+ let failed = false;
396
+ for (const line of stdout.split("\n")) {
397
+ const t = line.trim();
398
+ if (!t) continue;
399
+ try {
400
+ const o = JSON.parse(t);
401
+ if (o.type === "result") {
402
+ if (typeof o.result === "string" && o.result.trim()) text = o.result.trim();
403
+ if (o.is_error) failed = true;
404
+ } else if (o.type === "system" && o.subtype === "init") model ??= cleanModel(o.model);
405
+ else {
406
+ const at = assistantText$1(o);
407
+ if (at) {
408
+ lastAssistant = at;
409
+ model ??= cleanModel(o.message?.model);
410
+ }
411
+ }
412
+ } catch {}
413
+ }
414
+ if (!text) text = lastAssistant;
415
+ const { reply, asks, reanchors, said } = parseAgentText(text);
416
+ return {
417
+ reply,
418
+ model,
419
+ asks,
420
+ reanchors,
421
+ said,
422
+ ok: code === 0 && !failed && !!reply
423
+ };
424
+ }
425
+ };
426
+ //#endregion
427
+ //#region src/server/jam/adapter/opencode.ts
428
+ /**
429
+ * The opencode adapter. Spawns `opencode run --format json` headless - NDJSON events where
430
+ * finalized text parts are `{"type":"text","part":{type:"text",text}}` and errors are
431
+ * `{"type":"error","error":{name,data}}`. The LAST text part is the reply.
432
+ *
433
+ * Jail: headless opencode auto-REJECTS permission asks, and its `--auto` flag approves
434
+ * everything including arbitrary shell - so neither default works. The OPENCODE_PERMISSION
435
+ * env var (verified: it merges over the user's config for this one process) is DEFAULT-DENY
436
+ * with an explicit allowlist - so an unnamed or future tool is denied, not defaulted open.
437
+ * `--pure` runs without external plugins, which execute code OUTSIDE the tool-permission
438
+ * layer (a repo could otherwise ship a plugin the daemon's spawn would load and run).
439
+ * Claude-parity: edits yes, shell no. Subagents inherit it (verified live).
440
+ *
441
+ * opencode's stream names NO model in any event (verified against its schema) - so replies
442
+ * carry the harness without a model, same honest gap as codex. Never faked.
443
+ */
444
+ const textPart = (o) => o.type === "text" && typeof o.part?.text === "string" && o.part.text.trim() ? String(o.part.text).trim() : void 0;
445
+ const opencodeAdapter = {
446
+ name: "opencode",
447
+ supportsSubagents: true,
448
+ spawnArgs(goal) {
449
+ return {
450
+ cmd: "opencode",
451
+ args: [
452
+ "run",
453
+ "--pure",
454
+ "--format",
455
+ "json",
456
+ goal
457
+ ],
458
+ env: { OPENCODE_PERMISSION: "{\"*\":\"deny\",\"read\":\"allow\",\"edit\":\"allow\",\"glob\":\"allow\",\"grep\":\"allow\",\"list\":\"allow\",\"ls\":\"allow\",\"webfetch\":\"allow\",\"websearch\":\"allow\",\"task\":\"allow\",\"todowrite\":\"allow\",\"todoread\":\"allow\"}" }
459
+ };
460
+ },
461
+ earlyText(line) {
462
+ try {
463
+ const text = textPart(JSON.parse(line));
464
+ return text ? { text } : null;
465
+ } catch {
466
+ return null;
467
+ }
468
+ },
469
+ parse(stdout, code) {
470
+ let msgId;
471
+ let parts = [];
472
+ let failed = false;
473
+ for (const line of stdout.split("\n")) {
474
+ const t = line.trim();
475
+ if (!t) continue;
476
+ try {
477
+ const o = JSON.parse(t);
478
+ const part = textPart(o);
479
+ if (part) {
480
+ const id = typeof o.part?.messageID === "string" ? o.part.messageID : void 0;
481
+ if (id !== msgId) {
482
+ msgId = id;
483
+ parts = [];
484
+ }
485
+ parts.push(part);
486
+ } else if (o.type === "error") failed = true;
487
+ } catch {}
488
+ }
489
+ const { reply, asks, reanchors, said } = parseAgentText(parts.join("\n\n"));
490
+ return {
491
+ reply,
492
+ asks,
493
+ reanchors,
494
+ said,
495
+ ok: code === 0 && !failed && !!reply
496
+ };
497
+ }
498
+ };
499
+ //#endregion
500
+ //#region src/server/jam/adapter/pi.ts
501
+ /**
502
+ * The pi adapter (the pi coding agent). Spawns `pi -p --mode json` headless - NDJSON events
503
+ * where `message_end` carries each finished message and the terminal `agent_end` carries the
504
+ * authoritative full transcript. The reply is the last assistant text in `agent_end`
505
+ * (falling back to the last `message_end` when the stream was cut before it).
506
+ *
507
+ * Jail: pi has NO runtime permission system - the tool allowlist IS the jail, so bash is
508
+ * simply not on the list: read/edit/write/grep/find/ls. Claude-parity - edits yes, shell no
509
+ * (the packet carries untrusted text; a shell is an exfiltration channel).
510
+ * `--no-extensions --no-skills` keeps the headless run to those built-ins: extensions load
511
+ * arbitrary code outside the allowlist, which has no place in an unattended spawn.
512
+ */
513
+ /** Assistant text + model of one message object (message_end payload or agent_end member). */
514
+ const assistantText = (m) => {
515
+ const msg = m;
516
+ if (!msg || msg.role !== "assistant") return null;
517
+ const text = (Array.isArray(msg.content) ? msg.content : []).filter((c) => c?.type === "text" && typeof c.text === "string").map((c) => String(c.text).trim()).filter(Boolean).join("\n\n");
518
+ if (!text && !msg.errorMessage) return null;
519
+ return {
520
+ text,
521
+ model: typeof msg.model === "string" && msg.model ? msg.model : void 0,
522
+ error: Boolean(msg.errorMessage) || msg.stopReason === "error"
523
+ };
524
+ };
525
+ //#endregion
526
+ //#region src/server/jam/adapter/index.ts
527
+ const adapters = {
528
+ claude: claudeAdapter,
529
+ codex: codexAdapter,
530
+ cursor: cursorAdapter,
531
+ droid: droidAdapter,
532
+ opencode: opencodeAdapter,
533
+ grok: grokAdapter,
534
+ pi: {
535
+ name: "pi",
536
+ supportsSubagents: false,
537
+ spawnArgs(goal) {
538
+ return {
539
+ cmd: "pi",
540
+ args: [
541
+ "-p",
542
+ "--mode",
543
+ "json",
544
+ "--no-extensions",
545
+ "--no-skills",
546
+ "--tools",
547
+ "read,edit,write,grep,find,ls",
548
+ goal
549
+ ]
550
+ };
551
+ },
552
+ earlyText(line) {
553
+ try {
554
+ const o = JSON.parse(line);
555
+ if (o.type !== "message_end") return null;
556
+ const a = assistantText(o.message);
557
+ return a?.text && !a.error ? {
558
+ text: a.text,
559
+ model: a.model
560
+ } : null;
561
+ } catch {
562
+ return null;
563
+ }
564
+ },
565
+ parse(stdout, code) {
566
+ let last = null;
567
+ let fromEnd = false;
568
+ let failed = false;
569
+ for (const line of stdout.split("\n")) {
570
+ const t = line.trim();
571
+ if (!t) continue;
572
+ try {
573
+ const o = JSON.parse(t);
574
+ if (o.type === "agent_end" && Array.isArray(o.messages)) for (let i = o.messages.length - 1; i >= 0; i--) {
575
+ const a = assistantText(o.messages[i]);
576
+ if (a) {
577
+ last = a;
578
+ fromEnd = true;
579
+ break;
580
+ }
581
+ }
582
+ else if (o.type === "message_end" && !fromEnd) {
583
+ const a = assistantText(o.message);
584
+ if (a) last = a;
585
+ } else if (o.type === "error") failed = true;
586
+ } catch {}
587
+ }
588
+ if (last?.error) failed = true;
589
+ const { reply, asks, reanchors, said } = parseAgentText(last?.text ?? "");
590
+ return {
591
+ reply,
592
+ model: last?.model,
593
+ asks,
594
+ reanchors,
595
+ said,
596
+ ok: code === 0 && !failed && !!reply
597
+ };
598
+ }
599
+ }
600
+ };
601
+ //#endregion
602
+ //#region src/server/jam/daemon.ts
603
+ /**
604
+ * The Live Jam daemon - a module inside the long-lived dev server.
605
+ *
606
+ * The loop (spec 27): watch design/comments/ (dir-watch + ~5s rescan) → the queue ingests owner
607
+ * events (queue.ts: only a ledgered tag makes a card) → when a slot frees, claim what can run - the
608
+ * queued cards of one board on one frame make one batch, up to 8, with every brief frozen as text
609
+ * and the packet written to its file → spawn one headless agent (adapter) on a goal-phrased prompt
610
+ * that names the file → split its final message into one reply per member → write every result
611
+ * into the journal BEFORE posting anything → post each reply with a deterministic id → move the
612
+ * cards. A tag's card ends done ("replied") - its reply is in its thread; nothing raises a notice
613
+ * but a question or a failure.
614
+ *
615
+ * Startup is a barrier: nothing is scheduled until every orphan is fenced (`pgid`), the CLI holds
616
+ * are restored, batches with results are reconciled (posted, never rerun) and the rest re-armed.
617
+ *
618
+ * `createJam` is the loop with no timers or lock (a test drives `tick()` directly with an
619
+ * injected adapter); `startJam` wraps it with the repo lock, dir-watch, and rescan interval.
620
+ */
621
+ const LEASE_MS = 72e4;
622
+ const JOB_TIMEOUT_MS = 6e5;
623
+ const MAX_ATTEMPTS = 2;
624
+ const MAX_OUT = 2e6;
625
+ const RESCAN_MS = 5e3;
626
+ /** How often a card held by a chat agent's `work start` looks again. */
627
+ const HOLD_RECHECK_MS = 2e3;
628
+ /** Kill a whole process group (the child is detached, so pid === pgid). Best-effort. */
629
+ const fenceGroup = (pid) => {
630
+ try {
631
+ if (pid) process.kill(-pid, "SIGKILL");
632
+ } catch {}
633
+ };
634
+ /**
635
+ * What a spawned agent is allowed to inherit.
636
+ *
637
+ * Agents get the environment because they need it - PATH, HOME, the API key
638
+ * their own CLI signs in with. `MARVER_CLI_TOKEN` is the exception: it is the
639
+ * operator's credential for the PUBLISHED canvas, it is accepted as a shell
640
+ * fallback by `comments connect`, and an agent is the one process on this machine
641
+ * that is running somebody else's instructions. Handing it over would let a
642
+ * prompt-injected agent take the published canvas, which is a much larger blast
643
+ * radius than the frames it was asked to edit.
644
+ *
645
+ * Exported so the removal is testable: a spawn option nobody asserts is a spawn
646
+ * option that quietly grows back.
647
+ */
648
+ function agentEnv(from = process.env) {
649
+ const { MARVER_CLI_TOKEN: _withheld, ...rest } = from;
650
+ return rest;
651
+ }
652
+ const FRAME_FILE = /\.(tsx|jsx|html)$/;
653
+ /** Every frame FILE under design/scenes, as `frame id -> mtimeMs`. Used to see which frames the
654
+ * agent creates or edits mid-job (so the working glow can follow the work, not sit on the frame
655
+ * the comment happened to be pinned to). Infra files (`_layout`, `_fixtures`) are skipped. */
656
+ const sceneFrameMtimes = (root) => {
657
+ const scenesDir = join(root, "design", "scenes");
658
+ const out = /* @__PURE__ */ new Map();
659
+ let entries;
660
+ try {
661
+ entries = readdirSync(scenesDir, { recursive: true });
662
+ } catch {
663
+ return out;
664
+ }
665
+ for (const rel of entries) {
666
+ const parts = rel.split(/[\\/]/);
667
+ const base = parts[parts.length - 1];
668
+ if (!FRAME_FILE.test(base) || base.startsWith("_") || parts.slice(1, -1).some((s) => s.startsWith("_"))) continue;
669
+ try {
670
+ out.set(toFrameId(`scenes/${rel}`), statSync(join(scenesDir, rel)).mtimeMs);
671
+ } catch {}
672
+ }
673
+ return out;
674
+ };
675
+ /** The early ack posts VERBATIM, so a first line that narrates the agent's plan instead of
676
+ * addressing the owner must not ship. Deliberately NARROW - "acknowledg" only ever appears
677
+ * in meta-talk (a real ack never names itself), and the openers are pure plan phrasing.
678
+ * A skipped line just promotes the NEXT streamed text to ack; worst case is a later ack,
679
+ * never a lost one (the final reply posts regardless). */
680
+ const metaNarration = (text) => /acknowledg/i.test(text) || /^(let me |i'?ll start|i will start|first,? i |my plan|i'?m going to start|i am going to start)/i.test(text.trim());
681
+ /** Every file under design/ that is not a frame - the shared design source and assets a job may
682
+ * not edit - as `path -> mtimeMs`. The comment logs, the journal and pictures (.local), the board
683
+ * files, the build and the generated manifest are not design source. */
684
+ const sharedMtimes = (root) => {
685
+ const design = join(root, "design");
686
+ const out = /* @__PURE__ */ new Map();
687
+ let entries;
688
+ try {
689
+ entries = readdirSync(design, { recursive: true });
690
+ } catch {
691
+ return out;
692
+ }
693
+ for (const rel of entries) {
694
+ const parts = rel.split(/[\\/]/);
695
+ if (parts[0] === "comments" || parts[0] === "boards" || parts[0].startsWith(".") || rel === "manifest.json") continue;
696
+ const base = parts[parts.length - 1];
697
+ if (parts[0] === "scenes" && FRAME_FILE.test(base) && !base.startsWith("_") && !parts.slice(1, -1).some((x) => x.startsWith("_"))) continue;
698
+ try {
699
+ const st = statSync(join(design, rel));
700
+ if (st.isFile()) out.set(`design/${rel.split(/[\\/]/).join("/")}`, st.mtimeMs);
701
+ } catch {}
702
+ }
703
+ return out;
704
+ };
705
+ /** A `shared` file as the disk sees it: past the lexical check (any case - this filesystem may not
706
+ * care), its nearest existing ancestor must resolve inside design/, and the resolved path must
707
+ * still be shared design source - a symlink cannot alias local state, a board file or the outside. */
708
+ function canonicalShared(root, f) {
709
+ if (!sharedFile(f) || !sharedFile(f.toLowerCase())) return null;
710
+ try {
711
+ const design = realpathSync(join(root, "design"));
712
+ let at = join(root, f);
713
+ const tail = [];
714
+ for (;;) try {
715
+ lstatSync(at);
716
+ break;
717
+ } catch {
718
+ tail.unshift(basename(at));
719
+ at = dirname(at);
720
+ }
721
+ const rel = relative(design, join(realpathSync(at), ...tail));
722
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null;
723
+ return sharedFile(`design/${rel.split(sep).join("/")}`.toLowerCase()) ? f : null;
724
+ } catch {
725
+ return null;
726
+ }
727
+ }
728
+ /** The loop, without timers/watch/lock. Loads the queue (upgrading a v1 journal, baselining a
729
+ * fresh one); the first `tick()` recovers what a dead process left (the startup barrier), and
730
+ * every tick ingests, claims what can run and waits until the work is idle. */
731
+ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
732
+ const commentsDir = join(root, "design", "comments");
733
+ let stopped = false;
734
+ const q0 = createQueue(root, (fence) => {
735
+ for (const pid of fence) fenceGroup(pid);
736
+ log(` jam: only comments that tag @marver start work now - plain replies are listed in \`npx marver marks\` for your agent`);
737
+ }, () => !stopped);
738
+ const q = {
739
+ get j() {
740
+ return q0.j;
741
+ },
742
+ ctx: () => q0.ctx(),
743
+ lock: (fn) => q0.lock((j, ctx) => {
744
+ if (stopped) throw new Error("jam stopped");
745
+ return fn(j, ctx);
746
+ }),
747
+ persist: () => {
748
+ if (!stopped) q0.persist();
749
+ }
750
+ };
751
+ const activeChildren = /* @__PURE__ */ new Set();
752
+ const running = /* @__PURE__ */ new Map();
753
+ const runningBatches = /* @__PURE__ */ new Map();
754
+ /** every run that starts, counted: a run knows whether another began while it ran */
755
+ let batchStarts = 0;
756
+ const runAgent = (goal, onSpawn, onEarly) => new Promise((resolve) => {
757
+ const { cmd, args, env } = adapter.spawnArgs(goal);
758
+ let child;
759
+ try {
760
+ child = spawn(cmd, args, {
761
+ cwd: root,
762
+ detached: true,
763
+ stdio: [
764
+ "ignore",
765
+ "pipe",
766
+ "ignore"
767
+ ],
768
+ env: {
769
+ ...agentEnv(),
770
+ ...env,
771
+ PWD: root
772
+ }
773
+ });
774
+ } catch {
775
+ return resolve({
776
+ reply: "",
777
+ asks: false,
778
+ ok: false,
779
+ reanchors: []
780
+ });
781
+ }
782
+ activeChildren.add(child);
783
+ try {
784
+ onSpawn(child.pid);
785
+ } catch {}
786
+ let out = "";
787
+ let lineBuf = "";
788
+ let earlyFired = !onEarly || !adapter.earlyText;
789
+ let settled = false;
790
+ const decoder = new StringDecoder("utf8");
791
+ const settle = (r) => {
792
+ if (settled) return;
793
+ settled = true;
794
+ clearTimeout(to);
795
+ activeChildren.delete(child);
796
+ resolve(r);
797
+ };
798
+ const to = setTimeout(() => {
799
+ fenceGroup(child.pid);
800
+ settle({
801
+ reply: "",
802
+ asks: false,
803
+ ok: false,
804
+ reanchors: []
805
+ });
806
+ }, JOB_TIMEOUT_MS);
807
+ child.stdout?.on("data", (chunk) => {
808
+ const d = decoder.write(chunk);
809
+ out += d;
810
+ if (out.length > MAX_OUT) out = out.slice(-2e6);
811
+ if (earlyFired) return;
812
+ lineBuf += d;
813
+ const lines = lineBuf.split("\n");
814
+ lineBuf = lines.pop() ?? "";
815
+ for (const line of lines) {
816
+ const hit = adapter.earlyText(line);
817
+ if (!hit) continue;
818
+ const block = /```marver-reply/.test(hit.text) ? parseMembers(hit.text, ["m1"]).m1 : null;
819
+ if (block && !("body" in block)) continue;
820
+ const text = block && "body" in block ? block.body : parseAgentText(hit.text).reply.split(/\n\s*\n/)[0].trim();
821
+ if (!text || metaNarration(text)) continue;
822
+ earlyFired = true;
823
+ try {
824
+ onEarly(text, !!block && "body" in block && block.asks, hit.model);
825
+ } catch {}
826
+ break;
827
+ }
828
+ });
829
+ child.on("close", (code) => settle({
830
+ ...adapter.parse(out, code ?? 1),
831
+ raw: out
832
+ }));
833
+ child.on("error", () => settle({
834
+ reply: "",
835
+ asks: false,
836
+ ok: false,
837
+ reanchors: []
838
+ }));
839
+ });
840
+ /** Persist each run's raw stream to design/.local/jam-logs/ (gitignored, last 10 kept) - so
841
+ * "why did it reply THAT" is always answerable from the actual agent output. */
842
+ const logRun = (batchId, raw) => {
843
+ if (!raw) return;
844
+ try {
845
+ const dir = join(root, "design", ".local", "jam-logs");
846
+ mkdirSync(dir, { recursive: true });
847
+ writeFileSync(join(dir, `${batchId}.log`), raw, { mode: 384 });
848
+ const files = readdirSync(dir).filter((f) => f.endsWith(".log")).map((f) => ({
849
+ f,
850
+ t: statSync(join(dir, f)).mtimeMs
851
+ })).sort((a, b) => b.t - a.t);
852
+ for (const { f } of files.slice(10)) rmSync(join(dir, f), { force: true });
853
+ } catch {}
854
+ };
855
+ /** House style: never an em/en dash in a reply - a plain dash reads human. */
856
+ const plainDashes = (s) => s.replace(/\s*[—–]\s*/g, " - ");
857
+ const me = () => localProfile(root);
858
+ /** Post one reply in a card's thread. Deterministic ids - `jam-<batch>-<member>` for the reply,
859
+ * `jam-e<attempt>-<batch>` for a one-member job's early ack - so posting twice is a no-op. */
860
+ const postReply = (b, c, member, body, asks, model, kind = "reply", alsoChanged) => {
861
+ const suffix = kind === "early" ? `e${b.attempts}-${b.batchId}` : `${b.batchId}-${member}`;
862
+ const who = me();
863
+ const reply = {
864
+ id: `jam-${suffix}`,
865
+ ts: Date.now(),
866
+ type: "reply",
867
+ commentId: `jam-c-${suffix}`,
868
+ parentId: c.thread,
869
+ board: c.board,
870
+ author: who,
871
+ body: plainDashes(body),
872
+ asks,
873
+ ...alsoChanged?.length ? { alsoChanged } : {},
874
+ agent: true,
875
+ agentMeta: {
876
+ devUser: who.name,
877
+ harness: adapter.name,
878
+ model
879
+ }
880
+ };
881
+ appendEvents(commentsDir, c.board, [reply]);
882
+ return {
883
+ commentId: reply.commentId,
884
+ ts: reply.ts
885
+ };
886
+ };
887
+ /** Emit reanchor events for threads the agent re-pinned, in the shared anchor format: each
888
+ * element found in the rendered frame the way `comments move` finds it, unchecked when the
889
+ * check cannot run, skipped when the frame shows no such element or several. Owner-authored +
890
+ * agent:true (attributable, never a trigger), deterministic ids so a re-run dedups. */
891
+ const emitReanchors = async (b, cards, reanchors) => {
892
+ let n = 0;
893
+ for (const [k, r] of reanchors.entries()) {
894
+ const m = b.members.find((x) => cards.find((c) => c.id === x.card)?.thread === r.thread) ?? b.members[0];
895
+ const board = m.board;
896
+ const threads = replay(readLog(commentsDir, board));
897
+ const t = threads.find((t) => t.id === r.thread);
898
+ if (!t?.frame) {
899
+ log(` jam: re-pin skipped - no thread ${r.thread} on ${board}`);
900
+ continue;
901
+ }
902
+ const others = threads.filter((o) => !o.resolved && o.frame === t.frame && o.id !== t.id).map((o) => ({
903
+ key: o.id,
904
+ anchor: o.anchor
905
+ }));
906
+ const check = hooks.anchor ? await hooks.anchor(t.frame, r.target, others, r.look).catch((err) => ({
907
+ ok: false,
908
+ unchecked: err.message
909
+ })) : {
910
+ ok: false,
911
+ unchecked: "no anchor check here"
912
+ };
913
+ if (stopped) return n;
914
+ if (!check.ok && "refused" in check) {
915
+ log(` jam: re-pin skipped - ${t.frame} shows ${check.refused === "none" ? "no" : "several"} matching elements`);
916
+ continue;
917
+ }
918
+ const who = me();
919
+ appendEvents(commentsDir, board, [{
920
+ id: `jam-${b.batchId}-${m.id}-r${k}`,
921
+ ts: Date.now(),
922
+ type: "reanchor",
923
+ commentId: t.id,
924
+ anchor: check.ok ? check.anchor : uncheckedAnchor(r.target),
925
+ board,
926
+ author: who,
927
+ agent: true,
928
+ agentMeta: {
929
+ devUser: who.name,
930
+ harness: adapter.name
931
+ }
932
+ }]);
933
+ n++;
934
+ }
935
+ return n;
936
+ };
937
+ /** A short name for a capture, from its words, by a small fast model (the adapter's namer - Haiku with Claude
938
+ * Code), as soon as it lands: the lane, the panel and its thread show it. Never over a name you gave it;
939
+ * nothing when the agent has no namer, the capture has no words, or the call fails (its first words stay). */
940
+ const naming = /* @__PURE__ */ new Set();
941
+ let namerDir;
942
+ const nameCapture = (id) => {
943
+ const c0 = q.j.cards.find((x) => x.id === id);
944
+ if (!adapter.namerArgs || cfg.names === false || !c0 || c0.kind !== "capture" || c0.name || c0.autoName || naming.has(id)) return;
945
+ const cap = readCapture(root, id);
946
+ const words = cap ? [captureWords(cap.record, c0.payload?.edited), ...(c0.payload?.added ?? []).map((a) => a.text)].join("\n").trim() : "";
947
+ if (!words) return;
948
+ naming.add(id);
949
+ const prompt = "Name this design note in 2 to 6 plain words, like a short task title (e.g. \"New product page\", \"Quieter save button\"). Reply with the name only - no quotes, no punctuation at the end.\n\nThe note (spoken and written):\n" + words.slice(0, 4e3);
950
+ const { cmd, args } = adapter.namerArgs(prompt);
951
+ let out = "";
952
+ let child;
953
+ namerDir ??= mkdtempSync(join(tmpdir(), "marver-namer-"));
954
+ const cwd = namerDir;
955
+ try {
956
+ child = spawn(cmd, args, {
957
+ cwd,
958
+ stdio: [
959
+ "ignore",
960
+ "pipe",
961
+ "ignore"
962
+ ],
963
+ env: {
964
+ ...agentEnv(),
965
+ PWD: cwd
966
+ }
967
+ });
968
+ } catch {
969
+ naming.delete(id);
970
+ return;
971
+ }
972
+ const to = setTimeout(() => {
973
+ try {
974
+ child.kill();
975
+ } catch {}
976
+ }, 45e3);
977
+ child.stdout?.on("data", (d) => {
978
+ out += d.toString("utf8");
979
+ if (out.length > 4e3) out = out.slice(0, 4e3);
980
+ });
981
+ child.on("error", () => {
982
+ clearTimeout(to);
983
+ naming.delete(id);
984
+ });
985
+ child.on("close", (code) => {
986
+ clearTimeout(to);
987
+ naming.delete(id);
988
+ if (stopped || code !== 0) return;
989
+ const name = (out.split("\n").map((l) => l.trim()).find(Boolean) ?? "").replace(/^["'“”‘’`*#\s-]+|["'“”‘’`*.\s]+$/g, "").replace(/\s+/g, " ").slice(0, 60).trim();
990
+ if (!name) return;
991
+ q.lock((j) => {
992
+ const c = j.cards.find((x) => x.id === id);
993
+ if (!c || c.name || c.autoName) return;
994
+ c.autoName = name;
995
+ q.persist();
996
+ }).then(() => {
997
+ titles.delete(id);
998
+ queueChanged();
999
+ });
1000
+ });
1001
+ };
1002
+ /** A capture names every frame its run made (hosted on one or not) - and so does work queued on its thread
1003
+ * meanwhile: a tag or a More work waiting on it holds those frames when it runs. At delivery, and when the run
1004
+ * fails (its Retry is a new batch from the card: it must still hold them). Under the lock. */
1005
+ const ownCreated = (j, b) => {
1006
+ if (!b.created?.length || b.members.length !== 1) return;
1007
+ const live = liveCreated(b);
1008
+ const c = j.cards.find((x) => x.id === b.members[0].card);
1009
+ if (c) for (const x of j.cards.filter((y) => y === c || y.state === "queued" && y.board === c.board && !!c.thread && y.thread === c.thread)) {
1010
+ const add = live.filter((f) => !x.frames.includes(f));
1011
+ if (add.length) {
1012
+ x.frames = [...x.frames, ...add];
1013
+ if (x !== c) {
1014
+ x.rev += 1;
1015
+ x.at = Date.now();
1016
+ }
1017
+ }
1018
+ }
1019
+ };
1020
+ /** A capture whose run made a new frame and left every frame it named as it was asked for something new: at
1021
+ * delivery (again after a restart - it is in the batch with the results), its thread moves onto the new frame
1022
+ * (a re-pin naming the frame, frame-level, a deterministic id: written once) and its card names that frame. */
1023
+ const hostOnNew = (b) => {
1024
+ const live = new Set(liveCreated(b));
1025
+ for (const h of b.hosts ?? []) {
1026
+ if (!live.has(h.frame)) continue;
1027
+ const m = b.members.find((x) => x.id === h.member);
1028
+ const c = m && q.j.cards.find((x) => x.id === m.card);
1029
+ if (!c?.thread) continue;
1030
+ const id = `jam-${b.batchId}-${h.member}-host`;
1031
+ if (readLog(commentsDir, c.board).some((e) => e.id === id)) continue;
1032
+ const who = me();
1033
+ appendEvents(commentsDir, c.board, [{
1034
+ id,
1035
+ ts: Date.now(),
1036
+ type: "reanchor",
1037
+ commentId: c.thread,
1038
+ frame: h.frame,
1039
+ board: c.board,
1040
+ author: who,
1041
+ agent: true,
1042
+ agentMeta: {
1043
+ devUser: who.name,
1044
+ harness: adapter.name
1045
+ }
1046
+ }]);
1047
+ }
1048
+ };
1049
+ /** The frames a run made that still exist, on a board it works on (one made, then renamed or removed, is not). */
1050
+ const liveCreated = (b) => {
1051
+ if (!b.created?.length) return [];
1052
+ const now = sceneFrameMtimes(root);
1053
+ const boards = [...new Set(b.members.map((m) => m.board))];
1054
+ const onBoard = (f) => boards.some((board) => {
1055
+ try {
1056
+ const j = JSON.parse(readFileSync(join(root, "design", "boards", `${board}.json`), "utf8"));
1057
+ return j.auto === true || Array.isArray(j.nodes) && j.nodes.some((n) => n?.frame === f);
1058
+ } catch {
1059
+ return false;
1060
+ }
1061
+ });
1062
+ return b.created.filter((f) => now.has(f) && onBoard(f));
1063
+ };
1064
+ /** A frame's size where it sits on a board (its node's width and height), when the board says. */
1065
+ const sizeOnBoard = (frame, board) => {
1066
+ try {
1067
+ const n = (JSON.parse(readFileSync(join(root, "design", "boards", `${board}.json`), "utf8")).nodes ?? []).find((x) => x?.frame === frame);
1068
+ return n && Number.isFinite(n.w) && Number.isFinite(n.h) && n.w > 0 && n.h > 0 ? {
1069
+ w: Math.round(n.w),
1070
+ h: Math.round(n.h)
1071
+ } : void 0;
1072
+ } catch {
1073
+ return;
1074
+ }
1075
+ };
1076
+ /** Frames that exist now and did not when the run began, on a board the batch works on - three at most. */
1077
+ const newFrames = (start, b) => {
1078
+ const boards = [...new Set(b.members.map((m) => m.board))];
1079
+ const onBoard = (f) => boards.some((board) => {
1080
+ try {
1081
+ const j = JSON.parse(readFileSync(join(root, "design", "boards", `${board}.json`), "utf8"));
1082
+ return j.auto === true || Array.isArray(j.nodes) && j.nodes.some((n) => n?.frame === f);
1083
+ } catch {
1084
+ return false;
1085
+ }
1086
+ });
1087
+ return [...sceneFrameMtimes(root).keys()].filter((f) => !start.has(f) && onBoard(f));
1088
+ };
1089
+ const realShared = (f) => canonicalShared(root, f);
1090
+ const cards0 = (b) => b.members.map((m) => q.j.cards.find((c) => c.id === m.card)).filter((c) => !!c);
1091
+ const changedBoards = (b) => {
1092
+ for (const board of new Set(b.members.map((m) => m.board))) hooks.changed?.(board);
1093
+ };
1094
+ const reserve = (exclusiveWaiting) => {
1095
+ if (stopped) return;
1096
+ jamReservations.frames = new Map([...runningBatches.values()].flatMap((b) => b.frames.map((f) => [f, b.batchId])));
1097
+ const exclusiveRunning = [...runningBatches.values()].some((b) => b.exclusive);
1098
+ jamReservations.exclusive = exclusiveRunning ? "running" : exclusiveWaiting ?? q.j.cards.some((c) => c.state === "queued" && (c.exclusive || !c.frames.length)) ? "waiting" : null;
1099
+ jamReservations.settling = !ready || delivering.size > 0;
1100
+ };
1101
+ const queueChanged = () => {
1102
+ try {
1103
+ hooks.queue?.();
1104
+ } catch {}
1105
+ };
1106
+ const settled = (out) => {
1107
+ for (const s of out) if (s.notice === "failed") log(` jam: ${s.card.id} failed - ${s.card.note}`);
1108
+ };
1109
+ /** Post a batch's results (each append a no-op if it already landed) and move its cards. Never
1110
+ * runs the agent: a batch with results is reconciled, not rerun. Everything it needs is in the
1111
+ * journal (results, re-pins, the early ack), so a resumed delivery does exactly what the first
1112
+ * one would have. */
1113
+ const deliver = async (b) => {
1114
+ if (stopped) return;
1115
+ const cards = b.members.map((m) => q.j.cards.find((c) => c.id === m.card)).filter((c) => !!c);
1116
+ const early = b.early;
1117
+ const posted = {};
1118
+ const loggedTs = (board, id) => readLog(commentsDir, board).find((e) => e.id === id)?.ts;
1119
+ for (const m of b.members) {
1120
+ const c = cards.find((x) => x.id === m.card);
1121
+ const r = b.results?.[m.id];
1122
+ if (!c || !r || !("body" in r) || !c.thread) continue;
1123
+ const sameAsEarly = !!early && b.members.length === 1 && r.body === early.body;
1124
+ const earlyAsked = !!early && b.members.length === 1 && (sameAsEarly || early.asks || /\?\s*$/.test(early.body));
1125
+ const answered = r.asks && earlyAsked && answeredSince(ctxFor(root), c.board, c.thread, early.ts);
1126
+ if (sameAsEarly) {
1127
+ if (r.asks && !early.asks && !answered) {
1128
+ const who = me();
1129
+ appendEvents(commentsDir, c.board, [{
1130
+ id: `jam-f-e${b.attempts}-${b.batchId}`,
1131
+ ts: Date.now(),
1132
+ type: "edit",
1133
+ commentId: early.commentId,
1134
+ asks: true,
1135
+ board: c.board,
1136
+ author: who,
1137
+ agent: true,
1138
+ agentMeta: {
1139
+ devUser: who.name,
1140
+ harness: adapter.name
1141
+ }
1142
+ }]);
1143
+ }
1144
+ if (r.alsoChanged?.length) {
1145
+ const who = me();
1146
+ appendEvents(commentsDir, c.board, [{
1147
+ id: `jam-ac-${b.batchId}`,
1148
+ ts: Date.now(),
1149
+ type: "edit",
1150
+ commentId: early.commentId,
1151
+ alsoChanged: r.alsoChanged,
1152
+ board: c.board,
1153
+ author: who,
1154
+ agent: true,
1155
+ agentMeta: {
1156
+ devUser: who.name,
1157
+ harness: adapter.name
1158
+ }
1159
+ }]);
1160
+ }
1161
+ posted[m.id] = {
1162
+ reply: early.commentId,
1163
+ answered,
1164
+ asked: early.ts
1165
+ };
1166
+ } else {
1167
+ const p = postReply(b, c, m.id, r.body, r.asks && !answered, r.model, "reply", r.alsoChanged);
1168
+ posted[m.id] = {
1169
+ reply: p.commentId,
1170
+ answered,
1171
+ asked: loggedTs(c.board, `jam-${b.batchId}-${m.id}`) ?? p.ts
1172
+ };
1173
+ }
1174
+ }
1175
+ hostOnNew(b);
1176
+ const repinned = await emitReanchors(b, cards, b.reanchors ?? []);
1177
+ if (stopped) return;
1178
+ changedBoards(b);
1179
+ await q.lock((j) => {
1180
+ ownCreated(j, b);
1181
+ for (const m of b.members) {
1182
+ const c = j.cards.find((x) => x.id === m.card);
1183
+ const r = b.results?.[m.id];
1184
+ const p = posted[m.id];
1185
+ if (c?.thread && p && !p.answered && r && "body" in r && r.asks && p.asked) p.answered = answeredSince(ctxFor(root), c.board, c.thread, p.asked);
1186
+ }
1187
+ b.posted = true;
1188
+ settled(settle(j, b, posted));
1189
+ q.persist();
1190
+ });
1191
+ queueChanged();
1192
+ const replies = Object.keys(posted).length;
1193
+ log(` jam: replied ${replies} of ${b.members.length}${b.model ? ` (${b.model})` : ""}${repinned ? ` · re-pinned ${repinned}` : ""}`);
1194
+ };
1195
+ const runBatch = async (b) => {
1196
+ const myStart = ++batchStarts;
1197
+ const aloneAtStart = [...runningBatches.keys()].every((k) => k === b.batchId);
1198
+ let crowded = !!hooks.anyHold?.();
1199
+ const markCrowded = (x) => {
1200
+ if (x.crowded) return;
1201
+ q.lock(() => {
1202
+ x.crowded = true;
1203
+ q.persist();
1204
+ });
1205
+ };
1206
+ const unwatch = hooks.watchHolds?.(() => {
1207
+ crowded = true;
1208
+ markCrowded(b);
1209
+ }) ?? (() => {});
1210
+ for (const o of runningBatches.values()) if (o !== b) markCrowded(o);
1211
+ const bad = [];
1212
+ const logs = /* @__PURE__ */ new Map();
1213
+ const threadsOf = (board) => {
1214
+ let t = logs.get(board);
1215
+ if (!t) logs.set(board, t = replay(readLog(commentsDir, board)));
1216
+ return t;
1217
+ };
1218
+ const members = [];
1219
+ let disk = null;
1220
+ try {
1221
+ disk = JSON.parse(readFileSync(join(root, packetPath(b.batchId)), "utf8"));
1222
+ } catch {
1223
+ disk = null;
1224
+ }
1225
+ for (const m of b.members) {
1226
+ const c = q.j.cards.find((x) => x.id === m.card);
1227
+ const kept = m.brief ?? (c && c.kind !== "wrapup" ? disk?.members.find((x) => x.card === m.card && x.id === m.id)?.brief : void 0);
1228
+ if (!c || !kept) {
1229
+ bad.push(m.card);
1230
+ continue;
1231
+ }
1232
+ let brief = kept;
1233
+ if (c.kind === "wrapup") {
1234
+ const w = readWrapup(root, wrapupOf(c));
1235
+ if (!w || !wrapupIntact(q.ctx(), c) || recordPathProblem(root, w.wrapup.file)) {
1236
+ bad.push(m.card);
1237
+ continue;
1238
+ }
1239
+ brief = {
1240
+ ...brief,
1241
+ wrapup: {
1242
+ content: w.wrapup,
1243
+ hash: w.hash
1244
+ }
1245
+ };
1246
+ } else if (brief.wrapup) {
1247
+ const { wrapup: _w, ...rest } = brief;
1248
+ brief = rest;
1249
+ }
1250
+ const t = c.thread ? threadsOf(m.board).find((x) => x.id === c.thread) : void 0;
1251
+ members.push({
1252
+ id: m.id,
1253
+ card: c.id,
1254
+ kind: c.kind,
1255
+ board: m.board,
1256
+ ...c.thread ? { thread: c.thread } : {},
1257
+ frames: c.frames,
1258
+ ...t?.anchor !== void 0 ? { anchor: t.anchor } : {},
1259
+ brief
1260
+ });
1261
+ }
1262
+ if (bad.length) {
1263
+ await q.lock((j) => {
1264
+ for (const id of bad) {
1265
+ const c = j.cards.find((x) => x.id === id);
1266
+ if (c && c.state === "working") {
1267
+ c.state = "failed";
1268
+ c.note = c.kind === "wrapup" ? "the session record changed after it was written - write it again" : "interrupted - Retry";
1269
+ c.rev += 1;
1270
+ c.at = Date.now();
1271
+ }
1272
+ }
1273
+ q.persist();
1274
+ });
1275
+ b.members = b.members.filter((m) => !bad.includes(m.card));
1276
+ if (!b.members.length) {
1277
+ await q.lock((j) => {
1278
+ const x = j.batches.find((y) => y.batchId === b.batchId);
1279
+ if (x) x.state = "failed";
1280
+ q.persist();
1281
+ });
1282
+ queueChanged();
1283
+ return;
1284
+ }
1285
+ }
1286
+ const packet = buildPacket(b.batchId, members, b.frames, b.exclusive ? [...new Set(cards0(b).flatMap((c) => c.exclusive ?? []))] : void 0);
1287
+ writeFileSync(join(root, packetPath(b.batchId)), JSON.stringify(packet, null, 1), { mode: 384 });
1288
+ const cards = () => b.members.map((m) => q.j.cards.find((c) => c.id === m.card)).filter((c) => !!c);
1289
+ const lit = /* @__PURE__ */ new Set();
1290
+ const light = (f) => {
1291
+ if (f && !lit.has(f)) {
1292
+ hooks.work?.(f, true);
1293
+ lit.add(f);
1294
+ }
1295
+ };
1296
+ const clearGlow = () => {
1297
+ for (const f of lit) hooks.work?.(f, false);
1298
+ lit.clear();
1299
+ };
1300
+ const startMtimes = sceneFrameMtimes(root);
1301
+ await q.lock(() => {
1302
+ const made = new Set(b.created ?? []);
1303
+ b.before = [.../* @__PURE__ */ new Set([...b.before ?? [], ...[...startMtimes.keys()].filter((f) => !made.has(f))])];
1304
+ q.persist();
1305
+ });
1306
+ if (crowded || !aloneAtStart) await q.lock(() => {
1307
+ b.crowded = true;
1308
+ q.persist();
1309
+ });
1310
+ const one0 = b.members.length === 1 ? q.j.cards.find((c) => c.id === b.members[0].card) : void 0;
1311
+ const discover = async () => {
1312
+ if (one0?.kind !== "capture" || b.crowded || crowded || !aloneAtStart || batchStarts !== myStart || hooks.anyHold?.()) return;
1313
+ const found = newFrames(new Set(b.before ?? []), b).filter((f) => !(b.created ?? []).includes(f));
1314
+ if (!found.length) return;
1315
+ await q.lock(() => {
1316
+ b.created = [...b.created ?? [], ...found];
1317
+ b.frames = [.../* @__PURE__ */ new Set([...b.frames, ...b.created])];
1318
+ q.persist();
1319
+ });
1320
+ reserve();
1321
+ };
1322
+ const sharedBefore = b.exclusive ? null : sharedMtimes(root);
1323
+ const touched = /* @__PURE__ */ new Set();
1324
+ for (const f of b.frames) light(f);
1325
+ const capturing = cards().some((c) => !!c.capture);
1326
+ const theme = (() => {
1327
+ const c = cards().find((x) => x.capture);
1328
+ return c && readCapture(root, c.capture)?.record.view.theme || "light";
1329
+ })();
1330
+ const sizes = Object.assign({}, ...cards().flatMap((c) => c.capture ? [readCapture(root, c.capture)?.record.sizes ?? {}] : []));
1331
+ const shoot = async (when) => {
1332
+ if (!capturing || !hooks.shoot) return;
1333
+ const shots = b.shots ?? b.frames.map((frame) => ({ frame }));
1334
+ for (const s of shots) {
1335
+ if (stopped) return;
1336
+ if (s.new) continue;
1337
+ const id = await hooks.shoot(s.frame, theme, { batch: b.batchId }, sizes[s.frame]).catch(() => null);
1338
+ if (id) s[when] = id;
1339
+ }
1340
+ if (when === "after") for (const s of shots) if (s.before && s.after && samePicture(s.before, s.after)) s.same = true;
1341
+ else delete s.same;
1342
+ await q.lock(() => {
1343
+ b.shots = shots;
1344
+ q.persist();
1345
+ });
1346
+ };
1347
+ if (!b.shots?.some((s) => s.before)) await shoot("before");
1348
+ const followWork = () => {
1349
+ if (hooks.anyHold?.()) crowded = true;
1350
+ discover();
1351
+ for (const [id, mt] of sceneFrameMtimes(root)) if (startMtimes.get(id) !== mt) touched.add(id);
1352
+ for (const id of touched) light(id);
1353
+ for (const f of lit) hooks.work?.(f, true);
1354
+ };
1355
+ let early;
1356
+ let run = {
1357
+ reply: "",
1358
+ asks: false,
1359
+ ok: false,
1360
+ reanchors: []
1361
+ };
1362
+ try {
1363
+ while (!stopped && b.attempts < MAX_ATTEMPTS) {
1364
+ await q.lock(() => {
1365
+ b.attempts += 1;
1366
+ b.leaseUntil = Date.now() + LEASE_MS;
1367
+ q.persist();
1368
+ });
1369
+ for (const m of packet.members) if (m.kind === "wrapup") {
1370
+ const c = q.j.cards.find((x) => x.id === m.card);
1371
+ const w = c && readWrapup(root, wrapupOf(c));
1372
+ if (!c || !w || !wrapupIntact(q.ctx(), c) || recordPathProblem(root, w.wrapup.file)) throw new Error("the session record changed after it was written - write it again");
1373
+ m.brief = {
1374
+ ...m.brief,
1375
+ wrapup: {
1376
+ content: w.wrapup,
1377
+ hash: w.hash
1378
+ }
1379
+ };
1380
+ }
1381
+ writeFileSync(join(root, packetPath(b.batchId)), JSON.stringify(packet, null, 1), { mode: 384 });
1382
+ const beat = setInterval(followWork, 2e3);
1383
+ beat.unref?.();
1384
+ try {
1385
+ const one = b.members.length === 1 ? cards()[0] : void 0;
1386
+ run = await runAgent(goalText(packet, cfg.subagents && adapter.supportsSubagents), (pid) => {
1387
+ b.pgid = pid;
1388
+ q.persist();
1389
+ }, one?.thread ? (text, asks, model) => {
1390
+ if (stopped) return;
1391
+ const p = postReply(b, one, "m1", text, asks, model, "early");
1392
+ early = {
1393
+ body: text,
1394
+ asks,
1395
+ commentId: p.commentId,
1396
+ ts: p.ts
1397
+ };
1398
+ hooks.changed?.(one.board);
1399
+ } : void 0);
1400
+ } finally {
1401
+ clearInterval(beat);
1402
+ }
1403
+ logRun(b.batchId, run.raw);
1404
+ if (run.ok) break;
1405
+ }
1406
+ if (stopped) return;
1407
+ if (!run.ok) {
1408
+ await discover();
1409
+ await q.lock((j) => {
1410
+ ownCreated(j, b);
1411
+ settled(fail(j, b, "the agent could not finish - its run log is in design/.local/jam-logs"));
1412
+ q.persist();
1413
+ });
1414
+ queueChanged();
1415
+ log(` jam: gave up on a batch of ${b.members.length} after ${b.attempts} attempts`);
1416
+ return;
1417
+ }
1418
+ if (!aloneAtStart || batchStarts !== myStart || crowded || hooks.anyHold?.()) {
1419
+ if (!b.crowded) await q.lock(() => {
1420
+ b.crowded = true;
1421
+ q.persist();
1422
+ });
1423
+ }
1424
+ await discover();
1425
+ await shoot("after");
1426
+ const one = b.members.length === 1 ? cards()[0] : void 0;
1427
+ const created = capturing && one?.kind === "capture" ? liveCreated(b) : [];
1428
+ let hosts = [];
1429
+ if (!created.length && b.shots?.some((x) => x.new)) await q.lock(() => {
1430
+ b.shots = (b.shots ?? []).filter((x) => !x.new);
1431
+ q.persist();
1432
+ });
1433
+ if (created.length && hooks.shoot) {
1434
+ const shots = (b.shots ?? []).filter((x) => !x.new);
1435
+ for (const f of created.slice(0, 3)) {
1436
+ if (stopped) return;
1437
+ if (shots.some((x) => x.frame === f)) continue;
1438
+ const id = await hooks.shoot(f, theme, { batch: b.batchId }, sizeOnBoard(f, one.board)).catch(() => null);
1439
+ shots.push({
1440
+ frame: f,
1441
+ ...id ? { after: id } : {},
1442
+ new: true
1443
+ });
1444
+ }
1445
+ const own = shots.filter((x) => !x.new && one.frames.includes(x.frame));
1446
+ if (one.thread && own.every((x) => x.same)) hosts = [{
1447
+ member: b.members[0].id,
1448
+ frame: created[0]
1449
+ }];
1450
+ await q.lock(() => {
1451
+ b.shots = shots;
1452
+ q.persist();
1453
+ });
1454
+ }
1455
+ const split = parseMembers(run.said ?? run.reply, b.members.map((m) => m.id));
1456
+ const changedShared = sharedBefore ? [...sharedMtimes(root)].filter(([f, mt]) => sharedBefore.get(f) !== mt).map(([f]) => f) : [];
1457
+ const results = {};
1458
+ for (const [id, r0] of Object.entries(split)) {
1459
+ let r = r0;
1460
+ if ("shared" in r) {
1461
+ const files = r.shared.map(realShared).filter((f) => !!f);
1462
+ r = files.length ? { shared: files } : { missing: true };
1463
+ }
1464
+ results[id] = "body" in r ? {
1465
+ body: r.body,
1466
+ asks: r.asks,
1467
+ ...run.model ? { model: run.model } : {},
1468
+ reanchors: [],
1469
+ ...changedShared.length ? { alsoChanged: changedShared } : {}
1470
+ } : r;
1471
+ }
1472
+ await q.lock(() => {
1473
+ b.results = results;
1474
+ if (run.reanchors.length) b.reanchors = run.reanchors;
1475
+ if (hosts.length) b.hosts = hosts;
1476
+ if (early) b.early = early;
1477
+ if (run.model) b.model = run.model;
1478
+ q.persist();
1479
+ });
1480
+ if (changedShared.length) log(` jam: also changed ${changedShared.map((f) => relative("design", f)).join(", ")}`);
1481
+ await deliver(b);
1482
+ } finally {
1483
+ unwatch();
1484
+ clearGlow();
1485
+ }
1486
+ };
1487
+ /** Write a card's pending comment (once - an event already there must say the same, or the step
1488
+ * fails closed), ledger it, and end the step. Under the lock; resumable at any point. */
1489
+ const finishStep = (id) => q.lock((j) => {
1490
+ const c = j.cards.find((x) => x.id === id);
1491
+ const p = c?.pending;
1492
+ if (!c || !p) return c ? structuredClone(c) : void 0;
1493
+ const there = readLog(commentsDir, c.board).find((e) => e.id === p.event.id);
1494
+ if (there && !sameComment(there, p.event)) {
1495
+ conflictStep(j, c);
1496
+ q.persist();
1497
+ return structuredClone(c);
1498
+ }
1499
+ if (!there) appendEvents(commentsDir, c.board, [p.event]);
1500
+ record(root, c.board, p.event.id);
1501
+ if (p.op === "confirm") record(root, c.board, payloadKey(c));
1502
+ settled(endStep(j, c));
1503
+ q.persist();
1504
+ return structuredClone(c);
1505
+ });
1506
+ /** Confirm a draft (`end: queued`) or keep it from its read-back (`end: kept`): one recoverable step.
1507
+ * A retried request after a lost answer finds the step done and answers with the card. */
1508
+ const confirm = async (id, rev, end) => {
1509
+ const c0 = q.j.cards.find((x) => x.id === id);
1510
+ if (!c0 || c0.kind !== "capture") return {
1511
+ ok: false,
1512
+ error: "no such capture"
1513
+ };
1514
+ if (c0.pending?.op === "confirm") return {
1515
+ ok: true,
1516
+ card: await finishStep(id)
1517
+ };
1518
+ if (c0.thread && (c0.state === end || end === "queued" && [
1519
+ "working",
1520
+ "asks",
1521
+ "review",
1522
+ "done"
1523
+ ].includes(c0.state))) return {
1524
+ ok: true,
1525
+ card: structuredClone(c0)
1526
+ };
1527
+ if (c0.state !== "draft" || c0.rev !== rev) return {
1528
+ ok: false,
1529
+ card: structuredClone(c0),
1530
+ error: "the card changed - look again"
1531
+ };
1532
+ const cap = readCapture(root, id);
1533
+ if (!cap || cap.hash !== c0.payload?.recordHash) return {
1534
+ ok: false,
1535
+ card: structuredClone(c0),
1536
+ error: "the capture changed after it was sealed"
1537
+ };
1538
+ const point = firstPoint(cap.record);
1539
+ let at = { frame: point?.frame ?? captureFrames(cap.record)[0] };
1540
+ if (point?.frame && hooks.anchor) {
1541
+ const target = point.bundle.quote && point.bundle.quote !== "•••" ? { on: point.bundle.quote } : point.bundle.testId && point.bundle.testId !== "•••" ? { at: point.bundle.testId } : point.bundle.cssPath ? { at: point.bundle.cssPath } : null;
1542
+ if (target) {
1543
+ const check = await hooks.anchor(point.frame, target, [], void 0).catch(() => null);
1544
+ if (check?.ok) at = {
1545
+ frame: point.frame,
1546
+ anchor: check.anchor
1547
+ };
1548
+ }
1549
+ }
1550
+ if (!await q.lock((j) => {
1551
+ const c = j.cards.find((x) => x.id === id);
1552
+ if (!c || c.state !== "draft" || c.rev !== rev) return null;
1553
+ beginStep(j, c, "confirm", captureComment(c, cap.record, at, me()), Date.now(), end);
1554
+ q.persist();
1555
+ return true;
1556
+ })) return {
1557
+ ok: false,
1558
+ card: structuredClone(q.j.cards.find((x) => x.id === id)),
1559
+ error: "the card changed - look again"
1560
+ };
1561
+ const card = await finishStep(id);
1562
+ reserve();
1563
+ queueChanged();
1564
+ pump();
1565
+ return {
1566
+ ok: card?.state === end,
1567
+ card,
1568
+ ...card?.state === end ? {} : { error: card?.note }
1569
+ };
1570
+ };
1571
+ /** More work on a review: your words post as an @marver reply in the capture's thread (a ledgered
1572
+ * `mw-` reply that mints no tag card) and the SAME card goes round again, first. Recoverable. */
1573
+ const moreWork = async (id, rev, words) => {
1574
+ const c0 = q.j.cards.find((x) => x.id === id);
1575
+ if (c0?.pending?.op === "more") return {
1576
+ ok: true,
1577
+ card: await finishStep(id)
1578
+ };
1579
+ if (!words.trim()) return {
1580
+ ok: false,
1581
+ card: c0 && structuredClone(c0),
1582
+ error: "say what more to do"
1583
+ };
1584
+ if (c0?.kind === "wrapup") {
1585
+ const r = await q.lock((j, ctx) => {
1586
+ const c = j.cards.find((x) => x.id === id);
1587
+ if (!c || c.state !== "review" || c.rev !== rev || !c.payload) return { error: "the card changed - look again" };
1588
+ const prev = readWrapup(root, c.id);
1589
+ if (!prev || !wrapupIntact(ctx, c)) return { error: "the session record changed after it was written - write it again" };
1590
+ const w = moreOf(prev.wrapup, words.trim());
1591
+ const hash = storeWrapup(root, w);
1592
+ record(root, c.board, `wrapup:${w.id}:${hash}`);
1593
+ const next = moreWrapup(j, c, w, hash);
1594
+ q.persist();
1595
+ return { card: structuredClone(next) };
1596
+ });
1597
+ if ("error" in r) {
1598
+ const c = q.j.cards.find((x) => x.id === id);
1599
+ return {
1600
+ ok: false,
1601
+ card: c && structuredClone(c),
1602
+ error: r.error
1603
+ };
1604
+ }
1605
+ reserve();
1606
+ queueChanged();
1607
+ pump();
1608
+ return {
1609
+ ok: true,
1610
+ card: r.card
1611
+ };
1612
+ }
1613
+ if (!await q.lock((j) => {
1614
+ const c = j.cards.find((x) => x.id === id);
1615
+ if (!c || c.state !== "review" || c.rev !== rev || !c.thread) return null;
1616
+ const who = me();
1617
+ beginStep(j, c, "more", {
1618
+ id: `mw-${c.id}-${c.rev}`,
1619
+ ts: Date.now(),
1620
+ type: "reply",
1621
+ commentId: `mw-c-${c.id}-${c.rev}`,
1622
+ parentId: c.thread,
1623
+ board: c.board,
1624
+ author: who,
1625
+ body: `@marver ${words.trim()}`.slice(0, 2e4)
1626
+ });
1627
+ q.persist();
1628
+ return true;
1629
+ })) {
1630
+ const c = q.j.cards.find((x) => x.id === id);
1631
+ return {
1632
+ ok: false,
1633
+ card: c && structuredClone(c),
1634
+ error: "the card changed - look again"
1635
+ };
1636
+ }
1637
+ const card = await finishStep(id);
1638
+ reserve();
1639
+ queueChanged();
1640
+ pump();
1641
+ hooks.changed?.(card?.board ?? "");
1642
+ return {
1643
+ ok: card?.state === "queued",
1644
+ card
1645
+ };
1646
+ };
1647
+ /** Looks good: done, and the thread resolved (an ordinary owner resolve) unless something newer is open. */
1648
+ const good = async (id, rev) => {
1649
+ const r = await q.lock((j, ctx) => {
1650
+ const c = j.cards.find((x) => x.id === id);
1651
+ if (!c || c.state !== "review" || c.rev !== rev) return {
1652
+ ok: false,
1653
+ card: c && structuredClone(c),
1654
+ error: "the card changed - look again"
1655
+ };
1656
+ const { resolve } = looksGood(j, ctx, c, readLog(commentsDir, c.board));
1657
+ if (resolve && c.thread) appendEvents(commentsDir, c.board, [{
1658
+ id: `rs-${c.id}-${rev}`,
1659
+ ts: Date.now(),
1660
+ type: "resolve",
1661
+ commentId: c.thread,
1662
+ board: c.board,
1663
+ author: me()
1664
+ }]);
1665
+ q.persist();
1666
+ return {
1667
+ ok: true,
1668
+ card: structuredClone(c)
1669
+ };
1670
+ });
1671
+ if (r.ok) {
1672
+ queueChanged();
1673
+ hooks.changed?.(r.card.board);
1674
+ }
1675
+ return r;
1676
+ };
1677
+ let recheck = null;
1678
+ const holdLater = () => {
1679
+ if (recheck || stopped) return;
1680
+ recheck = setTimeout(() => {
1681
+ recheck = null;
1682
+ pump();
1683
+ }, HOLD_RECHECK_MS);
1684
+ recheck.unref?.();
1685
+ };
1686
+ const waitingSaid = /* @__PURE__ */ new Set();
1687
+ /** Batches recovered at boot that still wait for a chat agent's hold to end; they keep their frames. */
1688
+ const deferred = [];
1689
+ /** Claim what can run now and start it. Under the lock, after the ingest. */
1690
+ const pump = async () => {
1691
+ if (stopped || !ready) return;
1692
+ if (delivering.size) {
1693
+ holdLater();
1694
+ return;
1695
+ }
1696
+ for (const b of [...deferred]) {
1697
+ if (b.frames.some((f) => hooks.held?.(f)) || b.exclusive && hooks.anyHold?.()) {
1698
+ holdLater();
1699
+ continue;
1700
+ }
1701
+ deferred.splice(deferred.indexOf(b), 1);
1702
+ launch(b);
1703
+ }
1704
+ const started = await q.lock((j, ctx) => {
1705
+ const frames = new Set([...runningBatches.values()].flatMap((b) => b.frames));
1706
+ const { batches, exclusiveWaiting } = form(j, ctx, {
1707
+ free: Math.max(1, cfg.concurrency) - runningBatches.size,
1708
+ running: frames,
1709
+ exclusiveRunning: [...runningBatches.values()].some((b) => b.exclusive),
1710
+ held: (f) => !!hooks.held?.(f),
1711
+ anyHold: () => !!hooks.anyHold?.()
1712
+ });
1713
+ prune(j);
1714
+ q.persist();
1715
+ for (const b of batches) runningBatches.set(b.batchId, b);
1716
+ reserve(exclusiveWaiting);
1717
+ for (const c of j.cards) {
1718
+ if (c.state !== "queued") continue;
1719
+ const held = c.frames.find((f) => hooks.held?.(f));
1720
+ if (held || exclusiveWaiting && (c.exclusive || !c.frames.length)) {
1721
+ holdLater();
1722
+ if (held && !waitingSaid.has(c.id)) {
1723
+ waitingSaid.add(c.id);
1724
+ log(` jam: waiting - ${held} is being worked on in chat; the comment runs once it is done`);
1725
+ }
1726
+ } else waitingSaid.delete(c.id);
1727
+ }
1728
+ return batches;
1729
+ });
1730
+ if (started.length) queueChanged();
1731
+ for (const b of started) launch(b);
1732
+ };
1733
+ /** Batches whose results are saved and whose replies wait to be posted again. While any does, it
1734
+ * keeps its frames, nothing new is dispatched and no new hold is taken: what it moves (a `shared`
1735
+ * answer turns exclusive) must exist before anything else starts. */
1736
+ const delivering = /* @__PURE__ */ new Set();
1737
+ const settleDelivery = (b) => {
1738
+ delivering.delete(b.batchId);
1739
+ runningBatches.delete(b.batchId);
1740
+ reserve();
1741
+ queueChanged();
1742
+ pump();
1743
+ };
1744
+ /** Post a batch's results again after a failed delivery - a few times, further apart. If it never
1745
+ * posts, its cards fail with the results kept: Retry posts them (and a boot tries again) - the agent
1746
+ * never runs twice for one result. */
1747
+ const timers = /* @__PURE__ */ new Set();
1748
+ /** a wait that stop() cancels (it resolves at once then; the caller checks `stopped`) */
1749
+ const naps = /* @__PURE__ */ new Set();
1750
+ const nap = (ms) => new Promise((done) => {
1751
+ const t = setTimeout(() => {
1752
+ timers.delete(t);
1753
+ naps.delete(wake);
1754
+ done();
1755
+ }, ms);
1756
+ const wake = () => {
1757
+ clearTimeout(t);
1758
+ timers.delete(t);
1759
+ done();
1760
+ };
1761
+ timers.add(t);
1762
+ naps.add(wake);
1763
+ });
1764
+ const redeliver = (b, n, delay = 5e3 * n) => {
1765
+ if (stopped) return;
1766
+ delivering.add(b.batchId);
1767
+ runningBatches.set(b.batchId, b);
1768
+ reserve();
1769
+ const t = setTimeout(() => {
1770
+ timers.delete(t);
1771
+ if (stopped) return;
1772
+ deliver(b).then(() => settleDelivery(b), async (err) => {
1773
+ log(` jam: posting failed again - ${err.message}`);
1774
+ if (n < 5) return redeliver(b, n + 1);
1775
+ await q.lock((j) => {
1776
+ settled(undelivered(j, b, "its replies could not be posted - Retry posts them"));
1777
+ q.persist();
1778
+ }).catch(() => {});
1779
+ settleDelivery(b);
1780
+ });
1781
+ }, delay);
1782
+ timers.add(t);
1783
+ t.unref?.();
1784
+ };
1785
+ const launch = (b) => {
1786
+ runningBatches.set(b.batchId, b);
1787
+ const p = (async () => {
1788
+ try {
1789
+ await runBatch(b);
1790
+ } catch (err) {
1791
+ log(` jam: batch error - ${err.message}`);
1792
+ if (b.results) redeliver(b, 1);
1793
+ else {
1794
+ try {
1795
+ await q.lock((j) => {
1796
+ settled(fail(j, b, `the job broke: ${err.message}`));
1797
+ q.persist();
1798
+ });
1799
+ } catch {}
1800
+ queueChanged();
1801
+ }
1802
+ } finally {
1803
+ if (!delivering.has(b.batchId)) runningBatches.delete(b.batchId);
1804
+ running.delete(b.batchId);
1805
+ reserve();
1806
+ try {
1807
+ await pump();
1808
+ } catch (err) {
1809
+ log(` jam: pump error - ${err.message}`);
1810
+ }
1811
+ }
1812
+ })();
1813
+ running.set(b.batchId, p);
1814
+ };
1815
+ let ready = false;
1816
+ let recovering = null;
1817
+ const recover = () => recovering ??= (async () => {
1818
+ for (const c of q.j.cards.filter((x) => x.pending)) await finishStep(c.id).catch((err) => log(` jam: could not resume a step - ${err.message}`));
1819
+ const leftover = await q.lock((j) => {
1820
+ const out = [];
1821
+ for (const b of j.batches) {
1822
+ if (b.state !== "claimed") continue;
1823
+ if (b.results) {
1824
+ out.push({
1825
+ b,
1826
+ results: true
1827
+ });
1828
+ continue;
1829
+ }
1830
+ fenceGroup(b.pgid);
1831
+ const ctx = q.ctx();
1832
+ const logs = /* @__PURE__ */ new Map();
1833
+ const logOf = (board) => {
1834
+ let l = logs.get(board);
1835
+ if (!l) logs.set(board, l = readLog(commentsDir, board));
1836
+ return l;
1837
+ };
1838
+ const owned = (board, id) => ctx.owned.has(`${board}\t${id}`) && logOf(board).some((e) => e.id === id);
1839
+ const askOk = (board, a) => stillOwned(ctx, board, logOf(board), a);
1840
+ const clean = (board, brief, comment) => !brief || !comment ? brief : {
1841
+ ...brief,
1842
+ asks: brief.asks.filter((a) => askOk(board, a)),
1843
+ history: brief.history.map((m) => m.owner && !askOk(board, m) ? {
1844
+ id: m.id,
1845
+ ...m.author ? { author: m.author } : {},
1846
+ body: m.body,
1847
+ ts: m.ts,
1848
+ note: "someone else - context only"
1849
+ } : m),
1850
+ ...brief.follows ? { follows: {
1851
+ ...brief.follows,
1852
+ asks: brief.follows.asks.filter((a) => askOk(board, a))
1853
+ } } : {}
1854
+ };
1855
+ for (const m of b.members) {
1856
+ const c = j.cards.find((x) => x.id === m.card);
1857
+ if (!c) continue;
1858
+ if (c.capture && !captureIntact(j, ctx, c.capture)) {
1859
+ c.state = "failed";
1860
+ c.note = "the capture changed after it was confirmed - capture it again";
1861
+ c.rev += 1;
1862
+ c.at = Date.now();
1863
+ continue;
1864
+ }
1865
+ if (c.kind === "wrapup" && !wrapupIntact(ctx, c)) {
1866
+ c.state = "failed";
1867
+ c.note = "the session record changed after it was written - write it again";
1868
+ c.rev += 1;
1869
+ c.at = Date.now();
1870
+ continue;
1871
+ }
1872
+ const comment = c.kind === "comment";
1873
+ const had = c.brief?.asks.length ?? 0;
1874
+ c.brief = clean(c.board, c.brief, true);
1875
+ m.brief = clean(m.board, m.brief, true);
1876
+ const events = c.events.filter((id) => owned(c.board, id));
1877
+ if (events.length !== c.events.length && (events.length || !comment)) c.events = events;
1878
+ if (comment && (!events.length || had > 0 && !c.brief?.asks.length)) {
1879
+ c.state = "dropped";
1880
+ c.note = "no longer authorized";
1881
+ c.rev += 1;
1882
+ c.at = Date.now();
1883
+ }
1884
+ }
1885
+ const survivors = b.members.filter((m) => j.cards.find((x) => x.id === m.card)?.state === "working");
1886
+ if (!survivors.length) {
1887
+ b.state = "done";
1888
+ continue;
1889
+ }
1890
+ const ids = new Map(survivors.map((m, i) => [m.card, `m${i + 1}`]));
1891
+ const renumbered = survivors.some((m) => ids.get(m.card) !== m.id) || survivors.length !== b.members.length;
1892
+ b.members = survivors.map((m) => ({
1893
+ ...m,
1894
+ id: ids.get(m.card)
1895
+ }));
1896
+ const file = join(root, packetPath(b.batchId));
1897
+ try {
1898
+ const packet = JSON.parse(readFileSync(file, "utf8"));
1899
+ const members = packet.members.filter((m) => ids.has(m.card)).map((m) => ({
1900
+ ...m,
1901
+ id: ids.get(m.card),
1902
+ brief: clean(m.board, m.brief, true)
1903
+ }));
1904
+ const next = {
1905
+ ...packet,
1906
+ members
1907
+ };
1908
+ if (renumbered || JSON.stringify(next) !== JSON.stringify(packet)) writeFileSync(file, JSON.stringify(next, null, 1), { mode: 384 });
1909
+ } catch {
1910
+ b.state = "failed";
1911
+ b.note = "its packet is gone";
1912
+ for (const m of b.members) {
1913
+ const c = j.cards.find((x) => x.id === m.card);
1914
+ if (c) {
1915
+ c.state = "failed";
1916
+ c.note = "interrupted - Retry";
1917
+ c.rev += 1;
1918
+ c.at = Date.now();
1919
+ }
1920
+ }
1921
+ continue;
1922
+ }
1923
+ out.push({
1924
+ b,
1925
+ results: false
1926
+ });
1927
+ }
1928
+ q.persist();
1929
+ return out;
1930
+ });
1931
+ for (const { b } of leftover) runningBatches.set(b.batchId, b);
1932
+ reserve();
1933
+ for (const { b } of leftover.filter((x) => x.results)) {
1934
+ await q.lock((j) => {
1935
+ redelivering(j, b);
1936
+ q.persist();
1937
+ });
1938
+ for (let n = 1;; n++) try {
1939
+ await deliver(b);
1940
+ break;
1941
+ } catch (err) {
1942
+ if (n >= 4 || stopped) {
1943
+ log(` jam: could not post a recovered batch - ${err.message}; its cards fail, Retry posts them`);
1944
+ await q.lock((j) => {
1945
+ settled(undelivered(j, b, "its replies could not be posted - Retry posts them"));
1946
+ q.persist();
1947
+ });
1948
+ break;
1949
+ }
1950
+ await nap(500 * 2 ** n);
1951
+ if (stopped) return;
1952
+ }
1953
+ runningBatches.delete(b.batchId);
1954
+ }
1955
+ ready = true;
1956
+ reserve();
1957
+ for (const { b } of leftover.filter((x) => !x.results)) deferred.push(b);
1958
+ })();
1959
+ const idle = async () => {
1960
+ while (running.size && !stopped) await Promise.race([...running.values()]);
1961
+ };
1962
+ const tick = async () => {
1963
+ if (stopped) return;
1964
+ try {
1965
+ await recover();
1966
+ await pump();
1967
+ } catch (err) {
1968
+ log(` jam: tick error - ${err.message}`);
1969
+ }
1970
+ await idle();
1971
+ };
1972
+ /** A capture's record is the one sealed: its card holds the hash of these bytes, ledgered at the seal. */
1973
+ const sourceIntact = (id) => {
1974
+ const card = q.j.cards.find((c) => c.id === id && c.kind === "capture");
1975
+ const cap = readCapture(root, id);
1976
+ return !!card?.payload && !!cap && cap.hash === card.payload.recordHash && has(root, card.board, `capture:${id}:${cap.hash}`);
1977
+ };
1978
+ /** Already stored under this id (a retried upload): the checks ran when it was first taken. */
1979
+ const storedOnce = (rec) => q.j.cards.some((c) => c.id === rec.id);
1980
+ /** A capture's More work asks (its events after the confirm - each ledgered as yours), in order, each
1981
+ * with the result of the run that took it (none yet for one still queued or working). */
1982
+ const moreAsks = (j, ctx, c) => {
1983
+ if (!c.events.length) return [];
1984
+ const log = readLog(commentsDir, c.board);
1985
+ const runs = [...c.ran ?? [], ...c.batch ? [c.batch] : []].map((id) => j.batches.find((b) => b.batchId === id)).filter((b) => !!b);
1986
+ return c.events.filter((id) => id.startsWith("mw-")).flatMap((id) => {
1987
+ const ev = log.find((e) => e.id === id);
1988
+ if (!ev || !ctx.owned.has(`${c.board}\t${id}`)) return [];
1989
+ const took = runs.flatMap((b) => {
1990
+ const m = b.members.find((x) => x.card === c.id && x.brief?.asks.some((a) => a.id === id));
1991
+ return m ? [{
1992
+ b,
1993
+ m
1994
+ }] : [];
1995
+ });
1996
+ const ask = (took[took.length - 1]?.m.brief?.asks.find((a) => a.id === id)?.body ?? textOf(ctx, c.board, log, ev, true).body).replace(/^@marver\s*/i, "").trim();
1997
+ const answered = [...took].reverse().find(({ b, m }) => {
1998
+ const r = b.results?.[m.id];
1999
+ return !!r && "body" in r;
2000
+ });
2001
+ const r = answered?.b.results?.[answered.m.id];
2002
+ const failed = !answered && took.length > 0 && took.every(({ b }) => b.state === "done" || b.state === "failed");
2003
+ return [{
2004
+ ask,
2005
+ ...r && "body" in r ? { result: r.body } : failed ? { result: "(the run failed - not done)" } : {}
2006
+ }];
2007
+ });
2008
+ };
2009
+ /** A sealed capture taken in: checked (and, resumed, as a continuation), stored, ledgered, a draft card -
2010
+ * or queued at once with `jam.capture: 'at-once'`. */
2011
+ const landCapture = async (rec) => {
2012
+ const rs = rec.context.resumes;
2013
+ if (rs && !storedOnce(rec)) {
2014
+ const src = readCapture(root, rs.id);
2015
+ if (!src || !sourceIntact(rs.id)) return {
2016
+ ok: false,
2017
+ error: "the capture it resumes changed after it was sealed - capture it again"
2018
+ };
2019
+ if (!continues(src.record, rec, rs.at)) return {
2020
+ ok: false,
2021
+ error: "this capture does not continue the one it resumes"
2022
+ };
2023
+ }
2024
+ const stored = storeCapture(root, rec);
2025
+ if (typeof stored === "string") return {
2026
+ ok: false,
2027
+ error: stored
2028
+ };
2029
+ record(root, rec.context.board, `capture:${rec.id}:${stored.hash}`);
2030
+ const card = await q.lock((j) => {
2031
+ const c = addCapture(j, rec, stored.hash);
2032
+ q.persist();
2033
+ return structuredClone(c);
2034
+ });
2035
+ queueChanged();
2036
+ if (cfg.capture === "at-once" && card.state === "draft") return confirm(card.id, card.rev, "queued");
2037
+ return {
2038
+ ok: true,
2039
+ card
2040
+ };
2041
+ };
2042
+ /** Captures of a session open on some page, until they land: capture id -> its session, renewed until. */
2043
+ const openCaps = /* @__PURE__ */ new Map();
2044
+ /** Captures of a session being taken in right now (counted: a retry may overlap the first upload). */
2045
+ const landing = /* @__PURE__ */ new Map();
2046
+ const openFor = (session) => {
2047
+ const now = Date.now();
2048
+ for (const [k, v] of openCaps) if (v.until < now) openCaps.delete(k);
2049
+ return [...openCaps.values()].some((v) => v.session === session) || [...landing.values()].some((v) => v.session === session);
2050
+ };
2051
+ /** Tags written since a session began (they are answered in their threads, not in its record). */
2052
+ const tagsSince = (j, since) => {
2053
+ const seen = /* @__PURE__ */ new Set();
2054
+ for (const c of j.cards) for (const id of c.events) if (!id.startsWith("cap-") && !id.startsWith("mw-") && (c.when?.[id] ?? c.made) >= since) seen.add(`${c.board}|${id}`);
2055
+ return seen.size;
2056
+ };
2057
+ /** The agent's reply on a card's last run, as it said it. */
2058
+ const resultFor = (j, c) => {
2059
+ const b = j.batches.find((x) => x.batchId === (c.batch ?? c.ran?.[c.ran.length - 1]));
2060
+ const m = b?.members.find((x) => x.card === c.id);
2061
+ const r = m && b?.results?.[m.id];
2062
+ return r && "body" in r ? r.body : void 0;
2063
+ };
2064
+ /** Two pictures with the same bytes (the same render of the same pixels). */
2065
+ const samePicture = (a, b) => {
2066
+ const fa = picturePath(root, a), fb = picturePath(root, b);
2067
+ if (!fa || !fb) return false;
2068
+ try {
2069
+ const h = (p) => createHash("sha256").update(readFileSync(p)).digest("hex");
2070
+ return h(fa.path) === h(fb.path);
2071
+ } catch {
2072
+ return false;
2073
+ }
2074
+ };
2075
+ /** What the lane and the review need of a capture card - its first words, whether it is in the
2076
+ * run, its last run's before and after pictures, the run it reviewed, your edit, its notes. */
2077
+ const titles = /* @__PURE__ */ new Map();
2078
+ const captureView = (c) => {
2079
+ if (c.kind === "wrapup") return {
2080
+ title: c.name ?? "Session record",
2081
+ inRun: !!q.j.run && c.made >= q.j.run.since,
2082
+ ...c.session ? { session: c.session } : {},
2083
+ ...readWrapup(root, wrapupOf(c)) ? { file: readWrapup(root, wrapupOf(c)).wrapup.file } : {}
2084
+ };
2085
+ let t = titles.get(c.id);
2086
+ if (!t) {
2087
+ const rec = readCapture(root, c.id)?.record;
2088
+ t = {
2089
+ title: (rec ? rec.timeline.flatMap((x) => x.event === "words" || x.event === "note" ? [x.text] : []).join(" ").replace(/\s+/g, " ").trim() : "").slice(0, 300) || "Capture",
2090
+ notes: rec ? rec.timeline.filter((x) => x.event === "note").length : 0
2091
+ };
2092
+ if (rec) titles.set(c.id, t);
2093
+ }
2094
+ const b = q.j.batches.find((x) => x.batchId === c.batch);
2095
+ return {
2096
+ title: c.name ?? c.autoName ?? (c.payload?.edited !== void 0 ? c.payload.edited.replace(/\s+/g, " ").trim().slice(0, 300) || "(no words)" : t.title),
2097
+ notes: t.notes,
2098
+ ...c.name ? { named: true } : {},
2099
+ ...c.name ?? c.autoName ? { name: c.name ?? c.autoName } : {},
2100
+ inRun: !!q.j.run && c.made >= q.j.run.since,
2101
+ ...c.session ? { session: c.session } : {},
2102
+ ...b?.shots ? { shots: b.shots } : {},
2103
+ ...c.reviewing ? { reviewing: c.reviewing } : {},
2104
+ ...c.payload?.edited !== void 0 ? { edited: c.payload.edited } : {},
2105
+ ...c.payload?.added?.length ? { added: c.payload.added } : {}
2106
+ };
2107
+ };
2108
+ const boot = Math.random().toString(36).slice(2, 10);
2109
+ let viewN = 0;
2110
+ const view = () => {
2111
+ const j = q.j;
2112
+ const queued = j.cards.filter((c) => c.state === "queued").sort((a, b) => a.order - b.order || a.made - b.made);
2113
+ const shown = j.cards.filter((c) => pending(c) || c.at > Date.now() - 6e4 || !!j.run && c.kind !== "comment" && c.made >= j.run.since);
2114
+ const exclusiveAhead = jamReservations.exclusive;
2115
+ return {
2116
+ agent: adapter.name,
2117
+ seq: {
2118
+ boot,
2119
+ n: ++viewN
2120
+ },
2121
+ ...q.j.run ? { run: q.j.run } : {},
2122
+ ...q.j.session ? { session: q.j.session } : {},
2123
+ cards: shown.map((c) => {
2124
+ const position = c.state === "queued" ? queued.indexOf(c) + 1 : void 0;
2125
+ const held = c.state === "queued" ? c.frames.find((f) => hooks.held?.(f)) : void 0;
2126
+ const waiting = held ? `waiting - ${held} is held by your agent` : c.state === "queued" && (c.exclusive || !c.frames.length) && exclusiveAhead === "waiting" ? "waiting - runs alone once the other work is done" : c.state === "queued" && exclusiveAhead ? "waiting - a job changing a shared file runs first" : void 0;
2127
+ return {
2128
+ id: c.id,
2129
+ kind: c.kind,
2130
+ board: c.board,
2131
+ ...c.thread ? { thread: c.thread } : {},
2132
+ frames: c.frames,
2133
+ events: c.events,
2134
+ state: c.state,
2135
+ ...c.note ? { note: c.note } : {},
2136
+ rev: c.rev,
2137
+ made: c.made,
2138
+ order: c.order,
2139
+ at: c.at,
2140
+ ...c.follows ? { follows: c.follows } : {},
2141
+ ...c.reply ? { reply: c.reply } : {},
2142
+ ...c.batch ? { batch: c.batch } : {},
2143
+ ...position ? { position } : {},
2144
+ ...waiting ? { waiting } : {},
2145
+ ...c.exclusive ? { exclusive: true } : {},
2146
+ ...c.kind !== "comment" ? captureView(c) : {}
2147
+ };
2148
+ })
2149
+ };
2150
+ };
2151
+ return {
2152
+ tick,
2153
+ stop() {
2154
+ stopped = true;
2155
+ jamReservations.settling = false;
2156
+ if (recheck) clearTimeout(recheck);
2157
+ for (const t of timers) clearTimeout(t);
2158
+ timers.clear();
2159
+ for (const wake of naps) wake();
2160
+ naps.clear();
2161
+ for (const c of activeChildren) fenceGroup(c.pid);
2162
+ },
2163
+ snapshot() {
2164
+ return q.j;
2165
+ },
2166
+ view,
2167
+ sealed: (id) => sourceIntact(id),
2168
+ async session(op) {
2169
+ if (!SESSION_ID.test(op.id)) return {
2170
+ ok: false,
2171
+ error: "bad session id"
2172
+ };
2173
+ if (op.action === "start") {
2174
+ const r = await q.lock((j) => {
2175
+ const ses = startSession(j, op.id);
2176
+ q.persist();
2177
+ return ses;
2178
+ });
2179
+ queueChanged();
2180
+ return {
2181
+ ok: r.id === op.id,
2182
+ session: r,
2183
+ ...r.id === op.id ? {} : { error: "a session already runs" }
2184
+ };
2185
+ }
2186
+ if (op.action === "end") {
2187
+ const ended = await q.lock((j) => {
2188
+ const ok = endSession(j, op.id);
2189
+ q.persist();
2190
+ return ok;
2191
+ });
2192
+ queueChanged();
2193
+ return {
2194
+ ok: ended,
2195
+ session: null,
2196
+ ...ended ? {} : { error: "no such session runs" }
2197
+ };
2198
+ }
2199
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(op.board)) return {
2200
+ ok: false,
2201
+ error: "bad board"
2202
+ };
2203
+ const r = await q.lock((j, ctx) => {
2204
+ if (j.session?.id !== op.id) return { error: "no such session runs" };
2205
+ if (openFor(op.id)) return { error: "a capture of the session is still recording or being sent - end it first, then write the record" };
2206
+ const w = buildWrapup(j, root, {
2207
+ session: op.id,
2208
+ since: j.session.since,
2209
+ instructions: op.instructions,
2210
+ includeTalk: op.includeTalk,
2211
+ tags: tagsSince(j, j.session.since),
2212
+ title: (c) => captureView(c).title ?? c.id,
2213
+ reply: (c) => resultFor(j, c),
2214
+ intact: (c) => captureIntact(j, ctx, c.id),
2215
+ more: (c) => moreAsks(j, ctx, c)
2216
+ });
2217
+ if ("error" in w) return { error: w.error };
2218
+ const unsafe = recordPathProblem(root, w.file);
2219
+ if (unsafe) return { error: `the record's file is not safe to write: ${unsafe}` };
2220
+ const hash = storeWrapup(root, w);
2221
+ record(root, op.board, `wrapup:${w.id}:${hash}`);
2222
+ const card = addWrapup(j, w, hash, op.board);
2223
+ endSession(j, op.id);
2224
+ q.persist();
2225
+ return { card: structuredClone(card) };
2226
+ });
2227
+ if ("error" in r) return {
2228
+ ok: false,
2229
+ error: r.error
2230
+ };
2231
+ reserve();
2232
+ queueChanged();
2233
+ pump();
2234
+ return {
2235
+ ok: true,
2236
+ session: null,
2237
+ card: r.card
2238
+ };
2239
+ },
2240
+ captureOpen(capture, session, on) {
2241
+ if (!CAPTURE_ID.test(capture) || !SESSION_ID.test(session)) return "ok";
2242
+ if (!on) {
2243
+ openCaps.delete(capture);
2244
+ return "ok";
2245
+ }
2246
+ const landed = q.j.cards.find((c) => c.id === capture);
2247
+ if (landed) return landed.kind === "capture" && landed.session !== session ? "ended" : "ok";
2248
+ if (q.j.session?.id !== session && !openCaps.has(capture)) return "ended";
2249
+ openCaps.set(capture, {
2250
+ session,
2251
+ until: Date.now() + 6e4
2252
+ });
2253
+ return "ok";
2254
+ },
2255
+ tags(id) {
2256
+ const ses = q.j.session;
2257
+ return ses && ses.id === id ? tagsSince(q.j, ses.since) : 0;
2258
+ },
2259
+ canWrap(id) {
2260
+ const j = q.j, ctx = ctxFor(root);
2261
+ if (j.session?.id !== id) return "no such session runs";
2262
+ if (openFor(id)) return "a capture of the session is still recording or being sent - end it first, then write the record";
2263
+ for (const c of j.cards) {
2264
+ if (c.kind !== "capture" || c.session !== id || [
2265
+ "draft",
2266
+ "dropped",
2267
+ "confirming"
2268
+ ].includes(c.state)) continue;
2269
+ if (!captureIntact(j, ctx, c.id)) return "a capture of the session changed after it was confirmed - capture it again, then write the record";
2270
+ }
2271
+ const unsafe = recordPathProblem(root, recordFile(root, j.session.since, id));
2272
+ return unsafe ? `the record's file is not safe to write: ${unsafe}` : null;
2273
+ },
2274
+ record(id) {
2275
+ const c = q.j.cards.find((x) => x.id === id && x.kind === "wrapup");
2276
+ const w = c && readWrapup(root, wrapupOf(c));
2277
+ if (!c || !w) return null;
2278
+ const file = w.wrapup.file;
2279
+ let text = null;
2280
+ try {
2281
+ if (!recordPathProblem(root, file)) text = readFileSync(join(root, file), "utf8").slice(0, 5e5);
2282
+ } catch {
2283
+ text = null;
2284
+ }
2285
+ const reply = resultFor(q.j, c);
2286
+ return {
2287
+ file,
2288
+ text,
2289
+ ...reply ? { reply } : {}
2290
+ };
2291
+ },
2292
+ async capture(raw) {
2293
+ const rec = checkRecord(raw);
2294
+ if (typeof rec === "string") return {
2295
+ ok: false,
2296
+ error: rec
2297
+ };
2298
+ const ses = rec.context.session;
2299
+ if (ses) landing.set(rec.id, {
2300
+ session: ses,
2301
+ n: (landing.get(rec.id)?.n ?? 0) + 1
2302
+ });
2303
+ try {
2304
+ const r = await landCapture(rec);
2305
+ if (r.ok) nameCapture(rec.id);
2306
+ const c = r.ok ? q.j.cards.find((x) => x.id === rec.id) : void 0;
2307
+ return ses && c && c.session !== ses ? {
2308
+ ...r,
2309
+ outside: true
2310
+ } : r;
2311
+ } finally {
2312
+ openCaps.delete(rec.id);
2313
+ const l = landing.get(rec.id);
2314
+ if (l) {
2315
+ if (l.n <= 1) landing.delete(rec.id);
2316
+ else l.n -= 1;
2317
+ }
2318
+ }
2319
+ },
2320
+ async act(id, rev, action, body) {
2321
+ const c = q.j.cards.find((x) => x.id === id);
2322
+ if (c?.kind === "capture" && (action === "confirm" || action === "keep" && (c.state === "draft" || c.state === "confirming"))) return confirm(id, rev, action === "confirm" ? "queued" : "kept");
2323
+ if (action === "good" && c && c.kind !== "comment") return good(id, rev);
2324
+ if (action === "more" && c && c.kind !== "comment") return moreWork(id, rev, body ?? "");
2325
+ const saved = await q.lock((j) => {
2326
+ const c = j.cards.find((x) => x.id === id);
2327
+ const b = c && action === "retry" && c.state === "failed" && c.rev === rev ? j.batches.find((x) => x.batchId === c.batch && x.state === "claimed" && x.results && x.undelivered) : void 0;
2328
+ const r = b?.results?.[b.members.find((m) => m.card === id)?.id ?? ""];
2329
+ if (!b || !r || !("body" in r)) return null;
2330
+ redelivering(j, b);
2331
+ q.persist();
2332
+ return {
2333
+ b,
2334
+ card: structuredClone(c)
2335
+ };
2336
+ });
2337
+ if (saved) {
2338
+ redeliver(saved.b, 1, 0);
2339
+ queueChanged();
2340
+ return {
2341
+ ok: true,
2342
+ card: saved.card
2343
+ };
2344
+ }
2345
+ const r = await q.lock((j) => {
2346
+ const out = act(j, id, rev, action, Date.now(), body);
2347
+ if (out.ok) q.persist();
2348
+ return {
2349
+ ...out,
2350
+ ...out.card ? { card: structuredClone(out.card) } : {}
2351
+ };
2352
+ });
2353
+ if (r.ok) {
2354
+ reserve();
2355
+ queueChanged();
2356
+ pump();
2357
+ }
2358
+ return r;
2359
+ },
2360
+ async poke() {
2361
+ const sig = () => q.j.cards.map((c) => `${c.id}:${c.rev}`).join();
2362
+ const before = sig();
2363
+ await q.lock(() => {});
2364
+ if (sig() !== before) {
2365
+ queueChanged();
2366
+ pump();
2367
+ }
2368
+ }
2369
+ };
2370
+ }
2371
+ /** Start the daemon inside the dev server. Presence goes through the process-wide shared
2372
+ * activity set (work.ts) - the `marver work` CLI writes the same set, so the canvas shows
2373
+ * one merged glow, and its holds are also reservations (reserve.ts), restored here before
2374
+ * anything is scheduled. Returns null when the adapter is unavailable or another dev server
2375
+ * already holds the repo lock (that one runs the loop; this one watches without it). */
2376
+ function startJam(root, cfg, log = () => {}, onChanged = () => {}, anchor, onQueue, shoot) {
2377
+ const adapter = adapters[cfg.agent] ?? null;
2378
+ if (!adapter) {
2379
+ log(` jam: the "${cfg.agent}" adapter is not available yet; Live Jam is off`);
2380
+ return null;
2381
+ }
2382
+ if (!acquireLock(root)) {
2383
+ log(" jam: another marver dev holds the repo lock; this server watches without the daemon");
2384
+ return null;
2385
+ }
2386
+ const commentsDir = join(root, "design", "comments");
2387
+ mkdirSync(commentsDir, { recursive: true });
2388
+ const activity = workActivity;
2389
+ restoreHolds(root, activity);
2390
+ const core = createJam(root, cfg, adapter, log, {
2391
+ work: (f, on) => on ? activity.mark(f ?? "", void 0, "jam") : activity.clear(f ?? "", "jam"),
2392
+ changed: onChanged,
2393
+ held: (f) => activity.has(f, "cli"),
2394
+ anyHold: () => activity.leases("cli").length > 0,
2395
+ watchHolds: (fn) => activity.onChange(() => {
2396
+ if (activity.leases("cli").length > 0) fn();
2397
+ }),
2398
+ queue: onQueue,
2399
+ anchor,
2400
+ shoot
2401
+ });
2402
+ let stopped = false;
2403
+ let scheduled = null;
2404
+ const schedule = () => {
2405
+ if (!scheduled && !stopped) scheduled = setTimeout(() => {
2406
+ scheduled = null;
2407
+ core.poke();
2408
+ }, 150);
2409
+ };
2410
+ let watcher = null;
2411
+ try {
2412
+ watcher = watch(commentsDir, { persistent: false }, schedule);
2413
+ } catch {}
2414
+ const interval = setInterval(() => void core.poke(), RESCAN_MS);
2415
+ interval.unref?.();
2416
+ core.tick();
2417
+ jamLive.poke = () => void core.poke();
2418
+ jamLive.view = () => core.view();
2419
+ jamLive.act = (id, rev, action, body) => core.act(id, rev, action, body);
2420
+ jamLive.capture = (record) => core.capture(record);
2421
+ jamLive.sealed = (id) => core.sealed(id);
2422
+ jamLive.session = (op) => core.session(op);
2423
+ jamLive.record = (id) => core.record(id);
2424
+ jamLive.canWrap = (id) => core.canWrap(id);
2425
+ jamLive.captureOpen = (c, ses, on) => core.captureOpen(c, ses, on);
2426
+ jamLive.tags = (id) => core.tags(id);
2427
+ log(` jam: on (${adapter.name}) - tag @marver in a comment and it does the work; \`jam: false\` in design/config.ts turns it off`);
2428
+ return { stop() {
2429
+ stopped = true;
2430
+ if (scheduled) clearTimeout(scheduled);
2431
+ clearInterval(interval);
2432
+ watcher?.close();
2433
+ core.stop();
2434
+ delete jamLive.poke;
2435
+ delete jamLive.view;
2436
+ delete jamLive.act;
2437
+ delete jamLive.capture;
2438
+ jamReservations.frames.clear();
2439
+ jamReservations.exclusive = null;
2440
+ jamReservations.settling = false;
2441
+ releaseLock(root);
2442
+ } };
2443
+ }
2444
+ //#endregion
2445
+ export { startJam };