@marver-design/marver 0.27.2 → 0.28.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 (64) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +4 -2
  3. package/dist/{anchor-check-gkxkPAIv.mjs → anchor-check-PHUOFj1N.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-BsAyLMT1.mjs} +7 -5
  8. package/dist/{capture-vadKjuCo.mjs → capture-DdZ6xgoz.mjs} +92 -30
  9. package/dist/cli.mjs +37 -16
  10. package/dist/{comments-YEU1Zhv9.mjs → comments-CrBHPEQl.mjs} +2 -2
  11. package/dist/config-BezZTiov.mjs +182 -0
  12. package/dist/conn-BMiHS42T.mjs +222 -0
  13. package/dist/connectors-MR9d-EBP.mjs +290 -0
  14. package/dist/{context-Ccjrhr1J.mjs → context-BUnFiyA3.mjs} +2 -2
  15. package/dist/{daemon-Dc9AH0M3.mjs → daemon-C5dg2R-V.mjs} +2187 -182
  16. package/dist/{dev-ri6nAlRp.mjs → dev-D7YS7iT2.mjs} +22 -11
  17. package/dist/{init-W0nxR1OY.mjs → init-WE5lQkQL.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/{manifest-aFyDmL8C.mjs → manifest-DPZ3WNg_.mjs} +1 -1
  22. package/dist/{marks-BF9pNEgH.mjs → marks-Dyn6tmjp.mjs} +3 -3
  23. package/dist/{marks-CnCCfAbD.mjs → marks-Kmdab_5w.mjs} +2 -2
  24. package/dist/{perf-DkAUFT6W.mjs → perf-Cn5LiRaY.mjs} +3 -3
  25. package/dist/{perf-jam-BaH3Lg0m.mjs → perf-jam-QxD_UnzN.mjs} +1 -1
  26. package/dist/permit-DDa6wqOs.mjs +187 -0
  27. package/dist/{plugin-B8UghYuF.mjs → plugin-C_0yb-Fq.mjs} +365 -518
  28. package/dist/{poster-BNgafWMK.mjs → poster-DHi6I1fO.mjs} +1 -1
  29. package/dist/{publish-bakes-38Nja78p.mjs → publish-bakes-r4PEZuPl.mjs} +2 -2
  30. package/dist/{queue-CAM_vNmX.mjs → queue-c-6aTHEz.mjs} +164 -25
  31. package/dist/{recover-B8AiI29B.mjs → recover-nrLEVLyJ.mjs} +1 -1
  32. package/dist/{session-BAaJsK5c.mjs → session-DyVE7cCk.mjs} +1 -1
  33. package/dist/{shot-Ch24tiMO.mjs → shot-BrRtqaiS.mjs} +7 -6
  34. package/dist/{shot-CMQgMVZm.mjs → shot-DBWN8hPP.mjs} +1 -1
  35. package/dist/sizes-wjXDev3b.mjs +139 -0
  36. package/dist/speech-worker.mjs +23 -3
  37. package/dist/transport-C5FnY9ni.mjs +203 -0
  38. package/dist/{work-Bxz-ObF3.mjs → work-BYWD_1Zf.mjs} +3 -3
  39. package/dist/{work-CNhFF9pU.mjs → work-DJxH7cCX.mjs} +1 -1
  40. package/docs/jam-session.md +39 -14
  41. package/docs/live-jam.md +92 -10
  42. package/package.json +1 -1
  43. package/src/client/shell/JamSurface.tsx +56 -21
  44. package/src/client/shell/icons.tsx +1 -0
  45. package/src/client/shell/jam-capture.ts +97 -22
  46. package/src/client/shell/jam-keys.ts +32 -6
  47. package/src/client/shell/jam-lane.tsx +14 -5
  48. package/src/client/shell/jam-lines.ts +66 -9
  49. package/src/client/shell/jam-panel.tsx +55 -3
  50. package/src/client/shell/jam-queue.ts +50 -8
  51. package/src/client/shell/jam-session.tsx +53 -4
  52. package/src/client/shell/jam-surface-parts.tsx +6 -3
  53. package/src/client/shell/jam-ui.tsx +6 -1
  54. package/src/client/shell/jam-voice-wait.ts +21 -0
  55. package/src/client/shell/jam-voice.ts +14 -5
  56. package/src/client/shell/styles.css +27 -11
  57. package/src/client/shell/tidy.ts +3 -2
  58. package/src/shared/approval.ts +20 -0
  59. package/src/shared/events.ts +1 -1
  60. package/templates/AGENTS-embedded.md +28 -1
  61. package/templates/AGENTS-studio.md +28 -1
  62. package/templates/instructions/boards.md +7 -1
  63. package/templates/instructions/jam.md +90 -0
  64. package/dist/boards-BHKP5yhI.mjs +0 -342
@@ -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
5
  import { n as localProfile } from "./profile-jIS6BcAs.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-MR9d-EBP.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 sanitize, S as refusedAsk, _ as buildPacket, a as checkRecord, b as parseAgentText, c as firstPoint, d as picturePath, f as readCapture, g as wordsUntil, h as wordsSince, m as storeCapture, n as captureFrames, o as continues, p as requestWords, r as captureWords, t as CAPTURE_ID, u as madeOf, v as goalText, w as sharedWhy, x as parseMembers, y as packetPath } from "./capture-DdZ6xgoz.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-DyVE7cCk.mjs";
14
+ import { act, addCapture, addWrapup, answeredSince, beginStep, captureComment, captureIntact, conflictStep, createQueue, ctxFor, endSession, endStep, fail, 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-c-6aTHEz.mjs";
15
+ import { t as logJam } from "./perf-jam-QxD_UnzN.mjs";
16
+ import { t as PROTECTED_GLOBS } from "./permit-DDa6wqOs.mjs";
12
17
  import { jamReservations, restoreHolds } from "./reserve-BURNQ2Y3.mjs";
13
18
  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,1435 @@ 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
+ /** How long a request's answer is kept for the same request sent again. */
1099
+ const RECEIPT_MS = 6e5;
1100
+ /** The longest final message a session hands back (its replies, not its work). */
1101
+ const DONE_MAX = 4e5;
1102
+ /** Runs one session holds at once (F3). Claude Code dispatches each run to a background subagent of its own, so it can
1103
+ * hold several at once: 8. Marver gives Codex and Cursor runs one after another in their own thread: 3 (as before).
1104
+ * `jam.sessionMax` caps every session. */
1105
+ const sessionMaxFor = (cfg, agent) => cfg.sessionMax ?? (agent === "claude" ? 8 : 3);
1106
+ function settingsOf(root, cfg, agent) {
1107
+ const p = readPrefs(root);
1108
+ const b = (v, d) => typeof v === "boolean" ? v : d;
1109
+ return {
1110
+ runner: cfg.runner ?? "auto",
1111
+ session: cfg.session !== false,
1112
+ sessionMax: agent ? sessionMaxFor(cfg, agent) : cfg.sessionMax ?? 3,
1113
+ context: p.context === "fork" || p.context === "fresh" ? p.context : cfg.context ?? "fork",
1114
+ mcp: b(p.mcp, cfg.mcp ?? true),
1115
+ skills: b(p.skills, cfg.skills ?? true),
1116
+ others: b(p.others, cfg.others ?? false)
1117
+ };
1118
+ }
1119
+ const handleOf = (b, gen) => `r-${b.batchId.slice(0, 8)}.${gen}`;
1120
+ /** A session command as that session must type it - Cursor's names its connection (it has no session id in its shell). */
1121
+ const cmdFor = (conn, op, handle) => `\`npx marver jam ${op}${handle ? ` ${handle}` : ""}${conn?.agent === "cursor" ? ` --as ${conn.id}` : ""}\``;
1122
+ const HANDLE = /^r-([0-9a-f]{8})\.(\d+)$/;
1123
+ /** A session's final message, parsed as any agent's. */
1124
+ const parsedRun = (text) => {
1125
+ const p = parseAgentText(text);
1126
+ return {
1127
+ reply: p.reply,
1128
+ asks: p.asks,
1129
+ reanchors: p.reanchors,
1130
+ said: text,
1131
+ ok: !!p.reply
1132
+ };
1133
+ };
1134
+ function createRuns(d) {
1135
+ const { root, q } = d;
1136
+ let stopped = false;
1137
+ const waiters = /* @__PURE__ */ new Map();
1138
+ /** a `done` waits for its delivery: by batch, the answers to write when it is posted */
1139
+ const deliveries = /* @__PURE__ */ new Map();
1140
+ /** how a batch's delivery went, for a `done` sent again */
1141
+ const outcome = /* @__PURE__ */ new Map();
1142
+ const seenReqs = /* @__PURE__ */ new Set();
1143
+ /** each connection's offers as last written: a new batch among them grows its generation */
1144
+ const offered = /* @__PURE__ */ new Map();
1145
+ /** connections whose offers file last said a stop or a carry-on: looked at again until it says none */
1146
+ const worded = /* @__PURE__ */ new Set();
1147
+ /** connections whose offers this daemon has written since it started */
1148
+ const published = /* @__PURE__ */ new Set();
1149
+ const settings = () => settingsOf(root, d.cfg);
1150
+ const maxOf = (c) => sessionMaxFor(d.cfg, c.agent);
1151
+ /** may this session take Jam work now: alive, not muted or in plan mode, and its tool's connector not turned off */
1152
+ const usable = (c, now = Date.now()) => !!c && eligible(c, now) && !readPrefs(root).off?.[c.agent];
1153
+ const live = (now = Date.now()) => listConns(root).filter((c) => usable(c, now));
1154
+ const open = () => q.j.batches.filter((b) => b.state === "claimed" && !b.results);
1155
+ const byId = (id) => open().find((b) => b.batchId === id);
1156
+ /** 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 -
1157
+ * never once Marver spawned it (Codex's review: one let go of and spawned still took a place of your session's room) */
1158
+ const kept = (b, id) => b.share?.conn === id && !b.offer && !b.claim && !b.handoff && (!b.runner || b.runner.kind === "session");
1159
+ /** runs a connection holds now: offered to it, claimed by it and not stopping, or kept for it */
1160
+ const load = (id) => open().filter((b) => b.offer?.conn === id || b.claim?.conn === id && !b.claim.stopping || kept(b, id)).length;
1161
+ const selected = (now = Date.now()) => {
1162
+ const conns = live(now);
1163
+ const pick = readPrefs(root).pick;
1164
+ return conns.find((c) => c.id === pick) ?? conns.sort((a, b) => b.since - a.since)[0];
1165
+ };
1166
+ /** Can it take an offer now? Claude Code always (its inbox wakes it); Codex and Cursor while a turn runs. */
1167
+ const offerable = (c) => c.agent === "claude" || c.busy;
1168
+ /** Is it the record of a Jam session (a wrap-up)? Offered to your session though the session it records has ended. */
1169
+ const recordRun = (b) => b.members.some((m) => q.j.cards.find((c) => c.id === m.card)?.kind === "wrapup");
1170
+ /** Does a session take work now - this run, when one is named (`record`: a session's record)? Sessions on, the owner's
1171
+ * context allowed, not background-only, and a Jam session running (or, for a session's own record, just ended: never
1172
+ * any other run). */
1173
+ const sessionsOn = (s, b) => s.session && s.context === "fork" && s.runner !== "background" && (d.jamOn() || b === "record" || !!b && recordRun(b));
1174
+ /** Is the writer of a claim proven gone? Its process is (Claude Code, Codex), or - Cursor - that very incarnation
1175
+ * said it ended. A connection file missing, or silence, is "unknown", never "gone". */
1176
+ const writerGone = (claim) => {
1177
+ if (claim.pid) return !pidAlive(claim.pid);
1178
+ const c = readConn(root, claim.conn);
1179
+ return !!c && c.inc === claim.inc && !!c.ended;
1180
+ };
1181
+ const choose = (b, now = Date.now(), spawnOnly = false) => {
1182
+ const s = settings();
1183
+ let skipped;
1184
+ if (!spawnOnly && !b.handoff && b.share) {
1185
+ const pick = sessionsOn(s, b) ? selected(now) : void 0;
1186
+ if (pick && pick.id === b.share.conn && pick.inc === b.share.inc && offerable(pick)) return {
1187
+ kind: "session",
1188
+ conn: pick
1189
+ };
1190
+ }
1191
+ if (!spawnOnly && !b.handoff) {
1192
+ const pick = sessionsOn(s, b) ? selected(now) : void 0;
1193
+ if (pick && offerable(pick) && load(pick.id) < maxOf(pick)) return {
1194
+ kind: "session",
1195
+ conn: pick
1196
+ };
1197
+ if (s.runner === "session" && s.session && s.context === "fork") return { kind: "wait" };
1198
+ 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`;
1199
+ }
1200
+ const pick = s.session ? selected(now) : void 0;
1201
+ const agent = pick?.agent ?? d.cfg.agent;
1202
+ if (s.context === "fork") {
1203
+ const can = (a) => d.canSpawn(a);
1204
+ 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);
1205
+ 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);
1206
+ if (src && forkable(src)) return {
1207
+ kind: "fork",
1208
+ agent: src.agent,
1209
+ session: src.session,
1210
+ ...skipped ? { why: skipped } : {}
1211
+ };
1212
+ if (src) return {
1213
+ kind: "fresh",
1214
+ agent: src.agent,
1215
+ why: "your session is too long to copy - a fresh agent took it"
1216
+ };
1217
+ }
1218
+ return {
1219
+ kind: "fresh",
1220
+ agent: d.canSpawn(agent) ? agent : d.cfg.agent,
1221
+ ...skipped ? { why: skipped } : {}
1222
+ };
1223
+ };
1224
+ /** 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. */
1225
+ const titleOf = (b) => {
1226
+ const c = q.j.cards.find((x) => x.id === b.members[0]?.card);
1227
+ 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");
1228
+ const t = sanitize(String(words), 400).replace(/@marver\b/gi, "").replace(/\s+/g, " ").trim() || "a request";
1229
+ const cps = [...t];
1230
+ return cps.length > 60 ? `${cps.slice(0, 59).join("")}…` : t;
1231
+ };
1232
+ /** Write every connection's offers file: how many runs wait for it, the runs it must let go or carry on with, a new
1233
+ * generation when any of that is new - and the words its listener posts for it. */
1234
+ const publish = () => {
1235
+ const by = /* @__PURE__ */ new Map();
1236
+ const stops = /* @__PURE__ */ new Map();
1237
+ const resumes = /* @__PURE__ */ new Map();
1238
+ for (const b of open()) {
1239
+ if (b.offer) by.set(b.offer.conn, [...by.get(b.offer.conn) ?? [], b.batchId]);
1240
+ if (b.claim?.stopping) stops.set(b.claim.conn, [...stops.get(b.claim.conn) ?? [], handleOf(b, b.claim.gen)]);
1241
+ if (b.claim?.resumed) resumes.set(b.claim.conn, [...resumes.get(b.claim.conn) ?? [], handleOf(b, b.claim.gen)]);
1242
+ }
1243
+ for (const id of /* @__PURE__ */ new Set([
1244
+ ...by.keys(),
1245
+ ...offered.keys(),
1246
+ ...stops.keys(),
1247
+ ...resumes.keys(),
1248
+ ...worded
1249
+ ])) {
1250
+ const now = new Set(by.get(id) ?? []);
1251
+ const prev = readOffers(root, id);
1252
+ const newest = open().filter((b) => b.offer?.conn === id).sort((x, y) => y.offer.at - x.offer.at)[0];
1253
+ const over = newest?.overlaps?.map((x) => open().find((y) => y.batchId === x)).find((y) => !!y);
1254
+ const latest = newest ? {
1255
+ id: newest.batchId.slice(0, 8),
1256
+ title: titleOf(newest),
1257
+ ...over ? { overlaps: over.claim ? handleOf(over, over.claim.gen) : over.batchId.slice(0, 8) } : {}
1258
+ } : void 0;
1259
+ const was = offered.get(id) ?? (!published.has(id) && prev && prev.n === now.size && prev.latest?.id === latest?.id ? now : /* @__PURE__ */ new Set());
1260
+ published.add(id);
1261
+ const stop = stops.get(id) ?? [];
1262
+ const resume = resumes.get(id) ?? [];
1263
+ const newOffer = [...now].some((x) => !was.has(x));
1264
+ const newWord = JSON.stringify([stop, resume]) !== JSON.stringify([prev?.stop ?? [], prev?.resume ?? []]);
1265
+ if (now.size) offered.set(id, now);
1266
+ else offered.delete(id);
1267
+ if (stop.length || resume.length) worded.add(id);
1268
+ else worded.delete(id);
1269
+ if (!newOffer && !newWord && prev?.n === now.size) continue;
1270
+ const gen = newOffer || newWord && (stop.length || resume.length) ? Math.max((prev?.gen ?? 0) + 1, Date.now()) : prev?.gen ?? 0;
1271
+ const o = {
1272
+ n: now.size,
1273
+ gen,
1274
+ ...stop.length ? { stop } : {},
1275
+ ...resume.length ? { resume } : {},
1276
+ ...latest ? { latest } : {}
1277
+ };
1278
+ const line = gen > (prev?.gen ?? 0) ? pingLine(o, prev?.line) : prev?.line;
1279
+ try {
1280
+ writeOffers(root, id, {
1281
+ ...o,
1282
+ ...line ? { line } : {}
1283
+ });
1284
+ } catch {}
1285
+ }
1286
+ };
1287
+ const settle = (id, r) => {
1288
+ const w = waiters.get(id);
1289
+ if (w) {
1290
+ waiters.delete(id);
1291
+ w(r);
1292
+ }
1293
+ };
1294
+ const run = (b, conn) => new Promise((resolve) => {
1295
+ if (b.claim?.result !== void 0) return resolve(parsedRun(b.claim.result));
1296
+ waiters.set(b.batchId, resolve);
1297
+ let gone = false;
1298
+ q.lock(() => {
1299
+ if (!b.claim && !b.offer) {
1300
+ const held = conn ? load(conn.id) - (kept(b, conn.id) ? 1 : 0) : 0;
1301
+ if (conn && held >= maxOf(conn)) {
1302
+ letGo(b);
1303
+ if (b.handoff) {
1304
+ b.handoffWhy = `your session didn't take it - it already holds ${held} run${held === 1 ? "" : "s"}`;
1305
+ gone = true;
1306
+ }
1307
+ } else if (conn && !d.mayHold(b, conn)) {
1308
+ crowdedOut(b);
1309
+ gone = true;
1310
+ } else {
1311
+ b.runner = {
1312
+ kind: "session",
1313
+ agent: conn?.agent ?? ""
1314
+ };
1315
+ if (conn) {
1316
+ b.runner.conn = conn.id;
1317
+ b.offer = {
1318
+ conn: conn.id,
1319
+ inc: conn.inc,
1320
+ at: Date.now()
1321
+ };
1322
+ }
1323
+ }
1324
+ }
1325
+ q.persist();
1326
+ }).then(() => {
1327
+ publish();
1328
+ d.changed();
1329
+ if (gone) settle(b.batchId, null);
1330
+ }, () => settle(b.batchId, null));
1331
+ });
1332
+ /** Does a run a session let go of (not an explicit choice of the owner's) wait for a session again? Only under
1333
+ * `jam.runner: 'session'`, while sessions can take work at all. */
1334
+ const waitsForSession = (s = settings()) => s.runner === "session" && s.session && s.context === "fork";
1335
+ /** Where a run goes once its session lets go: back to waiting under session-only, else spawned. Call under the lock. */
1336
+ const letGo = (b) => {
1337
+ if (waitsForSession()) {
1338
+ delete b.handoff;
1339
+ b.runner = {
1340
+ kind: "session",
1341
+ agent: ""
1342
+ };
1343
+ } else b.handoff = "spawn";
1344
+ };
1345
+ /** It may not be held beside a run on one of its frames (F4: another runner's, or another incarnation's): it leaves its
1346
+ * session - spawned as letGo says, or under session-only back to the queue, never waiting for a session with the frame
1347
+ * kept (Codex's review: two runs waiting on one frame for the session you switched to each kept the frame the other
1348
+ * needed, forever - a queued request holds nothing, so two never wait on each other). Call under the lock. */
1349
+ const crowdedOut = (b) => {
1350
+ letGo(b);
1351
+ b.handoff ??= "queue";
1352
+ b.handoffWhy = "another runner holds one of its frames";
1353
+ };
1354
+ /** Take an offer back (not pulled in time, its session gone, Jam ended): where it goes is decided and saved in one write. */
1355
+ const withdraw = async (id, why) => {
1356
+ if (!await q.lock(() => {
1357
+ const b = byId(id);
1358
+ if (!b?.offer) return false;
1359
+ delete b.offer;
1360
+ letGo(b);
1361
+ if (b.handoff) b.handoffWhy = why;
1362
+ q.persist();
1363
+ return true;
1364
+ })) return;
1365
+ d.log(` jam: a run offered to your session went another way (${why})`);
1366
+ publish();
1367
+ if (byId(id)?.handoff) settle(id, null);
1368
+ d.changed();
1369
+ };
1370
+ /** The owner's stop, made final: dropped, or handed to a spawned runner (the owner's explicit choice wins over
1371
+ * session-only waiting). Call under the lock. */
1372
+ const stopNow = (b) => {
1373
+ const c = b.claim;
1374
+ b.gen = Math.max(b.gen ?? 0, c.gen);
1375
+ if (c.stopping === "drop") b.dropped = true;
1376
+ else b.handoff = "spawn";
1377
+ delete b.claim;
1378
+ };
1379
+ /** A stop the owner chose is confirmed by its writer proven gone: it runs as they chose - saved first. */
1380
+ const finishStop = async (id) => {
1381
+ const did = await q.lock(() => {
1382
+ const b = byId(id);
1383
+ if (!b?.claim?.stopping || b.claim.result !== void 0) return false;
1384
+ stopNow(b);
1385
+ q.persist();
1386
+ return true;
1387
+ });
1388
+ if (did) {
1389
+ publish();
1390
+ settle(id, null);
1391
+ d.changed();
1392
+ }
1393
+ return did;
1394
+ };
1395
+ /** The batch a handle names, checked for this connection - call it under the lock. */
1396
+ const claimOf = (conn, handle) => {
1397
+ const m = typeof handle === "string" ? HANDLE.exec(handle) : null;
1398
+ if (!m) return "that is not a run handle (r-xxxxxxxx.N)";
1399
+ const gen = Number(m[2]);
1400
+ const b = open().find((x) => x.batchId.startsWith(m[1]));
1401
+ if (!b) return "that run is over";
1402
+ if (!b.claim || b.claim.conn !== conn.id || b.claim.inc !== conn.inc) return "that run is not yours - it went to another runner";
1403
+ if (b.claim.gen !== gen) return "that handle is old - the run was taken again since";
1404
+ return {
1405
+ b,
1406
+ gen
1407
+ };
1408
+ };
1409
+ /** A change's receipt, in the same journal write as the change. */
1410
+ const keep = (req, out, b) => {
1411
+ (q.j.receipts ??= {})[req.id] = {
1412
+ at: Date.now(),
1413
+ out,
1414
+ op: req.op,
1415
+ ...b ? { batch: b.batchId } : {}
1416
+ };
1417
+ };
1418
+ /** How a handed-back run's delivery stands, from the batch itself - what every answer about it says. Null: not
1419
+ * settled yet (being posted). */
1420
+ const deliveryOf = (id) => {
1421
+ const b = q.j.batches.find((x) => x.batchId === id);
1422
+ if (!b) return {
1423
+ ok: false,
1424
+ error: "that run is gone from the journal"
1425
+ };
1426
+ if (b.posted || b.state === "done") return {
1427
+ ok: true,
1428
+ text: "Delivered - its replies are posted and the frames are free."
1429
+ };
1430
+ if (b.undelivered) return {
1431
+ ok: false,
1432
+ error: "its replies are saved, but they could not be posted - Retry on the card posts them"
1433
+ };
1434
+ if (b.state === "failed") return {
1435
+ ok: false,
1436
+ error: `it could not be delivered: ${b.note ?? "the run failed"}`
1437
+ };
1438
+ if (b.results) {
1439
+ const o = outcome.get(id);
1440
+ return o && !o.ok ? {
1441
+ ok: false,
1442
+ error: `it could not be delivered: ${o.note ?? "unknown"}`
1443
+ } : o?.note === "retrying" ? {
1444
+ ok: true,
1445
+ text: "Handed back - its replies are saved; posting them failed once and is being tried again."
1446
+ } : null;
1447
+ }
1448
+ const o = outcome.get(id);
1449
+ return o && !o.ok ? {
1450
+ ok: false,
1451
+ error: `it could not be delivered: ${o.note ?? "unknown"}`
1452
+ } : null;
1453
+ };
1454
+ /** A `done` or `say` sent again: where its run stands now, not what was hoped when it was taken. */
1455
+ const replay = (r, conn) => {
1456
+ if (r.op === "mute") {
1457
+ try {
1458
+ patchConn(root, conn.id, conn.inc, { muted: true });
1459
+ } catch {}
1460
+ return r.out;
1461
+ }
1462
+ if (r.op === "done" && r.batch) return deliveryOf(r.batch) ?? waitDelivery(r.batch);
1463
+ if (r.op === "say" && r.batch) {
1464
+ const b = q.j.batches.find((x) => x.batchId === r.batch);
1465
+ return b?.early && d.say(b) ? {
1466
+ ok: true,
1467
+ text: "Posted."
1468
+ } : {
1469
+ ok: true,
1470
+ text: "Taken - it is posted before the run is delivered."
1471
+ };
1472
+ }
1473
+ return r.out;
1474
+ };
1475
+ const waitDelivery = (id) => new Promise((res) => {
1476
+ const to = setTimeout(() => res(deliveryOf(id) ?? {
1477
+ ok: true,
1478
+ text: "Handed back - it is being posted; the canvas shows it in the thread."
1479
+ }), 1e5);
1480
+ to.unref?.();
1481
+ deliveries.set(id, [...deliveries.get(id) ?? [], () => {
1482
+ clearTimeout(to);
1483
+ res(deliveryOf(id) ?? {
1484
+ ok: true,
1485
+ text: "Handed back - it is being posted; the canvas shows it in the thread."
1486
+ });
1487
+ }]);
1488
+ });
1489
+ /** One request. Returns its answer, or a promise of it (a `done` answers once its replies are posted - and never
1490
+ * holds up the requests after it). */
1491
+ const ops = async (req, conn) => {
1492
+ const now = Date.now();
1493
+ if (req.op === "release") {
1494
+ let out = {
1495
+ ok: false,
1496
+ error: "that run is over"
1497
+ };
1498
+ let id = "";
1499
+ await q.lock(() => {
1500
+ const f = claimOf(conn, req.args.handle);
1501
+ if (typeof f === "string") {
1502
+ out = {
1503
+ ok: false,
1504
+ error: f
1505
+ };
1506
+ return;
1507
+ }
1508
+ const b = f.b;
1509
+ if (b.claim.result !== void 0) {
1510
+ out = {
1511
+ ok: false,
1512
+ error: "it is already handed back"
1513
+ };
1514
+ return;
1515
+ }
1516
+ id = b.batchId;
1517
+ if (b.claim.stopping) {
1518
+ out = {
1519
+ ok: true,
1520
+ text: "Released - the owner's choice goes ahead."
1521
+ };
1522
+ stopNow(b);
1523
+ } else {
1524
+ b.gen = Math.max(b.gen ?? 0, b.claim.gen);
1525
+ delete b.claim;
1526
+ letGo(b);
1527
+ if (b.handoff) b.handoffWhy = "your session let it go";
1528
+ out = {
1529
+ ok: true,
1530
+ text: b.handoff ? "Released - another runner takes it." : "Released - it waits for a session again."
1531
+ };
1532
+ }
1533
+ keep(req, out, b);
1534
+ q.persist();
1535
+ });
1536
+ if (id && out.ok) {
1537
+ publish();
1538
+ if (byId(id)?.handoff || byId(id)?.dropped || !byId(id)) settle(id, null);
1539
+ d.changed();
1540
+ }
1541
+ return out;
1542
+ }
1543
+ if (!usable(conn, now)) return {
1544
+ ok: false,
1545
+ error: conn.muted ? "this session is muted for Jam until it ends" : "this session cannot take Jam work now"
1546
+ };
1547
+ if (req.op === "mute") {
1548
+ const out = {
1549
+ ok: true,
1550
+ text: "Muted: this session takes no Jam work until it ends."
1551
+ };
1552
+ await q.lock(() => {
1553
+ keep(req, out);
1554
+ q.persist();
1555
+ });
1556
+ patchConn(root, conn.id, conn.inc, { muted: true });
1557
+ for (const b of open().filter((x) => x.offer?.conn === conn.id)) await withdraw(b.batchId, "muted");
1558
+ return out;
1559
+ }
1560
+ if (req.op === "status") {
1561
+ const mine = open().filter((b) => b.offer?.conn === conn.id || b.claim?.conn === conn.id);
1562
+ 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(", ")})`;
1563
+ return {
1564
+ ok: true,
1565
+ 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")
1566
+ };
1567
+ }
1568
+ if (req.op === "own") {
1569
+ const frame = String(req.args.frame ?? "");
1570
+ let out = {
1571
+ ok: false,
1572
+ error: "that run is over"
1573
+ };
1574
+ await q.lock(() => {
1575
+ const f = claimOf(conn, req.args.handle);
1576
+ if (typeof f === "string") {
1577
+ out = {
1578
+ ok: false,
1579
+ error: f
1580
+ };
1581
+ return;
1582
+ }
1583
+ const c = f.b.claim;
1584
+ if (c.stopping) {
1585
+ out = {
1586
+ ok: false,
1587
+ error: `the owner moved this run elsewhere - stop working on it and run ${cmdFor(conn, "release", String(req.args.handle))}`
1588
+ };
1589
+ return;
1590
+ }
1591
+ if (c.result !== void 0) {
1592
+ out = {
1593
+ ok: false,
1594
+ error: "it is already handed back"
1595
+ };
1596
+ return;
1597
+ }
1598
+ const why = d.own(f.b, frame);
1599
+ if (why) {
1600
+ out = {
1601
+ ok: false,
1602
+ error: why
1603
+ };
1604
+ return;
1605
+ }
1606
+ c.progress = Date.now();
1607
+ delete c.stalled;
1608
+ out = {
1609
+ ok: true,
1610
+ text: `${frame} is this run's now - no other runner gets it until the run is handed back.`
1611
+ };
1612
+ keep(req, out, f.b);
1613
+ q.persist();
1614
+ });
1615
+ if (out.ok) {
1616
+ publish();
1617
+ d.changed();
1618
+ }
1619
+ return out;
1620
+ }
1621
+ if (req.op === "next") {
1622
+ const let_go = [];
1623
+ const out = await q.lock(() => {
1624
+ const s = settings();
1625
+ const cur = readConn(root, conn.id);
1626
+ if (!cur || cur.inc !== conn.inc || !usable(cur)) return {
1627
+ ok: false,
1628
+ error: "this session's connection changed - run the command again"
1629
+ };
1630
+ 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);
1631
+ if (!sessionsOn(s) && !mine.length) return {
1632
+ ok: true,
1633
+ text: "Nothing waits for this session now (no Jam session takes it)."
1634
+ };
1635
+ if (selected(now)?.id !== conn.id) return {
1636
+ ok: true,
1637
+ text: "Nothing waits for this session now - another session takes the work."
1638
+ };
1639
+ let b;
1640
+ for (const x of mine) {
1641
+ if (d.mayHold(x, conn)) {
1642
+ b = x;
1643
+ break;
1644
+ }
1645
+ delete x.offer;
1646
+ crowdedOut(x);
1647
+ let_go.push(x.batchId);
1648
+ }
1649
+ if (!b) {
1650
+ if (let_go.length) q.persist();
1651
+ return {
1652
+ ok: true,
1653
+ text: "Nothing waits for this session now."
1654
+ };
1655
+ }
1656
+ const gen = Math.max(b.gen ?? 0, b.claim?.gen ?? 0) + 1;
1657
+ delete b.offer;
1658
+ delete b.handoff;
1659
+ b.gen = gen;
1660
+ b.runner = {
1661
+ kind: "session",
1662
+ agent: conn.agent,
1663
+ conn: conn.id
1664
+ };
1665
+ b.claim = {
1666
+ conn: conn.id,
1667
+ inc: conn.inc,
1668
+ ...conn.pid ? { pid: conn.pid } : {},
1669
+ gen,
1670
+ at: Date.now(),
1671
+ progress: Date.now()
1672
+ };
1673
+ const handle = handleOf(b, gen);
1674
+ const o = {
1675
+ ok: true,
1676
+ handle,
1677
+ frames: b.frames,
1678
+ text: d.goal(b, handle, conn)
1679
+ };
1680
+ keep(req, o, b);
1681
+ q.persist();
1682
+ return o;
1683
+ });
1684
+ for (const id of let_go) settle(id, null);
1685
+ if (out.handle || let_go.length) {
1686
+ publish();
1687
+ d.changed();
1688
+ }
1689
+ return out;
1690
+ }
1691
+ if (req.op === "progress") {
1692
+ let out = {
1693
+ ok: true,
1694
+ text: "Noted - still yours."
1695
+ };
1696
+ await q.lock(() => {
1697
+ const f = claimOf(conn, req.args.handle);
1698
+ if (typeof f === "string") {
1699
+ out = {
1700
+ ok: false,
1701
+ error: f
1702
+ };
1703
+ return;
1704
+ }
1705
+ const c = f.b.claim;
1706
+ if (c.stopping) {
1707
+ out = {
1708
+ ok: false,
1709
+ error: `the owner moved this run elsewhere - stop working on it and run ${cmdFor(conn, "release", String(req.args.handle))}`
1710
+ };
1711
+ return;
1712
+ }
1713
+ c.progress = Date.now();
1714
+ delete c.stalled;
1715
+ delete c.resumed;
1716
+ keep(req, out, f.b);
1717
+ q.persist();
1718
+ });
1719
+ if (out.ok) {
1720
+ publish();
1721
+ d.changed();
1722
+ }
1723
+ return out;
1724
+ }
1725
+ if (req.op === "say") {
1726
+ const text = String(req.args.text ?? "").trim().slice(0, 2e3);
1727
+ if (!text) return {
1728
+ ok: false,
1729
+ error: "say what"
1730
+ };
1731
+ let out = {
1732
+ ok: true,
1733
+ text: "Posted."
1734
+ };
1735
+ let b0;
1736
+ await q.lock(() => {
1737
+ const f = claimOf(conn, req.args.handle);
1738
+ if (typeof f === "string") {
1739
+ out = {
1740
+ ok: false,
1741
+ error: f
1742
+ };
1743
+ return;
1744
+ }
1745
+ const b = f.b, c = b.claim;
1746
+ if (c.stopping) {
1747
+ out = {
1748
+ ok: false,
1749
+ error: `the owner moved this run elsewhere - stop working on it and run ${cmdFor(conn, "release", String(req.args.handle))}`
1750
+ };
1751
+ return;
1752
+ }
1753
+ if (c.result !== void 0) {
1754
+ out = {
1755
+ ok: false,
1756
+ error: "it is already handed back"
1757
+ };
1758
+ return;
1759
+ }
1760
+ if (b.members.length !== 1) {
1761
+ out = {
1762
+ ok: false,
1763
+ error: "a run of several asks posts no early line - its replies come with done"
1764
+ };
1765
+ return;
1766
+ }
1767
+ if (b.early) {
1768
+ out = {
1769
+ ok: false,
1770
+ error: "its early line is already posted"
1771
+ };
1772
+ return;
1773
+ }
1774
+ b.early = {
1775
+ body: text,
1776
+ asks: false,
1777
+ commentId: `jam-c-e${b.attempts}-${b.batchId}`,
1778
+ ts: Date.now()
1779
+ };
1780
+ c.progress = Date.now();
1781
+ delete c.stalled;
1782
+ keep(req, {
1783
+ ok: true,
1784
+ text: "Posted."
1785
+ }, b);
1786
+ q.persist();
1787
+ b0 = b;
1788
+ });
1789
+ if (!b0) return out;
1790
+ if (!d.say(b0)) return {
1791
+ ok: true,
1792
+ text: "Taken - it is posted before the run is delivered."
1793
+ };
1794
+ d.changed();
1795
+ return out;
1796
+ }
1797
+ const text = String(req.args.text ?? "").slice(0, DONE_MAX);
1798
+ if (!parsedRun(text).reply) return {
1799
+ ok: false,
1800
+ error: "the final message is empty - write the marver-reply blocks to the file"
1801
+ };
1802
+ let err;
1803
+ let id = "";
1804
+ await q.lock(() => {
1805
+ const f = claimOf(conn, req.args.handle);
1806
+ if (typeof f === "string") {
1807
+ err = f;
1808
+ return;
1809
+ }
1810
+ const c = f.b.claim;
1811
+ if (c.stopping) {
1812
+ err = `the owner moved this run elsewhere - stop working on it and run ${cmdFor(conn, "release", String(req.args.handle))}`;
1813
+ return;
1814
+ }
1815
+ if (c.result !== void 0) {
1816
+ err = "it is already handed back";
1817
+ return;
1818
+ }
1819
+ c.result = text;
1820
+ c.progress = Date.now();
1821
+ delete c.stalled;
1822
+ delete c.resumed;
1823
+ id = f.b.batchId;
1824
+ keep(req, { ok: true }, f.b);
1825
+ q.persist();
1826
+ });
1827
+ if (err) return {
1828
+ ok: false,
1829
+ error: err
1830
+ };
1831
+ const later = waitDelivery(id);
1832
+ settle(id, parsedRun(text));
1833
+ d.changed();
1834
+ return { later };
1835
+ };
1836
+ const answerAll = async () => {
1837
+ for (const { raw } of takeRequests(root)) {
1838
+ const rid = raw?.id;
1839
+ const kept = typeof rid === "string" ? q.j.receipts?.[rid] : void 0;
1840
+ const v = verify(root, raw, kept ? /* @__PURE__ */ new Set() : seenReqs);
1841
+ if (!v.ok) {
1842
+ if (v.id) answer(root, v.id, {
1843
+ ok: false,
1844
+ error: v.error
1845
+ });
1846
+ continue;
1847
+ }
1848
+ if (kept) {
1849
+ const r = replay(kept, v.conn);
1850
+ if (r instanceof Promise) r.then((o) => answer(root, v.req.id, o));
1851
+ else answer(root, v.req.id, r);
1852
+ continue;
1853
+ }
1854
+ let out;
1855
+ try {
1856
+ out = await ops(v.req, v.conn);
1857
+ } catch (e) {
1858
+ out = {
1859
+ ok: false,
1860
+ error: e.message
1861
+ };
1862
+ }
1863
+ try {
1864
+ if (alive(v.conn)) patchConn(root, v.conn.id, v.conn.inc, {});
1865
+ } catch {}
1866
+ if ("later" in out && out.later instanceof Promise) {
1867
+ const id = v.req.id;
1868
+ out.later.then((o) => answer(root, id, o));
1869
+ } else answer(root, v.req.id, out);
1870
+ }
1871
+ if (seenReqs.size > 5e3) seenReqs.clear();
1872
+ };
1873
+ let lastSweep = 0;
1874
+ /** who takes the work and their room, as the last tick read it */
1875
+ let routed = "";
1876
+ const tick = async (now = Date.now()) => {
1877
+ if (stopped || !d.ready()) return;
1878
+ await answerAll();
1879
+ const s = settings();
1880
+ const chosen = selected(now);
1881
+ for (const b of open()) {
1882
+ const sel = sessionsOn(s, b) ? chosen : void 0;
1883
+ if (b.offer) {
1884
+ const c = readConn(root, b.offer.conn);
1885
+ if (!c || !usable(c, now) || c.inc !== b.offer.inc) {
1886
+ await withdraw(b.batchId, "it ended or cannot take work now");
1887
+ continue;
1888
+ }
1889
+ if (!sessionsOn(s, b)) {
1890
+ await withdraw(b.batchId, d.jamOn() ? "sessions are off" : "the Jam session ended");
1891
+ continue;
1892
+ }
1893
+ if (sel?.id !== c.id) {
1894
+ await withdraw(b.batchId, "another session takes the work now");
1895
+ continue;
1896
+ }
1897
+ if (s.runner === "session") continue;
1898
+ 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");
1899
+ } else if (b.claim) {
1900
+ const claim = b.claim;
1901
+ if (claim.result !== void 0) continue;
1902
+ if (claim.stopping) {
1903
+ if (writerGone(claim)) await finishStop(b.batchId);
1904
+ continue;
1905
+ }
1906
+ const quiet = writerGone(claim) || now - claim.progress > 9e5;
1907
+ if (!claim.stalled && quiet) {
1908
+ await q.lock(() => {
1909
+ const x = byId(b.batchId)?.claim;
1910
+ if (x && x.result === void 0 && !x.stopping) {
1911
+ x.stalled = true;
1912
+ q.persist();
1913
+ }
1914
+ });
1915
+ d.log(` jam: a run your session took went quiet (${writerGone(claim) ? "the session ended" : "no word for 15 minutes"}) - choose in the lane`);
1916
+ d.changed();
1917
+ }
1918
+ } else if (b.runner?.kind === "session" && !b.handoff && waiters.has(b.batchId)) {
1919
+ if (!waitsForSession(s) && !sel) {
1920
+ await q.lock(() => {
1921
+ const x = byId(b.batchId);
1922
+ if (x && !x.offer && !x.claim) {
1923
+ x.handoff = "spawn";
1924
+ q.persist();
1925
+ }
1926
+ });
1927
+ settle(b.batchId, null);
1928
+ d.changed();
1929
+ continue;
1930
+ }
1931
+ const fits = (x) => load(sel.id) - (kept(x, sel.id) ? 1 : 0) < maxOf(sel);
1932
+ if (sel && offerable(sel) && fits(b)) {
1933
+ let out = false;
1934
+ await q.lock(() => {
1935
+ const x = byId(b.batchId);
1936
+ if (!x || x.offer || x.claim || x.handoff || !fits(x)) return;
1937
+ if (d.mayHold(x, sel)) {
1938
+ x.runner = {
1939
+ kind: "session",
1940
+ agent: sel.agent,
1941
+ conn: sel.id
1942
+ };
1943
+ x.offer = {
1944
+ conn: sel.id,
1945
+ inc: sel.inc,
1946
+ at: Date.now()
1947
+ };
1948
+ } else {
1949
+ crowdedOut(x);
1950
+ out = true;
1951
+ }
1952
+ q.persist();
1953
+ });
1954
+ if (out) settle(b.batchId, null);
1955
+ d.changed();
1956
+ }
1957
+ }
1958
+ }
1959
+ const routing = [roomOf(now), roomOf(now, true)].map((r) => r ? `${r.conn.id}.${r.conn.inc}.${r.room}` : "").join("|");
1960
+ if (routing !== routed) {
1961
+ routed = routing;
1962
+ d.changed();
1963
+ }
1964
+ publish();
1965
+ if (now - lastSweep > 6e4) {
1966
+ lastSweep = now;
1967
+ sweep(root, now);
1968
+ const old = Object.entries(q.j.receipts ?? {}).filter(([, r]) => now - r.at > RECEIPT_MS);
1969
+ if (old.length) await q.lock(() => {
1970
+ for (const [k] of old) delete q.j.receipts[k];
1971
+ q.persist();
1972
+ });
1973
+ const held = new Set(open().flatMap((b) => [b.offer?.conn, b.claim?.conn]).filter(Boolean));
1974
+ for (const c of listConns(root)) if (!held.has(c.id) && (c.ended || !alive(c, now)) && now - c.seen > 6e4) closeConn(root, c.id);
1975
+ }
1976
+ };
1977
+ /** the session that takes new work now and its room for more (F3, F4) - `record`: a session's record (F5) */
1978
+ const roomOf = (now = Date.now(), record = false) => {
1979
+ const s = settings();
1980
+ const sel = sessionsOn(s, record ? "record" : void 0) ? selected(now) : void 0;
1981
+ return sel && offerable(sel) ? {
1982
+ conn: sel,
1983
+ room: Math.max(0, maxOf(sel) - load(sel.id))
1984
+ } : void 0;
1985
+ };
1986
+ return {
1987
+ settings: () => {
1988
+ const sel = selected();
1989
+ return settingsOf(root, d.cfg, sel?.agent);
552
1990
  },
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;
1991
+ room: (now) => roomOf(now)?.room ?? 0,
1992
+ taker: (now) => {
1993
+ const r = roomOf(now);
1994
+ return r && r.room > 0 ? r.conn : void 0;
1995
+ },
1996
+ takes: roomOf,
1997
+ selected,
1998
+ choose,
1999
+ run,
2000
+ tick,
2001
+ title: titleOf,
2002
+ delivered(batchId, ok, note) {
2003
+ outcome.set(batchId, {
2004
+ ok,
2005
+ ...note ? { note } : {}
2006
+ });
2007
+ if (outcome.size > 200) outcome.delete(outcome.keys().next().value);
2008
+ const rs = deliveries.get(batchId);
2009
+ if (rs) {
2010
+ deliveries.delete(batchId);
2011
+ for (const r of rs) r({
2012
+ ok,
2013
+ note
2014
+ });
564
2015
  }
565
2016
  },
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 {}
2017
+ async act(batchId, gen, action) {
2018
+ let out = { ok: true };
2019
+ let check = false;
2020
+ await q.lock(() => {
2021
+ const b = byId(batchId);
2022
+ const c = b?.claim;
2023
+ if (!b || !c || c.gen !== gen) {
2024
+ out = {
2025
+ ok: false,
2026
+ error: "the run changed - look again"
2027
+ };
2028
+ return;
2029
+ }
2030
+ if (c.result !== void 0) {
2031
+ out = {
2032
+ ok: false,
2033
+ error: "it just finished - its reply is being posted"
2034
+ };
2035
+ return;
2036
+ }
2037
+ if (action === "again") {
2038
+ c.progress = Date.now();
2039
+ delete c.stalled;
2040
+ delete c.stopping;
2041
+ c.resumed = true;
2042
+ } else {
2043
+ c.stopping = action;
2044
+ delete c.stalled;
2045
+ delete c.resumed;
2046
+ check = true;
2047
+ }
2048
+ q.persist();
2049
+ });
2050
+ if (!out.ok) return out;
2051
+ if (check) {
2052
+ const c = byId(batchId)?.claim;
2053
+ if (c && writerGone(c)) await finishStop(batchId);
588
2054
  }
589
- if (last?.error) failed = true;
590
- const { reply, asks, reanchors, said } = parseAgentText(last?.text ?? "");
2055
+ publish();
2056
+ d.changed();
2057
+ return out;
2058
+ },
2059
+ view(now = Date.now()) {
2060
+ const sel = selected(now);
2061
+ return { sessions: live(now).map((c) => ({
2062
+ id: c.id,
2063
+ agent: c.agent,
2064
+ busy: c.busy,
2065
+ selected: c.id === sel?.id,
2066
+ since: c.since,
2067
+ ...c.mode ? { mode: c.mode } : {}
2068
+ })) };
2069
+ },
2070
+ runnerOf(b) {
2071
+ if (!b?.runner) return void 0;
2072
+ const state = b.offer ? "offered" : b.claim?.stopping ? "stopping" : b.claim?.stalled ? "stalled" : b.claim ? "claimed" : b.runner.kind === "session" ? "waiting" : void 0;
591
2073
  return {
592
- reply,
593
- model: last?.model,
594
- asks,
595
- reanchors,
596
- said,
597
- ok: code === 0 && !failed && !!reply
2074
+ kind: b.runner.kind,
2075
+ agent: b.runner.agent,
2076
+ batch: b.batchId,
2077
+ ...b.claim ? { gen: b.claim.gen } : {},
2078
+ ...state ? { state } : {},
2079
+ ...b.runner.why ? { why: b.runner.why } : {}
598
2080
  };
2081
+ },
2082
+ stop() {
2083
+ stopped = true;
2084
+ for (const w of waiters.values()) w(null);
2085
+ waiters.clear();
599
2086
  }
600
- }
601
- };
2087
+ };
2088
+ }
602
2089
  //#endregion
603
2090
  //#region src/server/jam/daemon.ts
604
2091
  /**
@@ -624,8 +2111,14 @@ const JOB_TIMEOUT_MS = 6e5;
624
2111
  const MAX_ATTEMPTS = 2;
625
2112
  const MAX_OUT = 2e6;
626
2113
  const RESCAN_MS = 5e3;
627
- /** How often a card held by a chat agent's `work start` looks again. */
2114
+ /** 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
2115
  const HOLD_RECHECK_MS = 2e3;
2116
+ /** What each tool's sandbox holds, as a spawned run is told it - only what it really does (spec 29b v2, 24). */
2117
+ const SANDBOX_SAYS = {
2118
+ claude: "the repo is writable, keys are not readable, no network",
2119
+ codex: "the repo is writable, no network; Codex's reviewer judges anything more",
2120
+ cursor: "the repo is writable, no network"
2121
+ };
629
2122
  /** Kill a whole process group (the child is detached, so pid === pgid). Best-effort. */
630
2123
  const fenceGroup = (pid) => {
631
2124
  try {
@@ -647,8 +2140,11 @@ const fenceGroup = (pid) => {
647
2140
  * option that quietly grows back.
648
2141
  */
649
2142
  function agentEnv(from = process.env) {
650
- const { MARVER_CLI_TOKEN: _withheld, ...rest } = from;
651
- return rest;
2143
+ 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;
2144
+ return {
2145
+ ...rest,
2146
+ MARVER_JAM_BACKGROUND: "1"
2147
+ };
652
2148
  }
653
2149
  const FRAME_FILE = /\.(tsx|jsx|html)$/;
654
2150
  /** Every frame FILE under design/scenes, as `frame id -> mtimeMs`. Used to see which frames the
@@ -703,11 +2199,13 @@ const sharedMtimes = (root) => {
703
2199
  }
704
2200
  return out;
705
2201
  };
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;
2202
+ /** Why a `shared` file is refused as the disk sees it, or null: past the lexical check (any case - this filesystem
2203
+ * may not care), its nearest existing ancestor must resolve inside design/, and the resolved path must still be
2204
+ * shared design source - a symlink cannot alias local state, a board file or the outside. The reason is the
2205
+ * validator's own (the owner reads it, F1). */
2206
+ function canonicalSharedWhy(root, f) {
2207
+ const lexical = sharedWhy(f) ?? sharedWhy(f.toLowerCase());
2208
+ if (lexical) return lexical;
711
2209
  try {
712
2210
  const design = realpathSync(join(root, "design"));
713
2211
  let at = join(root, f);
@@ -720,12 +2218,18 @@ function canonicalShared(root, f) {
720
2218
  at = dirname(at);
721
2219
  }
722
2220
  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;
2221
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) return "it is a link that leads outside the design folder";
2222
+ const to = `design/${rel.split(sep).join("/")}`;
2223
+ const why = sharedWhy(to.toLowerCase());
2224
+ return why ? `it is a link to ${to}, and ${why}` : null;
725
2225
  } catch {
726
- return null;
2226
+ return "it is a link that leads nowhere";
727
2227
  }
728
2228
  }
2229
+ /** A `shared` file as the disk sees it (`canonicalSharedWhy` found nothing against it), else null. */
2230
+ function canonicalShared(root, f) {
2231
+ return canonicalSharedWhy(root, f) ? null : f;
2232
+ }
729
2233
  /** The loop, without timers/watch/lock. Loads the queue (upgrading a v1 journal, baselining a
730
2234
  * fresh one); the first `tick()` recovers what a dead process left (the startup barrier), and
731
2235
  * every tick ingests, claims what can run and waits until the work is idle. */
@@ -754,8 +2258,9 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
754
2258
  const runningBatches = /* @__PURE__ */ new Map();
755
2259
  /** every run that starts, counted: a run knows whether another began while it ran */
756
2260
  let batchStarts = 0;
757
- const runAgent = (goal, onSpawn, onEarly) => new Promise((resolve) => {
758
- const { cmd, args, env } = adapter.spawnArgs(goal);
2261
+ const runAgent = (ad, opts, goal, onSpawn, onEarly) => new Promise((resolve) => {
2262
+ const adapter = ad;
2263
+ const { cmd, args, env } = adapter.spawnArgs(goal, opts);
759
2264
  let child;
760
2265
  try {
761
2266
  child = spawn(cmd, args, {
@@ -856,6 +2361,8 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
856
2361
  /** House style: never an em/en dash in a reply - a plain dash reads human. */
857
2362
  const plainDashes = (s) => s.replace(/\s*[—–]\s*/g, " - ");
858
2363
  const me = () => localProfile(root);
2364
+ /** The agent that ran a batch - its runner's, or the one Jam is set to. */
2365
+ const harnessOf = (b) => b.runner?.agent || adapter.name;
859
2366
  /** Post one reply in a card's thread. Deterministic ids - `jam-<batch>-<member>` for the reply,
860
2367
  * `jam-e<attempt>-<batch>` for a one-member job's early ack - so posting twice is a no-op. */
861
2368
  const postReply = (b, c, member, body, asks, model, kind = "reply", alsoChanged) => {
@@ -875,8 +2382,9 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
875
2382
  agent: true,
876
2383
  agentMeta: {
877
2384
  devUser: who.name,
878
- harness: adapter.name,
879
- model
2385
+ harness: harnessOf(b),
2386
+ model,
2387
+ ...b.runner ? { runner: b.runner.kind } : {}
880
2388
  }
881
2389
  };
882
2390
  appendEvents(commentsDir, c.board, [reply]);
@@ -885,6 +2393,131 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
885
2393
  ts: reply.ts
886
2394
  };
887
2395
  };
2396
+ /** How a spawned run reaches this marver (`jam permit`): the repo's install, else the CLI running now. */
2397
+ const marverCmd = () => {
2398
+ const bin = hookBin(root);
2399
+ if (bin) return {
2400
+ cmd: bin,
2401
+ args: []
2402
+ };
2403
+ const here = dirname(fileURLToPath(import.meta.url));
2404
+ const self = [
2405
+ join(here, "cli.mjs"),
2406
+ join(here, "..", "cli.mjs"),
2407
+ join(here, "..", "..", "cli", "index.ts")
2408
+ ].find((f) => existsSync(f));
2409
+ return self ? {
2410
+ cmd: process.execPath,
2411
+ args: [self]
2412
+ } : {
2413
+ cmd: "npx",
2414
+ args: ["--no-install", "marver"]
2415
+ };
2416
+ };
2417
+ const runs = createRuns({
2418
+ root,
2419
+ cfg,
2420
+ q,
2421
+ log,
2422
+ changed: () => {
2423
+ queueChanged();
2424
+ pumpSoon();
2425
+ },
2426
+ goal: (b, handle, conn) => {
2427
+ const as = conn.agent === "cursor" ? conn.id : void 0;
2428
+ let packet = null;
2429
+ try {
2430
+ packet = JSON.parse(readFileSync(join(root, packetPath(b.batchId)), "utf8"));
2431
+ } catch {
2432
+ packet = null;
2433
+ }
2434
+ if (packet && packet.frames.join("\n") !== b.frames.join("\n")) {
2435
+ packet.frames = [...b.frames];
2436
+ writeFileSync(join(root, packetPath(b.batchId)), JSON.stringify(packet, null, 1), { mode: 384 });
2437
+ }
2438
+ return packet ? sessionBrief(packet, handle, as, {
2439
+ agent: conn.agent,
2440
+ conn: conn.id,
2441
+ overlaps: overlapsOf(b, conn)
2442
+ }) : `The packet of this run is missing (${packetPath(b.batchId)}) - release it: \`npx marver jam release ${handle}${as ? ` --as ${as}` : ""}\`.`;
2443
+ },
2444
+ say: (b) => ensureEarly(b),
2445
+ ready: () => ready,
2446
+ jamOn: () => !!q.j.session,
2447
+ canSpawn: (agent) => Object.hasOwn(AGENT_BIN, agent) && onPath(AGENT_BIN[agent]),
2448
+ own: (b, frame) => {
2449
+ if (!/^[\w.@+-]+(\/[\w.@+-]+)+$/.test(frame)) return "name a frame: <scene>/<name>";
2450
+ if (b.frames.includes(frame)) return null;
2451
+ 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`;
2452
+ if (hooks.held?.(frame)) return `your agent in chat is working on ${frame}`;
2453
+ b.frames = [...b.frames, frame];
2454
+ if (!(b.before ?? []).includes(frame)) {
2455
+ b.created = [.../* @__PURE__ */ new Set([...b.created ?? [], frame])];
2456
+ madeScene(b, frame);
2457
+ }
2458
+ reserve();
2459
+ return null;
2460
+ },
2461
+ mayHold: (b, conn) => [...runningBatches.values()].every((x) => x.batchId === b.batchId || !x.frames.some((f) => b.frames.includes(f)) || heldBy(x, conn))
2462
+ });
2463
+ /** 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
2464
+ * made first: the scene is this run's (F5) - its `_` files are no shared file it changed. Under the lock. */
2465
+ function madeScene(b, frame) {
2466
+ const sc = frame.split("/")[0];
2467
+ if (!b.scenes || b.scenes.includes(sc) || q.j.batches.some((x) => x.madeScenes?.includes(sc))) return;
2468
+ b.madeScenes = [...b.madeScenes ?? [], sc];
2469
+ }
2470
+ /** Is a running batch this session incarnation's (F4): offered to it, taken by it and not stopping, or formed for it -
2471
+ * or done editing (its results saved, being posted)? Two such runs may share a frame: the session coordinates them.
2472
+ * Who runs it now decides: one Marver spawned is never a session's, whatever it was formed for (Codex's review: let go
2473
+ * of and spawned, it kept `share`, and a request on its frame went to your session beside it - a journal from before
2474
+ * `share` was cleared on a spawn too) */
2475
+ function heldBy(x, c) {
2476
+ if (x.results) return true;
2477
+ if (x.handoff || x.runner && x.runner.kind !== "session") return false;
2478
+ 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;
2479
+ }
2480
+ /** The runs of this same session incarnation that share a frame with `b` (F4) - named in its brief: their handle (or,
2481
+ * offered and not taken yet, their short id), the frames they share, their title. */
2482
+ 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) => ({
2483
+ handle: x.claim ? handleOf(x, x.claim.gen) : `${x.batchId.slice(0, 8)} (offered, not taken yet)`,
2484
+ frames: x.frames.filter((f) => b.frames.includes(f)),
2485
+ title: runs.title(x)
2486
+ }));
2487
+ /** A session's early line (`marver jam say`), journaled on the batch before it is posted: posted with the id it
2488
+ * names, once - an id already in the log is not posted again (a restart between the two posts it then). */
2489
+ const ensureEarly = (b) => {
2490
+ const e = b.early;
2491
+ const one = b.members.length === 1 ? q.j.cards.find((c) => c.id === b.members[0].card) : void 0;
2492
+ if (!e || !one?.thread || stopped) return false;
2493
+ const id = e.commentId.replace(/^jam-c-/, "jam-");
2494
+ try {
2495
+ if (!readLog(commentsDir, one.board).some((x) => x.id === id)) {
2496
+ const who = me();
2497
+ appendEvents(commentsDir, one.board, [{
2498
+ id,
2499
+ ts: e.ts,
2500
+ type: "reply",
2501
+ commentId: e.commentId,
2502
+ parentId: one.thread,
2503
+ board: one.board,
2504
+ author: who,
2505
+ body: plainDashes(e.body),
2506
+ asks: false,
2507
+ agent: true,
2508
+ agentMeta: {
2509
+ devUser: who.name,
2510
+ harness: harnessOf(b),
2511
+ ...b.runner ? { runner: b.runner.kind } : {}
2512
+ }
2513
+ }]);
2514
+ }
2515
+ hooks.changed?.(one.board);
2516
+ return true;
2517
+ } catch {
2518
+ return false;
2519
+ }
2520
+ };
888
2521
  /** Emit reanchor events for threads the agent re-pinned, in the shared anchor format: each
889
2522
  * element found in the rendered frame the way `comments move` finds it, unchecked when the
890
2523
  * check cannot run, skipped when the frame shows no such element or several. Owner-authored +
@@ -928,7 +2561,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
928
2561
  agent: true,
929
2562
  agentMeta: {
930
2563
  devUser: who.name,
931
- harness: adapter.name
2564
+ harness: harnessOf(b)
932
2565
  }
933
2566
  }]);
934
2567
  n++;
@@ -1081,7 +2714,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1081
2714
  agent: true,
1082
2715
  agentMeta: {
1083
2716
  devUser: who.name,
1084
- harness: adapter.name
2717
+ harness: harnessOf(b)
1085
2718
  }
1086
2719
  }]);
1087
2720
  }
@@ -1131,11 +2764,19 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1131
2764
  const changedBoards = (b) => {
1132
2765
  for (const board of new Set(b.members.map((m) => m.board))) hooks.changed?.(board);
1133
2766
  };
2767
+ /** The session that takes the work now and its room - `record`: the one a session's record goes to (F5) - looked at once */
2768
+ const takersNow = () => {
2769
+ let on;
2770
+ return (record) => (on ??= [runs.takes(), runs.takes(void 0, true)])[record ? 1 : 0];
2771
+ };
2772
+ /** Does a queued card run alone now (queue.ts runsAlone), with the session that takes the work as it is now (F5) */
2773
+ const aloneNow = (taking = takersNow()) => (c) => runsAlone(c, (record) => !!taking(record));
1134
2774
  const reserve = (exclusiveWaiting) => {
1135
2775
  if (stopped) return;
1136
2776
  jamReservations.frames = new Map([...runningBatches.values()].flatMap((b) => b.frames.map((f) => [f, b.batchId])));
1137
2777
  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;
2778
+ const alone = aloneNow();
2779
+ jamReservations.exclusive = exclusiveRunning ? "running" : exclusiveWaiting ?? q.j.cards.some((c) => c.state === "queued" && alone(c)) ? "waiting" : null;
1139
2780
  jamReservations.settling = !ready || delivering.size > 0;
1140
2781
  };
1141
2782
  const queueChanged = () => {
@@ -1153,6 +2794,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1153
2794
  * one would have. */
1154
2795
  const deliver = async (b) => {
1155
2796
  if (stopped) return;
2797
+ if (b.early && !ensureEarly(b)) throw new Error("its early line could not be posted");
1156
2798
  const cards = b.members.map((m) => q.j.cards.find((c) => c.id === m.card)).filter((c) => !!c);
1157
2799
  const early = b.early;
1158
2800
  const posted = {};
@@ -1178,7 +2820,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1178
2820
  agent: true,
1179
2821
  agentMeta: {
1180
2822
  devUser: who.name,
1181
- harness: adapter.name
2823
+ harness: harnessOf(b)
1182
2824
  }
1183
2825
  }]);
1184
2826
  }
@@ -1195,7 +2837,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1195
2837
  agent: true,
1196
2838
  agentMeta: {
1197
2839
  devUser: who.name,
1198
- harness: adapter.name
2840
+ harness: harnessOf(b)
1199
2841
  }
1200
2842
  }]);
1201
2843
  }
@@ -1313,6 +2955,10 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1313
2955
  const { wrapup: _w, ...rest } = brief;
1314
2956
  brief = rest;
1315
2957
  }
2958
+ if (b.others === void 0 || b.others && !runs.settings().others) {
2959
+ brief = ownerOnly(brief, me());
2960
+ m.brief = brief;
2961
+ }
1316
2962
  const t = c.thread ? threadsOf(m.board).find((x) => x.id === c.thread) : void 0;
1317
2963
  members.push({
1318
2964
  id: m.id,
@@ -1351,7 +2997,11 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1351
2997
  }
1352
2998
  }
1353
2999
  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 });
3000
+ const writePacket = () => {
3001
+ packet.frames = [...b.frames];
3002
+ writeFileSync(join(root, packetPath(b.batchId)), JSON.stringify(packet, null, 1), { mode: 384 });
3003
+ };
3004
+ writePacket();
1355
3005
  const cards = () => b.members.map((m) => q.j.cards.find((c) => c.id === m.card)).filter((c) => !!c);
1356
3006
  const lit = /* @__PURE__ */ new Set();
1357
3007
  const light = (f) => {
@@ -1365,9 +3015,12 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1365
3015
  lit.clear();
1366
3016
  };
1367
3017
  const startMtimes = sceneFrameMtimes(root);
3018
+ const sharedBefore = b.exclusive ? null : sharedMtimes(root);
3019
+ const sceneOf = (f) => /^design\/scenes\/([^/]+)\//.exec(f)?.[1];
1368
3020
  await q.lock(() => {
1369
3021
  const made = new Set(b.created ?? []);
1370
3022
  b.before = [.../* @__PURE__ */ new Set([...b.before ?? [], ...[...startMtimes.keys()].filter((f) => !made.has(f))])];
3023
+ if (sharedBefore && !b.scenes) b.scenes = [.../* @__PURE__ */ new Set([...[...sharedBefore.keys()].flatMap((f) => sceneOf(f) ?? []), ...[...startMtimes.keys()].map((f) => f.split("/")[0])])];
1371
3024
  q.persist();
1372
3025
  });
1373
3026
  if (crowded || !aloneAtStart) await q.lock(() => {
@@ -1382,11 +3035,11 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1382
3035
  await q.lock(() => {
1383
3036
  b.created = [...b.created ?? [], ...found];
1384
3037
  b.frames = [.../* @__PURE__ */ new Set([...b.frames, ...b.created])];
3038
+ for (const f of found) madeScene(b, f);
1385
3039
  q.persist();
1386
3040
  });
1387
3041
  reserve();
1388
3042
  };
1389
- const sharedBefore = b.exclusive ? null : sharedMtimes(root);
1390
3043
  const touched = /* @__PURE__ */ new Set();
1391
3044
  for (const f of b.frames) light(f);
1392
3045
  const capturing = cards().some((c) => !!c.capture);
@@ -1402,7 +3055,10 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1402
3055
  if (stopped) return;
1403
3056
  if (s.new) continue;
1404
3057
  const id = await hooks.shoot(s.frame, theme, { batch: b.batchId }, sizes[s.frame]).catch(() => null);
1405
- if (id) s[when] = id;
3058
+ if (id) {
3059
+ s[when] = id;
3060
+ if (when === "before") s.beforeAt = Date.now();
3061
+ }
1406
3062
  }
1407
3063
  if (when === "after") for (const s of shots) if (s.before && s.after && samePicture(s.before, s.after)) s.same = true;
1408
3064
  else delete s.same;
@@ -1431,50 +3087,213 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1431
3087
  reanchors: []
1432
3088
  };
1433
3089
  try {
1434
- while (!stopped && b.attempts < MAX_ATTEMPTS) {
3090
+ if (!b.power) {
3091
+ const s0 = runs.settings();
1435
3092
  await q.lock(() => {
1436
- b.attempts += 1;
1437
- b.leaseUntil = Date.now() + LEASE_MS;
3093
+ b.power = {
3094
+ mcp: s0.mcp,
3095
+ skills: s0.skills
3096
+ };
1438
3097
  q.persist();
1439
3098
  });
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 });
3099
+ }
3100
+ if (b.dropped) {
3101
+ await q.lock((j) => {
3102
+ settled(fail(j, b, "you dropped it while your session had it"));
3103
+ q.persist();
3104
+ });
3105
+ runs.delivered(b.batchId, false, "the owner dropped it");
3106
+ queueChanged();
3107
+ timeRun("agent");
3108
+ return;
3109
+ }
3110
+ let sessionRan = false;
3111
+ const spawnedBefore = b.runner && b.runner.kind !== "session" ? b.runner : void 0;
3112
+ const sessionHeld = !spawnedBefore && !b.handoff && (!!b.claim || !!b.offer || b.runner?.kind === "session");
3113
+ let first = sessionHeld ? { kind: "wait" } : spawnedBefore || b.handoff ? {
3114
+ kind: "fresh",
3115
+ agent: ""
3116
+ } : runs.choose(b);
3117
+ const passedOver = !sessionHeld && !spawnedBefore && !b.handoff && (first.kind === "fork" || first.kind === "fresh") ? first.why : void 0;
3118
+ if (b.early && b.claim) ensureEarly(b);
3119
+ while (!spawnedBefore && !b.handoff && (sessionHeld || first.kind === "session" || first.kind === "wait")) {
1453
3120
  const beat = setInterval(followWork, 2e3);
1454
3121
  beat.unref?.();
1455
3122
  const tAgent = performance.now();
3123
+ let r;
1456
3124
  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);
3125
+ r = await runs.run(b, first.kind === "session" ? first.conn : void 0);
1472
3126
  } finally {
1473
3127
  clearInterval(beat);
1474
3128
  timing.agentMs.push(performance.now() - tAgent);
1475
3129
  }
1476
- logRun(b.batchId, run.raw);
1477
- if (run.ok) break;
3130
+ if (stopped) return;
3131
+ if (b.dropped) {
3132
+ await q.lock((j) => {
3133
+ settled(fail(j, b, "you dropped it while your session had it"));
3134
+ q.persist();
3135
+ });
3136
+ runs.delivered(b.batchId, false, "the owner dropped it");
3137
+ queueChanged();
3138
+ timeRun("agent");
3139
+ return;
3140
+ }
3141
+ if (r) {
3142
+ run = r;
3143
+ sessionRan = true;
3144
+ break;
3145
+ }
3146
+ first = { kind: "wait" };
3147
+ }
3148
+ if (!sessionRan) {
3149
+ let none = false;
3150
+ if (await q.lock((j) => {
3151
+ none = !b.exclusive && !b.frames.length;
3152
+ if (b.handoff !== "queue" && !none && ![...runningBatches.values()].some((o) => o.batchId !== b.batchId && o.frames.some((f) => b.frames.includes(f)))) return false;
3153
+ const spawn = b.handoff === "spawn" || !!spawnedBefore;
3154
+ const why = b.handoffWhy ?? spawnedBefore?.why;
3155
+ const shots = (b.shots ?? []).flatMap((s) => !s.new && s.before ? [{
3156
+ frame: s.frame,
3157
+ before: s.before,
3158
+ ...s.beforeAt ? { at: s.beforeAt } : {}
3159
+ }] : []);
3160
+ const created = b.members.length === 1 ? b.created ?? [] : [];
3161
+ for (const m of b.members) {
3162
+ const c = j.cards.find((x) => x.id === m.card);
3163
+ if (!c || c.state !== "working" || c.batch !== b.batchId) continue;
3164
+ const add = b.frames.filter((f) => !c.frames.includes(f));
3165
+ if (add.length) c.frames = [...c.frames, ...add];
3166
+ const t = requeue(j, c, Date.now());
3167
+ t.alone = joinAlone(t.alone, {
3168
+ ...spawn ? { spawn: true } : {},
3169
+ ...why ? { why } : {},
3170
+ ...created.length ? { created: [...created] } : {},
3171
+ ...shots.length ? { shots: shots.map((s) => ({ ...s })) } : {}
3172
+ });
3173
+ }
3174
+ b.state = "done";
3175
+ b.at = Date.now();
3176
+ b.note = none ? "back in the queue - with no frame, it runs alone" : "back in the queue - another runner holds one of its frames";
3177
+ q.persist();
3178
+ return true;
3179
+ })) {
3180
+ 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");
3181
+ queueChanged();
3182
+ timeRun("other");
3183
+ return;
3184
+ }
3185
+ const ch = spawnedBefore ? {
3186
+ kind: spawnedBefore.kind,
3187
+ agent: spawnedBefore.agent,
3188
+ ...spawnedBefore.session ? { session: spawnedBefore.session } : {},
3189
+ ...spawnedBefore.why ? { why: spawnedBefore.why } : {}
3190
+ } : (() => {
3191
+ const pick = runs.choose(b, Date.now(), true);
3192
+ const p = pick.kind === "fork" || pick.kind === "fresh" ? pick : {
3193
+ kind: "fresh",
3194
+ agent: cfg.agent
3195
+ };
3196
+ 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;
3197
+ return why && !("why" in p && p.why) ? {
3198
+ ...p,
3199
+ why
3200
+ } : p;
3201
+ })();
3202
+ const agent = Object.hasOwn(adapters, ch.agent) ? ch.agent : cfg.agent;
3203
+ const ad = agent === cfg.agent ? adapter : adapters[agent];
3204
+ const s = {
3205
+ mcp: b.power?.mcp ?? true,
3206
+ skills: b.power?.skills ?? true
3207
+ };
3208
+ const full = agent === "claude" || agent === "codex" || agent === "cursor";
3209
+ const opts = full ? {
3210
+ root,
3211
+ mcp: s.mcp,
3212
+ skills: s.skills,
3213
+ ...ch.kind === "fork" && ch.session ? { fork: ch.session } : {},
3214
+ marver: marverCmd()
3215
+ } : void 0;
3216
+ await q.lock(() => {
3217
+ b.runner = {
3218
+ kind: ch.kind,
3219
+ agent,
3220
+ ...ch.kind === "fork" && ch.session ? { session: ch.session } : {},
3221
+ ...ch.why ? { why: ch.why } : {}
3222
+ };
3223
+ delete b.handoff;
3224
+ delete b.share;
3225
+ q.persist();
3226
+ });
3227
+ queueChanged();
3228
+ const permit = await takePermit();
3229
+ try {
3230
+ while (!stopped && b.attempts < MAX_ATTEMPTS) {
3231
+ await q.lock(() => {
3232
+ b.attempts += 1;
3233
+ b.leaseUntil = Date.now() + LEASE_MS;
3234
+ q.persist();
3235
+ });
3236
+ for (const m of packet.members) if (m.kind === "wrapup") {
3237
+ const c = q.j.cards.find((x) => x.id === m.card);
3238
+ const w = c && readWrapup(root, wrapupOf(c));
3239
+ 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");
3240
+ m.brief = {
3241
+ ...m.brief,
3242
+ wrapup: {
3243
+ content: w.wrapup,
3244
+ hash: w.hash
3245
+ }
3246
+ };
3247
+ }
3248
+ writePacket();
3249
+ const beat = setInterval(followWork, 2e3);
3250
+ beat.unref?.();
3251
+ const tAgent = performance.now();
3252
+ try {
3253
+ const one = b.members.length === 1 ? cards()[0] : void 0;
3254
+ const forked = b.runner?.kind === "fork" ? b.runner.session : void 0;
3255
+ const goal = goalText(packet, cfg.subagents && ad.supportsSubagents, full ? {
3256
+ kind: forked ? "fork" : "fresh",
3257
+ shell: true,
3258
+ mcp: s.mcp,
3259
+ skills: s.skills,
3260
+ sandbox: SANDBOX_SAYS[agent]
3261
+ } : void 0);
3262
+ run = await runAgent(ad, opts && {
3263
+ ...opts,
3264
+ fork: forked
3265
+ }, goal, (pid) => {
3266
+ b.pgid = pid;
3267
+ q.persist();
3268
+ }, one?.thread && !b.early ? (text, asks, model) => {
3269
+ if (stopped) return;
3270
+ const p = postReply(b, one, "m1", text, asks, model, "early");
3271
+ early = {
3272
+ body: text,
3273
+ asks,
3274
+ commentId: p.commentId,
3275
+ ts: p.ts
3276
+ };
3277
+ hooks.changed?.(one.board);
3278
+ } : void 0);
3279
+ if (!run.ok && forked) await q.lock(() => {
3280
+ b.runner = {
3281
+ kind: "fresh",
3282
+ agent,
3283
+ why: "the copy of your session could not run - a fresh agent took it"
3284
+ };
3285
+ q.persist();
3286
+ });
3287
+ } finally {
3288
+ clearInterval(beat);
3289
+ timing.agentMs.push(performance.now() - tAgent);
3290
+ }
3291
+ logRun(b.batchId, run.raw);
3292
+ if (run.ok) break;
3293
+ }
3294
+ } finally {
3295
+ permit();
3296
+ }
1478
3297
  }
1479
3298
  if (stopped) return;
1480
3299
  if (!run.ok) {
@@ -1484,6 +3303,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1484
3303
  settled(fail(j, b, "the agent could not finish - its run log is in design/.local/jam-logs"));
1485
3304
  q.persist();
1486
3305
  });
3306
+ runs.delivered(b.batchId, false, "the run failed");
1487
3307
  queueChanged();
1488
3308
  log(` jam: gave up on a batch of ${b.members.length} after ${b.attempts} attempts`);
1489
3309
  timeRun("agent");
@@ -1529,13 +3349,22 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1529
3349
  }
1530
3350
  if (capturing) timing.afterMs = performance.now() - tAfter;
1531
3351
  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) : [];
3352
+ const changedShared = sharedBefore ? [...sharedMtimes(root)].filter(([f, mt]) => {
3353
+ const sc = sceneOf(f);
3354
+ return sharedBefore.get(f) !== mt && !(sc && b.madeScenes?.includes(sc));
3355
+ }).map(([f]) => f) : [];
1533
3356
  const results = {};
1534
3357
  for (const [id, r0] of Object.entries(split)) {
1535
3358
  let r = r0;
1536
3359
  if ("shared" in r) {
1537
3360
  const files = r.shared.map(realShared).filter((f) => !!f);
1538
- r = files.length ? { shared: files } : { missing: true };
3361
+ r = files.length ? { shared: files } : {
3362
+ body: refusedAsk(r.shared.map((f) => ({
3363
+ file: f,
3364
+ why: canonicalSharedWhy(root, f) ?? "it could not be read"
3365
+ }))),
3366
+ asks: true
3367
+ };
1539
3368
  }
1540
3369
  results[id] = "body" in r ? {
1541
3370
  body: r.body,
@@ -1560,8 +3389,10 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1560
3389
  } catch (err) {
1561
3390
  timing.deliverMs = performance.now() - tDeliver;
1562
3391
  timeRun("delivery");
3392
+ runs.delivered(b.batchId, true, "retrying");
1563
3393
  throw err;
1564
3394
  }
3395
+ runs.delivered(b.batchId, true);
1565
3396
  timing.deliverMs = performance.now() - tDeliver;
1566
3397
  timeRun();
1567
3398
  } finally {
@@ -1573,24 +3404,45 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1573
3404
  }
1574
3405
  };
1575
3406
  /** 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;
3407
+ * fails closed), ledger it, and end the step. Called under the lock, synchronously; resumable at any point. */
3408
+ const finishIn = (j, c) => {
3409
+ const p = c.pending;
3410
+ if (!p) return;
1581
3411
  const there = readLog(commentsDir, c.board).find((e) => e.id === p.event.id);
1582
3412
  if (there && !sameComment(there, p.event)) {
1583
3413
  conflictStep(j, c);
1584
3414
  q.persist();
1585
- return structuredClone(c);
3415
+ return;
1586
3416
  }
1587
3417
  if (!there) appendEvents(commentsDir, c.board, [p.event]);
1588
3418
  record(root, c.board, p.event.id);
1589
3419
  if (p.op === "confirm") record(root, c.board, payloadKey(c));
1590
3420
  settled(endStep(j, c));
1591
3421
  q.persist();
3422
+ };
3423
+ const finishStep = (id) => q.lock((j) => {
3424
+ const c = j.cards.find((x) => x.id === id);
3425
+ if (!c) return void 0;
3426
+ finishIn(j, c);
1592
3427
  return structuredClone(c);
1593
3428
  });
3429
+ /** Where a capture's comment is pinned: on its first point (found in the rendered frame), else its first frame,
3430
+ * else the board. A render - so it is looked up before any lock is taken. */
3431
+ const pinOf = async (record) => {
3432
+ const point = firstPoint(record);
3433
+ let at = { frame: point?.frame ?? captureFrames(record)[0] };
3434
+ if (point?.frame && hooks.anchor) {
3435
+ 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;
3436
+ if (target) {
3437
+ const check = await hooks.anchor(point.frame, target, [], void 0).catch(() => null);
3438
+ if (check?.ok) at = {
3439
+ frame: point.frame,
3440
+ anchor: check.anchor
3441
+ };
3442
+ }
3443
+ }
3444
+ return at;
3445
+ };
1594
3446
  /** Confirm a draft (`end: queued`) or keep it from its read-back (`end: kept`): one recoverable step.
1595
3447
  * A retried request after a lost answer finds the step done and answers with the card. */
1596
3448
  const confirm = async (id, rev, end) => {
@@ -1623,18 +3475,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1623
3475
  card: structuredClone(c0),
1624
3476
  error: "the capture changed after it was sealed"
1625
3477
  };
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
- }
3478
+ const at = await pinOf(cap.record);
1638
3479
  if (!await q.lock((j) => {
1639
3480
  const c = j.cards.find((x) => x.id === id);
1640
3481
  if (!c || c.state !== "draft" || c.rev !== rev) return null;
@@ -1762,12 +3603,43 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1762
3603
  }
1763
3604
  return r;
1764
3605
  };
3606
+ /** A pump soon, once however often it is asked for, outside whatever lock asks for it. */
3607
+ let pumpDue = null;
3608
+ const pumpSoon = () => {
3609
+ if (pumpDue || stopped) return;
3610
+ pumpDue = setTimeout(() => {
3611
+ pumpDue = null;
3612
+ pump().catch((err) => log(` jam: pump error - ${err.message}`));
3613
+ }, 0);
3614
+ pumpDue.unref?.();
3615
+ };
3616
+ /** Spawned processes at once: never more than jam.concurrency, whatever routing decided - a run that falls back from
3617
+ * your session (released, withdrawn, moved by you, a restart) takes a permit before its first attempt and gives it
3618
+ * back after its last (Codex's review of the F3 design). First come, first served. */
3619
+ const permits = {
3620
+ free: Math.max(1, cfg.concurrency),
3621
+ waiting: []
3622
+ };
3623
+ const takePermit = () => new Promise((res) => {
3624
+ const grant = () => {
3625
+ permits.free -= 1;
3626
+ let back = false;
3627
+ res(() => {
3628
+ if (back) return;
3629
+ back = true;
3630
+ permits.free += 1;
3631
+ permits.waiting.shift()?.();
3632
+ });
3633
+ };
3634
+ if (permits.free > 0 && !permits.waiting.length) grant();
3635
+ else permits.waiting.push(grant);
3636
+ });
1765
3637
  let recheck = null;
1766
3638
  const holdLater = () => {
1767
3639
  if (recheck || stopped) return;
1768
3640
  recheck = setTimeout(() => {
1769
3641
  recheck = null;
1770
- pump();
3642
+ pump().catch((err) => log(` jam: pump error - ${err.message}`));
1771
3643
  }, HOLD_RECHECK_MS);
1772
3644
  recheck.unref?.();
1773
3645
  };
@@ -1791,16 +3663,43 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1791
3663
  }
1792
3664
  const started = await q.lock((j, ctx) => {
1793
3665
  noteQueued();
3666
+ const moved = () => `${j.batches.length}|${j.cards.map((c) => `${c.id}:${c.rev}`).join()}`;
3667
+ const was = moved();
1794
3668
  const frames = new Set([...runningBatches.values()].flatMap((b) => b.frames));
3669
+ const sessionSide = (x) => x.handoff !== "spawn" && (!!x.offer || !!x.claim || x.runner?.kind === "session");
3670
+ const spawned = [...runningBatches.values()].filter((x) => !sessionSide(x)).length;
3671
+ const taker = runs.taker();
3672
+ const taking = takersNow();
1795
3673
  const { batches, exclusiveWaiting } = form(j, ctx, {
1796
- free: Math.max(1, cfg.concurrency) - runningBatches.size,
3674
+ session: (record) => {
3675
+ const t = taking(record);
3676
+ return t && {
3677
+ conn: t.conn.id,
3678
+ inc: t.conn.inc,
3679
+ room: t.room
3680
+ };
3681
+ },
3682
+ free: Math.max(1, cfg.concurrency) - spawned + runs.room(),
3683
+ ...taker ? {
3684
+ share: (f) => {
3685
+ const hs = [...runningBatches.values()].filter((x) => x.frames.includes(f));
3686
+ return hs.length && hs.every((x) => !x.exclusive && heldBy(x, taker)) ? hs.map((x) => x.batchId) : null;
3687
+ },
3688
+ shareRoom: runs.room(),
3689
+ sharer: {
3690
+ conn: taker.id,
3691
+ inc: taker.inc
3692
+ }
3693
+ } : {},
1797
3694
  running: frames,
3695
+ active: runningBatches.size,
1798
3696
  exclusiveRunning: [...runningBatches.values()].some((b) => b.exclusive),
1799
3697
  held: (f) => !!hooks.held?.(f),
1800
- anyHold: () => !!hooks.anyHold?.()
3698
+ anyHold: () => !!hooks.anyHold?.(),
3699
+ others: runs.settings().others
1801
3700
  });
1802
3701
  prune(j);
1803
- q.persist();
3702
+ if (moved() !== was) q.persist();
1804
3703
  for (const b of batches) runningBatches.set(b.batchId, b);
1805
3704
  const now = performance.now();
1806
3705
  for (const b of batches) batchWaits.set(b.batchId, new Map(b.members.flatMap((m) => {
@@ -1810,14 +3709,12 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1810
3709
  reserve(exclusiveWaiting);
1811
3710
  for (const c of j.cards) {
1812
3711
  if (c.state !== "queued") continue;
3712
+ holdLater();
1813
3713
  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);
3714
+ if (held && !waitingSaid.has(c.id)) {
3715
+ waitingSaid.add(c.id);
3716
+ log(` jam: waiting - ${held} is being worked on in chat; the comment runs once it is done`);
3717
+ } else if (!held) waitingSaid.delete(c.id);
1821
3718
  }
1822
3719
  return batches;
1823
3720
  });
@@ -1900,6 +3797,7 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1900
3797
  log(` jam: batch error - ${err.message}`);
1901
3798
  if (b.results) redeliver(b, 1);
1902
3799
  else {
3800
+ runs.delivered(b.batchId, false, err.message);
1903
3801
  try {
1904
3802
  await q.lock((j) => {
1905
3803
  settled(fail(j, b, `the job broke: ${err.message}`));
@@ -1936,6 +3834,13 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
1936
3834
  });
1937
3835
  continue;
1938
3836
  }
3837
+ if (b.claim) {
3838
+ out.push({
3839
+ b,
3840
+ results: false
3841
+ });
3842
+ continue;
3843
+ }
1939
3844
  fenceGroup(b.pgid);
1940
3845
  const ctx = q.ctx();
1941
3846
  const logs = /* @__PURE__ */ new Map();
@@ -2130,8 +4035,9 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2130
4035
  }];
2131
4036
  });
2132
4037
  };
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'`. */
4038
+ /** A sealed capture taken in: checked (and, resumed, as a continuation), stored, ledgered - ended with E, a card
4039
+ * queued in the same step that makes it; ended with ⇧E (or sealed by its page leaving), a draft card. `held`: an
4040
+ * E capture the queue would not take - it stays a draft, and this says why (the page says so in one line). */
2135
4041
  const landCapture = async (rec) => {
2136
4042
  const rs = rec.context.resumes;
2137
4043
  if (rs && !storedOnce(rec)) {
@@ -2151,13 +4057,32 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2151
4057
  error: stored
2152
4058
  };
2153
4059
  record(root, rec.context.board, `capture:${rec.id}:${stored.hash}`);
2154
- const card = await q.lock((j) => {
4060
+ const auto = !rec.context.interrupted && !rec.context.review;
4061
+ const at = auto && !storedOnce(rec) ? await pinOf(rec) : void 0;
4062
+ let card = await q.lock((j) => {
4063
+ const fresh = !j.cards.some((c) => c.id === rec.id);
2155
4064
  const c = addCapture(j, rec, stored.hash);
4065
+ if (fresh && at) {
4066
+ beginStep(j, c, "confirm", captureComment(c, rec, at, me()), Date.now(), "queued");
4067
+ q.persist();
4068
+ finishIn(j, c);
4069
+ }
2156
4070
  q.persist();
2157
4071
  return structuredClone(c);
2158
4072
  });
4073
+ if (card.pending?.op === "confirm") card = await finishStep(card.id) ?? card;
4074
+ if (auto && card.state === "draft" && !card.note) {
4075
+ const r = await confirm(card.id, card.rev, "queued");
4076
+ if ("card" in r && r.card) card = r.card;
4077
+ }
4078
+ reserve();
2159
4079
  queueChanged();
2160
- if (cfg.capture === "at-once" && card.state === "draft" && !rec.context.interrupted) return confirm(card.id, card.rev, "queued");
4080
+ pump();
4081
+ if (auto && card.state === "draft") return {
4082
+ ok: true,
4083
+ card,
4084
+ held: card.note ?? "it could not be queued"
4085
+ };
2161
4086
  return {
2162
4087
  ok: true,
2163
4088
  card
@@ -2233,7 +4158,11 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2233
4158
  let viewN = 0;
2234
4159
  const view = () => {
2235
4160
  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);
4161
+ const busyFrame = (c) => c.frames.find((f) => jamReservations.frames.has(f) || !!hooks.held?.(f));
4162
+ const taking = takersNow();
4163
+ const alone = aloneNow(taking);
4164
+ const full = (c) => !c.frames.length && !alone(c) && (taking(c.kind === "wrapup")?.room ?? 0) < 1;
4165
+ 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
4166
  const shown = j.cards.filter((c) => pending(c) || c.at > Date.now() - 6e4 || !!j.run && c.kind !== "comment" && c.made >= j.run.since);
2238
4167
  const exclusiveAhead = jamReservations.exclusive;
2239
4168
  return {
@@ -2245,9 +4174,14 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2245
4174
  ...q.j.run ? { run: q.j.run } : {},
2246
4175
  ...q.j.session ? { session: q.j.session } : {},
2247
4176
  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;
4177
+ const busy = c.state === "queued" ? busyFrame(c) : void 0;
4178
+ const holder = busy ? j.batches.find((b) => b.batchId === jamReservations.frames.get(busy)) : void 0;
4179
+ const waitsFor = busy ? {
4180
+ frame: busy,
4181
+ ...holder ? { by: runs.title(holder) } : hooks.held?.(busy) ? { by: "chat" } : {}
4182
+ } : void 0;
4183
+ const position = c.state === "queued" && !busy && !full(c) ? queued.indexOf(c) + 1 : void 0;
4184
+ const waiting = c.state === "queued" && exclusiveAhead === "waiting" && alone(c) ? "alone" : c.state === "queued" && exclusiveAhead ? "behind" : c.state === "queued" && full(c) ? "session" : void 0;
2251
4185
  return {
2252
4186
  id: c.id,
2253
4187
  kind: c.kind,
@@ -2265,19 +4199,30 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2265
4199
  ...c.reply ? { reply: c.reply } : {},
2266
4200
  ...c.batch ? { batch: c.batch } : {},
2267
4201
  ...position ? { position } : {},
4202
+ ...waitsFor ? { waitsFor } : {},
2268
4203
  ...waiting ? { waiting } : {},
2269
4204
  ...c.exclusive ? { exclusive: true } : {},
2270
- ...c.kind !== "comment" ? captureView(c) : {}
4205
+ ...c.kind !== "comment" ? captureView(c) : {},
4206
+ ...c.state === "working" ? (() => {
4207
+ const r = runs.runnerOf(j.batches.find((b) => b.batchId === c.batch));
4208
+ return r ? { runner: r } : {};
4209
+ })() : {}
2271
4210
  };
2272
- })
4211
+ }),
4212
+ ...runs.view(),
4213
+ settings: runs.settings()
2273
4214
  };
2274
4215
  };
2275
4216
  return {
2276
4217
  tick,
4218
+ runs,
2277
4219
  stop() {
2278
4220
  stopped = true;
2279
4221
  jamReservations.settling = false;
4222
+ runs.stop();
2280
4223
  if (recheck) clearTimeout(recheck);
4224
+ if (pumpDue) clearTimeout(pumpDue);
4225
+ for (const w of permits.waiting.splice(0)) w();
2281
4226
  for (const t of timers) clearTimeout(t);
2282
4227
  timers.clear();
2283
4228
  for (const wake of naps) wake();
@@ -2443,8 +4388,28 @@ function createJam(root, cfg, adapter, log = () => {}, hooks = {}) {
2443
4388
  },
2444
4389
  async act(id, rev, action, body) {
2445
4390
  const c = q.j.cards.find((x) => x.id === id);
4391
+ if (action === "session-again" || action === "session-background" || action === "session-drop") {
4392
+ if (!c || c.rev !== rev) return {
4393
+ ok: false,
4394
+ ...c ? { card: structuredClone(c) } : {},
4395
+ error: "the card changed - look again"
4396
+ };
4397
+ const b = q.j.batches.find((x) => x.batchId === c.batch);
4398
+ if (!b?.claim) return {
4399
+ ok: false,
4400
+ card: structuredClone(c),
4401
+ error: "no session holds it now"
4402
+ };
4403
+ const r = await runs.act(b.batchId, b.claim.gen, action === "session-again" ? "again" : action === "session-background" ? "background" : "drop");
4404
+ queueChanged();
4405
+ return {
4406
+ ...r,
4407
+ card: structuredClone(c)
4408
+ };
4409
+ }
2446
4410
  if (c?.kind === "capture" && (action === "confirm" || action === "keep" && (c.state === "draft" || c.state === "confirming"))) return confirm(id, rev, action === "confirm" ? "queued" : "kept");
2447
4411
  if (action === "good" && c && c.kind !== "comment") return good(id, rev);
4412
+ if (action === "more" && c && c.kind !== "comment" && c.state === "review" && isApproval(body ?? "")) return good(id, rev);
2448
4413
  if (action === "more" && c && c.kind !== "comment") return moreWork(id, rev, body ?? "");
2449
4414
  const saved = await q.lock((j) => {
2450
4415
  const c = j.cards.find((x) => x.id === id);
@@ -2539,6 +4504,36 @@ function startJam(root, cfg, log = () => {}, onChanged = () => {}, anchor, onQue
2539
4504
  } catch {}
2540
4505
  const interval = setInterval(() => void core.poke(), RESCAN_MS);
2541
4506
  interval.unref?.();
4507
+ let ticking = false;
4508
+ const runTick = () => {
4509
+ if (ticking || stopped) return;
4510
+ ticking = true;
4511
+ core.runs.tick().catch((err) => log(` jam: session tick error - ${err.message}`)).finally(() => {
4512
+ ticking = false;
4513
+ });
4514
+ };
4515
+ const sessionWatchers = [];
4516
+ let pushDue = null;
4517
+ const connsChanged = () => {
4518
+ runTick();
4519
+ pushDue ??= setTimeout(() => {
4520
+ pushDue = null;
4521
+ try {
4522
+ onQueue?.();
4523
+ } catch {}
4524
+ }, 250);
4525
+ };
4526
+ for (const [dir, on] of [[reqDir(root), runTick], [connDir(root), connsChanged]]) try {
4527
+ mkdirSync(dir, {
4528
+ recursive: true,
4529
+ mode: 448
4530
+ });
4531
+ const w = watch(dir, { persistent: false }, on);
4532
+ w.on("error", () => {});
4533
+ sessionWatchers.push(w);
4534
+ } catch {}
4535
+ const sessionInterval = setInterval(runTick, 2e3);
4536
+ sessionInterval.unref?.();
2542
4537
  core.tick();
2543
4538
  jamLive.poke = () => void core.poke();
2544
4539
  jamLive.view = () => core.view();
@@ -2550,12 +4545,22 @@ function startJam(root, cfg, log = () => {}, onChanged = () => {}, anchor, onQue
2550
4545
  jamLive.canWrap = (id) => core.canWrap(id);
2551
4546
  jamLive.captureOpen = (c, ses, on) => core.captureOpen(c, ses, on);
2552
4547
  jamLive.tags = (id) => core.tags(id);
4548
+ jamLive.runAct = (batch, gen, action) => core.runs.act(batch, gen, action);
4549
+ jamLive.refresh = () => {
4550
+ try {
4551
+ onQueue?.();
4552
+ } catch {}
4553
+ runTick();
4554
+ };
2553
4555
  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
4556
  return { stop() {
2555
4557
  stopped = true;
2556
4558
  if (scheduled) clearTimeout(scheduled);
2557
4559
  clearInterval(interval);
4560
+ clearInterval(sessionInterval);
4561
+ if (pushDue) clearTimeout(pushDue);
2558
4562
  watcher?.close();
4563
+ for (const w of sessionWatchers) w.close();
2559
4564
  core.stop();
2560
4565
  delete jamLive.poke;
2561
4566
  delete jamLive.view;