toolroll 0.9.118 → 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.
- package/CHANGELOG.md +63 -0
- package/README.md +22 -22
- package/dist/assignment.js +43 -30
- package/dist/browser/workspace.css +1 -1
- package/dist/browser/workspace.js +32 -31
- package/dist/builder.js +288 -237
- package/dist/central-recovery-stage.js +3 -3
- package/dist/check-failure.js +2 -2
- package/dist/check-levels.js +3 -0
- package/dist/check-report.js +58 -7
- package/dist/cli-help.js +1 -0
- package/dist/codex-limits.js +40 -22
- package/dist/contracts/console-api.js +6 -1
- package/dist/contracts/engine-api.js +1 -0
- package/dist/contracts/release-check.js +7 -4
- package/dist/contracts/release-terms.js +11 -2
- package/dist/contracts/verification-receipt.js +1 -1
- package/dist/deploy-gate.js +7 -1
- package/dist/direct-chat.js +3 -3
- package/dist/easy-start.js +8 -6
- package/dist/engine-reads.js +74 -0
- package/dist/flexible-conversation-schema.js +24 -0
- package/dist/flexible-conversation.js +162 -0
- package/dist/flexible-custody.js +3 -0
- package/dist/flexible-import.js +89 -0
- package/dist/flexible-save.js +128 -0
- package/dist/flexible-session.js +93 -13
- package/dist/flexible-ship.js +3 -3
- package/dist/flexible-thread.js +2 -2
- package/dist/install-mode.js +1 -1
- package/dist/local-checks.js +32 -0
- package/dist/local-landing.js +758 -0
- package/dist/local-owner.js +3 -0
- package/dist/operate.js +165 -26
- package/dist/passwordless.js +1 -1
- package/dist/plan-limits-demand.js +48 -0
- package/dist/project-delete.js +1 -0
- package/dist/rehearsal.js +27 -0
- package/dist/release-adapters.js +170 -2
- package/dist/release-approval.js +11 -8
- package/dist/release-card.js +7 -2
- package/dist/release-carry.js +1 -1
- package/dist/release-cli.js +115 -14
- package/dist/release-main-proof.js +49 -0
- package/dist/release-main.js +110 -0
- package/dist/release-recheck.js +10 -3
- package/dist/release.js +221 -33
- package/dist/reply-shape.js +6 -1
- package/dist/result-actions.js +7 -1
- package/dist/result-follow-ups.js +30 -12
- package/dist/review-context.js +2 -1
- package/dist/serve.js +31 -14
- package/dist/server/direct-chat.js +109 -3
- package/dist/server/engine-api.js +65 -6
- package/dist/server/render-results.js +8 -4
- package/dist/server/render-tasks.js +10 -1
- package/dist/server/route-table.js +15 -1
- package/dist/server/send-back-build.js +4 -0
- package/dist/server/settings.js +33 -7
- package/dist/server/task-views.js +20 -0
- package/dist/server/tasks.js +108 -6
- package/dist/settings-groups-ui.js +3 -3
- package/dist/store.js +29 -4
- package/dist/subscription-usage.js +11 -5
- package/dist/surface.js +11 -2
- package/dist/task-base.js +23 -4
- package/dist/task-outcome-cli.js +10 -1
- package/dist/tui/darwin-arm64/toolroll-tui +0 -0
- package/dist/tui/darwin-x64/toolroll-tui +0 -0
- package/dist/tui/linux-arm64/toolroll-tui +0 -0
- package/dist/tui/linux-x64/toolroll-tui +0 -0
- package/dist/verification-evidence.js +20 -7
- package/dist/workspace-ui.js +1 -1
- package/package.json +2 -1
- package/scripts/release-proof.mjs +240 -0
|
@@ -0,0 +1,758 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstatSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { run as execRun } from "./exec.js";
|
|
6
|
+
import { hardenedGit } from "./teardown-git.js";
|
|
7
|
+
import { assignmentOf } from "./assignment.js";
|
|
8
|
+
import { projectCheckSet, quickVerifyKey } from "./check-levels.js";
|
|
9
|
+
import { recordActionWhole } from "./action-ledger.js";
|
|
10
|
+
import { reproveApprover, verifyApproverStanding } from "./principal.js";
|
|
11
|
+
import { localActNow, LOCAL_OWNER_LAPSED } from "./local-owner.js";
|
|
12
|
+
import { publishingOf } from "./pull-request-flow.js";
|
|
13
|
+
import { wholeChangeBaseOf } from "./task-base.js";
|
|
14
|
+
export const LAND_DESTINATION = "land destination";
|
|
15
|
+
export const LAND_INTENT = "land intent";
|
|
16
|
+
export const LAND_SETTLED = "land settled";
|
|
17
|
+
export const LAND_HANDOFF = "land handoff";
|
|
18
|
+
export const LAND_HANDOFF_SETTLED = "land handoff settled";
|
|
19
|
+
function checkBindingsOf(store, repo) {
|
|
20
|
+
return { full: store.liveVerifyCommand(repo)?.digest ?? null, quick: store.liveVerifyCommand(quickVerifyKey(repo))?.digest ?? null,
|
|
21
|
+
setup: store.liveWorktreeSetup(repo)?.digest ?? null, access: String(store.projectCheckAccess(repo)) };
|
|
22
|
+
}
|
|
23
|
+
const OID = /^[0-9a-f]{40}$/;
|
|
24
|
+
const refuse = (reason, message) => ({ ok: false, reason, message });
|
|
25
|
+
const short = (oid) => oid.slice(0, 7);
|
|
26
|
+
const keyOf = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 16);
|
|
27
|
+
export function landableBranch(name) {
|
|
28
|
+
if (name === "" || name === "HEAD" || name.startsWith("-") || name.length > 100 || !/^[A-Za-z0-9._/-]+$/.test(name))
|
|
29
|
+
return false;
|
|
30
|
+
if (name.startsWith("toolroll/"))
|
|
31
|
+
return false;
|
|
32
|
+
return name.split("/").every(part => part !== "" && !part.startsWith(".") && !part.startsWith("-") && !part.endsWith(".lock") && !part.endsWith(".")) && !name.includes("..");
|
|
33
|
+
}
|
|
34
|
+
function commonDirOf(repo) {
|
|
35
|
+
try {
|
|
36
|
+
const dotgit = join(realpathSync(repo), ".git");
|
|
37
|
+
const held = lstatSync(dotgit);
|
|
38
|
+
return held.isDirectory() && !held.isSymbolicLink() ? realpathSync(dotgit) : null;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function gitFor(repo, given) {
|
|
45
|
+
const git = hardenedGit(given ?? execRun, "build", { repo });
|
|
46
|
+
return (args, cwd = repo, timeoutMs = 60_000) => git("git", args, { cwd, timeoutMs });
|
|
47
|
+
}
|
|
48
|
+
function rows(store, where, args) {
|
|
49
|
+
return store.handle.prepare(`SELECT id,at,actor,outcome,detail FROM action_ledger WHERE ${where} ORDER BY id DESC`).all(...args).flatMap(row => {
|
|
50
|
+
try {
|
|
51
|
+
const detail = JSON.parse(String(row["detail"] ?? "null"));
|
|
52
|
+
return detail !== null && typeof detail === "object" ? [{ id: Number(row["id"]), at: String(row["at"]), actor: String(row["actor"]), outcome: String(row["outcome"]), detail: detail }] : [];
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
export function recordedDestination(store, repo) {
|
|
60
|
+
const row = rows(store, "repo = ? AND action = ? AND source = 'request'", [repo, LAND_DESTINATION])[0];
|
|
61
|
+
const ref = row?.detail["ref"], common = row?.detail["common"];
|
|
62
|
+
return typeof ref === "string" && typeof common === "string" ? { ref, common } : null;
|
|
63
|
+
}
|
|
64
|
+
function intentOf(row) {
|
|
65
|
+
const d = row.detail;
|
|
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"])
|
|
67
|
+
|| (d["mode"] !== "files" && d["mode"] !== "ref") || typeof d["key"] !== "string" || (d["kind"] !== "land" && d["kind"] !== "undo"))
|
|
68
|
+
return 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 };
|
|
72
|
+
}
|
|
73
|
+
function intents(store, where, args) {
|
|
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 => {
|
|
75
|
+
try {
|
|
76
|
+
const detail = JSON.parse(String(row["detail"] ?? "null"));
|
|
77
|
+
const one = intentOf({ id: Number(row["id"]), at: String(row["at"]), actor: String(row["actor"]), outcome: String(row["outcome"]), detail,
|
|
78
|
+
repo: String(row["repo"]), task: String(row["task_id"]), run: Number(row["run_id"]) });
|
|
79
|
+
return one === null ? [] : [one];
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return [];
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
function settledOf(store, intent) {
|
|
87
|
+
const row = rows(store, "action = ? AND outcome LIKE ?", [LAND_SETTLED, `${intent}:%`])[0];
|
|
88
|
+
return row === undefined ? null : { outcome: row.outcome.slice(String(intent).length + 1), at: row.at, detail: row.detail };
|
|
89
|
+
}
|
|
90
|
+
export function landingOf(store, rootId) {
|
|
91
|
+
const all = intents(store, "task_id = ?", [rootId]);
|
|
92
|
+
const landed = all.find(one => one.kind === "land" && settledOf(store, one.id)?.outcome.startsWith("landed") === true);
|
|
93
|
+
if (landed === undefined)
|
|
94
|
+
return null;
|
|
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);
|
|
97
|
+
return { intent: landed, at: settledOf(store, landed.id).at, undone };
|
|
98
|
+
}
|
|
99
|
+
async function treeProblem(git, commit) {
|
|
100
|
+
const listed = await git(["ls-tree", "-r", "-z", "--full-tree", commit]);
|
|
101
|
+
if (listed.code !== 0)
|
|
102
|
+
return "its files couldn't be read";
|
|
103
|
+
for (const entry of listed.stdout.split("\0")) {
|
|
104
|
+
if (entry === "")
|
|
105
|
+
continue;
|
|
106
|
+
const match = /^(\d{6}) (\w+) ([0-9a-f]{40})\t(.*)$/s.exec(entry);
|
|
107
|
+
if (match === null)
|
|
108
|
+
return "its files couldn't be read";
|
|
109
|
+
const [, mode, , oid, path] = match;
|
|
110
|
+
if (mode === "160000")
|
|
111
|
+
return "it holds a submodule";
|
|
112
|
+
if (path === ".gitattributes" || path.endsWith("/.gitattributes")) {
|
|
113
|
+
const blob = await git(["cat-file", "blob", oid]);
|
|
114
|
+
if (blob.code !== 0)
|
|
115
|
+
return "its .gitattributes couldn't be read";
|
|
116
|
+
if (/\b(filter|working-tree-encoding)\s*=/.test(blob.stdout) || /(^|\s)filter(\s|$)/m.test(blob.stdout))
|
|
117
|
+
return "its files use a Git filter (like Git LFS) or an encoding";
|
|
118
|
+
}
|
|
119
|
+
if (path === ".gitmodules")
|
|
120
|
+
return "it holds a submodule";
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
async function checkoutsOn(git, ref) {
|
|
125
|
+
const listed = await git(["worktree", "list", "--porcelain", "-z"]);
|
|
126
|
+
if (listed.code !== 0)
|
|
127
|
+
return null;
|
|
128
|
+
const found = [];
|
|
129
|
+
let path = null;
|
|
130
|
+
for (const line of listed.stdout.split("\0")) {
|
|
131
|
+
if (line.startsWith("worktree "))
|
|
132
|
+
path = line.slice("worktree ".length);
|
|
133
|
+
else if (line === `branch ${ref}` && path !== null) {
|
|
134
|
+
try {
|
|
135
|
+
found.push(realpathSync(path));
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
found.push(path);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return found;
|
|
143
|
+
}
|
|
144
|
+
async function placeOf(git, project, ref, old) {
|
|
145
|
+
const branch = ref.slice("refs/heads/".length);
|
|
146
|
+
const symbolic = await git(["symbolic-ref", "-q", ref]);
|
|
147
|
+
if (symbolic.code === 0)
|
|
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.` };
|
|
149
|
+
if (symbolic.code !== 1)
|
|
150
|
+
return { kind: "problem", reason: "git", message: `Toolroll couldn't read ${branch}.` };
|
|
151
|
+
if (old !== null) {
|
|
152
|
+
const read = await git(["rev-parse", "--verify", "-q", `${ref}^{commit}`]);
|
|
153
|
+
if (read.code !== 0 || read.stdout.trim() !== old)
|
|
154
|
+
return { kind: "problem", reason: "moved", message: `${branch} moved since you looked. Look again, then land it.` };
|
|
155
|
+
}
|
|
156
|
+
const on = await checkoutsOn(git, ref);
|
|
157
|
+
if (on === null)
|
|
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);
|
|
164
|
+
}
|
|
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)}`;
|
|
174
|
+
}
|
|
175
|
+
function projectOf(store, repo) {
|
|
176
|
+
if (repo === null || !store.knownRepos().includes(repo))
|
|
177
|
+
return null;
|
|
178
|
+
const common = commonDirOf(repo);
|
|
179
|
+
return common === null ? null : { repo, common };
|
|
180
|
+
}
|
|
181
|
+
export function publishesThroughPullRequests(store, repo) {
|
|
182
|
+
try {
|
|
183
|
+
return publishingOf(store, repo).on || store.publicationGrantFor(repo) !== null;
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
return true;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
export const PULL_REQUESTS_INSTEAD = "This project publishes through pull requests; open one from the task instead.";
|
|
190
|
+
const ALREADY_MSG = (ref, commit) => `Already on ${ref.replace(/^refs\/heads\//, "")} (${short(commit)}).`;
|
|
191
|
+
export async function readLanding(store, taskId, access, now, options) {
|
|
192
|
+
const assignment = assignmentOf(store, taskId, now, { principal: "operator", repos: access.repos, includeUnplaced: false }, options.root);
|
|
193
|
+
if (assignment === null)
|
|
194
|
+
return refuse("not-found", `No task \`${taskId}\` in your projects.`);
|
|
195
|
+
if (assignment.repo !== null && publishesThroughPullRequests(store, assignment.repo))
|
|
196
|
+
return refuse("pull-requests", PULL_REQUESTS_INSTEAD);
|
|
197
|
+
const project = projectOf(store, assignment.repo);
|
|
198
|
+
if (project === null)
|
|
199
|
+
return refuse("destination", "This task's project isn't a local Git folder Toolroll can land in.");
|
|
200
|
+
const git = gitFor(project.repo, options.git);
|
|
201
|
+
if (options.undo === true)
|
|
202
|
+
return readUndo(store, assignment.rootId, project, git, options);
|
|
203
|
+
const receipt = assignment.receipt;
|
|
204
|
+
if (assignment.state !== "complete" || assignment.completion === null || receipt === null)
|
|
205
|
+
return refuse("not-complete", "Accept it first: only accepted work lands.");
|
|
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.");
|
|
209
|
+
const candidate = receipt.head;
|
|
210
|
+
if (candidate === null || !OID.test(candidate) || receipt.completionKind === "research-report")
|
|
211
|
+
return refuse("nothing", "This result has no commit to land.");
|
|
212
|
+
const landed = landingOf(store, assignment.rootId);
|
|
213
|
+
if (landed !== null && !landed.undone && landed.intent.candidate === candidate)
|
|
214
|
+
return { ok: true, landed: { at: landed.at, ref: landed.intent.ref, commit: landed.intent.commit, mode: landed.intent.mode } };
|
|
215
|
+
const checks = receipt.checks.status === "passed" ? "passed" : !projectCheckSet(store, project.repo) && receipt.checks.status === "not-run" ? "none" : null;
|
|
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
|
+
}
|
|
223
|
+
const destination = await destinationOf(store, project, git, options.into);
|
|
224
|
+
if (!destination.ok)
|
|
225
|
+
return destination;
|
|
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) });
|
|
232
|
+
}
|
|
233
|
+
async function destinationOf(store, project, git, into) {
|
|
234
|
+
const recorded = recordedDestination(store, project.repo);
|
|
235
|
+
if (into !== undefined) {
|
|
236
|
+
if (!landableBranch(into))
|
|
237
|
+
return refuse("destination", `\`${into}\` isn't a branch Toolroll can land on.`);
|
|
238
|
+
const ref = `refs/heads/${into}`;
|
|
239
|
+
return { ok: true, ref, recorded: recorded?.ref === ref && recorded.common === project.common };
|
|
240
|
+
}
|
|
241
|
+
if (recorded !== null && recorded.common === project.common)
|
|
242
|
+
return { ok: true, ref: recorded.ref, recorded: true };
|
|
243
|
+
const head = await git(["symbolic-ref", "-q", "HEAD"]);
|
|
244
|
+
const ref = head.stdout.trim();
|
|
245
|
+
if (head.code !== 0 || !ref.startsWith("refs/heads/") || !landableBranch(ref.slice("refs/heads/".length))) {
|
|
246
|
+
return refuse("destination", "Your project folder isn't on a branch Toolroll can land on. Name one: --into <branch>.");
|
|
247
|
+
}
|
|
248
|
+
return { ok: true, ref, recorded: false };
|
|
249
|
+
}
|
|
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 };
|
|
271
|
+
}
|
|
272
|
+
async function planFor(git, project, destination, fixed, squashing = null) {
|
|
273
|
+
const { ref } = destination;
|
|
274
|
+
const branch = ref.slice("refs/heads/".length);
|
|
275
|
+
const read = await git(["rev-parse", "--verify", "-q", `${ref}^{commit}`]);
|
|
276
|
+
const old = read.stdout.trim();
|
|
277
|
+
if (read.code !== 0 || !OID.test(old))
|
|
278
|
+
return refuse("destination", `There's no branch \`${branch}\` in this project.`);
|
|
279
|
+
if (fixed.candidate !== null) {
|
|
280
|
+
if (old === fixed.candidate)
|
|
281
|
+
return refuse("nothing", ALREADY_MSG(ref, old));
|
|
282
|
+
const type = await git(["cat-file", "-t", fixed.candidate]);
|
|
283
|
+
if (type.code !== 0 || type.stdout.trim() !== "commit")
|
|
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
|
+
}
|
|
289
|
+
const ancestor = await git(["merge-base", "--is-ancestor", old, fixed.candidate]);
|
|
290
|
+
if (ancestor.code === 1) {
|
|
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.`);
|
|
293
|
+
}
|
|
294
|
+
if (ancestor.code !== 0)
|
|
295
|
+
return refuse("git", "Toolroll couldn't compare the commits.");
|
|
296
|
+
const problem = await treeProblem(git, fixed.candidate) ?? await treeProblem(git, old);
|
|
297
|
+
if (problem !== null)
|
|
298
|
+
return refuse("unsupported", `This project can't be landed by Toolroll: ${problem}. Land it with git yourself.`);
|
|
299
|
+
}
|
|
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 };
|
|
318
|
+
return { ok: true, plan: { ...plan, key: keyOf({ v: 1, ...plan, common: project.common }) } };
|
|
319
|
+
}
|
|
320
|
+
async function readUndo(store, rootId, project, git, options) {
|
|
321
|
+
void options;
|
|
322
|
+
const landed = landingOf(store, rootId);
|
|
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)}}`);
|
|
357
|
+
}
|
|
358
|
+
export function landingWords(plan) {
|
|
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`;
|
|
361
|
+
if (plan.kind === "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."];
|
|
364
|
+
}
|
|
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.",
|
|
370
|
+
...(plan.recorded ? [] : [`Toolroll remembers ${plan.branch} as where this project's work lands.`])];
|
|
371
|
+
}
|
|
372
|
+
async function settleUnfinished(store, repo, now, options) {
|
|
373
|
+
const project = projectOf(store, repo);
|
|
374
|
+
if (project === null)
|
|
375
|
+
return;
|
|
376
|
+
const git = gitFor(repo, options.git);
|
|
377
|
+
for (const intent of intents(store, "repo = ?", [repo]).filter(one => settledOf(store, one.id) === null)) {
|
|
378
|
+
const symbolic = await git(["symbolic-ref", "-q", intent.ref]);
|
|
379
|
+
const read = await git(["rev-parse", "--verify", "-q", `${intent.ref}^{commit}`]);
|
|
380
|
+
const at = read.stdout.trim();
|
|
381
|
+
let outcome, words;
|
|
382
|
+
if (symbolic.code !== 1) {
|
|
383
|
+
outcome = "needs-person";
|
|
384
|
+
words = `${intent.ref.replace(/^refs\/heads\//, "")} now points at another branch or can't be read. Look at ${repo} with git log.`;
|
|
385
|
+
}
|
|
386
|
+
else if (at === intent.old) {
|
|
387
|
+
outcome = "abandoned";
|
|
388
|
+
words = "It stopped before the branch moved; nothing changed.";
|
|
389
|
+
}
|
|
390
|
+
else if (at === intent.commit && intent.mode === "files") {
|
|
391
|
+
outcome = "needs-person";
|
|
392
|
+
words = `The branch moved to ${short(intent.commit)}; check your folder's files with git status in ${repo}.`;
|
|
393
|
+
}
|
|
394
|
+
else if (at === intent.commit) {
|
|
395
|
+
outcome = "landed:recovered";
|
|
396
|
+
words = "It had finished; recorded now.";
|
|
397
|
+
}
|
|
398
|
+
else {
|
|
399
|
+
outcome = "needs-person";
|
|
400
|
+
words = `The branch is at ${OID.test(at) ? short(at) : "an unreadable commit"} now, neither before nor after the landing. Look at ${repo} with git log.`;
|
|
401
|
+
}
|
|
402
|
+
recordActionWhole(store.handle, { at: now.toISOString(), actor: "toolroll", repo, taskId: intent.task, runId: intent.run, action: LAND_SETTLED, outcome: `${intent.id}:${outcome}`, source: "work" }, { v: 1, words });
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
function standing(store, authority, repo) {
|
|
406
|
+
if (authority.kind === "local") {
|
|
407
|
+
const local = localActNow(store, "land-task");
|
|
408
|
+
if (local === null)
|
|
409
|
+
return refuse("authority", LOCAL_OWNER_LAPSED);
|
|
410
|
+
const proved = verifyApproverStanding(store, local.account, local.accountGeneration, store.knownRepos().filter(one => store.accountCanAccess(local.account, one)));
|
|
411
|
+
if (!proved.ok || !store.accountCanAccess(local.account, repo))
|
|
412
|
+
return refuse("authority", LOCAL_OWNER_LAPSED);
|
|
413
|
+
return { ok: true, actor: `operator:${local.account}` };
|
|
414
|
+
}
|
|
415
|
+
const proved = reproveApprover(store, authority.who);
|
|
416
|
+
if (!proved.ok || !authority.who.repos.includes(repo) || !store.accountCanAccess(authority.who.name, repo))
|
|
417
|
+
return refuse("authority", "Your access changed. Sign in again.");
|
|
418
|
+
return { ok: true, actor: `operator:${authority.who.name}` };
|
|
419
|
+
}
|
|
420
|
+
const projectLocks = new Map();
|
|
421
|
+
async function locked(repo, body) {
|
|
422
|
+
const before = projectLocks.get(repo) ?? Promise.resolve();
|
|
423
|
+
let release;
|
|
424
|
+
const mine = new Promise(resolve => { release = resolve; });
|
|
425
|
+
const chained = before.then(() => mine);
|
|
426
|
+
projectLocks.set(repo, chained);
|
|
427
|
+
await before.catch(() => undefined);
|
|
428
|
+
try {
|
|
429
|
+
return await body();
|
|
430
|
+
}
|
|
431
|
+
finally {
|
|
432
|
+
release();
|
|
433
|
+
if (projectLocks.get(repo) === chained)
|
|
434
|
+
projectLocks.delete(repo);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
export async function land(store, taskId, input, authority, access, now, options) {
|
|
438
|
+
if (!/^[0-9a-f]{16}$/.test(input.key))
|
|
439
|
+
return refuse("stale", "That landing isn't the one on screen. Look again, then land it.");
|
|
440
|
+
const ref = store.lookupRef(taskId);
|
|
441
|
+
const repo = ref?.repo ?? null;
|
|
442
|
+
if (repo === null || (access.repos !== null && !access.repos.includes(repo)))
|
|
443
|
+
return refuse("not-found", `No task \`${taskId}\` in your projects.`);
|
|
444
|
+
const first = standing(store, authority, repo);
|
|
445
|
+
if (!first.ok)
|
|
446
|
+
return first;
|
|
447
|
+
if (publishesThroughPullRequests(store, repo))
|
|
448
|
+
return refuse("pull-requests", PULL_REQUESTS_INSTEAD);
|
|
449
|
+
const named = input.into !== undefined && landableBranch(input.into) ? `refs/heads/${input.into}` : recordedDestination(store, repo)?.ref ?? null;
|
|
450
|
+
if (named !== null && projectOf(store, repo) !== null) {
|
|
451
|
+
const symbolic = await gitFor(repo, options.git)(["symbolic-ref", "-q", named]);
|
|
452
|
+
if (symbolic.code === 0)
|
|
453
|
+
return refuse("destination", `${named.replace(/^refs\/heads\//, "")} points at another branch, so Toolroll won't move it. Land it with git yourself.`);
|
|
454
|
+
}
|
|
455
|
+
return locked(repo, async () => {
|
|
456
|
+
const done = intents(store, "repo = ? AND task_id IS NOT NULL", [repo]).find(one => one.key === input.key);
|
|
457
|
+
if (done !== undefined) {
|
|
458
|
+
const settled = settledOf(store, done.id);
|
|
459
|
+
if (settled?.outcome.startsWith("landed") === true) {
|
|
460
|
+
const who = standing(store, authority, repo);
|
|
461
|
+
if (!who.ok)
|
|
462
|
+
return who;
|
|
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 };
|
|
464
|
+
}
|
|
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
|
+
}
|
|
483
|
+
await settleUnfinished(store, repo, now, options);
|
|
484
|
+
const read = await readLanding(store, taskId, access, now, { ...options, ...(input.into === undefined ? {} : { into: input.into }), ...(input.undo === true ? { undo: true } : {}) });
|
|
485
|
+
if (!read.ok)
|
|
486
|
+
return read;
|
|
487
|
+
if (!("plan" in read))
|
|
488
|
+
return refuse("nothing", ALREADY_MSG(read.landed.ref, read.landed.commit));
|
|
489
|
+
const plan = read.plan;
|
|
490
|
+
if (plan.key !== input.key)
|
|
491
|
+
return refuse("stale", "Something changed since you looked (the branch, the checks or the result). Look again, then land it.");
|
|
492
|
+
const project = projectOf(store, plan.repo);
|
|
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
|
+
}
|
|
498
|
+
const stillStands = () => {
|
|
499
|
+
const who = standing(store, authority, plan.repo);
|
|
500
|
+
if (!who.ok)
|
|
501
|
+
return who;
|
|
502
|
+
if (publishesThroughPullRequests(store, plan.repo))
|
|
503
|
+
return refuse("pull-requests", PULL_REQUESTS_INSTEAD);
|
|
504
|
+
if (plan.kind === "land") {
|
|
505
|
+
const again = assignmentOf(store, taskId, now, { principal: "operator", repos: access.repos }, options.root);
|
|
506
|
+
if (again?.state !== "complete" || again.receipt?.digest !== plan.receipt || again.completion?.digest !== plan.completion)
|
|
507
|
+
return refuse("stale", "This result changed since you looked. Look again, then land it.");
|
|
508
|
+
}
|
|
509
|
+
else {
|
|
510
|
+
const landed = landingOf(store, plan.rootId);
|
|
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)
|
|
513
|
+
return refuse("stale", "That landing changed since you looked. Look again.");
|
|
514
|
+
}
|
|
515
|
+
if (JSON.stringify(checkBindingsOf(store, plan.repo)) !== JSON.stringify(plan.bindings))
|
|
516
|
+
return refuse("stale", "The project's checks changed since you looked. Look again, then land it.");
|
|
517
|
+
return who;
|
|
518
|
+
};
|
|
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) } };
|
|
566
|
+
}
|
|
567
|
+
let intentId;
|
|
568
|
+
try {
|
|
569
|
+
intentId = store.transact(() => {
|
|
570
|
+
const who = stillStands();
|
|
571
|
+
if (!who.ok)
|
|
572
|
+
throw new Refused(who);
|
|
573
|
+
if (intents(store, "repo = ?", [plan.repo]).some(one => settledOf(store, one.id) === null))
|
|
574
|
+
throw new Refused(refuse("busy", "Another landing in this project hasn't finished. Try again in a moment."));
|
|
575
|
+
if (!plan.recorded)
|
|
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 });
|
|
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 }) });
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
catch (error) {
|
|
582
|
+
if (error instanceof Refused)
|
|
583
|
+
return error.result;
|
|
584
|
+
throw error;
|
|
585
|
+
}
|
|
586
|
+
const settle = (outcome, words) => recordActionWhole(store.handle, { at: now.toISOString(), actor: "toolroll", repo: plan.repo, taskId: plan.rootId, runId: plan.runId,
|
|
587
|
+
action: LAND_SETTLED, outcome: `${intentId}:${outcome}`, source: "work" }, { v: 1, words });
|
|
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);
|
|
593
|
+
}
|
|
594
|
+
const last = store.transact(stillStands);
|
|
595
|
+
if (!last.ok) {
|
|
596
|
+
settle("refused", last.message);
|
|
597
|
+
return last;
|
|
598
|
+
}
|
|
599
|
+
const swapped = await git(["update-ref", "--no-deref", "-m", `toolroll: land ${plan.taskId}`, plan.ref, commit, plan.old]);
|
|
600
|
+
if (swapped.code !== 0) {
|
|
601
|
+
const words = `${plan.branch} moved while landing, so nothing changed. Look again, then land it.`;
|
|
602
|
+
settle("refused", words);
|
|
603
|
+
return refuse("moved", words);
|
|
604
|
+
}
|
|
605
|
+
settle("landed", plan.kind === "undo" ? "Undone." : "Landed.");
|
|
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;
|
|
632
|
+
});
|
|
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
|
+
}
|
|
672
|
+
class Refused extends Error {
|
|
673
|
+
result;
|
|
674
|
+
constructor(result) {
|
|
675
|
+
super(result.message);
|
|
676
|
+
this.result = result;
|
|
677
|
+
}
|
|
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
|
+
}
|
|
706
|
+
async function revertCommit(git, plan, scratch) {
|
|
707
|
+
const reverts = plan.reverts;
|
|
708
|
+
const folder = mkdtempSync(join(scratch ?? tmpdir(), "toolroll-undo-"));
|
|
709
|
+
const checkout = join(folder, "checkout");
|
|
710
|
+
let added = false;
|
|
711
|
+
try {
|
|
712
|
+
const add = await git(["worktree", "add", "--detach", checkout, plan.old]);
|
|
713
|
+
added = add.code === 0;
|
|
714
|
+
if (!added)
|
|
715
|
+
return refuse("git", "Toolroll couldn't make a temporary checkout for the undo.");
|
|
716
|
+
const identity = ["-c", "user.name=Toolroll", "-c", "user.email=undo@toolroll.invalid", "-c", "commit.gpgsign=false", "-c", "core.hooksPath=/dev/null"];
|
|
717
|
+
const reverted = await git([...identity, "revert", "--no-edit", "--no-commit", `${reverts.old}..${reverts.landed}`], checkout);
|
|
718
|
+
if (reverted.code !== 0) {
|
|
719
|
+
await git(["revert", "--abort"], checkout);
|
|
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}`}`);
|
|
723
|
+
}
|
|
724
|
+
const committed = await git([...identity, "commit", "--no-verify", "--allow-empty", "-m", `Undo landing of ${plan.taskId} (${short(reverts.old)}..${short(reverts.landed)})`], checkout);
|
|
725
|
+
const head = await git(["rev-parse", "--verify", "-q", "HEAD^{commit}"], checkout);
|
|
726
|
+
const commit = head.stdout.trim();
|
|
727
|
+
if (committed.code !== 0 || head.code !== 0 || !OID.test(commit))
|
|
728
|
+
return refuse("git", "Toolroll couldn't make the undo commit.");
|
|
729
|
+
return { ok: true, commit };
|
|
730
|
+
}
|
|
731
|
+
finally {
|
|
732
|
+
if (added)
|
|
733
|
+
await git(["worktree", "remove", checkout]).catch(() => null);
|
|
734
|
+
rmSync(folder, { recursive: true, force: true });
|
|
735
|
+
await git(["worktree", "prune"]).catch(() => null);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
export function landedWords(store, rootId) {
|
|
739
|
+
const landed = landingOf(store, rootId);
|
|
740
|
+
if (landed === null)
|
|
741
|
+
return null;
|
|
742
|
+
return landed.undone ? `Landed on ${landed.intent.ref.replace(/^refs\/heads\//, "")} (${short(landed.intent.commit)}), then undone.`
|
|
743
|
+
: `Landed on ${landed.intent.ref.replace(/^refs\/heads\//, "")} (${short(landed.intent.commit)}).`;
|
|
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
|
+
}
|