toolroll 0.9.119 → 0.9.120

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 (40) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +8 -8
  3. package/dist/assignment.js +9 -7
  4. package/dist/browser/workspace.js +23 -23
  5. package/dist/builder.js +2 -1
  6. package/dist/cli-help.js +1 -0
  7. package/dist/codex-limits.js +40 -22
  8. package/dist/contracts/console-api.js +2 -0
  9. package/dist/engine-reads.js +3 -1
  10. package/dist/flexible-import.js +38 -0
  11. package/dist/flexible-save.js +128 -0
  12. package/dist/flexible-session.js +9 -2
  13. package/dist/flexible-ship.js +3 -3
  14. package/dist/flexible-thread.js +2 -2
  15. package/dist/local-checks.js +32 -0
  16. package/dist/local-landing.js +321 -63
  17. package/dist/local-owner.js +2 -0
  18. package/dist/operate.js +25 -7
  19. package/dist/plan-limits-demand.js +48 -0
  20. package/dist/result-follow-ups.js +22 -8
  21. package/dist/review-context.js +2 -1
  22. package/dist/server/direct-chat.js +24 -3
  23. package/dist/server/engine-api.js +24 -3
  24. package/dist/server/render-results.js +6 -4
  25. package/dist/server/route-table.js +6 -1
  26. package/dist/server/send-back-build.js +4 -0
  27. package/dist/server/settings.js +2 -0
  28. package/dist/server/task-views.js +8 -3
  29. package/dist/server/tasks.js +51 -9
  30. package/dist/settings-groups-ui.js +1 -1
  31. package/dist/subscription-usage.js +11 -5
  32. package/dist/surface.js +3 -2
  33. package/dist/task-base.js +23 -4
  34. package/dist/task-outcome-cli.js +10 -1
  35. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  36. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  37. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  38. package/dist/tui/linux-x64/toolroll-tui +0 -0
  39. package/dist/verification-evidence.js +3 -1
  40. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { lstatSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
2
+ import { lstatSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { run as execRun } from "./exec.js";
@@ -10,9 +10,12 @@ import { recordActionWhole } from "./action-ledger.js";
10
10
  import { reproveApprover, verifyApproverStanding } from "./principal.js";
11
11
  import { localActNow, LOCAL_OWNER_LAPSED } from "./local-owner.js";
12
12
  import { publishingOf } from "./pull-request-flow.js";
13
+ import { wholeChangeBaseOf } from "./task-base.js";
13
14
  export const LAND_DESTINATION = "land destination";
14
15
  export const LAND_INTENT = "land intent";
15
16
  export const LAND_SETTLED = "land settled";
17
+ export const LAND_HANDOFF = "land handoff";
18
+ export const LAND_HANDOFF_SETTLED = "land handoff settled";
16
19
  function checkBindingsOf(store, repo) {
17
20
  return { full: store.liveVerifyCommand(repo)?.digest ?? null, quick: store.liveVerifyCommand(quickVerifyKey(repo))?.digest ?? null,
18
21
  setup: store.liveWorktreeSetup(repo)?.digest ?? null, access: String(store.projectCheckAccess(repo)) };
@@ -63,8 +66,9 @@ function intentOf(row) {
63
66
  if (d["v"] !== 1 || typeof d["ref"] !== "string" || typeof d["old"] !== "string" || typeof d["commit"] !== "string" || !OID.test(d["old"]) || !OID.test(d["commit"])
64
67
  || (d["mode"] !== "files" && d["mode"] !== "ref") || typeof d["key"] !== "string" || (d["kind"] !== "land" && d["kind"] !== "undo"))
65
68
  return null;
66
- return { id: row.id, at: row.at, repo: row.repo, task: row.task, run: row.run, kind: d["kind"], ref: d["ref"], old: d["old"], commit: d["commit"], mode: d["mode"], key: d["key"],
67
- reverts: typeof d["reverts"] === "number" ? d["reverts"] : null };
69
+ const candidate = typeof d["candidate"] === "string" && OID.test(d["candidate"]) ? d["candidate"] : d["commit"];
70
+ return { id: row.id, at: row.at, repo: row.repo, task: row.task, run: row.run, kind: d["kind"], ref: d["ref"], old: d["old"], commit: d["commit"], candidate, mode: d["mode"], key: d["key"],
71
+ reverts: typeof d["reverts"] === "number" || typeof d["reverts"] === "string" ? d["reverts"] : null, fromHandoff: typeof d["fromHandoff"] === "number" ? d["fromHandoff"] : null };
68
72
  }
69
73
  function intents(store, where, args) {
70
74
  return store.handle.prepare(`SELECT id,at,actor,outcome,detail,repo,task_id,run_id FROM action_ledger WHERE ${where} AND action = ? ORDER BY id DESC`).all(...args, LAND_INTENT).flatMap(row => {
@@ -88,7 +92,8 @@ export function landingOf(store, rootId) {
88
92
  const landed = all.find(one => one.kind === "land" && settledOf(store, one.id)?.outcome.startsWith("landed") === true);
89
93
  if (landed === undefined)
90
94
  return null;
91
- const undone = all.some(one => one.kind === "undo" && one.reverts === landed.id && settledOf(store, one.id)?.outcome.startsWith("landed") === true);
95
+ const name = landed.fromHandoff !== null ? `handoff:${landed.fromHandoff}` : `intent:${landed.id}`;
96
+ const undone = all.some(one => one.kind === "undo" && (one.reverts === name || one.reverts === landed.id) && settledOf(store, one.id)?.outcome.startsWith("landed") === true);
92
97
  return { intent: landed, at: settledOf(store, landed.id).at, undone };
93
98
  }
94
99
  async function treeProblem(git, commit) {
@@ -136,31 +141,36 @@ async function checkoutsOn(git, ref) {
136
141
  }
137
142
  return found;
138
143
  }
139
- async function refProblem(git, repo, ref, old, own) {
144
+ async function placeOf(git, project, ref, old) {
140
145
  const branch = ref.slice("refs/heads/".length);
141
146
  const symbolic = await git(["symbolic-ref", "-q", ref]);
142
147
  if (symbolic.code === 0)
143
- return { reason: "destination", message: `${branch} points at another branch (${symbolic.stdout.trim().replace(/^refs\/heads\//, "")}), so Toolroll won't move it. Land it with git yourself.` };
148
+ return { kind: "problem", reason: "destination", message: `${branch} points at another branch (${symbolic.stdout.trim().replace(/^refs\/heads\//, "")}), so Toolroll won't move it. Land it with git yourself.` };
144
149
  if (symbolic.code !== 1)
145
- return { reason: "git", message: `Toolroll couldn't read ${branch}.` };
150
+ return { kind: "problem", reason: "git", message: `Toolroll couldn't read ${branch}.` };
146
151
  if (old !== null) {
147
152
  const read = await git(["rev-parse", "--verify", "-q", `${ref}^{commit}`]);
148
153
  if (read.code !== 0 || read.stdout.trim() !== old)
149
- return { reason: "moved", message: `${branch} moved since you looked. Look again, then land it.` };
154
+ return { kind: "problem", reason: "moved", message: `${branch} moved since you looked. Look again, then land it.` };
150
155
  }
151
156
  const on = await checkoutsOn(git, ref);
152
157
  if (on === null)
153
- return { reason: "git", message: "Toolroll couldn't list this project's checkouts." };
154
- if (on.length > 0) {
155
- let repoReal = repo;
156
- try {
157
- repoReal = realpathSync(repo);
158
- }
159
- catch { }
160
- const where = on.includes(repoReal) ? "your project folder" : `another folder (${on[0]})`;
161
- return { reason: "occupied", message: `${branch} is checked out in ${where}, so Toolroll won't touch its files. To do it yourself there: ${own}` };
158
+ return { kind: "problem", reason: "git", message: "Toolroll couldn't list this project's checkouts." };
159
+ if (on.length === 0)
160
+ return { kind: "free" };
161
+ let repoReal = project.repo;
162
+ try {
163
+ repoReal = realpathSync(project.repo);
162
164
  }
163
- return null;
165
+ catch { }
166
+ if (on.length !== 1 || on[0] !== repoReal)
167
+ return { kind: "problem", reason: "occupied", message: `${branch} is checked out in another folder, so Toolroll won't move it or suggest a command to run there. Switch that folder to another branch, then land it.` };
168
+ return { kind: "folder" };
169
+ }
170
+ export function handoffRefOf(taskId, commit) {
171
+ const safe = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(taskId) && !taskId.includes("..") && !taskId.endsWith(".lock") && !taskId.endsWith(".") ? taskId
172
+ : createHash("sha256").update(taskId).digest("hex").slice(0, 16);
173
+ return `refs/toolroll/land/${safe}/${oidOrThrow(commit)}`;
164
174
  }
165
175
  function projectOf(store, repo) {
166
176
  if (repo === null || !store.knownRepos().includes(repo))
@@ -193,22 +203,32 @@ export async function readLanding(store, taskId, access, now, options) {
193
203
  const receipt = assignment.receipt;
194
204
  if (assignment.state !== "complete" || assignment.completion === null || receipt === null)
195
205
  return refuse("not-complete", "Accept it first: only accepted work lands.");
196
- if (assignment.completion.digest !== receipt.digest)
197
- return refuse("checks", "Its checks read differently since you accepted it. Run checks again, then land it.");
206
+ const later = assignment.completion.digest !== receipt.digest;
207
+ if (later && assignment.completion.historical !== true)
208
+ return refuse("checks", "This result changed since you accepted it. Look at it again, then land it.");
198
209
  const candidate = receipt.head;
199
210
  if (candidate === null || !OID.test(candidate) || receipt.completionKind === "research-report")
200
211
  return refuse("nothing", "This result has no commit to land.");
201
212
  const landed = landingOf(store, assignment.rootId);
202
- if (landed !== null && !landed.undone && landed.intent.commit === candidate)
213
+ if (landed !== null && !landed.undone && landed.intent.candidate === candidate)
203
214
  return { ok: true, landed: { at: landed.at, ref: landed.intent.ref, commit: landed.intent.commit, mode: landed.intent.mode } };
204
215
  const checks = receipt.checks.status === "passed" ? "passed" : !projectCheckSet(store, project.repo) && receipt.checks.status === "not-run" ? "none" : null;
205
- if (checks === null)
206
- return refuse("checks", receipt.checks.status === "failed" ? "Its checks failed. Only work whose checks passed on its exact commit lands." : "Its checks haven't passed on its exact commit. Run checks, then land it.");
216
+ if (checks === null) {
217
+ if (receipt.checks.status === "failed")
218
+ return refuse("checks", later ? `Its checks failed when they ran again after you accepted it (${receipt.checks.detail}). It stays Complete; it can't land until they pass on its exact commit.`
219
+ : "Its checks failed. Only work whose checks passed on its exact commit lands.");
220
+ return refuse("checks", later ? "Its checks changed since you accepted it and haven't run on its exact commit since. Run checks (it stays Complete), then land it."
221
+ : "Its checks haven't passed on its exact commit. Run checks, then land it.");
222
+ }
207
223
  const destination = await destinationOf(store, project, git, options.into);
208
224
  if (!destination.ok)
209
225
  return destination;
210
- return planFor(git, project, destination, { kind: "land", taskId: receipt.taskId, rootId: assignment.rootId, runId: receipt.runId, receipt: receipt.digest, candidate, checks,
211
- bindings: checkBindingsOf(store, project.repo) });
226
+ const run = store.getRun(receipt.runId);
227
+ const base = run === null || run.branch === null ? null : wholeChangeBaseOf(store, run.taskRef, run.branch) ?? run.baseRevision;
228
+ return planFor(git, project, destination, { kind: "land", taskId: receipt.taskId, rootId: assignment.rootId, runId: receipt.runId, receipt: receipt.digest, completion: assignment.completion.digest, candidate, checks,
229
+ bindings: checkBindingsOf(store, project.repo) }, { base, message: squashMessage(store.getTask(receipt.taskId)?.title ?? null, receipt.taskId),
230
+ time: Math.max(0, Math.floor(Date.parse(assignment.completion.at) / 1000) || 0),
231
+ handedOff: handoffsOf(store, project.repo, assignment.rootId).filter(one => one.candidate === candidate).map(one => one.commit) });
212
232
  }
213
233
  async function destinationOf(store, project, git, into) {
214
234
  const recorded = recordedDestination(store, project.repo);
@@ -227,10 +247,29 @@ async function destinationOf(store, project, git, into) {
227
247
  }
228
248
  return { ok: true, ref, recorded: false };
229
249
  }
230
- function ownCommand(repo, fixed) {
231
- return fixed.candidate !== null ? `git -C ${repo} merge --ff-only ${fixed.candidate}` : `git -C ${repo} revert --no-edit ${fixed.reverts.old}..${fixed.reverts.landed}`;
250
+ const UNSAFE_MESSAGE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]+/g;
251
+ function squashMessage(title, taskId) {
252
+ const plain = (text) => text.replace(UNSAFE_MESSAGE, " ").replace(/\s+/g, " ").trim();
253
+ const line = plain(title ?? "").slice(0, 200), id = plain(taskId).slice(0, 100);
254
+ return line === "" ? `Toolroll task ${id}` : `${line} (Toolroll task ${id})`;
255
+ }
256
+ async function changesOf(git, old, candidate) {
257
+ const stat = await git(["diff", "--numstat", "-z", "--no-renames", "--no-ext-diff", "--no-textconv", old, candidate]);
258
+ if (stat.code !== 0)
259
+ return null;
260
+ const files = [];
261
+ let added = 0, removed = 0;
262
+ for (const entry of stat.stdout.split("\0")) {
263
+ const match = /^(\d+|-)\t(\d+|-)\t(.+)$/s.exec(entry);
264
+ if (match === null)
265
+ continue;
266
+ added += match[1] === "-" ? 0 : Number(match[1]);
267
+ removed += match[2] === "-" ? 0 : Number(match[2]);
268
+ files.push(match[3]);
269
+ }
270
+ return { files: files.slice(0, 20), fileCount: files.length, added, removed };
232
271
  }
233
- async function planFor(git, project, destination, fixed) {
272
+ async function planFor(git, project, destination, fixed, squashing = null) {
234
273
  const { ref } = destination;
235
274
  const branch = ref.slice("refs/heads/".length);
236
275
  const read = await git(["rev-parse", "--verify", "-q", `${ref}^{commit}`]);
@@ -243,10 +282,14 @@ async function planFor(git, project, destination, fixed) {
243
282
  const type = await git(["cat-file", "-t", fixed.candidate]);
244
283
  if (type.code !== 0 || type.stdout.trim() !== "commit")
245
284
  return refuse("git", `This result's commit ${short(fixed.candidate)} is no longer in the project.`);
285
+ for (const landed of [fixed.candidate, ...(squashing?.handedOff ?? [])]) {
286
+ if ((await git(["merge-base", "--is-ancestor", landed, old])).code === 0)
287
+ return refuse("nothing", ALREADY_MSG(ref, landed));
288
+ }
246
289
  const ancestor = await git(["merge-base", "--is-ancestor", old, fixed.candidate]);
247
290
  if (ancestor.code === 1) {
248
- return refuse("moved", `${branch} moved on since this work started (it's at ${short(old)} now), so it can't land as a fast-forward. `
249
- + `A merged commit would need its own check. To merge it yourself: git -C ${project.repo} merge ${fixed.candidate}`);
291
+ return refuse("moved", `${branch} moved on since this work started (it's at ${short(old)} now): bring this task up to date first. `
292
+ + `Send it back to build on the current ${branch}; landing it as it is would drop or mix in changes nobody checked together.`);
250
293
  }
251
294
  if (ancestor.code !== 0)
252
295
  return refuse("git", "Toolroll couldn't compare the commits.");
@@ -254,29 +297,76 @@ async function planFor(git, project, destination, fixed) {
254
297
  if (problem !== null)
255
298
  return refuse("unsupported", `This project can't be landed by Toolroll: ${problem}. Land it with git yourself.`);
256
299
  }
257
- const blocked = await refProblem(git, project.repo, ref, null, ownCommand(project.repo, fixed));
258
- if (blocked !== null)
259
- return refuse(blocked.reason, blocked.message);
260
- const plan = { ...fixed, repo: project.repo, ref, branch, old, mode: "ref", recorded: destination.recorded };
300
+ let squash = null;
301
+ if (fixed.candidate !== null) {
302
+ const tree = await git(["rev-parse", "--verify", "-q", `${fixed.candidate}^{tree}`]);
303
+ const changes = await changesOf(git, old, fixed.candidate);
304
+ if (tree.code !== 0 || !OID.test(tree.stdout.trim()) || changes === null)
305
+ return refuse("git", `Toolroll couldn't read what ${short(fixed.candidate)} changes.`);
306
+ const message = squashing?.message ?? `Toolroll task ${fixed.taskId}`, time = squashing?.time ?? 0, treeId = tree.stdout.trim();
307
+ squash = { policy: "squash", base: squashing?.base ?? null, commit: commitIdOf(squashBody(treeId, old, time, message)), tree: treeId, checkedTree: treeId, time, message, ...changes };
308
+ }
309
+ const place = await placeOf(git, project, ref, old);
310
+ if (place.kind === "problem")
311
+ return refuse(place.reason, place.message);
312
+ if (place.kind === "folder" && fixed.kind === "undo") {
313
+ const command = gitCommand(project.repo, ["revert", "--no-edit", `${oidOrThrow(fixed.reverts.old)}..${oidOrThrow(fixed.reverts.landed)}`]);
314
+ return refuse("occupied", `${branch} is checked out in your project folder, so Toolroll won't touch its files. ${command === null ? UNSAFE_FOLDER(`git revert --no-edit ${fixed.reverts.old}..${fixed.reverts.landed}`) : `To do it yourself there: ${command}`}`);
315
+ }
316
+ const mode = place.kind === "free" ? "ref" : "handoff";
317
+ const plan = { ...fixed, squash, repo: project.repo, ref, branch, old, mode, ...(place.kind === "folder" ? { handoff: { folder: project.repo } } : {}), recorded: destination.recorded };
261
318
  return { ok: true, plan: { ...plan, key: keyOf({ v: 1, ...plan, common: project.common }) } };
262
319
  }
263
320
  async function readUndo(store, rootId, project, git, options) {
264
321
  void options;
265
322
  const landed = landingOf(store, rootId);
266
- if (landed === null || landed.undone)
267
- return refuse("nothing", landed === null ? "This task hasn't landed, so there's nothing to undo." : "This landing was already undone.");
268
- const destination = { ref: landed.intent.ref, recorded: true };
269
- return planFor(git, project, destination, { kind: "undo", taskId: landed.intent.task, rootId, runId: landed.intent.run, receipt: landed.intent.key, candidate: null, checks: "none",
270
- reverts: { intent: landed.intent.id, old: landed.intent.old, landed: landed.intent.commit }, bindings: checkBindingsOf(store, project.repo) });
323
+ if (landed !== null && landed.undone)
324
+ return refuse("nothing", "This landing was already undone.");
325
+ const brought = landed === null ? await broughtIn(store, git, project.repo, rootId) : null;
326
+ const source = landed !== null ? { key: landed.intent.key, task: landed.intent.task, run: landed.intent.run, ref: landed.intent.ref, old: landed.intent.old, commit: landed.intent.commit,
327
+ name: landed.intent.fromHandoff !== null ? `handoff:${landed.intent.fromHandoff}` : `intent:${landed.intent.id}` }
328
+ : brought === null ? null : { key: brought.key, task: brought.task, run: brought.run, ref: brought.ref, old: brought.old, commit: brought.commit, name: `handoff:${brought.id}` };
329
+ if (source === null)
330
+ return refuse("nothing", "This task hasn't landed, so there's nothing to undo.");
331
+ return planFor(git, project, { ref: source.ref, recorded: true }, { kind: "undo", taskId: source.task, rootId, runId: source.run, receipt: source.key, completion: source.key, candidate: null, checks: "none",
332
+ reverts: { source: source.name, old: source.old, landed: source.commit }, bindings: checkBindingsOf(store, project.repo) });
333
+ }
334
+ function landedCommits(store, rootId) {
335
+ return new Set(intents(store, "task_id = ?", [rootId]).filter(one => one.kind === "land" && settledOf(store, one.id)?.outcome.startsWith("landed") === true).map(one => one.commit));
336
+ }
337
+ async function broughtIn(store, git, repo, rootId) {
338
+ const landed = landedCommits(store, rootId);
339
+ for (const one of handoffsOf(store, repo, rootId)) {
340
+ if (landed.has(one.commit))
341
+ continue;
342
+ if ((await git(["merge-base", "--is-ancestor", one.commit, one.ref])).code === 0)
343
+ return one;
344
+ }
345
+ return null;
346
+ }
347
+ function squashBody(tree, parent, time, message) {
348
+ const who = `Toolroll <land@toolroll.invalid> ${time} +0000`;
349
+ return `tree ${tree}\nparent ${parent}\nauthor ${who}\ncommitter ${who}\n\n${message}\n`;
350
+ }
351
+ function commitIdOf(body) {
352
+ return createHash("sha1").update(`commit ${Buffer.byteLength(body, "utf8")}\0`).update(body, "utf8").digest("hex");
353
+ }
354
+ const UNSAFE_SHOWN = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff\\]/g;
355
+ export function shownName(name) {
356
+ return name.replace(UNSAFE_SHOWN, ch => ch === "\\" ? "\\\\" : `\\u{${ch.codePointAt(0).toString(16)}}`);
271
357
  }
272
358
  export function landingWords(plan) {
273
- const where = `${plan.branch} in ${plan.repo} (no folder has it checked out; only the branch moves)`;
359
+ const how = plan.mode === "handoff" ? `your project folder has ${plan.branch} checked out, so Toolroll won't touch its files: Land makes the commit and shows the one git command that brings it in`
360
+ : `no folder has ${plan.branch} checked out; only the branch moves`;
274
361
  if (plan.kind === "undo") {
275
- return [`Undo the landing of ${short(plan.reverts.old)}..${short(plan.reverts.landed)} on ${where}.`,
276
- "A new commit reverts exactly those changes; nothing is rewritten. No check runs on the undo."];
362
+ return [`Undo the landing of ${short(plan.reverts.landed)} on ${plan.branch} in ${shownName(plan.repo)} (${how}).`,
363
+ "A new commit reverts exactly what it changed; nothing is rewritten. No check runs on the undo."];
277
364
  }
278
- return [`Land ${short(plan.candidate)} on ${where}, as a fast-forward from ${short(plan.old)}.`,
279
- plan.checks === "passed" ? `Checks passed on ${short(plan.candidate)}.` : "No check ran: this project has no check command.",
365
+ const squash = plan.squash;
366
+ const names = squash.files.slice(0, 3).map(shownName).join(", ") + (squash.fileCount > 3 ? ` and ${squash.fileCount - 3} more` : "");
367
+ return [`Lands 1 commit on ${plan.branch}: ${squash.fileCount === 0 ? "no file changes" : names} (+${squash.added} −${squash.removed}).`,
368
+ `${short(squash.commit)} "${shownName(squash.message)}", on top of ${short(plan.old)} in ${shownName(plan.repo)} (${how}).`,
369
+ plan.checks === "passed" ? `Checks ran on these exact files: they passed on ${short(plan.candidate)}, and ${short(squash.commit)} carries the same tree.` : "No check ran: this project has no check command.",
280
370
  ...(plan.recorded ? [] : [`Toolroll remembers ${plan.branch} as where this project's work lands.`])];
281
371
  }
282
372
  async function settleUnfinished(store, repo, now, options) {
@@ -370,9 +460,26 @@ export async function land(store, taskId, input, authority, access, now, options
370
460
  const who = standing(store, authority, repo);
371
461
  if (!who.ok)
372
462
  return who;
373
- return { ok: true, replayed: true, kind: done.kind, ref: done.ref, branch: done.ref.slice("refs/heads/".length), commit: done.commit, old: done.old, mode: done.mode, warning: null };
463
+ return { ok: true, replayed: true, kind: done.kind, ref: done.ref, branch: done.ref.slice("refs/heads/".length), commit: done.commit, old: done.old, mode: done.mode, warning: null, handoff: null };
374
464
  }
375
465
  }
466
+ const handedOff = input.undo === true ? undefined : handoffRows(store, repo).find(one => one.key === input.key);
467
+ if (handedOff !== undefined) {
468
+ const who = standing(store, authority, repo);
469
+ if (!who.ok)
470
+ return who;
471
+ const git = gitFor(repo, options.git);
472
+ const there = await git(["cat-file", "-t", handedOff.commit]);
473
+ if (there.code !== 0 || there.stdout.trim() !== "commit")
474
+ return refuse("git", "The landing commit Toolroll kept for this is gone. Look again, then land it.");
475
+ if (!await keepAt(git, handedOff.keep, handedOff.commit, `toolroll: landing commit for ${taskId}`))
476
+ return refuse("git", "Toolroll couldn't keep the landing commit. Look again, then land it.");
477
+ if (!handedOff.settled)
478
+ recordActionWhole(store.handle, { at: now.toISOString(), actor: "toolroll", repo, taskId: handedOff.task, runId: handedOff.run, action: LAND_HANDOFF_SETTLED,
479
+ outcome: `${handedOff.id}:kept`, source: "work" }, { v: 1, keep: handedOff.keep, commit: handedOff.commit });
480
+ return { ok: true, replayed: handedOff.settled, kind: "land", ref: handedOff.ref, branch: handedOff.ref.slice("refs/heads/".length), commit: handedOff.commit, old: handedOff.old, mode: "handoff",
481
+ warning: null, handoff: { ref: handedOff.keep, command: handoffCommand(repo, handedOff.commit) } };
482
+ }
376
483
  await settleUnfinished(store, repo, now, options);
377
484
  const read = await readLanding(store, taskId, access, now, { ...options, ...(input.into === undefined ? {} : { into: input.into }), ...(input.undo === true ? { undo: true } : {}) });
378
485
  if (!read.ok)
@@ -384,6 +491,10 @@ export async function land(store, taskId, input, authority, access, now, options
384
491
  return refuse("stale", "Something changed since you looked (the branch, the checks or the result). Look again, then land it.");
385
492
  const project = projectOf(store, plan.repo);
386
493
  const git = gitFor(plan.repo, options.git);
494
+ const handoffSource = plan.kind === "undo" ? /^handoff:(\d+)$/.exec(plan.reverts?.source ?? "") : null;
495
+ if (handoffSource !== null && !(await reconcileHandoff(store, git, plan.repo, plan.rootId, Number(handoffSource[1]), first.actor, now))) {
496
+ return refuse("stale", "That landing changed since you looked. Look again.");
497
+ }
387
498
  const stillStands = () => {
388
499
  const who = standing(store, authority, plan.repo);
389
500
  if (!who.ok)
@@ -392,27 +503,66 @@ export async function land(store, taskId, input, authority, access, now, options
392
503
  return refuse("pull-requests", PULL_REQUESTS_INSTEAD);
393
504
  if (plan.kind === "land") {
394
505
  const again = assignmentOf(store, taskId, now, { principal: "operator", repos: access.repos }, options.root);
395
- if (again?.state !== "complete" || again.receipt?.digest !== plan.receipt || again.completion?.digest !== plan.receipt)
506
+ if (again?.state !== "complete" || again.receipt?.digest !== plan.receipt || again.completion?.digest !== plan.completion)
396
507
  return refuse("stale", "This result changed since you looked. Look again, then land it.");
397
508
  }
398
509
  else {
399
510
  const landed = landingOf(store, plan.rootId);
400
- if (landed === null || landed.undone || landed.intent.id !== plan.reverts?.intent)
511
+ const name = landed === null ? null : landed.intent.fromHandoff !== null ? `handoff:${landed.intent.fromHandoff}` : `intent:${landed.intent.id}`;
512
+ if (landed === null || landed.undone || name !== plan.reverts?.source)
401
513
  return refuse("stale", "That landing changed since you looked. Look again.");
402
514
  }
403
515
  if (JSON.stringify(checkBindingsOf(store, plan.repo)) !== JSON.stringify(plan.bindings))
404
516
  return refuse("stale", "The project's checks changed since you looked. Look again, then land it.");
405
517
  return who;
406
518
  };
407
- let commit = plan.candidate;
408
- if (plan.kind === "undo") {
409
- const pre = standing(store, authority, plan.repo);
410
- if (!pre.ok)
411
- return pre;
412
- const made = await revertCommit(git, plan, options.scratch);
413
- if (!made.ok)
414
- return made;
415
- commit = made.commit;
519
+ const pre = standing(store, authority, plan.repo);
520
+ if (!pre.ok)
521
+ return pre;
522
+ const made = plan.kind === "undo" ? await revertCommit(git, plan, options.scratch) : await squashCommit(git, plan, options.scratch);
523
+ if (!made.ok)
524
+ return made;
525
+ const commit = made.commit;
526
+ const keep = handoffRefOf(plan.rootId, commit);
527
+ if (plan.kind === "land") {
528
+ const kept = await keepAt(git, keep, commit, `toolroll: landing commit for ${plan.taskId}`);
529
+ if (!kept)
530
+ return refuse("git", "Toolroll made the landing commit but couldn't keep it. Nothing landed; look again, then land it.");
531
+ }
532
+ if (plan.mode === "handoff") {
533
+ const place = await placeOf(git, project, plan.ref, plan.old);
534
+ if (place.kind !== "folder")
535
+ return refuse(place.kind === "problem" ? place.reason : "stale", place.kind === "problem" ? place.message : "Your project folder changed since you looked. Look again, then land it.");
536
+ let handoffId, replayed = false;
537
+ try {
538
+ handoffId = store.transact(() => {
539
+ const who = stillStands();
540
+ if (!who.ok)
541
+ throw new Refused(who);
542
+ const earlier = handoffRows(store, plan.repo).find(one => one.key === plan.key && one.commit === commit);
543
+ if (earlier !== undefined) {
544
+ replayed = earlier.settled;
545
+ return earlier.id;
546
+ }
547
+ if (!plan.recorded)
548
+ recordActionWhole(store.handle, { at: now.toISOString(), actor: who.actor, repo: plan.repo, taskId: null, runId: null, action: LAND_DESTINATION, outcome: plan.ref, source: "request" }, { v: 1, ref: plan.ref, common: project.common });
549
+ return recordActionWhole(store.handle, { at: now.toISOString(), actor: who.actor, repo: plan.repo, taskId: plan.rootId, runId: plan.runId, action: LAND_HANDOFF, outcome: "pending", source: "request" }, { v: 1, key: plan.key, ref: plan.ref, old: plan.old, commit, keep, folder: project.repo, policy: "squash", candidate: plan.candidate, base: plan.squash.base, tree: plan.squash.tree,
550
+ checkedTree: plan.squash.checkedTree, checks: plan.checks });
551
+ });
552
+ }
553
+ catch (error) {
554
+ if (error instanceof Refused)
555
+ return error.result;
556
+ throw error;
557
+ }
558
+ const at = await git(["rev-parse", "--verify", "-q", `${keep}^{commit}`]);
559
+ if (at.code !== 0 || at.stdout.trim() !== commit)
560
+ return refuse("git", "Toolroll couldn't keep the landing commit. Nothing landed; look again, then land it.");
561
+ if (!replayed)
562
+ recordActionWhole(store.handle, { at: now.toISOString(), actor: "toolroll", repo: plan.repo, taskId: plan.rootId, runId: plan.runId, action: LAND_HANDOFF_SETTLED,
563
+ outcome: `${handoffId}:kept`, source: "work" }, { v: 1, keep, commit });
564
+ return { ok: true, replayed, kind: "land", ref: plan.ref, branch: plan.branch, commit, old: plan.old, mode: "handoff", warning: null,
565
+ handoff: { ref: keep, command: handoffCommand(project.repo, commit) } };
416
566
  }
417
567
  let intentId;
418
568
  try {
@@ -424,7 +574,8 @@ export async function land(store, taskId, input, authority, access, now, options
424
574
  throw new Refused(refuse("busy", "Another landing in this project hasn't finished. Try again in a moment."));
425
575
  if (!plan.recorded)
426
576
  recordActionWhole(store.handle, { at: now.toISOString(), actor: who.actor, repo: plan.repo, taskId: null, runId: null, action: LAND_DESTINATION, outcome: plan.ref, source: "request" }, { v: 1, ref: plan.ref, common: project.common });
427
- return recordActionWhole(store.handle, { at: now.toISOString(), actor: who.actor, repo: plan.repo, taskId: plan.rootId, runId: plan.runId, action: LAND_INTENT, outcome: "pending", source: "request" }, { v: 1, kind: plan.kind, key: plan.key, ref: plan.ref, old: plan.old, commit, mode: "ref", ...(plan.reverts === undefined ? {} : { reverts: plan.reverts.intent }) });
577
+ return recordActionWhole(store.handle, { at: now.toISOString(), actor: who.actor, repo: plan.repo, taskId: plan.rootId, runId: plan.runId, action: LAND_INTENT, outcome: "pending", source: "request" }, { v: 1, kind: plan.kind, key: plan.key, ref: plan.ref, old: plan.old, commit, mode: "ref", ...(plan.reverts === undefined ? {} : { reverts: plan.reverts.source }),
578
+ ...(plan.squash === null ? {} : { policy: "squash", candidate: plan.candidate, base: plan.squash.base, tree: plan.squash.tree, checkedTree: plan.squash.checkedTree, keep, checks: plan.checks }) });
428
579
  });
429
580
  }
430
581
  catch (error) {
@@ -434,10 +585,11 @@ export async function land(store, taskId, input, authority, access, now, options
434
585
  }
435
586
  const settle = (outcome, words) => recordActionWhole(store.handle, { at: now.toISOString(), actor: "toolroll", repo: plan.repo, taskId: plan.rootId, runId: plan.runId,
436
587
  action: LAND_SETTLED, outcome: `${intentId}:${outcome}`, source: "work" }, { v: 1, words });
437
- const blocked = await refProblem(git, plan.repo, plan.ref, plan.old, ownCommand(plan.repo, plan));
438
- if (blocked !== null) {
439
- settle("refused", blocked.message);
440
- return refuse(blocked.reason, blocked.message);
588
+ const place = await placeOf(git, project, plan.ref, plan.old);
589
+ if (place.kind !== "free") {
590
+ const words = place.kind === "problem" ? place.message : `${plan.branch} is checked out in your project folder now, so Toolroll won't move it. Look again, then land it.`;
591
+ settle("refused", words);
592
+ return refuse(place.kind === "problem" ? place.reason : "occupied", words);
441
593
  }
442
594
  const last = store.transact(stillStands);
443
595
  if (!last.ok) {
@@ -451,9 +603,72 @@ export async function land(store, taskId, input, authority, access, now, options
451
603
  return refuse("moved", words);
452
604
  }
453
605
  settle("landed", plan.kind === "undo" ? "Undone." : "Landed.");
454
- return { ok: true, replayed: false, kind: plan.kind, ref: plan.ref, branch: plan.branch, commit: commit, old: plan.old, mode: "ref", warning: null };
606
+ return { ok: true, replayed: false, kind: plan.kind, ref: plan.ref, branch: plan.branch, commit, old: plan.old, mode: "ref", warning: null, handoff: null };
607
+ });
608
+ }
609
+ async function keepAt(git, ref, commit, why) {
610
+ const was = await git(["rev-parse", "--verify", "-q", ref]);
611
+ const old = was.code === 0 ? was.stdout.trim() : "0".repeat(40);
612
+ if (old === commit)
613
+ return true;
614
+ if (was.code === 0 && !OID.test(old))
615
+ return false;
616
+ const moved = await git(["update-ref", "--no-deref", "-m", why, ref, commit, old]);
617
+ return moved.code === 0;
618
+ }
619
+ async function reconcileHandoff(store, git, repo, rootId, id, actor, now) {
620
+ const one = handoffsOf(store, repo, rootId).find(row => row.id === id);
621
+ if (one === undefined || (await git(["merge-base", "--is-ancestor", one.commit, one.ref])).code !== 0)
622
+ return false;
623
+ return store.transact(() => {
624
+ const recorded = intents(store, "task_id = ?", [rootId]).find(intent => intent.fromHandoff === one.id);
625
+ if (recorded !== undefined)
626
+ return settledOf(store, recorded.id)?.outcome.startsWith("landed") === true;
627
+ if (landedCommits(store, rootId).has(one.commit))
628
+ return false;
629
+ const intent = recordActionWhole(store.handle, { at: now.toISOString(), actor, repo, taskId: rootId, runId: one.run, action: LAND_INTENT, outcome: "pending", source: "request" }, { v: 1, kind: "land", key: one.key, ref: one.ref, old: one.old, commit: one.commit, mode: "ref", policy: "squash", candidate: one.candidate, fromHandoff: one.id });
630
+ recordActionWhole(store.handle, { at: now.toISOString(), actor: "toolroll", repo, taskId: rootId, runId: one.run, action: LAND_SETTLED, outcome: `${intent}:landed:brought-in`, source: "work" }, { v: 1, words: "The person brought in the landing commit Toolroll made; recorded as landed." });
631
+ return true;
455
632
  });
456
633
  }
634
+ function oidOrThrow(oid) {
635
+ if (!OID.test(oid))
636
+ throw new Error("not a commit id");
637
+ return oid;
638
+ }
639
+ const UNSAFE_IN_COMMAND = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/;
640
+ export function gitCommand(folder, args) {
641
+ if (UNSAFE_IN_COMMAND.test(folder))
642
+ return null;
643
+ return ["git", "-C", `'${folder.replace(/'/g, "'\\''")}'`, ...args].join(" ");
644
+ }
645
+ const UNSAFE_FOLDER = (what) => `Toolroll can't write a safe command for this folder's name; run ${what} in your project folder.`;
646
+ function handoffCommand(folder, commit) {
647
+ return gitCommand(folder, ["merge", "--ff-only", oidOrThrow(commit)]);
648
+ }
649
+ export function handoffWords(handoff, commit) {
650
+ return handoff.command === null ? UNSAFE_FOLDER(`git merge --ff-only ${commit}`) : `To bring it in: ${handoff.command}`;
651
+ }
652
+ function handoffRows(store, repo, taskId) {
653
+ return store.handle.prepare(`SELECT id,detail,task_id,run_id FROM action_ledger WHERE repo = ? AND action = ?${taskId === undefined ? "" : " AND task_id = ?"} ORDER BY id DESC`)
654
+ .all(...(taskId === undefined ? [repo, LAND_HANDOFF] : [repo, LAND_HANDOFF, taskId])).flatMap(row => {
655
+ try {
656
+ const d = JSON.parse(String(row["detail"] ?? "null"));
657
+ const ok = d["v"] === 1 && typeof d["key"] === "string" && typeof d["ref"] === "string" && typeof d["old"] === "string" && OID.test(d["old"]) && typeof d["commit"] === "string" && OID.test(d["commit"])
658
+ && typeof d["keep"] === "string" && typeof d["folder"] === "string" && typeof d["candidate"] === "string" && OID.test(d["candidate"]);
659
+ const id = Number(row["id"]);
660
+ const settled = ok && store.handle.prepare("SELECT 1 AS hit FROM action_ledger WHERE action = ? AND outcome = ? LIMIT 1").get(LAND_HANDOFF_SETTLED, `${id}:kept`) !== undefined;
661
+ return ok ? [{ id, task: String(row["task_id"]), run: Number(row["run_id"]), key: d["key"], ref: d["ref"], old: d["old"], commit: d["commit"],
662
+ keep: d["keep"], folder: d["folder"], candidate: d["candidate"], settled }] : [];
663
+ }
664
+ catch {
665
+ return [];
666
+ }
667
+ });
668
+ }
669
+ export function handoffsOf(store, repo, taskId) {
670
+ return handoffRows(store, repo, taskId).filter(one => one.settled);
671
+ }
457
672
  class Refused extends Error {
458
673
  result;
459
674
  constructor(result) {
@@ -461,6 +676,33 @@ class Refused extends Error {
461
676
  this.result = result;
462
677
  }
463
678
  }
679
+ async function squashCommit(git, plan, scratch) {
680
+ const squash = plan.squash;
681
+ if (squash.tree !== squash.checkedTree)
682
+ return refuse("checks", "The commit Toolroll would land doesn't carry the files its checks ran on. Nothing landed.");
683
+ const verified = await git(["rev-parse", "--verify", "-q", `${plan.candidate}^{tree}`]);
684
+ if (verified.code !== 0 || verified.stdout.trim() !== squash.checkedTree)
685
+ return refuse("checks", "The result's files aren't the ones its checks ran on any more. Nothing landed.");
686
+ const folder = mkdtempSync(join(scratch ?? tmpdir(), "toolroll-land-"));
687
+ let written;
688
+ try {
689
+ const file = join(folder, "commit");
690
+ writeFileSync(file, squashBody(squash.tree, plan.old, squash.time, squash.message), { encoding: "utf8", mode: 0o600, flag: "wx" });
691
+ written = await git(["hash-object", "-t", "commit", "-w", "--", file]);
692
+ }
693
+ finally {
694
+ rmSync(folder, { recursive: true, force: true });
695
+ }
696
+ const commit = written.stdout.trim();
697
+ if (written.code !== 0 || commit !== squash.commit)
698
+ return refuse("stale", "The commit Toolroll would land isn't the one you read. Nothing landed; look again.");
699
+ const shown = await git(["cat-file", "commit", commit]);
700
+ const header = shown.stdout.split("\n\n")[0] ?? "";
701
+ const parents = header.split("\n").filter(line => line.startsWith("parent ")).map(line => line.slice("parent ".length));
702
+ if (shown.code !== 0 || !header.startsWith(`tree ${squash.checkedTree}\n`) || parents.length !== 1 || parents[0] !== plan.old)
703
+ return refuse("git", "Toolroll couldn't make the landing commit.");
704
+ return { ok: true, commit };
705
+ }
464
706
  async function revertCommit(git, plan, scratch) {
465
707
  const reverts = plan.reverts;
466
708
  const folder = mkdtempSync(join(scratch ?? tmpdir(), "toolroll-undo-"));
@@ -475,7 +717,9 @@ async function revertCommit(git, plan, scratch) {
475
717
  const reverted = await git([...identity, "revert", "--no-edit", "--no-commit", `${reverts.old}..${reverts.landed}`], checkout);
476
718
  if (reverted.code !== 0) {
477
719
  await git(["revert", "--abort"], checkout);
478
- return refuse("moved", `Undoing it conflicts with later changes on ${plan.branch}. To undo it yourself: git -C ${plan.repo} revert ${reverts.old}..${reverts.landed}`);
720
+ const range = `${oidOrThrow(reverts.old)}..${oidOrThrow(reverts.landed)}`;
721
+ const command = gitCommand(plan.repo, ["revert", range]);
722
+ return refuse("moved", `Undoing it conflicts with later changes on ${plan.branch}. ${command === null ? UNSAFE_FOLDER(`git revert ${range}`) : `To undo it yourself: ${command}`}`);
479
723
  }
480
724
  const committed = await git([...identity, "commit", "--no-verify", "--allow-empty", "-m", `Undo landing of ${plan.taskId} (${short(reverts.old)}..${short(reverts.landed)})`], checkout);
481
725
  const head = await git(["rev-parse", "--verify", "-q", "HEAD^{commit}"], checkout);
@@ -498,3 +742,17 @@ export function landedWords(store, rootId) {
498
742
  return landed.undone ? `Landed on ${landed.intent.ref.replace(/^refs\/heads\//, "")} (${short(landed.intent.commit)}), then undone.`
499
743
  : `Landed on ${landed.intent.ref.replace(/^refs\/heads\//, "")} (${short(landed.intent.commit)}).`;
500
744
  }
745
+ export function recognisedOnBranch(store, repo, rootId, candidate, read) {
746
+ if (candidate === null || !OID.test(candidate))
747
+ return null;
748
+ const recorded = recordedDestination(store, repo)?.ref ?? null;
749
+ const ref = recorded ?? (() => { const head = read(repo, ["symbolic-ref", "-q", "HEAD"]); return head !== null && head.startsWith("refs/heads/") ? head : null; })();
750
+ if (ref === null || !landableBranch(ref.slice("refs/heads/".length)))
751
+ return null;
752
+ const commits = [candidate, ...handoffsOf(store, repo, rootId).filter(one => one.candidate === candidate && one.ref === ref).map(one => one.commit)];
753
+ return commits.some(commit => read(repo, ["merge-base", "--is-ancestor", commit, ref]) !== null) ? `On ${ref.slice("refs/heads/".length)}` : null;
754
+ }
755
+ export function broughtInOnBranch(store, repo, rootId, read) {
756
+ const landed = landedCommits(store, rootId);
757
+ return handoffsOf(store, repo, rootId).some(one => !landed.has(one.commit) && read(repo, ["merge-base", "--is-ancestor", one.commit, one.ref]) !== null);
758
+ }
@@ -30,6 +30,7 @@ export const LOCAL_OWNER_ACTS = Object.freeze([
30
30
  "memory-review",
31
31
  "request-plan",
32
32
  "retry-build",
33
+ "run-checks",
33
34
  "view-preference",
34
35
  "take-over",
35
36
  "start-thread",
@@ -44,6 +45,7 @@ export const LOCAL_OWNER_ACTS = Object.freeze([
44
45
  "flexible-switch",
45
46
  "ship-thread",
46
47
  "cancel-ship",
48
+ "save-thread",
47
49
  "flexible-sign-in-save",
48
50
  "flexible-sign-in-check",
49
51
  "flexible-sign-in-clear",