flowviant 0.41.0 → 0.44.1

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.
@@ -0,0 +1,875 @@
1
+ /**
2
+ * Work sessions — the Workbench tabs, daemon side.
3
+ *
4
+ * A tab is a held Claude session with BUILD permissions in a PERSISTENT
5
+ * worktree on its own `session/<id>` branch. Nothing here is detached and
6
+ * nothing is ever reset — uncommitted state between turns IS the session, and
7
+ * blowing it away would be closing the human's editor mid-thought. (Plan
8
+ * worktrees are the deliberate opposite: reset at base every turn.)
9
+ *
10
+ * Everything the loop guarantees lives here: per-session turn/ship chains,
11
+ * per-session work credentials, the settle-every-turn contract, the ship
12
+ * executor, and worktree retirement. Split out of fleet.mjs mechanically —
13
+ * the daemon's reconcile loop constructs one manager per run and feeds it
14
+ * roster jobs; the only state it borrows from the loop is read through the
15
+ * two getters (the MCP URL and the lease TTL can change with any poll).
16
+ */
17
+
18
+ import { existsSync, rmSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
19
+ import { execFileSync } from 'node:child_process';
20
+ import { join } from 'node:path';
21
+ import { FLEET_URL, FLEET_TOKEN, USER_AGENT, REFRESH_BEFORE_SECONDS } from './config.mjs';
22
+ import { git, baseBranchName, isSafePathSegment } from './git.mjs';
23
+ import { c, note, ok, warn } from './ui.mjs';
24
+ import { mcpFor, runTurn } from './claude.mjs';
25
+ import { SYSTEM_WORK, WORK_TURN_KICKOFF } from './prompts.mjs';
26
+ import { materializeInto, scrub as envScrub } from './env.mjs';
27
+ import { detectRuntimes, pickRuntimeFor, RUNTIMES } from './runtimes.mjs';
28
+
29
+ export function createWorkManager({ repoRoot, baseDir, baseRef, getMcpUrl, getLeaseTtl }) {
30
+ const WORK_TOKEN_URL = FLEET_URL.replace(/\/agents\/?$/, '/work-token');
31
+ const WORK_DONE_URL = FLEET_URL.replace(/\/agents\/?$/, '/work-turn-done');
32
+ const SHIP_DONE_URL = FLEET_URL.replace(/\/agents\/?$/, '/ship-done');
33
+ const workAnswering = new Set(); // turn ids currently queued/running here
34
+ const workAttempts = new Map(); // turn id -> completed runTurn attempts
35
+ const MAX_WORK_TRIES = 3;
36
+ const shipping = new Set(); // sessionIds with a ship queued/running here
37
+ /**
38
+ * Per-SESSION serialization, parallel ACROSS sessions: turns within one tab
39
+ * must land in order (they share a directory and a context), but two tabs
40
+ * are two terminals — the human opened both on purpose. Ship jobs ride the
41
+ * SAME chain, never a separate one: a ship must not run git in a worktree
42
+ * while that session's turn has a live CLI in it.
43
+ */
44
+ const workChains = new Map(); // sessionId -> settled-safe tail promise
45
+ const chainFor = (sessionId, fn) => {
46
+ const prev = workChains.get(sessionId) ?? Promise.resolve();
47
+ // `.then(fn, fn)`, like withWikiLock: one rejected link must never wedge
48
+ // every later turn of the tab.
49
+ const run = prev.then(fn, fn);
50
+ const stored = run.then(
51
+ () => {},
52
+ () => {}
53
+ );
54
+ workChains.set(sessionId, stored);
55
+ // Release the entry when the chain drains, so the map cannot grow for the
56
+ // process lifetime and `workChains.has()` means "busy right now".
57
+ stored.then(() => {
58
+ if (workChains.get(sessionId) === stored) workChains.delete(sessionId);
59
+ });
60
+ return run;
61
+ };
62
+
63
+ /**
64
+ * EVERY turn settles — the work loop's prime contract. A pending turn nobody
65
+ * answers holds one of the tab's slots until the server expires it (24h);
66
+ * silence is the worst outcome. So a report that cannot be DELIVERED right
67
+ * now is queued in memory and retried at the top of every poll, and a turn
68
+ * whose finished answer sits in that queue is never re-run — a session turn
69
+ * has side effects (edits, commits, cards), and a dropped 200 must not apply
70
+ * them twice.
71
+ */
72
+ const pendingWorkReports = new Map(); // turnId -> work-turn-done body
73
+ const pendingShipReports = new Map(); // sessionId -> ship-done body
74
+ /** POST a settle body. 'ok' | 'terminal' (the server will never accept this
75
+ * body — 403 not this fleet's session, 404 unknown turn, 409 ship already
76
+ * settled — so retrying is spam, not delivery) | 'retry'. */
77
+ const postSettle = async (url, body, terminalStatuses) => {
78
+ try {
79
+ const res = await fetch(url, {
80
+ method: 'POST',
81
+ headers: {
82
+ Authorization: `Bearer ${FLEET_TOKEN}`,
83
+ 'User-Agent': USER_AGENT,
84
+ 'Content-Type': 'application/json',
85
+ },
86
+ signal: AbortSignal.timeout(30_000),
87
+ body: JSON.stringify(body),
88
+ });
89
+ if (res.ok) return 'ok';
90
+ if (terminalStatuses.includes(res.status)) return 'terminal';
91
+ return 'retry';
92
+ } catch {
93
+ return 'retry';
94
+ }
95
+ };
96
+ const settleWorkTurn = async (turnId, payload) => {
97
+ const body = { turnId, ...payload };
98
+ const r = await postSettle(WORK_DONE_URL, body, [403, 404]);
99
+ if (r === 'retry') pendingWorkReports.set(turnId, body);
100
+ else {
101
+ pendingWorkReports.delete(turnId);
102
+ workAttempts.delete(turnId);
103
+ }
104
+ return r;
105
+ };
106
+ const settleShip = async (sessionId, payload) => {
107
+ const body = { sessionId, ...payload };
108
+ const r = await postSettle(SHIP_DONE_URL, body, [403, 409]);
109
+ if (r === 'retry') pendingShipReports.set(sessionId, body);
110
+ else pendingShipReports.delete(sessionId);
111
+ return r;
112
+ };
113
+ let flushingReports = false;
114
+ const flushWorkReports = async () => {
115
+ if (flushingReports) return;
116
+ if (pendingWorkReports.size === 0 && pendingShipReports.size === 0) return;
117
+ flushingReports = true;
118
+ try {
119
+ for (const [id, body] of [...pendingWorkReports]) {
120
+ const r = await postSettle(WORK_DONE_URL, body, [403, 404]);
121
+ if (r !== 'retry') {
122
+ pendingWorkReports.delete(id);
123
+ workAttempts.delete(id);
124
+ }
125
+ }
126
+ for (const [id, body] of [...pendingShipReports]) {
127
+ const r = await postSettle(SHIP_DONE_URL, body, [403, 409]);
128
+ if (r !== 'retry') pendingShipReports.delete(id);
129
+ }
130
+ } finally {
131
+ flushingReports = false;
132
+ }
133
+ };
134
+
135
+ /**
136
+ * The work credential, ONE PER SESSION. The server binds each minted token
137
+ * to the sessionId in the mint body and the MCP layer refuses it for any
138
+ * other session, so a process-wide token would fail every tab but the one
139
+ * that minted it. Cached per session, re-minted near expiry (the endpoint
140
+ * rotates on every mint; per-session chaining means no turn is in flight
141
+ * for the session when its next turn mints). 404 means the server no longer
142
+ * holds that session for this fleet — a fact for the turn to settle with,
143
+ * not a retry.
144
+ */
145
+ const workTokens = new Map(); // sessionId -> { token, mintedAt }
146
+ const mintWorkToken = async (sessionId, force = false) => {
147
+ const cached = workTokens.get(sessionId);
148
+ const freshEnoughS = getLeaseTtl() - REFRESH_BEFORE_SECONDS;
149
+ if (cached && !force && (Date.now() - cached.mintedAt) / 1000 < freshEnoughS)
150
+ return { token: cached.token };
151
+ try {
152
+ const res = await fetch(WORK_TOKEN_URL, {
153
+ method: 'POST',
154
+ headers: {
155
+ Authorization: `Bearer ${FLEET_TOKEN}`,
156
+ 'User-Agent': USER_AGENT,
157
+ 'Content-Type': 'application/json',
158
+ },
159
+ signal: AbortSignal.timeout(30_000),
160
+ body: JSON.stringify({ sessionId }),
161
+ });
162
+ if (res.status === 404) return { gone: true };
163
+ if (!res.ok) return null;
164
+ const token = (await res.json().catch(() => null))?.data?.token ?? null;
165
+ if (!token) return null;
166
+ workTokens.set(sessionId, { token, mintedAt: Date.now() });
167
+ return { token };
168
+ } catch {
169
+ return null;
170
+ }
171
+ };
172
+
173
+ /**
174
+ * This tab's worktree — its held context, expressed as a place, ON A BRANCH.
175
+ *
176
+ * Fresh: branch `session/<id>` off the current base. Existing: touched not at
177
+ * all — no fetch-reset-clean like a plan directory, because the dirty state
178
+ * is the point. If the directory was retired but the branch survives, the
179
+ * worktree re-attaches to the branch and the committed work is still there.
180
+ */
181
+ const sessionWtFor = (sessionId) => {
182
+ if (!isSafePathSegment(sessionId)) return null;
183
+ const wt = join(baseDir, 'sessions', sessionId);
184
+ const fresh = !existsSync(wt);
185
+ if (fresh) {
186
+ const branch = `session/${sessionId}`;
187
+ try {
188
+ git(['worktree', 'add', '-b', branch, wt, baseRef], repoRoot);
189
+ } catch {
190
+ git(['worktree', 'prune'], repoRoot);
191
+ try {
192
+ // The branch may already exist (a retired directory's work) — attach.
193
+ git(['worktree', 'add', wt, branch], repoRoot);
194
+ } catch {
195
+ try {
196
+ git(['worktree', 'add', '-b', branch, wt, baseRef], repoRoot);
197
+ } catch {
198
+ return null;
199
+ }
200
+ }
201
+ }
202
+ // Synced env into the fresh worktree, exactly like a task checkout gets
203
+ // (worktreeFor): a tab builds and runs dev servers here, and without the
204
+ // bundle every session build was missing its .env while dispatched runs
205
+ // got theirs. Only on creation — a live directory's env belongs to the
206
+ // session, same as a resumed task tree. Ship's dirty-check is safe by
207
+ // construction: materializeInto writes ONLY gitignored paths (it refuses
208
+ // otherwise), and ignored files never appear in `git status --porcelain`.
209
+ // Best-effort, like everywhere else — the session still builds; paths
210
+ // that need secrets may 500.
211
+ try {
212
+ materializeInto(wt);
213
+ } catch {
214
+ /* best-effort */
215
+ }
216
+ }
217
+ return { wt, fresh };
218
+ };
219
+
220
+ /**
221
+ * A file in the worktree's PRIVATE git dir (…/.git/worktrees/<name>). It
222
+ * travels with the worktree, dies with `git worktree remove`, and is
223
+ * invisible to `git status` — so nothing stored here can ever make the
224
+ * session look dirty (a dirty tree refuses ships). A marker file in the
225
+ * working tree itself would show up as an untracked path and block every
226
+ * ship of an otherwise-clean session.
227
+ */
228
+ const sessionMetaPath = (wt, name) => {
229
+ try {
230
+ return join(git(['rev-parse', '--absolute-git-dir'], wt), name);
231
+ } catch {
232
+ return null;
233
+ }
234
+ };
235
+
236
+ /**
237
+ * WHICH CLI drives this session — picked ONCE, on the first turn, and pinned
238
+ * in the worktree's meta dir. The held context belongs to the CLI that made
239
+ * it: `--continue` under a different binary is a different brain wearing the
240
+ * session's half-finished state (the dispatch path pins heldRuntime for the
241
+ * same reason). If the pinned CLI has left the machine, the turn settles
242
+ * honestly instead of substituting. A retired-and-reattached directory has
243
+ * no marker and no held context either, so re-picking there is correct.
244
+ * Returns { id } | { id: null } (nothing installed) | { missing: label }.
245
+ */
246
+ const sessionRuntime = (wt) => {
247
+ const marker = sessionMetaPath(wt, 'flowviant-runtime');
248
+ let pinned = null;
249
+ if (marker && existsSync(marker)) {
250
+ try {
251
+ pinned = readFileSync(marker, 'utf8').trim() || null;
252
+ } catch {
253
+ /* unreadable marker — re-pin below */
254
+ }
255
+ }
256
+ if (pinned && RUNTIMES[pinned]) {
257
+ const installed = detectRuntimes().find((r) => r.id === pinned)?.installed;
258
+ return installed ? { id: pinned } : { missing: RUNTIMES[pinned].label || pinned };
259
+ }
260
+ const id = pickRuntimeFor('build');
261
+ if (!id) return { id: null };
262
+ if (marker) {
263
+ try {
264
+ writeFileSync(marker, id);
265
+ } catch {
266
+ /* best-effort — an unpinnable session just re-picks next turn */
267
+ }
268
+ }
269
+ return { id };
270
+ };
271
+
272
+ /**
273
+ * The spawn lock: the pid of the CLI currently live in this worktree. A
274
+ * restarted daemon must not put a second Claude into a directory the orphan
275
+ * of its previous life is still editing — two CLIs appending to one held
276
+ * conversation is exactly the incoherence workChains prevents in-process,
277
+ * and the lock extends that guarantee across a restart. A dead pid is a
278
+ * stale lock (removed here); a live one means "come back next poll".
279
+ */
280
+ const turnLockedByLivePid = (lockPath) => {
281
+ if (!lockPath || !existsSync(lockPath)) return false;
282
+ let pid = 0;
283
+ try {
284
+ pid = Number(readFileSync(lockPath, 'utf8').trim());
285
+ } catch {
286
+ /* unreadable — treat as stale */
287
+ }
288
+ if (Number.isInteger(pid) && pid > 0) {
289
+ try {
290
+ process.kill(pid, 0);
291
+ return true; // signal 0 delivered — the process is alive
292
+ } catch (e) {
293
+ if (e.code === 'EPERM') return true; // alive, just not ours to signal
294
+ }
295
+ }
296
+ try {
297
+ rmSync(lockPath, { force: true }); // dead holder — clear the stale lock
298
+ } catch {
299
+ /* best-effort */
300
+ }
301
+ return false;
302
+ };
303
+
304
+ /**
305
+ * Live session-turn CLI children. The daemon's teardown SIGTERMs them: an
306
+ * orphaned CLI keeps editing the session worktree and burning quota after
307
+ * the daemon is gone. Each child's pid-lock is deliberately LEFT IN PLACE —
308
+ * a CLI can trap SIGTERM to finish an in-flight request and outlive this
309
+ * loop by seconds, and removing the lock in the same tick handed the
310
+ * restarted daemon a green light to spawn a second CLI into the same held
311
+ * context. turnLockedByLivePid already covers both outcomes: it waits while
312
+ * the pid lives and clears the lock once it is dead.
313
+ */
314
+ const workChildren = new Map(); // child process -> lockPath | null
315
+ const shutdownWork = () => {
316
+ for (const [ch] of workChildren) {
317
+ try {
318
+ ch.kill('SIGTERM');
319
+ } catch {
320
+ /* best-effort */
321
+ }
322
+ }
323
+ workChildren.clear();
324
+ };
325
+
326
+ /**
327
+ * Retire the worktrees of sessions the server says are CLOSED.
328
+ *
329
+ * `activeWorkSessions` on the roster is the list of this fleet's LIVE
330
+ * sessions; a directory whose id is absent belongs to a tab its owner
331
+ * closed, and the directory — never the branch: committed work survives on
332
+ * `session/<id>`, and ship re-attaches to it — is returned to disk. NEVER
333
+ * by count: the old cap-12 retirement destroyed live sessions on shared
334
+ * machines. When the roster omits the field entirely (older server),
335
+ * absence of signal is not a close — retire nothing.
336
+ */
337
+ const retireWorkSessions = (activeIds) => {
338
+ if (!Array.isArray(activeIds)) return;
339
+ const dir = join(baseDir, 'sessions');
340
+ if (!existsSync(dir)) return;
341
+ let ids;
342
+ try {
343
+ ids = readdirSync(dir);
344
+ } catch {
345
+ return;
346
+ }
347
+ const live = new Set(activeIds);
348
+ let removed = 0;
349
+ for (const id of ids) {
350
+ if (live.has(id)) continue;
351
+ if (workChains.has(id) || shipping.has(id)) continue; // still draining here
352
+ const wt = join(dir, id);
353
+ try {
354
+ // Uncommitted work is the human's — a resource sweep does not outrank
355
+ // it, closed tab or not. (The non-force remove would refuse anyway;
356
+ // the explicit check keeps the intent legible.)
357
+ if (git(['status', '--porcelain'], wt) !== '') continue;
358
+ git(['worktree', 'remove', wt], repoRoot); // non-force; the branch survives
359
+ workTokens.delete(id);
360
+ removed++;
361
+ } catch {
362
+ /* not cleanly removable — leave it */
363
+ }
364
+ }
365
+ if (removed) {
366
+ try {
367
+ git(['worktree', 'prune'], repoRoot);
368
+ } catch {
369
+ /* best effort */
370
+ }
371
+ }
372
+ };
373
+
374
+ const processWorkTurns = (jobs) => {
375
+ for (const job of jobs ?? []) {
376
+ if (!job || typeof job.id !== 'string' || !job.body || !job.sessionId) continue;
377
+ if (workAnswering.has(job.id)) continue;
378
+ // The turn already RAN and its answer sits in the delivery queue — never
379
+ // run it again while the report is merely undelivered.
380
+ if (pendingWorkReports.has(job.id)) continue;
381
+ workAnswering.add(job.id);
382
+ chainFor(job.sessionId, async () => {
383
+ try {
384
+ const tries = workAttempts.get(job.id) ?? 0;
385
+ if (tries >= MAX_WORK_TRIES) {
386
+ // Out of local tries: SETTLE, don't skip — a silently skipped turn
387
+ // strands the tab for the server's whole 24h expiry window.
388
+ await settleWorkTurn(job.id, {
389
+ ok: false,
390
+ answer: `the turn failed ${tries} times on this machine — check the daemon log, then send the message again`,
391
+ });
392
+ return;
393
+ }
394
+ note(
395
+ `${c.cyan('tab')} ${c.dim(`— ${job.askedByName || 'the owner'} in "${job.sessionName || 'a session'}"`)}`
396
+ );
397
+ const dir = sessionWtFor(job.sessionId);
398
+ if (!dir) {
399
+ await settleWorkTurn(job.id, {
400
+ ok: false,
401
+ answer:
402
+ 'the session worktree could not be opened on the machine — check the daemon log',
403
+ });
404
+ return;
405
+ }
406
+ // A live CLI is ALREADY in this worktree — this daemon's previous
407
+ // life, most likely; the lock outlives a restart. Leave the job
408
+ // pending and look again next poll; spawning a second CLI would put
409
+ // two Claudes in one held context. Costs no attempt: nothing ran.
410
+ const lockPath = sessionMetaPath(dir.wt, 'flowviant-turn.lock');
411
+ if (turnLockedByLivePid(lockPath)) {
412
+ warn(
413
+ `a turn is already running in "${job.sessionName || job.sessionId}" — waiting for it to finish`
414
+ );
415
+ return;
416
+ }
417
+ const rt = sessionRuntime(dir.wt);
418
+ if (rt.missing) {
419
+ await settleWorkTurn(job.id, {
420
+ ok: false,
421
+ answer: `this session runs on ${rt.missing}, which is no longer installed on the machine — reinstall it, or open a new tab`,
422
+ });
423
+ return;
424
+ }
425
+ if (!rt.id) {
426
+ await settleWorkTurn(job.id, {
427
+ ok: false,
428
+ answer:
429
+ 'No coding CLI is installed on the machine — install Claude Code (or another supported CLI), then send the message again',
430
+ });
431
+ return;
432
+ }
433
+ let mint = await mintWorkToken(job.sessionId);
434
+ if (!mint) mint = await mintWorkToken(job.sessionId, true); // one transient blip ≠ a dead turn
435
+ if (mint?.gone) {
436
+ await settleWorkTurn(job.id, {
437
+ ok: false,
438
+ answer:
439
+ 'Flowviant no longer offers this session to this machine — the tab may have been closed or moved',
440
+ });
441
+ return;
442
+ }
443
+ if (!mint?.token) {
444
+ await settleWorkTurn(job.id, {
445
+ ok: false,
446
+ answer:
447
+ 'the machine could not mint a session credential from Flowviant — check its connection, then send the message again',
448
+ });
449
+ return;
450
+ }
451
+ // Resume iff a conversation is known to live in THIS directory: the
452
+ // server's sessionRef is only ever a path some turn actually SPOKE
453
+ // from (see the settle below), and it must match the directory we
454
+ // just opened. Anything else starts fresh IN the existing worktree —
455
+ // never a reset; the dirty state is the session.
456
+ const resume = !dir.fresh && Boolean(job.sessionRef) && job.sessionRef === dir.wt;
457
+ const mcp = mcpFor(rt.id, mint.token, getMcpUrl());
458
+ // Attempts count RUNS: the infra refusals above consumed nothing and
459
+ // settled on their own terms.
460
+ workAttempts.set(job.id, tries + 1);
461
+ let out;
462
+ const spawned = []; // this turn's children, for the teardown registry
463
+ try {
464
+ const turnArgs = {
465
+ prompt: WORK_TURN_KICKOFF({
466
+ sessionId: job.sessionId,
467
+ sessionName: job.sessionName,
468
+ message: job.body,
469
+ askedByName: job.askedByName,
470
+ }),
471
+ system: SYSTEM_WORK,
472
+ cwd: dir.wt,
473
+ mcpArgs: mcp.args,
474
+ mcpEnv: mcp.env,
475
+ runtime: rt.id,
476
+ label: c.cyan('[tab]'),
477
+ onSpawn: (ch) => {
478
+ if (!ch) return;
479
+ spawned.push(ch);
480
+ workChildren.set(ch, lockPath ?? null);
481
+ if (lockPath && ch.pid) {
482
+ try {
483
+ writeFileSync(lockPath, String(ch.pid));
484
+ } catch {
485
+ /* best-effort */
486
+ }
487
+ }
488
+ },
489
+ };
490
+ out = await runTurn({ ...turnArgs, resume });
491
+ // A resume that produced NOTHING usually means the held
492
+ // conversation is gone (a first turn that crashed before writing
493
+ // state, a wiped CLI dir). Retry once fresh in the SAME worktree —
494
+ // never reset — instead of bricking the tab forever.
495
+ if (resume && !(out || '').trim()) out = await runTurn({ ...turnArgs, resume: false });
496
+ } finally {
497
+ for (const ch of spawned) workChildren.delete(ch);
498
+ if (lockPath) {
499
+ try {
500
+ rmSync(lockPath, { force: true });
501
+ } catch {
502
+ /* best-effort */
503
+ }
504
+ }
505
+ if (mcp.dir) rmSync(mcp.dir, { recursive: true, force: true });
506
+ }
507
+ const answer = (out || '').trim();
508
+ // No output at all smells like a dead MCP credential (the lane
509
+ // workers' no-sentinel case) — drop the cached token so the next
510
+ // turn re-mints instead of failing the same way forever.
511
+ if (!answer) workTokens.delete(job.sessionId);
512
+ await settleWorkTurn(job.id, {
513
+ ok: answer.length > 0,
514
+ answer:
515
+ answer.length > 0
516
+ ? // Scrub: a reply can quote config or env-adjacent code.
517
+ envScrub(answer).slice(0, 16000)
518
+ : 'the turn produced no output on the machine — its CLI may be signed out; try again',
519
+ // Only a turn that actually SPOKE proves a conversation lives
520
+ // here. Recording the path unconditionally is how a crashed first
521
+ // turn used to brick resume for the session's whole life.
522
+ ...(answer.length > 0 ? { sessionRef: dir.wt } : {}),
523
+ });
524
+ if (answer.length > 0) ok(`${c.cyan('tab')} ${c.dim('— replied in the session')}`);
525
+ else warn('session turn produced no output — settled as failed');
526
+ } catch (e) {
527
+ await settleWorkTurn(job.id, {
528
+ ok: false,
529
+ // Scrub, like every string that leaves this machine: an exception
530
+ // routinely quotes command output, and command output can quote a
531
+ // synced secret.
532
+ answer: envScrub(String(e?.message ?? 'the session turn failed')).slice(0, 2000),
533
+ });
534
+ warn(`session turn failed: ${e?.message ?? e}`);
535
+ } finally {
536
+ workAnswering.delete(job.id);
537
+ }
538
+ });
539
+ }
540
+ };
541
+
542
+ // Ship — a session's branch merging to main, on the human's word.
543
+ //
544
+ // --no-ff, NEVER squash: every delivered card carries commit shas as its
545
+ // receipts, and a squash would point them all at commits that no longer
546
+ // exist on main. Sequence: idempotency FIRST (a re-offered job after a lost
547
+ // report recovers its receipts and re-reports — it must never re-merge, and
548
+ // never be refused by checks that judge a merge this job already made).
549
+ // Then two paths. A LIVE session: re-open the worktree if it was retired,
550
+ // defer while a turn's CLI holds it, refuse a dirty worktree
551
+ // (auto-committing someone's mid-thought state is not shipping, it is
552
+ // guessing), refuse a worktree that left its own branch, fold main INTO the
553
+ // branch first so conflicts surface where the session can resolve them,
554
+ // then merge THE RESOLVED TIP outward through a throwaway worktree so
555
+ // nobody's checkout moves — receipts and merged ref are the same sha by
556
+ // construction. An ENDED session (absent from the roster's
557
+ // activeWorkSessions): the BRANCH is the session now — nobody can commit,
558
+ // discard, or resolve anything in its directory, so the checks whose
559
+ // remedies address a live tab don't apply; merge the tip directly through
560
+ // the throwaway, and a conflict fails honestly. Every exit reports
561
+ // ship-done exactly once — except a deliberate deferral, re-offered next
562
+ // poll; a ship that failed silently leaves the human believing their work
563
+ // is on main.
564
+ const processShipJobs = (jobs, activeIds) => {
565
+ // Field absent (older server) = no liveness signal: treat every session
566
+ // as live, which keeps the stricter checks.
567
+ const liveIds = Array.isArray(activeIds) ? new Set(activeIds) : null;
568
+ for (const job of jobs ?? []) {
569
+ if (!job || typeof job.sessionId !== 'string') continue;
570
+ if (shipping.has(job.sessionId)) continue;
571
+ // The merge already LANDED and only the report is owed — flushing
572
+ // delivers it; re-running the ship would misread its own success.
573
+ if (pendingShipReports.has(job.sessionId)) continue;
574
+ shipping.add(job.sessionId);
575
+ // The SESSION's own chain, never a ship-wide one: a ship must not run
576
+ // git in this worktree while a turn's CLI is live in it. `shipping`
577
+ // (above) keeps overlapping polls from queueing the same job twice.
578
+ chainFor(job.sessionId, async () => {
579
+ let settled = false;
580
+ let deferred = false;
581
+ const done = async (payload) => {
582
+ if (settled) return;
583
+ settled = true;
584
+ await settleShip(job.sessionId, payload);
585
+ };
586
+ try {
587
+ if (!isSafePathSegment(job.sessionId)) {
588
+ await done({ ok: false, error: 'invalid session id' });
589
+ return;
590
+ }
591
+ note(`${c.cyan('ship')} ${c.dim(`— "${job.sessionName || job.sessionId}"`)}`);
592
+ const branch = `session/${job.sessionId}`;
593
+ const wt = join(baseDir, 'sessions', job.sessionId);
594
+ let branchExists = true;
595
+ try {
596
+ git(['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`], repoRoot);
597
+ } catch {
598
+ branchExists = false;
599
+ }
600
+ // "Nothing to ship" is a statement about the BRANCH. A retired
601
+ // directory is not a missing session — retirement promises that
602
+ // committed work survives, and ship re-attaches below to keep it.
603
+ if (!existsSync(wt) && !branchExists) {
604
+ await done({
605
+ ok: false,
606
+ error: 'nothing to ship — this session has no branch on this machine',
607
+ });
608
+ return;
609
+ }
610
+ try {
611
+ git(['fetch', 'origin', '--quiet'], repoRoot);
612
+ } catch {
613
+ /* offline fetch — merge against what we have */
614
+ }
615
+ const ancestorOfBase = (ref) => {
616
+ try {
617
+ git(['merge-base', '--is-ancestor', ref, baseRef], repoRoot);
618
+ return true;
619
+ } catch {
620
+ return false;
621
+ }
622
+ };
623
+ // The machine may have no git identity, and a merge COMMIT needs
624
+ // one. Prefer the user's own config; fall back to the daemon's (the
625
+ // same fallback checkpointWip uses) so a bare machine doesn't fail
626
+ // the fold with "Please tell me who you are".
627
+ let idEnv = null;
628
+ try {
629
+ git(['config', 'user.email'], repoRoot);
630
+ } catch {
631
+ idEnv = {
632
+ GIT_AUTHOR_NAME: 'Flowviant',
633
+ GIT_AUTHOR_EMAIL: 'daemon@flowviant.com',
634
+ GIT_COMMITTER_NAME: 'Flowviant',
635
+ GIT_COMMITTER_EMAIL: 'daemon@flowviant.com',
636
+ };
637
+ }
638
+ const gitMerge = (args, cwd) =>
639
+ execFileSync('git', args, {
640
+ cwd,
641
+ encoding: 'utf8',
642
+ stdio: ['ignore', 'pipe', 'pipe'],
643
+ ...(idEnv ? { env: { ...process.env, ...idEnv } } : {}),
644
+ });
645
+ // Receipts for a range: --no-merges, because fold commits describe
646
+ // plumbing, not work.
647
+ const logCommits = (range) =>
648
+ git(['log', range, '--no-merges', '--format=%H%x09%s'], repoRoot)
649
+ .split('\n')
650
+ .filter(Boolean)
651
+ .map((l) => {
652
+ const [sha, ...rest] = l.split('\t');
653
+ return { sha, subject: envScrub(rest.join('\t')).slice(0, 200) };
654
+ });
655
+ // Merge outward through a throwaway worktree so no checkout moves.
656
+ // The throwaway dies on EVERY exit — success, conflict or throw —
657
+ // or the next ship of this session trips over its corpse.
658
+ const mergeOutward = (tip, count) => {
659
+ const tmp = join(baseDir, 'ship', job.sessionId);
660
+ try {
661
+ try {
662
+ git(['worktree', 'remove', '--force', tmp], repoRoot);
663
+ } catch {
664
+ /* not there — fine */
665
+ }
666
+ git(['worktree', 'add', '--detach', tmp, baseRef], repoRoot);
667
+ gitMerge(
668
+ [
669
+ 'merge',
670
+ '--no-ff',
671
+ tip,
672
+ '-m',
673
+ `ship(${job.sessionName || job.sessionId.slice(0, 8)}): ${count} commit${count === 1 ? '' : 's'}`,
674
+ ],
675
+ tmp
676
+ );
677
+ git(['push', 'origin', `HEAD:${baseBranchName(baseRef)}`], tmp);
678
+ } finally {
679
+ try {
680
+ git(['worktree', 'remove', '--force', tmp], repoRoot);
681
+ git(['worktree', 'prune'], repoRoot);
682
+ } catch {
683
+ /* best effort */
684
+ }
685
+ }
686
+ };
687
+ // Idempotency: base already contains the branch tip. A re-offered
688
+ // job after a lost report lands here — never a re-merge, and never
689
+ // "nothing to ship" AS A FAILURE for work that in fact shipped. The
690
+ // receipts must not die with the lost report: the --no-ff merge
691
+ // commit that carried the tip in holds it as its SECOND parent, so
692
+ // the original commit list is recoverable — settling with none
693
+ // would silently skip the reconciliation backstop for this branch.
694
+ if (branchExists && ancestorOfBase(branch)) {
695
+ const tip = git(['rev-parse', branch], repoRoot);
696
+ let commits = [];
697
+ try {
698
+ const m = git(['log', baseRef, '--merges', '--format=%H %P', '-n', '500'], repoRoot)
699
+ .split('\n')
700
+ .map((l) => l.trim().split(' '))
701
+ .find((p) => p.length >= 3 && p[2] === tip);
702
+ if (m) commits = logCommits(`${m[1]}..${tip}`);
703
+ } catch {
704
+ /* recovery is best-effort — an ok ship with no receipts beats a false failure */
705
+ }
706
+ await done({
707
+ ok: true,
708
+ commits,
709
+ note: `${baseBranchName(baseRef)} already contains this session's branch — nothing new to merge`,
710
+ });
711
+ ok(`${c.cyan('ship')} ${c.dim('— already on main; nothing new to merge')}`);
712
+ return;
713
+ }
714
+ const ended = liveIds ? !liveIds.has(job.sessionId) : false;
715
+ if (ended) {
716
+ // The tab is closed: no turn can commit, discard, or resolve
717
+ // anything in the directory, so a dirty worktree must not strand
718
+ // the branch's committed work in review forever. Ship the TIP.
719
+ if (!branchExists) {
720
+ await done({
721
+ ok: false,
722
+ error: 'nothing to ship — this session has no branch on this machine',
723
+ });
724
+ return;
725
+ }
726
+ const tip = git(['rev-parse', branch], repoRoot);
727
+ const commits = logCommits(`${baseRef}..${tip}`);
728
+ if (commits.length === 0) {
729
+ await done({
730
+ ok: false,
731
+ error: 'nothing to ship — no commits on the session branch',
732
+ });
733
+ return;
734
+ }
735
+ try {
736
+ mergeOutward(tip, commits.length);
737
+ } catch (e) {
738
+ const detail = `${e?.stdout ?? ''}\n${e?.stderr ?? ''}\n${e?.message ?? ''}`;
739
+ if (/conflict/i.test(detail)) {
740
+ await done({
741
+ ok: false,
742
+ error:
743
+ 'conflicts with main — the tab is closed, so open a new session from this branch to resolve them, then ship again',
744
+ });
745
+ } else {
746
+ const line = envScrub(
747
+ String(detail)
748
+ .split('\n')
749
+ .find((l) => l.trim()) ?? 'git merge failed'
750
+ );
751
+ await done({ ok: false, error: `the merge failed: ${line.slice(0, 300)}` });
752
+ }
753
+ return;
754
+ }
755
+ await done({ ok: true, commits });
756
+ ok(`${c.cyan('ship')} ${c.dim(`— ${commits.length} commit${commits.length === 1 ? '' : 's'} on main`)}`);
757
+ return;
758
+ }
759
+ const dir = sessionWtFor(job.sessionId);
760
+ if (!dir) {
761
+ await done({
762
+ ok: false,
763
+ error: 'the session worktree could not be opened on this machine',
764
+ });
765
+ return;
766
+ }
767
+ // A live CLI is in this worktree — a restarted daemon's orphan
768
+ // mid-turn (in-process the chain serializes, but the lock is the
769
+ // only guarantee that survives a crash). Folding under it would
770
+ // rewrite HEAD inside a held conversation; defer like the turn
771
+ // path, and the job re-offers next poll.
772
+ if (turnLockedByLivePid(sessionMetaPath(dir.wt, 'flowviant-turn.lock'))) {
773
+ warn(
774
+ `a turn is still running in "${job.sessionName || job.sessionId}" — ship waits for it`
775
+ );
776
+ deferred = true;
777
+ return;
778
+ }
779
+ if (git(['status', '--porcelain'], dir.wt) !== '') {
780
+ await done({
781
+ ok: false,
782
+ error:
783
+ 'the session has uncommitted changes — ask it to commit or discard them first',
784
+ });
785
+ return;
786
+ }
787
+ // What is checked out here must BE the session branch. Sessions may
788
+ // create branches when asked — but then "ship" is ambiguous, and
789
+ // folding+logging HEAD while merging the stale branch NAME once
790
+ // shipped receipts for commits that never landed on main.
791
+ let head = null;
792
+ try {
793
+ head = git(['symbolic-ref', '--short', 'HEAD'], dir.wt);
794
+ } catch {
795
+ /* detached */
796
+ }
797
+ if (head !== branch) {
798
+ await done({
799
+ ok: false,
800
+ error: `the session is on ${head ? `branch '${head}'` : 'a detached HEAD'}, not its own '${branch}' — ask it to return to its session branch, then ship again`,
801
+ });
802
+ return;
803
+ }
804
+ // Fold main into the branch FIRST: conflicts land here, in the
805
+ // session's own worktree, where the next turn can resolve them.
806
+ try {
807
+ gitMerge(['merge', '--no-edit', baseRef], dir.wt);
808
+ } catch (e) {
809
+ const detail = `${e?.stdout ?? ''}\n${e?.stderr ?? ''}\n${e?.message ?? ''}`;
810
+ // NEVER leave the session mid-merge: a MERGE_HEAD left behind puts
811
+ // every later turn inside someone else's half-finished merge.
812
+ try {
813
+ git(['merge', '--abort'], dir.wt);
814
+ } catch {
815
+ /* nothing in progress */
816
+ }
817
+ if (/conflict/i.test(detail)) {
818
+ await done({
819
+ ok: false,
820
+ error: 'conflicts with main — ask the session to resolve them, then ship again',
821
+ });
822
+ } else {
823
+ // An honest error beats a fabricated conflict — the human can
824
+ // only fix what they are told about.
825
+ const line = envScrub(
826
+ String(detail)
827
+ .split('\n')
828
+ .find((l) => l.trim()) ?? 'git merge failed'
829
+ );
830
+ await done({ ok: false, error: `the merge failed: ${line.slice(0, 300)}` });
831
+ }
832
+ return;
833
+ }
834
+ // Resolve the EXACT sha to merge, then compute the receipts from it:
835
+ // one X for both, so the ledger can never carry receipts for commits
836
+ // that did not land.
837
+ const tip = git(['rev-parse', branch], repoRoot);
838
+ const commits = logCommits(`${baseRef}..${tip}`);
839
+ if (commits.length === 0) {
840
+ // Post-fold this is nearly unreachable (a zero-commit branch is an
841
+ // ancestor of base, settled above) — but if the branch's commits
842
+ // all exist on main already, say so truthfully.
843
+ if (ancestorOfBase(tip)) {
844
+ await done({ ok: true, commits: [], note: 'already merged — nothing new to ship' });
845
+ } else {
846
+ await done({
847
+ ok: false,
848
+ error: 'nothing to ship — no commits on the session branch',
849
+ });
850
+ }
851
+ return;
852
+ }
853
+ mergeOutward(tip, commits.length);
854
+ await done({ ok: true, commits });
855
+ ok(`${c.cyan('ship')} ${c.dim(`— ${commits.length} commit${commits.length === 1 ? '' : 's'} on main`)}`);
856
+ } catch (e) {
857
+ warn(`ship failed: ${e?.message ?? e}`);
858
+ await done({
859
+ ok: false,
860
+ error: envScrub(String(e?.message ?? 'the merge failed')).slice(0, 500),
861
+ });
862
+ } finally {
863
+ if (!settled && !deferred) {
864
+ // Belt over braces: NO exit path may leave the ship unreported —
865
+ // a deferral is the one deliberate exception, re-offered next poll.
866
+ await done({ ok: false, error: 'the ship did not complete — check the daemon log' });
867
+ }
868
+ shipping.delete(job.sessionId);
869
+ }
870
+ });
871
+ }
872
+ };
873
+
874
+ return { flushWorkReports, processWorkTurns, processShipJobs, retireWorkSessions, shutdownWork };
875
+ }