viewable-one 0.12.2 → 0.12.3

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 (59) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +2 -2
  3. package/SPAWN.md +107 -53
  4. package/glytch.mjs +41 -10
  5. package/lib/acp.mjs +110 -148
  6. package/lib/admission.mjs +25 -5
  7. package/lib/agents.mjs +59 -16
  8. package/lib/answerTag.mjs +47 -0
  9. package/lib/atomic.mjs +1 -16
  10. package/lib/auth.mjs +25 -9
  11. package/lib/boardside.mjs +28 -12
  12. package/lib/child.mjs +89 -116
  13. package/lib/claudeModels.mjs +168 -0
  14. package/lib/codex-rpc.mjs +2 -2
  15. package/lib/codex.mjs +43 -63
  16. package/lib/codexApps.mjs +5 -3
  17. package/lib/codexToolInputs.mjs +98 -22
  18. package/lib/codingChecks.mjs +8 -4
  19. package/lib/conversationRules.mjs +46 -6
  20. package/lib/detect.mjs +14 -23
  21. package/lib/devserver.mjs +6 -6
  22. package/lib/doctor.mjs +4 -2
  23. package/lib/folderReads.mjs +96 -0
  24. package/lib/followUps.mjs +170 -0
  25. package/lib/hosted.mjs +13 -4
  26. package/lib/init-connect.mjs +29 -10
  27. package/lib/lateResume.mjs +135 -0
  28. package/lib/logindaemon.mjs +113 -33
  29. package/lib/mcpjson.mjs +35 -2
  30. package/lib/multiwatch.mjs +25 -38
  31. package/lib/pagePictures.mjs +14 -11
  32. package/lib/paths.mjs +0 -1
  33. package/lib/permissionAsk.mjs +341 -58
  34. package/lib/procs.mjs +73 -2
  35. package/lib/refusal.mjs +0 -2
  36. package/lib/restartPass.mjs +39 -11
  37. package/lib/rowsAnswers.mjs +18 -34
  38. package/lib/rowsEvents.mjs +20 -2
  39. package/lib/runner-health.mjs +26 -2
  40. package/lib/runner.mjs +106 -1363
  41. package/lib/runnerAdmission.mjs +6 -12
  42. package/lib/runnerApi.mjs +20 -11
  43. package/lib/runnerBeat.mjs +384 -0
  44. package/lib/runnerCompletion.mjs +5 -2
  45. package/lib/runnerExecute.mjs +227 -0
  46. package/lib/runnerGates.mjs +338 -0
  47. package/lib/runnerLaunch.mjs +351 -0
  48. package/lib/runnerLease.mjs +31 -9
  49. package/lib/runnerOps.mjs +217 -0
  50. package/lib/runnerPace.mjs +10 -6
  51. package/lib/runnerRecovery.mjs +457 -0
  52. package/lib/runnerRegister.mjs +28 -7
  53. package/lib/runnerSettlement.mjs +29 -9
  54. package/lib/spawn.mjs +0 -5
  55. package/lib/sync.mjs +26 -14
  56. package/lib/viewableFolder.mjs +8 -2
  57. package/lib/worktree.mjs +66 -13
  58. package/lib/writePolicy.mjs +90 -10
  59. package/package.json +1 -1
@@ -0,0 +1,351 @@
1
+ // Spawn, retry, check, complete: the half of one claimed run that starts a
2
+ // process, moved out of runner.mjs's `executeRequest` (#4668). `startRun`
3
+ // is the step the run's process lives in; `retryOnce` and `checkAndRepair`
4
+ // are the two things that can run the engine again after the first try.
5
+
6
+ import { mkdir, rm, writeFile } from "node:fs/promises";
7
+ import { join, posix, win32 } from "node:path";
8
+ import { createRowsAnswerPoll } from "./rowsAnswers.mjs";
9
+ import { createPermissionAsker } from "./permissionAsk.mjs";
10
+ import { makeRowEventStreamer } from "./rowsEvents.mjs";
11
+ import { AGENTS, agentFor, prepareWorkspace, runnerFor } from "./agents.mjs";
12
+ import { classifyExit } from "./exitClass.mjs";
13
+ import { DEFAULTS, childEnv } from "./child.mjs";
14
+ import { BOARD_DIR } from "./paths.mjs";
15
+ import { completeRequest, mayHaveChangedFiles } from "./runnerCompletion.mjs";
16
+ import { OUT_OF_TIME, runCodingChecks } from "./codingChecks.mjs";
17
+ import { beforePicture, checkPage } from "./pagePictures.mjs";
18
+ import { retainRunEvents, deliverRunEvents, isMissingConversation } from "./runnerSettlement.mjs";
19
+ import { changedFiles } from "./worktree.mjs";
20
+
21
+ /** The two notes a fresh session gets in place of a conversation that could
22
+ * not be resumed: its worktree is gone, or Claude Code has no record of it. */
23
+ export function resumeNotes(request) {
24
+ const TREE_GONE_NOTE =
25
+ `[From the runner] The earlier conversation for this prompt could not be resumed: ` +
26
+ `the worktree it lived in (${request.worktreePath}) is gone, and Claude Code keeps ` +
27
+ `conversations per working directory. This is a FRESH session in a new worktree, with ` +
28
+ `none of that history. Work from the prompt above and from the repository.`;
29
+ const NOT_FOUND_NOTE =
30
+ `[From the runner] The earlier conversation for this prompt could not be resumed: its ` +
31
+ `worktree is still here, but Claude Code has no record of session ` +
32
+ `${String(request.resumeSessionId ?? "").trim()} in it. This is a FRESH session in that ` +
33
+ `same worktree, with none of that history. Work from the prompt above, and from what is ` +
34
+ `already committed on this branch.`;
35
+ return { TREE_GONE_NOTE, NOT_FOUND_NOTE };
36
+ }
37
+
38
+ /** Spawn the run's process and see it through to its receipt. */
39
+ export async function startRun(ctx, state, { timing, receipt, preparation, finish }) {
40
+ const { root, id, request, isChat, runnerApi, rowsOpts, hostedEnv, session, boardId, settings, log } = ctx;
41
+ const { referenceImages, from, agent, made, useStreaming, boardToken, childMcpUrl, hostedCallTool, isPersistent, maxMs, resumeTreeGone, resumeSessionId, planRun } = state;
42
+ const { TREE_GONE_NOTE, NOT_FOUND_NOTE } = resumeNotes(request);
43
+ const plan = await planRun({ resumeId: resumeSessionId, note: resumeTreeGone ? TREE_GONE_NOTE : null });
44
+ const { prompt, chosen, args } = plan;
45
+
46
+ let prepared = { wrote: null };
47
+ try {
48
+ prepared = await prepareWorkspace(agent, { mcpUrl: childMcpUrl, token: boardToken, sessionKey: session.key, boardId });
49
+ } catch (error) {
50
+ log(`[${id}] could not prepare the board config: ${error?.message ?? error}`);
51
+ }
52
+
53
+ // LOG STREAMING, over run_events (item 3). Uncapped live; the cap shows up
54
+ // in the final flush - see rowsEvents.mjs's own header for why.
55
+ const streamer = makeRowEventStreamer({
56
+ initialSeq: ctx.eventSeq ?? 0,
57
+ retain: (events) => retainRunEvents(ctx.project, id, events, settings),
58
+ send: (events) => deliverRunEvents(ctx.project, id, events, settings, log),
59
+ log,
60
+ });
61
+ const flushTimer = setInterval(() => void streamer.tick(), settings.logFlushMs ?? 3000);
62
+ if (flushTimer.unref) flushTimer.unref();
63
+ let imagesDir = null;
64
+ let rowsPoll = null;
65
+ try {
66
+ const onChunk = (chunk) => { if (chunk.length > 0) { timing.output(); void settings.recoveryTracker?.output(); } streamer.onChunk(chunk); };
67
+
68
+ const childEnvObj = childEnv(settings.baseEnv ?? process.env, { root, session, depth: settings.depth, fromId: from });
69
+ if (boardToken) childEnvObj.PM_BOARD_TOKEN = boardToken;
70
+ Object.assign(childEnvObj, prepared.env ?? {});
71
+ // npm agents use /usr/bin/env node. Discovery alone is not enough after
72
+ // nvm/fnm removes the old Node: every spawn and retry needs its new bin dir.
73
+ const windows = (settings.platform ?? process.platform) === "win32";
74
+ const paths = windows ? win32 : posix;
75
+ if (settings.claudeBin === undefined && state.resolvedBinPath && paths.isAbsolute(state.resolvedBinPath)) {
76
+ const key = windows ? Object.keys(childEnvObj).find(key => key.toLowerCase() === "path") ?? "PATH" : "PATH";
77
+ childEnvObj[key] = [paths.dirname(state.resolvedBinPath), childEnvObj[key]].filter(Boolean).join(windows ? ";" : ":");
78
+ }
79
+
80
+
81
+ // STOP, from the runner's own heartbeat beat (item 5: heartbeat's `stops`
82
+ // replaces the `.stop` file). `settings.stopped` is a Set the watch loop
83
+ // keeps current; a run started outside the watch loop (a test, `pollOnce`)
84
+ // simply never sees anything in it, which is the same as "never asked to
85
+ // stop".
86
+ const stopCheck = async () => Boolean(settings.stopped?.has(id));
87
+
88
+ rowsPoll = boardToken
89
+ ? createRowsAnswerPoll({ callTool: hostedCallTool, sessionKey: session.key, env: hostedEnv, log, realtime: settings.realtime })
90
+ : null;
91
+ const answerPoll = rowsPoll ? rowsPoll.poll : undefined;
92
+ // Who answers "can I do this?" for a run on this computer. Only for a run
93
+ // that can wait for a person: streaming Claude, non-draft Codex and the ACP
94
+ // engine (#4615), with a board to file the question on. A draft never asks
95
+ // (it stays read-only).
96
+ const askPermission = boardToken && request.planMode !== "draft" && (useStreaming || agentFor(agent) === "codex" || chosen.spec?.protocol === "acp")
97
+ ? createPermissionAsker({
98
+ folder: root, cwd: made.cwd, agentLabel: AGENTS[agentFor(agent)]?.label ?? "The agent", session, boardId, fromId: from, env: hostedEnv,
99
+ callTool: hostedCallTool, poll: rowsPoll, log: (message) => log(`[${id}] ${message}`),
100
+ pollMs: settings.permissionPollMs ?? 2000,
101
+ })
102
+ : undefined;
103
+
104
+ let imageSuffix = "";
105
+ const promptIsAnArgument = args.some((a) => typeof a === "string" && a.includes(prompt));
106
+ const protocolImages = useStreaming || ["acp", "codex-app-server"].includes(chosen.spec?.protocol);
107
+ if (referenceImages.length > 0 && !protocolImages) {
108
+ if (!promptIsAnArgument) {
109
+ clearInterval(flushTimer);
110
+ throw new Error("Reference images cannot be delivered by this command: it has no prompt argument or image transport. Restore the engine's standard command and try again.");
111
+ }
112
+ const imgDir = join(root, BOARD_DIR, "images", id);
113
+ imagesDir = imgDir;
114
+ try {
115
+ await mkdir(imgDir, { recursive: true });
116
+ const paths = [];
117
+ for (const [index, image] of referenceImages.entries()) {
118
+ const filePath = join(imgDir, `context-${index}.${image.extension}`);
119
+ await writeFile(filePath, image.bytes);
120
+ paths.push(filePath);
121
+ }
122
+ imageSuffix = `\n\n[${paths.length} screenshot${paths.length === 1 ? "" : "s"} from the idea's pictures, saved as files. Open each with your image-capable Read/view tool:${paths.map((p) => `\n ${p}`).join("")}]`;
123
+ log(`[${id}] wrote all ${paths.length} reference image(s) to ${imgDir}`);
124
+ } catch (error) {
125
+ clearInterval(flushTimer);
126
+ throw new Error(`Reference images could not be prepared; no coding session was started: ${error.message}`);
127
+ }
128
+ }
129
+
130
+ const makeRunOpts = runOptionsFor(ctx, state, { imageSuffix, onChunk, childEnvObj, stopCheck, answerPoll, askPermission, receipt });
131
+ const runOpts = makeRunOpts(plan);
132
+ const runFn = runnerFor(agent, useStreaming);
133
+
134
+ if (settings.stopped?.has(id)) return await finish({ status: "stopped", result: settings.leaseLost?.has(id) ? "STOPPED\n\nRunner connection expired before the process was started.\n" : "STOPPED\n\nStopped by user request before the process was started.\n", finished_at: new Date().toISOString() });
135
+ preparation.complete();
136
+ timing.launched();
137
+ const firstRunStartedAt = Date.now();
138
+ settings.recoveryTracker?.launching();
139
+ const firstTry = await runFn(runOpts);
140
+ if ((request.recovery === true && (isMissingConversation(firstTry) || (!firstTry.ok && !firstTry.sawAssistant))) || (request.continues && isMissingConversation(firstTry))) {
141
+ clearInterval(flushTimer);
142
+ await streamer.settle(firstTry.log ?? "", { dropped: firstTry.dropped ?? 0 });
143
+ return finish({ status: "error", result: "ERROR\n\nThe conversation could not carry on. Run again to start a new session.\n", finished_at: new Date().toISOString(), sidecar: { ...receipt.sidecar, ...(request.recovery === true ? { recoveryFailed: true } : {}) } });
144
+ }
145
+ const remainingBudget = () => Math.max(1000, maxMs - (Date.now() - firstRunStartedAt));
146
+
147
+ const retried = await retryOnce(ctx, {
148
+ made, firstTry, runFn, runOpts, makeRunOpts, planRun, resumeSessionId, remainingBudget, NOT_FOUND_NOTE,
149
+ });
150
+ let { outcome, sessionIdSource } = retried;
151
+ const { resumeNotFound } = retried;
152
+
153
+ // Checking is part of this run, before its one closing reply and cleanup.
154
+ // Drafts and chat turns must never start scripts or an automatic edit.
155
+ if (outcome.ok && !isChat && request.planMode !== "draft" && !await stopCheck()) {
156
+ ({ outcome, sessionIdSource } = await checkAndRepair(ctx, state, {
157
+ outcome, sessionIdSource, stopCheck, firstRunStartedAt, childEnvObj, onChunk, runFn, makeRunOpts, remainingBudget,
158
+ }));
159
+ }
160
+
161
+ timing.exited();
162
+ clearInterval(flushTimer);
163
+ await streamer.settle(outcome.log ?? "", { dropped: outcome.dropped ?? 0 });
164
+ if (imagesDir) await rm(imagesDir, { recursive: true, force: true }).catch(() => {});
165
+
166
+ // A lease expiry is an interruption, not a human Stop or an ending.
167
+ // Leave result null for the reaper/restart pass, and keep the copy intact.
168
+ if (settings.leaseLost?.has(id)) return { id, state: "waiting" };
169
+
170
+ const completed = await completeRequest({
171
+ root, id, outcome, made, isPersistent, isChat, sessionIdSource, from, session, maxMs, agent,
172
+ readStopRequested: () => Boolean(settings.stopped?.has(id)) || outcome.stoppedByUser === true,
173
+ resumeTreeGone, resumeNotFound, request, log,
174
+ rowsPoll, hostedCallTool, hostedEnv,
175
+ resumeFn: (args, opts) => runnerApi.resume(args, { ...rowsOpts, ...opts }),
176
+ });
177
+ return await finish(completed.patch);
178
+ } finally {
179
+ rowsPoll?.close();
180
+ clearInterval(flushTimer);
181
+ if (imagesDir) await rm(imagesDir, { recursive: true, force: true }).catch(() => {});
182
+ }
183
+ }
184
+
185
+ /** The options one try of the engine runs with, for a plan from `planRun`.
186
+ * `extra` overrides the defaults (a retry's shorter `maxMs`). */
187
+ function runOptionsFor({ id, request, runnerApi, rowsOpts, settings, log }, { agent, made, useStreaming, maxMs }, { imageSuffix, onChunk, childEnvObj, stopCheck, answerPoll, askPermission, receipt }) {
188
+ return (p, extra = {}) => {
189
+ const renderedPrompt = p.prompt + imageSuffix;
190
+ const withImages = imageSuffix
191
+ ? p.args.map((a) => (typeof a === "string" && a.includes(p.prompt) ? a.replace(p.prompt, () => p.prompt + imageSuffix) : a))
192
+ : p.args;
193
+ const platform = settings.platform ?? process.platform;
194
+ const promptArgIndex = p.chosen.args.findIndex((arg, index) => arg === "{prompt}" && ["-p", "--print"].includes(p.chosen.args[index - 1]));
195
+ const promptOnStdin = platform === "win32" && agentFor(agent) === "claude" && !useStreaming && promptArgIndex >= 0;
196
+ const childArgs = promptOnStdin ? withImages.filter((_arg, index) => index !== promptArgIndex) : withImages;
197
+ const base = {
198
+ bin: p.chosen.bin,
199
+ args: childArgs,
200
+ claudeResult: agent === "claude" && !useStreaming,
201
+ brief: p.brief,
202
+ cwd: made.cwd,
203
+ env: childEnvObj,
204
+ maxMs,
205
+ maxLogBytes: settings.maxLogBytes ?? DEFAULTS.maxLogBytes,
206
+ killGraceMs: settings.killGraceMs ?? DEFAULTS.killGraceMs,
207
+ stallMs: settings.stallMs ?? DEFAULTS.stallMs,
208
+ onChunk,
209
+ requireResume: request.recovery === true && Boolean(request.resumeSessionId),
210
+ recoveryGroup: Boolean(settings.recoveryTracker),
211
+ onProcess: settings.recoveryTracker ? (pid) => settings.recoveryTracker.onProcess(pid, { group: platform !== "win32" }) : undefined,
212
+ onSession: async (threadId) => {
213
+ receipt.sidecar = { ...receipt.sidecar, [agentFor(agent) === "codex" ? "codexThreadId" : "claudeSessionId"]: threadId, resumeSessionId: threadId, restartable: true };
214
+ settings.recoveryTracker?.persist();
215
+ await settings.recoveryTracker?.session();
216
+ if (agentFor(agent) !== "codex") return; // Other engines retain the ID locally and in the terminal receipt.
217
+ try {
218
+ const saved = await runnerApi.update({ runId: id, patch: { sidecar: receipt.sidecar } }, rowsOpts);
219
+ if (!saved.ok) log(`[${id}] could not record the conversation: ${saved.error}`);
220
+ } catch (error) {
221
+ log(`[${id}] could not record the conversation: ${error instanceof Error ? error.message : String(error)}`);
222
+ }
223
+ },
224
+ platform,
225
+ ...(promptOnStdin ? { input: renderedPrompt } : {}),
226
+ acp: p.chosen.acp ?? null,
227
+ codex: p.chosen.codex ?? null,
228
+ askPermission,
229
+ log: (message) => log(`[${id}] ${message}`),
230
+ };
231
+ return useStreaming
232
+ ? { ...base, prompt: renderedPrompt, images: request.images, stopCheck, answerPoll, answerPollMs: settings.rowsPollMs ?? 5000, ...extra }
233
+ : { ...base, prompt: renderedPrompt, images: request.images, stopCheck, ...extra };
234
+ };
235
+ }
236
+
237
+ /** After the first try: a resume that found no conversation goes again once
238
+ * as a fresh session in the same worktree; a crash that streamed nothing
239
+ * goes again once as it was. Anything else is the outcome as it stands. */
240
+ async function retryOnce({ id, log }, { made, firstTry, runFn, runOpts, makeRunOpts, planRun, resumeSessionId, remainingBudget, NOT_FOUND_NOTE }) {
241
+ const exitClass = classifyExit(firstTry.code, firstTry.signal);
242
+ let resumeNotFound = false;
243
+ let outcome;
244
+ let sessionIdSource = null;
245
+ if (resumeSessionId !== "" && isMissingConversation(firstTry)) {
246
+ log(`[${id}] the conversation ${resumeSessionId} was not found in ${made.cwd} ($0.00, 0 turns - nothing was spent); retrying once as a FRESH session there`);
247
+ resumeNotFound = true;
248
+ const freshPlan = await planRun({ resumeId: "", note: NOT_FOUND_NOTE });
249
+ const resumeLog = firstTry.log ?? "";
250
+ outcome = await runFn(makeRunOpts(freshPlan, { maxMs: remainingBudget() }));
251
+ sessionIdSource = outcome.log ?? "";
252
+ outcome.log = `=== Resume attempt (no conversation found; $0.00, 0 turns) ===\n${resumeLog}\n\n=== Fresh session in the same worktree ===\n${outcome.log ?? ""}`;
253
+ outcome.retried = true;
254
+ outcome.firstCrashClass = "the resumed conversation was not found";
255
+ } else if (exitClass.isCrash && !firstTry.sawAssistant && !firstTry.finished) {
256
+ log(`[${id}] first run ${exitClass.description}, no output streamed; retrying once`);
257
+ outcome = await runFn({ ...runOpts, maxMs: remainingBudget() });
258
+ if (firstTry.log) {
259
+ outcome.log = `=== First attempt (${exitClass.description}) ===\n${firstTry.log}\n\n=== Retry ===\n${outcome.log ?? ""}`;
260
+ outcome.retried = true;
261
+ outcome.firstCrashClass = exitClass.description;
262
+ }
263
+ } else {
264
+ outcome = firstTry;
265
+ }
266
+ return { outcome, sessionIdSource, resumeNotFound };
267
+ }
268
+
269
+ /** The folder's checks after a finished run, and at most one fix by the
270
+ * same engine when they fail. Returns the outcome with `result` set. */
271
+ async function checkAndRepair({ root, settings }, { made, maxMs, planRun }, { outcome, sessionIdSource, stopCheck, firstRunStartedAt, childEnvObj, onChunk, runFn, makeRunOpts, remainingBudget }) {
272
+ // A completed agent must not leave the card Working for tens of minutes
273
+ // while a full test/build pass eats the rest of the session (#3610).
274
+ // Each round of checks (tests, build, pictures) gets its own cap, never
275
+ // past the session's end. A check that hits it is "not finished", not
276
+ // failed. The one repair run stays on the session budget.
277
+ const sessionEnd = firstRunStartedAt + maxMs;
278
+ const checkCap = settings.checkMaxMs ?? DEFAULTS.checkMaxMs;
279
+ let deadline = Math.min(sessionEnd, Date.now() + checkCap);
280
+ const platform = settings.platform ?? process.platform;
281
+ const killGraceMs = settings.killGraceMs ?? DEFAULTS.killGraceMs;
282
+ // The page check and After come from the copy, only when the run changed
283
+ // a screen (#2194). A run with no copy has no list of what it changed.
284
+ const pageOptions = () => ({
285
+ cwd: made.cwd, folder: root, env: childEnvObj, baseEnv: settings.baseEnv ?? process.env,
286
+ platform, deadline, stopCheck, killGraceMs,
287
+ onProcess: settings.recoveryTracker ? (pid) => settings.recoveryTracker.onProcess(pid, { group: platform !== "win32" }) : undefined,
288
+ ...(settings.browser !== undefined ? { browser: settings.browser } : {}),
289
+ });
290
+ const checkAll = async () => {
291
+ deadline = Math.min(sessionEnd, Date.now() + checkCap);
292
+ const ran = await runCodingChecks({
293
+ cwd: made.cwd, env: childEnvObj, deadline, stopCheck, platform, killGraceMs, onChunk,
294
+ onProcess: settings.recoveryTracker ? (pid) => settings.recoveryTracker.onProcess(pid, { group: platform !== "win32" }) : undefined,
295
+ });
296
+ const paged = made.isolated && !ran.stopped && settings.pictures !== false
297
+ ? await checkPage({ ...pageOptions(), files: await changedFiles(made.cwd, root) }) : null;
298
+ if (!paged) return { ...ran, paged };
299
+ return {
300
+ ...ran, paged, stopped: ran.stopped || Boolean(paged.stopped),
301
+ checks: [...ran.checks, paged.check],
302
+ failures: paged.failure ? [...ran.failures, paged.failure] : ran.failures,
303
+ };
304
+ };
305
+ let checked = await checkAll();
306
+ outcome.log = (outcome.log ?? "") + checked.log;
307
+ let fixAttempted = false;
308
+ if (checked.failures.length && !checked.stopped && !await stopCheck() && Date.now() < sessionEnd) {
309
+ const fixPlan = await planRun({
310
+ resumeId: outcome.codexThreadId ?? outcome.envelope?.session_id ?? "",
311
+ fixing: true,
312
+ note: `The folder's checks failed after your work. Try ONE fix in this same folder. Reproduce the failed check, fix the cause without removing or weakening checks, and leave checking to the runner when you finish. Do not start another automatic attempt.\n\n${checked.failures.join("\n\n")}`,
313
+ });
314
+ if (!await stopCheck() && Date.now() < sessionEnd) {
315
+ fixAttempted = true;
316
+ const step = `${JSON.stringify({ type: "assistant", message: { content: [{ type: "text", text: "Coding is trying one fix." }] } })}\n`;
317
+ onChunk(step);
318
+ outcome.log = (outcome.log ?? "") + step;
319
+ const fixed = await runFn(makeRunOpts(fixPlan, { maxMs: remainingBudget() }));
320
+ const combinedLog = (outcome.log ?? "") + (fixed.log ?? "");
321
+ // A repair failure is a failed check, not a crash of the finished run.
322
+ // Keep its closing reply, and always verify the files left behind.
323
+ if (fixed.ok) {
324
+ outcome = { ...outcome, ...fixed };
325
+ sessionIdSource = fixed.log ?? "";
326
+ }
327
+ outcome.log = combinedLog;
328
+ outcome.stoppedByUser ||= fixed.stoppedByUser;
329
+ const previous = checked.checks;
330
+ checked = await checkAll();
331
+ outcome.log += checked.log;
332
+ checked.checks = checked.checks.map((check) => check.status === "skipped" && check.reason !== OUT_OF_TIME && previous.some((p) => p.kind === check.kind && p.status === "failed")
333
+ ? { ...check, status: "failed", failed: 1 } : check);
334
+ }
335
+ }
336
+ outcome.stoppedByUser ||= checked.stopped;
337
+ // Before is the folder's page, which the run has not touched yet.
338
+ deadline = Math.min(sessionEnd, Date.now() + checkCap);
339
+ const pictures = checked.paged?.after && !checked.stopped
340
+ ? await beforePicture({ ...pageOptions(), page: checked.paged.page, after: checked.paged.after, browser: checked.paged.browser })
341
+ : {};
342
+ // Whether this run changed a file decides if "Not checked" is worth
343
+ // saying at all (#4094). A runner copy knows exactly; a run in the
344
+ // person's own folder is judged from its log, a doubt reading as yes.
345
+ const filesChanged = made.isolated
346
+ ? (await changedFiles(made.cwd, root)).length > 0
347
+ : mayHaveChangedFiles(outcome.log, { dropped: outcome.dropped });
348
+ outcome.result = { checks: checked.checks, filesChanged, fixAttempted, ...pictures };
349
+ if (checked.paged?.note) outcome.picturesNote = checked.paged.note;
350
+ return { outcome, sessionIdSource };
351
+ }
@@ -1,11 +1,20 @@
1
1
  /** Lease renewal never restarts work. Losing ownership requests the same
2
- * local stop as the human Stop action, including during run preparation. */
3
- export function startRunLease(project, run, settings, { api, log = () => {}, now = () => performance.now(), every = setInterval, clear = clearInterval } = {}) {
2
+ * local stop as the human Stop action, including during run preparation.
3
+ * A fenced run (one with a lease generation) loses ownership only when the
4
+ * server says so: silence or an unreadable answer is an outage, and a run the
5
+ * reaper settled meanwhile stays this owner's to finish while the server
6
+ * names it held (#4948). Its receipt carries the generation, so the server
7
+ * refuses it if anyone else took the run over. */
8
+ export function startRunLease(project, run, settings, { api, log = () => {}, now = () => performance.now(), every = setInterval, clear = clearInterval, onDisconnect = () => {}, onReconnect = () => {} } = {}) {
4
9
  if (!run.lease_expires_at || !settings.runnerInstanceId) return { ready: Promise.resolve(), stop() {} };
5
10
  settings.stopped ??= new Set();
11
+ const fenced = Boolean(run.lease_generation);
12
+ let disconnected = false;
13
+ const offline = () => { if (!disconnected) { disconnected = true; onDisconnect(); } };
6
14
  let deadline = now() + 240_000;
7
15
  let closed = false;
8
16
  let pending = false;
17
+ let held = false;
9
18
  const lose = () => {
10
19
  if (!settings.stopped.has(run.id)) log(`[${run.id}] runner lease lost; stopping local execution`);
11
20
  settings.stopped.add(run.id);
@@ -13,23 +22,36 @@ export function startRunLease(project, run, settings, { api, log = () => {}, now
13
22
  };
14
23
  const tick = async (initial = false) => {
15
24
  if (closed) return;
16
- if (!Number.isFinite(deadline) || now() >= deadline) lose();
25
+ if (!fenced && (!Number.isFinite(deadline) || now() >= deadline)) lose();
17
26
  if (pending || settings.stopped.has(run.id)) return;
18
27
  pending = true;
19
28
  const sentAt = now();
20
29
  try {
21
- const response = await api.heartbeat({ projectIds: [project.id], runnerInstanceId: settings.runnerInstanceId, activeRunIds: [run.id] }, { env: settings.env, fetchImpl: settings.fetchImpl });
30
+ const response = await api.heartbeat({ projectIds: [project.id], runnerInstanceId: settings.runnerInstanceId, activeRunIds: [run.id], ...(fenced ? { leaseGenerations: { [run.id]: run.lease_generation } } : {}) }, { env: settings.env, fetchImpl: settings.fetchImpl });
22
31
  if (closed) return;
23
32
  for (const id of response.stops ?? []) settings.stopped.add(id);
33
+ if (response.stops?.includes(run.id)) return;
24
34
  if (response.ok && Array.isArray(response.renewedRunIds)) {
25
- if (!response.renewedRunIds.includes(run.id)) lose();
26
- else if (Number.isFinite(response.leaseDurationMs) && response.leaseDurationMs > 60_000) deadline = sentAt + response.leaseDurationMs - 60_000;
27
- } else if (initial) lose();
28
- } catch { if (initial) lose(); }
35
+ const renewed = response.renewedRunIds.includes(run.id);
36
+ const keeps = renewed || (fenced && Array.isArray(response.heldRunIds) && response.heldRunIds.includes(run.id));
37
+ if (!keeps) lose();
38
+ else {
39
+ if (disconnected) { disconnected = false; onReconnect(); log(`[${run.id}] network connection restored; local execution continued`); }
40
+ if (!renewed) {
41
+ // The server answers, so this is not an outage; no renewal will
42
+ // come, so the local timer must not call it one either.
43
+ deadline = Infinity;
44
+ if (!held) log(`[${run.id}] the server ended this lease while the computer was away; finishing here and settling under the same generation`);
45
+ held = true;
46
+ } else if (Number.isFinite(response.leaseDurationMs) && response.leaseDurationMs > 60_000) deadline = sentAt + response.leaseDurationMs - 60_000;
47
+ }
48
+ } else if (fenced && (response.transient === true || !initial)) offline();
49
+ else if (fenced || initial) lose();
50
+ } catch { if (fenced) offline(); else if (initial) lose(); }
29
51
  finally { pending = false; }
30
52
  };
31
53
  // Check expiry independently of a potentially pending network request.
32
- const expiry = every(() => { if (!closed && now() >= deadline) lose(); }, 1000);
54
+ const expiry = every(() => { if (!closed && now() >= deadline) { if (fenced) offline(); else lose(); } }, 1000);
33
55
  const renewal = every(() => { void tick(); }, 30_000);
34
56
  expiry.unref?.(); renewal.unref?.();
35
57
  const ready = tick(true);
@@ -0,0 +1,217 @@
1
+ // Beat-time ops for one folder, moved out of runner.mjs (#4668): `forget`
2
+ // (the folder leaves this machine) and the one-shot row ops a heartbeat
3
+ // hands over - merge, delete, relaunch, the person's apps and folder reads.
4
+ // `watch()`'s beat (runnerBeat.mjs) calls both every beat; `preview` is not
5
+ // here, see `serviceRowOps`'s own note.
6
+
7
+ import { serviceComputerApps, flushComputerApps } from "./computerApps.mjs";
8
+ import { serviceFolderRead } from "./folderReads.mjs";
9
+ import * as runnerApiModule from "./runnerApi.mjs";
10
+ import { folderRestoreGeneration, removeFolder, withRegistryLock } from "./registry.mjs";
11
+ import { deleteWorktree, mergeWorktree } from "./worktree.mjs";
12
+ import { relaunchServer, readWorktreeRecord } from "./devserver.mjs";
13
+
14
+ // ---------- forget: this folder leaves the machine (2026-09-12, ruling 3) ----------
15
+
16
+ /**
17
+ * Act on a `forget` op for THIS project, if this beat's heartbeat carried one.
18
+ * Returns true when it did, which tells `watch()` to stop beating: it has
19
+ * just unregistered the folder it was watching.
20
+ *
21
+ * The whole gesture is three steps and this is the middle one. A person
22
+ * clicks Remove on a row in the Project panel; the app raises `forgotten_at`
23
+ * on that `runner_projects` row, which hides it from the picker at once; the
24
+ * next heartbeat hands this daemon the op; and the row only actually goes
25
+ * once this call has acknowledged it. That ordering is what makes a forget
26
+ * survive a daemon that was asleep at the time - the signal is re-surfaced
27
+ * every beat until it is answered.
28
+ *
29
+ * IT IS NOT `opTake`n. There is no `run_ops` row to take: a forget belongs to
30
+ * a project, not to a run, and board-runner synthesises the op straight off
31
+ * the column (see supabase/functions/board-runner/store.mjs's
32
+ * `forgetSignals`). Acting and then acknowledging is the whole protocol.
33
+ *
34
+ * THE REGISTRY FIRST, THE ACK SECOND, and the order is load-bearing. Dropping
35
+ * the folder from `~/.glytch/folders.json` is what stops the NEXT beat's
36
+ * `registerAndFindProject` naming it again - register upserts on
37
+ * (user, host, path), so a row deleted while the folder is still registered
38
+ * would simply be recreated on the following beat, and the person's Remove
39
+ * would visibly undo itself. It is also what stops the watcher: multiwatch
40
+ * re-reads the registry (a 1 s stat poll, and a one-minute floor) and aborts the
41
+ * watcher of any folder that has left it.
42
+ *
43
+ * A FAILED ACK IS NOT A FAILED FORGET. The folder is already gone locally and
44
+ * the row is already invisible to the picker; the ack is what deletes the row
45
+ * for good, and an ack that did not land leaves a tombstone nobody can see.
46
+ * So it is logged and never thrown - the same posture every other beat-time
47
+ * call in this file keeps.
48
+ */
49
+ export async function serviceForgetOps(root, project, ops, settings, log = () => {}) {
50
+ const mine = (ops ?? []).find((op) => op.kind === "forget" && op.project_id === project.id);
51
+ if (!mine) return false;
52
+
53
+ const runnerApi = settings.runnerApi ?? runnerApiModule;
54
+ const env = settings.env ?? process.env;
55
+
56
+ // Capture init's local generation BEFORE the confirmation request. init may
57
+ // restore after that request reads Remove but before its response arrives.
58
+ // Read under the lock too: never capture init's new generation while its
59
+ // hosted restore is still in flight and the server still reports Remove.
60
+ const generation = await withRegistryLock(() => folderRestoreGeneration(root, env), env);
61
+ const latest = await runnerApi.heartbeat({ projectIds: [project.id] }, { env, fetchImpl: settings.fetchImpl });
62
+ if (!latest.ok) throw new Error(latest.error ?? "Could not confirm folder removal.");
63
+ if (!(latest.ops ?? []).some((op) => op.kind === "forget" && op.project_id === project.id)) return false;
64
+
65
+ return withRegistryLock(async () => {
66
+ // The compare, local removal and acknowledgement share init's restore lock:
67
+ // no restore can slip between this check and either destructive operation.
68
+ if (await folderRestoreGeneration(root, env) !== generation) return false;
69
+ const { removed } = await removeFolder(root, env);
70
+ log(
71
+ removed
72
+ ? `forget: the board asked for ${root} to be removed - dropped it from the folder registry`
73
+ : `forget: the board asked for ${root} to be removed - it was not in the folder registry`,
74
+ );
75
+
76
+ const acked = await runnerApi.forget({ projectIds: [project.id] }, { env, fetchImpl: settings.fetchImpl });
77
+ if (!acked.ok) log(`forget: could not acknowledge it to the board: ${acked.error}`);
78
+ else if ((acked.kept ?? []).length > 0) {
79
+ log(`forget: ${root}'s row is kept as a tombstone - runs still reference it - and is hidden from the picker`);
80
+ }
81
+ return true;
82
+ }, env);
83
+ }
84
+
85
+ // ---------- ops: merge, delete and relaunch, over heartbeat/opTake/opResult (item 2/5) ----------
86
+
87
+ /** Take and act on every merge/delete/relaunch op this beat's heartbeat
88
+ * surfaced. `preview` is NOT here: unlike the other three, it is not a
89
+ * one-shot op - it is a tunnel this process has to keep re-verifying and
90
+ * re-reporting on for as long as it stands, so it needs state across beats
91
+ * rather than one pass per op. `watch()`'s own beat loop owns a
92
+ * `createSharedPreviewService` instance for exactly that, feeding it this
93
+ * same untaken-ops list (`onOps`) and ticking it (`tick`) every beat
94
+ * alongside this function - see there. */
95
+ /** Write an op's result back, CHECKED and RETRIED (2026-09-20).
96
+ *
97
+ * THIS IS THE OTHER HALF OF op-mua5l39p-0bdcf7's STUCK "Deleting...": even
98
+ * once `stopsAndOps` (board-runner/store.mjs) surfaces an op and `opTake`
99
+ * claims it, the git operation's own result used to be logged
100
+ * "succeeded"/"failed" and then fired at `opResult` with the return value
101
+ * never read - so a write-back that itself failed (a token mid-refresh, a
102
+ * dropped connection) left `taken_at` set, `result` still null, the op
103
+ * genuinely done on disk but invisible to the app, and the log line claiming
104
+ * an outcome the row never recorded. The caller's own "succeeded" log line
105
+ * now waits for THIS to report the write landed, not for the git command to
106
+ * finish.
107
+ *
108
+ * THREE TRIES, SHORT BACKOFF: a board-runner call is one HTTP request against
109
+ * a function this same beat already reached (the heartbeat that surfaced the
110
+ * op just answered), so a failure here is almost always a blip worth a
111
+ * second attempt, not a standing outage worth a long wait. If every attempt
112
+ * fails, the op is left exactly where the server-side reclaim window (see
113
+ * `takeOp` in board-runner/store.mjs) expects a stuck claim to be: taken,
114
+ * unresolved, and takeable again once it goes stale - so this failing loud
115
+ * is a log line, never a throw that would leave the beat itself looking
116
+ * broken. */
117
+ async function writeOpResult(runnerApi, opId, result, rowsOpts, log, { attempts = 3, delayMs = 500 } = {}) {
118
+ let last = { ok: false, error: "never attempted" };
119
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
120
+ last = await runnerApi.opResult({ opId, result }, rowsOpts);
121
+ if (last.ok) return last;
122
+ if (attempt < attempts) {
123
+ log(`[${opId}] opResult write-back failed (attempt ${attempt}/${attempts}): ${last.error}; retrying`);
124
+ await new Promise((resolve) => setTimeout(resolve, delayMs * attempt));
125
+ }
126
+ }
127
+ log(
128
+ `[${opId}] opResult write-back did NOT land after ${attempts} attempt(s): ${last.error}. ` +
129
+ `The op stays taken with no result recorded - it becomes takeable again once the server's ` +
130
+ `reclaim window passes (see takeOp, board-runner/store.mjs).`,
131
+ );
132
+ return last;
133
+ }
134
+
135
+ export async function serviceRowOps(root, project, ops, settings, log = () => {}) {
136
+ const runnerApi = settings.runnerApi ?? runnerApiModule;
137
+ const rowsOpts = { env: settings.env, fetchImpl: settings.fetchImpl };
138
+ // OVERRIDABLE SO A TEST DOES NOT PAY FOR A REAL BACKOFF: every other
139
+ // timing knob in this file (`pollMs`, `beatMs`, `killGraceMs`, ...) already
140
+ // rides `settings`, and a write-back retry belongs beside them rather than
141
+ // being the one delay a test cannot shorten.
142
+ const retryOpts = { attempts: settings.opResultAttempts ?? 3, delayMs: settings.opResultRetryMs ?? 500 };
143
+ let ok = await flushComputerApps(root, project, runnerApi, rowsOpts);
144
+ for (const op of ops ?? []) {
145
+ if (op.kind === "computer-apps") {
146
+ ok = await serviceComputerApps(root, project, op, runnerApi, rowsOpts, settings.lookForComputerApps) && ok;
147
+ continue;
148
+ }
149
+ if (op.kind === "folder-read") {
150
+ ok = await serviceFolderRead(root, project, op, runnerApi, rowsOpts) && ok;
151
+ continue;
152
+ }
153
+ if (op.kind === "merge" || op.kind === "delete") {
154
+ const taken = await runnerApi.opTake({ opId: op.id }, rowsOpts);
155
+ if (!taken.ok) ok = false;
156
+ if (!taken.ok || !taken.op) continue; // already taken, gone, or not ours
157
+ const opWorktreePath = taken.op.payload?.worktreePath;
158
+ if (!opWorktreePath) {
159
+ ok = false;
160
+ await writeOpResult(runnerApi, op.id, { ok: false, detail: "No worktreePath on this op." }, rowsOpts, log, retryOpts);
161
+ continue;
162
+ }
163
+ log(`[${op.id}] ${op.kind} requested for ${opWorktreePath}`);
164
+ const result = op.kind === "merge"
165
+ ? await mergeWorktree(root, opWorktreePath, log)
166
+ : await deleteWorktree(root, opWorktreePath, log);
167
+ // THE CONFLICT TRAVELS WITH THE RESULT (#483): the app reads `conflict`
168
+ // and `files` and sends Coding back to fit its changes around the
169
+ // person's. No question is filed here any more: Coding starts the fix,
170
+ // not the person, so a failed Keep is never a "Retry merge?" ask.
171
+ const written = await writeOpResult(
172
+ runnerApi,
173
+ op.id,
174
+ {
175
+ ok: result.ok,
176
+ detail: result.detail,
177
+ ...(result.conflict ? { conflict: true, files: result.files ?? [] } : {}),
178
+ ...(result.ok && typeof result.files === "number" ? { files: result.files } : {}),
179
+ },
180
+ rowsOpts,
181
+ log,
182
+ retryOpts,
183
+ );
184
+ if (!result.ok || !written.ok) ok = false;
185
+ if (written.ok) log(`[${op.id}] ${op.kind} ${result.ok ? "succeeded" : "failed"}: ${result.detail}`);
186
+ continue;
187
+ }
188
+ if (op.kind === "relaunch") {
189
+ const taken = await runnerApi.opTake({ opId: op.id }, rowsOpts);
190
+ if (!taken.ok) ok = false;
191
+ if (!taken.ok || !taken.op) continue;
192
+ // THE RECORD: the owning run's own `server` column (mirrored there by
193
+ // `runnerCompletion.mjs` when the child exits), or the hinted
194
+ // worktree's own live `.glytch-server.json` file when the row has
195
+ // none yet - the row equivalent of the file version's
196
+ // `<id>.server`-then-`.glytch-server.json` fallback chain.
197
+ const listed = await runnerApi.runs({ projectIds: [project.id] }, rowsOpts);
198
+ if (!listed.ok) ok = false;
199
+ const owner = listed.ok ? listed.runs?.find((r) => r.id === op.run_id) : null;
200
+ const hinted = taken.op.payload?.worktreePath;
201
+ const record = owner?.server ?? (hinted ? await readWorktreeRecord(hinted) : null);
202
+ const outcome = await relaunchServer(record, { root });
203
+ const written = await writeOpResult(runnerApi, op.id, { ok: outcome.ok, detail: outcome.detail }, rowsOpts, log, retryOpts);
204
+ if (!outcome.ok || !written.ok) ok = false;
205
+ if (written.ok) log(`[${op.id}] relaunch ${outcome.ok ? "ok" : "refused"}: ${outcome.detail}`);
206
+ // THE FRESH RECORD LANDS ON THE RUN ROW, the row equivalent of the
207
+ // file version's second write to `<id>.server` - a later relaunch (or
208
+ // lib/serverSweep.mjs) reads the SAME copy this one just wrote.
209
+ if (outcome.ok && outcome.record && owner) {
210
+ const updated = await runnerApi.update({ runId: owner.id, patch: { server: outcome.record } }, rowsOpts);
211
+ if (!updated.ok) ok = false;
212
+ }
213
+ }
214
+ }
215
+ if (!ok) log("Operation results remain pending; retained Look answers will retry on heartbeat.");
216
+ return { ok };
217
+ }