toolroll 0.9.116 → 0.9.117

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 (129) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +43 -26
  3. package/dist/acp-agents.js +14 -1
  4. package/dist/acp-client.js +19 -1
  5. package/dist/agent-change-check.js +60 -0
  6. package/dist/agent-change-schema.js +19 -0
  7. package/dist/agent-detect.js +11 -1
  8. package/dist/agent-fence.js +39 -10
  9. package/dist/agent-network-request.js +108 -0
  10. package/dist/agent-requests.js +105 -0
  11. package/dist/approval-summary.js +3 -3
  12. package/dist/backup.js +17 -1
  13. package/dist/batch-checks.js +81 -18
  14. package/dist/browser/terminal.js +41 -41
  15. package/dist/browser/workspace.css +2 -2
  16. package/dist/browser/workspace.js +36 -36
  17. package/dist/builder.js +3 -1
  18. package/dist/candidate-materialize.js +119 -0
  19. package/dist/central-enrollment-contract.js +156 -0
  20. package/dist/central-recovery-stage.js +329 -0
  21. package/dist/chat-actions.js +101 -2
  22. package/dist/chat-channel.js +40 -0
  23. package/dist/check-only-standing.js +13 -0
  24. package/dist/check-only.js +25 -13
  25. package/dist/check-recovery-hold.js +199 -0
  26. package/dist/check-recovery-index-schema.js +3 -0
  27. package/dist/check-screenshots.js +83 -0
  28. package/dist/cli.js +125 -6
  29. package/dist/codex-limits.js +4 -0
  30. package/dist/connect-cli.js +257 -11
  31. package/dist/contracts/chat-actions.js +4 -0
  32. package/dist/contracts/console-api.js +14 -3
  33. package/dist/contracts/engine-api.js +331 -2
  34. package/dist/contracts/lead-tools.js +56 -2
  35. package/dist/contracts/provider.js +1 -1
  36. package/dist/contracts/route.js +1 -1
  37. package/dist/contracts/terminal-connection.js +50 -0
  38. package/dist/converse.js +80 -4
  39. package/dist/device-pair.js +280 -0
  40. package/dist/direct-chat-artifacts.js +347 -0
  41. package/dist/direct-chat-catalog.js +311 -0
  42. package/dist/direct-chat-fence.js +96 -0
  43. package/dist/direct-chat-git.js +343 -0
  44. package/dist/direct-chat-laptop.js +19 -0
  45. package/dist/direct-chat-schema.js +181 -0
  46. package/dist/direct-chat-ship.js +861 -0
  47. package/dist/direct-chat-workspace.js +389 -0
  48. package/dist/direct-chat.js +2107 -0
  49. package/dist/doctor.js +1 -1
  50. package/dist/easy-start.js +18 -0
  51. package/dist/egress.js +25 -4
  52. package/dist/engine-chat.js +454 -0
  53. package/dist/engine-reads.js +141 -13
  54. package/dist/exec.js +4 -3
  55. package/dist/flexible-agents.js +8 -16
  56. package/dist/flexible-session.js +91 -47
  57. package/dist/flexible-ship.js +87 -7
  58. package/dist/flexible-start.js +4 -1
  59. package/dist/flexible-thread.js +2 -3
  60. package/dist/flexible-turns.js +26 -5
  61. package/dist/flow-triggers.js +13 -4
  62. package/dist/flows-ui.js +54 -20
  63. package/dist/handoff-cli.js +630 -0
  64. package/dist/invoke.js +55 -13
  65. package/dist/lead-contract.js +5 -4
  66. package/dist/lead-doors.js +80 -1
  67. package/dist/lead-progress.js +9 -0
  68. package/dist/lead-tools.js +681 -10
  69. package/dist/lead.js +37 -9
  70. package/dist/live-bus.js +11 -0
  71. package/dist/live-terminal.js +132 -12
  72. package/dist/local-handoff.js +363 -0
  73. package/dist/local-owner-acts.js +264 -2
  74. package/dist/local-owner.js +16 -1
  75. package/dist/multiplayer-handoff.js +528 -0
  76. package/dist/multiplayer-presence.js +471 -0
  77. package/dist/names.js +17 -4
  78. package/dist/needs-you.js +10 -0
  79. package/dist/operate.js +280 -19
  80. package/dist/policy.js +2 -2
  81. package/dist/project-delete-ui.js +18 -11
  82. package/dist/project-delete.js +65 -4
  83. package/dist/project-tools.js +1 -1
  84. package/dist/prompt.js +1 -1
  85. package/dist/provider-connection.js +2 -0
  86. package/dist/provider-home.js +251 -8
  87. package/dist/provider.js +3 -2
  88. package/dist/publish.js +119 -64
  89. package/dist/pull-request-flow.js +35 -14
  90. package/dist/read-executor-worker.js +1 -1
  91. package/dist/read-executor.js +95 -1
  92. package/dist/restore-retirement.js +152 -0
  93. package/dist/result-follow-ups.js +116 -37
  94. package/dist/route-change.js +44 -4
  95. package/dist/scope.js +62 -5
  96. package/dist/serve.js +49 -5
  97. package/dist/server/chat.js +94 -13
  98. package/dist/server/direct-chat.js +583 -0
  99. package/dist/server/engine-api.js +219 -21
  100. package/dist/server/flows.js +43 -10
  101. package/dist/server/found-repos.js +25 -0
  102. package/dist/server/guards.js +20 -6
  103. package/dist/server/live.js +81 -23
  104. package/dist/server/pages.js +67 -13
  105. package/dist/server/people-tokens.js +47 -6
  106. package/dist/server/remote.js +29 -0
  107. package/dist/server/render-results.js +6 -2
  108. package/dist/server/render-settings.js +4 -2
  109. package/dist/server/render-tasks.js +18 -17
  110. package/dist/server/route-table.js +69 -2
  111. package/dist/server/settings.js +22 -7
  112. package/dist/server/task-views.js +15 -3
  113. package/dist/server/tasks.js +39 -2
  114. package/dist/server/terminals.js +185 -11
  115. package/dist/settings-proofs.js +1 -1
  116. package/dist/store.js +499 -56
  117. package/dist/subscription-chat.js +33 -6
  118. package/dist/subscription-usage.js +233 -0
  119. package/dist/task-live.js +2 -1
  120. package/dist/teardown-git.js +34 -4
  121. package/dist/terminal-connection.js +159 -0
  122. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  123. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  124. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  125. package/dist/tui/linux-x64/toolroll-tui +0 -0
  126. package/dist/tui-contract.js +1 -1
  127. package/dist/tui-launch.js +32 -1
  128. package/dist/workspace-identity-schema.js +21 -0
  129. package/package.json +3 -1
@@ -0,0 +1,861 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { existsSync, lstatSync, readlinkSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { assignmentOf } from "./assignment.js";
5
+ import { canonicalJson } from "./canonical-json.js";
6
+ import { runCheckLevel } from "./check-levels.js";
7
+ import { readVerificationView } from "./contracts/verification-view.js";
8
+ import { assertTrustedCloneGit, fetchTrustedSnapshotIntoMainRepo, runHardenedMainGit, runTrustedCloneGit, } from "./direct-chat-git.js";
9
+ import { directChatShipSealAllowed } from "./direct-chat-laptop.js";
10
+ import { laptopShipProblem } from "./flexible-laptop.js";
11
+ import { soloNow } from "./install-mode.js";
12
+ import { taskBranch } from "./names.js";
13
+ import { verifyApproverStanding } from "./principal.js";
14
+ import { fileTaskProposal } from "./proposal.js";
15
+ import { completeAndOpenPullRequest, mergePullRequest } from "./pull-request-flow.js";
16
+ import { fullCheckGate } from "./result-follow-ups.js";
17
+ import { approvalOf, approve, machineActing, proposeGuarded } from "./scope.js";
18
+ import { verificationEvidence } from "./verification-evidence.js";
19
+ export { directChatShipSealAllowed };
20
+ export const DIRECT_CHAT_FILED_PREFIX = "direct-chat:";
21
+ export const DIRECT_CHAT_SHIP_OUT_OF_SCOPE = "Verify the frozen Direct Chat snapshot commit only. Further changes need a new Ship.";
22
+ export const DIRECT_CHAT_STALE_MERGE_MS = 15 * 60_000;
23
+ const DEFAULT_ACCEPTANCE = Object.freeze([
24
+ { id: "c1", statement: "The project's checks pass on this exact snapshot commit.", how: null, evidence: ["check"] },
25
+ ]);
26
+ export function directChatShipTaskId(digest) {
27
+ return `dc-${digest}`;
28
+ }
29
+ export function directChatShipDigestOf(terms) {
30
+ return createHash("sha256").update(`toolroll:direct-chat-ship:${canonicalJson(terms)}`, "utf8").digest("hex").slice(0, 32);
31
+ }
32
+ function destinationOf(store, repo) {
33
+ const grant = store.publicationGrantFor(repo);
34
+ if (grant === null || !grant.capabilities.includes("push-branch") || !grant.capabilities.includes("open-pr")) {
35
+ return null;
36
+ }
37
+ return {
38
+ repo: grant.githubRepo,
39
+ remote: grant.remote,
40
+ base: grant.base,
41
+ method: grant.mergeMethod ?? "squash",
42
+ draft: grant.draft,
43
+ };
44
+ }
45
+ function bindingFromThreadRow(stateRoot, thread) {
46
+ const clonePath = String(thread["clone_path"] ?? "");
47
+ const gitDir = typeof thread["git_dir"] === "string" ? thread["git_dir"] : "";
48
+ const configSha256 = typeof thread["config_sha256"] === "string" ? thread["config_sha256"] : "";
49
+ if (!clonePath || !gitDir || !configSha256)
50
+ return null;
51
+ return { stateRoot, clonePath, gitDir, configSha256 };
52
+ }
53
+ class ShipUnreadable extends Error {
54
+ }
55
+ const SHIP_UNREADABLE = "A changed file in this chat couldn't be read, so nothing was shipped. Check the chat's files and try again.";
56
+ const SHIP_CHANGED = "The chat's files changed while shipping, so nothing was shipped. Review the updated Ship preview first.";
57
+ const nulPaths = (raw) => raw.split("\0").filter(one => one !== "");
58
+ function contentOf(binding, realClone, rel) {
59
+ let info;
60
+ try {
61
+ info = lstatSync(join(realClone, rel));
62
+ }
63
+ catch (error) {
64
+ if (error.code === "ENOENT")
65
+ return "deleted";
66
+ throw new ShipUnreadable(SHIP_UNREADABLE);
67
+ }
68
+ if (info.isSymbolicLink()) {
69
+ try {
70
+ return `link:${createHash("sha256").update(readlinkSync(join(realClone, rel))).digest("hex")}`;
71
+ }
72
+ catch {
73
+ throw new ShipUnreadable(SHIP_UNREADABLE);
74
+ }
75
+ }
76
+ if (!info.isFile())
77
+ throw new ShipUnreadable(SHIP_UNREADABLE);
78
+ let blob;
79
+ try {
80
+ blob = runTrustedCloneGit(binding, ["hash-object", "--", rel]).trim();
81
+ }
82
+ catch {
83
+ throw new ShipUnreadable(SHIP_UNREADABLE);
84
+ }
85
+ if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(blob))
86
+ throw new ShipUnreadable(SHIP_UNREADABLE);
87
+ return `blob:${(info.mode & 0o100) !== 0 ? "100755" : "100644"}:${blob}`;
88
+ }
89
+ function inspectCloneForShip(binding, baseSha) {
90
+ const verified = assertTrustedCloneGit(binding);
91
+ if (!verified.ok)
92
+ throw new Error(verified.error);
93
+ const headSha = runTrustedCloneGit(binding, ["rev-parse", "HEAD"]).trim();
94
+ const status = runTrustedCloneGit(binding, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"]);
95
+ const committed = nulPaths(runTrustedCloneGit(binding, ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "-z", "--name-only", baseSha, "HEAD"]));
96
+ const tracked = nulPaths(runTrustedCloneGit(binding, ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "-z", "--name-only", "HEAD"]));
97
+ const untracked = nulPaths(runTrustedCloneGit(binding, ["ls-files", "-z", "--others", "--exclude-standard"]));
98
+ const working = new Map();
99
+ for (const rel of [...new Set([...tracked, ...untracked])].sort())
100
+ working.set(rel, contentOf(binding, verified.realClone, rel));
101
+ const changedFiles = [...new Set([...committed, ...working.keys()])].sort();
102
+ const diffRaw = runTrustedCloneGit(binding, ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--binary", baseSha]);
103
+ const manifest = createHash("sha256");
104
+ for (const [rel, content] of working)
105
+ manifest.update(`${rel}\0${content}\n`);
106
+ const worktreeDigest = createHash("sha256")
107
+ .update(`${headSha}\n${status}\n${diffRaw}\n${manifest.digest("hex")}`)
108
+ .digest("hex")
109
+ .slice(0, 32);
110
+ return {
111
+ changedFiles,
112
+ worktreeDigest,
113
+ headSha,
114
+ dirty: working.size > 0,
115
+ working,
116
+ };
117
+ }
118
+ function freezeSnapshotCommit(binding, title, baseSha, previewed) {
119
+ const verified = assertTrustedCloneGit(binding);
120
+ if (!verified.ok)
121
+ throw new Error(verified.error);
122
+ const head = runTrustedCloneGit(binding, ["rev-parse", "HEAD"]).trim();
123
+ if (head !== previewed.headSha)
124
+ throw new ShipUnreadable(SHIP_CHANGED);
125
+ if (previewed.working.size > 0) {
126
+ const paths = [...previewed.working.keys()];
127
+ runTrustedCloneGit(binding, ["reset", "-q"]);
128
+ try {
129
+ try {
130
+ runTrustedCloneGit(binding, ["--literal-pathspecs", "add", "-A", "--pathspec-from-file=-", "--pathspec-file-nul"], `${paths.join("\0")}\0`);
131
+ }
132
+ catch {
133
+ throw new ShipUnreadable(SHIP_CHANGED);
134
+ }
135
+ const staged = new Map();
136
+ const raw = nulPaths(runTrustedCloneGit(binding, ["diff", "--cached", "--no-ext-diff", "--no-textconv", "--no-renames", "--raw", "--no-abbrev", "-z", "HEAD"]));
137
+ for (let index = 0; index < raw.length; index += 2) {
138
+ const match = /^:(\d{6}) (\d{6}) [0-9a-f]+ ([0-9a-f]{40,64}) ([A-Z])$/.exec(raw[index]);
139
+ const rel = raw[index + 1];
140
+ if (match === null || rel === undefined)
141
+ throw new ShipUnreadable(SHIP_CHANGED);
142
+ staged.set(rel, match[4] === "D" ? "deleted"
143
+ : match[2] === "120000" ? `link:${createHash("sha256").update(runTrustedCloneGit(binding, ["cat-file", "blob", match[3]])).digest("hex")}`
144
+ : `blob:${match[2]}:${match[3]}`);
145
+ }
146
+ if (staged.size !== previewed.working.size)
147
+ throw new ShipUnreadable(SHIP_CHANGED);
148
+ for (const [rel, content] of previewed.working) {
149
+ if (staged.get(rel) !== content)
150
+ throw new ShipUnreadable(SHIP_CHANGED);
151
+ }
152
+ }
153
+ catch (error) {
154
+ try {
155
+ runTrustedCloneGit(binding, ["reset", "-q"]);
156
+ }
157
+ catch { }
158
+ throw error;
159
+ }
160
+ const msg = `Direct chat snapshot: ${title.slice(0, 72)}`;
161
+ runTrustedCloneGit(binding, [
162
+ "-c", "user.name=Toolroll Direct Chat",
163
+ "-c", "user.email=direct-chat@toolroll.local",
164
+ "commit", "-q", "--no-verify", "-m", msg,
165
+ ]);
166
+ }
167
+ const sha = runTrustedCloneGit(binding, ["rev-parse", "HEAD"]).trim();
168
+ if (sha === baseSha) {
169
+ throw new Error("No changes to ship compared to base commit.");
170
+ }
171
+ return sha;
172
+ }
173
+ export function directChatShipReadiness(store, repo) {
174
+ const github = destinationOf(store, repo);
175
+ const check = store.liveVerifyCommand(repo);
176
+ const canAutoMerge = github !== null && check !== null;
177
+ let autoMergeReason = null;
178
+ if (github === null) {
179
+ autoMergeReason = "This project isn't connected to GitHub pull requests yet — use Keep branch instead.";
180
+ }
181
+ else if (check === null) {
182
+ autoMergeReason = "Set a project check command in Settings before auto-merging — or use Keep branch.";
183
+ }
184
+ return {
185
+ canAutoMerge,
186
+ autoMergeReason,
187
+ checkCommand: check?.command ?? null,
188
+ githubRepo: github?.repo ?? null,
189
+ githubBase: github?.base ?? null,
190
+ recommendedMode: canAutoMerge ? "ship" : "keep-branch",
191
+ };
192
+ }
193
+ export function previewDirectChatShip(store, input) {
194
+ const read = previewWithInspection(store, input);
195
+ return read.ok ? { ok: true, preview: read.preview } : read;
196
+ }
197
+ function previewWithInspection(store, input) {
198
+ if (!/^[0-9a-f]{32}$/.test(input.threadId))
199
+ return { ok: false, status: 400, error: "Invalid thread id." };
200
+ const thread = store.handle
201
+ .prepare("SELECT * FROM direct_chat_thread WHERE id = ? AND owner = ? AND archived_at IS NULL")
202
+ .get(input.threadId, input.owner);
203
+ if (!thread)
204
+ return { ok: false, status: 404, error: "Chat thread not found." };
205
+ if (Number(thread["is_legacy"] ?? 0) === 1) {
206
+ return { ok: false, status: 409, error: "Imported chats are read-only history and cannot be shipped." };
207
+ }
208
+ const running = store.handle
209
+ .prepare("SELECT 1 FROM direct_chat_turn WHERE thread_id = ? AND status = 'running' LIMIT 1")
210
+ .get(input.threadId);
211
+ if (running !== undefined) {
212
+ return { ok: false, status: 409, error: "Wait for the running or stopping turn to finish before shipping this chat." };
213
+ }
214
+ const account = store.accountOf(input.owner);
215
+ if (account === null || account.revokedAt !== null || account.role !== "approver") {
216
+ return { ok: false, status: 403, error: "Approver standing is required to ship." };
217
+ }
218
+ const binding = bindingFromThreadRow(input.stateRoot, thread);
219
+ if (binding === null) {
220
+ return { ok: false, status: 409, error: "This chat has no trusted isolated clone workspace." };
221
+ }
222
+ const verified = assertTrustedCloneGit(binding);
223
+ if (!verified.ok) {
224
+ return { ok: false, status: 409, error: verified.error };
225
+ }
226
+ const repo = String(thread["repo"]);
227
+ const baseSha = String(thread["base_sha"]);
228
+ const baseBranch = String(thread["branch"]);
229
+ let inspected;
230
+ try {
231
+ inspected = inspectCloneForShip(binding, baseSha);
232
+ }
233
+ catch (error) {
234
+ if (error instanceof ShipUnreadable)
235
+ return { ok: false, status: 409, error: error.message };
236
+ return { ok: false, status: 500, error: `Could not inspect chat clone: ${error instanceof Error ? error.message : String(error)}` };
237
+ }
238
+ if (inspected.changedFiles.length === 0) {
239
+ return { ok: false, status: 409, error: "There are no changes to ship in this chat yet." };
240
+ }
241
+ const github = destinationOf(store, repo);
242
+ const check = store.liveVerifyCommand(repo);
243
+ const canAutoMerge = github !== null && check !== null;
244
+ let autoMergeReason = null;
245
+ if (github === null) {
246
+ autoMergeReason = "This project isn't connected to GitHub pull requests yet — use Keep branch instead.";
247
+ }
248
+ else if (check === null) {
249
+ autoMergeReason = "Set a project check command in Settings before auto-merging — or use Keep branch.";
250
+ }
251
+ const mode = input.mode ?? (canAutoMerge ? "ship" : "keep-branch");
252
+ const nextSeq = Number(store.handle.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS n FROM direct_chat_ship WHERE thread_id = ?").get(input.threadId)["n"]);
253
+ const branch = mode === "keep-branch" ? `${baseBranch}-${nextSeq}` : baseBranch;
254
+ const title = (input.title?.trim() || String(thread["title"]) || "Changes from Direct Chat").slice(0, 120);
255
+ const goal = (input.goal?.trim() || `Ship verified changes from Direct Chat (${title}).`).slice(0, 400);
256
+ const terms = {
257
+ kind: "direct-chat-ship",
258
+ version: 1,
259
+ threadId: input.threadId,
260
+ repo,
261
+ owner: input.owner,
262
+ ownerGeneration: account.generation,
263
+ seq: nextSeq,
264
+ mode,
265
+ baseSha,
266
+ worktreeDigest: inspected.worktreeDigest,
267
+ branch,
268
+ changedFiles: inspected.changedFiles,
269
+ title,
270
+ goal,
271
+ check: check ? { command: check.command, digest: check.digest } : null,
272
+ github,
273
+ };
274
+ const termsDigest = directChatShipDigestOf(terms);
275
+ const mergeSummary = mode === "ship" && canAutoMerge && github && check
276
+ ? `Freezes a snapshot commit, runs ${check.command}, opens a PR into ${github.repo} (${github.base}), and merges automatically once checks pass on this exact commit.`
277
+ : `Freezes a snapshot commit and saves local branch ${branch} in your main repo without pushing.`;
278
+ return {
279
+ ok: true,
280
+ inspected,
281
+ preview: {
282
+ threadId: input.threadId,
283
+ mode,
284
+ canAutoMerge,
285
+ autoMergeReason,
286
+ termsDigest,
287
+ title,
288
+ goal,
289
+ baseSha,
290
+ branch,
291
+ changedFiles: inspected.changedFiles,
292
+ checkCommand: check?.command ?? null,
293
+ githubRepo: github?.repo ?? null,
294
+ githubBase: github?.base ?? null,
295
+ mergeSummary,
296
+ terms,
297
+ },
298
+ };
299
+ }
300
+ export function executeDirectChatShip(store, input) {
301
+ if (machineActing()) {
302
+ return { ok: false, status: 403, error: "Only a person can ship a chat's changes." };
303
+ }
304
+ if (!soloNow(store)) {
305
+ return { ok: false, status: 403, error: "Direct chat shipping is only available on solo local installs." };
306
+ }
307
+ const previewRes = previewWithInspection(store, {
308
+ stateRoot: input.stateRoot,
309
+ owner: input.owner,
310
+ threadId: input.threadId,
311
+ mode: input.mode,
312
+ title: input.title,
313
+ goal: input.goal,
314
+ });
315
+ if (!previewRes.ok)
316
+ return previewRes;
317
+ const { preview, inspected } = previewRes;
318
+ if (preview.termsDigest !== input.termsDigest) {
319
+ return {
320
+ ok: false,
321
+ status: 409,
322
+ code: "terms_changed",
323
+ error: "Changes occurred since this preview was generated. Review the updated Ship preview first.",
324
+ };
325
+ }
326
+ if (input.mode === "ship" && !preview.canAutoMerge) {
327
+ return {
328
+ ok: false,
329
+ status: 409,
330
+ code: "auto_merge_unavailable",
331
+ error: preview.autoMergeReason ?? "Auto-merge isn't available for this project; use Keep branch instead.",
332
+ };
333
+ }
334
+ const thread = store.handle
335
+ .prepare("SELECT * FROM direct_chat_thread WHERE id = ? AND owner = ? AND archived_at IS NULL")
336
+ .get(input.threadId, input.owner);
337
+ if (!thread)
338
+ return { ok: false, status: 404, error: "Chat thread not found." };
339
+ const binding = bindingFromThreadRow(input.stateRoot, thread);
340
+ if (binding === null) {
341
+ return { ok: false, status: 409, error: "This chat has no trusted isolated clone workspace." };
342
+ }
343
+ const repo = String(thread["repo"]);
344
+ const baseSha = String(thread["base_sha"]);
345
+ const now = input.now ?? new Date();
346
+ const stamp = now.toISOString();
347
+ let candidateSha;
348
+ try {
349
+ candidateSha = freezeSnapshotCommit(binding, preview.title, baseSha, inspected);
350
+ }
351
+ catch (error) {
352
+ if (error instanceof ShipUnreadable)
353
+ return { ok: false, status: 409, code: "terms_changed", error: error.message };
354
+ return { ok: false, status: 409, error: error instanceof Error ? error.message : String(error) };
355
+ }
356
+ const shipId = preview.termsDigest;
357
+ const termsJson = canonicalJson(preview.terms);
358
+ const proof = input.localOwner != null
359
+ ? "local-owner"
360
+ : (input.password && input.password !== "" ? "password-now" : "solo-session");
361
+ if (input.mode === "keep-branch") {
362
+ const targetRef = `refs/heads/${preview.branch}`;
363
+ try {
364
+ fetchTrustedSnapshotIntoMainRepo({ binding, repo, candidateSha, targetRef });
365
+ }
366
+ catch (error) {
367
+ const rawMsg = error instanceof Error ? error.message : String(error);
368
+ const friendly = rawMsg.includes("checked out") || rawMsg.includes("non-fast-forward") || rawMsg.includes("rejected")
369
+ ? `Branch ${preview.branch} already exists or is checked out in your main repo. Preview again to create the next snapshot branch.`
370
+ : `Could not import branch into main repo: ${rawMsg}`;
371
+ return { ok: false, status: 409, error: friendly };
372
+ }
373
+ store.transact(() => {
374
+ store.handle.prepare(`
375
+ INSERT INTO direct_chat_ship (
376
+ id, thread_id, seq, repo, mode, base_sha, candidate_sha, branch, terms_json,
377
+ approved_by, approved_generation, local_generation, proof, state,
378
+ task_id, scope_digest, pr_url, merge_token, merge_reserved_at, detail, created_at, state_at
379
+ ) VALUES (?, ?, ?, ?, 'keep-branch', ?, ?, ?, ?, ?, ?, ?, ?, 'kept', NULL, NULL, NULL, NULL, NULL, NULL, ?, ?)
380
+ `).run(shipId, input.threadId, preview.terms.seq, repo, baseSha, candidateSha, preview.branch, termsJson, input.owner, preview.terms.ownerGeneration, input.localOwner?.localGeneration ?? null, proof, stamp, stamp);
381
+ store.recordAction({
382
+ at: stamp,
383
+ actor: input.owner,
384
+ repo,
385
+ taskId: null,
386
+ runId: null,
387
+ source: "work",
388
+ action: "direct chat keep-branch",
389
+ outcome: candidateSha.slice(0, 12),
390
+ detail: `thread ${input.threadId} · branch ${preview.branch} · commit ${candidateSha}`,
391
+ });
392
+ });
393
+ const row = readShipRow(store.handle.prepare("SELECT * FROM direct_chat_ship WHERE id = ?").get(shipId));
394
+ return { ok: true, ship: row };
395
+ }
396
+ if (proof === "local-owner") {
397
+ const laptopErr = laptopShipProblem(store, { owner: input.owner, localGeneration: input.localOwner.localGeneration });
398
+ if (laptopErr !== null) {
399
+ return { ok: false, status: 403, error: `Password-free Ship is unavailable: ${laptopErr}.` };
400
+ }
401
+ }
402
+ const taskId = directChatShipTaskId(shipId);
403
+ if (store.lookupRef(taskId) !== null) {
404
+ return { ok: false, status: 409, error: "This snapshot was already shipped." };
405
+ }
406
+ const branch = taskBranch(taskId);
407
+ try {
408
+ fetchTrustedSnapshotIntoMainRepo({ binding, repo, candidateSha, targetRef: `refs/heads/${branch}` });
409
+ }
410
+ catch (error) {
411
+ return { ok: false, status: 500, error: `Could not import snapshot commit into main repo: ${error instanceof Error ? error.message : String(error)}` };
412
+ }
413
+ try {
414
+ const sealedShip = store.transact(() => {
415
+ if (!soloNow(store)) {
416
+ throw new Error("Direct chat shipping requires solo mode.");
417
+ }
418
+ store.handle.prepare(`
419
+ INSERT INTO direct_chat_ship (
420
+ id, thread_id, seq, repo, mode, base_sha, candidate_sha, branch, terms_json,
421
+ approved_by, approved_generation, local_generation, proof, state,
422
+ task_id, scope_digest, pr_url, merge_token, merge_reserved_at, detail, created_at, state_at
423
+ ) VALUES (?, ?, ?, ?, 'ship', ?, ?, ?, ?, ?, ?, ?, ?, 'imported', NULL, NULL, NULL, NULL, NULL, NULL, ?, ?)
424
+ `).run(shipId, input.threadId, preview.terms.seq, repo, baseSha, candidateSha, branch, termsJson, input.owner, preview.terms.ownerGeneration, input.localOwner?.localGeneration ?? null, proof, stamp, stamp);
425
+ const made = fileTaskProposal(store, {
426
+ id: taskId,
427
+ title: preview.title,
428
+ repo,
429
+ goal: preview.goal,
430
+ outOfScope: DIRECT_CHAT_SHIP_OUT_OF_SCOPE,
431
+ acceptance: [...DEFAULT_ACCEPTANCE],
432
+ filedVia: `${DIRECT_CHAT_FILED_PREFIX}${shipId}`,
433
+ filedBy: { name: input.owner, kind: "person" },
434
+ planning: "skip",
435
+ admittedRepos: [repo],
436
+ }, now);
437
+ if (!made.ok)
438
+ throw new Error(made.message);
439
+ const ref = store.lookupRef(made.id);
440
+ const proposed = proposeGuarded(store, {
441
+ taskId: made.id,
442
+ author: input.owner,
443
+ taskRef: ref.id,
444
+ sawDigest: store.getScope(made.id).digest,
445
+ goal: preview.goal,
446
+ outOfScope: DIRECT_CHAT_SHIP_OUT_OF_SCOPE,
447
+ acceptance: [...DEFAULT_ACCEPTANCE],
448
+ candidate: candidateSha,
449
+ now,
450
+ });
451
+ if (!proposed.ok)
452
+ throw new Error(proposed.message || "Could not propose task scope.");
453
+ const yes = approve(store, made.id, input.owner, now, proposed.scope.digest, input.password ?? "");
454
+ if (!yes.ok) {
455
+ const msg = "message" in yes && typeof yes.message === "string" ? yes.message : yes.reason;
456
+ throw new Error(`Approval refused: ${msg}`);
457
+ }
458
+ const sealed = store.getScope(made.id);
459
+ if (!approvalOf(sealed).approved || sealed.candidate !== candidateSha) {
460
+ throw new Error("Task approval seal did not hold for this snapshot commit.");
461
+ }
462
+ store.handle.prepare(`
463
+ UPDATE direct_chat_ship
464
+ SET state = 'armed', task_id = ?, scope_digest = ?, state_at = ?
465
+ WHERE id = ? AND state = 'imported'
466
+ `).run(made.id, sealed.digest, stamp, shipId);
467
+ store.recordAction({
468
+ at: stamp,
469
+ actor: input.owner,
470
+ repo,
471
+ taskId: made.id,
472
+ runId: null,
473
+ source: "work",
474
+ action: "direct chat ship armed",
475
+ outcome: "direct-chat-ship",
476
+ detail: `thread ${input.threadId} · ship ${shipId} · commit ${candidateSha} · scope ${sealed.digest}`,
477
+ });
478
+ return readShipRow(store.handle.prepare("SELECT * FROM direct_chat_ship WHERE id = ?").get(shipId));
479
+ });
480
+ return { ok: true, ship: sealedShip };
481
+ }
482
+ catch (error) {
483
+ try {
484
+ runHardenedMainGit(["branch", "-D", branch], repo, { write: true });
485
+ }
486
+ catch {
487
+ }
488
+ return { ok: false, status: 409, error: error instanceof Error ? error.message : String(error) };
489
+ }
490
+ }
491
+ export function cancelDirectChatShip(store, input) {
492
+ if (!/^[0-9a-f]{32}$/.test(input.threadId) || !/^[0-9a-f]{32}$/.test(input.shipId)) {
493
+ return { ok: false, status: 400, error: "Invalid thread or ship id." };
494
+ }
495
+ const row = store.handle
496
+ .prepare("SELECT * FROM direct_chat_ship WHERE id = ? AND thread_id = ? AND approved_by = ?")
497
+ .get(input.shipId, input.threadId, input.owner);
498
+ if (!row)
499
+ return { ok: false, status: 404, error: "Ship record not found." };
500
+ const state = String(row["state"]);
501
+ if (state !== "armed" && state !== "completed") {
502
+ return { ok: false, status: 409, error: `Cannot cancel a ship in state '${state}'.` };
503
+ }
504
+ const now = input.now ?? new Date();
505
+ const stamp = now.toISOString();
506
+ const taskId = typeof row["task_id"] === "string" ? row["task_id"] : null;
507
+ store.transact(() => {
508
+ store.handle.prepare(`
509
+ UPDATE direct_chat_ship
510
+ SET state = 'cancelled', merge_token = NULL, merge_reserved_at = NULL, detail = 'Cancelled by owner.', state_at = ?
511
+ WHERE id = ? AND state IN ('armed', 'completed')
512
+ `).run(stamp, input.shipId);
513
+ store.recordAction({
514
+ at: stamp,
515
+ actor: input.owner,
516
+ repo: String(row["repo"]),
517
+ taskId,
518
+ runId: null,
519
+ source: "work",
520
+ action: "direct chat ship cancelled",
521
+ outcome: "cancelled",
522
+ detail: `thread ${input.threadId} · ship ${input.shipId}`,
523
+ });
524
+ });
525
+ if (taskId !== null) {
526
+ try {
527
+ store.cancelTask(taskId, now, "Direct Chat Ship cancelled by owner.");
528
+ }
529
+ catch {
530
+ }
531
+ }
532
+ return { ok: true };
533
+ }
534
+ export function listDirectChatShips(store, threadId) {
535
+ const rows = store.handle
536
+ .prepare("SELECT * FROM direct_chat_ship WHERE thread_id = ? ORDER BY seq DESC")
537
+ .all(threadId);
538
+ return rows.map(readShipRow).filter((one) => one !== null);
539
+ }
540
+ function readShipRow(raw) {
541
+ if (!raw)
542
+ return null;
543
+ let terms;
544
+ try {
545
+ terms = JSON.parse(String(raw["terms_json"]));
546
+ }
547
+ catch {
548
+ return null;
549
+ }
550
+ return {
551
+ id: String(raw["id"]),
552
+ threadId: String(raw["thread_id"]),
553
+ seq: Number(raw["seq"]),
554
+ repo: String(raw["repo"]),
555
+ mode: raw["mode"] === "keep-branch" ? "keep-branch" : "ship",
556
+ baseSha: String(raw["base_sha"]),
557
+ candidateSha: String(raw["candidate_sha"]),
558
+ branch: String(raw["branch"]),
559
+ terms,
560
+ approvedBy: String(raw["approved_by"]),
561
+ approvedGeneration: Number(raw["approved_generation"]),
562
+ localGeneration: typeof raw["local_generation"] === "number" ? raw["local_generation"] : null,
563
+ proof: raw["proof"] === "local-owner" ? "local-owner" : raw["proof"] === "password-now" ? "password-now" : "solo-session",
564
+ state: String(raw["state"]),
565
+ taskId: typeof raw["task_id"] === "string" ? raw["task_id"] : null,
566
+ scopeDigest: typeof raw["scope_digest"] === "string" ? raw["scope_digest"] : null,
567
+ prUrl: typeof raw["pr_url"] === "string" ? raw["pr_url"] : null,
568
+ mergeToken: typeof raw["merge_token"] === "string" ? raw["merge_token"] : null,
569
+ mergeReservedAt: typeof raw["merge_reserved_at"] === "string" ? raw["merge_reserved_at"] : null,
570
+ detail: typeof raw["detail"] === "string" ? raw["detail"] : null,
571
+ createdAt: String(raw["created_at"]),
572
+ stateAt: String(raw["state_at"]),
573
+ };
574
+ }
575
+ function directChatShipAuthorityProblem(store, ship) {
576
+ if (!soloNow(store))
577
+ return "install is no longer solo";
578
+ const who = verifyApproverStanding(store, ship.approvedBy, ship.approvedGeneration, [ship.repo]);
579
+ if (!who.ok)
580
+ return "approver standing or account generation changed";
581
+ if (ship.proof === "local-owner") {
582
+ if (ship.localGeneration === null)
583
+ return "laptop consent missing";
584
+ const err = laptopShipProblem(store, { owner: ship.approvedBy, localGeneration: ship.localGeneration });
585
+ if (err !== null)
586
+ return err;
587
+ }
588
+ if (ship.taskId === null || ship.scopeDigest === null)
589
+ return "verify task missing";
590
+ const task = store.getTask(ship.taskId);
591
+ if (task === null || task.state === "cancelled")
592
+ return "verify task was cancelled";
593
+ const scope = store.getScope(ship.taskId);
594
+ if (scope === null || scope.digest !== ship.scopeDigest || scope.candidate !== ship.candidateSha || !approvalOf(scope).approved) {
595
+ return "sealed task scope changed";
596
+ }
597
+ const dest = destinationOf(store, ship.repo);
598
+ if (dest === null || ship.terms.github === null || canonicalJson(dest) !== canonicalJson(ship.terms.github)) {
599
+ return "GitHub destination changed";
600
+ }
601
+ const check = store.liveVerifyCommand(ship.repo);
602
+ if (check === null || ship.terms.check === null || check.digest !== ship.terms.check.digest) {
603
+ return "project check command changed";
604
+ }
605
+ return null;
606
+ }
607
+ function cancelArmedRow(store, ship, why, now) {
608
+ const stamp = now.toISOString();
609
+ store.transact(() => {
610
+ store.handle.prepare(`
611
+ UPDATE direct_chat_ship
612
+ SET state = 'cancelled', merge_token = NULL, merge_reserved_at = NULL, detail = ?, state_at = ?
613
+ WHERE id = ? AND state IN ('armed', 'completed', 'merging')
614
+ `).run(why.slice(0, 1000), stamp, ship.id);
615
+ store.recordAction({
616
+ at: stamp,
617
+ actor: "toolroll",
618
+ repo: ship.repo,
619
+ taskId: ship.taskId,
620
+ runId: null,
621
+ source: "policy",
622
+ action: "direct chat ship cancelled",
623
+ outcome: "cancelled",
624
+ detail: `ship ${ship.id} · ${why}`.slice(0, 1000),
625
+ });
626
+ if (ship.taskId !== null) {
627
+ try {
628
+ store.cancelTask(ship.taskId, now, `Direct Chat Ship cancelled: ${why}`);
629
+ }
630
+ catch {
631
+ }
632
+ }
633
+ });
634
+ }
635
+ function newestBuilderRun(store, taskId) {
636
+ const ref = store.lookupRef(taskId);
637
+ const runs = ref === null ? [] : store.runsFor(ref.id).filter(one => one.role !== "reviewer");
638
+ return runs.reduce((best, one) => (best === null || one.id > best.id ? one : best), null);
639
+ }
640
+ function passingCheckDigest(store, root, runId, ship, now) {
641
+ if (ship.terms.check === null)
642
+ return null;
643
+ if (runCheckLevel(store, runId) === null || fullCheckGate(store, runId, now).state !== "clear")
644
+ return null;
645
+ const ev = verificationEvidence(store, root, runId);
646
+ if (!ev.ok || ev.bytes === null)
647
+ return null;
648
+ const view = readVerificationView(ev.bytes);
649
+ if (!view.ok)
650
+ return null;
651
+ const result = view.value.result;
652
+ return view.value.head === ship.candidateSha && view.value.command.digest === ship.terms.check.digest && result.exitCode === 0
653
+ ? ev.digest
654
+ : null;
655
+ }
656
+ export function baseStillAncestor(repo, baseSha, remote, targetBranch) {
657
+ if (!existsSync(repo))
658
+ return "unknown";
659
+ const remoteRef = `refs/remotes/${remote}/${targetBranch}`;
660
+ let targetRef = `refs/heads/${targetBranch}`;
661
+ try {
662
+ runHardenedMainGit(["rev-parse", "--verify", "--quiet", remoteRef], repo);
663
+ targetRef = remoteRef;
664
+ }
665
+ catch {
666
+ }
667
+ try {
668
+ runHardenedMainGit(["--no-replace-objects", "merge-base", "--is-ancestor", baseSha, targetRef], repo);
669
+ return "yes";
670
+ }
671
+ catch (error) {
672
+ const status = error.status;
673
+ return status === 1 ? "no" : "unknown";
674
+ }
675
+ }
676
+ const inFlightMerges = new Set();
677
+ export async function directChatArmedPass(store, input) {
678
+ const clock = input.clock ?? (() => new Date());
679
+ const report = { ok: true, completed: 0, merged: 0, cancelled: 0, waiting: 0 };
680
+ const rows = store.handle
681
+ .prepare("SELECT * FROM direct_chat_ship WHERE state IN ('armed', 'completed', 'merging') ORDER BY created_at ASC")
682
+ .all();
683
+ for (const raw of rows) {
684
+ const ship = readShipRow(raw);
685
+ if (ship === null || ship.taskId === null)
686
+ continue;
687
+ if (ship.state === "merging") {
688
+ if (ship.mergeToken !== null && inFlightMerges.has(ship.mergeToken)) {
689
+ report.waiting += 1;
690
+ continue;
691
+ }
692
+ const reservedMs = ship.mergeReservedAt ? Date.parse(ship.mergeReservedAt) : 0;
693
+ if (Number.isFinite(reservedMs) && clock().getTime() - reservedMs < DIRECT_CHAT_STALE_MERGE_MS) {
694
+ report.waiting += 1;
695
+ continue;
696
+ }
697
+ const run = newestBuilderRun(store, ship.taskId);
698
+ const pub = run ? store.publicationForRun(run.id) : null;
699
+ if (pub?.remoteState === "MERGED") {
700
+ const at = clock().toISOString();
701
+ store.handle.prepare(`
702
+ UPDATE direct_chat_ship SET state = 'merged', merge_token = NULL, merge_reserved_at = NULL, pr_url = ?, state_at = ?
703
+ WHERE id = ? AND state = 'merging'
704
+ `).run(pub.prUrl ?? null, at, ship.id);
705
+ report.merged += 1;
706
+ }
707
+ else {
708
+ cancelArmedRow(store, ship, "Merge outcome was uncertain after a restart; inspect the pull request on GitHub.", clock());
709
+ report.cancelled += 1;
710
+ }
711
+ continue;
712
+ }
713
+ const problem = directChatShipAuthorityProblem(store, ship);
714
+ if (problem !== null) {
715
+ cancelArmedRow(store, ship, problem, clock());
716
+ report.cancelled += 1;
717
+ continue;
718
+ }
719
+ if (ship.terms.github !== null) {
720
+ const ancestor = baseStillAncestor(ship.repo, ship.baseSha, ship.terms.github.remote, ship.terms.github.base);
721
+ if (ancestor === "no") {
722
+ cancelArmedRow(store, ship, `Base commit is no longer an ancestor of ${ship.terms.github.remote}/${ship.terms.github.base}.`, clock());
723
+ report.cancelled += 1;
724
+ continue;
725
+ }
726
+ }
727
+ const newest = newestBuilderRun(store, ship.taskId);
728
+ if (newest === null || newest.headRevision === null || newest.finishedAt == null) {
729
+ report.waiting += 1;
730
+ continue;
731
+ }
732
+ if (newest.headRevision !== ship.candidateSha) {
733
+ cancelArmedRow(store, ship, "Result commit moved away from the shipped snapshot commit.", clock());
734
+ report.cancelled += 1;
735
+ continue;
736
+ }
737
+ const checkReceipt = passingCheckDigest(store, input.root, newest.id, ship, clock());
738
+ if (checkReceipt === null) {
739
+ report.waiting += 1;
740
+ continue;
741
+ }
742
+ if (ship.state === "armed") {
743
+ const receipt = assignmentOf(store, ship.taskId, clock(), { principal: "operator", repos: [ship.repo] }, input.root)?.receipt ?? null;
744
+ if (receipt === null || receipt.runId !== newest.id) {
745
+ report.waiting += 1;
746
+ continue;
747
+ }
748
+ const who = verifyApproverStanding(store, ship.approvedBy, ship.approvedGeneration, [ship.repo]);
749
+ if (!who.ok) {
750
+ cancelArmedRow(store, ship, "Approver standing ended.", clock());
751
+ report.cancelled += 1;
752
+ continue;
753
+ }
754
+ try {
755
+ store.transact(() => {
756
+ const opened = completeAndOpenPullRequest(store, { taskId: ship.taskId, digest: receipt.digest, runId: newest.id, who: who.who, root: input.root }, clock());
757
+ if (!opened.ok)
758
+ throw new Error(opened.message);
759
+ const at = clock().toISOString();
760
+ store.handle.prepare(`
761
+ UPDATE direct_chat_ship SET state = 'completed', state_at = ?
762
+ WHERE id = ? AND state = 'armed'
763
+ `).run(at, ship.id);
764
+ });
765
+ report.completed += 1;
766
+ }
767
+ catch {
768
+ report.waiting += 1;
769
+ }
770
+ continue;
771
+ }
772
+ const pub = store.publicationForRun(newest.id);
773
+ if (pub === null || pub.prNumber === null) {
774
+ report.waiting += 1;
775
+ continue;
776
+ }
777
+ if (pub.headSha !== ship.candidateSha || pub.githubRepo !== ship.terms.github?.repo || pub.base !== ship.terms.github?.base) {
778
+ cancelArmedRow(store, ship, "Pull request head or destination no longer matches shipped terms.", clock());
779
+ report.cancelled += 1;
780
+ continue;
781
+ }
782
+ const token = randomBytes(16).toString("hex");
783
+ inFlightMerges.add(token);
784
+ let merged;
785
+ try {
786
+ merged = await mergePullRequest(store, {
787
+ runId: newest.id,
788
+ by: ship.approvedBy,
789
+ clock,
790
+ ...(input.exec === undefined ? {} : { exec: input.exec }),
791
+ proceed: seen => {
792
+ if (directChatShipAuthorityProblem(store, ship) !== null) {
793
+ cancelArmedRow(store, ship, "Authority changed before merge.", clock());
794
+ return false;
795
+ }
796
+ if (seen.head !== null && seen.head !== ship.candidateSha) {
797
+ cancelArmedRow(store, ship, "PR head changed on GitHub.", clock());
798
+ return false;
799
+ }
800
+ if (seen.base !== null && ship.terms.github !== null && seen.base !== ship.terms.github.base) {
801
+ cancelArmedRow(store, ship, "PR base changed on GitHub.", clock());
802
+ return false;
803
+ }
804
+ if (seen.url !== null && ship.terms.github !== null && pub.prNumber !== null) {
805
+ const expectedUrl = `https://github.com/${ship.terms.github.repo}/pull/${pub.prNumber}`;
806
+ if (seen.url.toLowerCase() !== expectedUrl.toLowerCase()) {
807
+ cancelArmedRow(store, ship, "PR repository or number changed on GitHub.", clock());
808
+ return false;
809
+ }
810
+ }
811
+ const at = clock().toISOString();
812
+ const reserved = store.handle.prepare(`
813
+ UPDATE direct_chat_ship
814
+ SET state = 'merging', merge_token = ?, merge_reserved_at = ?, state_at = ?
815
+ WHERE id = ? AND state = 'completed'
816
+ `).run(token, at, at, ship.id);
817
+ return Number(reserved.changes) === 1;
818
+ },
819
+ });
820
+ }
821
+ finally {
822
+ inFlightMerges.delete(token);
823
+ }
824
+ if (merged.ok) {
825
+ const at = clock().toISOString();
826
+ store.transact(() => {
827
+ store.handle.prepare(`
828
+ UPDATE direct_chat_ship
829
+ SET state = 'merged', merge_token = NULL, merge_reserved_at = NULL, pr_url = ?, state_at = ?
830
+ WHERE id = ? AND state IN ('merging', 'completed')
831
+ `).run(pub.prUrl ?? null, at, ship.id);
832
+ store.recordAction({
833
+ at,
834
+ actor: ship.approvedBy,
835
+ repo: ship.repo,
836
+ taskId: ship.taskId,
837
+ runId: newest.id,
838
+ source: "work",
839
+ action: "direct chat merged",
840
+ outcome: merged.commit ?? "merged",
841
+ detail: `ship ${ship.id} · commit ${ship.candidateSha}`,
842
+ });
843
+ });
844
+ report.merged += 1;
845
+ }
846
+ else if (merged.reason === "closed" || merged.reason === "moved" || merged.reason === "elsewhere") {
847
+ cancelArmedRow(store, ship, merged.message, clock());
848
+ report.cancelled += 1;
849
+ }
850
+ else {
851
+ const at = clock().toISOString();
852
+ store.handle.prepare(`
853
+ UPDATE direct_chat_ship
854
+ SET state = 'completed', merge_token = NULL, merge_reserved_at = NULL, detail = ?, state_at = ?
855
+ WHERE id = ? AND state = 'merging' AND merge_token = ?
856
+ `).run(merged.message.slice(0, 1000), at, ship.id, token);
857
+ report.waiting += 1;
858
+ }
859
+ }
860
+ return report;
861
+ }