@marver-design/marver 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +3 -1
  3. package/dist/{anchor-DVV732zR.mjs → anchor-5H1vnoLu.mjs} +6 -1
  4. package/dist/{anchor-check-BE5VVN6Q.mjs → anchor-check-Dg5xpNnU.mjs} +1 -1
  5. package/dist/audio-CmSRYFEs.mjs +429 -0
  6. package/dist/{auth-DdUKeVKt.mjs → auth-Dix8wrXV.mjs} +1 -1
  7. package/dist/{bake-D8byeRzB.mjs → bake-DtVlm0_F.mjs} +45 -6
  8. package/dist/{boards-Csxj2WJn.mjs → boards-DYG22tOe.mjs} +2 -2
  9. package/dist/{build-BHoWLvSj.mjs → build-C_gUgcdC.mjs} +16 -9
  10. package/dist/capture-CrqvU_jh.mjs +729 -0
  11. package/dist/cli.mjs +23 -17
  12. package/dist/{collab-gqNdScUE.mjs → collab-Dxg2trOK.mjs} +4 -3
  13. package/dist/{comments-Zoch254k.mjs → comments-0BSbb04K.mjs} +14 -3
  14. package/dist/{comments-pTLlhjh4.mjs → comments-BqXua-XL.mjs} +7 -7
  15. package/dist/{config-cKgZBRj0.mjs → config-Cf7EjAMf.mjs} +12 -1
  16. package/dist/{context-D2ugHqwO.mjs → context-HQ4Giw58.mjs} +1 -1
  17. package/dist/daemon-DZo6o3rU.mjs +2445 -0
  18. package/dist/{dev-DJdgow47.mjs → dev-_Nlsc6v9.mjs} +189 -18
  19. package/dist/dev-lock-DWSpa6nj.mjs +179 -0
  20. package/dist/{events-DnK_AnrW.mjs → events-CLH4ijKP.mjs} +14 -4
  21. package/dist/{init-DO4DhUt_.mjs → init-D8DtrK_F.mjs} +2 -2
  22. package/dist/{ledger-BNXW14Xw.mjs → ledger-D54iROST.mjs} +17 -1
  23. package/dist/{link-C-qUIuKU.mjs → link-BNzLvdhI.mjs} +2 -2
  24. package/dist/live-Cgzsicwi.mjs +4 -0
  25. package/dist/{manifest-DnAte_fB.mjs → manifest-Nl3KSVOk.mjs} +1 -1
  26. package/dist/{marks-koRsbHfe.mjs → marks-CKgzucHZ.mjs} +2 -2
  27. package/dist/{marks-DFuintmJ.mjs → marks-NQi0wZJ4.mjs} +23 -5
  28. package/dist/{marver-id-gate-DGANtVyC.mjs → marver-id-gate-BjF6v4bT.mjs} +4 -4
  29. package/dist/{perf-QJIWtTw1.mjs → perf-D6VmmJ2q.mjs} +1 -1
  30. package/dist/{perf-CCisg-ny.mjs → perf-DPbLGhhO.mjs} +1 -1
  31. package/dist/{plugin-CTyhjwoJ.mjs → plugin-CTD0rydA.mjs} +279 -38
  32. package/dist/{poster-D0cbV7hi.mjs → poster-ChjXGTS5.mjs} +1 -1
  33. package/dist/{profile-Do0nGkXO.mjs → profile-WU9qcbIo.mjs} +1 -1
  34. package/dist/{publish-bakes--l8ot2eQ.mjs → publish-bakes-CEP_2NRc.mjs} +3 -3
  35. package/dist/queue-BuiCKSX1.mjs +1319 -0
  36. package/dist/reserve-BURNQ2Y3.mjs +53 -0
  37. package/dist/{rolldown-runtime-D7D4PA-g.mjs → rolldown-runtime-8H4AJuhK.mjs} +1 -0
  38. package/dist/{serve-wv2QWdxB.mjs → serve-C8rVheYk.mjs} +12 -12
  39. package/dist/session-qZWKt_VA.mjs +191 -0
  40. package/dist/{share-ScamJcks.mjs → share--oFJ1bCI.mjs} +2 -2
  41. package/dist/{shot-jdO_B6Qw.mjs → shot-CNbHoZ6H.mjs} +1 -1
  42. package/dist/{shot-CckrGW-J.mjs → shot-DqcxJibP.mjs} +4 -3
  43. package/dist/speech-models-DomiLQcY.mjs +299 -0
  44. package/dist/speech-worker.mjs +319 -0
  45. package/dist/{summary-CrW88e3q.mjs → summary-Y8MY1Wuc.mjs} +2 -2
  46. package/dist/{sync-C3035OnJ.mjs → sync-DKk-yT1V.mjs} +9 -8
  47. package/dist/{work-GE88wb_3.mjs → work-F5u-twpJ.mjs} +28 -5
  48. package/dist/{work-CpJn1gwY.mjs → work-VvX_JIgl.mjs} +2 -2
  49. package/docs/jam-session.md +177 -0
  50. package/docs/live-jam.md +21 -3
  51. package/package.json +7 -1
  52. package/src/client/frame-host/bridge.js +20 -2
  53. package/src/client/frame-host/inspect.d.ts +4 -0
  54. package/src/client/frame-host/inspect.js +88 -3
  55. package/src/client/frame-host/keys.d.ts +6 -0
  56. package/src/client/frame-host/keys.js +55 -0
  57. package/src/client/frame-host/trail.d.ts +7 -0
  58. package/src/client/frame-host/trail.js +204 -0
  59. package/src/client/shell/App.tsx +45 -5
  60. package/src/client/shell/Comments.tsx +20 -6
  61. package/src/client/shell/JamSurface.tsx +340 -0
  62. package/src/client/shell/Play.tsx +22 -3
  63. package/src/client/shell/Tip.tsx +8 -3
  64. package/src/client/shell/canvas/Canvas.tsx +12 -2
  65. package/src/client/shell/canvas/FrameNode.tsx +11 -2
  66. package/src/client/shell/canvas/sleep.ts +19 -1
  67. package/src/client/shell/comments-store.ts +23 -16
  68. package/src/client/shell/icons.tsx +15 -0
  69. package/src/client/shell/jam-capture.ts +939 -0
  70. package/src/client/shell/jam-keys.ts +329 -0
  71. package/src/client/shell/jam-lane.tsx +208 -0
  72. package/src/client/shell/jam-lines.ts +115 -0
  73. package/src/client/shell/jam-panel.tsx +506 -0
  74. package/src/client/shell/jam-queue.ts +126 -0
  75. package/src/client/shell/jam-session.tsx +389 -0
  76. package/src/client/shell/jam-state.ts +61 -0
  77. package/src/client/shell/jam-surface-parts.tsx +102 -0
  78. package/src/client/shell/jam-ui.tsx +104 -0
  79. package/src/client/shell/jam-voice.ts +479 -0
  80. package/src/client/shell/sound.ts +22 -0
  81. package/src/client/shell/stage-size.ts +11 -0
  82. package/src/client/shell/store.ts +34 -13
  83. package/src/client/shell/styles.css +544 -2
  84. package/src/client/stage/main.tsx +16 -2
  85. package/src/shared/capture-frames.ts +41 -0
  86. package/src/shared/events.ts +19 -4
  87. package/src/shared/speech.ts +16 -0
  88. package/templates/AGENTS-embedded.md +10 -2
  89. package/templates/AGENTS-studio.md +10 -2
  90. package/templates/instructions/iterate.md +8 -6
  91. package/templates/instructions/jam.md +129 -59
  92. package/dist/daemon-Cl8KXGW4.mjs +0 -1523
@@ -0,0 +1,1319 @@
1
+ import { r as pidRuns, t as createExclusive } from "./dev-lock-DWSpa6nj.mjs";
2
+ import { r as replay } from "./events-CLH4ijKP.mjs";
3
+ import { a as readLog, i as listBoards } from "./comments-0BSbb04K.mjs";
4
+ import { a as deviceId, r as owned } from "./ledger-D54iROST.mjs";
5
+ import { S as threadId, _ as packetPath, b as sanitize, f as readCapture, h as buildPacket, l as hashOf, m as wordsSince, n as captureFrames, r as captureWords, s as factsOf, u as madeOf } from "./capture-CrqvU_jh.mjs";
6
+ import { i as readWrapup, o as recordPathProblem } from "./session-qZWKt_VA.mjs";
7
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { randomBytes, randomUUID } from "node:crypto";
10
+ //#region src/server/jam/journal.ts
11
+ /**
12
+ * The durable batch journal - design/.local/jam-jobs.json.
13
+ *
14
+ * This is job-DELIVERY state (event ids + batch status), never comment content and never the
15
+ * agent session id (that stays in daemon memory), so it is not the session/form state the
16
+ * privacy rule forbids. Written atomically (temp + rename + fsync) and torn-write tolerant:
17
+ * a corrupt or absent file is treated as a fresh journal, which the activation baseline then
18
+ * seeds so enabling Live Jam never replays every old @marver.
19
+ *
20
+ * Version 2 (0.26) holds cards and batches; a v1 journal is upgraded once by the queue
21
+ * (queue.ts `createQueue`). A single daemon per repo is enforced by an advisory pid lock; a second dev
22
+ * server on the same root runs without the jam loop.
23
+ */
24
+ const localDir = (root) => join(root, "design", ".local");
25
+ const journalFile = (root) => join(localDir(root), "jam-jobs.json");
26
+ const lockFile = (root) => join(localDir(root), "jam.lock");
27
+ const fresh = () => ({
28
+ version: 2,
29
+ device: deviceId(),
30
+ baselined: false,
31
+ seen: [],
32
+ cards: [],
33
+ batches: [],
34
+ covered: {},
35
+ legacy: []
36
+ });
37
+ /** What is on disk: this machine's v2 journal, this machine's v1 journal (the upgrade reads it
38
+ * once, queue.ts), or nothing usable. A journal stamped by ANOTHER machine is treated as absent:
39
+ * a repo that ships its own design/.local/ would otherwise hand a clone a pre-baselined journal
40
+ * whose `seen` omits the attacker's own comments, and the daemon would run them. Rebaselining is
41
+ * the safe read - every event already on disk becomes seen, so nothing pre-existing executes. */
42
+ function readRaw(root) {
43
+ const file = journalFile(root);
44
+ if (!existsSync(file)) return {};
45
+ try {
46
+ const j = JSON.parse(readFileSync(file, "utf8"));
47
+ if (!j || j.device !== deviceId() || !Array.isArray(j.seen) || !Array.isArray(j.batches)) return {};
48
+ if (j.version === 1) return { v1: {
49
+ version: 1,
50
+ device: j.device,
51
+ baselined: !!j.baselined,
52
+ seen: j.seen,
53
+ batches: j.batches
54
+ } };
55
+ if (j.version !== 2 || !Array.isArray(j.cards)) return {};
56
+ return { v2: {
57
+ version: 2,
58
+ device: j.device,
59
+ baselined: !!j.baselined,
60
+ seen: j.seen,
61
+ cards: j.cards,
62
+ batches: j.batches,
63
+ covered: j.covered && typeof j.covered === "object" ? j.covered : {},
64
+ legacy: Array.isArray(j.legacy) ? j.legacy : [],
65
+ ...typeof j.upgraded === "number" ? { upgraded: j.upgraded } : {},
66
+ ...j.run && typeof j.run.since === "number" ? { run: { since: j.run.since } } : {},
67
+ ...j.session && typeof j.session.id === "string" && /^ses-\d{10,16}-[a-z0-9]{4,12}$/.test(j.session.id) && typeof j.session.since === "number" ? { session: {
68
+ id: j.session.id,
69
+ since: j.session.since
70
+ } } : {}
71
+ } };
72
+ } catch {
73
+ return {};
74
+ }
75
+ }
76
+ /** Persist atomically and durably. */
77
+ function write(root, j) {
78
+ const dir = localDir(root);
79
+ mkdirSync(dir, { recursive: true });
80
+ const file = journalFile(root);
81
+ const tmp = `${file}.${randomBytes(6).toString("hex")}.tmp`;
82
+ const fd = openSync(tmp, "w", 384);
83
+ try {
84
+ writeSync(fd, JSON.stringify(j));
85
+ fsyncSync(fd);
86
+ } finally {
87
+ closeSync(fd);
88
+ }
89
+ renameSync(tmp, file);
90
+ try {
91
+ const dfd = openSync(dir, "r");
92
+ try {
93
+ fsyncSync(dfd);
94
+ } finally {
95
+ closeSync(dfd);
96
+ }
97
+ } catch {}
98
+ }
99
+ const holderOf = (file) => {
100
+ try {
101
+ return parseInt(readFileSync(file, "utf8").trim(), 10) || 0;
102
+ } catch {
103
+ return 0;
104
+ }
105
+ };
106
+ const exists = (err) => err.code === "EEXIST";
107
+ /** Acquire the repo's jam lock. Returns true if this process now holds it. A lock held by a live
108
+ * process is respected (that daemon runs the loop). A lock left by a dead process is reclaimed the
109
+ * way dev.lock is (spec 27 Part 7): under `jam.lock.reclaim`, created exclusively, re-reading the
110
+ * lock and replacing it only if it still names the same dead pid - so two daemons starting at once
111
+ * can never both reclaim it. Another start mid-reclaim (or a crashed one) means no loop here. */
112
+ function acquireLock(root) {
113
+ const dir = localDir(root);
114
+ mkdirSync(dir, { recursive: true });
115
+ const file = lockFile(root);
116
+ const take = () => {
117
+ try {
118
+ createExclusive(file, String(process.pid));
119
+ return true;
120
+ } catch (err) {
121
+ if (exists(err)) return false;
122
+ throw err;
123
+ }
124
+ };
125
+ try {
126
+ if (take()) return true;
127
+ const holder = holderOf(file);
128
+ if (!holder) return false;
129
+ if (holder === process.pid) return true;
130
+ if (pidRuns(holder)) return false;
131
+ const reclaim = `${file}.reclaim`;
132
+ try {
133
+ createExclusive(reclaim, String(process.pid));
134
+ } catch (err) {
135
+ if (exists(err)) return false;
136
+ throw err;
137
+ }
138
+ try {
139
+ if (holderOf(file) !== holder) return false;
140
+ unlinkSync(file);
141
+ return take();
142
+ } finally {
143
+ try {
144
+ unlinkSync(reclaim);
145
+ } catch {}
146
+ }
147
+ } catch {
148
+ return false;
149
+ }
150
+ }
151
+ /** Release the lock if we own it (best-effort). */
152
+ function releaseLock(root) {
153
+ const file = lockFile(root);
154
+ try {
155
+ if (parseInt(readFileSync(file, "utf8").trim(), 10) === process.pid) unlinkSync(file);
156
+ } catch {}
157
+ }
158
+ //#endregion
159
+ //#region src/server/jam/queue.ts
160
+ /**
161
+ * The jam queue (spec 27, Parts 1-2): cards and batches, and every rule that moves them.
162
+ *
163
+ * Only ledgered owner events become asks, and only a create or reply that tags `@marver` starts
164
+ * work - a plain reply never does, in any thread. A tag joins its thread's queued card (a thread
165
+ * has at most one), follows a working one, or makes a new card. Cards change in one place, under
166
+ * one async lock, and every operation under it starts by ingesting the comment logs, so a claim or
167
+ * an action always sees a reply, a tag or a resolve whose write finished before it.
168
+ *
169
+ * The functions here are synchronous over a journal held in memory; `createQueue` adds the lock
170
+ * and the writes. The daemon (daemon.ts) runs what `form` claims and hands the results back.
171
+ */
172
+ const MENTION = /@marver\b/i;
173
+ const KEEP_MS = 6048e5;
174
+ const TERMINAL = [
175
+ "done",
176
+ "dropped",
177
+ "kept"
178
+ ];
179
+ const pending = (c) => !TERMINAL.includes(c.state);
180
+ const ctxFor = (root) => ({
181
+ root,
182
+ dir: join(root, "design", "comments"),
183
+ owned: owned(root)
184
+ });
185
+ const isOwned = (ctx, board, id) => ctx.owned.has(`${board}\t${id}`);
186
+ const seenKey = (board, id) => `${board}|${id}`;
187
+ const set = (c, state, now, note) => {
188
+ c.state = state;
189
+ c.rev += 1;
190
+ c.at = now;
191
+ if (note !== void 0) c.note = note;
192
+ };
193
+ const onThread = (j, board, thread) => j.cards.filter((c) => c.board === board && c.thread === thread);
194
+ /** The frame each thread sits on (a reply names only its thread). */
195
+ const framesOf = (events) => {
196
+ const m = /* @__PURE__ */ new Map();
197
+ for (const ev of events) if (ev.type === "create" && ev.commentId && ev.frame) m.set(ev.commentId, ev.frame);
198
+ return m;
199
+ };
200
+ /** Read every log for events not seen yet and apply them. Synchronous - the watcher, the claim,
201
+ * the card actions and the page's comment route all call it. Returns whether a card changed.
202
+ * An owner-looking event that is not ledgered is left unseen and looked at again next time: the
203
+ * page ledgers it just after it appends, and a synced event never is (a set lookup each time). */
204
+ function ingest(j, ctx, now = Date.now()) {
205
+ const seen = new Set(j.seen);
206
+ const before = seen.size;
207
+ let changed = false;
208
+ for (const board of listBoards(ctx.dir)) {
209
+ const events = readLog(ctx.dir, board);
210
+ let frames;
211
+ for (const ev of events) {
212
+ const k = seenKey(board, ev.id);
213
+ if (seen.has(k)) continue;
214
+ if (ev.agent) {
215
+ seen.add(k);
216
+ continue;
217
+ }
218
+ if (ev.type === "resolve") {
219
+ seen.add(k);
220
+ changed = resolved(j, board, ev.commentId ?? "", now) || changed;
221
+ continue;
222
+ }
223
+ if (ev.type !== "create" && ev.type !== "reply" && ev.type !== "edit") {
224
+ seen.add(k);
225
+ continue;
226
+ }
227
+ if (!isOwned(ctx, board, ev.id)) continue;
228
+ seen.add(k);
229
+ if (ev.capture || ev.id.startsWith("mw-") || ev.id.startsWith("cap-")) continue;
230
+ if (ev.type === "edit") {
231
+ changed = edited(j, board, events, ev, now) || changed;
232
+ continue;
233
+ }
234
+ const thread = threadId(ev);
235
+ if (MENTION.test(ev.body ?? "")) {
236
+ frames ??= framesOf(events);
237
+ tagged(j, board, ev, ev.frame ?? frames.get(thread), now);
238
+ changed = true;
239
+ } else if (ev.type === "reply") changed = answered(j, board, thread, now) || changed;
240
+ }
241
+ }
242
+ if (seen.size !== before) j.seen = [...seen];
243
+ return changed;
244
+ }
245
+ /** An owner comment or reply that tags @marver. */
246
+ function tagged(j, board, ev, frame, now) {
247
+ const thread = threadId(ev);
248
+ const on = onThread(j, board, thread);
249
+ const queued = on.find((c) => c.state === "queued");
250
+ const working = on.find((c) => c.state === "working");
251
+ const asking = on.find((c) => c.state === "asks");
252
+ const failed = on.filter((c) => c.state === "failed").sort((a, b) => b.at - a.at)[0];
253
+ if (asking) set(asking, "done", now, "answered");
254
+ if (failed && !asking) set(failed, "done", now, "retried by a new tag");
255
+ if (queued) {
256
+ queued.events.push(ev.id);
257
+ queued.when = {
258
+ ...queued.when,
259
+ [ev.id]: ev.ts
260
+ };
261
+ if (asking || failed) queued.follows ??= (asking ?? failed).id;
262
+ queued.rev += 1;
263
+ queued.at = now;
264
+ return;
265
+ }
266
+ let follows;
267
+ if (working) follows = working.id;
268
+ else if (asking) follows = asking.id;
269
+ else if (failed) follows = failed.id;
270
+ const capCard = on.find((c) => c.capture);
271
+ const capture = capCard?.capture;
272
+ const frames = capCard ? [...capCard.frames] : frame ? [frame] : [];
273
+ j.cards.push({
274
+ id: `c-${ev.id}`,
275
+ kind: "comment",
276
+ board,
277
+ frames,
278
+ thread,
279
+ ...capture ? { capture } : {},
280
+ events: [ev.id],
281
+ when: { [ev.id]: ev.ts },
282
+ state: "queued",
283
+ ...follows ? { follows } : {},
284
+ made: ev.ts,
285
+ order: ev.ts,
286
+ rev: 1,
287
+ at: now
288
+ });
289
+ }
290
+ /** A plain owner reply: conversation, never a command. It answers a card that asks. */
291
+ function answered(j, board, thread, now) {
292
+ let changed = false;
293
+ for (const c of onThread(j, board, thread)) if (c.state === "asks") {
294
+ set(c, "done", now, "answered");
295
+ changed = true;
296
+ }
297
+ return changed;
298
+ }
299
+ /** An edit never starts work and never cancels it; it only changes the text of a card not yet
300
+ * claimed (the brief reads the latest ledgered edit at claim) - bump it so a page redraws. */
301
+ function edited(j, board, events, ev, now) {
302
+ const target = events.find((e) => (e.type === "create" || e.type === "reply") && e.commentId === ev.commentId);
303
+ if (!target) return false;
304
+ let changed = false;
305
+ for (const c of j.cards) if (c.board === board && c.state === "queued" && c.events.includes(target.id)) {
306
+ c.rev += 1;
307
+ c.at = now;
308
+ changed = true;
309
+ }
310
+ return changed;
311
+ }
312
+ /** A thread resolved by hand: a queued card is dropped, a working one runs to its end (and goes to
313
+ * done, not review), and one that asks, waits for review or failed is done. */
314
+ function resolved(j, board, thread, now) {
315
+ let changed = false;
316
+ for (const c of onThread(j, board, thread)) {
317
+ if (c.state === "queued") set(c, "dropped", now, "resolved");
318
+ else if (c.state === "working") {
319
+ c.resolved = true;
320
+ c.rev += 1;
321
+ c.at = now;
322
+ } else if (c.state === "asks" || c.state === "review" || c.state === "failed") set(c, "done", now, "resolved");
323
+ else continue;
324
+ changed = true;
325
+ }
326
+ return changed;
327
+ }
328
+ /** Two cards meet on one thread (a Retry, a `shared` requeue): one survives with both cards' asks,
329
+ * its rev bumped, and the other turns done ("merged"). A capture card always survives - it keeps
330
+ * its tile, its scope and its review; with no capture card involved, `queued` (the card already
331
+ * waiting) survives. */
332
+ function merge(j, queued, other, now) {
333
+ const [keep, gone] = other.kind === "capture" && queued.kind !== "capture" ? [other, queued] : [queued, other];
334
+ const when = {
335
+ ...gone.when,
336
+ ...keep.when
337
+ };
338
+ const at = (id) => when[id] ?? (gone.events.includes(id) ? gone.made : keep.made);
339
+ keep.events = [.../* @__PURE__ */ new Set([...gone.events, ...keep.events])].sort((a, b) => at(a) - at(b) || (a < b ? -1 : 1));
340
+ keep.when = Object.fromEntries(keep.events.map((id) => [id, at(id)]));
341
+ if (gone.exclusive || keep.exclusive) keep.exclusive = [.../* @__PURE__ */ new Set([...keep.exclusive ?? [], ...gone.exclusive ?? []])];
342
+ keep.shared = Math.max(keep.shared ?? 0, gone.shared ?? 0) || void 0;
343
+ for (const f of gone.frames) if (!keep.frames.includes(f)) keep.frames.push(f);
344
+ if (gone.batch || gone.ran?.length) keep.follows ??= gone.id;
345
+ keep.state = "queued";
346
+ keep.rev += 1;
347
+ keep.at = now;
348
+ keep.order = Math.min(keep.order, gone.order);
349
+ set(gone, "done", now, "merged");
350
+ gone.note = `merged into ${keep.id}`;
351
+ return keep;
352
+ }
353
+ /** Put a card back in the queue (Retry, a `shared` answer): its last run joins `ran`. If the thread
354
+ * already holds a queued card, the two merge. */
355
+ function requeue(j, c, now, first = false) {
356
+ if (c.batch) c.ran = [...c.ran ?? [], c.batch];
357
+ c.batch = void 0;
358
+ c.note = void 0;
359
+ c.state = "queued";
360
+ c.rev += 1;
361
+ c.at = now;
362
+ if (first) c.order = Math.min(now, ...j.cards.filter((x) => x.state === "queued" && x !== c).map((x) => x.order - 1));
363
+ const other = c.thread ? onThread(j, c.board, c.thread).find((x) => x !== c && x.state === "queued") : void 0;
364
+ return other ? merge(j, other, c, now) : c;
365
+ }
366
+ const ACTIONS = [
367
+ "drop",
368
+ "retry",
369
+ "keep",
370
+ "first",
371
+ "confirm",
372
+ "edit",
373
+ "good",
374
+ "more",
375
+ "later",
376
+ "rename",
377
+ "note"
378
+ ];
379
+ /** One card action from the page (POST /jam/card). It applies only if the card is still at `rev`
380
+ * (two tabs cannot both decide); anything not allowed answers with the current card. */
381
+ function act(j, id, rev, action, now = Date.now(), body) {
382
+ const c = j.cards.find((x) => x.id === id);
383
+ if (!c) return {
384
+ ok: false,
385
+ error: "no such card"
386
+ };
387
+ if (c.rev !== rev) return {
388
+ ok: false,
389
+ card: c,
390
+ error: "the card changed - look again"
391
+ };
392
+ const capture = c.kind === "capture";
393
+ if (action === "drop" && (c.state === "queued" || (capture || c.kind === "wrapup") && (c.state === "draft" || c.state === "failed"))) {
394
+ set(c, "dropped", now, "dropped");
395
+ return {
396
+ ok: true,
397
+ card: c
398
+ };
399
+ }
400
+ if (action === "retry" && c.state === "failed") return {
401
+ ok: true,
402
+ card: requeue(j, c, now)
403
+ };
404
+ if (action === "keep" && capture && c.state === "queued") {
405
+ set(c, "kept", now, "kept, not sent");
406
+ return {
407
+ ok: true,
408
+ card: c
409
+ };
410
+ }
411
+ if (action === "first" && capture && c.state === "queued") {
412
+ c.order = Math.min(c.order, ...j.cards.filter((x) => x.state === "queued" && x !== c).map((x) => x.order - 1));
413
+ c.rev += 1;
414
+ c.at = now;
415
+ return {
416
+ ok: true,
417
+ card: c
418
+ };
419
+ }
420
+ if (action === "edit" && capture && c.state === "draft" && typeof body === "string") {
421
+ c.payload = {
422
+ ...c.payload,
423
+ edited: body.slice(0, 2e4)
424
+ };
425
+ c.rev += 1;
426
+ c.at = now;
427
+ return {
428
+ ok: true,
429
+ card: c
430
+ };
431
+ }
432
+ if (action === "note" && capture && c.state === "draft" && typeof body === "string" && body.trim()) {
433
+ let n = { text: body };
434
+ try {
435
+ const o = JSON.parse(body);
436
+ if (o && typeof o.text === "string") n = {
437
+ ...typeof o.id === "string" && /^n-[a-z0-9]{6,24}$/.test(o.id) ? { id: o.id } : {},
438
+ text: o.text,
439
+ ...Number.isFinite(o.order) ? { order: Number(o.order) } : {}
440
+ };
441
+ } catch {}
442
+ const text = n.text.trim().slice(0, 4e3);
443
+ const was = n.id ? c.payload?.added?.find((a) => a.id === n.id) : void 0;
444
+ if (was) {
445
+ if (text && was.text !== text) {
446
+ c.payload = {
447
+ ...c.payload,
448
+ added: c.payload.added.map((a) => a === was ? {
449
+ ...a,
450
+ text
451
+ } : a)
452
+ };
453
+ c.rev += 1;
454
+ c.at = now;
455
+ }
456
+ return {
457
+ ok: true,
458
+ card: c
459
+ };
460
+ }
461
+ if (text && (c.payload?.added?.length ?? 0) < 50) {
462
+ const added = [...c.payload?.added ?? [], {
463
+ at: n.order ?? now,
464
+ text,
465
+ ...n.id ? { id: n.id } : {}
466
+ }].sort((a, b) => a.at - b.at);
467
+ c.payload = {
468
+ ...c.payload,
469
+ added
470
+ };
471
+ c.rev += 1;
472
+ c.at = now;
473
+ return {
474
+ ok: true,
475
+ card: c
476
+ };
477
+ }
478
+ }
479
+ if (action === "rename" && (capture || c.kind === "wrapup") && c.state !== "dropped" && typeof body === "string") {
480
+ const name = body.replace(/\s+/g, " ").trim().slice(0, 80);
481
+ if (name) c.name = name;
482
+ else delete c.name;
483
+ c.rev += 1;
484
+ c.at = now;
485
+ return {
486
+ ok: true,
487
+ card: c
488
+ };
489
+ }
490
+ if (action === "later" && c.state === "review") return {
491
+ ok: true,
492
+ card: c
493
+ };
494
+ return {
495
+ ok: false,
496
+ card: c,
497
+ error: `${action} is not allowed on this card`
498
+ };
499
+ }
500
+ /** The text of one message as the owner wrote it: for an owner event, its body or its latest
501
+ * LEDGERED edit (an edit that arrived by sync is never the owner's text); for anyone else, the
502
+ * latest edit as replay shows it. */
503
+ function textOf(ctx, board, events, ev, owner) {
504
+ let body = ev.body ?? "";
505
+ let rev = ev.id;
506
+ for (const e of events) {
507
+ if (e.type !== "edit" || e.commentId !== ev.commentId || e.body === void 0) continue;
508
+ if (owner ? !e.agent && isOwned(ctx, board, e.id) : !!e.agent === !!ev.agent) {
509
+ body = e.body;
510
+ rev = e.id;
511
+ }
512
+ }
513
+ return {
514
+ body,
515
+ rev
516
+ };
517
+ }
518
+ /** Is a copied ask still the owner's? Its event is in the log and ledgered, and its frozen revision is
519
+ * the event itself or a ledgered edit OF THAT MESSAGE (never another message's edit). */
520
+ function stillOwned(ctx, board, events, m) {
521
+ const ev = events.find((e) => e.id === m.id);
522
+ if (!ev || ev.agent || !isOwned(ctx, board, m.id)) return false;
523
+ if (!m.rev || m.rev === m.id) return true;
524
+ const edit = events.find((e) => e.id === m.rev);
525
+ return !!edit && edit.type === "edit" && !edit.agent && edit.commentId === ev.commentId && isOwned(ctx, board, m.rev);
526
+ }
527
+ const resultText = (j, batchId, card, fallback = "") => {
528
+ const b = j.batches.find((x) => x.batchId === batchId);
529
+ const m = b?.members.find((x) => x.card === card);
530
+ const r = m && b?.results?.[m.id];
531
+ if (!r) return fallback;
532
+ if ("body" in r) return r.body;
533
+ if ("missing" in r) return "the agent did not answer this one";
534
+ return `needed shared files: ${r.shared.join(", ")}`;
535
+ };
536
+ /** Freeze a card's brief as text, from the logs as they stand at claim. Covers every owner event it
537
+ * copies (the `covered` record that takes a plain reply off `marver marks`). */
538
+ function freezeBrief(j, ctx, c, events) {
539
+ const msgs = c.thread ? events.filter((e) => e.type === "create" && e.commentId === c.thread || e.type === "reply" && e.parentId === c.thread) : [];
540
+ const dropped = new Set(j.cards.filter((x) => x.board === c.board && x.state === "dropped").flatMap((x) => x.events));
541
+ const asks = new Set(c.events);
542
+ const toMsg = (e) => {
543
+ const owner = !e.agent && isOwned(ctx, c.board, e.id);
544
+ const { body, rev } = textOf(ctx, c.board, events, e, owner);
545
+ const note = !owner && !e.agent ? "someone else - context only" : owner && !asks.has(e.id) && dropped.has(e.id) ? "dropped - not an ask" : void 0;
546
+ if (owner) j.covered[e.id] = rev;
547
+ return {
548
+ id: e.id,
549
+ ...e.author?.name ? { author: sanitize(e.author.name, 80) } : {},
550
+ ...e.agent ? { agent: true } : {},
551
+ ...owner ? {
552
+ owner: true,
553
+ rev
554
+ } : {},
555
+ body: sanitize(body, Infinity),
556
+ ts: e.ts,
557
+ ...note ? { note } : {}
558
+ };
559
+ };
560
+ const brief = {
561
+ asks: c.events.map((id) => msgs.find((e) => e.id === id) ?? events.find((e) => e.id === id)).filter((e) => !!e).map(toMsg),
562
+ history: msgs.filter((e) => !asks.has(e.id)).map(toMsg)
563
+ };
564
+ if (c.capture) {
565
+ const capCard = j.cards.find((x) => x.id === c.capture);
566
+ const cap = readCapture(ctx.root, c.capture);
567
+ if (cap && capCard?.payload) {
568
+ const note = capCard !== c && capCard.state === "kept" ? "kept - not an ask" : capCard !== c && capCard.state === "dropped" ? "dropped - not an ask" : void 0;
569
+ brief.capture = {
570
+ record: cap.record,
571
+ recordHash: cap.hash,
572
+ ...capCard.payload.edited !== void 0 ? { edited: capCard.payload.edited } : {},
573
+ ...capCard.payload.added?.length ? { added: capCard.payload.added } : {},
574
+ ...capCard.payload.reviewed ? { reviewed: capCard.payload.reviewed } : {},
575
+ ...note ? { note } : {}
576
+ };
577
+ }
578
+ }
579
+ if (c.kind === "wrapup") {
580
+ const w = readWrapup(ctx.root, wrapupOf(c));
581
+ if (w) brief.wrapup = {
582
+ content: w.wrapup,
583
+ hash: w.hash
584
+ };
585
+ }
586
+ const followed = c.follows ? j.cards.find((x) => x.id === c.follows) : void 0;
587
+ const lastRun = (x) => x.batch ?? x.ran?.[x.ran.length - 1];
588
+ const keep = (asks) => (asks ?? []).filter((a) => stillOwned(ctx, c.board, events, a));
589
+ if (followed && !c.ran?.length) {
590
+ const b = lastRun(followed);
591
+ brief.follows = {
592
+ asks: keep(followed.brief?.asks),
593
+ result: resultText(j, b, followed.id, j.batches.find((x) => x.batchId === b)?.note ?? followed.note ?? "")
594
+ };
595
+ } else if (c.ran?.length) {
596
+ const last = c.ran[c.ran.length - 1];
597
+ const m = j.batches.find((b) => b.batchId === last)?.members.find((x) => x.card === c.id);
598
+ brief.follows = {
599
+ asks: keep(m?.brief?.asks),
600
+ result: resultText(j, last, c.id, j.batches.find((b) => b.batchId === last)?.note ?? "the run failed")
601
+ };
602
+ }
603
+ return brief;
604
+ }
605
+ /** Are a card's asks still the owner's? Each must be in its board's log and ledgered; the ones that
606
+ * are not are dropped, and a card with none left is dropped ("no longer authorized"). */
607
+ /** Is a capture still what was ledgered at confirm - its sealed record's hash and the confirmed edit?
608
+ * Checked for EVERY card that carries the capture (a tag on its thread included), at claim and at
609
+ * resume: a record or an edit changed afterwards never reaches the agent. */
610
+ function captureIntact(j, ctx, capId) {
611
+ const capCard = j.cards.find((x) => x.id === capId && x.kind === "capture");
612
+ const cap = readCapture(ctx.root, capId);
613
+ return !!capCard?.payload && !!cap && cap.hash === capCard.payload.recordHash && isOwned(ctx, capCard.board, payloadKey(capCard));
614
+ }
615
+ /** A wrap-up's content is the one sealed: its file hashes to what the card holds, and that is ledgered. */
616
+ function wrapupIntact(ctx, c) {
617
+ const w = readWrapup(ctx.root, wrapupOf(c));
618
+ return !!w && !!c.payload && w.hash === c.payload.recordHash && isOwned(ctx, c.board, `wrapup:${w.wrapup.id}:${w.hash}`);
619
+ }
620
+ /** The wrap-up content a card writes from (a More work card writes from the same, its note added). */
621
+ const wrapupOf = (c) => c.id;
622
+ function validate(ctx, c, events, now, j) {
623
+ if (c.capture && j && !captureIntact(j, ctx, c.capture)) {
624
+ set(c, "failed", now, "the capture changed after it was confirmed - capture it again");
625
+ return false;
626
+ }
627
+ if (c.kind === "capture") {
628
+ const ok = c.events.every((id) => isOwned(ctx, c.board, id) && events.some((e) => e.id === id));
629
+ if (!ok) set(c, "failed", now, "an ask on this capture is no longer the owner's");
630
+ return ok;
631
+ }
632
+ if (c.kind === "wrapup") {
633
+ if (!wrapupIntact(ctx, c)) {
634
+ set(c, "failed", now, "the session record changed after it was written - write it again");
635
+ return false;
636
+ }
637
+ const w = readWrapup(ctx.root, c.id);
638
+ const unsafe = w && recordPathProblem(ctx.root, w.wrapup.file);
639
+ if (unsafe) {
640
+ set(c, "failed", now, `the record's file is not safe to write: ${unsafe}`);
641
+ return false;
642
+ }
643
+ return true;
644
+ }
645
+ if (c.kind !== "comment") return true;
646
+ const ok = c.events.filter((id) => isOwned(ctx, c.board, id) && events.some((e) => e.id === id));
647
+ if (ok.length !== c.events.length) {
648
+ c.events = ok;
649
+ c.rev += 1;
650
+ c.at = now;
651
+ }
652
+ if (!ok.length) {
653
+ set(c, "dropped", now, "no longer authorized");
654
+ return false;
655
+ }
656
+ return true;
657
+ }
658
+ /** Claim what can run now: the queued cards of one board on one single frame join one batch, in
659
+ * run order, up to 8; a card naming several frames runs alone and waits for all of them; a card
660
+ * with no frame, or one that must edit a shared file, runs exclusive - alone, once nothing runs and
661
+ * no hold is left, and while it waits nothing new starts. Briefs are frozen, cards turn working,
662
+ * and each packet is written to its file. Returns the new batches (already in the journal). */
663
+ function form(j, ctx, o, now = Date.now()) {
664
+ const logs = /* @__PURE__ */ new Map();
665
+ const log = (board) => {
666
+ let l = logs.get(board);
667
+ if (!l) logs.set(board, l = readLog(ctx.dir, board));
668
+ return l;
669
+ };
670
+ for (const c of j.cards) if (c.state === "queued" && (c.exclusive || !c.frames.length)) validate(ctx, c, log(c.board), now, j);
671
+ const queued = j.cards.filter((c) => c.state === "queued").sort((a, b) => a.order - b.order || a.made - b.made);
672
+ const exclusive = queued.filter((c) => c.exclusive || !c.frames.length);
673
+ const forming = [];
674
+ if (exclusive.length) {
675
+ if (o.exclusiveRunning || o.running.size || o.anyHold() || o.free < 1) return {
676
+ batches: [],
677
+ exclusiveWaiting: !o.exclusiveRunning
678
+ };
679
+ const c = exclusive[0];
680
+ forming.push({
681
+ board: c.board,
682
+ frames: [...c.frames],
683
+ cards: [c],
684
+ exclusive: true,
685
+ single: false
686
+ });
687
+ } else if (!o.exclusiveRunning) {
688
+ const reserved = new Set(o.running);
689
+ for (const c of queued) if (c.frames.length === 1) {
690
+ const f = c.frames[0];
691
+ const join = forming.find((b) => b.single && b.board === c.board && b.frames[0] === f && b.cards.length < 8);
692
+ if (join) {
693
+ if (validate(ctx, c, log(c.board), now, j)) join.cards.push(c);
694
+ continue;
695
+ }
696
+ if (reserved.has(f) || o.held(f) || forming.length >= o.free) continue;
697
+ if (!validate(ctx, c, log(c.board), now, j)) continue;
698
+ forming.push({
699
+ board: c.board,
700
+ frames: [f],
701
+ cards: [c],
702
+ single: true
703
+ });
704
+ reserved.add(f);
705
+ } else {
706
+ if (c.frames.some((f) => reserved.has(f) || o.held(f)) || forming.length >= o.free) continue;
707
+ if (!validate(ctx, c, log(c.board), now, j)) continue;
708
+ forming.push({
709
+ board: c.board,
710
+ frames: [...c.frames],
711
+ cards: [c],
712
+ single: false
713
+ });
714
+ for (const f of c.frames) reserved.add(f);
715
+ }
716
+ }
717
+ const batches = [];
718
+ for (const f of forming) {
719
+ const batchId = randomUUID();
720
+ const members = [];
721
+ const packetMembers = [];
722
+ const threads = replay(log(f.board));
723
+ for (const c of f.cards) {
724
+ const brief = freezeBrief(j, ctx, c, log(c.board));
725
+ const id = `m${members.length + 1}`;
726
+ c.brief = brief;
727
+ c.batch = batchId;
728
+ set(c, "working", now);
729
+ members.push({
730
+ id,
731
+ card: c.id,
732
+ board: c.board,
733
+ brief
734
+ });
735
+ const t = c.thread ? threads.find((x) => x.id === c.thread) : void 0;
736
+ packetMembers.push({
737
+ id,
738
+ card: c.id,
739
+ kind: c.kind,
740
+ board: c.board,
741
+ ...c.thread ? { thread: c.thread } : {},
742
+ frames: c.frames,
743
+ ...t?.anchor !== void 0 ? { anchor: t.anchor } : {},
744
+ brief
745
+ });
746
+ }
747
+ const files = f.exclusive ? [...new Set(f.cards.flatMap((c) => c.exclusive ?? []))] : void 0;
748
+ const b = {
749
+ batchId,
750
+ members,
751
+ frames: f.frames,
752
+ ...f.exclusive ? { exclusive: true } : {},
753
+ state: "claimed",
754
+ leaseUntil: 0,
755
+ attempts: 0,
756
+ at: now
757
+ };
758
+ j.batches.push(b);
759
+ writePacket(ctx.root, buildPacket(batchId, packetMembers, f.frames, f.exclusive ? files : void 0), new Set(j.batches.filter((x) => x.state === "claimed").map((x) => x.batchId)));
760
+ batches.push(b);
761
+ }
762
+ return {
763
+ batches,
764
+ exclusiveWaiting: exclusive.length > 0 && batches.length === 0
765
+ };
766
+ }
767
+ const PACKETS_KEPT = 50;
768
+ /** Write a batch's packet once (a rerun reads the same file) and forget old ones - never one an
769
+ * unfinished batch (`keep`) still needs to resume. */
770
+ function writePacket(root, packet, keep = /* @__PURE__ */ new Set()) {
771
+ const file = join(root, packetPath(packet.batchId));
772
+ const dir = join(root, "design", ".local", "jam", "packets");
773
+ mkdirSync(dir, { recursive: true });
774
+ writeFileSync(file, JSON.stringify(packet, null, 1), {
775
+ mode: 384,
776
+ flag: "wx"
777
+ });
778
+ try {
779
+ const files = readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => ({
780
+ f,
781
+ t: statSync(join(dir, f)).mtimeMs
782
+ })).sort((a, b) => b.t - a.t);
783
+ for (const { f } of files.slice(PACKETS_KEPT)) if (!keep.has(f.replace(/\.json$/, ""))) rmSync(join(dir, f), { force: true });
784
+ } catch {}
785
+ }
786
+ /** Did the owner answer in this thread after `since` (a ledgered create or reply)? A question the
787
+ * agent posted early may be answered while the job still runs. */
788
+ function answeredSince(ctx, board, thread, since) {
789
+ return readLog(ctx.dir, board).some((e) => e.type === "reply" && e.parentId === thread && !e.agent && e.ts > since && isOwned(ctx, board, e.id));
790
+ }
791
+ /** Move a batch's cards by their results, once every reply is posted. `posted` names each member's
792
+ * reply (comment id), whether its question was already answered, and when it was asked. */
793
+ function settle(j, b, posted, now = Date.now()) {
794
+ const out = [];
795
+ for (const m of b.members) settleOne(j, b, m, posted[m.id] ?? {}, now, out);
796
+ b.state = "done";
797
+ b.at = now;
798
+ return out;
799
+ }
800
+ /** Move one member's card by its result (see `settle`). */
801
+ function settleOne(j, b, m, p, now, out) {
802
+ const c = j.cards.find((x) => x.id === m.card);
803
+ const r = b.results?.[m.id];
804
+ if (!c || c.state !== "working" || c.batch !== b.batchId || !r) return;
805
+ if ("body" in r) {
806
+ if (p.reply) c.reply = p.reply;
807
+ if (c.resolved) set(c, "done", now, "replied");
808
+ else if (r.asks && p.answered) set(c, "done", now, "answered");
809
+ else if (c.kind === "wrapup") set(c, "review", now, "ready to review");
810
+ else if (r.asks) {
811
+ c.asked = p.asked ?? now;
812
+ set(c, "asks", now, "asks you");
813
+ out.push({
814
+ card: c,
815
+ notice: "asks"
816
+ });
817
+ return;
818
+ } else set(c, c.kind === "comment" ? "done" : "review", now, c.kind === "comment" ? "replied" : "ready to review");
819
+ out.push({ card: c });
820
+ } else if (c.resolved) {
821
+ set(c, "done", now, "resolved");
822
+ out.push({ card: c });
823
+ } else if ("missing" in r) {
824
+ set(c, "failed", now, "the agent did not answer this one");
825
+ out.push({
826
+ card: c,
827
+ notice: "failed"
828
+ });
829
+ } else if (c.exclusive || (c.shared ?? 0) >= 1) {
830
+ set(c, "failed", now, "needed more shared files than it was given");
831
+ out.push({
832
+ card: c,
833
+ notice: "failed"
834
+ });
835
+ } else {
836
+ c.exclusive = r.shared;
837
+ c.shared = 1;
838
+ out.push({ card: requeue(j, c, now) });
839
+ }
840
+ }
841
+ /** Two failed attempts: every working card of the batch turns failed. */
842
+ function fail(j, b, note, now = Date.now()) {
843
+ const out = [];
844
+ for (const m of b.members) {
845
+ const c = j.cards.find((x) => x.id === m.card);
846
+ if (!c || c.state !== "working" || c.batch !== b.batchId) continue;
847
+ if (c.resolved) set(c, "done", now, "resolved");
848
+ else {
849
+ set(c, "failed", now, note);
850
+ out.push({
851
+ card: c,
852
+ notice: "failed"
853
+ });
854
+ }
855
+ }
856
+ b.state = "failed";
857
+ b.at = now;
858
+ b.note = note;
859
+ return out;
860
+ }
861
+ /** Results saved, posting failed for good: the cards show failed - Retry posts the saved replies - and
862
+ * the batch stays claimed with its results, so a boot reconciles it too. Never a rerun. */
863
+ function undelivered(j, b, note, now = Date.now()) {
864
+ const out = [];
865
+ for (const m of b.members) {
866
+ const c = j.cards.find((x) => x.id === m.card);
867
+ if (!c || c.state !== "working" || c.batch !== b.batchId) continue;
868
+ const r = b.results?.[m.id];
869
+ if (r && !("body" in r)) settleOne(j, b, m, {}, now, out);
870
+ else {
871
+ set(c, "failed", now, note);
872
+ out.push({
873
+ card: c,
874
+ notice: "failed"
875
+ });
876
+ }
877
+ }
878
+ b.undelivered = true;
879
+ b.at = now;
880
+ return out;
881
+ }
882
+ /** A batch whose replies are posted again (Retry, or a boot): its failed cards go back to working. */
883
+ function redelivering(j, b, now = Date.now()) {
884
+ for (const m of b.members) {
885
+ const c = j.cards.find((x) => x.id === m.card);
886
+ const r = b.results?.[m.id];
887
+ if (c && c.state === "failed" && c.batch === b.batchId && r && "body" in r) set(c, "working", now, "");
888
+ }
889
+ b.undelivered = false;
890
+ }
891
+ /** Forget finished cards and batches after a week, unless a live card follows one. */
892
+ function prune(j, now = Date.now()) {
893
+ const needed = new Set(j.cards.filter(pending).flatMap((c) => [
894
+ c.follows,
895
+ ...c.ran ?? [],
896
+ c.batch,
897
+ c.capture
898
+ ]).filter(Boolean));
899
+ j.cards = j.cards.filter((c) => pending(c) || c.kind === "capture" || c.at > now - KEEP_MS || needed.has(c.id));
900
+ const cardIds = new Set(j.cards.map((c) => c.id));
901
+ j.batches = j.batches.filter((b) => b.state === "claimed" || needed.has(b.batchId) || b.members.some((m) => cardIds.has(m.card)));
902
+ }
903
+ /** First-enable safety: every event already on disk is seen without being run. */
904
+ function baseline(j, ctx) {
905
+ if (j.baselined) return;
906
+ const seen = new Set(j.seen);
907
+ for (const board of listBoards(ctx.dir)) for (const ev of readLog(ctx.dir, board)) seen.add(seenKey(board, ev.id));
908
+ j.seen = [...seen];
909
+ j.baselined = true;
910
+ }
911
+ /** A 0.25 journal becomes a v2 one (spec 27, Part 7). Every v1 batch stays a batch; one whose final
912
+ * reply (`jam-<batch>`) is already logged is reconciled, not rerun. Any other in flight is fenced
913
+ * (the caller kills `fence`) and, if its trigger tagged @marver, becomes a failed card with Retry;
914
+ * a plain reply never survives as work - it stays on `marver marks`' answered list. A plain reply
915
+ * v1 took in without running is `legacy`: listed apart, never as definitely unread. */
916
+ function upgrade(v1, ctx, now = Date.now()) {
917
+ const j = fresh();
918
+ j.baselined = v1.baselined;
919
+ j.upgraded = now;
920
+ const fence = [];
921
+ const v1seen = new Set(v1.seen);
922
+ const unfinished = /* @__PURE__ */ new Set();
923
+ for (const board of listBoards(ctx.dir)) {
924
+ const events = readLog(ctx.dir, board);
925
+ const frames = framesOf(events);
926
+ for (const ev of events) if (v1seen.has(ev.id)) j.seen.push(seenKey(board, ev.id));
927
+ for (const b of v1.batches.filter((x) => x.board === board)) {
928
+ const id = b.memberEventIds[0];
929
+ const ev = events.find((e) => e.id === id);
930
+ if (!ev) continue;
931
+ if (b.state === "pending" || b.state === "claimed") unfinished.add(id);
932
+ const thread = threadId(ev);
933
+ const frame = ev.frame ?? frames.get(thread);
934
+ const final = events.find((e) => e.id === `jam-${b.batchId}`) ?? (b.state === "done" ? [...events].reverse().find((e) => new RegExp(`^jam-e\\d+-${b.batchId}$`).test(e.id)) : void 0);
935
+ const tag = MENTION.test(ev.body ?? "") && isOwned(ctx, board, id);
936
+ const card = (state, note) => ({
937
+ id: `c-${id}`,
938
+ kind: "comment",
939
+ board,
940
+ frames: frame ? [frame] : [],
941
+ thread,
942
+ events: [id],
943
+ state,
944
+ note,
945
+ batch: b.batchId,
946
+ made: ev.ts,
947
+ order: ev.ts,
948
+ rev: 1,
949
+ at: now
950
+ });
951
+ if (final) {
952
+ const answered = events.some((e) => e.type === "reply" && e.parentId === thread && !e.agent && e.ts > final.ts && isOwned(ctx, board, e.id));
953
+ const shown = replay(events).find((x) => x.id === thread)?.replies.find((r) => r.id === final.commentId);
954
+ const asks = !answered && (shown?.asks ?? final.asks ?? /\?\s*$/.test(final.body ?? ""));
955
+ j.cards.push({
956
+ ...card(asks ? "asks" : "done", asks ? "asks you" : answered ? "answered" : "replied"),
957
+ reply: final.commentId,
958
+ ...asks ? { asked: final.ts } : {}
959
+ });
960
+ j.batches.push({
961
+ batchId: b.batchId,
962
+ members: [{
963
+ id: "m1",
964
+ card: `c-${id}`,
965
+ board
966
+ }],
967
+ frames: frame ? [frame] : [],
968
+ state: "done",
969
+ leaseUntil: 0,
970
+ attempts: b.attempts,
971
+ results: { m1: {
972
+ body: final.body ?? "",
973
+ asks,
974
+ reanchors: []
975
+ } },
976
+ posted: true,
977
+ at: now
978
+ });
979
+ continue;
980
+ }
981
+ if (b.state === "done") continue;
982
+ if (b.state === "claimed" && b.pgid) fence.push(b.pgid);
983
+ if (!tag) continue;
984
+ j.cards.push(card("failed", b.state === "failed" ? "the agent could not finish - Retry" : "interrupted by the upgrade - Retry"));
985
+ j.batches.push({
986
+ batchId: b.batchId,
987
+ members: [{
988
+ id: "m1",
989
+ card: `c-${id}`,
990
+ board
991
+ }],
992
+ frames: frame ? [frame] : [],
993
+ state: "failed",
994
+ leaseUntil: 0,
995
+ attempts: b.attempts,
996
+ ...b.pgid ? { pgid: b.pgid } : {},
997
+ at: now
998
+ });
999
+ }
1000
+ for (const ev of events) if (ev.type === "reply" && !ev.agent && v1seen.has(ev.id) && !unfinished.has(ev.id) && !MENTION.test(ev.body ?? "") && isOwned(ctx, board, ev.id)) j.legacy.push(ev.id);
1001
+ }
1002
+ return {
1003
+ j,
1004
+ fence
1005
+ };
1006
+ }
1007
+ /** Every ledgered plain owner reply, in an open thread where Marver spoke, that nothing has taken in
1008
+ * yet: no frozen brief copied its current text, and the coding agent has not answered after it (a
1009
+ * reply from the CLI, not a jam job's). A later ledgered edit makes it unread again. Cards on the
1010
+ * thread, done or not, do not hide it. `earlier`: replies a v1 journal took in - maybe handled. */
1011
+ function answers(root) {
1012
+ const ctx = ctxFor(root);
1013
+ const raw = readRaw(root);
1014
+ const j = raw.v2 ?? (raw.v1 ? upgrade(raw.v1, ctx).j : fresh());
1015
+ const legacy = new Set(j.legacy);
1016
+ const out = {
1017
+ answered: [],
1018
+ earlier: []
1019
+ };
1020
+ for (const board of listBoards(ctx.dir)) {
1021
+ const events = readLog(ctx.dir, board);
1022
+ for (const t of replay(events)) {
1023
+ if (t.resolved || !(t.agent || t.replies.some((r) => r.agent))) continue;
1024
+ const msgs = events.filter((e) => e.type === "create" && e.commentId === t.id || e.type === "reply" && e.parentId === t.id);
1025
+ for (const ev of msgs) {
1026
+ if (ev.type !== "reply" || ev.agent || !isOwned(ctx, board, ev.id)) continue;
1027
+ const { body, rev } = textOf(ctx, board, events, ev, true);
1028
+ if (MENTION.test(body)) continue;
1029
+ const at = rev === ev.id ? ev.ts : events.find((e) => e.id === rev)?.ts ?? ev.ts;
1030
+ if (j.covered[ev.id] === rev) continue;
1031
+ if (msgs.some((e) => e.agent && !e.id.startsWith("jam-") && e.ts > at)) continue;
1032
+ const a = {
1033
+ board,
1034
+ thread: t.id,
1035
+ ...t.frame ? { frame: t.frame } : {},
1036
+ event: ev.id,
1037
+ body: body.replace(/\s+/g, " ").trim(),
1038
+ ts: ev.ts
1039
+ };
1040
+ (legacy.has(ev.id) ? out.earlier : out.answered).push(a);
1041
+ }
1042
+ }
1043
+ }
1044
+ return out;
1045
+ }
1046
+ /** The ledger key that binds a confirmed capture's payload: its record hash and your edit. */
1047
+ const payloadKey = (c) => `cap:${c.id}:${hashOf({
1048
+ recordHash: c.payload?.recordHash ?? "",
1049
+ edited: c.payload?.edited ?? null,
1050
+ ...c.payload?.added?.length ? { added: c.payload.added } : {}
1051
+ })}`;
1052
+ /** A sealed capture becomes a draft card (once - a second post finds it). A capture made during a
1053
+ * review follows the reviewed card and keeps the run it saw (`reviewing`). */
1054
+ function addCapture(j, record, hash, now = Date.now()) {
1055
+ const have = j.cards.find((c) => c.id === record.id);
1056
+ if (have) return have;
1057
+ const rs = record.context.resumes;
1058
+ const src = rs ? j.cards.find((c) => c.id === rs.id && c.kind === "capture" && c.board === record.context.board) : void 0;
1059
+ const prev = src?.state === "draft" ? src : void 0;
1060
+ const made = prev?.made ?? (madeOf(record.id) || now);
1061
+ const r0 = record.context.reviewing ?? src?.reviewing;
1062
+ const r = r0 && j.cards.find((x) => x.id === r0.card)?.kind === "capture" ? r0 : void 0;
1063
+ const more = src?.payload?.edited !== void 0 && rs ? wordsSince(record, rs.at) : "";
1064
+ const edited = src?.payload?.edited !== void 0 ? [src.payload.edited.trim(), more].filter(Boolean).join("\n") : void 0;
1065
+ const c = {
1066
+ id: record.id,
1067
+ kind: "capture",
1068
+ board: record.context.board,
1069
+ frames: [.../* @__PURE__ */ new Set([...src?.frames ?? [], ...captureFrames(record)])],
1070
+ capture: record.id,
1071
+ events: [],
1072
+ state: "draft",
1073
+ made,
1074
+ order: prev?.order ?? made,
1075
+ rev: 1,
1076
+ at: now,
1077
+ payload: {
1078
+ recordHash: hash,
1079
+ ...edited !== void 0 ? { edited } : {},
1080
+ ...src?.payload?.added?.length ? { added: src.payload.added } : {}
1081
+ },
1082
+ ...r ? {
1083
+ reviewing: r,
1084
+ follows: r.card
1085
+ } : {},
1086
+ ...src?.name ? { name: src.name } : {},
1087
+ ...record.context.session && j.session?.id === record.context.session ? { session: record.context.session } : {}
1088
+ };
1089
+ if (prev) set(prev, "dropped", now, `resumed as ${record.id}`);
1090
+ j.cards.push(c);
1091
+ touchRun(j, now);
1092
+ return c;
1093
+ }
1094
+ /** The comment a capture writes at confirm: its words as confirmed (cut at 600 characters - the full
1095
+ * text stays in the record), its facts, the capture it stands for; pinned on the first point, else
1096
+ * its first frame, else the board. Deterministic ids, so a resumed confirm writes it once. */
1097
+ function captureComment(c, record, at, author, now = Date.now()) {
1098
+ const words = [captureWords(record, c.payload?.edited), ...(c.payload?.added ?? []).map((a) => a.text)].filter(Boolean).join("\n");
1099
+ return {
1100
+ id: `cap-${c.id}-e`,
1101
+ ts: now,
1102
+ type: "create",
1103
+ commentId: `cap-${c.id}`,
1104
+ board: c.board,
1105
+ author,
1106
+ body: (words.length > 600 ? words.slice(0, 599) + "…" : words) || "(a capture with no words)",
1107
+ capture: c.id,
1108
+ facts: factsOf(record),
1109
+ ...at.frame ? { frame: at.frame } : {},
1110
+ ...at.anchor !== void 0 ? { anchor: at.anchor } : {}
1111
+ };
1112
+ }
1113
+ /** Begin a recoverable step on a card: the exact comment it will write is in the journal first. */
1114
+ function beginStep(j, c, op, event, now = Date.now(), end) {
1115
+ c.pending = {
1116
+ op,
1117
+ event,
1118
+ ...end ? { end } : {}
1119
+ };
1120
+ if (op === "confirm") {
1121
+ c.state = "confirming";
1122
+ const r = c.reviewing && j.batches.find((b) => b.batchId === c.reviewing.batch);
1123
+ const m = r && r.members.find((x) => x.card === c.reviewing.card);
1124
+ if (m && !c.payload?.reviewed) c.payload = {
1125
+ ...c.payload,
1126
+ reviewed: {
1127
+ asks: m.brief?.asks ?? [],
1128
+ result: resultText(j, r.batchId, m.card, r.note ?? ""),
1129
+ ...m.brief?.capture ? { capture: {
1130
+ record: m.brief.capture.record,
1131
+ recordHash: m.brief.capture.recordHash,
1132
+ ...m.brief.capture.edited !== void 0 ? { edited: m.brief.capture.edited } : {},
1133
+ ...m.brief.capture.added?.length ? { added: m.brief.capture.added } : {}
1134
+ } } : {}
1135
+ }
1136
+ };
1137
+ }
1138
+ c.rev += 1;
1139
+ c.at = now;
1140
+ }
1141
+ /** Did a comment already in the log under the step's id say exactly what the step would write? */
1142
+ /** An event as stable text: every field, keys sorted at every depth - except `ts`, when it was written. */
1143
+ const canon = (e) => {
1144
+ const sort = (v) => Array.isArray(v) ? v.map(sort) : v && typeof v === "object" ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sort(v[k])])) : v;
1145
+ const { ts: _ts, ...rest } = e;
1146
+ return JSON.stringify(sort(rest));
1147
+ };
1148
+ /** Did a comment already in the log under the step's id say EXACTLY what the step would write - every
1149
+ * field that matters, not just its words? Anything else fails closed. (`ts` is when it was written.) */
1150
+ const sameComment = (a, b) => canon(a) === canon(b);
1151
+ /** A step whose comment is written and ledgered ends: a confirm leaves the card queued (or kept), on
1152
+ * its thread - and a capture made during a review sends that review back as More work, if the card
1153
+ * is still in review from the run the capture saw, at the rev it saw (no @marver reply: this card is
1154
+ * the one job). More work puts the SAME card back, first, with your words as its follow-up ask. */
1155
+ function endStep(j, c, now = Date.now()) {
1156
+ const p = c.pending;
1157
+ if (!p) return [];
1158
+ c.pending = void 0;
1159
+ if (p.op === "confirm") {
1160
+ c.thread = p.event.commentId;
1161
+ set(c, p.end ?? "queued", now, p.end === "kept" ? "kept, not sent" : void 0);
1162
+ if (p.end !== "kept" && c.reviewing) {
1163
+ const r = j.cards.find((x) => x.id === c.reviewing.card);
1164
+ if (r && r.kind === "capture" && r.state === "review" && r.batch === c.reviewing.batch && r.rev === c.reviewing.rev) {
1165
+ r.verdict = "more work";
1166
+ set(r, "done", now, "more work");
1167
+ }
1168
+ }
1169
+ touchRun(j, now);
1170
+ return [{ card: c }];
1171
+ }
1172
+ c.events = [...c.events, p.event.id];
1173
+ c.when = {
1174
+ ...c.when,
1175
+ [p.event.id]: p.event.ts
1176
+ };
1177
+ c.verdict = "more work";
1178
+ return [{ card: requeue(j, c, now, true) }];
1179
+ }
1180
+ /** A step that found another comment in its place fails closed: nothing is ledgered, the card goes
1181
+ * back to where it was, and says so. */
1182
+ function conflictStep(j, c, now = Date.now()) {
1183
+ const p = c.pending;
1184
+ c.pending = void 0;
1185
+ set(c, p?.op === "confirm" ? "draft" : "review", now, "a conflicting comment took this one's place - write it again");
1186
+ }
1187
+ /** Looks good: done, and its thread resolved - unless a newer card on the thread is open, or an owner
1188
+ * reply or edit arrived after its frozen brief (that answer stays open, on the answered list). */
1189
+ function looksGood(j, ctx, c, events, now = Date.now()) {
1190
+ const newer = j.cards.some((x) => x !== c && x.board === c.board && x.thread === c.thread && pending(x) && x.made > c.made);
1191
+ const frozen = new Map([...c.brief?.asks ?? [], ...c.brief?.history ?? []].map((m) => [m.id, m.rev ?? m.id]));
1192
+ const after = events.some((e) => {
1193
+ if (e.agent || !isOwned(ctx, c.board, e.id)) return false;
1194
+ if (!(e.type === "create" && e.commentId === c.thread || e.type === "reply" && e.parentId === c.thread)) return false;
1195
+ if (!frozen.has(e.id)) return e.type === "reply";
1196
+ return textOf(ctx, c.board, events, e, true).rev !== frozen.get(e.id);
1197
+ });
1198
+ c.verdict = "looks good";
1199
+ set(c, "done", now, "looks good");
1200
+ touchRun(j, now);
1201
+ return { resolve: !!c.thread && !newer && !after };
1202
+ }
1203
+ /** Start a session (once: one runs at a time). */
1204
+ function startSession(j, id, now = Date.now()) {
1205
+ if (!j.session) {
1206
+ j.session = {
1207
+ id,
1208
+ since: now
1209
+ };
1210
+ touchRun(j, now);
1211
+ }
1212
+ return j.session;
1213
+ }
1214
+ /** End the session running (if it is `id`): the run then lasts while its captures are pending. */
1215
+ function endSession(j, id, now = Date.now()) {
1216
+ if (j.session?.id !== id) return false;
1217
+ j.session = void 0;
1218
+ touchRun(j, now);
1219
+ return true;
1220
+ }
1221
+ /** A sealed wrap-up becomes a queued card - the run's last tile; it writes the session's record. */
1222
+ function addWrapup(j, w, hash, board, now = Date.now()) {
1223
+ const have = j.cards.find((c) => c.id === w.id);
1224
+ if (have) return have;
1225
+ const c = {
1226
+ id: w.id,
1227
+ kind: "wrapup",
1228
+ board,
1229
+ frames: [],
1230
+ events: [],
1231
+ state: "queued",
1232
+ made: now,
1233
+ order: now,
1234
+ rev: 1,
1235
+ at: now,
1236
+ payload: { recordHash: hash },
1237
+ session: w.session,
1238
+ name: "Session record"
1239
+ };
1240
+ j.cards.push(c);
1241
+ touchRun(j, now);
1242
+ return c;
1243
+ }
1244
+ /** More work on a record: a new record job from its own sealed wrap-up (the first's content, your note
1245
+ * added, the same file) follows the record it improves, which is done. */
1246
+ function moreWrapup(j, prev, w, hash, now = Date.now()) {
1247
+ const c = {
1248
+ id: w.id,
1249
+ kind: "wrapup",
1250
+ board: prev.board,
1251
+ frames: [],
1252
+ events: [],
1253
+ state: "queued",
1254
+ made: now,
1255
+ order: now,
1256
+ rev: 1,
1257
+ at: now,
1258
+ follows: prev.id,
1259
+ payload: { recordHash: hash },
1260
+ session: prev.session,
1261
+ name: "Session record"
1262
+ };
1263
+ prev.verdict = "more work";
1264
+ set(prev, "done", now, "more work");
1265
+ j.cards.push(c);
1266
+ touchRun(j, now);
1267
+ return c;
1268
+ }
1269
+ /** The lane's run: the captures made since the lane last appeared. It lasts while any of them is
1270
+ * pending (or a session runs - M4) and ends when every one is done, kept or dropped. */
1271
+ function touchRun(j, now = Date.now()) {
1272
+ const live = j.cards.filter((c) => c.kind === "capture" || c.kind === "wrapup").filter((c) => pending(c));
1273
+ if (j.session) {
1274
+ j.run = { since: Math.min(j.run?.since ?? Infinity, j.session.since, ...live.map((c) => c.made)) };
1275
+ return;
1276
+ }
1277
+ if (!j.run && live.length) j.run = { since: Math.min(...live.map((c) => c.made)) };
1278
+ else if (j.run && !live.length) j.run = void 0;
1279
+ else if (j.run && live.length) j.run = { since: Math.min(j.run.since, ...live.map((c) => c.made)) };
1280
+ }
1281
+ /** Load the journal - upgrading a v1 one, or starting fresh and baselining - and wrap it in the
1282
+ * lock. `onUpgrade` gets the orphans to fence and runs once, before anything is scheduled. */
1283
+ function createQueue(root, onUpgrade, alive = () => true) {
1284
+ const raw = readRaw(root);
1285
+ let ctx = ctxFor(root);
1286
+ let j;
1287
+ if (raw.v2) j = raw.v2;
1288
+ else if (raw.v1) {
1289
+ const u = upgrade(raw.v1, ctx);
1290
+ j = u.j;
1291
+ onUpgrade?.(u.fence);
1292
+ } else j = fresh();
1293
+ baseline(j, ctx);
1294
+ write(root, j);
1295
+ let tail = Promise.resolve();
1296
+ return {
1297
+ get j() {
1298
+ return j;
1299
+ },
1300
+ ctx: () => ctx,
1301
+ lock(fn) {
1302
+ const run = tail.then(async () => {
1303
+ if (!alive()) throw new Error("jam stopped");
1304
+ ctx = ctxFor(root);
1305
+ if (ingest(j, ctx)) write(root, j);
1306
+ const out = await fn(j, ctx);
1307
+ touchRun(j);
1308
+ return out;
1309
+ });
1310
+ tail = run.catch(() => {});
1311
+ return run;
1312
+ },
1313
+ persist() {
1314
+ if (alive()) write(root, j);
1315
+ }
1316
+ };
1317
+ }
1318
+ //#endregion
1319
+ export { ACTIONS, act, addCapture, addWrapup, answeredSince, answers, beginStep, captureComment, captureIntact, conflictStep, createQueue, ctxFor, endSession, endStep, fail, form, looksGood, moreWrapup, releaseLock as n, payloadKey, pending, prune, redelivering, sameComment, settle, startSession, stillOwned, acquireLock as t, textOf, undelivered, wrapupIntact, wrapupOf };