viewable-one 0.12.2 → 0.12.4

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 (61) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +2 -2
  3. package/SPAWN.md +107 -53
  4. package/glytch.mjs +49 -12
  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 +80 -45
  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 +52 -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 +33 -12
  42. package/lib/runnerApi.mjs +28 -12
  43. package/lib/runnerBeat.mjs +398 -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 +226 -0
  50. package/lib/runnerPace.mjs +10 -6
  51. package/lib/runnerRecovery.mjs +457 -0
  52. package/lib/runnerRegister.mjs +29 -8
  53. package/lib/runnerSettlement.mjs +29 -9
  54. package/lib/selfUninstall.mjs +239 -0
  55. package/lib/spawn.mjs +0 -5
  56. package/lib/sync.mjs +26 -14
  57. package/lib/update.mjs +184 -0
  58. package/lib/viewableFolder.mjs +8 -2
  59. package/lib/worktree.mjs +66 -13
  60. package/lib/writePolicy.mjs +90 -10
  61. package/package.json +1 -1
@@ -0,0 +1,227 @@
1
+ // One claimed run, as named steps (#4668; this was one 660-line function in
2
+ // runner.mjs). `runRequest` (runner.mjs) owns the claim's lease, the
3
+ // preparation clock and the terminal receipt on a throw; `executeRequest`
4
+ // reads as the steps a run goes through, in this order and no other:
5
+ //
6
+ // admitRequest (runnerGates.mjs) - every refusal, before anything is made
7
+ // prepareRun - the hosted board, the worktree
8
+ // startRun (runnerLaunch.mjs) - spawn, retry, check, complete
9
+ //
10
+ // `finish` is the one way a step ends the run: it closes preparation and
11
+ // settles the receipt (runnerSettlement.mjs) unless the lease was lost.
12
+
13
+ import { probeClaudeEffort } from "./detect.mjs";
14
+ import * as runnerApiModule from "./runnerApi.mjs";
15
+ import { callTool as hostedCallToolDefault } from "./hosted.mjs";
16
+ import { runnerMcpUrlFrom } from "./mcpjson.mjs";
17
+ import { hostedConfig, hostedToken } from "./auth.mjs";
18
+ import { computerAppsOffRule, otherAppsRule } from "./conversationRules.mjs";
19
+ import { acceptsMessages, agentFor, commandFor, isPersistentRequest, preambleFor } from "./agents.mjs";
20
+ import { getRepoMap, formatRepoPrimer } from "./repomap.mjs";
21
+ import { buildAttemptsSectionFromRows } from "./compose.mjs";
22
+ import { imageInspectionInstruction } from "./imageAttachments.mjs";
23
+ import { isChatTurn, titleFor, wallClockFor } from "./spawn.mjs";
24
+ import { settleMeasuredRun } from "./runnerSettlement.mjs";
25
+ import { IN_PLACE_WORKPLACE, prepareRequestWorkspace } from "./runnerWorkspace.mjs";
26
+ import { admitRequest } from "./runnerGates.mjs";
27
+ import { startRun } from "./runnerLaunch.mjs";
28
+
29
+ /** THE session key, minted in exactly one place - unchanged reasoning from
30
+ * the file-based runner: a run's own row id IS the key `report()`'s
31
+ * `PM_SESSION_KEY` and `X-Glytch-Session` both use. */
32
+ export const sessionKeyFor = (runId) => String(runId);
33
+
34
+ export async function executeRequest(project, run, settings, log, timing, receipt, preparation) {
35
+
36
+ const root = project.path;
37
+ const id = run.id;
38
+ const request = run.request ?? {};
39
+ const runnerApi = settings.runnerApi ?? runnerApiModule;
40
+ const hostedEnv = settings.env ?? process.env;
41
+ const rowsOpts = { env: hostedEnv, fetchImpl: settings.fetchImpl };
42
+ const session = { key: run.session_key ?? sessionKeyFor(id), title: titleFor(request), requestId: id };
43
+ // CLAIMED, LOGGED (2026-09-21, the claim-to-spawn gap). `runRequest` runs
44
+ // immediately after `claimOne` hands back a claimed row, in both `watch`'s
45
+ // loop and `pollOnce` - so this is the earliest point in this file that
46
+ // can say a run was claimed at all, and `claimedAt` below is what the
47
+ // "spawning" line's elapsed-time note (`prepareRequestWorkspace`) is
48
+ // measured against. Before this, everything between the network claim and
49
+ // the first line `prepareRequestWorkspace` logs was silent - a run seen
50
+ // claimed at 11:35:57 and "spawning" only at 11:37:00, nothing between.
51
+ const claimedAt = Date.now();
52
+ log(`[${id}] claimed: agent ${request.agent ?? "claude"}, project ${root}`);
53
+ // THE RUN'S OWN BOARD (2026-09-21, board reporting fix). `run` is the row
54
+ // `claim` handed back (board-runner/store.mjs's `claimOldest`, `select("*")`
55
+ // on `runs`), which already carries `board_id` - src/runs/api.ts's
56
+ // RunRequestRow is what wrote it. Sent on to the spawned agent's MCP server
57
+ // config as `X-Glytch-Board`, next to `X-Glytch-Session`, so board-mcp's
58
+ // `report` (and every other board_id-less tool) lands on THIS board
59
+ // instead of guessing the account's most recently touched one
60
+ // (board-mcp/tools.mjs's `boardFor`). Absent on an older row or a chat
61
+ // turn with none recorded - `commandFor`/`prepareWorkspace`/`codexBoardArgs`
62
+ // all treat an empty string the same as "no header", today's behaviour.
63
+ const boardId = typeof run.board_id === "string" ? run.board_id : "";
64
+
65
+ const finish = (patch) => {
66
+ preparation.complete();
67
+ // Completion rebuilds the sidecar (including removal of a deleted copy).
68
+ // Retain the capability marker without restoring stale workspace fields.
69
+ if (receipt.sidecar.restartable === true && patch.sidecar) {
70
+ patch = { ...patch, sidecar: { ...patch.sidecar, restartable: true } };
71
+ }
72
+ patch = { ...patch, sidecar: { ...(patch.sidecar ?? receipt.sidecar), ...(receipt.sidecar.networkInterrupted ? { networkInterrupted: true } : {}), ...(receipt.sidecar.recoveryCause ? { recoveryCause: receipt.sidecar.recoveryCause } : {}) } };
73
+ return settings.leaseLost?.has(id)
74
+ ? { id, state: "waiting" }
75
+ : settleMeasuredRun(project, id, patch, settings, log, timing, receipt);
76
+ };
77
+
78
+ // A CHAT TURN IS A DIFFERENT KIND OF REQUEST (brief 25, ported onto rows
79
+ // brief 30 Move 2b, 2026-09-11). Absent `kind` means "session", so
80
+ // everything below this line that is not explicitly guarded by `isChat` is
81
+ // what it has always been. The five differences, and no others, are
82
+ // marked `chat turn:` where they happen; bridge/SPAWN.md, "Chat turns", is
83
+ // the contract - only the DOOR each one reaches through changed (a run row
84
+ // and its `runnerApi` calls, not a signal file).
85
+ const isChat = isChatTurn(request);
86
+
87
+ const ctx = { eventSeq: run.event_seq, project, root, id, request, isChat, runnerApi, hostedEnv, rowsOpts, session, claimedAt, boardId, settings, log };
88
+ const admitted = await admitRequest(ctx, preparation);
89
+ if ("patch" in admitted) return finish(admitted.patch);
90
+ const prepared = await prepareRun(ctx, admitted, receipt, preparation);
91
+ if ("patch" in prepared) return finish(prepared.patch);
92
+ const state = { ...admitted, ...prepared };
93
+ state.planRun = makePlanRun(ctx, state);
94
+ return startRun(ctx, state, { timing, receipt, preparation, finish });
95
+ }
96
+
97
+ /** The hosted board this run reports to, and the worktree it runs in. `{
98
+ * patch }` when the workspace refused; otherwise what `startRun` needs. */
99
+ async function prepareRun({ project, root, id, request, isChat, runnerApi, hostedEnv, rowsOpts, session, claimedAt, settings, log }, { chatCwd, isResume, from, ownTreePath }, receipt, preparation) {
100
+ const hostedBoard = await hostedConfig({ env: hostedEnv });
101
+ const childMcpUrl = runnerMcpUrlFrom(hostedBoard, hostedEnv, (message) => log(`[${id}] ${message}`));
102
+ // The runner's permission checks and collect_session (including the final
103
+ // sweep) use the same direct endpoint as its child. Keep the hosted
104
+ // transport's refresh/deadline/cancellation logic; only reroute MCP posts,
105
+ // never OAuth discovery or refresh requests made through the same fetch.
106
+ const hostedCallTool = settings.hostedCallTool ?? ((name, args, options) => hostedCallToolDefault(name, args, {
107
+ ...options,
108
+ mcpUrl: childMcpUrl, fetchImpl: settings.fetchImpl,
109
+ }));
110
+ const boardToken = await hostedToken({ env: hostedEnv, fetchImpl: settings.fetchImpl, log });
111
+ preparation.check();
112
+ if (!boardToken) {
113
+ log(`[${id}] not signed in to the hosted board (viewable login) and no VIEWABLE_BOARD_TOKEN - this session's board tools will have nothing to authenticate with`);
114
+ }
115
+ const isPersistent = isPersistentRequest(request);
116
+ const useStreaming = request.planMode !== "draft" && acceptsMessages(request);
117
+ const maxMs = wallClockFor(request);
118
+ const otherRunningCount = async () => {
119
+ const listed = await runnerApi.runs({ projectIds: [project.id], status: "running" }, rowsOpts);
120
+ if (!listed.ok) throw new Error(`Cannot verify competing runs: ${listed.error}`);
121
+ return (listed.runs ?? []).filter((r) => r.id !== id).length;
122
+ };
123
+ const retainSidecar = (sidecar) => {
124
+ receipt.sidecar = { ...receipt.sidecar, ...sidecar };
125
+ if (agentFor(request.agent) === "claude") {
126
+ receipt.sidecar.claudeSessionId = request.resumeSessionId ?? request.sessionId;
127
+ receipt.sidecar.restartable = true;
128
+ }
129
+ };
130
+ const workspace = await prepareRequestWorkspace({
131
+ root, id, request, isResume, session, from, log, isChat, chatCwd, claimedAt, ownTreePath,
132
+ otherRunningCount, preparation, retainSidecar,
133
+ updateSidecarEarly: (sidecar) => {
134
+ preparation.check();
135
+ retainSidecar(sidecar);
136
+ // A sidecar write already on the wire must finish before the terminal
137
+ // receipt is published, so an older JSON patch cannot overtake it.
138
+ return preparation.own(() => runnerApi.update({ runId: id, patch: { sidecar: receipt.sidecar } }, rowsOpts));
139
+ },
140
+ });
141
+ preparation.check();
142
+ if (!workspace.ok) return { patch: workspace.patch };
143
+ const { made, resumeTreeGone, resumeSessionId } = workspace;
144
+ receipt.sidecar.recoveryCwd = made.cwd;
145
+ // Keep isolated worktree paths in their existing field; cwd recovery is only
146
+ // for in-place and chat work. This never offers Keep/Delete on the source.
147
+ if (made.isolated) delete receipt.sidecar.recoveryCwd;
148
+ receipt.sidecar.resumeSessionId = resumeSessionId || request.sessionId;
149
+ if (request.recovery === true && request.resumeSessionId) settings.recoveryTracker?.launching({ preparedResume: true });
150
+ settings.recoveryTracker?.persist();
151
+ if (resumeTreeGone) {
152
+ log(`[${id}] the recorded worktree ${request.worktreePath} is gone; starting a FRESH session instead of resuming ${String(request.resumeSessionId).trim()}`);
153
+ }
154
+ return { hostedCallTool, childMcpUrl, boardToken, isPersistent, useStreaming, maxMs, made, resumeTreeGone, resumeSessionId };
155
+ }
156
+
157
+ /** The prompt, the command and its arguments for one try of this run: the
158
+ * first, a fresh retry when the resume was not found, or the one fix. */
159
+ function makePlanRun({ project, root, id, request, isChat, runnerApi, hostedEnv, session, boardId, settings, log }, { referenceImages, from, agent, resolvedBinPath, made, useStreaming, boardToken, childMcpUrl }) {
160
+ return async ({ resumeId, note, fixing = false }) => {
161
+ const fresh = resumeId === "";
162
+ // chat turn, difference 3: NEITHER, EVER. Both the primer and the
163
+ // attempts log exist to save a FRESH session from rediscovering what an
164
+ // earlier one already learned; a chat turn is either the first message
165
+ // of a conversation or a resume of one, and there is no idea
166
+ // behind it to have attempted anything.
167
+ const repoMap = fresh && !isChat ? await getRepoMap(root, log) : null;
168
+ const attemptsSection = fresh && !isChat && from
169
+ ? await buildAttemptsSectionFromRows(project.id, from, id, { runnerApi, env: hostedEnv, log })
170
+ : null;
171
+ const repoPrimer = formatRepoPrimer(repoMap, attemptsSection ? attemptsSection.length : 0);
172
+ // chat turn, difference 1: NO IDEA PREAMBLE. The app composes the persona,
173
+ // room context and message; instructions such as "call report before you
174
+ // finish" do not belong in chat. Only the other-apps rule and, when
175
+ // needed, the apps-off rule are added for Claude Code and Codex, so the reply can offer Manage agent.
176
+ let text = request.planMode === "draft"
177
+ ? `Investigate the request using read-only research, then return an actionable implementation plan in your final response. Structure the response as a report: keep resolved or contextual findings in their own sections; put actionable work under a \`## Implementation plan\` heading with one \`### Step N: ...\` or \`### Issue X: ...\` heading per top-level item; put numbered substeps under a \`**Steps:**\` label; and label checks and open decisions clearly. Do not implement anything, use tools to modify files, or ask for permission to implement. The human will edit and approve or reject your final plan on the board.\n\n${String(request.prompt)}`
178
+ : `${isChat ? "" : preambleFor(agent, { ...(made.isolated ? {} : { workplace: IN_PLACE_WORKPLACE }), computerApps: request.computerApps === true })}${String(request.prompt)}`;
179
+ if (isChat && request.planMode !== "draft" && ["claude", "codex"].includes(agent)) {
180
+ text = `${otherAppsRule()}${request.computerApps === true ? "" : computerAppsOffRule()}${text}`;
181
+ }
182
+ if (request.planMode === "execute") text += `\n\nHUMAN-APPROVED IMPLEMENTATION PLAN\nFollow this exact plan, including the human's edits. Ask the human about any material scope change before implementing it.\n\n${request.approvedPlan}`;
183
+ if (note) text = `${text}\n\n${note}`;
184
+ if (repoPrimer) text = `${text}\n\n${repoPrimer}`;
185
+ if (attemptsSection) text = `${text}\n\n${attemptsSection}`;
186
+ if (referenceImages.length > 0) {
187
+ text = `${imageInspectionInstruction(referenceImages.length, request.planMode).trim()}\n\n${text}`;
188
+ }
189
+ const claudeEfforts = agent === "claude" && request.effort
190
+ ? (await probeClaudeEffort(settings.claudeBin ?? resolvedBinPath ?? "claude", { env: settings.env ?? process.env }))[request.model] ?? []
191
+ : [];
192
+ const resolved = commandFor(agent, settings.env ?? process.env, {
193
+ planMode: request.planMode,
194
+ model: request.model,
195
+ effort: request.effort,
196
+ claudeEfforts: Array.isArray(claudeEfforts) ? claudeEfforts : [],
197
+ sessionId: fixing ? undefined : request.sessionId,
198
+ resumeSessionId: resumeId,
199
+ streaming: useStreaming,
200
+ // ASK IN THE IDEA (#478): with a board to ask on, anything outside the
201
+ // usual list becomes a question in the idea instead of a silent refusal.
202
+ // Drafts are read-only; commandFor drops the ask for them.
203
+ askPermissions: Boolean(boardToken),
204
+ webSearch: request.webSearch === true,
205
+ boardUrl: childMcpUrl,
206
+ boardToken,
207
+ sessionKey: session.key,
208
+ boardId,
209
+ // The person's own apps (#481): only an explicit true from the app,
210
+ // which sends it when this person turned the switch on for this agent.
211
+ computerApps: request.computerApps === true,
212
+ });
213
+ const chosen = settings.claudeBin !== undefined
214
+ ? { ...resolved, bin: settings.claudeBin, args: request.planMode === "draft" ? resolved.args : settings.claudeArgs ?? resolved.args }
215
+ // THE RESOLVED PATH, NOT THE BARE NAME: the check above already found
216
+ // where this binary actually runs FROM - `spec.bin` unchanged when it
217
+ // was already on this process's own PATH, an absolute path when it
218
+ // took a known install directory or a login shell to find. Handing
219
+ // `spawn` the resolved path means it never repeats a PATH search this
220
+ // process's own (possibly narrower) PATH would have failed anyway.
221
+ : { ...resolved, bin: resolvedBinPath ?? resolved.bin };
222
+ for (const what of chosen.ignored ?? []) log(`[${id}] ignoring ${what}`);
223
+ // `brief` is what the person typed, on its own - the adapters echo it
224
+ // into the transcript instead of the preamble-wrapped `prompt`.
225
+ return { prompt: text, brief: String(request.prompt), chosen, args: chosen.args.map((a) => a.replaceAll("{prompt}", () => text)) };
226
+ };
227
+ }
@@ -0,0 +1,338 @@
1
+ // What can refuse a claimed run before anything is spawned, moved out of
2
+ // runner.mjs (#4668): the per-prompt and per-room locks over rows, and
3
+ // `admitRequest`, every check `executeRequest` used to make inline before
4
+ // it touched a worktree. A refusal comes back as `{ patch }`, the terminal
5
+ // receipt the caller settles; every refusal says nothing was spawned or
6
+ // billed, in words a person reads in the run's result.
7
+
8
+ import { access, stat } from "node:fs/promises";
9
+ import { realpathSync } from "node:fs";
10
+ import { resolve } from "node:path";
11
+ import * as runnerApiModule from "./runnerApi.mjs";
12
+ import { AGENTS, agentFor, isCodingCli } from "./agents.mjs";
13
+ import { resolveAgentBinary } from "./detect.mjs";
14
+ import { imageAttachments } from "./imageAttachments.mjs";
15
+ import { checkRequest, isChatTurn, isSignIn, titleFor } from "./spawn.mjs";
16
+ import { codexLogin } from "./signIn.mjs";
17
+ import { fromIdOf } from "./boardside.mjs";
18
+ import { chatBoardOf, makeBoardCwd } from "./viewableFolder.mjs";
19
+ import { defaultBranchOf, git, makeChatWorktree, resolveChatCwd, worktreeBranch, worktreePath, worktreeSummary } from "./worktree.mjs";
20
+
21
+ // ---------- the per-prompt lock, over rows ----------
22
+
23
+ const exists = async (path) => {
24
+ try {
25
+ await access(path);
26
+ return true;
27
+ } catch {
28
+ return false;
29
+ }
30
+ };
31
+
32
+ /** Is an unmerged worktree already serving this prompt? Admission reads
33
+ * this project's run rows, then checks the expected worktree path and the
34
+ * branch's relationship to main before treating that run as a lock. */
35
+ /** ONE PATH, WHATEVER SPELLING (round 3 item 69): Windows hands a temp dir
36
+ * out as an 8.3 short name and the app may send the long one, so the
37
+ * worktree comparisons below resolve both sides first. */
38
+ export function samePath(a, b) {
39
+ const norm = (p) => { try { return realpathSync.native(p); } catch { return resolve(p); } };
40
+ return typeof a === "string" && typeof b === "string" && a !== "" && b !== "" && norm(a) === norm(b);
41
+ }
42
+
43
+ /** Besides the lock, `trees` lists every existing worktree a run of this
44
+ * prompt made, held or not (an empty error tree, a merged one): a request
45
+ * may reuse one of ITS OWN trees only (round 3 item 67). */
46
+ export async function activeWorktreeForPromptRows(root, projectId, promptNodeId, settings, log = () => {}) {
47
+ const trees = [];
48
+ if (!promptNodeId) return { locked: false, trees };
49
+ const runnerApi = settings.runnerApi ?? runnerApiModule;
50
+ const listed = await runnerApi.runs({ projectIds: [projectId] }, { env: settings.env, fetchImpl: settings.fetchImpl });
51
+ if (!listed.ok) throw new Error(`Cannot verify prompt ownership: ${listed.error}`);
52
+ for (const run of listed.runs ?? []) {
53
+ if (fromIdOf(run.request) !== promptNodeId) continue;
54
+ const title = titleFor(run.request);
55
+ const expectedPath = worktreePath(root, run.id, title);
56
+ if (!(await exists(expectedPath))) continue;
57
+ trees.push(expectedPath);
58
+ const branch = worktreeBranch(run.id, title);
59
+ const resolved = await git(["rev-parse", "--verify", branch], root);
60
+ if (!resolved.ok) continue;
61
+ // A RUN THAT NEVER GOT PAST "COULD NOT START" HAS NOTHING TO LOSE
62
+ // (2026-09-20). `runnerCompletion.mjs` removes a spawn-failed run's
63
+ // worktree outright; this guard is the backstop for a row written before
64
+ // that fix, or a removal that failed: an ERROR run whose tree carries
65
+ // zero commits and zero changed files must not hold the NEXT request on
66
+ // this prompt hostage (spawn-mua51lhf-96f76b, "spawn claude ENOENT",
67
+ // kept a "0 commits, 0 files touched" tree and the follow-up was refused).
68
+ //
69
+ // 0/0 IS NOT "EMPTY" BY ITSELF (2026-09-21, review): `worktreeSummary`
70
+ // counts uncommitted edits too (#482), but a git read that failed also
71
+ // reads as 0, so the same porcelain check `cleanWorktreeImpl` runs
72
+ // decides before the lock goes; a porcelain check that fails to run is
73
+ // not evidence the tree is empty.
74
+ if (run.status === "error") {
75
+ const summary = await worktreeSummary(expectedPath, root).catch(() => null);
76
+ if (summary && summary.commits === 0 && summary.files === 0) {
77
+ const dirty = await git(["status", "--porcelain"], expectedPath);
78
+ const clean = dirty.ok && dirty.stdout.trim() === "";
79
+ if (clean) continue;
80
+ }
81
+ }
82
+ // SAME HELPER worktree.mjs's base-selection and merge op use
83
+ // (defaultBranchOf, 2026-09-21): a master-only repo asks about master.
84
+ const mainBranch = (await defaultBranchOf(root)) ?? "main";
85
+ const branchInMain = await git(["merge-base", "--is-ancestor", branch, mainBranch], root);
86
+ const mainInBranch = await git(["merge-base", "--is-ancestor", mainBranch, branch], root);
87
+ if (branchInMain.ok && !mainInBranch.ok) continue; // merged into the default branch
88
+ log(`[lock] prompt ${promptNodeId} is held by worktree ${expectedPath} on branch ${branch}`);
89
+ return { locked: true, worktreePath: expectedPath, branch, requestId: run.id, trees };
90
+ }
91
+ return { locked: false, trees };
92
+ }
93
+
94
+ /** ROWS VERSION of the file-based `activeChatTurnForRoom` (`spawn.mjs`,
95
+ * retired brief 30 Move 2b): is a chat turn already live in this room, on
96
+ * this project? Same question (one live turn per room, because two would
97
+ * otherwise resume the same Claude Code conversation in the same directory
98
+ * at once), `runnerApi.runs({..., status:'running'})` in place of scanning
99
+ * `runningRequests` for an unreceipted claim. `exceptId` is the caller's own
100
+ * run, which has usually just claimed itself. */
101
+ export async function activeChatTurnForRoomRows(projectId, roomId, exceptId, settings) {
102
+ const wanted = typeof roomId === "string" ? roomId.trim() : "";
103
+ if (wanted === "") return null;
104
+ const runnerApi = settings.runnerApi ?? runnerApiModule;
105
+ const listed = await runnerApi.runs({ projectIds: [projectId], status: "running" }, { env: settings.env, fetchImpl: settings.fetchImpl });
106
+ if (!listed.ok) throw new Error(`Cannot verify active chat turns: ${listed.error}`);
107
+ for (const run of listed.runs ?? []) {
108
+ if (run.id === exceptId) continue;
109
+ if (!isChatTurn(run.request)) continue;
110
+ const its = typeof run.request?.roomId === "string" ? run.request.roomId.trim() : "";
111
+ if (its === wanted) return { requestId: run.id, roomId: wanted };
112
+ }
113
+ return null;
114
+ }
115
+
116
+ // ---------- before anything is spawned: the refusals ----------
117
+
118
+ /** Every check that can refuse `run` before a worktree is minted, in the
119
+ * order `executeRequest` always made them. `{ patch }` is a refusal (or the
120
+ * sign-in's own receipt); otherwise what the later steps need. */
121
+ export async function admitRequest({ project, root, id, request, isChat, runnerApi, rowsOpts, settings, log }, preparation) {
122
+ const problems = checkRequest(request);
123
+ if (problems.length > 0) {
124
+ return { patch: { status: "error", result: `ERROR\n\nRefused: ${problems.join("\n")}\n`, finished_at: new Date().toISOString() } };
125
+ }
126
+
127
+ // SIGN IN TO CODEX (#482, lib/signIn.mjs): `codex login` opens the sign-in
128
+ // page in this computer's browser. Then the agents are probed again, so the
129
+ // app's sign-in box goes as soon as Codex says it is signed in rather than
130
+ // on the probe's own five-minute clock.
131
+ if (isSignIn(request)) {
132
+ log(`[${id}] signing in to ${request.agent}`);
133
+ const signedIn = await (settings.codexLogin ?? codexLogin)({ env: settings.baseEnv ?? process.env });
134
+ await settings.refreshAgents?.();
135
+ return { patch: { status: signedIn.ok ? "done" : "error", result: `${signedIn.ok ? "OK" : "ERROR"}\n\n${signedIn.detail}\n`, finished_at: new Date().toISOString() } };
136
+ }
137
+
138
+ // A PROJECT FOLDER THAT IS GONE (brief 52 round 1, item 17): one fixed
139
+ // sentence the app matches for its Pick a folder chip (sessionReplies.ts
140
+ // FOLDER_GONE); otherwise the spawn fails in a folder that is not there
141
+ // and the person reads "not installed", the wrong cause.
142
+ if (!isChat && !(await stat(root).then((s) => s.isDirectory(), () => false))) {
143
+ log(`[${id}] refused: the project folder ${root} is not on this computer`);
144
+ return { patch: { status: "error", result: `ERROR\n\nNOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\nThe project folder is not on this computer.\n${root}\n`, finished_at: new Date().toISOString() } };
145
+ }
146
+
147
+ let referenceImages;
148
+ try {
149
+ referenceImages = imageAttachments(request.images);
150
+ } catch (error) {
151
+ return { patch: { status: "error", result: `ERROR\n\nNOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n${error.message}\n`, finished_at: new Date().toISOString() } };
152
+ }
153
+
154
+ if (request.planMode === "execute") {
155
+ // ONE LIST QUERY covers both checks below: the matching draft (contract
156
+ // point 3/5) and single-use consumption (point 4), so a request already
157
+ // seeded with everything runs() returns pays for one round trip rather
158
+ // than two.
159
+ const projectRuns = (await runnerApi.runs({ projectIds: [project.id] }, rowsOpts).catch(() => null))?.runs ?? [];
160
+ const source = projectRuns.find((r) => r.id === request.approvedPlanFrom);
161
+ // ENGINE IS PART OF THE BOUND SCOPE (contract point 3/5): absent means
162
+ // "claude" on both sides, the same default agentFor and checkRequest
163
+ // already use, so a draft and an execute that both left `agent` unset
164
+ // still match.
165
+ const sourceAgent = source?.request?.agent ?? "claude";
166
+ const requestAgent = request.agent ?? "claude";
167
+ const samePrompt = source?.request?.planMode === "draft" &&
168
+ sourceAgent === requestAgent &&
169
+ fromIdOf(source.request) === fromIdOf(request);
170
+ if (!samePrompt || source?.status !== "done") {
171
+ return { patch: { status: "error", result: "ERROR\n\nRefused: implementation requires a successful draft run for this same prompt and the same engine.\n", finished_at: new Date().toISOString() } };
172
+ }
173
+ // SINGLE-USE (contract point 4). The draft's approval is bound to AT
174
+ // MOST ONE implementation, ever - a duplicate click, a copied execute
175
+ // request, or a fresh run row spelling the same `approvedPlanFrom` must
176
+ // all lose to whichever execute run against this draft already got this
177
+ // far. There is no exclusive-create over rows the way
178
+ // `<id>.plan-consumed` was on disk (brief 30 Move 2 retired the file
179
+ // contract this bound to), so this is a scan for an earlier claimed row
180
+ // rather than a race-proof claim of its own - the same trade-off
181
+ // `activeChatTurnForRoomRows` above already accepts for its per-room
182
+ // lock, and for the same reason: the window between the scan and this
183
+ // run's own claim is a process's worth of code, not a poll interval.
184
+ const already = projectRuns.find((r) => {
185
+ // Continued/recovered segments carry on the same approved implementation.
186
+ // `continues` keeps its root session key across resumes; derived run ids
187
+ // also identify ancestors when an older request lacks that chain key.
188
+ const sameChain = (typeof request.continues === "string" && request.continues.length > 0 &&
189
+ (request.continues === r.id || request.continues === r.session_key || request.continues === r.request?.continues)) ||
190
+ id.startsWith(`${r.id}-r`);
191
+ return r.id !== id && !sameChain && r.request?.planMode === "execute" &&
192
+ r.request?.approvedPlanFrom === request.approvedPlanFrom &&
193
+ (r.claimed_by != null || r.status !== "pending");
194
+ });
195
+ if (already) {
196
+ return { patch: { status: "error", result: "ERROR\n\nRefused: this approved plan has already started an implementation. Draft and approve a new plan to try again.\n", finished_at: new Date().toISOString() } };
197
+ }
198
+ }
199
+
200
+ // ---------- chat turn: the things only the disk (or the room) can answer ----------
201
+ // checkRequest (pure) has said `cwd` and `roomId` are there. Each check
202
+ // here refuses in words a person reads in the run's result, never throws.
203
+ let chatCwd = null;
204
+ if (isChat) {
205
+ // WHERE IT RUNS: refused if it escapes the folder (Write, Edit and Bash).
206
+ const resolvedCwd = resolveChatCwd(root, request.cwd);
207
+ if (!resolvedCwd.ok) {
208
+ const detail =
209
+ `NOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n` +
210
+ `This chat turn names ${String(request.cwd ?? "").trim()} as the directory to ` +
211
+ `run in, and ${resolvedCwd.reason}`;
212
+ log(`[${id}] refused: the chat turn's cwd ${String(request.cwd ?? "").trim()} is outside ${root}`);
213
+ return { patch: { status: "error", result: `ERROR\n\n${detail}\n`, finished_at: new Date().toISOString() } };
214
+ }
215
+ // A BOARD'S SUBFOLDER (viewableFolder.mjs) is made inside the chat tree.
216
+ const board = request.boardFolder === undefined ? null : chatBoardOf(root, resolvedCwd.path, request.boardFolder);
217
+ chatCwd = board?.tree ?? resolvedCwd.path;
218
+ // THE DIRECTORY IS THE CONVERSATION (brief 25 difference 2): no worktree
219
+ // PER MESSAGE and no fallback to the linked checkout. `mintIfMissing`
220
+ // (ruling 1) cuts the folder's one long-lived chat worktree, once.
221
+ let isDir = false;
222
+ try { isDir = (await stat(chatCwd)).isDirectory(); } catch { isDir = false; }
223
+ if (!isDir && request.mintIfMissing === true) {
224
+ const minted = await makeChatWorktree(root, chatCwd, log, preparation);
225
+ preparation.check();
226
+ if (!minted.ok) {
227
+ const detail = `NOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n${minted.reason}`;
228
+ log(`[${id}] refused: the chat worktree ${chatCwd} could not be made`);
229
+ return { patch: { status: "error", result: `ERROR\n\n${detail}\n`, finished_at: new Date().toISOString() } };
230
+ }
231
+ log(`[${id}] ${minted.detail}`);
232
+ isDir = true;
233
+ }
234
+ if (!isDir) {
235
+ const detail =
236
+ `NOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n` +
237
+ `This chat turn names ${chatCwd} as the directory to run in, and there is no ` +
238
+ `directory there. A chat turn never mints a worktree: the directory IS which ` +
239
+ `conversation this is, and falling back to the linked folder would put a chat agent ` +
240
+ `in the checkout you are working in.\n\n` +
241
+ `Make the directory (the chat worktree for this agent) and send the message again.`;
242
+ log(`[${id}] refused: the chat turn's cwd ${chatCwd} is not a directory`);
243
+ return { patch: { status: "error", result: `ERROR\n\n${detail}\n`, finished_at: new Date().toISOString() } };
244
+ }
245
+ if (board) {
246
+ const sub = await preparation.own(() => makeBoardCwd(root, chatCwd, board.name));
247
+ preparation.check();
248
+ if (!sub.ok) {
249
+ log(`[${id}] refused: ${sub.reason}`);
250
+ return { patch: { status: "error", result: `ERROR\n\nNOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n${sub.reason}\n`, finished_at: new Date().toISOString() } };
251
+ }
252
+ chatCwd = sub.path;
253
+ }
254
+ // AND THE ENGINE HAS TO BE A CODING CLI THIS BRIDGE RUNS (agents.mjs).
255
+ if (request.agent !== undefined && !isCodingCli(request.agent)) {
256
+ const detail =
257
+ `NOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n` +
258
+ `This chat turn names the engine "${request.agent}", and this bridge has no such ` +
259
+ `coding CLI. Answering on another engine would tell you that you are talking to ` +
260
+ `"${request.agent}" when you are not.`;
261
+ log(`[${id}] refused: "${request.agent}" is not a coding CLI this bridge runs`);
262
+ return { patch: { status: "error", result: `ERROR\n\n${detail}\n`, finished_at: new Date().toISOString() } };
263
+ }
264
+ // difference 4: THE PER-ROOM LOCK, not the per-prompt one below.
265
+ const roomId = String(request.roomId).trim();
266
+ const live = await activeChatTurnForRoomRows(project.id, roomId, id, settings);
267
+ if (live) {
268
+ const detail =
269
+ `NOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n` +
270
+ `A chat turn is already running in room ${roomId} (run ${live.requestId}). ` +
271
+ `One live turn per room: both would resume the same Claude Code conversation in the ` +
272
+ `same directory at the same time, and a conversation is one thread.\n\n` +
273
+ `Wait for that turn to finish, or stop it, then send this message again.`;
274
+ log(`[${id}] refused: room ${roomId} already has a live turn (${live.requestId})`);
275
+ return { patch: { status: "error", result: `ERROR\n\n${detail}\n`, finished_at: new Date().toISOString() } };
276
+ }
277
+ }
278
+
279
+ const isResume = typeof request.resumeSessionId === "string" && request.resumeSessionId.trim() !== "";
280
+ // chat turn, difference 4 (cont.): no idea behind it, so no per-prompt lock.
281
+ const from = isChat ? undefined : fromIdOf(request);
282
+ // THE ONE TREE A REQUEST MAY NAME: one of this idea's own (round 3 item 67).
283
+ let ownTreePath = null;
284
+ if (from) {
285
+ const lock = await activeWorktreeForPromptRows(root, project.id, from, settings, log);
286
+ // The tree's own spelling goes down (round 4 item 70): reuseWorktree
287
+ // compares text, and the request may say /var for a /private/var tree.
288
+ ownTreePath = lock.trees.find((tree) => samePath(tree, request.worktreePath)) ?? null;
289
+ if (lock.locked) {
290
+ // A resume, or a new session (Codex, opencode) naming the kept tree
291
+ // (review 2026-10-04, D7): both run IN that tree, so neither is a second one.
292
+ const isOwnTree = samePath(request.worktreePath, lock.worktreePath);
293
+ if (!isOwnTree) {
294
+ const detail =
295
+ `Refused: this prompt already has an active session.\n\n` +
296
+ `Worktree ${lock.worktreePath} on branch ${lock.branch} (run ${lock.requestId}) ` +
297
+ `is still in progress for prompt ${from}. Only one session per prompt is allowed ` +
298
+ `while a worktree exists and its branch is not merged into main.\n\n` +
299
+ `Merge or delete the existing worktree first, then file a new request.`;
300
+ log(`[${id}] refused: prompt ${from} is locked by ${lock.worktreePath}`);
301
+ return { patch: { status: "error", result: `ERROR\n\n${detail}\n`, finished_at: new Date().toISOString() } };
302
+ }
303
+ log(`[${id}] ${isResume ? "resume" : "new session"} into own worktree ${lock.worktreePath}, lock exempted`);
304
+ }
305
+ }
306
+
307
+ const agent = agentFor(request.agent);
308
+
309
+ // CAN THIS ENGINE EVEN BE SPAWNED ON THIS MACHINE, settled BEFORE a
310
+ // worktree is minted (2026-09-20): the daemon runs with its service's
311
+ // PATH, so a `claude` that answers from Terminal can still ENOENT here.
312
+ // `resolveAgentBinary` (detect.mjs, what `glytch doctor` probes through)
313
+ // tries the daemon's PATH, the well-known install directories, then a
314
+ // login shell's `command -v`, and only then refuses in words a person can
315
+ // act on, before prepareRequestWorkspace has minted anything.
316
+ // SKIPPED WHEN `settings.claudeBin` IS SET: the test/CI override already
317
+ // names a known-runnable binary (runner.test.mjs sets process.execPath).
318
+ let resolvedBinPath;
319
+ if (settings.claudeBin === undefined) {
320
+ const spec = AGENTS[agent];
321
+ const env = settings.env ?? process.env;
322
+ const platform = settings.platform ?? process.platform;
323
+ const wantedBin = env[spec.binEnv]?.trim() || spec.bin;
324
+ const resolvedBin = await resolveAgentBinary(wantedBin, { env, platform });
325
+ if (!resolvedBin.found) {
326
+ const machine = settings.host ?? "your computer";
327
+ const detail =
328
+ `NOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n` +
329
+ `${spec.label} could not be found on ${machine}.\n\n` +
330
+ `Open Claude Code or Codex and ask it to install or repair ${spec.label}, then try again.`;
331
+ log(`[${id}] refused: could not resolve ${wantedBin} to a runnable path on your computer`);
332
+ return { patch: { status: "error", result: `ERROR\n\n${detail}\n`, finished_at: new Date().toISOString() } };
333
+ }
334
+ resolvedBinPath = resolvedBin.path;
335
+ }
336
+
337
+ return { referenceImages, chatCwd, isResume, from, ownTreePath, agent, resolvedBinPath };
338
+ }