@marver-design/marver 0.27.2 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/CHANGELOG.md +160 -0
  2. package/README.md +6 -4
  3. package/dist/{anchor-check-gkxkPAIv.mjs → anchor-check-DhlpKl2K.mjs} +1 -1
  4. package/dist/{audio-Dw1lfMdb.mjs → audio-DX4POHAj.mjs} +39 -4
  5. package/dist/{boards-BqUqKNW8.mjs → boards-BeWtjGUM.mjs} +49 -4
  6. package/dist/boards-EH2onUXM.mjs +995 -0
  7. package/dist/{build-VgNg4rr8.mjs → build-CWbrb2bl.mjs} +9 -5
  8. package/dist/{capture-vadKjuCo.mjs → capture-DEtM4qm5.mjs} +259 -34
  9. package/dist/cli.mjs +40 -19
  10. package/dist/{comments-YEU1Zhv9.mjs → comments-XNhMmSSu.mjs} +4 -4
  11. package/dist/config-BezZTiov.mjs +182 -0
  12. package/dist/conn-BMiHS42T.mjs +222 -0
  13. package/dist/connectors-DekQvKt9.mjs +292 -0
  14. package/dist/{context-Ccjrhr1J.mjs → context-BUnFiyA3.mjs} +2 -2
  15. package/dist/{daemon-Dc9AH0M3.mjs → daemon-Sc_z8gT6.mjs} +2209 -205
  16. package/dist/{dev-ri6nAlRp.mjs → dev-DWBKQhxf.mjs} +31 -15
  17. package/dist/{init-W0nxR1OY.mjs → init-CYlFaRzG.mjs} +7 -2
  18. package/dist/jam-Cj5gBvwD.mjs +373 -0
  19. package/dist/{link-CdTgn94Y.mjs → link-BFFRgrMt.mjs} +3 -3
  20. package/dist/listener-DdLEM79A.mjs +80 -0
  21. package/dist/logo-CXY-1yrn.mjs +305 -0
  22. package/dist/{ls-BZ5TAtd5.mjs → ls-NqmePKOf.mjs} +1 -1
  23. package/dist/{manifest-aFyDmL8C.mjs → manifest-DPZ3WNg_.mjs} +1 -1
  24. package/dist/{marks-CnCCfAbD.mjs → marks-BnNANic9.mjs} +22 -3
  25. package/dist/{marks-BF9pNEgH.mjs → marks-DBp3h1Mc.mjs} +3 -6
  26. package/dist/{marver-id-gate-D-R0hSt_.mjs → marver-id-gate-vBLb_Icb.mjs} +1 -1
  27. package/dist/{perf-DkAUFT6W.mjs → perf-Denssrko.mjs} +45 -27
  28. package/dist/{perf-jam-BaH3Lg0m.mjs → perf-jam-CLkERSHo.mjs} +9 -2
  29. package/dist/permit-DDa6wqOs.mjs +187 -0
  30. package/dist/{plugin-B8UghYuF.mjs → plugin-DqoZB-D6.mjs} +849 -789
  31. package/dist/{poster-BNgafWMK.mjs → poster-CrsjqhY4.mjs} +1 -1
  32. package/dist/{profile-jIS6BcAs.mjs → profile-B1FKOM1e.mjs} +1 -1
  33. package/dist/{publish-bakes-38Nja78p.mjs → publish-bakes-DW-NDgU2.mjs} +3 -3
  34. package/dist/{queue-CAM_vNmX.mjs → queue-DeSQm24g.mjs} +189 -35
  35. package/dist/{recover-B8AiI29B.mjs → recover-GtJ9UDAB.mjs} +2 -2
  36. package/dist/{serve-Dp3nHstu.mjs → serve-DQv3Ti6X.mjs} +8 -4
  37. package/dist/{session-BAaJsK5c.mjs → session-VDJfXEEm.mjs} +1 -1
  38. package/dist/{share-Ce4tP7ji.mjs → share-Bu_kuOKL.mjs} +1 -1
  39. package/dist/{shot-CMQgMVZm.mjs → shot-DBWN8hPP.mjs} +1 -1
  40. package/dist/{shot-Ch24tiMO.mjs → shot-T04Ixrvq.mjs} +7 -6
  41. package/dist/sizes-wjXDev3b.mjs +139 -0
  42. package/dist/{slots-CFNnegCc.mjs → slots-Dn4Onb0V.mjs} +101 -3
  43. package/dist/speech-worker.mjs +23 -3
  44. package/dist/{sync-CQdGARJ9.mjs → sync-CMozOwZ0.mjs} +1 -1
  45. package/dist/transport-C5FnY9ni.mjs +203 -0
  46. package/dist/{work-Bxz-ObF3.mjs → work-BYWD_1Zf.mjs} +3 -3
  47. package/dist/{work-CNhFF9pU.mjs → work-DJxH7cCX.mjs} +1 -1
  48. package/docs/boards-and-folders.md +11 -0
  49. package/docs/jam-session.md +52 -18
  50. package/docs/live-jam.md +95 -10
  51. package/docs/performance.md +1 -1
  52. package/docs/publish.md +7 -0
  53. package/package.json +1 -1
  54. package/src/client/shell/Comments.tsx +5 -4
  55. package/src/client/shell/ContextMenu.tsx +5 -4
  56. package/src/client/shell/JamSurface.tsx +135 -29
  57. package/src/client/shell/Play.tsx +16 -4
  58. package/src/client/shell/api.ts +7 -3
  59. package/src/client/shell/app-bridge.ts +11 -3
  60. package/src/client/shell/comments-store.ts +14 -0
  61. package/src/client/shell/goto.ts +4 -3
  62. package/src/client/shell/icons.tsx +1 -0
  63. package/src/client/shell/jam-capture.ts +136 -37
  64. package/src/client/shell/jam-keys.ts +170 -18
  65. package/src/client/shell/jam-lane.tsx +14 -5
  66. package/src/client/shell/jam-lines.ts +76 -10
  67. package/src/client/shell/jam-panel.tsx +58 -4
  68. package/src/client/shell/jam-queue.ts +55 -8
  69. package/src/client/shell/jam-session.tsx +55 -6
  70. package/src/client/shell/jam-state.ts +19 -4
  71. package/src/client/shell/jam-surface-parts.tsx +6 -3
  72. package/src/client/shell/jam-ui.tsx +10 -1
  73. package/src/client/shell/jam-voice-wait.ts +21 -0
  74. package/src/client/shell/jam-voice.ts +14 -5
  75. package/src/client/shell/live-picture.ts +134 -0
  76. package/src/client/shell/open-item.ts +83 -0
  77. package/src/client/shell/open-resolve.ts +50 -0
  78. package/src/client/shell/store.ts +6 -2
  79. package/src/client/shell/styles.css +29 -11
  80. package/src/client/shell/tidy.ts +3 -2
  81. package/src/client/stage/main.tsx +30 -8
  82. package/src/shared/app-api.ts +173 -3
  83. package/src/shared/app-perf.ts +4 -2
  84. package/src/shared/approval.ts +20 -0
  85. package/src/shared/events.ts +1 -1
  86. package/templates/AGENTS-embedded.md +28 -1
  87. package/templates/AGENTS-studio.md +28 -1
  88. package/templates/instructions/boards.md +7 -1
  89. package/templates/instructions/jam.md +94 -0
  90. package/dist/boards-BHKP5yhI.mjs +0 -342
  91. package/dist/live-Cgzsicwi.mjs +0 -4
@@ -1,21 +1,27 @@
1
- import { l as toFrameId } from "./manifest-aFyDmL8C.mjs";
2
- import { a as workActivity } from "./work-CNhFF9pU.mjs";
1
+ import { l as toFrameId } from "./manifest-DPZ3WNg_.mjs";
2
+ import { a as workActivity } from "./work-DJxH7cCX.mjs";
3
3
  import { r as replay } from "./events-CLH4ijKP.mjs";
4
4
  import { a as readLog, t as appendEvents } from "./comments-0BSbb04K.mjs";
5
- import { n as localProfile } from "./profile-jIS6BcAs.mjs";
5
+ import { n as localProfile } from "./profile-B1FKOM1e.mjs";
6
+ import { i as onPath, t as AGENT_BIN } from "./agent-BsieQGTD.mjs";
6
7
  import { r as uncheckedAnchor } from "./anchor-5H1vnoLu.mjs";
8
+ import { S as writeOffers, _ as readPrefs, f as patchConn, g as readOffers, h as readConn, l as listConns, m as pingLine, n as closeConn, o as eligible, p as pidAlive, r as connDir, t as alive } from "./conn-BMiHS42T.mjs";
9
+ import { hookBin } from "./connectors-DekQvKt9.mjs";
10
+ import { answer, reqDir, sweep, takeRequests, verify } from "./transport-C5FnY9ni.mjs";
7
11
  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-vadKjuCo.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-BAaJsK5c.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-CAM_vNmX.mjs";
11
- import { t as logJam } from "./perf-jam-BaH3Lg0m.mjs";
12
+ import { C as refusedAsk, S as parseMembers, T as sharedWhy, _ as wordsUntil, a as checkRecord, b as packetPath, c as firstPoint, d as packetPictures, f as picturePath, g as wordsSince, h as storeCapture, m as requestWords, n as captureFrames, o as continues, p as readCapture, r as captureWords, t as CAPTURE_ID, u as madeOf, v as buildPacket, w as sanitize, x as parseAgentText, y as goalText } from "./capture-DEtM4qm5.mjs";
13
+ 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-VDJfXEEm.mjs";
14
+ import { act, addCapture, addWrapup, answeredSince, beginStep, captureComment, captureIntact, conflictStep, createQueue, ctxFor, endSession, endStep, fail, failCard, form, joinAlone, looksGood, moreWrapup, n as releaseLock, ownerOnly, payloadKey, pending, prune, redelivering, requeue, runsAlone, sameComment, settle, startSession, stillOwned, t as acquireLock, textOf, undelivered, wrapupIntact, wrapupOf } from "./queue-DeSQm24g.mjs";
15
+ import { t as logJam } from "./perf-jam-CLkERSHo.mjs";
16
+ import { i as jamLive } from "./plugin-DqoZB-D6.mjs";
17
+ import { t as PROTECTED_GLOBS } from "./permit-DDa6wqOs.mjs";
12
18
  import { jamReservations, restoreHolds } from "./reserve-BURNQ2Y3.mjs";
13
- import { jamLive } from "./live-Cgzsicwi.mjs";
14
- import { lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
19
+ import { closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
15
20
  import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
21
+ import { fileURLToPath } from "node:url";
16
22
  import { createHash } from "node:crypto";
17
- import { tmpdir } from "node:os";
18
- import { spawn } from "node:child_process";
23
+ import { homedir, tmpdir } from "node:os";
24
+ import { execFileSync, spawn } from "node:child_process";
19
25
  import { StringDecoder } from "node:string_decoder";
20
26
  //#region src/server/jam/adapter/claude.ts
21
27
  /**
@@ -26,12 +32,26 @@ import { StringDecoder } from "node:string_decoder";
26
32
  */
27
33
  /** First key of an object, or undefined. */
28
34
  const firstKey = (o) => o && typeof o === "object" ? Object.keys(o)[0] : void 0;
35
+ /** Can Claude Code's sandbox run here? macOS has it built in; Linux needs bubblewrap and socat. (It may still fail
36
+ * to start: `failIfUnavailable` makes that a failed command, never an open one.) */
37
+ const sandboxReady = (platform = process.platform, env = process.env) => platform === "darwin" || platform === "linux" && onPath("bwrap", env) && onPath("socat", env);
38
+ /** What no Jam run reads, whoever asks: keys and credentials. */
39
+ const SECRETS = [
40
+ "~/.ssh/**",
41
+ "~/.aws/**",
42
+ "~/.gnupg/**",
43
+ "~/.config/gcloud/**",
44
+ "~/.netrc",
45
+ "~/.npmrc",
46
+ "~/Library/Keychains/**"
47
+ ];
29
48
  const cleanModel$1 = (raw) => typeof raw === "string" ? raw.replace(/\[[^\]]*\]$/, "") || void 0 : void 0;
30
49
  const claudeAdapter = {
31
50
  name: "claude",
32
51
  supportsSubagents: true,
33
- spawnArgs(goal) {
34
- return {
52
+ forks: true,
53
+ spawnArgs(goal, o) {
54
+ if (!o) return {
35
55
  cmd: "claude",
36
56
  args: [
37
57
  "-p",
@@ -47,6 +67,61 @@ const claudeAdapter = {
47
67
  "--verbose"
48
68
  ]
49
69
  };
70
+ const sandboxed = o.sandbox ?? sandboxReady();
71
+ const root = o.root.replace(/\/+$/, "");
72
+ const settings = {
73
+ sandbox: sandboxed ? {
74
+ enabled: true,
75
+ autoAllowBashIfSandboxed: true,
76
+ allowUnsandboxedCommands: false,
77
+ failIfUnavailable: true,
78
+ excludedCommands: []
79
+ } : { enabled: false },
80
+ permissions: { deny: [
81
+ ...SECRETS.map((p) => `Read(${p})`),
82
+ ...PROTECTED_GLOBS.map((g) => `Edit(/${root}/${g})`),
83
+ ...o.skills ? [] : ["Skill"],
84
+ ...sandboxed ? [] : ["Bash"]
85
+ ] }
86
+ };
87
+ const permit = { mcpServers: { "marver-jam": {
88
+ command: o.marver?.cmd ?? "npx",
89
+ args: [
90
+ ...o.marver?.args ?? ["marver"],
91
+ "jam",
92
+ "permit"
93
+ ],
94
+ env: { MARVER_JAM_PERMIT: JSON.stringify({
95
+ root: o.root,
96
+ mcp: o.mcp,
97
+ skills: o.skills
98
+ }) }
99
+ } } };
100
+ return {
101
+ cmd: "claude",
102
+ args: [
103
+ "-p",
104
+ goal,
105
+ "--permission-mode",
106
+ "acceptEdits",
107
+ "--settings",
108
+ JSON.stringify(settings),
109
+ "--mcp-config",
110
+ JSON.stringify(permit),
111
+ ...o.mcp ? [] : ["--strict-mcp-config"],
112
+ ...o.skills ? [] : ["--disable-slash-commands"],
113
+ "--permission-prompt-tool",
114
+ "mcp__marver-jam__decide",
115
+ ...o.fork ? [
116
+ "--resume",
117
+ o.fork,
118
+ "--fork-session"
119
+ ] : [],
120
+ "--output-format",
121
+ "stream-json",
122
+ "--verbose"
123
+ ]
124
+ };
50
125
  },
51
126
  namerArgs(prompt) {
52
127
  return {
@@ -127,11 +202,36 @@ const claudeAdapter = {
127
202
  * so a multi-frame job fans out the same way Claude Code's does. The job prompt only ever says
128
203
  * "you MAY", so an older codex without those tools simply works serially instead of failing.
129
204
  */
205
+ /** The MCP servers Codex would start for a run in `cwd` (`codex mcp list --json`: your config, the project's,
206
+ * plugins'), or null when it cannot say - then a run with MCP off leaves your config out entirely. */
207
+ function codexMcpServers(cwd, env = process.env) {
208
+ try {
209
+ const out = execFileSync("codex", [
210
+ "mcp",
211
+ "list",
212
+ "--json"
213
+ ], {
214
+ cwd,
215
+ encoding: "utf8",
216
+ timeout: 15e3,
217
+ stdio: [
218
+ "ignore",
219
+ "pipe",
220
+ "ignore"
221
+ ],
222
+ env
223
+ });
224
+ const list = JSON.parse(out);
225
+ if (Array.isArray(list)) return [...new Set(list.map((x) => x?.name).filter((n) => typeof n === "string" && /^[A-Za-z0-9_-]+$/.test(n)))];
226
+ } catch {}
227
+ return null;
228
+ }
130
229
  const codexAdapter = {
131
230
  name: "codex",
132
231
  supportsSubagents: true,
133
- spawnArgs(goal) {
134
- return {
232
+ forks: true,
233
+ spawnArgs(goal, o) {
234
+ if (!o) return {
135
235
  cmd: "codex",
136
236
  args: [
137
237
  "exec",
@@ -142,6 +242,40 @@ const codexAdapter = {
142
242
  goal
143
243
  ]
144
244
  };
245
+ const review = [
246
+ "-c",
247
+ "approvals_reviewer=\"auto_review\"",
248
+ "-c",
249
+ "approval_policy=\"on-request\"",
250
+ "-c",
251
+ "sandbox_mode=\"workspace-write\""
252
+ ];
253
+ const listed = o.mcp ? [] : codexMcpServers(o.root);
254
+ if (!listed) throw new Error("MCP servers are off for Jam runs, and Codex could not list them to turn them off - run `codex mcp list` here, or turn MCP back on in the start sheet");
255
+ const mcpOff = listed.flatMap((n) => ["-c", `mcp_servers.${n}.enabled=false`]);
256
+ return o.fork ? {
257
+ cmd: "codex",
258
+ args: [
259
+ "exec",
260
+ "fork",
261
+ o.fork,
262
+ "--json",
263
+ "--skip-git-repo-check",
264
+ ...review,
265
+ ...mcpOff,
266
+ goal
267
+ ]
268
+ } : {
269
+ cmd: "codex",
270
+ args: [
271
+ "exec",
272
+ "--json",
273
+ "--skip-git-repo-check",
274
+ ...review,
275
+ ...mcpOff,
276
+ goal
277
+ ]
278
+ };
145
279
  },
146
280
  earlyText(line) {
147
281
  try {
@@ -201,7 +335,7 @@ const assistantText$2 = (o) => {
201
335
  const cursorAdapter = {
202
336
  name: "cursor",
203
337
  supportsSubagents: false,
204
- spawnArgs(goal) {
338
+ spawnArgs(goal, o) {
205
339
  return {
206
340
  cmd: "cursor-agent",
207
341
  args: [
@@ -211,7 +345,8 @@ const cursorAdapter = {
211
345
  "stream-json",
212
346
  "--sandbox",
213
347
  "enabled",
214
- "--trust"
348
+ "--trust",
349
+ ...o?.mcp ? ["--approve-mcps"] : []
215
350
  ]
216
351
  };
217
352
  },
@@ -522,83 +657,1445 @@ const assistantText = (m) => {
522
657
  model: typeof msg.model === "string" && msg.model ? msg.model : void 0,
523
658
  error: Boolean(msg.errorMessage) || msg.stopReason === "error"
524
659
  };
525
- };
526
- //#endregion
527
- //#region src/server/jam/adapter/index.ts
528
- const adapters = {
529
- claude: claudeAdapter,
530
- codex: codexAdapter,
531
- cursor: cursorAdapter,
532
- droid: droidAdapter,
533
- opencode: opencodeAdapter,
534
- grok: grokAdapter,
535
- pi: {
536
- name: "pi",
537
- supportsSubagents: false,
538
- spawnArgs(goal) {
539
- return {
540
- cmd: "pi",
541
- args: [
542
- "-p",
543
- "--mode",
544
- "json",
545
- "--no-extensions",
546
- "--no-skills",
547
- "--tools",
548
- "read,edit,write,grep,find,ls",
549
- goal
550
- ]
551
- };
660
+ };
661
+ //#endregion
662
+ //#region src/server/jam/adapter/index.ts
663
+ const adapters = {
664
+ claude: claudeAdapter,
665
+ codex: codexAdapter,
666
+ cursor: cursorAdapter,
667
+ droid: droidAdapter,
668
+ opencode: opencodeAdapter,
669
+ grok: grokAdapter,
670
+ pi: {
671
+ name: "pi",
672
+ supportsSubagents: false,
673
+ spawnArgs(goal) {
674
+ return {
675
+ cmd: "pi",
676
+ args: [
677
+ "-p",
678
+ "--mode",
679
+ "json",
680
+ "--no-extensions",
681
+ "--no-skills",
682
+ "--tools",
683
+ "read,edit,write,grep,find,ls",
684
+ goal
685
+ ]
686
+ };
687
+ },
688
+ earlyText(line) {
689
+ try {
690
+ const o = JSON.parse(line);
691
+ if (o.type !== "message_end") return null;
692
+ const a = assistantText(o.message);
693
+ return a?.text && !a.error ? {
694
+ text: a.text,
695
+ model: a.model
696
+ } : null;
697
+ } catch {
698
+ return null;
699
+ }
700
+ },
701
+ parse(stdout, code) {
702
+ let last = null;
703
+ let fromEnd = false;
704
+ let failed = false;
705
+ for (const line of stdout.split("\n")) {
706
+ const t = line.trim();
707
+ if (!t) continue;
708
+ try {
709
+ const o = JSON.parse(t);
710
+ if (o.type === "agent_end" && Array.isArray(o.messages)) for (let i = o.messages.length - 1; i >= 0; i--) {
711
+ const a = assistantText(o.messages[i]);
712
+ if (a) {
713
+ last = a;
714
+ fromEnd = true;
715
+ break;
716
+ }
717
+ }
718
+ else if (o.type === "message_end" && !fromEnd) {
719
+ const a = assistantText(o.message);
720
+ if (a) last = a;
721
+ } else if (o.type === "error") failed = true;
722
+ } catch {}
723
+ }
724
+ if (last?.error) failed = true;
725
+ const { reply, asks, reanchors, said } = parseAgentText(last?.text ?? "");
726
+ return {
727
+ reply,
728
+ model: last?.model,
729
+ asks,
730
+ reanchors,
731
+ said,
732
+ ok: code === 0 && !failed && !!reply
733
+ };
734
+ }
735
+ }
736
+ };
737
+ //#endregion
738
+ //#region src/server/jam/session-brief.ts
739
+ /**
740
+ * What `marver jam next` prints for a session that takes a run (spec 29b): the request in the owner's own words,
741
+ * the frames it may edit, and how to hand it back - a dozen lines, not the spawned agent's whole prompt. The session
742
+ * already knows the contract (design/AGENTS.md, which its CLAUDE.md or AGENTS.md brings in); the full rules -
743
+ * captures, re-pins, shared files - stay in design/instructions/jam.md for when a run needs them.
744
+ */
745
+ const clip = (s, n) => {
746
+ const t = sanitize(s, 4096).replace(/^\s*@marver\b\s*/i, "").replace(/\s+/g, " ").trim();
747
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
748
+ };
749
+ /** The owner's words for a run, newest first, each with its kind - never what became of them (whether an earlier run
750
+ * did them is in the packet). Oldest to newest they come in the order they were said: the capture, its read-back
751
+ * notes, then tags and More-work notes in their order. A capture resumed after its read-back (⇧E, a note, Resume) is
752
+ * two parts - what was said before the pause, the notes written in it, then what was said after - so a correction
753
+ * spoken after the resume leads; edited, its edit stands for both parts, after those notes. A note is before the
754
+ * resume when its time is before the resumed capture's id (both the page's wall clock; the record's steps run on
755
+ * another, so they are split by `resumes.at` alone). */
756
+ const wordsOf = (m) => {
757
+ const c = m.brief.capture;
758
+ const rs = c?.record.context?.resumes;
759
+ const from = c && rs ? madeOf(c.record.id) : 0;
760
+ const notes = (c?.added ?? []).map((a) => ({
761
+ kind: "a read-back note",
762
+ text: a.text,
763
+ at: a.at
764
+ }));
765
+ const before = (t) => notes.filter((n) => n.at <= t), after = (t) => notes.filter((n) => n.at > t);
766
+ const said = !c ? [] : c.edited !== void 0 && c.editedAt ? [
767
+ ...before(c.editedAt),
768
+ {
769
+ kind: "the capture (your edit)",
770
+ text: captureWords(c.record, c.edited)
771
+ },
772
+ ...after(c.editedAt)
773
+ ] : rs && c.edited === void 0 ? [
774
+ {
775
+ kind: "the capture",
776
+ text: wordsUntil(c.record, rs.at)
777
+ },
778
+ ...before(from - 1),
779
+ {
780
+ kind: "the capture, resumed",
781
+ text: wordsSince(c.record, rs.at)
782
+ },
783
+ ...after(from - 1)
784
+ ] : [
785
+ ...before(from - 1),
786
+ {
787
+ kind: "the capture",
788
+ text: captureWords(c.record, c.edited)
789
+ },
790
+ ...after(from - 1)
791
+ ];
792
+ const asks = m.brief.asks.map((a, i) => ({
793
+ a,
794
+ i,
795
+ t: a.edited ?? a.ts ?? 0
796
+ })).sort((x, y) => x.t - y.t || x.i - y.i).map((x) => x.a);
797
+ return [...said, ...asks.map((a) => ({
798
+ kind: a.id?.startsWith("mw-") ? "a More-work note" : "a tag",
799
+ text: a.body
800
+ }))].filter((w) => clip(w.text, Infinity)).reverse();
801
+ };
802
+ function sessionBrief(packet, handle, as, o = {}) {
803
+ const jam = (op, rest = "") => `npx marver jam ${op} ${handle}${as ? ` --as ${as}` : ""}${rest}`;
804
+ const one = packet.members.length === 1;
805
+ const record = packet.members.every((m) => m.brief.wrapup);
806
+ const files = packet.members.flatMap((m) => m.brief.wrapup ? [m.brief.wrapup.content.file] : []);
807
+ const last = (m) => Math.max(0, ...m.brief.asks.map((a) => a.edited ?? a.ts ?? 0), ...(m.brief.capture?.added ?? []).map((a) => a.at), m.brief.capture?.editedAt ?? 0, m.brief.capture ? madeOf(m.brief.capture.record.id) : 0);
808
+ const asks = packet.members.map((m, i) => ({
809
+ m,
810
+ i,
811
+ t: last(m)
812
+ })).sort((a, b) => b.t - a.t || b.i - a.i).map((x) => x.m).flatMap((m) => {
813
+ const at = `${one ? "" : `${m.id} `}on ${m.frames.join(", ") || `board ${m.board}`}`;
814
+ if (m.brief.wrapup) {
815
+ const w = m.brief.wrapup.content;
816
+ return [
817
+ `- ${one ? "" : `${m.id}, `}the session record: write it to ${w.file} - that file only, no design work.`,
818
+ ...w.instructions.trim() ? [` The owner's instructions for it: "${clip(w.instructions, 1200)}"`] : [],
819
+ ...w.more?.trim() ? [` Their note on the record before (improve it by this): "${clip(w.more, 1200)}"`] : []
820
+ ];
821
+ }
822
+ const words = wordsOf(m).map((w, i) => `${w.kind}: "${clip(w.text, i ? 200 : 1200)}"`);
823
+ if (words.length < 2) return [`- ${at}, ${words[0] ?? "(no words - see the packet)"}`];
824
+ return [`- ${at}, the owner's words, newest first:`, ...words.map((w) => ` ${w}`)];
825
+ });
826
+ if (record) return [
827
+ `Live Jam run ${handle} - the owner's request from the canvas.`,
828
+ ...asks,
829
+ `The captures and talk it is written from: ${packetPath(packet.batchId)}`,
830
+ "",
831
+ "Do it in this session, then:",
832
+ `1. Write your reply to a file - ONE or TWO plain sentences on what the record says:`,
833
+ ...packet.members.map((m) => ` \`\`\`marver-reply ${m.id}\n The record ...\n \`\`\``),
834
+ `2. ${jam("done", " --file <that file>")} - the canvas posts it.`,
835
+ `A long run: ${jam("progress")} every few minutes. Cannot do it now: ${jam("release")}.`,
836
+ `Edit nothing but ${files.join(", ")}. The full rules: design/instructions/jam.md, "Runs from the canvas".`
837
+ ].join("\n");
838
+ const none = !packet.frames.length && !packet.exclusive?.files.length;
839
+ const board = packet.members[0]?.board ?? "<board>";
840
+ const what = [
841
+ ...asks,
842
+ none ? "It reserves no frame: make what it asks for as new frames, in a scene of their own if nothing on the board fits (a scene the run makes is its own, its _ files included)." : `Frames you may edit: ${packet.frames.join(", ") || "(none)"}${packet.exclusive?.files.length ? `; and these shared files: ${packet.exclusive.files.join(", ")}` : ""}.`,
843
+ `The thread, ${packet.members.some((m) => m.brief.capture) ? "the capture's picks and pictures, " : ""}and what earlier runs did: ${packetPath(packet.batchId)}`
844
+ ];
845
+ const reply = [
846
+ `Write your reply to a file, one block per request, plain text, about as long as the ask:`,
847
+ ...packet.members.map((m) => ` \`\`\`marver-reply ${m.id}\n Done - ...\n \`\`\``),
848
+ ` Need an answer from the owner first? Open the block with \`\`\`marver-reply ${packet.members[0]?.id ?? "m1"} asks instead.`
849
+ ];
850
+ const run = ` --run ${handle}${as ? ` --as ${as}` : ""}`;
851
+ const newFrame = none ? `Edit no frame that exists; each new frame goes on board ${board} with npx marver boards place ${board} <scene/frame> --after <scene/frame>${run} (on an empty board: npx marver boards pin ${board} <scene/frame>${run})` : `Edit only those frames; a new frame goes on the board with npx marver boards place <board> <scene/frame> --after <scene/frame>${run}`;
852
+ const ov = o.overlaps ?? [];
853
+ const overlapping = ov.length ? `It overlaps your run${ov.length === 1 ? "" : "s"} ${ov.map((x) => `${x.handle} ("${x.title}") on ${x.frames.join(", ")}`).join("; ")}.` : "";
854
+ if (o.agent === "claude") {
855
+ const n = (i) => `${i}.`;
856
+ return [
857
+ `Live Jam run ${handle} from the owner's canvas - dispatch it, so you are free for the next request:`,
858
+ "start ONE background subagent (Agent tool, run_in_background: true) whose prompt is everything below the line, plus what this conversation knows that matters for it.",
859
+ `Then run \`npx marver jam next\` again until nothing waits, and end your turn. Dispatch every run, however small - the next request may be on its way, and it waits while you work. Only if you cannot start a background subagent, do it here by the same steps. Cannot take it: ${jam("release")}.`,
860
+ ...overlapping ? [`${overlapping.slice(0, -1)} - a subagent of yours may be editing ${ov.length === 1 ? "it" : "them"}. Your call, for speed and quality:`, "send this run to that subagent (SendMessage: do it after, or fold it in now - it answers both handles), or run it in parallel as a variant in a NEW frame placed beside it. Never two subagents on one frame."] : [],
861
+ "----",
862
+ `You own Live Jam run ${handle} - the owner's request from their Marver canvas. Do it and hand it back yourself; never run \`jam next\` or take another run.`,
863
+ ...what,
864
+ ...one ? [`${n(1)} One line to the owner now: ${jam("say", " \"On it - ...\"")}`] : [],
865
+ `${n(one ? 2 : 1)} Do the work (design/AGENTS.md; design/instructions/jam.md, "Runs from the canvas"). ${jam("progress")} every few minutes.`,
866
+ `${n(one ? 3 : 2)} ${reply[0]}`,
867
+ ...reply.slice(1),
868
+ `${n(one ? 4 : 3)} ${jam("done", " --file <that file>")} - the canvas posts it and frees the frames.`,
869
+ `${newFrame}. A command that answers "the owner moved this run elsewhere": stop editing at once and run ${jam("release")}.`,
870
+ ...o.conn && !as ? [`A command that answers "this session is not connected": add --as ${o.conn}.`] : []
871
+ ].join("\n");
872
+ }
873
+ const tool = o.agent === "codex" ? "Codex" : o.agent === "cursor" ? "Cursor" : "";
874
+ return [
875
+ `Live Jam run ${handle} - the owner's request from the canvas.`,
876
+ ...what,
877
+ ...overlapping ? [`${overlapping} Do it after ${ov.length === 1 ? "that one" : "those"}, or together with ${ov.length === 1 ? "it" : "them"} (answer every handle).`] : [],
878
+ "",
879
+ tool ? `Do it in this session (Marver gives ${tool} runs to it one at a time), then:` : "Do it in this session, then:",
880
+ ...one ? [`1. One line to the owner now: ${jam("say", " \"On it - ...\"")}`] : [],
881
+ `${one ? "2" : "1"}. ${reply[0]}`,
882
+ ...reply.slice(1),
883
+ `${one ? "3" : "2"}. ${jam("done", " --file <that file>")} - the canvas posts it and frees the frames.`,
884
+ `A long run: ${jam("progress")} every few minutes. Cannot do it now: ${jam("release")}.`,
885
+ `${newFrame}. Captures, re-pins and shared files: design/instructions/jam.md, "Runs from the canvas".`
886
+ ].join("\n");
887
+ }
888
+ //#endregion
889
+ //#region src/shared/approval.ts
890
+ /**
891
+ * Is a More-work note only "looks good"? Then it settles the review as Looks good instead of running the work again.
892
+ * The whole note must BE one phrase of this list once lower-cased, trimmed, and its trailing punctuation and approving
893
+ * emoji dropped: one word more, another script, a digit - it goes to the agent as More work. An extra run is cheap; a
894
+ * request swallowed as approval is lost. By design the agent's reply is never read: after a reply that offered more
895
+ * ("Want me to do the footer too?") "looks good" settles it - the owner said looks good, not yes - and no answer to a
896
+ * question ("yes", "ok", "sure") is on the list.
897
+ */
898
+ const PHRASES = /* @__PURE__ */ new Set([
899
+ "looks good",
900
+ "looks great",
901
+ "looks good to me",
902
+ "lgtm",
903
+ "perfect",
904
+ "great",
905
+ "great job",
906
+ "nice",
907
+ "nice work",
908
+ "love it",
909
+ "thanks",
910
+ "thank you",
911
+ "looks good thanks",
912
+ "looks great thanks",
913
+ "looks good, thanks",
914
+ "looks great, thanks",
915
+ "approved",
916
+ "good",
917
+ "good job",
918
+ "well done",
919
+ "👍",
920
+ "👌",
921
+ "✅"
922
+ ]);
923
+ /** trailing punctuation, skin tones and variation selectors - and, in the second pass, the approving emoji too */
924
+ const TAIL = /[\s.!,;:…\u{1F3FB}-\u{1F3FF}️]+$/u;
925
+ const TAIL_EMOJI = /[\s.!,;:…\u{1F3FB}-\u{1F3FF}️👍👌✅]+$/u;
926
+ function isApproval(note) {
927
+ const t = note.toLowerCase().replace(/\s+/g, " ").trim();
928
+ return PHRASES.has(t.replace(TAIL_EMOJI, "")) || PHRASES.has(t.replace(TAIL, ""));
929
+ }
930
+ const claudeHome = (env) => env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
931
+ const codexHome = (env) => env.CODEX_HOME || join(homedir(), ".codex");
932
+ /** The same folder, links resolved (macOS's /var is /private/var; a repo opened through a link). */
933
+ const real = (p) => {
934
+ try {
935
+ return realpathSync(p);
936
+ } catch {
937
+ return p;
938
+ }
939
+ };
940
+ const sameDir = (a, b) => typeof a === "string" && (a === b || real(a) === real(b));
941
+ /** Claude Code's folder for a project: its path with every character but letters and digits made a dash. */
942
+ const claudeSlug = (root) => root.replace(/[^A-Za-z0-9]/g, "-");
943
+ /** The first `max` bytes of a file, as lines (the last, maybe cut, dropped). */
944
+ function headLines(file, max = 65536) {
945
+ let fd;
946
+ try {
947
+ fd = openSync(file, "r");
948
+ const buf = Buffer.alloc(max);
949
+ const n = readSync(fd, buf, 0, max, 0);
950
+ const lines = buf.subarray(0, n).toString("utf8").split("\n");
951
+ return n === max ? lines.slice(0, -1) : lines;
952
+ } catch {
953
+ return [];
954
+ } finally {
955
+ if (fd !== void 0) closeSync(fd);
956
+ }
957
+ }
958
+ /** A Claude Code session's transcript, when it is an interactive one of this repo. */
959
+ function claudeTranscript(root, session, env = process.env) {
960
+ if (!/^[0-9a-f-]{36}$/.test(session)) return null;
961
+ const file = join(claudeHome(env), "projects", claudeSlug(root), `${session}.jsonl`);
962
+ let bytes;
963
+ try {
964
+ bytes = statSync(file).size;
965
+ } catch {
966
+ return null;
967
+ }
968
+ return claudeInteractive(file, root) ? {
969
+ agent: "claude",
970
+ session,
971
+ bytes,
972
+ file
973
+ } : null;
974
+ }
975
+ /** Is this Claude Code transcript a person's session of this repo (entrypoint `cli`, its `cwd` the repo), not a
976
+ * headless run - Marver's own runs and copies are `sdk-cli`? */
977
+ function claudeInteractive(file, root) {
978
+ for (const l of headLines(file)) try {
979
+ const o = JSON.parse(l);
980
+ if (typeof o.entrypoint === "string") return o.entrypoint === "cli" && sameDir(o.cwd, root);
981
+ } catch {}
982
+ return false;
983
+ }
984
+ /** The newest interactive Claude Code session of this repo, on disk. */
985
+ function newestClaude(root, env = process.env) {
986
+ const dir = join(claudeHome(env), "projects", claudeSlug(real(root)));
987
+ let names;
988
+ try {
989
+ names = readdirSync(dir).filter((n) => /^[0-9a-f-]{36}\.jsonl$/.test(n));
990
+ } catch {
991
+ return null;
992
+ }
993
+ const files = names.map((n) => {
994
+ try {
995
+ const st = statSync(join(dir, n));
996
+ return {
997
+ n,
998
+ t: st.mtimeMs,
999
+ bytes: st.size
1000
+ };
1001
+ } catch {
1002
+ return null;
1003
+ }
1004
+ }).filter((x) => !!x).sort((a, b) => b.t - a.t);
1005
+ for (const f of files.slice(0, 12)) if (claudeInteractive(join(dir, f.n), root)) return {
1006
+ agent: "claude",
1007
+ session: f.n.slice(0, -6),
1008
+ bytes: f.bytes,
1009
+ file: join(dir, f.n)
1010
+ };
1011
+ return null;
1012
+ }
1013
+ /** A Codex rollout's header: its thread id, folder and source. */
1014
+ function codexMeta(file) {
1015
+ const first = headLines(file, 262144)[0];
1016
+ try {
1017
+ const o = JSON.parse(first);
1018
+ const p = o?.type === "session_meta" ? o.payload : null;
1019
+ return p && typeof p.id === "string" && typeof p.cwd === "string" ? {
1020
+ id: p.id,
1021
+ cwd: p.cwd,
1022
+ source: typeof p.source === "string" ? p.source : void 0
1023
+ } : null;
1024
+ } catch {
1025
+ return null;
1026
+ }
1027
+ }
1028
+ /** The sources a person's Codex session carries: its terminal app, its desktop and editor apps. Anything else - an
1029
+ * `exec` run (Marver's own, a review), a subagent, a source not known - is never copied. */
1030
+ const PERSON = /* @__PURE__ */ new Set(["cli", "vscode"]);
1031
+ /** Codex rollouts, newest first, from the last few days' folders. */
1032
+ function codexRollouts(env, days = 14) {
1033
+ const base = join(codexHome(env), "sessions");
1034
+ const out = [];
1035
+ const now = /* @__PURE__ */ new Date();
1036
+ for (let d = 0; d < days; d++) {
1037
+ const day = /* @__PURE__ */ new Date(now.getTime() - d * 864e5);
1038
+ const dir = join(base, String(day.getFullYear()), String(day.getMonth() + 1).padStart(2, "0"), String(day.getDate()).padStart(2, "0"));
1039
+ let names;
1040
+ try {
1041
+ names = readdirSync(dir);
1042
+ } catch {
1043
+ continue;
1044
+ }
1045
+ for (const n of names) if (n.startsWith("rollout-") && n.endsWith(".jsonl")) try {
1046
+ const st = statSync(join(dir, n));
1047
+ out.push({
1048
+ file: join(dir, n),
1049
+ t: st.mtimeMs,
1050
+ bytes: st.size
1051
+ });
1052
+ } catch {}
1053
+ }
1054
+ return out.sort((a, b) => b.t - a.t);
1055
+ }
1056
+ /** A Codex thread's rollout, when it is an interactive one of this repo. */
1057
+ function codexTranscript(root, thread, env = process.env) {
1058
+ for (const r of codexRollouts(env)) {
1059
+ if (!r.file.endsWith(`${thread}.jsonl`)) continue;
1060
+ const m = codexMeta(r.file);
1061
+ return m && m.id === thread && sameDir(m.cwd, root) && PERSON.has(m.source ?? "") ? {
1062
+ agent: "codex",
1063
+ session: thread,
1064
+ bytes: r.bytes,
1065
+ file: r.file
1066
+ } : null;
1067
+ }
1068
+ return null;
1069
+ }
1070
+ /** The newest interactive Codex session of this repo, on disk. */
1071
+ function newestCodex(root, env = process.env) {
1072
+ for (const r of codexRollouts(env).slice(0, 40)) {
1073
+ const m = codexMeta(r.file);
1074
+ if (m && sameDir(m.cwd, root) && PERSON.has(m.source ?? "")) return {
1075
+ agent: "codex",
1076
+ session: m.id,
1077
+ bytes: r.bytes,
1078
+ file: r.file
1079
+ };
1080
+ }
1081
+ return null;
1082
+ }
1083
+ const transcriptOf = (root, agent, session, env = process.env) => agent === "claude" ? claudeTranscript(root, session, env) : codexTranscript(root, session, env);
1084
+ const newestOf = (root, agent, env = process.env) => agent === "claude" ? newestClaude(root, env) : newestCodex(root, env);
1085
+ /** The newest person's session of this repo in either tool (by its transcript's last write). */
1086
+ function newestAny(root, can, env = process.env) {
1087
+ const all = ["claude", "codex"].filter(can).map((a) => newestOf(root, a, env)).filter((x) => !!x);
1088
+ const t = (x) => {
1089
+ try {
1090
+ return statSync(x.file).mtimeMs;
1091
+ } catch {
1092
+ return 0;
1093
+ }
1094
+ };
1095
+ return all.sort((a, b) => t(b) - t(a))[0] ?? null;
1096
+ }
1097
+ const forkable = (s) => !!s && existsSync(s.file) && s.bytes <= 12582912;
1098
+ /** A claimed run with no word from its session in this long is stalled - the owner decides. */
1099
+ const STALL_MS = 9e5;
1100
+ /** STALL_MS, or the suite's MV_JAM_STALL_MS for a dev server a test starts - read in the suite's build only, with
1101
+ * MARVER_SLOT_BASE set (test-build.ts; as perf-run.ts's MV_PERF_RUN_T): a real stall in seconds, so a browser case
1102
+ * drives one through this daemon and the page's own actions. */
1103
+ const stallMs = () => {
1104
+ return STALL_MS;
1105
+ };
1106
+ /** How long a request's answer is kept for the same request sent again. */
1107
+ const RECEIPT_MS = 6e5;
1108
+ /** The longest final message a session hands back (its replies, not its work). */
1109
+ const DONE_MAX = 4e5;
1110
+ /** Runs one session holds at once (F3). Claude Code dispatches each run to a background subagent of its own, so it can
1111
+ * hold several at once: 8. Marver gives Codex and Cursor runs one after another in their own thread: 3 (as before).
1112
+ * `jam.sessionMax` caps every session. */
1113
+ const sessionMaxFor = (cfg, agent) => cfg.sessionMax ?? (agent === "claude" ? 8 : 3);
1114
+ function settingsOf(root, cfg, agent) {
1115
+ const p = readPrefs(root);
1116
+ const b = (v, d) => typeof v === "boolean" ? v : d;
1117
+ return {
1118
+ runner: cfg.runner ?? "auto",
1119
+ session: cfg.session !== false,
1120
+ sessionMax: agent ? sessionMaxFor(cfg, agent) : cfg.sessionMax ?? 3,
1121
+ context: p.context === "fork" || p.context === "fresh" ? p.context : cfg.context ?? "fork",
1122
+ mcp: b(p.mcp, cfg.mcp ?? true),
1123
+ skills: b(p.skills, cfg.skills ?? true),
1124
+ others: b(p.others, cfg.others ?? false)
1125
+ };
1126
+ }
1127
+ const handleOf = (b, gen) => `r-${b.batchId.slice(0, 8)}.${gen}`;
1128
+ /** A session command as that session must type it - Cursor's names its connection (it has no session id in its shell). */
1129
+ const cmdFor = (conn, op, handle) => `\`npx marver jam ${op}${handle ? ` ${handle}` : ""}${conn?.agent === "cursor" ? ` --as ${conn.id}` : ""}\``;
1130
+ const HANDLE = /^r-([0-9a-f]{8})\.(\d+)$/;
1131
+ /** A session's final message, parsed as any agent's. */
1132
+ const parsedRun = (text) => {
1133
+ const p = parseAgentText(text);
1134
+ return {
1135
+ reply: p.reply,
1136
+ asks: p.asks,
1137
+ reanchors: p.reanchors,
1138
+ said: text,
1139
+ ok: !!p.reply
1140
+ };
1141
+ };
1142
+ function createRuns(d) {
1143
+ const { root, q } = d;
1144
+ let stopped = false;
1145
+ const waiters = /* @__PURE__ */ new Map();
1146
+ /** a `done` waits for its delivery: by batch, the answers to write when it is posted */
1147
+ const deliveries = /* @__PURE__ */ new Map();
1148
+ /** how a batch's delivery went, for a `done` sent again */
1149
+ const outcome = /* @__PURE__ */ new Map();
1150
+ const seenReqs = /* @__PURE__ */ new Set();
1151
+ /** each connection's offers as last written: a new batch among them grows its generation */
1152
+ const offered = /* @__PURE__ */ new Map();
1153
+ /** connections whose offers file last said a stop or a carry-on: looked at again until it says none */
1154
+ const worded = /* @__PURE__ */ new Set();
1155
+ /** connections whose offers this daemon has written since it started */
1156
+ const published = /* @__PURE__ */ new Set();
1157
+ const settings = () => settingsOf(root, d.cfg);
1158
+ const maxOf = (c) => sessionMaxFor(d.cfg, c.agent);
1159
+ /** may this session take Jam work now: alive, not muted or in plan mode, and its tool's connector not turned off */
1160
+ const usable = (c, now = Date.now()) => !!c && eligible(c, now) && !readPrefs(root).off?.[c.agent];
1161
+ const live = (now = Date.now()) => listConns(root).filter((c) => usable(c, now));
1162
+ const open = () => q.j.batches.filter((b) => b.state === "claimed" && !b.results);
1163
+ const byId = (id) => open().find((b) => b.batchId === id);
1164
+ /** a run formed beside this connection's runs (F4) and not offered yet: its slot is kept for it from the moment it is formed -
1165
+ * never once Marver spawned it (Codex's review: one let go of and spawned still took a place of your session's room) */
1166
+ const kept = (b, id) => b.share?.conn === id && !b.offer && !b.claim && !b.handoff && (!b.runner || b.runner.kind === "session");
1167
+ /** runs a connection holds now: offered to it, claimed by it and not stopping, or kept for it */
1168
+ const load = (id) => open().filter((b) => b.offer?.conn === id || b.claim?.conn === id && !b.claim.stopping || kept(b, id)).length;
1169
+ const selected = (now = Date.now()) => {
1170
+ const conns = live(now);
1171
+ const pick = readPrefs(root).pick;
1172
+ return conns.find((c) => c.id === pick) ?? conns.sort((a, b) => b.since - a.since)[0];
1173
+ };
1174
+ /** Can it take an offer now? Claude Code always (its inbox wakes it); Codex and Cursor while a turn runs. */
1175
+ const offerable = (c) => c.agent === "claude" || c.busy;
1176
+ /** Is it the record of a Jam session (a wrap-up)? Offered to your session though the session it records has ended. */
1177
+ const recordRun = (b) => b.members.some((m) => q.j.cards.find((c) => c.id === m.card)?.kind === "wrapup");
1178
+ /** Does a session take work now - this run, when one is named (`record`: a session's record)? Sessions on, the owner's
1179
+ * context allowed, not background-only, and a Jam session running (or, for a session's own record, just ended: never
1180
+ * any other run). */
1181
+ const sessionsOn = (s, b) => s.session && s.context === "fork" && s.runner !== "background" && (d.jamOn() || b === "record" || !!b && recordRun(b));
1182
+ /** Is the writer of a claim proven gone? Its process is (Claude Code, Codex), or - Cursor - that very incarnation
1183
+ * said it ended. A connection file missing, or silence, is "unknown", never "gone". */
1184
+ const writerGone = (claim) => {
1185
+ if (claim.pid) return !pidAlive(claim.pid);
1186
+ const c = readConn(root, claim.conn);
1187
+ return !!c && c.inc === claim.inc && !!c.ended;
1188
+ };
1189
+ const choose = (b, now = Date.now(), spawnOnly = false) => {
1190
+ const s = settings();
1191
+ let skipped;
1192
+ if (!spawnOnly && !b.handoff && b.share) {
1193
+ const pick = sessionsOn(s, b) ? selected(now) : void 0;
1194
+ if (pick && pick.id === b.share.conn && pick.inc === b.share.inc && offerable(pick)) return {
1195
+ kind: "session",
1196
+ conn: pick
1197
+ };
1198
+ }
1199
+ if (!spawnOnly && !b.handoff) {
1200
+ const pick = sessionsOn(s, b) ? selected(now) : void 0;
1201
+ if (pick && offerable(pick) && load(pick.id) < maxOf(pick)) return {
1202
+ kind: "session",
1203
+ conn: pick
1204
+ };
1205
+ if (s.runner === "session" && s.session && s.context === "fork") return { kind: "wait" };
1206
+ if (pick) skipped = offerable(pick) ? `your session didn't take it - it already holds ${load(pick.id)} run${load(pick.id) === 1 ? "" : "s"}` : `your session was idle - ${pick.agent === "codex" ? "Codex" : "Cursor"} takes a run only while it works`;
1207
+ }
1208
+ const pick = s.session ? selected(now) : void 0;
1209
+ const agent = pick?.agent ?? d.cfg.agent;
1210
+ if (s.context === "fork") {
1211
+ const can = (a) => d.canSpawn(a);
1212
+ const conns = listConns(root).filter((c) => (c.agent === "claude" || c.agent === "codex") && alive(c, now) && can(c.agent)).sort((x, y) => y.since - x.since);
1213
+ const src = (pick && (pick.agent === "claude" || pick.agent === "codex") && can(pick.agent) ? transcriptOf(root, pick.agent, pick.session) : null) ?? conns.map((c) => transcriptOf(root, c.agent, c.session)).find((t) => !!t) ?? newestAny(root, can);
1214
+ if (src && forkable(src)) return {
1215
+ kind: "fork",
1216
+ agent: src.agent,
1217
+ session: src.session,
1218
+ ...skipped ? { why: skipped } : {}
1219
+ };
1220
+ if (src) return {
1221
+ kind: "fresh",
1222
+ agent: src.agent,
1223
+ why: "your session is too long to copy - a fresh agent took it"
1224
+ };
1225
+ }
1226
+ return {
1227
+ kind: "fresh",
1228
+ agent: d.canSpawn(agent) ? agent : d.cfg.agent,
1229
+ ...skipped ? { why: skipped } : {}
1230
+ };
1231
+ };
1232
+ /** What a run is called in a ping: its card's name, else the owner's words (a capture's first words - its name comes later), clipped. */
1233
+ const titleOf = (b) => {
1234
+ const c = q.j.cards.find((x) => x.id === b.members[0]?.card);
1235
+ const words = c?.name ?? c?.autoName ?? b.members[0]?.brief?.asks?.[0]?.body ?? (b.members[0]?.brief?.capture ? requestWords(b.members[0].brief.capture, " ") || void 0 : void 0) ?? (c?.kind === "wrapup" ? "Session record" : "a request");
1236
+ const t = sanitize(String(words), 400).replace(/@marver\b/gi, "").replace(/\s+/g, " ").trim() || "a request";
1237
+ const cps = [...t];
1238
+ return cps.length > 60 ? `${cps.slice(0, 59).join("")}…` : t;
1239
+ };
1240
+ /** Write every connection's offers file: how many runs wait for it, the runs it must let go or carry on with, a new
1241
+ * generation when any of that is new - and the words its listener posts for it. */
1242
+ const publish = () => {
1243
+ const by = /* @__PURE__ */ new Map();
1244
+ const stops = /* @__PURE__ */ new Map();
1245
+ const resumes = /* @__PURE__ */ new Map();
1246
+ for (const b of open()) {
1247
+ if (b.offer) by.set(b.offer.conn, [...by.get(b.offer.conn) ?? [], b.batchId]);
1248
+ if (b.claim?.stopping) stops.set(b.claim.conn, [...stops.get(b.claim.conn) ?? [], handleOf(b, b.claim.gen)]);
1249
+ if (b.claim?.resumed) resumes.set(b.claim.conn, [...resumes.get(b.claim.conn) ?? [], handleOf(b, b.claim.gen)]);
1250
+ }
1251
+ for (const id of /* @__PURE__ */ new Set([
1252
+ ...by.keys(),
1253
+ ...offered.keys(),
1254
+ ...stops.keys(),
1255
+ ...resumes.keys(),
1256
+ ...worded
1257
+ ])) {
1258
+ const now = new Set(by.get(id) ?? []);
1259
+ const prev = readOffers(root, id);
1260
+ const newest = open().filter((b) => b.offer?.conn === id).sort((x, y) => y.offer.at - x.offer.at)[0];
1261
+ const over = newest?.overlaps?.map((x) => open().find((y) => y.batchId === x)).find((y) => !!y);
1262
+ const latest = newest ? {
1263
+ id: newest.batchId.slice(0, 8),
1264
+ title: titleOf(newest),
1265
+ ...over ? { overlaps: over.claim ? handleOf(over, over.claim.gen) : over.batchId.slice(0, 8) } : {}
1266
+ } : void 0;
1267
+ const was = offered.get(id) ?? (!published.has(id) && prev && prev.n === now.size && prev.latest?.id === latest?.id ? now : /* @__PURE__ */ new Set());
1268
+ published.add(id);
1269
+ const stop = stops.get(id) ?? [];
1270
+ const resume = resumes.get(id) ?? [];
1271
+ const newOffer = [...now].some((x) => !was.has(x));
1272
+ const newWord = JSON.stringify([stop, resume]) !== JSON.stringify([prev?.stop ?? [], prev?.resume ?? []]);
1273
+ if (now.size) offered.set(id, now);
1274
+ else offered.delete(id);
1275
+ if (stop.length || resume.length) worded.add(id);
1276
+ else worded.delete(id);
1277
+ if (!newOffer && !newWord && prev?.n === now.size) continue;
1278
+ const gen = newOffer || newWord && (stop.length || resume.length) ? Math.max((prev?.gen ?? 0) + 1, Date.now()) : prev?.gen ?? 0;
1279
+ const o = {
1280
+ n: now.size,
1281
+ gen,
1282
+ ...stop.length ? { stop } : {},
1283
+ ...resume.length ? { resume } : {},
1284
+ ...latest ? { latest } : {}
1285
+ };
1286
+ const line = gen > (prev?.gen ?? 0) ? pingLine(o, prev?.line) : prev?.line;
1287
+ try {
1288
+ writeOffers(root, id, {
1289
+ ...o,
1290
+ ...line ? { line } : {}
1291
+ });
1292
+ } catch {}
1293
+ }
1294
+ };
1295
+ const settle = (id, r) => {
1296
+ const w = waiters.get(id);
1297
+ if (w) {
1298
+ waiters.delete(id);
1299
+ w(r);
1300
+ }
1301
+ };
1302
+ const run = (b, conn) => new Promise((resolve) => {
1303
+ if (b.claim?.result !== void 0) return resolve(parsedRun(b.claim.result));
1304
+ waiters.set(b.batchId, resolve);
1305
+ let gone = false;
1306
+ q.lock(() => {
1307
+ if (!b.claim && !b.offer) {
1308
+ const held = conn ? load(conn.id) - (kept(b, conn.id) ? 1 : 0) : 0;
1309
+ if (conn && held >= maxOf(conn)) {
1310
+ letGo(b);
1311
+ if (b.handoff) {
1312
+ b.handoffWhy = `your session didn't take it - it already holds ${held} run${held === 1 ? "" : "s"}`;
1313
+ gone = true;
1314
+ }
1315
+ } else if (conn && !d.mayHold(b, conn)) {
1316
+ crowdedOut(b);
1317
+ gone = true;
1318
+ } else {
1319
+ b.runner = {
1320
+ kind: "session",
1321
+ agent: conn?.agent ?? ""
1322
+ };
1323
+ if (conn) {
1324
+ b.runner.conn = conn.id;
1325
+ b.offer = {
1326
+ conn: conn.id,
1327
+ inc: conn.inc,
1328
+ at: Date.now()
1329
+ };
1330
+ }
1331
+ }
1332
+ }
1333
+ q.persist();
1334
+ }).then(() => {
1335
+ publish();
1336
+ d.changed();
1337
+ if (gone) settle(b.batchId, null);
1338
+ }, () => settle(b.batchId, null));
1339
+ });
1340
+ /** Does a run a session let go of (not an explicit choice of the owner's) wait for a session again? Only under
1341
+ * `jam.runner: 'session'`, while sessions can take work at all. */
1342
+ const waitsForSession = (s = settings()) => s.runner === "session" && s.session && s.context === "fork";
1343
+ /** Where a run goes once its session lets go: back to waiting under session-only, else spawned. Call under the lock. */
1344
+ const letGo = (b) => {
1345
+ if (waitsForSession()) {
1346
+ delete b.handoff;
1347
+ b.runner = {
1348
+ kind: "session",
1349
+ agent: ""
1350
+ };
1351
+ } else b.handoff = "spawn";
1352
+ };
1353
+ /** It may not be held beside a run on one of its frames (F4: another runner's, or another incarnation's): it leaves its
1354
+ * session - spawned as letGo says, or under session-only back to the queue, never waiting for a session with the frame
1355
+ * kept (Codex's review: two runs waiting on one frame for the session you switched to each kept the frame the other
1356
+ * needed, forever - a queued request holds nothing, so two never wait on each other). Call under the lock. */
1357
+ const crowdedOut = (b) => {
1358
+ letGo(b);
1359
+ b.handoff ??= "queue";
1360
+ b.handoffWhy = "another runner holds one of its frames";
1361
+ };
1362
+ /** Take an offer back (not pulled in time, its session gone, Jam ended): where it goes is decided and saved in one write. */
1363
+ const withdraw = async (id, why) => {
1364
+ if (!await q.lock(() => {
1365
+ const b = byId(id);
1366
+ if (!b?.offer) return false;
1367
+ delete b.offer;
1368
+ letGo(b);
1369
+ if (b.handoff) b.handoffWhy = why;
1370
+ q.persist();
1371
+ return true;
1372
+ })) return;
1373
+ d.log(` jam: a run offered to your session went another way (${why})`);
1374
+ publish();
1375
+ if (byId(id)?.handoff) settle(id, null);
1376
+ d.changed();
1377
+ };
1378
+ /** The owner's stop, made final: dropped, or handed to a spawned runner (the owner's explicit choice wins over
1379
+ * session-only waiting). Call under the lock. */
1380
+ const stopNow = (b) => {
1381
+ const c = b.claim;
1382
+ b.gen = Math.max(b.gen ?? 0, c.gen);
1383
+ if (c.stopping === "drop") b.dropped = true;
1384
+ else b.handoff = "spawn";
1385
+ delete b.claim;
1386
+ };
1387
+ /** A stop the owner chose is confirmed by its writer proven gone: it runs as they chose - saved first. */
1388
+ const finishStop = async (id) => {
1389
+ const did = await q.lock(() => {
1390
+ const b = byId(id);
1391
+ if (!b?.claim?.stopping || b.claim.result !== void 0) return false;
1392
+ stopNow(b);
1393
+ q.persist();
1394
+ return true;
1395
+ });
1396
+ if (did) {
1397
+ publish();
1398
+ settle(id, null);
1399
+ d.changed();
1400
+ }
1401
+ return did;
1402
+ };
1403
+ /** The batch a handle names, checked for this connection - call it under the lock. */
1404
+ const claimOf = (conn, handle) => {
1405
+ const m = typeof handle === "string" ? HANDLE.exec(handle) : null;
1406
+ if (!m) return "that is not a run handle (r-xxxxxxxx.N)";
1407
+ const gen = Number(m[2]);
1408
+ const b = open().find((x) => x.batchId.startsWith(m[1]));
1409
+ if (!b) return "that run is over";
1410
+ if (!b.claim || b.claim.conn !== conn.id || b.claim.inc !== conn.inc) return "that run is not yours - it went to another runner";
1411
+ if (b.claim.gen !== gen) return "that handle is old - the run was taken again since";
1412
+ return {
1413
+ b,
1414
+ gen
1415
+ };
1416
+ };
1417
+ /** A change's receipt, in the same journal write as the change. */
1418
+ const keep = (req, out, b) => {
1419
+ (q.j.receipts ??= {})[req.id] = {
1420
+ at: Date.now(),
1421
+ out,
1422
+ op: req.op,
1423
+ ...b ? { batch: b.batchId } : {}
1424
+ };
1425
+ };
1426
+ /** How a handed-back run's delivery stands, from the batch itself - what every answer about it says. Null: not
1427
+ * settled yet (being posted). */
1428
+ const deliveryOf = (id) => {
1429
+ const b = q.j.batches.find((x) => x.batchId === id);
1430
+ if (!b) return {
1431
+ ok: false,
1432
+ error: "that run is gone from the journal"
1433
+ };
1434
+ if (b.posted || b.state === "done") return {
1435
+ ok: true,
1436
+ text: "Delivered - its replies are posted and the frames are free."
1437
+ };
1438
+ if (b.undelivered) return {
1439
+ ok: false,
1440
+ error: "its replies are saved, but they could not be posted - Retry on the card posts them"
1441
+ };
1442
+ if (b.state === "failed") return {
1443
+ ok: false,
1444
+ error: `it could not be delivered: ${b.note ?? "the run failed"}`
1445
+ };
1446
+ if (b.results) {
1447
+ const o = outcome.get(id);
1448
+ return o && !o.ok ? {
1449
+ ok: false,
1450
+ error: `it could not be delivered: ${o.note ?? "unknown"}`
1451
+ } : o?.note === "retrying" ? {
1452
+ ok: true,
1453
+ text: "Handed back - its replies are saved; posting them failed once and is being tried again."
1454
+ } : null;
1455
+ }
1456
+ const o = outcome.get(id);
1457
+ return o && !o.ok ? {
1458
+ ok: false,
1459
+ error: `it could not be delivered: ${o.note ?? "unknown"}`
1460
+ } : null;
1461
+ };
1462
+ /** A `done` or `say` sent again: where its run stands now, not what was hoped when it was taken. */
1463
+ const replay = (r, conn) => {
1464
+ if (r.op === "mute") {
1465
+ try {
1466
+ patchConn(root, conn.id, conn.inc, { muted: true });
1467
+ } catch {}
1468
+ return r.out;
1469
+ }
1470
+ if (r.op === "done" && r.batch) return deliveryOf(r.batch) ?? waitDelivery(r.batch);
1471
+ if (r.op === "say" && r.batch) {
1472
+ const b = q.j.batches.find((x) => x.batchId === r.batch);
1473
+ return b?.early && d.say(b) ? {
1474
+ ok: true,
1475
+ text: "Posted."
1476
+ } : {
1477
+ ok: true,
1478
+ text: "Taken - it is posted before the run is delivered."
1479
+ };
1480
+ }
1481
+ return r.out;
1482
+ };
1483
+ const waitDelivery = (id) => new Promise((res) => {
1484
+ const to = setTimeout(() => res(deliveryOf(id) ?? {
1485
+ ok: true,
1486
+ text: "Handed back - it is being posted; the canvas shows it in the thread."
1487
+ }), 1e5);
1488
+ to.unref?.();
1489
+ deliveries.set(id, [...deliveries.get(id) ?? [], () => {
1490
+ clearTimeout(to);
1491
+ res(deliveryOf(id) ?? {
1492
+ ok: true,
1493
+ text: "Handed back - it is being posted; the canvas shows it in the thread."
1494
+ });
1495
+ }]);
1496
+ });
1497
+ /** One request. Returns its answer, or a promise of it (a `done` answers once its replies are posted - and never
1498
+ * holds up the requests after it). */
1499
+ const ops = async (req, conn) => {
1500
+ const now = Date.now();
1501
+ if (req.op === "release") {
1502
+ let out = {
1503
+ ok: false,
1504
+ error: "that run is over"
1505
+ };
1506
+ let id = "";
1507
+ await q.lock(() => {
1508
+ const f = claimOf(conn, req.args.handle);
1509
+ if (typeof f === "string") {
1510
+ out = {
1511
+ ok: false,
1512
+ error: f
1513
+ };
1514
+ return;
1515
+ }
1516
+ const b = f.b;
1517
+ if (b.claim.result !== void 0) {
1518
+ out = {
1519
+ ok: false,
1520
+ error: "it is already handed back"
1521
+ };
1522
+ return;
1523
+ }
1524
+ id = b.batchId;
1525
+ if (b.claim.stopping) {
1526
+ out = {
1527
+ ok: true,
1528
+ text: "Released - the owner's choice goes ahead."
1529
+ };
1530
+ stopNow(b);
1531
+ } else {
1532
+ b.gen = Math.max(b.gen ?? 0, b.claim.gen);
1533
+ delete b.claim;
1534
+ letGo(b);
1535
+ if (b.handoff) b.handoffWhy = "your session let it go";
1536
+ out = {
1537
+ ok: true,
1538
+ text: b.handoff ? "Released - another runner takes it." : "Released - it waits for a session again."
1539
+ };
1540
+ }
1541
+ keep(req, out, b);
1542
+ q.persist();
1543
+ });
1544
+ if (id && out.ok) {
1545
+ publish();
1546
+ if (byId(id)?.handoff || byId(id)?.dropped || !byId(id)) settle(id, null);
1547
+ d.changed();
1548
+ }
1549
+ return out;
1550
+ }
1551
+ if (!usable(conn, now)) return {
1552
+ ok: false,
1553
+ error: conn.muted ? "this session is muted for Jam until it ends" : "this session cannot take Jam work now"
1554
+ };
1555
+ if (req.op === "mute") {
1556
+ const out = {
1557
+ ok: true,
1558
+ text: "Muted: this session takes no Jam work until it ends."
1559
+ };
1560
+ await q.lock(() => {
1561
+ keep(req, out);
1562
+ q.persist();
1563
+ });
1564
+ patchConn(root, conn.id, conn.inc, { muted: true });
1565
+ for (const b of open().filter((x) => x.offer?.conn === conn.id)) await withdraw(b.batchId, "muted");
1566
+ return out;
1567
+ }
1568
+ if (req.op === "status") {
1569
+ const mine = open().filter((b) => b.offer?.conn === conn.id || b.claim?.conn === conn.id);
1570
+ const line = (b) => b.offer ? `offered: run ${b.batchId.slice(0, 8)} (${b.frames.join(", ")}) - take it with ${cmdFor(conn, "next")}` : `${b.claim.stopping ? `stopping - release it: ${cmdFor(conn, "release", handleOf(b, b.claim.gen))}` : b.claim.result !== void 0 ? "handed back" : b.claim.stalled ? "stalled" : "yours"}: ${handleOf(b, b.claim.gen)} (${b.frames.join(", ")})`;
1571
+ return {
1572
+ ok: true,
1573
+ text: [`Connected: ${conn.agent} session ${conn.id}${selected(now)?.id === conn.id ? " - it takes the work" : ""}${d.jamOn() ? "" : " (no Jam session runs on the canvas now)"}.`, ...mine.length ? mine.map(line) : ["No runs for it now."]].join("\n")
1574
+ };
1575
+ }
1576
+ if (req.op === "own") {
1577
+ const frame = String(req.args.frame ?? "");
1578
+ let out = {
1579
+ ok: false,
1580
+ error: "that run is over"
1581
+ };
1582
+ await q.lock(() => {
1583
+ const f = claimOf(conn, req.args.handle);
1584
+ if (typeof f === "string") {
1585
+ out = {
1586
+ ok: false,
1587
+ error: f
1588
+ };
1589
+ return;
1590
+ }
1591
+ const c = f.b.claim;
1592
+ if (c.stopping) {
1593
+ out = {
1594
+ ok: false,
1595
+ error: `the owner moved this run elsewhere - stop working on it and run ${cmdFor(conn, "release", String(req.args.handle))}`
1596
+ };
1597
+ return;
1598
+ }
1599
+ if (c.result !== void 0) {
1600
+ out = {
1601
+ ok: false,
1602
+ error: "it is already handed back"
1603
+ };
1604
+ return;
1605
+ }
1606
+ const why = d.own(f.b, frame);
1607
+ if (why) {
1608
+ out = {
1609
+ ok: false,
1610
+ error: why
1611
+ };
1612
+ return;
1613
+ }
1614
+ c.progress = Date.now();
1615
+ delete c.stalled;
1616
+ out = {
1617
+ ok: true,
1618
+ text: `${frame} is this run's now - no other runner gets it until the run is handed back.`
1619
+ };
1620
+ keep(req, out, f.b);
1621
+ q.persist();
1622
+ });
1623
+ if (out.ok) {
1624
+ publish();
1625
+ d.changed();
1626
+ }
1627
+ return out;
1628
+ }
1629
+ if (req.op === "next") {
1630
+ const let_go = [];
1631
+ const out = await q.lock(() => {
1632
+ const s = settings();
1633
+ const cur = readConn(root, conn.id);
1634
+ if (!cur || cur.inc !== conn.inc || !usable(cur)) return {
1635
+ ok: false,
1636
+ error: "this session's connection changed - run the command again"
1637
+ };
1638
+ const mine = open().filter((x) => x.offer?.conn === conn.id && x.offer.inc === conn.inc && sessionsOn(s, x)).sort((a, z) => a.offer.at - z.offer.at);
1639
+ if (!sessionsOn(s) && !mine.length) return {
1640
+ ok: true,
1641
+ text: "Nothing waits for this session now (no Jam session takes it)."
1642
+ };
1643
+ if (selected(now)?.id !== conn.id) return {
1644
+ ok: true,
1645
+ text: "Nothing waits for this session now - another session takes the work."
1646
+ };
1647
+ let b;
1648
+ for (const x of mine) {
1649
+ if (d.mayHold(x, conn)) {
1650
+ b = x;
1651
+ break;
1652
+ }
1653
+ delete x.offer;
1654
+ crowdedOut(x);
1655
+ let_go.push(x.batchId);
1656
+ }
1657
+ if (!b) {
1658
+ if (let_go.length) q.persist();
1659
+ return {
1660
+ ok: true,
1661
+ text: "Nothing waits for this session now."
1662
+ };
1663
+ }
1664
+ const gen = Math.max(b.gen ?? 0, b.claim?.gen ?? 0) + 1;
1665
+ delete b.offer;
1666
+ delete b.handoff;
1667
+ b.gen = gen;
1668
+ b.runner = {
1669
+ kind: "session",
1670
+ agent: conn.agent,
1671
+ conn: conn.id
1672
+ };
1673
+ b.claim = {
1674
+ conn: conn.id,
1675
+ inc: conn.inc,
1676
+ ...conn.pid ? { pid: conn.pid } : {},
1677
+ gen,
1678
+ at: Date.now(),
1679
+ progress: Date.now()
1680
+ };
1681
+ const handle = handleOf(b, gen);
1682
+ const o = {
1683
+ ok: true,
1684
+ handle,
1685
+ frames: b.frames,
1686
+ text: d.goal(b, handle, conn)
1687
+ };
1688
+ keep(req, o, b);
1689
+ q.persist();
1690
+ return o;
1691
+ });
1692
+ for (const id of let_go) settle(id, null);
1693
+ if (out.handle || let_go.length) {
1694
+ publish();
1695
+ d.changed();
1696
+ }
1697
+ return out;
1698
+ }
1699
+ if (req.op === "progress") {
1700
+ let out = {
1701
+ ok: true,
1702
+ text: "Noted - still yours."
1703
+ };
1704
+ await q.lock(() => {
1705
+ const f = claimOf(conn, req.args.handle);
1706
+ if (typeof f === "string") {
1707
+ out = {
1708
+ ok: false,
1709
+ error: f
1710
+ };
1711
+ return;
1712
+ }
1713
+ const c = f.b.claim;
1714
+ if (c.stopping) {
1715
+ out = {
1716
+ ok: false,
1717
+ error: `the owner moved this run elsewhere - stop working on it and run ${cmdFor(conn, "release", String(req.args.handle))}`
1718
+ };
1719
+ return;
1720
+ }
1721
+ c.progress = Date.now();
1722
+ delete c.stalled;
1723
+ delete c.resumed;
1724
+ keep(req, out, f.b);
1725
+ q.persist();
1726
+ });
1727
+ if (out.ok) {
1728
+ publish();
1729
+ d.changed();
1730
+ }
1731
+ return out;
1732
+ }
1733
+ if (req.op === "say") {
1734
+ const text = String(req.args.text ?? "").trim().slice(0, 2e3);
1735
+ if (!text) return {
1736
+ ok: false,
1737
+ error: "say what"
1738
+ };
1739
+ let out = {
1740
+ ok: true,
1741
+ text: "Posted."
1742
+ };
1743
+ let b0;
1744
+ await q.lock(() => {
1745
+ const f = claimOf(conn, req.args.handle);
1746
+ if (typeof f === "string") {
1747
+ out = {
1748
+ ok: false,
1749
+ error: f
1750
+ };
1751
+ return;
1752
+ }
1753
+ const b = f.b, c = b.claim;
1754
+ if (c.stopping) {
1755
+ out = {
1756
+ ok: false,
1757
+ error: `the owner moved this run elsewhere - stop working on it and run ${cmdFor(conn, "release", String(req.args.handle))}`
1758
+ };
1759
+ return;
1760
+ }
1761
+ if (c.result !== void 0) {
1762
+ out = {
1763
+ ok: false,
1764
+ error: "it is already handed back"
1765
+ };
1766
+ return;
1767
+ }
1768
+ if (b.members.length !== 1) {
1769
+ out = {
1770
+ ok: false,
1771
+ error: "a run of several asks posts no early line - its replies come with done"
1772
+ };
1773
+ return;
1774
+ }
1775
+ if (b.early) {
1776
+ out = {
1777
+ ok: false,
1778
+ error: "its early line is already posted"
1779
+ };
1780
+ return;
1781
+ }
1782
+ b.early = {
1783
+ body: text,
1784
+ asks: false,
1785
+ commentId: `jam-c-e${b.attempts}-${b.batchId}`,
1786
+ ts: Date.now()
1787
+ };
1788
+ c.progress = Date.now();
1789
+ delete c.stalled;
1790
+ keep(req, {
1791
+ ok: true,
1792
+ text: "Posted."
1793
+ }, b);
1794
+ q.persist();
1795
+ b0 = b;
1796
+ });
1797
+ if (!b0) return out;
1798
+ if (!d.say(b0)) return {
1799
+ ok: true,
1800
+ text: "Taken - it is posted before the run is delivered."
1801
+ };
1802
+ d.changed();
1803
+ return out;
1804
+ }
1805
+ const text = String(req.args.text ?? "").slice(0, DONE_MAX);
1806
+ if (!parsedRun(text).reply) return {
1807
+ ok: false,
1808
+ error: "the final message is empty - write the marver-reply blocks to the file"
1809
+ };
1810
+ let err;
1811
+ let id = "";
1812
+ await q.lock(() => {
1813
+ const f = claimOf(conn, req.args.handle);
1814
+ if (typeof f === "string") {
1815
+ err = f;
1816
+ return;
1817
+ }
1818
+ const c = f.b.claim;
1819
+ if (c.stopping) {
1820
+ err = `the owner moved this run elsewhere - stop working on it and run ${cmdFor(conn, "release", String(req.args.handle))}`;
1821
+ return;
1822
+ }
1823
+ if (c.result !== void 0) {
1824
+ err = "it is already handed back";
1825
+ return;
1826
+ }
1827
+ c.result = text;
1828
+ c.progress = Date.now();
1829
+ delete c.stalled;
1830
+ delete c.resumed;
1831
+ id = f.b.batchId;
1832
+ keep(req, { ok: true }, f.b);
1833
+ q.persist();
1834
+ });
1835
+ if (err) return {
1836
+ ok: false,
1837
+ error: err
1838
+ };
1839
+ const later = waitDelivery(id);
1840
+ settle(id, parsedRun(text));
1841
+ d.changed();
1842
+ return { later };
1843
+ };
1844
+ const answerAll = async () => {
1845
+ for (const { raw } of takeRequests(root)) {
1846
+ const rid = raw?.id;
1847
+ const kept = typeof rid === "string" ? q.j.receipts?.[rid] : void 0;
1848
+ const v = verify(root, raw, kept ? /* @__PURE__ */ new Set() : seenReqs);
1849
+ if (!v.ok) {
1850
+ if (v.id) answer(root, v.id, {
1851
+ ok: false,
1852
+ error: v.error
1853
+ });
1854
+ continue;
1855
+ }
1856
+ if (kept) {
1857
+ const r = replay(kept, v.conn);
1858
+ if (r instanceof Promise) r.then((o) => answer(root, v.req.id, o));
1859
+ else answer(root, v.req.id, r);
1860
+ continue;
1861
+ }
1862
+ let out;
1863
+ try {
1864
+ out = await ops(v.req, v.conn);
1865
+ } catch (e) {
1866
+ out = {
1867
+ ok: false,
1868
+ error: e.message
1869
+ };
1870
+ }
1871
+ try {
1872
+ if (alive(v.conn)) patchConn(root, v.conn.id, v.conn.inc, {});
1873
+ } catch {}
1874
+ if ("later" in out && out.later instanceof Promise) {
1875
+ const id = v.req.id;
1876
+ out.later.then((o) => answer(root, id, o));
1877
+ } else answer(root, v.req.id, out);
1878
+ }
1879
+ if (seenReqs.size > 5e3) seenReqs.clear();
1880
+ };
1881
+ let lastSweep = 0;
1882
+ /** who takes the work and their room, as the last tick read it */
1883
+ let routed = "";
1884
+ const tick = async (now = Date.now()) => {
1885
+ if (stopped || !d.ready()) return;
1886
+ await answerAll();
1887
+ const s = settings();
1888
+ const chosen = selected(now);
1889
+ for (const b of open()) {
1890
+ const sel = sessionsOn(s, b) ? chosen : void 0;
1891
+ if (b.offer) {
1892
+ const c = readConn(root, b.offer.conn);
1893
+ if (!c || !usable(c, now) || c.inc !== b.offer.inc) {
1894
+ await withdraw(b.batchId, "it ended or cannot take work now");
1895
+ continue;
1896
+ }
1897
+ if (!sessionsOn(s, b)) {
1898
+ await withdraw(b.batchId, d.jamOn() ? "sessions are off" : "the Jam session ended");
1899
+ continue;
1900
+ }
1901
+ if (sel?.id !== c.id) {
1902
+ await withdraw(b.batchId, "another session takes the work now");
1903
+ continue;
1904
+ }
1905
+ if (s.runner === "session") continue;
1906
+ if (c.agent === "claude" ? now - b.offer.at > 12e4 : !c.busy && now - Math.max(b.offer.at, c.seen) > 3e4) await withdraw(b.batchId, c.agent === "claude" ? "not taken in 2 minutes" : "its turn ended without taking it");
1907
+ } else if (b.claim) {
1908
+ const claim = b.claim;
1909
+ if (claim.result !== void 0) continue;
1910
+ if (claim.stopping) {
1911
+ if (writerGone(claim)) await finishStop(b.batchId);
1912
+ continue;
1913
+ }
1914
+ const quiet = writerGone(claim) || now - claim.progress > stallMs();
1915
+ if (!claim.stalled && quiet) {
1916
+ await q.lock(() => {
1917
+ const x = byId(b.batchId)?.claim;
1918
+ if (x && x.result === void 0 && !x.stopping) {
1919
+ if (!x.stalled) x.stalls = (x.stalls ?? 0) + 1;
1920
+ x.stalled = true;
1921
+ q.persist();
1922
+ }
1923
+ });
1924
+ d.log(` jam: a run your session took went quiet (${writerGone(claim) ? "the session ended" : "no word for 15 minutes"}) - choose in the lane`);
1925
+ d.changed();
1926
+ }
1927
+ } else if (b.runner?.kind === "session" && !b.handoff && waiters.has(b.batchId)) {
1928
+ if (!waitsForSession(s) && !sel) {
1929
+ await q.lock(() => {
1930
+ const x = byId(b.batchId);
1931
+ if (x && !x.offer && !x.claim) {
1932
+ x.handoff = "spawn";
1933
+ q.persist();
1934
+ }
1935
+ });
1936
+ settle(b.batchId, null);
1937
+ d.changed();
1938
+ continue;
1939
+ }
1940
+ const fits = (x) => load(sel.id) - (kept(x, sel.id) ? 1 : 0) < maxOf(sel);
1941
+ if (sel && offerable(sel) && fits(b)) {
1942
+ let out = false;
1943
+ await q.lock(() => {
1944
+ const x = byId(b.batchId);
1945
+ if (!x || x.offer || x.claim || x.handoff || !fits(x)) return;
1946
+ if (d.mayHold(x, sel)) {
1947
+ x.runner = {
1948
+ kind: "session",
1949
+ agent: sel.agent,
1950
+ conn: sel.id
1951
+ };
1952
+ x.offer = {
1953
+ conn: sel.id,
1954
+ inc: sel.inc,
1955
+ at: Date.now()
1956
+ };
1957
+ } else {
1958
+ crowdedOut(x);
1959
+ out = true;
1960
+ }
1961
+ q.persist();
1962
+ });
1963
+ if (out) settle(b.batchId, null);
1964
+ d.changed();
1965
+ }
1966
+ }
1967
+ }
1968
+ const routing = [roomOf(now), roomOf(now, true)].map((r) => r ? `${r.conn.id}.${r.conn.inc}.${r.room}` : "").join("|");
1969
+ if (routing !== routed) {
1970
+ routed = routing;
1971
+ d.changed();
1972
+ }
1973
+ publish();
1974
+ if (now - lastSweep > 6e4) {
1975
+ lastSweep = now;
1976
+ sweep(root, now);
1977
+ const old = Object.entries(q.j.receipts ?? {}).filter(([, r]) => now - r.at > RECEIPT_MS);
1978
+ if (old.length) await q.lock(() => {
1979
+ for (const [k] of old) delete q.j.receipts[k];
1980
+ q.persist();
1981
+ });
1982
+ const held = new Set(open().flatMap((b) => [b.offer?.conn, b.claim?.conn]).filter(Boolean));
1983
+ for (const c of listConns(root)) if (!held.has(c.id) && (c.ended || !alive(c, now)) && now - c.seen > 6e4) closeConn(root, c.id);
1984
+ }
1985
+ };
1986
+ /** the session that takes new work now and its room for more (F3, F4) - `record`: a session's record (F5) */
1987
+ const roomOf = (now = Date.now(), record = false) => {
1988
+ const s = settings();
1989
+ const sel = sessionsOn(s, record ? "record" : void 0) ? selected(now) : void 0;
1990
+ return sel && offerable(sel) ? {
1991
+ conn: sel,
1992
+ room: Math.max(0, maxOf(sel) - load(sel.id))
1993
+ } : void 0;
1994
+ };
1995
+ return {
1996
+ settings: () => {
1997
+ const sel = selected();
1998
+ return settingsOf(root, d.cfg, sel?.agent);
552
1999
  },
553
- earlyText(line) {
554
- try {
555
- const o = JSON.parse(line);
556
- if (o.type !== "message_end") return null;
557
- const a = assistantText(o.message);
558
- return a?.text && !a.error ? {
559
- text: a.text,
560
- model: a.model
561
- } : null;
562
- } catch {
563
- return null;
2000
+ room: (now) => roomOf(now)?.room ?? 0,
2001
+ taker: (now) => {
2002
+ const r = roomOf(now);
2003
+ return r && r.room > 0 ? r.conn : void 0;
2004
+ },
2005
+ takes: roomOf,
2006
+ selected,
2007
+ choose,
2008
+ run,
2009
+ tick,
2010
+ title: titleOf,
2011
+ delivered(batchId, ok, note) {
2012
+ outcome.set(batchId, {
2013
+ ok,
2014
+ ...note ? { note } : {}
2015
+ });
2016
+ if (outcome.size > 200) outcome.delete(outcome.keys().next().value);
2017
+ const rs = deliveries.get(batchId);
2018
+ if (rs) {
2019
+ deliveries.delete(batchId);
2020
+ for (const r of rs) r({
2021
+ ok,
2022
+ note
2023
+ });
564
2024
  }
565
2025
  },
566
- parse(stdout, code) {
567
- let last = null;
568
- let fromEnd = false;
569
- let failed = false;
570
- for (const line of stdout.split("\n")) {
571
- const t = line.trim();
572
- if (!t) continue;
573
- try {
574
- const o = JSON.parse(t);
575
- if (o.type === "agent_end" && Array.isArray(o.messages)) for (let i = o.messages.length - 1; i >= 0; i--) {
576
- const a = assistantText(o.messages[i]);
577
- if (a) {
578
- last = a;
579
- fromEnd = true;
580
- break;
581
- }
582
- }
583
- else if (o.type === "message_end" && !fromEnd) {
584
- const a = assistantText(o.message);
585
- if (a) last = a;
586
- } else if (o.type === "error") failed = true;
587
- } catch {}
2026
+ async act(batchId, gen, action) {
2027
+ let out = { ok: true };
2028
+ let check = false;
2029
+ await q.lock(() => {
2030
+ const b = byId(batchId);
2031
+ const c = b?.claim;
2032
+ if (!b || !c || c.gen !== gen) {
2033
+ out = {
2034
+ ok: false,
2035
+ error: "the run changed - look again"
2036
+ };
2037
+ return;
2038
+ }
2039
+ if (c.result !== void 0) {
2040
+ out = {
2041
+ ok: false,
2042
+ error: "it just finished - its reply is being posted"
2043
+ };
2044
+ return;
2045
+ }
2046
+ if (action === "again") {
2047
+ c.progress = Date.now();
2048
+ delete c.stalled;
2049
+ delete c.stopping;
2050
+ c.resumed = true;
2051
+ } else {
2052
+ c.stopping = action;
2053
+ delete c.stalled;
2054
+ delete c.resumed;
2055
+ check = true;
2056
+ }
2057
+ q.persist();
2058
+ });
2059
+ if (!out.ok) return out;
2060
+ if (check) {
2061
+ const c = byId(batchId)?.claim;
2062
+ if (c && writerGone(c)) await finishStop(batchId);
588
2063
  }
589
- if (last?.error) failed = true;
590
- const { reply, asks, reanchors, said } = parseAgentText(last?.text ?? "");
2064
+ publish();
2065
+ d.changed();
2066
+ return out;
2067
+ },
2068
+ view(now = Date.now()) {
2069
+ const sel = selected(now);
2070
+ return { sessions: live(now).map((c) => ({
2071
+ id: c.id,
2072
+ agent: c.agent,
2073
+ busy: c.busy,
2074
+ selected: c.id === sel?.id,
2075
+ since: c.since,
2076
+ ...c.mode ? { mode: c.mode } : {}
2077
+ })) };
2078
+ },
2079
+ runnerOf(b) {
2080
+ if (!b?.runner) return void 0;
2081
+ const state = b.offer ? "offered" : b.claim?.stopping ? "stopping" : b.claim?.stalled ? "stalled" : b.claim ? "claimed" : b.runner.kind === "session" ? "waiting" : void 0;
591
2082
  return {
592
- reply,
593
- model: last?.model,
594
- asks,
595
- reanchors,
596
- said,
597
- ok: code === 0 && !failed && !!reply
2083
+ kind: b.runner.kind,
2084
+ agent: b.runner.agent,
2085
+ batch: b.batchId,
2086
+ ...b.claim ? { gen: b.claim.gen } : {},
2087
+ ...b.claim?.stalls ? { stalls: b.claim.stalls } : {},
2088
+ ...state ? { state } : {},
2089
+ ...b.runner.why ? { why: b.runner.why } : {}
598
2090
  };
2091
+ },
2092
+ stop() {
2093
+ stopped = true;
2094
+ for (const w of waiters.values()) w(null);
2095
+ waiters.clear();
599
2096
  }
600
- }
601
- };
2097
+ };
2098
+ }
602
2099
  //#endregion
603
2100
  //#region src/server/jam/daemon.ts
604
2101
  /**
@@ -624,8 +2121,14 @@ const JOB_TIMEOUT_MS = 6e5;
624
2121
  const MAX_ATTEMPTS = 2;
625
2122
  const MAX_OUT = 2e6;
626
2123
  const RESCAN_MS = 5e3;
627
- /** How often a card held by a chat agent's `work start` looks again. */
2124
+ /** How often the queue looks again while a card waits in it - held by a chat agent's `work start`, or by anything else. */
628
2125
  const HOLD_RECHECK_MS = 2e3;
2126
+ /** What each tool's sandbox holds, as a spawned run is told it - only what it really does (spec 29b v2, 24). */
2127
+ const SANDBOX_SAYS = {
2128
+ claude: "the repo is writable, keys are not readable, no network",
2129
+ codex: "the repo is writable, no network; Codex's reviewer judges anything more",
2130
+ cursor: "the repo is writable, no network"
2131
+ };
629
2132
  /** Kill a whole process group (the child is detached, so pid === pgid). Best-effort. */
630
2133
  const fenceGroup = (pid) => {
631
2134
  try {
@@ -647,8 +2150,11 @@ const fenceGroup = (pid) => {
647
2150
  * option that quietly grows back.
648
2151
  */
649
2152
  function agentEnv(from = process.env) {
650
- const { MARVER_CLI_TOKEN: _withheld, ...rest } = from;
651
- return rest;
2153
+ const { MARVER_CLI_TOKEN: _withheld, CLAUDE_CODE_MESSAGING_SOCKET: _s, CLAUDE_CODE_MESSAGING_TOKEN: _t, CLAUDE_CODE_SESSION_ID: _i, CLAUDE_PID: _p, CLAUDE_CODE_SESSION_ATTENDED: _a, CODEX_THREAD_ID: _ct, CODEX_SESSION_ID: _cs, ...rest } = from;
2154
+ return {
2155
+ ...rest,
2156
+ MARVER_JAM_BACKGROUND: "1"
2157
+ };
652
2158
  }
653
2159
  const FRAME_FILE = /\.(tsx|jsx|html)$/;
654
2160
  /** Every frame FILE under design/scenes, as `frame id -> mtimeMs`. Used to see which frames the
@@ -703,11 +2209,13 @@ const sharedMtimes = (root) => {
703
2209
  }
704
2210
  return out;
705
2211
  };
706
- /** A `shared` file as the disk sees it: past the lexical check (any case - this filesystem may not
707
- * care), its nearest existing ancestor must resolve inside design/, and the resolved path must
708
- * still be shared design source - a symlink cannot alias local state, a board file or the outside. */
709
- function canonicalShared(root, f) {
710
- if (!sharedFile(f) || !sharedFile(f.toLowerCase())) return null;
2212
+ /** Why a `shared` file is refused as the disk sees it, or null: past the lexical check (any case - this filesystem
2213
+ * may not care), its nearest existing ancestor must resolve inside design/, and the resolved path must still be
2214
+ * shared design source - a symlink cannot alias local state, a board file or the outside. The reason is the
2215
+ * validator's own (the owner reads it, F1). */
2216
+ function canonicalSharedWhy(root, f) {
2217
+ const lexical = sharedWhy(f) ?? sharedWhy(f.toLowerCase());
2218
+ if (lexical) return lexical;
711
2219
  try {
712
2220
  const design = realpathSync(join(root, "design"));
713
2221
  let at = join(root, f);
@@ -720,12 +2228,18 @@ function canonicalShared(root, f) {
720
2228
  at = dirname(at);
721
2229
  }
722
2230
  const rel = relative(design, join(realpathSync(at), ...tail));
723
- if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null;
724
- return sharedFile(`design/${rel.split(sep).join("/")}`.toLowerCase()) ? f : null;
2231
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) return "it is a link that leads outside the design folder";
2232
+ const to = `design/${rel.split(sep).join("/")}`;
2233
+ const why = sharedWhy(to.toLowerCase());
2234
+ return why ? `it is a link to ${to}, and ${why}` : null;
725
2235
  } catch {
726
- return null;
2236
+ return "it is a link that leads nowhere";
727
2237
  }
728
2238
  }
2239
+ /** A `shared` file as the disk sees it (`canonicalSharedWhy` found nothing against it), else null. */
2240
+ function canonicalShared(root, f) {
2241
+ return canonicalSharedWhy(root, f) ? null : f;
2242
+ }
729
2243
  /** The loop, without timers/watch/lock. Loads the queue (upgrading a v1 journal, baselining a
730
2244
  * fresh one); the first `tick()` recovers what a dead process left (the startup barrier), and
731
2245
  * every tick ingests, claims what can run and waits until the work is idle. */
@@ -754,8 +2268,9 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
754
2268
  const runningBatches = /* @__PURE__ */ new Map();
755
2269
  /** every run that starts, counted: a run knows whether another began while it ran */
756
2270
  let batchStarts = 0;
757
- const runAgent = (goal, onSpawn, onEarly) => new Promise((resolve) => {
758
- const { cmd, args, env } = adapter.spawnArgs(goal);
2271
+ const runAgent = (ad, opts, goal, onSpawn, onEarly) => new Promise((resolve) => {
2272
+ const adapter = ad;
2273
+ const { cmd, args, env } = adapter.spawnArgs(goal, opts);
759
2274
  let child;
760
2275
  try {
761
2276
  child = spawn(cmd, args, {
@@ -856,6 +2371,8 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
856
2371
  /** House style: never an em/en dash in a reply - a plain dash reads human. */
857
2372
  const plainDashes = (s) => s.replace(/\s*[—–]\s*/g, " - ");
858
2373
  const me = () => localProfile(root);
2374
+ /** The agent that ran a batch - its runner's, or the one Jam is set to. */
2375
+ const harnessOf = (b) => b.runner?.agent || adapter.name;
859
2376
  /** Post one reply in a card's thread. Deterministic ids - `jam-<batch>-<member>` for the reply,
860
2377
  * `jam-e<attempt>-<batch>` for a one-member job's early ack - so posting twice is a no-op. */
861
2378
  const postReply = (b, c, member, body, asks, model, kind = "reply", alsoChanged) => {
@@ -875,8 +2392,9 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
875
2392
  agent: true,
876
2393
  agentMeta: {
877
2394
  devUser: who.name,
878
- harness: adapter.name,
879
- model
2395
+ harness: harnessOf(b),
2396
+ model,
2397
+ ...b.runner ? { runner: b.runner.kind } : {}
880
2398
  }
881
2399
  };
882
2400
  appendEvents(commentsDir, c.board, [reply]);
@@ -885,6 +2403,131 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
885
2403
  ts: reply.ts
886
2404
  };
887
2405
  };
2406
+ /** How a spawned run reaches this marver (`jam permit`): the repo's install, else the CLI running now. */
2407
+ const marverCmd = () => {
2408
+ const bin = hookBin(root);
2409
+ if (bin) return {
2410
+ cmd: bin,
2411
+ args: []
2412
+ };
2413
+ const here = dirname(fileURLToPath(import.meta.url));
2414
+ const self = [
2415
+ join(here, "cli.mjs"),
2416
+ join(here, "..", "cli.mjs"),
2417
+ join(here, "..", "..", "cli", "index.ts")
2418
+ ].find((f) => existsSync(f));
2419
+ return self ? {
2420
+ cmd: process.execPath,
2421
+ args: [self]
2422
+ } : {
2423
+ cmd: "npx",
2424
+ args: ["--no-install", "marver"]
2425
+ };
2426
+ };
2427
+ const runs = createRuns({
2428
+ root,
2429
+ cfg,
2430
+ q,
2431
+ log,
2432
+ changed: () => {
2433
+ queueChanged();
2434
+ pumpSoon();
2435
+ },
2436
+ goal: (b, handle, conn) => {
2437
+ const as = conn.agent === "cursor" ? conn.id : void 0;
2438
+ let packet = null;
2439
+ try {
2440
+ packet = JSON.parse(readFileSync(join(root, packetPath(b.batchId)), "utf8"));
2441
+ } catch {
2442
+ packet = null;
2443
+ }
2444
+ if (packet && packet.frames.join("\n") !== b.frames.join("\n")) {
2445
+ packet.frames = [...b.frames];
2446
+ writeFileSync(join(root, packetPath(b.batchId)), JSON.stringify(packet, null, 1), { mode: 384 });
2447
+ }
2448
+ return packet ? sessionBrief(packet, handle, as, {
2449
+ agent: conn.agent,
2450
+ conn: conn.id,
2451
+ overlaps: overlapsOf(b, conn)
2452
+ }) : `The packet of this run is missing (${packetPath(b.batchId)}) - release it: \`npx marver jam release ${handle}${as ? ` --as ${as}` : ""}\`.`;
2453
+ },
2454
+ say: (b) => ensureEarly(b),
2455
+ ready: () => ready,
2456
+ jamOn: () => !!q.j.session,
2457
+ canSpawn: (agent) => Object.hasOwn(AGENT_BIN, agent) && onPath(AGENT_BIN[agent]),
2458
+ own: (b, frame) => {
2459
+ if (!/^[\w.@+-]+(\/[\w.@+-]+)+$/.test(frame)) return "name a frame: <scene>/<name>";
2460
+ if (b.frames.includes(frame)) return null;
2461
+ if ([...runningBatches.values()].find((x) => x.batchId !== b.batchId && x.frames.includes(frame))) return `another run is working on ${frame} - make the variant a frame of its own`;
2462
+ if (hooks.held?.(frame)) return `your agent in chat is working on ${frame}`;
2463
+ b.frames = [...b.frames, frame];
2464
+ if (!(b.before ?? []).includes(frame)) {
2465
+ b.created = [.../* @__PURE__ */ new Set([...b.created ?? [], frame])];
2466
+ madeScene(b, frame);
2467
+ }
2468
+ reserve();
2469
+ return null;
2470
+ },
2471
+ mayHold: (b, conn) => [...runningBatches.values()].every((x) => x.batchId === b.batchId || !x.frames.some((f) => b.frames.includes(f)) || heldBy(x, conn))
2472
+ });
2473
+ /** A frame a run made, given to it or found as its own, in a scene that was not there when it began and that no other run
2474
+ * made first: the scene is this run's (F5) - its `_` files are no shared file it changed. Under the lock. */
2475
+ function madeScene(b, frame) {
2476
+ const sc = frame.split("/")[0];
2477
+ if (!b.scenes || b.scenes.includes(sc) || q.j.batches.some((x) => x.madeScenes?.includes(sc))) return;
2478
+ b.madeScenes = [...b.madeScenes ?? [], sc];
2479
+ }
2480
+ /** Is a running batch this session incarnation's (F4): offered to it, taken by it and not stopping, or formed for it -
2481
+ * or done editing (its results saved, being posted)? Two such runs may share a frame: the session coordinates them.
2482
+ * Who runs it now decides: one Marver spawned is never a session's, whatever it was formed for (Codex's review: let go
2483
+ * of and spawned, it kept `share`, and a request on its frame went to your session beside it - a journal from before
2484
+ * `share` was cleared on a spawn too) */
2485
+ function heldBy(x, c) {
2486
+ if (x.results) return true;
2487
+ if (x.handoff || x.runner && x.runner.kind !== "session") return false;
2488
+ return !!x.offer && x.offer.conn === c.id && x.offer.inc === c.inc || !!x.claim && x.claim.conn === c.id && x.claim.inc === c.inc && !x.claim.stopping || !!x.share && x.share.conn === c.id && x.share.inc === c.inc && !x.offer && !x.claim;
2489
+ }
2490
+ /** The runs of this same session incarnation that share a frame with `b` (F4) - named in its brief: their handle (or,
2491
+ * offered and not taken yet, their short id), the frames they share, their title. */
2492
+ const overlapsOf = (b, conn) => q.j.batches.filter((x) => x.batchId !== b.batchId && x.state === "claimed" && !x.results && x.frames.some((f) => b.frames.includes(f)) && (x.claim && x.claim.conn === conn.id && x.claim.inc === conn.inc || x.offer && x.offer.conn === conn.id && x.offer.inc === conn.inc)).map((x) => ({
2493
+ handle: x.claim ? handleOf(x, x.claim.gen) : `${x.batchId.slice(0, 8)} (offered, not taken yet)`,
2494
+ frames: x.frames.filter((f) => b.frames.includes(f)),
2495
+ title: runs.title(x)
2496
+ }));
2497
+ /** A session's early line (`marver jam say`), journaled on the batch before it is posted: posted with the id it
2498
+ * names, once - an id already in the log is not posted again (a restart between the two posts it then). */
2499
+ const ensureEarly = (b) => {
2500
+ const e = b.early;
2501
+ const one = b.members.length === 1 ? q.j.cards.find((c) => c.id === b.members[0].card) : void 0;
2502
+ if (!e || !one?.thread || stopped) return false;
2503
+ const id = e.commentId.replace(/^jam-c-/, "jam-");
2504
+ try {
2505
+ if (!readLog(commentsDir, one.board).some((x) => x.id === id)) {
2506
+ const who = me();
2507
+ appendEvents(commentsDir, one.board, [{
2508
+ id,
2509
+ ts: e.ts,
2510
+ type: "reply",
2511
+ commentId: e.commentId,
2512
+ parentId: one.thread,
2513
+ board: one.board,
2514
+ author: who,
2515
+ body: plainDashes(e.body),
2516
+ asks: false,
2517
+ agent: true,
2518
+ agentMeta: {
2519
+ devUser: who.name,
2520
+ harness: harnessOf(b),
2521
+ ...b.runner ? { runner: b.runner.kind } : {}
2522
+ }
2523
+ }]);
2524
+ }
2525
+ hooks.changed?.(one.board);
2526
+ return true;
2527
+ } catch {
2528
+ return false;
2529
+ }
2530
+ };
888
2531
  /** Emit reanchor events for threads the agent re-pinned, in the shared anchor format: each
889
2532
  * element found in the rendered frame the way `comments move` finds it, unchecked when the
890
2533
  * check cannot run, skipped when the frame shows no such element or several. Owner-authored +
@@ -928,7 +2571,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
928
2571
  agent: true,
929
2572
  agentMeta: {
930
2573
  devUser: who.name,
931
- harness: adapter.name
2574
+ harness: harnessOf(b)
932
2575
  }
933
2576
  }]);
934
2577
  n++;
@@ -1081,7 +2724,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1081
2724
  agent: true,
1082
2725
  agentMeta: {
1083
2726
  devUser: who.name,
1084
- harness: adapter.name
2727
+ harness: harnessOf(b)
1085
2728
  }
1086
2729
  }]);
1087
2730
  }
@@ -1131,11 +2774,19 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1131
2774
  const changedBoards = (b) => {
1132
2775
  for (const board of new Set(b.members.map((m) => m.board))) hooks.changed?.(board);
1133
2776
  };
2777
+ /** The session that takes the work now and its room - `record`: the one a session's record goes to (F5) - looked at once */
2778
+ const takersNow = () => {
2779
+ let on;
2780
+ return (record) => (on ??= [runs.takes(), runs.takes(void 0, true)])[record ? 1 : 0];
2781
+ };
2782
+ /** Does a queued card run alone now (queue.ts runsAlone), with the session that takes the work as it is now (F5) */
2783
+ const aloneNow = (taking = takersNow()) => (c) => runsAlone(c, (record) => !!taking(record));
1134
2784
  const reserve = (exclusiveWaiting) => {
1135
2785
  if (stopped) return;
1136
2786
  jamReservations.frames = new Map([...runningBatches.values()].flatMap((b) => b.frames.map((f) => [f, b.batchId])));
1137
2787
  const exclusiveRunning = [...runningBatches.values()].some((b) => b.exclusive);
1138
- jamReservations.exclusive = exclusiveRunning ? "running" : exclusiveWaiting ?? q.j.cards.some((c) => c.state === "queued" && (c.exclusive || !c.frames.length)) ? "waiting" : null;
2788
+ const alone = aloneNow();
2789
+ jamReservations.exclusive = exclusiveRunning ? "running" : exclusiveWaiting ?? q.j.cards.some((c) => c.state === "queued" && alone(c)) ? "waiting" : null;
1139
2790
  jamReservations.settling = !ready || delivering.size > 0;
1140
2791
  };
1141
2792
  const queueChanged = () => {
@@ -1153,6 +2804,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1153
2804
  * one would have. */
1154
2805
  const deliver = async (b) => {
1155
2806
  if (stopped) return;
2807
+ if (b.early && !ensureEarly(b)) throw new Error("its early line could not be posted");
1156
2808
  const cards = b.members.map((m) => q.j.cards.find((c) => c.id === m.card)).filter((c) => !!c);
1157
2809
  const early = b.early;
1158
2810
  const posted = {};
@@ -1178,7 +2830,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1178
2830
  agent: true,
1179
2831
  agentMeta: {
1180
2832
  devUser: who.name,
1181
- harness: adapter.name
2833
+ harness: harnessOf(b)
1182
2834
  }
1183
2835
  }]);
1184
2836
  }
@@ -1195,7 +2847,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1195
2847
  agent: true,
1196
2848
  agentMeta: {
1197
2849
  devUser: who.name,
1198
- harness: adapter.name
2850
+ harness: harnessOf(b)
1199
2851
  }
1200
2852
  }]);
1201
2853
  }
@@ -1313,7 +2965,12 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1313
2965
  const { wrapup: _w, ...rest } = brief;
1314
2966
  brief = rest;
1315
2967
  }
2968
+ if (b.others === void 0 || b.others && !runs.settings().others) {
2969
+ brief = ownerOnly(brief, me());
2970
+ m.brief = brief;
2971
+ }
1316
2972
  const t = c.thread ? threadsOf(m.board).find((x) => x.id === c.thread) : void 0;
2973
+ const pictures = packetPictures(root, brief);
1317
2974
  members.push({
1318
2975
  id: m.id,
1319
2976
  card: c.id,
@@ -1322,19 +2979,15 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1322
2979
  ...c.thread ? { thread: c.thread } : {},
1323
2980
  frames: c.frames,
1324
2981
  ...t?.anchor !== void 0 ? { anchor: t.anchor } : {},
1325
- brief
2982
+ brief,
2983
+ ...pictures.length ? { pictures } : {}
1326
2984
  });
1327
2985
  }
1328
2986
  if (bad.length) {
1329
2987
  await q.lock((j) => {
1330
2988
  for (const id of bad) {
1331
2989
  const c = j.cards.find((x) => x.id === id);
1332
- if (c && c.state === "working") {
1333
- c.state = "failed";
1334
- c.note = c.kind === "wrapup" ? "the session record changed after it was written - write it again" : "interrupted - Retry";
1335
- c.rev += 1;
1336
- c.at = Date.now();
1337
- }
2990
+ if (c && c.state === "working") failCard(j, c, c.kind === "wrapup" ? "the session record changed after it was written - write it again" : "interrupted - Retry", Date.now());
1338
2991
  }
1339
2992
  q.persist();
1340
2993
  });
@@ -1351,7 +3004,11 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1351
3004
  }
1352
3005
  }
1353
3006
  const packet = buildPacket(b.batchId, members, b.frames, b.exclusive ? [...new Set(cards0(b).flatMap((c) => c.exclusive ?? []))] : void 0);
1354
- writeFileSync(join(root, packetPath(b.batchId)), JSON.stringify(packet, null, 1), { mode: 384 });
3007
+ const writePacket = () => {
3008
+ packet.frames = [...b.frames];
3009
+ writeFileSync(join(root, packetPath(b.batchId)), JSON.stringify(packet, null, 1), { mode: 384 });
3010
+ };
3011
+ writePacket();
1355
3012
  const cards = () => b.members.map((m) => q.j.cards.find((c) => c.id === m.card)).filter((c) => !!c);
1356
3013
  const lit = /* @__PURE__ */ new Set();
1357
3014
  const light = (f) => {
@@ -1365,9 +3022,12 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1365
3022
  lit.clear();
1366
3023
  };
1367
3024
  const startMtimes = sceneFrameMtimes(root);
3025
+ const sharedBefore = b.exclusive ? null : sharedMtimes(root);
3026
+ const sceneOf = (f) => /^design\/scenes\/([^/]+)\//.exec(f)?.[1];
1368
3027
  await q.lock(() => {
1369
3028
  const made = new Set(b.created ?? []);
1370
3029
  b.before = [.../* @__PURE__ */ new Set([...b.before ?? [], ...[...startMtimes.keys()].filter((f) => !made.has(f))])];
3030
+ if (sharedBefore && !b.scenes) b.scenes = [.../* @__PURE__ */ new Set([...[...sharedBefore.keys()].flatMap((f) => sceneOf(f) ?? []), ...[...startMtimes.keys()].map((f) => f.split("/")[0])])];
1371
3031
  q.persist();
1372
3032
  });
1373
3033
  if (crowded || !aloneAtStart) await q.lock(() => {
@@ -1382,11 +3042,11 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1382
3042
  await q.lock(() => {
1383
3043
  b.created = [...b.created ?? [], ...found];
1384
3044
  b.frames = [.../* @__PURE__ */ new Set([...b.frames, ...b.created])];
3045
+ for (const f of found) madeScene(b, f);
1385
3046
  q.persist();
1386
3047
  });
1387
3048
  reserve();
1388
3049
  };
1389
- const sharedBefore = b.exclusive ? null : sharedMtimes(root);
1390
3050
  const touched = /* @__PURE__ */ new Set();
1391
3051
  for (const f of b.frames) light(f);
1392
3052
  const capturing = cards().some((c) => !!c.capture);
@@ -1402,7 +3062,10 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1402
3062
  if (stopped) return;
1403
3063
  if (s.new) continue;
1404
3064
  const id = await hooks.shoot(s.frame, theme, { batch: b.batchId }, sizes[s.frame]).catch(() => null);
1405
- if (id) s[when] = id;
3065
+ if (id) {
3066
+ s[when] = id;
3067
+ if (when === "before") s.beforeAt = Date.now();
3068
+ }
1406
3069
  }
1407
3070
  if (when === "after") for (const s of shots) if (s.before && s.after && samePicture(s.before, s.after)) s.same = true;
1408
3071
  else delete s.same;
@@ -1431,50 +3094,213 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1431
3094
  reanchors: []
1432
3095
  };
1433
3096
  try {
1434
- while (!stopped && b.attempts < MAX_ATTEMPTS) {
3097
+ if (!b.power) {
3098
+ const s0 = runs.settings();
1435
3099
  await q.lock(() => {
1436
- b.attempts += 1;
1437
- b.leaseUntil = Date.now() + LEASE_MS;
3100
+ b.power = {
3101
+ mcp: s0.mcp,
3102
+ skills: s0.skills
3103
+ };
1438
3104
  q.persist();
1439
3105
  });
1440
- for (const m of packet.members) if (m.kind === "wrapup") {
1441
- const c = q.j.cards.find((x) => x.id === m.card);
1442
- const w = c && readWrapup(root, wrapupOf(c));
1443
- 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");
1444
- m.brief = {
1445
- ...m.brief,
1446
- wrapup: {
1447
- content: w.wrapup,
1448
- hash: w.hash
1449
- }
1450
- };
1451
- }
1452
- writeFileSync(join(root, packetPath(b.batchId)), JSON.stringify(packet, null, 1), { mode: 384 });
3106
+ }
3107
+ if (b.dropped) {
3108
+ await q.lock((j) => {
3109
+ settled(fail(j, b, "you dropped it while your session had it"));
3110
+ q.persist();
3111
+ });
3112
+ runs.delivered(b.batchId, false, "the owner dropped it");
3113
+ queueChanged();
3114
+ timeRun("agent");
3115
+ return;
3116
+ }
3117
+ let sessionRan = false;
3118
+ const spawnedBefore = b.runner && b.runner.kind !== "session" ? b.runner : void 0;
3119
+ const sessionHeld = !spawnedBefore && !b.handoff && (!!b.claim || !!b.offer || b.runner?.kind === "session");
3120
+ let first = sessionHeld ? { kind: "wait" } : spawnedBefore || b.handoff ? {
3121
+ kind: "fresh",
3122
+ agent: ""
3123
+ } : runs.choose(b);
3124
+ const passedOver = !sessionHeld && !spawnedBefore && !b.handoff && (first.kind === "fork" || first.kind === "fresh") ? first.why : void 0;
3125
+ if (b.early && b.claim) ensureEarly(b);
3126
+ while (!spawnedBefore && !b.handoff && (sessionHeld || first.kind === "session" || first.kind === "wait")) {
1453
3127
  const beat = setInterval(followWork, 2e3);
1454
3128
  beat.unref?.();
1455
3129
  const tAgent = performance.now();
3130
+ let r;
1456
3131
  try {
1457
- const one = b.members.length === 1 ? cards()[0] : void 0;
1458
- run = await runAgent(goalText(packet, cfg.subagents && adapter.supportsSubagents), (pid) => {
1459
- b.pgid = pid;
1460
- q.persist();
1461
- }, one?.thread ? (text, asks, model) => {
1462
- if (stopped) return;
1463
- const p = postReply(b, one, "m1", text, asks, model, "early");
1464
- early = {
1465
- body: text,
1466
- asks,
1467
- commentId: p.commentId,
1468
- ts: p.ts
1469
- };
1470
- hooks.changed?.(one.board);
1471
- } : void 0);
3132
+ r = await runs.run(b, first.kind === "session" ? first.conn : void 0);
1472
3133
  } finally {
1473
3134
  clearInterval(beat);
1474
3135
  timing.agentMs.push(performance.now() - tAgent);
1475
3136
  }
1476
- logRun(b.batchId, run.raw);
1477
- if (run.ok) break;
3137
+ if (stopped) return;
3138
+ if (b.dropped) {
3139
+ await q.lock((j) => {
3140
+ settled(fail(j, b, "you dropped it while your session had it"));
3141
+ q.persist();
3142
+ });
3143
+ runs.delivered(b.batchId, false, "the owner dropped it");
3144
+ queueChanged();
3145
+ timeRun("agent");
3146
+ return;
3147
+ }
3148
+ if (r) {
3149
+ run = r;
3150
+ sessionRan = true;
3151
+ break;
3152
+ }
3153
+ first = { kind: "wait" };
3154
+ }
3155
+ if (!sessionRan) {
3156
+ let none = false;
3157
+ if (await q.lock((j) => {
3158
+ none = !b.exclusive && !b.frames.length;
3159
+ if (b.handoff !== "queue" && !none && ![...runningBatches.values()].some((o) => o.batchId !== b.batchId && o.frames.some((f) => b.frames.includes(f)))) return false;
3160
+ const spawn = b.handoff === "spawn" || !!spawnedBefore;
3161
+ const why = b.handoffWhy ?? spawnedBefore?.why;
3162
+ const shots = (b.shots ?? []).flatMap((s) => !s.new && s.before ? [{
3163
+ frame: s.frame,
3164
+ before: s.before,
3165
+ ...s.beforeAt ? { at: s.beforeAt } : {}
3166
+ }] : []);
3167
+ const created = b.members.length === 1 ? b.created ?? [] : [];
3168
+ for (const m of b.members) {
3169
+ const c = j.cards.find((x) => x.id === m.card);
3170
+ if (!c || c.state !== "working" || c.batch !== b.batchId) continue;
3171
+ const add = b.frames.filter((f) => !c.frames.includes(f));
3172
+ if (add.length) c.frames = [...c.frames, ...add];
3173
+ const t = requeue(j, c, Date.now());
3174
+ t.alone = joinAlone(t.alone, {
3175
+ ...spawn ? { spawn: true } : {},
3176
+ ...why ? { why } : {},
3177
+ ...created.length ? { created: [...created] } : {},
3178
+ ...shots.length ? { shots: shots.map((s) => ({ ...s })) } : {}
3179
+ });
3180
+ }
3181
+ b.state = "done";
3182
+ b.at = Date.now();
3183
+ b.note = none ? "back in the queue - with no frame, it runs alone" : "back in the queue - another runner holds one of its frames";
3184
+ q.persist();
3185
+ return true;
3186
+ })) {
3187
+ log(none ? " jam: a run with no frame went back to the queue - it runs alone once the other work is done" : " jam: a run went back to the queue - another runner holds one of its frames; it starts when they are free");
3188
+ queueChanged();
3189
+ timeRun("other");
3190
+ return;
3191
+ }
3192
+ const ch = spawnedBefore ? {
3193
+ kind: spawnedBefore.kind,
3194
+ agent: spawnedBefore.agent,
3195
+ ...spawnedBefore.session ? { session: spawnedBefore.session } : {},
3196
+ ...spawnedBefore.why ? { why: spawnedBefore.why } : {}
3197
+ } : (() => {
3198
+ const pick = runs.choose(b, Date.now(), true);
3199
+ const p = pick.kind === "fork" || pick.kind === "fresh" ? pick : {
3200
+ kind: "fresh",
3201
+ agent: cfg.agent
3202
+ };
3203
+ const why = b.handoffWhy === "not taken in 2 minutes" || b.handoffWhy === "its turn ended without taking it" ? "your session didn't take it - it was busy or away" : b.handoffWhy === "your session let it go" ? "your session didn't take it - it let it go" : b.handoffWhy?.startsWith("your session didn't take it") ? b.handoffWhy : b.handoffWhy === "the Jam session ended" ? "the Jam session had ended" : passedOver;
3204
+ return why && !("why" in p && p.why) ? {
3205
+ ...p,
3206
+ why
3207
+ } : p;
3208
+ })();
3209
+ const agent = Object.hasOwn(adapters, ch.agent) ? ch.agent : cfg.agent;
3210
+ const ad = agent === cfg.agent ? adapter : adapters[agent];
3211
+ const s = {
3212
+ mcp: b.power?.mcp ?? true,
3213
+ skills: b.power?.skills ?? true
3214
+ };
3215
+ const full = agent === "claude" || agent === "codex" || agent === "cursor";
3216
+ const opts = full ? {
3217
+ root,
3218
+ mcp: s.mcp,
3219
+ skills: s.skills,
3220
+ ...ch.kind === "fork" && ch.session ? { fork: ch.session } : {},
3221
+ marver: marverCmd()
3222
+ } : void 0;
3223
+ await q.lock(() => {
3224
+ b.runner = {
3225
+ kind: ch.kind,
3226
+ agent,
3227
+ ...ch.kind === "fork" && ch.session ? { session: ch.session } : {},
3228
+ ...ch.why ? { why: ch.why } : {}
3229
+ };
3230
+ delete b.handoff;
3231
+ delete b.share;
3232
+ q.persist();
3233
+ });
3234
+ queueChanged();
3235
+ const permit = await takePermit();
3236
+ try {
3237
+ while (!stopped && b.attempts < MAX_ATTEMPTS) {
3238
+ await q.lock(() => {
3239
+ b.attempts += 1;
3240
+ b.leaseUntil = Date.now() + LEASE_MS;
3241
+ q.persist();
3242
+ });
3243
+ for (const m of packet.members) if (m.kind === "wrapup") {
3244
+ const c = q.j.cards.find((x) => x.id === m.card);
3245
+ const w = c && readWrapup(root, wrapupOf(c));
3246
+ 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");
3247
+ m.brief = {
3248
+ ...m.brief,
3249
+ wrapup: {
3250
+ content: w.wrapup,
3251
+ hash: w.hash
3252
+ }
3253
+ };
3254
+ }
3255
+ writePacket();
3256
+ const beat = setInterval(followWork, 2e3);
3257
+ beat.unref?.();
3258
+ const tAgent = performance.now();
3259
+ try {
3260
+ const one = b.members.length === 1 ? cards()[0] : void 0;
3261
+ const forked = b.runner?.kind === "fork" ? b.runner.session : void 0;
3262
+ const goal = goalText(packet, cfg.subagents && ad.supportsSubagents, full ? {
3263
+ kind: forked ? "fork" : "fresh",
3264
+ shell: true,
3265
+ mcp: s.mcp,
3266
+ skills: s.skills,
3267
+ sandbox: SANDBOX_SAYS[agent]
3268
+ } : void 0);
3269
+ run = await runAgent(ad, opts && {
3270
+ ...opts,
3271
+ fork: forked
3272
+ }, goal, (pid) => {
3273
+ b.pgid = pid;
3274
+ q.persist();
3275
+ }, one?.thread && !b.early ? (text, asks, model) => {
3276
+ if (stopped) return;
3277
+ const p = postReply(b, one, "m1", text, asks, model, "early");
3278
+ early = {
3279
+ body: text,
3280
+ asks,
3281
+ commentId: p.commentId,
3282
+ ts: p.ts
3283
+ };
3284
+ hooks.changed?.(one.board);
3285
+ } : void 0);
3286
+ if (!run.ok && forked) await q.lock(() => {
3287
+ b.runner = {
3288
+ kind: "fresh",
3289
+ agent,
3290
+ why: "the copy of your session could not run - a fresh agent took it"
3291
+ };
3292
+ q.persist();
3293
+ });
3294
+ } finally {
3295
+ clearInterval(beat);
3296
+ timing.agentMs.push(performance.now() - tAgent);
3297
+ }
3298
+ logRun(b.batchId, run.raw);
3299
+ if (run.ok) break;
3300
+ }
3301
+ } finally {
3302
+ permit();
3303
+ }
1478
3304
  }
1479
3305
  if (stopped) return;
1480
3306
  if (!run.ok) {
@@ -1484,6 +3310,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1484
3310
  settled(fail(j, b, "the agent could not finish - its run log is in design/.local/jam-logs"));
1485
3311
  q.persist();
1486
3312
  });
3313
+ runs.delivered(b.batchId, false, "the run failed");
1487
3314
  queueChanged();
1488
3315
  log(` jam: gave up on a batch of ${b.members.length} after ${b.attempts} attempts`);
1489
3316
  timeRun("agent");
@@ -1529,13 +3356,22 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1529
3356
  }
1530
3357
  if (capturing) timing.afterMs = performance.now() - tAfter;
1531
3358
  const split = parseMembers(run.said ?? run.reply, b.members.map((m) => m.id));
1532
- const changedShared = sharedBefore ? [...sharedMtimes(root)].filter(([f, mt]) => sharedBefore.get(f) !== mt).map(([f]) => f) : [];
3359
+ const changedShared = sharedBefore ? [...sharedMtimes(root)].filter(([f, mt]) => {
3360
+ const sc = sceneOf(f);
3361
+ return sharedBefore.get(f) !== mt && !(sc && b.madeScenes?.includes(sc));
3362
+ }).map(([f]) => f) : [];
1533
3363
  const results = {};
1534
3364
  for (const [id, r0] of Object.entries(split)) {
1535
3365
  let r = r0;
1536
3366
  if ("shared" in r) {
1537
3367
  const files = r.shared.map(realShared).filter((f) => !!f);
1538
- r = files.length ? { shared: files } : { missing: true };
3368
+ r = files.length ? { shared: files } : {
3369
+ body: refusedAsk(r.shared.map((f) => ({
3370
+ file: f,
3371
+ why: canonicalSharedWhy(root, f) ?? "it could not be read"
3372
+ }))),
3373
+ asks: true
3374
+ };
1539
3375
  }
1540
3376
  results[id] = "body" in r ? {
1541
3377
  body: r.body,
@@ -1560,8 +3396,10 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1560
3396
  } catch (err) {
1561
3397
  timing.deliverMs = performance.now() - tDeliver;
1562
3398
  timeRun("delivery");
3399
+ runs.delivered(b.batchId, true, "retrying");
1563
3400
  throw err;
1564
3401
  }
3402
+ runs.delivered(b.batchId, true);
1565
3403
  timing.deliverMs = performance.now() - tDeliver;
1566
3404
  timeRun();
1567
3405
  } finally {
@@ -1573,24 +3411,45 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1573
3411
  }
1574
3412
  };
1575
3413
  /** Write a card's pending comment (once - an event already there must say the same, or the step
1576
- * fails closed), ledger it, and end the step. Under the lock; resumable at any point. */
1577
- const finishStep = (id) => q.lock((j) => {
1578
- const c = j.cards.find((x) => x.id === id);
1579
- const p = c?.pending;
1580
- if (!c || !p) return c ? structuredClone(c) : void 0;
3414
+ * fails closed), ledger it, and end the step. Called under the lock, synchronously; resumable at any point. */
3415
+ const finishIn = (j, c) => {
3416
+ const p = c.pending;
3417
+ if (!p) return;
1581
3418
  const there = readLog(commentsDir, c.board).find((e) => e.id === p.event.id);
1582
3419
  if (there && !sameComment(there, p.event)) {
1583
3420
  conflictStep(j, c);
1584
3421
  q.persist();
1585
- return structuredClone(c);
3422
+ return;
1586
3423
  }
1587
3424
  if (!there) appendEvents(commentsDir, c.board, [p.event]);
1588
3425
  record(root, c.board, p.event.id);
1589
3426
  if (p.op === "confirm") record(root, c.board, payloadKey(c));
1590
3427
  settled(endStep(j, c));
1591
3428
  q.persist();
3429
+ };
3430
+ const finishStep = (id) => q.lock((j) => {
3431
+ const c = j.cards.find((x) => x.id === id);
3432
+ if (!c) return void 0;
3433
+ finishIn(j, c);
1592
3434
  return structuredClone(c);
1593
3435
  });
3436
+ /** Where a capture's comment is pinned: on its first point (found in the rendered frame), else its first frame,
3437
+ * else the board. A render - so it is looked up before any lock is taken. */
3438
+ const pinOf = async (record) => {
3439
+ const point = firstPoint(record);
3440
+ let at = { frame: point?.frame ?? captureFrames(record)[0] };
3441
+ if (point?.frame && hooks.anchor) {
3442
+ 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;
3443
+ if (target) {
3444
+ const check = await hooks.anchor(point.frame, target, [], void 0).catch(() => null);
3445
+ if (check?.ok) at = {
3446
+ frame: point.frame,
3447
+ anchor: check.anchor
3448
+ };
3449
+ }
3450
+ }
3451
+ return at;
3452
+ };
1594
3453
  /** Confirm a draft (`end: queued`) or keep it from its read-back (`end: kept`): one recoverable step.
1595
3454
  * A retried request after a lost answer finds the step done and answers with the card. */
1596
3455
  const confirm = async (id, rev, end) => {
@@ -1623,18 +3482,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1623
3482
  card: structuredClone(c0),
1624
3483
  error: "the capture changed after it was sealed"
1625
3484
  };
1626
- const point = firstPoint(cap.record);
1627
- let at = { frame: point?.frame ?? captureFrames(cap.record)[0] };
1628
- if (point?.frame && hooks.anchor) {
1629
- 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;
1630
- if (target) {
1631
- const check = await hooks.anchor(point.frame, target, [], void 0).catch(() => null);
1632
- if (check?.ok) at = {
1633
- frame: point.frame,
1634
- anchor: check.anchor
1635
- };
1636
- }
1637
- }
3485
+ const at = await pinOf(cap.record);
1638
3486
  if (!await q.lock((j) => {
1639
3487
  const c = j.cards.find((x) => x.id === id);
1640
3488
  if (!c || c.state !== "draft" || c.rev !== rev) return null;
@@ -1762,12 +3610,43 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1762
3610
  }
1763
3611
  return r;
1764
3612
  };
3613
+ /** A pump soon, once however often it is asked for, outside whatever lock asks for it. */
3614
+ let pumpDue = null;
3615
+ const pumpSoon = () => {
3616
+ if (pumpDue || stopped) return;
3617
+ pumpDue = setTimeout(() => {
3618
+ pumpDue = null;
3619
+ pump().catch((err) => log(` jam: pump error - ${err.message}`));
3620
+ }, 0);
3621
+ pumpDue.unref?.();
3622
+ };
3623
+ /** Spawned processes at once: never more than jam.concurrency, whatever routing decided - a run that falls back from
3624
+ * your session (released, withdrawn, moved by you, a restart) takes a permit before its first attempt and gives it
3625
+ * back after its last (Codex's review of the F3 design). First come, first served. */
3626
+ const permits = {
3627
+ free: Math.max(1, cfg.concurrency),
3628
+ waiting: []
3629
+ };
3630
+ const takePermit = () => new Promise((res) => {
3631
+ const grant = () => {
3632
+ permits.free -= 1;
3633
+ let back = false;
3634
+ res(() => {
3635
+ if (back) return;
3636
+ back = true;
3637
+ permits.free += 1;
3638
+ permits.waiting.shift()?.();
3639
+ });
3640
+ };
3641
+ if (permits.free > 0 && !permits.waiting.length) grant();
3642
+ else permits.waiting.push(grant);
3643
+ });
1765
3644
  let recheck = null;
1766
3645
  const holdLater = () => {
1767
3646
  if (recheck || stopped) return;
1768
3647
  recheck = setTimeout(() => {
1769
3648
  recheck = null;
1770
- pump();
3649
+ pump().catch((err) => log(` jam: pump error - ${err.message}`));
1771
3650
  }, HOLD_RECHECK_MS);
1772
3651
  recheck.unref?.();
1773
3652
  };
@@ -1791,16 +3670,43 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1791
3670
  }
1792
3671
  const started = await q.lock((j, ctx) => {
1793
3672
  noteQueued();
3673
+ const moved = () => `${j.batches.length}|${j.cards.map((c) => `${c.id}:${c.rev}`).join()}`;
3674
+ const was = moved();
1794
3675
  const frames = new Set([...runningBatches.values()].flatMap((b) => b.frames));
3676
+ const sessionSide = (x) => x.handoff !== "spawn" && (!!x.offer || !!x.claim || x.runner?.kind === "session");
3677
+ const spawned = [...runningBatches.values()].filter((x) => !sessionSide(x)).length;
3678
+ const taker = runs.taker();
3679
+ const taking = takersNow();
1795
3680
  const { batches, exclusiveWaiting } = form(j, ctx, {
1796
- free: Math.max(1, cfg.concurrency) - runningBatches.size,
3681
+ session: (record) => {
3682
+ const t = taking(record);
3683
+ return t && {
3684
+ conn: t.conn.id,
3685
+ inc: t.conn.inc,
3686
+ room: t.room
3687
+ };
3688
+ },
3689
+ free: Math.max(1, cfg.concurrency) - spawned + runs.room(),
3690
+ ...taker ? {
3691
+ share: (f) => {
3692
+ const hs = [...runningBatches.values()].filter((x) => x.frames.includes(f));
3693
+ return hs.length && hs.every((x) => !x.exclusive && heldBy(x, taker)) ? hs.map((x) => x.batchId) : null;
3694
+ },
3695
+ shareRoom: runs.room(),
3696
+ sharer: {
3697
+ conn: taker.id,
3698
+ inc: taker.inc
3699
+ }
3700
+ } : {},
1797
3701
  running: frames,
3702
+ active: runningBatches.size,
1798
3703
  exclusiveRunning: [...runningBatches.values()].some((b) => b.exclusive),
1799
3704
  held: (f) => !!hooks.held?.(f),
1800
- anyHold: () => !!hooks.anyHold?.()
3705
+ anyHold: () => !!hooks.anyHold?.(),
3706
+ others: runs.settings().others
1801
3707
  });
1802
3708
  prune(j);
1803
- q.persist();
3709
+ if (moved() !== was) q.persist();
1804
3710
  for (const b of batches) runningBatches.set(b.batchId, b);
1805
3711
  const now = performance.now();
1806
3712
  for (const b of batches) batchWaits.set(b.batchId, new Map(b.members.flatMap((m) => {
@@ -1810,14 +3716,12 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1810
3716
  reserve(exclusiveWaiting);
1811
3717
  for (const c of j.cards) {
1812
3718
  if (c.state !== "queued") continue;
3719
+ holdLater();
1813
3720
  const held = c.frames.find((f) => hooks.held?.(f));
1814
- if (held || exclusiveWaiting && (c.exclusive || !c.frames.length)) {
1815
- holdLater();
1816
- if (held && !waitingSaid.has(c.id)) {
1817
- waitingSaid.add(c.id);
1818
- log(` jam: waiting - ${held} is being worked on in chat; the comment runs once it is done`);
1819
- }
1820
- } else waitingSaid.delete(c.id);
3721
+ if (held && !waitingSaid.has(c.id)) {
3722
+ waitingSaid.add(c.id);
3723
+ log(` jam: waiting - ${held} is being worked on in chat; the comment runs once it is done`);
3724
+ } else if (!held) waitingSaid.delete(c.id);
1821
3725
  }
1822
3726
  return batches;
1823
3727
  });
@@ -1900,6 +3804,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1900
3804
  log(` jam: batch error - ${err.message}`);
1901
3805
  if (b.results) redeliver(b, 1);
1902
3806
  else {
3807
+ runs.delivered(b.batchId, false, err.message);
1903
3808
  try {
1904
3809
  await q.lock((j) => {
1905
3810
  settled(fail(j, b, `the job broke: ${err.message}`));
@@ -1936,6 +3841,13 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1936
3841
  });
1937
3842
  continue;
1938
3843
  }
3844
+ if (b.claim) {
3845
+ out.push({
3846
+ b,
3847
+ results: false
3848
+ });
3849
+ continue;
3850
+ }
1939
3851
  fenceGroup(b.pgid);
1940
3852
  const ctx = q.ctx();
1941
3853
  const logs = /* @__PURE__ */ new Map();
@@ -1965,17 +3877,11 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1965
3877
  const c = j.cards.find((x) => x.id === m.card);
1966
3878
  if (!c) continue;
1967
3879
  if (c.capture && !captureIntact(j, ctx, c.capture)) {
1968
- c.state = "failed";
1969
- c.note = "the capture changed after it was confirmed - capture it again";
1970
- c.rev += 1;
1971
- c.at = Date.now();
3880
+ failCard(j, c, "the capture changed after it was confirmed - capture it again", Date.now());
1972
3881
  continue;
1973
3882
  }
1974
3883
  if (c.kind === "wrapup" && !wrapupIntact(ctx, c)) {
1975
- c.state = "failed";
1976
- c.note = "the session record changed after it was written - write it again";
1977
- c.rev += 1;
1978
- c.at = Date.now();
3884
+ failCard(j, c, "the session record changed after it was written - write it again", Date.now());
1979
3885
  continue;
1980
3886
  }
1981
3887
  const comment = c.kind === "comment";
@@ -2020,12 +3926,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2020
3926
  b.note = "its packet is gone";
2021
3927
  for (const m of b.members) {
2022
3928
  const c = j.cards.find((x) => x.id === m.card);
2023
- if (c) {
2024
- c.state = "failed";
2025
- c.note = "interrupted - Retry";
2026
- c.rev += 1;
2027
- c.at = Date.now();
2028
- }
3929
+ if (c) failCard(j, c, "interrupted - Retry", Date.now());
2029
3930
  }
2030
3931
  continue;
2031
3932
  }
@@ -2130,8 +4031,9 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2130
4031
  }];
2131
4032
  });
2132
4033
  };
2133
- /** A sealed capture taken in: checked (and, resumed, as a continuation), stored, ledgered, a draft card -
2134
- * or queued at once with `jam.capture: 'at-once'`. */
4034
+ /** A sealed capture taken in: checked (and, resumed, as a continuation), stored, ledgered - ended with E, a card
4035
+ * queued in the same step that makes it; ended with ⇧E (or sealed by its page leaving), a draft card. `held`: an
4036
+ * E capture the queue would not take - it stays a draft, and this says why (the page says so in one line). */
2135
4037
  const landCapture = async (rec) => {
2136
4038
  const rs = rec.context.resumes;
2137
4039
  if (rs && !storedOnce(rec)) {
@@ -2151,13 +4053,32 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2151
4053
  error: stored
2152
4054
  };
2153
4055
  record(root, rec.context.board, `capture:${rec.id}:${stored.hash}`);
2154
- const card = await q.lock((j) => {
4056
+ const auto = !rec.context.interrupted && !rec.context.review;
4057
+ const at = auto && !storedOnce(rec) ? await pinOf(rec) : void 0;
4058
+ let card = await q.lock((j) => {
4059
+ const fresh = !j.cards.some((c) => c.id === rec.id);
2155
4060
  const c = addCapture(j, rec, stored.hash);
4061
+ if (fresh && at) {
4062
+ beginStep(j, c, "confirm", captureComment(c, rec, at, me()), Date.now(), "queued");
4063
+ q.persist();
4064
+ finishIn(j, c);
4065
+ }
2156
4066
  q.persist();
2157
4067
  return structuredClone(c);
2158
4068
  });
4069
+ if (card.pending?.op === "confirm") card = await finishStep(card.id) ?? card;
4070
+ if (auto && card.state === "draft" && !card.note) {
4071
+ const r = await confirm(card.id, card.rev, "queued");
4072
+ if ("card" in r && r.card) card = r.card;
4073
+ }
4074
+ reserve();
2159
4075
  queueChanged();
2160
- if (cfg.capture === "at-once" && card.state === "draft" && !rec.context.interrupted) return confirm(card.id, card.rev, "queued");
4076
+ pump();
4077
+ if (auto && card.state === "draft") return {
4078
+ ok: true,
4079
+ card,
4080
+ held: card.note ?? "it could not be queued"
4081
+ };
2161
4082
  return {
2162
4083
  ok: true,
2163
4084
  card
@@ -2233,7 +4154,11 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2233
4154
  let viewN = 0;
2234
4155
  const view = () => {
2235
4156
  const j = q.j;
2236
- const queued = j.cards.filter((c) => c.state === "queued").sort((a, b) => a.order - b.order || a.made - b.made);
4157
+ const busyFrame = (c) => c.frames.find((f) => jamReservations.frames.has(f) || !!hooks.held?.(f));
4158
+ const taking = takersNow();
4159
+ const alone = aloneNow(taking);
4160
+ const full = (c) => !c.frames.length && !alone(c) && (taking(c.kind === "wrapup")?.room ?? 0) < 1;
4161
+ const queued = j.cards.filter((c) => c.state === "queued" && !busyFrame(c) && !full(c)).sort((a, b) => a.order - b.order || a.made - b.made);
2237
4162
  const shown = j.cards.filter((c) => pending(c) || c.at > Date.now() - 6e4 || !!j.run && c.kind !== "comment" && c.made >= j.run.since);
2238
4163
  const exclusiveAhead = jamReservations.exclusive;
2239
4164
  return {
@@ -2245,9 +4170,15 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2245
4170
  ...q.j.run ? { run: q.j.run } : {},
2246
4171
  ...q.j.session ? { session: q.j.session } : {},
2247
4172
  cards: shown.map((c) => {
2248
- const position = c.state === "queued" ? queued.indexOf(c) + 1 : void 0;
2249
- const held = c.state === "queued" ? c.frames.find((f) => hooks.held?.(f)) : void 0;
2250
- 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;
4173
+ const busy = c.state === "queued" ? busyFrame(c) : void 0;
4174
+ const holder = busy ? j.batches.find((b) => b.batchId === jamReservations.frames.get(busy)) : void 0;
4175
+ const waitsFor = busy ? {
4176
+ frame: busy,
4177
+ ...holder ? { by: runs.title(holder) } : hooks.held?.(busy) ? { by: "chat" } : {}
4178
+ } : void 0;
4179
+ const position = c.state === "queued" && !busy && !full(c) ? queued.indexOf(c) + 1 : void 0;
4180
+ const waiting = c.state === "queued" && exclusiveAhead === "waiting" && alone(c) ? "alone" : c.state === "queued" && exclusiveAhead ? "behind" : c.state === "queued" && full(c) ? "session" : void 0;
4181
+ const fails = c.batch ? j.batches.find((b) => b.batchId === c.batch)?.failures : void 0;
2251
4182
  return {
2252
4183
  id: c.id,
2253
4184
  kind: c.kind,
@@ -2261,23 +4192,36 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2261
4192
  made: c.made,
2262
4193
  order: c.order,
2263
4194
  at: c.at,
4195
+ ...c.att ? { att: c.att } : {},
4196
+ ...fails ? { fails } : {},
2264
4197
  ...c.follows ? { follows: c.follows } : {},
2265
4198
  ...c.reply ? { reply: c.reply } : {},
2266
4199
  ...c.batch ? { batch: c.batch } : {},
2267
4200
  ...position ? { position } : {},
4201
+ ...waitsFor ? { waitsFor } : {},
2268
4202
  ...waiting ? { waiting } : {},
2269
4203
  ...c.exclusive ? { exclusive: true } : {},
2270
- ...c.kind !== "comment" ? captureView(c) : {}
4204
+ ...c.kind !== "comment" ? captureView(c) : {},
4205
+ ...c.state === "working" ? (() => {
4206
+ const r = runs.runnerOf(j.batches.find((b) => b.batchId === c.batch));
4207
+ return r ? { runner: r } : {};
4208
+ })() : {}
2271
4209
  };
2272
- })
4210
+ }),
4211
+ ...runs.view(),
4212
+ settings: runs.settings()
2273
4213
  };
2274
4214
  };
2275
4215
  return {
2276
4216
  tick,
4217
+ runs,
2277
4218
  stop() {
2278
4219
  stopped = true;
2279
4220
  jamReservations.settling = false;
4221
+ runs.stop();
2280
4222
  if (recheck) clearTimeout(recheck);
4223
+ if (pumpDue) clearTimeout(pumpDue);
4224
+ for (const w of permits.waiting.splice(0)) w();
2281
4225
  for (const t of timers) clearTimeout(t);
2282
4226
  timers.clear();
2283
4227
  for (const wake of naps) wake();
@@ -2443,8 +4387,28 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2443
4387
  },
2444
4388
  async act(id, rev, action, body) {
2445
4389
  const c = q.j.cards.find((x) => x.id === id);
4390
+ if (action === "session-again" || action === "session-background" || action === "session-drop") {
4391
+ if (!c || c.rev !== rev) return {
4392
+ ok: false,
4393
+ ...c ? { card: structuredClone(c) } : {},
4394
+ error: "the card changed - look again"
4395
+ };
4396
+ const b = q.j.batches.find((x) => x.batchId === c.batch);
4397
+ if (!b?.claim) return {
4398
+ ok: false,
4399
+ card: structuredClone(c),
4400
+ error: "no session holds it now"
4401
+ };
4402
+ const r = await runs.act(b.batchId, b.claim.gen, action === "session-again" ? "again" : action === "session-background" ? "background" : "drop");
4403
+ queueChanged();
4404
+ return {
4405
+ ...r,
4406
+ card: structuredClone(c)
4407
+ };
4408
+ }
2446
4409
  if (c?.kind === "capture" && (action === "confirm" || action === "keep" && (c.state === "draft" || c.state === "confirming"))) return confirm(id, rev, action === "confirm" ? "queued" : "kept");
2447
4410
  if (action === "good" && c && c.kind !== "comment") return good(id, rev);
4411
+ if (action === "more" && c && c.kind !== "comment" && c.state === "review" && isApproval(body ?? "")) return good(id, rev);
2448
4412
  if (action === "more" && c && c.kind !== "comment") return moreWork(id, rev, body ?? "");
2449
4413
  const saved = await q.lock((j) => {
2450
4414
  const c = j.cards.find((x) => x.id === id);
@@ -2539,6 +4503,36 @@ function startJam(root, cfg, log = () => {}, onChanged = () => {}, anchor, onQue
2539
4503
  } catch {}
2540
4504
  const interval = setInterval(() => void core.poke(), RESCAN_MS);
2541
4505
  interval.unref?.();
4506
+ let ticking = false;
4507
+ const runTick = () => {
4508
+ if (ticking || stopped) return;
4509
+ ticking = true;
4510
+ core.runs.tick().catch((err) => log(` jam: session tick error - ${err.message}`)).finally(() => {
4511
+ ticking = false;
4512
+ });
4513
+ };
4514
+ const sessionWatchers = [];
4515
+ let pushDue = null;
4516
+ const connsChanged = () => {
4517
+ runTick();
4518
+ pushDue ??= setTimeout(() => {
4519
+ pushDue = null;
4520
+ try {
4521
+ onQueue?.();
4522
+ } catch {}
4523
+ }, 250);
4524
+ };
4525
+ for (const [dir, on] of [[reqDir(root), runTick], [connDir(root), connsChanged]]) try {
4526
+ mkdirSync(dir, {
4527
+ recursive: true,
4528
+ mode: 448
4529
+ });
4530
+ const w = watch(dir, { persistent: false }, on);
4531
+ w.on("error", () => {});
4532
+ sessionWatchers.push(w);
4533
+ } catch {}
4534
+ const sessionInterval = setInterval(runTick, 2e3);
4535
+ sessionInterval.unref?.();
2542
4536
  core.tick();
2543
4537
  jamLive.poke = () => void core.poke();
2544
4538
  jamLive.view = () => core.view();
@@ -2550,12 +4544,22 @@ function startJam(root, cfg, log = () => {}, onChanged = () => {}, anchor, onQue
2550
4544
  jamLive.canWrap = (id) => core.canWrap(id);
2551
4545
  jamLive.captureOpen = (c, ses, on) => core.captureOpen(c, ses, on);
2552
4546
  jamLive.tags = (id) => core.tags(id);
4547
+ jamLive.runAct = (batch, gen, action) => core.runs.act(batch, gen, action);
4548
+ jamLive.refresh = () => {
4549
+ try {
4550
+ onQueue?.();
4551
+ } catch {}
4552
+ runTick();
4553
+ };
2553
4554
  log(` jam: on (${adapter.name}) - tag @marver in a comment and it does the work; \`jam: false\` in design/config.ts turns it off`);
2554
4555
  return { stop() {
2555
4556
  stopped = true;
2556
4557
  if (scheduled) clearTimeout(scheduled);
2557
4558
  clearInterval(interval);
4559
+ clearInterval(sessionInterval);
4560
+ if (pushDue) clearTimeout(pushDue);
2558
4561
  watcher?.close();
4562
+ for (const w of sessionWatchers) w.close();
2559
4563
  core.stop();
2560
4564
  delete jamLive.poke;
2561
4565
  delete jamLive.view;