toolroll 0.9.108 → 0.9.110
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 +69 -0
- package/dist/advanced-view.js +0 -1
- package/dist/agent-detect.js +244 -0
- package/dist/agent-fence.js +47 -5
- package/dist/agent-state.js +5 -2
- package/dist/agentconfig.js +2 -2
- package/dist/approval-summary.js +344 -0
- package/dist/assignment-ui.js +5 -5
- package/dist/assignment.js +5 -2
- package/dist/attest.js +2 -2
- package/dist/browser/terminal.js +1 -1
- package/dist/browser/workspace.css +2 -2
- package/dist/browser/workspace.js +37 -34
- package/dist/browser-crew.js +4 -4
- package/dist/browser-workspace.js +4 -11
- package/dist/builder.js +45 -3
- package/dist/chat-actions.js +24 -17
- package/dist/chat-controls.js +6 -5
- package/dist/chat-core.js +3 -1
- package/dist/chat-decide.js +102 -47
- package/dist/chat-delivery-state.js +2 -0
- package/dist/chat-delivery.js +3 -2
- package/dist/chat-live.js +2 -1
- package/dist/chat-quiet.js +3 -3
- package/dist/chat-task-actions.js +6 -0
- package/dist/chat-voice.js +2 -2
- package/dist/check-report.js +1 -1
- package/dist/cli-help.js +12 -13
- package/dist/cli.js +6 -3
- package/dist/console-chrome.js +10 -3
- package/dist/console-instance.js +10 -1
- package/dist/contracts/console-api.js +14 -8
- package/dist/contracts/engine-api.js +271 -0
- package/dist/contracts/handoff.js +4 -0
- package/dist/coordinator.js +2 -2
- package/dist/decision.js +17 -0
- package/dist/demo-chat.js +1 -1
- package/dist/demo.js +6 -0
- package/dist/design/kit.js +4 -3
- package/dist/discord-api.js +4 -3
- package/dist/discord-chat.js +3 -1
- package/dist/dispatch.js +3 -8
- package/dist/easy-start-args.js +7 -3
- package/dist/easy-start.js +25 -0
- package/dist/egress.js +72 -10
- package/dist/engine-handoff.js +34 -0
- package/dist/engine-reads.js +261 -0
- package/dist/eval-world.js +3 -2
- package/dist/evidence.js +2 -0
- package/dist/fast-start.js +55 -14
- package/dist/fast-terms.js +2 -2
- package/dist/first-run.js +10 -2
- package/dist/flexible-agents.js +234 -0
- package/dist/flexible-answers-schema.js +61 -0
- package/dist/flexible-answers.js +889 -0
- package/dist/flexible-available.js +1 -0
- package/dist/flexible-custody.js +494 -0
- package/dist/flexible-import.js +782 -0
- package/dist/flexible-launch-schema.js +72 -0
- package/dist/flexible-launch.js +331 -0
- package/dist/flexible-launcher.js +88 -0
- package/dist/flexible-levels.js +34 -0
- package/dist/flexible-merge-guard.js +47 -0
- package/dist/flexible-refs.js +47 -0
- package/dist/flexible-relay-cancel.js +19 -0
- package/dist/flexible-relay-schema.js +55 -0
- package/dist/flexible-relay-upstreams.js +36 -0
- package/dist/flexible-relay.js +1032 -0
- package/dist/flexible-schema.js +32 -0
- package/dist/flexible-session.js +732 -0
- package/dist/flexible-ship-schema.js +81 -0
- package/dist/flexible-ship.js +694 -0
- package/dist/flexible-start.js +80 -0
- package/dist/flexible-thread-schema.js +30 -0
- package/dist/flexible-thread.js +676 -0
- package/dist/flexible-turns-schema.js +69 -0
- package/dist/flexible-turns.js +490 -0
- package/dist/flexible-ui.js +44 -0
- package/dist/flexible.js +368 -0
- package/dist/flow-actions.js +6 -4
- package/dist/flow-steps.js +1 -1
- package/dist/flows-cli.js +2 -1
- package/dist/git-views.js +44 -41
- package/dist/guides.js +11 -10
- package/dist/install-mode.js +225 -0
- package/dist/keymap.js +1 -1
- package/dist/lead-context.js +1 -1
- package/dist/lead-doors.js +7 -1
- package/dist/limits-ui.js +8 -1
- package/dist/live-bus.js +70 -13
- package/dist/live-reply.js +6 -0
- package/dist/live-terminal.js +425 -29
- package/dist/local-owner.js +6 -0
- package/dist/model-choices.js +12 -6
- package/dist/needs-you.js +3 -3
- package/dist/nightly-github.js +2 -2
- package/dist/notification-delivery.js +11 -0
- package/dist/operate.js +185 -33
- package/dist/outbound-privacy.js +204 -0
- package/dist/passwordless.js +2 -1
- package/dist/project-delete-ui.js +2 -1
- package/dist/project-delete.js +15 -0
- package/dist/provider-auth.js +1 -1
- package/dist/provider-connection.js +5 -3
- package/dist/publish.js +5 -0
- package/dist/pull-request-flow.js +26 -7
- package/dist/push.js +5 -1
- package/dist/release-card.js +11 -3
- package/dist/release.js +11 -1
- package/dist/result-actions.js +3 -0
- package/dist/result-evidence-readers.js +8 -2
- package/dist/result-review.js +20 -9
- package/dist/route-store.js +2 -2
- package/dist/sandbox-launch.js +32 -8
- package/dist/sandbox-runtime.js +16 -7
- package/dist/sandbox-tools.js +176 -0
- package/dist/scope.js +12 -36
- package/dist/scout-net.js +7 -2
- package/dist/serve.js +90 -40
- package/dist/server/chat.js +9 -9
- package/dist/server/chrome.js +19 -17
- package/dist/server/console.css +33 -6
- package/dist/server/engine-api.js +378 -0
- package/dist/server/flows.js +2 -2
- package/dist/server/guards.js +10 -4
- package/dist/server/home.js +37 -5
- package/dist/server/http.js +11 -2
- package/dist/server/in-place.js +5 -4
- package/dist/server/kit.js +2 -2
- package/dist/server/link-redemption.js +52 -0
- package/dist/server/live.js +100 -10
- package/dist/server/mutation-key.js +21 -7
- package/dist/server/pages.js +129 -74
- package/dist/server/people-tokens.js +17 -41
- package/dist/server/render-chat.js +2 -1
- package/dist/server/render-history.js +18 -4
- package/dist/server/render-new-task.js +4 -4
- package/dist/server/render-pages.js +21 -39
- package/dist/server/render-people.js +2 -2
- package/dist/server/render-projects.js +5 -5
- package/dist/server/render-results.js +30 -14
- package/dist/server/render-tasks.js +155 -155
- package/dist/server/retired-routes.js +37 -4
- package/dist/server/route-policy.js +8 -0
- package/dist/server/route-table.js +43 -5
- package/dist/server/settings-computers.js +140 -0
- package/dist/server/settings-scripts.js +15 -0
- package/dist/server/settings-section-table.js +59 -0
- package/dist/server/settings-sections.js +291 -0
- package/dist/server/settings.js +247 -28
- package/dist/server/task-views.js +55 -15
- package/dist/server/tasks.js +168 -98
- package/dist/server/terminals.js +181 -28
- package/dist/server/welcome.js +40 -14
- package/dist/settings-groups-ui.js +26 -107
- package/dist/settings-proofs.js +18 -11
- package/dist/slack-api.js +4 -3
- package/dist/slack-chat.js +5 -3
- package/dist/spend.js +46 -12
- package/dist/sqlite-telemetry.js +70 -21
- package/dist/status-probe.js +343 -0
- package/dist/store.js +206 -10
- package/dist/task-link.js +64 -0
- package/dist/teams-api.js +4 -3
- package/dist/teams-chat.js +4 -2
- package/dist/telegram-lead.js +2 -1
- package/dist/telegram-live.js +2 -1
- package/dist/telegram-team.js +2 -1
- package/dist/telegram.js +17 -5
- package/dist/trusted-path.js +162 -0
- 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/tui-launch.js +282 -0
- package/dist/tui-source.js +5 -3
- package/dist/tui.js +2 -2
- package/dist/typed-words-schema.js +18 -0
- package/dist/webhooks.js +8 -4
- package/dist/welcome-facts.js +25 -17
- package/dist/work-index.js +126 -29
- package/dist/work-reads.js +279 -0
- package/dist/workspace-ui.js +5 -0
- package/package.json +4 -2
- package/scripts/crash-canary.mjs +1 -1
- package/scripts/pilot.mjs +1 -1
- package/scripts/provider-canary.mjs +5 -3
|
@@ -0,0 +1,694 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
|
|
4
|
+
import { FLEXIBLE_UNAVAILABLE, flexibleNetworkOf, flexibleStanding, flexibleTwoPerson } from "./flexible.js";
|
|
5
|
+
import { flexibleThread, flexibleThreadBranch, withFlexibleThreadLock } from "./flexible-thread.js";
|
|
6
|
+
import { flexibleImportRef, flexibleTaskBranch, importFlexibleCandidate, readFlexibleCandidate, removeFlexibleImportRefs, settleInterruptedImport } from "./flexible-import.js";
|
|
7
|
+
import { unsettledLaunch } from "./flexible-launch.js";
|
|
8
|
+
import { shipSummaryOf } from "./approval-summary.js";
|
|
9
|
+
import { canonicalJson } from "./canonical-json.js";
|
|
10
|
+
import { approvalOf, approve, authenticateApprover, machineActing, parseAcceptanceCriteria, proposeGuarded } from "./scope.js";
|
|
11
|
+
import { personProof } from "./person-proof.js";
|
|
12
|
+
import { fileTaskProposal } from "./proposal.js";
|
|
13
|
+
import { validateTaskText } from "./task-text.js";
|
|
14
|
+
import { taskBranch } from "./names.js";
|
|
15
|
+
import { verifyApproverStanding } from "./principal.js";
|
|
16
|
+
import { assignmentOf } from "./assignment.js";
|
|
17
|
+
import { completeAndOpenPullRequest, mergePullRequest } from "./pull-request-flow.js";
|
|
18
|
+
import { fullCheckGate } from "./result-follow-ups.js";
|
|
19
|
+
import { runCheckLevel } from "./check-levels.js";
|
|
20
|
+
import { FLEXIBLE_FILED_PREFIX } from "./flexible-merge-guard.js";
|
|
21
|
+
import { run } from "./exec.js";
|
|
22
|
+
import { verificationEvidence } from "./verification-evidence.js";
|
|
23
|
+
import { readVerificationView } from "./contracts/verification-view.js";
|
|
24
|
+
import { hardenedGit } from "./teardown-git.js";
|
|
25
|
+
export const FLEXIBLE_SHIP_VERSION = 1;
|
|
26
|
+
export const SHIP_OUT_OF_SCOPE = "Verify the imported candidate only. Further code changes need a new Ship.";
|
|
27
|
+
export const HISTORY_WORDS = "This thread could read your repository's full history, not just the commit it started from: it reads your repository's stored objects, read-only.";
|
|
28
|
+
const OPEN_HISTORY_WORDS = "This project's network is open, so the thread could have sent what it read, that history included, to any website.";
|
|
29
|
+
export const MERGE_WORDS = "Toolroll merges it by itself once the project's checks pass on this exact commit. A failed or missing check never merges it. A change to the result, your cancel, or your access changing stops the merge.";
|
|
30
|
+
const DEFAULT_TITLE = "Changes from a Flexible thread";
|
|
31
|
+
const DEFAULT_GOAL = "Ship the thread's committed changes once the project's checks pass on them.";
|
|
32
|
+
const DEFAULT_ACCEPTANCE = Object.freeze([{ id: "c1", statement: "The project's checks pass on this exact commit.", how: null, evidence: ["check"] }]);
|
|
33
|
+
export const flexibleShipDigestOf = (terms) => createHash("sha256").update(`standing-orders:flexible-ship:${canonicalJson(terms)}`, "utf8").digest("hex").slice(0, 32);
|
|
34
|
+
export const flexibleShipTaskId = (digest) => `flexible-${digest}`;
|
|
35
|
+
const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
|
|
36
|
+
export function flexibleShipSummary(terms, digest) {
|
|
37
|
+
const shown = terms.changedPaths.slice(0, 50);
|
|
38
|
+
const decisions = [
|
|
39
|
+
{ label: "Task", words: terms.title, fields: ["ship.title"] },
|
|
40
|
+
{ label: "Ships", words: `${plural(terms.changedPaths.length, "changed file")} from this thread, as commit ${terms.candidate.slice(0, 12)}`,
|
|
41
|
+
lines: terms.changedPaths.length > shown.length ? [...shown, `and ${terms.changedPaths.length - shown.length} more`] : shown, fields: ["ship.candidate", "ship.changedPaths"] },
|
|
42
|
+
{ label: "Starts from", words: `commit ${terms.base.slice(0, 12)}, where the thread started`, fields: ["ship.base"] },
|
|
43
|
+
{ label: "Goal", words: terms.goal, fields: ["goal"] },
|
|
44
|
+
{ label: "Done when", words: terms.acceptance.map(one => one.statement).join(" "), fields: ["acceptance"] },
|
|
45
|
+
{ label: "Checks", words: `${terms.check.command} runs on this exact commit. It can't be skipped.`, fields: ["ship.check"] },
|
|
46
|
+
{ label: "Merges", words: MERGE_WORDS, fields: ["ship.merge"] },
|
|
47
|
+
{ label: "Merges into", words: `${terms.github.repo}, branch ${terms.github.base}, by ${terms.github.method}`,
|
|
48
|
+
lines: [`Toolroll may ${terms.github.capabilities.map(one => one.replace(/-/g, " ")).join(", ")} there${terms.github.draft ? ", as a draft" : ""}, through ${terms.github.remote}.`], fields: ["ship.github"] },
|
|
49
|
+
{ label: "Further changes", words: "Need a new Ship.", fields: ["outOfScope"] },
|
|
50
|
+
];
|
|
51
|
+
const warnings = [{ words: HISTORY_WORDS, fields: ["ship.history"] },
|
|
52
|
+
...(terms.network === "open" ? [{ words: OPEN_HISTORY_WORDS, fields: ["ship.network"] }] : [])];
|
|
53
|
+
return shipSummaryOf(digest, decisions, warnings);
|
|
54
|
+
}
|
|
55
|
+
const WORDS = Object.freeze({
|
|
56
|
+
"not-available": FLEXIBLE_UNAVAILABLE,
|
|
57
|
+
"thread-unknown": "There's no such thread.",
|
|
58
|
+
"not-owner": "Only the person who started this thread can do that. Nothing changed.",
|
|
59
|
+
"not-an-approver": "Only an approver for this project can do that. Nothing changed.",
|
|
60
|
+
"stale-generation": "Your account changed since this started. Sign in again and retry. Nothing changed.",
|
|
61
|
+
"two-person": "This project needs two people to approve work, so a Flexible thread can't ship from it. Nothing changed.",
|
|
62
|
+
"not-flexible": "This project's Flexible terms don't count right now, so nothing was shipped.",
|
|
63
|
+
"no-check": "This project has no check command, and a Flexible thread's work ships only after its checks pass. Set one in the project's settings first. Nothing changed.",
|
|
64
|
+
"thread-running": "The thread's agent is still working. Stop it, then ship. Nothing changed.",
|
|
65
|
+
"invalid-request": "The title, goal or what done means isn't valid. Nothing changed.",
|
|
66
|
+
"changed": "These terms changed since they were shown, or were already used. Read them again first. Nothing changed.",
|
|
67
|
+
"machine-proof": "Only a person can ship a thread's work. Nothing changed.",
|
|
68
|
+
"proof-refused": "That didn't prove it's you, or you can't approve work in this project. Nothing changed.",
|
|
69
|
+
"handoff-failed": "The changes were imported, but their check task couldn't be made. The import is kept: ship again, or remove it.",
|
|
70
|
+
"approval-refused": "The changes were imported, but their check task couldn't be approved. The import is kept: ship again, or remove it.",
|
|
71
|
+
"not-found": "There's no such Ship.",
|
|
72
|
+
"wrong-state": "This Ship can't do that now.",
|
|
73
|
+
"cancelled": "The merge was stopped for good.",
|
|
74
|
+
"no-publishing": "This project can't publish pull requests, so a Flexible thread's work can't merge from it. Set up pull requests first. Nothing changed.",
|
|
75
|
+
"merging": "Too late: the merge is already happening. Its outcome is read back from GitHub.",
|
|
76
|
+
});
|
|
77
|
+
const refuse = (reason, detail) => ({ ok: false, reason, message: detail === undefined ? WORDS[reason] : `${WORDS[reason]} (${detail})` });
|
|
78
|
+
function ownerStanding(store, thread, by) {
|
|
79
|
+
if (thread.createdBy !== by)
|
|
80
|
+
return refuse("not-owner");
|
|
81
|
+
const account = store.accountOf(by);
|
|
82
|
+
if (account === null || account.revokedAt !== null || account.role !== "approver" || !store.accountCanAccess(by, thread.repo))
|
|
83
|
+
return refuse("not-an-approver");
|
|
84
|
+
if (flexibleTwoPerson(store, thread.repo))
|
|
85
|
+
return refuse("two-person");
|
|
86
|
+
const standing = flexibleStanding(store, thread.repo);
|
|
87
|
+
if (standing.state !== "on")
|
|
88
|
+
return refuse("not-flexible", standing.state);
|
|
89
|
+
return { generation: account.generation, termsId: standing.id, termsDigest: standing.digest };
|
|
90
|
+
}
|
|
91
|
+
function personNow(store, by, token, repo) {
|
|
92
|
+
if (machineActing())
|
|
93
|
+
return refuse("machine-proof");
|
|
94
|
+
const proved = authenticateApprover(store, by, token, repo);
|
|
95
|
+
if (!proved.ok)
|
|
96
|
+
return refuse("proof-refused");
|
|
97
|
+
if (!personProof(proved.method))
|
|
98
|
+
return refuse("machine-proof");
|
|
99
|
+
return { method: proved.method };
|
|
100
|
+
}
|
|
101
|
+
const turnRunning = (store, thread) => store.handle.prepare("SELECT 1 FROM thread_turn WHERE thread = ? AND status IN ('admitted', 'running')").get(thread) !== undefined;
|
|
102
|
+
function branchHeld(store, thread) {
|
|
103
|
+
const row = store.handle.prepare("SELECT candidate FROM flexible_ship WHERE thread = ? AND state IN ('imported', 'armed', 'completed', 'merged', 'cancelled', 'sent-back') ORDER BY seq DESC LIMIT 1").get(thread);
|
|
104
|
+
return row === undefined ? null : String(row["candidate"]);
|
|
105
|
+
}
|
|
106
|
+
const nextSeq = (store, thread) => Number(store.handle.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS n FROM flexible_ship WHERE thread = ?").get(thread)["n"]);
|
|
107
|
+
function destinationOf(store, repo) {
|
|
108
|
+
const grant = store.publicationGrantFor(repo);
|
|
109
|
+
if (grant === null || !grant.capabilities.includes("push-branch") || !grant.capabilities.includes("open-pr"))
|
|
110
|
+
return null;
|
|
111
|
+
return { repo: grant.githubRepo, remote: grant.remote, base: grant.base, method: grant.mergeMethod ?? "squash", capabilities: [...grant.capabilities].sort(), draft: grant.draft };
|
|
112
|
+
}
|
|
113
|
+
export async function flexibleShipTerms(store, input) {
|
|
114
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
115
|
+
return refuse("not-available");
|
|
116
|
+
const thread = flexibleThread(store, input.thread);
|
|
117
|
+
if (thread === null)
|
|
118
|
+
return refuse("thread-unknown");
|
|
119
|
+
const standing = ownerStanding(store, thread, input.by);
|
|
120
|
+
if ("ok" in standing)
|
|
121
|
+
return standing;
|
|
122
|
+
const check = store.liveVerifyCommand(thread.repo);
|
|
123
|
+
if (check === null)
|
|
124
|
+
return refuse("no-check");
|
|
125
|
+
const title = (input.text?.title ?? DEFAULT_TITLE).trim(), goal = (input.text?.goal ?? DEFAULT_GOAL).trim();
|
|
126
|
+
if (validateTaskText({ title, goal }) !== null || goal === "")
|
|
127
|
+
return refuse("invalid-request");
|
|
128
|
+
const parsed = parseAcceptanceCriteria(input.text?.acceptance ?? DEFAULT_ACCEPTANCE);
|
|
129
|
+
if (parsed.problems.length > 0 || parsed.criteria.length === 0)
|
|
130
|
+
return refuse("invalid-request");
|
|
131
|
+
const destination = destinationOf(store, thread.repo);
|
|
132
|
+
if (destination === null)
|
|
133
|
+
return refuse("no-publishing");
|
|
134
|
+
const read = await readFlexibleCandidate(store, { thread: thread.id, ...(input.runner === undefined ? {} : { runner: input.runner }) });
|
|
135
|
+
if (!read.ok)
|
|
136
|
+
return read;
|
|
137
|
+
const seq = nextSeq(store, thread.id);
|
|
138
|
+
const terms = {
|
|
139
|
+
kind: "flexible-ship", version: FLEXIBLE_SHIP_VERSION, thread: thread.id, repo: thread.repo, owner: input.by, ownerGeneration: standing.generation, seq,
|
|
140
|
+
base: read.base, candidate: read.candidate, branch: flexibleThreadBranch(thread.id), importRef: flexibleImportRef(thread.id, seq), changedPaths: read.changedPaths,
|
|
141
|
+
title, goal, acceptance: parsed.criteria, outOfScope: SHIP_OUT_OF_SCOPE, check: { command: check.command, digest: check.digest }, merge: "when-checks-pass",
|
|
142
|
+
github: destination, delegation: standing.termsDigest, network: flexibleNetworkOf(store, thread.repo), history: "beyond-base",
|
|
143
|
+
};
|
|
144
|
+
const digest = flexibleShipDigestOf(terms);
|
|
145
|
+
return { ok: true, terms, digest, summary: flexibleShipSummary(terms, digest) };
|
|
146
|
+
}
|
|
147
|
+
export async function shipFlexible(store, input) {
|
|
148
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
149
|
+
return refuse("not-available");
|
|
150
|
+
const first = flexibleThread(store, input.thread);
|
|
151
|
+
if (first === null)
|
|
152
|
+
return refuse("thread-unknown");
|
|
153
|
+
const proved = personNow(store, input.by, input.token, first.repo);
|
|
154
|
+
if ("ok" in proved)
|
|
155
|
+
return proved;
|
|
156
|
+
const locked = await withFlexibleThreadLock(input.thread, () => shipLocked(store, input, proved.method));
|
|
157
|
+
if (locked.ok === false && (locked.reason === "not-available" || locked.reason === "thread-unknown"))
|
|
158
|
+
return refuse(locked.reason);
|
|
159
|
+
return locked;
|
|
160
|
+
}
|
|
161
|
+
class ShipStop extends Error {
|
|
162
|
+
refusal;
|
|
163
|
+
constructor(refusal) {
|
|
164
|
+
super(refusal.message);
|
|
165
|
+
this.refusal = refusal;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
async function shipLocked(store, input, method) {
|
|
169
|
+
if (turnRunning(store, input.thread) || unsettledLaunch(store, input.thread) !== null)
|
|
170
|
+
return refuse("thread-running");
|
|
171
|
+
const shown = await flexibleShipTerms(store, { thread: input.thread, by: input.by, ...(input.text === undefined ? {} : { text: input.text }), ...(input.runner === undefined ? {} : { runner: input.runner }) });
|
|
172
|
+
if (!shown.ok)
|
|
173
|
+
return shown;
|
|
174
|
+
if (shown.digest !== input.shownDigest || shown.summary.key !== input.shownKey)
|
|
175
|
+
return refuse("changed");
|
|
176
|
+
const { terms, digest } = shown;
|
|
177
|
+
const now = input.now.toISOString();
|
|
178
|
+
const recorded = store.transact(() => {
|
|
179
|
+
const thread = flexibleThread(store, input.thread);
|
|
180
|
+
if (thread === null || thread.state !== "ready")
|
|
181
|
+
return refuse("thread-unknown");
|
|
182
|
+
const standing = ownerStanding(store, thread, input.by);
|
|
183
|
+
if ("ok" in standing)
|
|
184
|
+
return standing;
|
|
185
|
+
if (standing.generation !== terms.ownerGeneration)
|
|
186
|
+
return refuse("stale-generation");
|
|
187
|
+
if (standing.termsDigest !== terms.delegation)
|
|
188
|
+
return refuse("changed");
|
|
189
|
+
if (nextSeq(store, thread.id) !== terms.seq || store.handle.prepare("SELECT 1 FROM flexible_ship WHERE id = ?").get(digest) !== undefined)
|
|
190
|
+
return refuse("changed");
|
|
191
|
+
const branchBefore = branchHeld(store, thread.id);
|
|
192
|
+
store.handle.prepare(`INSERT INTO flexible_ship (id, thread, seq, repo, base_sha, candidate, import_ref, branch, branch_before, terms_json, digest, summary_key, approved_by, approved_generation, proof, approved_at, delegation_id, state, state_at)
|
|
193
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'approved', ?)`).run(digest, thread.id, terms.seq, thread.repo, terms.base, terms.candidate, terms.importRef, terms.branch, branchBefore, canonicalJson(terms), digest, shown.summary.key, input.by, standing.generation, method, now, standing.termsId, now);
|
|
194
|
+
store.recordAction({ at: now, actor: input.by, repo: thread.repo, taskId: null, runId: null, source: "work", action: "flexible ship approved", outcome: "flexible-ship",
|
|
195
|
+
detail: `thread ${thread.id} · ship ${terms.seq} · terms ${digest} · candidate ${terms.candidate} · ${method} · generation ${standing.generation}` });
|
|
196
|
+
return { branchBefore };
|
|
197
|
+
});
|
|
198
|
+
if ("ok" in recorded)
|
|
199
|
+
return recorded;
|
|
200
|
+
const imported = await importFlexibleCandidate(store, { thread: input.thread, seq: terms.seq, expected: terms.candidate, branchBefore: recorded.branchBefore, by: input.by, now: input.now,
|
|
201
|
+
...(input.runner === undefined ? {} : { runner: input.runner }) });
|
|
202
|
+
if (!imported.ok) {
|
|
203
|
+
store.transact(() => {
|
|
204
|
+
store.handle.prepare("UPDATE flexible_ship SET state = 'refused', reason = ?, detail = ?, state_at = ? WHERE id = ? AND state = 'approved'")
|
|
205
|
+
.run("check" in imported ? imported.check : imported.reason, imported.message.slice(0, 2000), now, digest);
|
|
206
|
+
store.recordAction({ at: now, actor: input.by, repo: terms.repo, taskId: null, runId: null, source: "work", action: "flexible ship refused", outcome: "check" in imported ? imported.check : imported.reason,
|
|
207
|
+
detail: `thread ${terms.thread} · ship ${terms.seq} · ${imported.message}`.slice(0, 2000) });
|
|
208
|
+
});
|
|
209
|
+
return imported;
|
|
210
|
+
}
|
|
211
|
+
store.transact(() => { store.handle.prepare("UPDATE flexible_ship SET state = 'imported', state_at = ? WHERE id = ? AND state = 'approved'").run(now, digest); });
|
|
212
|
+
return fileAndSeal(store, { terms, digest, by: input.by, token: input.token, now: input.now, refsChanged: imported.refsChanged, ...(input.runner === undefined ? {} : { runner: input.runner }) });
|
|
213
|
+
}
|
|
214
|
+
async function fileAndSeal(store, input) {
|
|
215
|
+
const { terms, digest } = input;
|
|
216
|
+
const taskId = flexibleShipTaskId(digest);
|
|
217
|
+
const branch = taskBranch(taskId);
|
|
218
|
+
const runner = input.runner === undefined ? {} : { runner: input.runner };
|
|
219
|
+
const kept = (refusal) => {
|
|
220
|
+
store.transact(() => { store.handle.prepare("UPDATE flexible_ship SET detail = ?, state_at = ? WHERE id = ? AND state = 'imported'").run(refusal.message.slice(0, 2000), input.now.toISOString(), digest); });
|
|
221
|
+
return refusal;
|
|
222
|
+
};
|
|
223
|
+
if (store.lookupRef(taskId) !== null)
|
|
224
|
+
return kept(refuse("handoff-failed", "its task already exists"));
|
|
225
|
+
if (!await flexibleTaskBranch(store, { thread: terms.thread, branch, at: terms.base, make: true, ...runner }))
|
|
226
|
+
return kept(refuse("handoff-failed", "its task's branch couldn't be made"));
|
|
227
|
+
try {
|
|
228
|
+
return store.transact(() => {
|
|
229
|
+
const row = store.handle.prepare("SELECT state FROM flexible_ship WHERE id = ?").get(digest);
|
|
230
|
+
if (row?.["state"] !== "imported")
|
|
231
|
+
throw new ShipStop(refuse("wrong-state"));
|
|
232
|
+
const made = fileTaskProposal(store, { id: taskId, title: terms.title, repo: terms.repo, goal: terms.goal, outOfScope: terms.outOfScope, acceptance: terms.acceptance,
|
|
233
|
+
filedVia: `${FLEXIBLE_FILED_PREFIX}${digest}`, filedBy: { name: input.by, kind: "person" }, planning: "skip", admittedRepos: [terms.repo] }, input.now);
|
|
234
|
+
if (!made.ok)
|
|
235
|
+
throw new ShipStop(refuse("handoff-failed", made.message));
|
|
236
|
+
const ref = store.lookupRef(made.id);
|
|
237
|
+
const proposed = proposeGuarded(store, { taskId: made.id, author: input.by, taskRef: ref.id, sawDigest: store.getScope(made.id).digest, goal: terms.goal, outOfScope: terms.outOfScope,
|
|
238
|
+
acceptance: terms.acceptance, candidate: terms.candidate, now: input.now });
|
|
239
|
+
if (!proposed.ok)
|
|
240
|
+
throw new ShipStop(refuse("handoff-failed", proposed.message || "its scope couldn't be saved"));
|
|
241
|
+
const yes = approve(store, made.id, input.by, input.now, proposed.scope.digest, input.token);
|
|
242
|
+
if (!yes.ok)
|
|
243
|
+
throw new ShipStop(refuse("approval-refused", "message" in yes && typeof yes.message === "string" ? yes.message : yes.reason));
|
|
244
|
+
const sealed = store.getScope(made.id);
|
|
245
|
+
if (!approvalOf(sealed).approved || sealed.candidate !== terms.candidate)
|
|
246
|
+
throw new ShipStop(refuse("approval-refused", "its seal didn't hold"));
|
|
247
|
+
const moved = store.handle.prepare("UPDATE flexible_ship SET state = 'armed', task_id = ?, scope_digest = ?, detail = NULL, state_at = ? WHERE id = ? AND state = 'imported'")
|
|
248
|
+
.run(made.id, sealed.digest, input.now.toISOString(), digest);
|
|
249
|
+
if (Number(moved.changes) !== 1)
|
|
250
|
+
throw new ShipStop(refuse("wrong-state"));
|
|
251
|
+
store.recordAction({ at: input.now.toISOString(), actor: input.by, repo: terms.repo, taskId: made.id, runId: null, source: "work", action: "flexible ship armed", outcome: "flexible-ship",
|
|
252
|
+
detail: `thread ${terms.thread} · ship ${terms.seq} · terms ${digest} · scope ${sealed.digest} · candidate ${terms.candidate}` });
|
|
253
|
+
return { ok: true, ship: digest, seq: terms.seq, taskId: made.id, scopeDigest: sealed.digest, importRef: terms.importRef, refsChanged: input.refsChanged };
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
await flexibleTaskBranch(store, { thread: terms.thread, branch, at: terms.base, make: false, ...runner });
|
|
258
|
+
if (error instanceof ShipStop)
|
|
259
|
+
return kept(error.refusal);
|
|
260
|
+
return kept(refuse("handoff-failed", error instanceof Error ? error.message.slice(0, 300) : undefined));
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function readRow(row) {
|
|
264
|
+
if (row === undefined)
|
|
265
|
+
return null;
|
|
266
|
+
let terms;
|
|
267
|
+
try {
|
|
268
|
+
terms = JSON.parse(String(row["terms_json"]));
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
if (canonicalJson(terms) !== row["terms_json"] || flexibleShipDigestOf(terms) !== row["digest"] || row["id"] !== row["digest"] || terms.kind !== "flexible-ship" || terms.version !== FLEXIBLE_SHIP_VERSION)
|
|
274
|
+
return null;
|
|
275
|
+
if (terms.thread !== row["thread"] || terms.seq !== row["seq"] || terms.repo !== row["repo"] || terms.base !== row["base_sha"] || terms.candidate !== row["candidate"] || terms.importRef !== row["import_ref"] || terms.branch !== row["branch"])
|
|
276
|
+
return null;
|
|
277
|
+
if (terms.owner !== row["approved_by"] || terms.ownerGeneration !== row["approved_generation"])
|
|
278
|
+
return null;
|
|
279
|
+
const text = (key) => (row[key] === null || row[key] === undefined ? null : String(row[key]));
|
|
280
|
+
return { id: String(row["id"]), thread: terms.thread, seq: terms.seq, repo: terms.repo, base: terms.base, candidate: terms.candidate, importRef: terms.importRef, branch: terms.branch,
|
|
281
|
+
branchBefore: text("branch_before"), terms, approvedBy: String(row["approved_by"]), approvedGeneration: Number(row["approved_generation"]), state: String(row["state"]), reason: text("reason"),
|
|
282
|
+
detail: text("detail"), taskId: text("task_id"), scopeDigest: text("scope_digest"), feedback: text("feedback"), mergeHead: text("merge_head"), checkReceipt: text("check_receipt"),
|
|
283
|
+
mergeToken: text("merge_token"), mergeReservedAt: text("merge_reserved_at"), delegationId: Number(row["delegation_id"]), stateAt: String(row["state_at"]) };
|
|
284
|
+
}
|
|
285
|
+
export function flexibleShipsOf(store, thread) {
|
|
286
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
287
|
+
return refuse("not-available");
|
|
288
|
+
const rows = store.handle.prepare("SELECT * FROM flexible_ship WHERE thread = ? ORDER BY seq DESC").all(thread);
|
|
289
|
+
return { ok: true, ships: rows.map(readRow).filter((one) => one !== null) };
|
|
290
|
+
}
|
|
291
|
+
const rowOfTask = (store, taskId) => readRow(store.handle.prepare("SELECT * FROM flexible_ship WHERE task_id = ?").get(taskId));
|
|
292
|
+
function shipOfTask(store, taskId) {
|
|
293
|
+
const via = store.filedViaOf(taskId);
|
|
294
|
+
if (via === null || !via.startsWith(FLEXIBLE_FILED_PREFIX))
|
|
295
|
+
return null;
|
|
296
|
+
const ship = rowOfTask(store, taskId);
|
|
297
|
+
if (ship === null || via !== `${FLEXIBLE_FILED_PREFIX}${ship.id}` || taskId !== flexibleShipTaskId(ship.id))
|
|
298
|
+
return null;
|
|
299
|
+
const scope = store.getScope(taskId);
|
|
300
|
+
if (scope === null || scope.digest !== ship.scopeDigest || scope.candidate !== ship.candidate || !approvalOf(scope).approved)
|
|
301
|
+
return null;
|
|
302
|
+
return ship;
|
|
303
|
+
}
|
|
304
|
+
const inFlight = new Set();
|
|
305
|
+
export const FLEXIBLE_STALE_MERGE_MS = 15 * 60_000;
|
|
306
|
+
function cancelArmed(store, ship, why, now, actor = "toolroll") {
|
|
307
|
+
return store.transact(() => {
|
|
308
|
+
const moved = store.handle.prepare("UPDATE flexible_ship SET state = 'cancelled', detail = ?, state_at = ? WHERE id = ? AND state IN ('armed', 'completed')").run(why.slice(0, 2000), now.toISOString(), ship.id);
|
|
309
|
+
if (Number(moved.changes) !== 1)
|
|
310
|
+
return false;
|
|
311
|
+
store.recordAction({ at: now.toISOString(), actor, repo: ship.repo, taskId: ship.taskId, runId: null, source: actor === "toolroll" ? "policy" : "work", action: "flexible merge cancelled", outcome: "cancelled", detail: why.slice(0, 2000) });
|
|
312
|
+
return true;
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
function authorityProblem(store, ship) {
|
|
316
|
+
const thread = flexibleThread(store, ship.thread);
|
|
317
|
+
if (thread === null)
|
|
318
|
+
return "its thread is gone";
|
|
319
|
+
const standing = ownerStanding(store, thread, ship.approvedBy);
|
|
320
|
+
if ("ok" in standing)
|
|
321
|
+
return `the person's authority ended: ${standing.message}`;
|
|
322
|
+
if (standing.generation !== ship.approvedGeneration)
|
|
323
|
+
return "the person's account changed since they shipped it";
|
|
324
|
+
if (standing.termsId !== ship.delegationId || standing.termsDigest !== ship.terms.delegation)
|
|
325
|
+
return "the project's Flexible terms it was shipped under ended";
|
|
326
|
+
if (ship.taskId === null || shipOfTask(store, ship.taskId) === null)
|
|
327
|
+
return "its task's sealed terms no longer hold";
|
|
328
|
+
if (store.getTask(ship.taskId)?.state === "cancelled")
|
|
329
|
+
return "its task was cancelled";
|
|
330
|
+
const destination = destinationOf(store, ship.repo);
|
|
331
|
+
if (destination === null || canonicalJson(destination) !== canonicalJson(ship.terms.github))
|
|
332
|
+
return "where it merges, or what Toolroll may do there, changed since it was shipped";
|
|
333
|
+
if (store.liveVerifyCommand(ship.repo)?.digest !== ship.terms.check.digest)
|
|
334
|
+
return "the project's check command changed since it was shipped";
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
function newestRun(store, taskId) {
|
|
338
|
+
const ref = store.lookupRef(taskId);
|
|
339
|
+
const runs = ref === null ? [] : store.runsFor(ref.id).filter(one => one.role !== "reviewer");
|
|
340
|
+
return runs.reduce((best, one) => (best === null || one.id > best.id ? one : best), null);
|
|
341
|
+
}
|
|
342
|
+
function passingCheck(store, root, runId, ship, now) {
|
|
343
|
+
if (runCheckLevel(store, runId) === null || fullCheckGate(store, runId, now).state !== "clear")
|
|
344
|
+
return null;
|
|
345
|
+
const evidence = verificationEvidence(store, root, runId);
|
|
346
|
+
if (!evidence.ok || evidence.bytes === null)
|
|
347
|
+
return null;
|
|
348
|
+
const view = readVerificationView(evidence.bytes);
|
|
349
|
+
if (!view.ok)
|
|
350
|
+
return null;
|
|
351
|
+
const result = view.value.result;
|
|
352
|
+
return view.value.head === ship.candidate && view.value.command.digest === ship.terms.check.digest && result.exitCode === 0 ? evidence.digest : null;
|
|
353
|
+
}
|
|
354
|
+
export async function mergeArmedFlexible(store, input) {
|
|
355
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
356
|
+
return refuse("not-available");
|
|
357
|
+
const clock = input.clock ?? (() => new Date());
|
|
358
|
+
const found = rowOfTask(store, input.taskId);
|
|
359
|
+
if (found === null)
|
|
360
|
+
return refuse("not-found");
|
|
361
|
+
if (found.state === "merging")
|
|
362
|
+
return { ok: true, state: "waiting", why: "its merge is under way; its outcome is read back from GitHub" };
|
|
363
|
+
if (found.state !== "armed" && found.state !== "completed")
|
|
364
|
+
return refuse("wrong-state", found.state);
|
|
365
|
+
const stop = (why) => { cancelArmed(store, found, why, clock()); return refuse("cancelled", why); };
|
|
366
|
+
const lapsed = authorityProblem(store, found);
|
|
367
|
+
if (lapsed !== null)
|
|
368
|
+
return stop(lapsed);
|
|
369
|
+
let project;
|
|
370
|
+
try {
|
|
371
|
+
project = realpathSync(found.repo);
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
return { ok: true, state: "waiting", why: "the project can't be read" };
|
|
375
|
+
}
|
|
376
|
+
const read = hardenedGit(input.runner ?? run, "read", { repo: project });
|
|
377
|
+
const based = await read("git", ["--no-replace-objects", "merge-base", "--is-ancestor", found.base, `refs/heads/${found.terms.github.base}`], { cwd: project, timeoutMs: 30_000 });
|
|
378
|
+
if (based.code === 1)
|
|
379
|
+
return stop(`its starting commit is no longer on ${found.terms.github.base}`);
|
|
380
|
+
if (based.code !== 0)
|
|
381
|
+
return { ok: true, state: "waiting", why: `${found.terms.github.base} couldn't be read` };
|
|
382
|
+
const newest = newestRun(store, input.taskId);
|
|
383
|
+
if (newest === null || newest.headRevision === null || newest.finishedAt == null)
|
|
384
|
+
return { ok: true, state: "waiting", why: "its check task hasn't finished" };
|
|
385
|
+
const head = newest.headRevision;
|
|
386
|
+
if (head !== found.candidate)
|
|
387
|
+
return stop("the result isn't the shipped commit itself; another commit, even with identical files, needs a new Ship");
|
|
388
|
+
const check = passingCheck(store, input.root, newest.id, found, clock());
|
|
389
|
+
if (found.state === "armed") {
|
|
390
|
+
if (check === null)
|
|
391
|
+
return { ok: true, state: "waiting", why: "the check hasn't passed on this exact commit" };
|
|
392
|
+
const receipt = assignmentOf(store, input.taskId, clock(), { principal: "operator", repos: [found.repo] }, input.root)?.receipt ?? null;
|
|
393
|
+
if (receipt === null || receipt.runId !== newest.id || (receipt.head !== null && receipt.head !== head))
|
|
394
|
+
return { ok: true, state: "waiting", why: "its result isn't ready to complete yet" };
|
|
395
|
+
try {
|
|
396
|
+
store.transact(() => {
|
|
397
|
+
const again = rowOfTask(store, input.taskId);
|
|
398
|
+
if (again === null || again.state !== "armed")
|
|
399
|
+
throw new ShipStop(refuse("wrong-state"));
|
|
400
|
+
const problem = authorityProblem(store, again);
|
|
401
|
+
if (problem !== null) {
|
|
402
|
+
cancelArmed(store, again, problem, clock());
|
|
403
|
+
throw new ShipStop(refuse("cancelled", problem));
|
|
404
|
+
}
|
|
405
|
+
const who = verifyApproverStanding(store, again.approvedBy, again.approvedGeneration, [again.repo]);
|
|
406
|
+
if (!who.ok)
|
|
407
|
+
throw new ShipStop(refuse("not-an-approver"));
|
|
408
|
+
const opened = completeAndOpenPullRequest(store, { taskId: input.taskId, digest: receipt.digest, runId: newest.id, who: who.who, root: input.root }, clock());
|
|
409
|
+
if (!opened.ok)
|
|
410
|
+
throw new ShipStop(refuse("wrong-state", opened.message));
|
|
411
|
+
if (opened.publication.headSha !== head || opened.publication.githubRepo !== again.terms.github.repo || opened.publication.base !== again.terms.github.base) {
|
|
412
|
+
throw new ShipStop(refuse("wrong-state", "its pull request would go somewhere other than the shipped commit and destination"));
|
|
413
|
+
}
|
|
414
|
+
const at = clock().toISOString();
|
|
415
|
+
store.handle.prepare("UPDATE flexible_ship SET state = 'completed', merge_head = ?, merge_at = ?, check_receipt = ?, state_at = ? WHERE id = ? AND state = 'armed'").run(head, at, check, at, again.id);
|
|
416
|
+
store.recordAction({ at, actor: again.approvedBy, repo: again.repo, taskId: input.taskId, runId: newest.id, source: "work", action: "flexible ship completed", outcome: head,
|
|
417
|
+
detail: `ship ${again.id} · checked head ${head} · check receipt ${check} · pull request owed to ${again.terms.github.repo} ${again.terms.github.base}` });
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
catch (error) {
|
|
421
|
+
if (error instanceof ShipStop)
|
|
422
|
+
return error.refusal.reason === "cancelled" ? error.refusal : { ok: true, state: "waiting", why: error.refusal.message };
|
|
423
|
+
throw error;
|
|
424
|
+
}
|
|
425
|
+
return { ok: true, state: "completed" };
|
|
426
|
+
}
|
|
427
|
+
const publication = store.publicationForRun(newest.id);
|
|
428
|
+
if (head !== found.mergeHead || publication === null || publication.headSha !== found.mergeHead)
|
|
429
|
+
return stop("the result's head changed since its check passed");
|
|
430
|
+
if (publication.githubRepo !== found.terms.github.repo || publication.base !== found.terms.github.base)
|
|
431
|
+
return stop("its pull request goes somewhere other than the signed destination");
|
|
432
|
+
if (check === null || check !== found.checkReceipt)
|
|
433
|
+
return { ok: true, state: "waiting", why: "the check no longer stands on this exact commit" };
|
|
434
|
+
if (publication.prNumber === null)
|
|
435
|
+
return { ok: true, state: "waiting", why: "its pull request isn't open yet" };
|
|
436
|
+
const prNumber = publication.prNumber;
|
|
437
|
+
const token = randomBytes(16).toString("hex");
|
|
438
|
+
const destination = (seen) => pullRequestElsewhere(found, seen, prNumber) ?? (seen.head !== found.mergeHead ? "its pull request on GitHub shows another commit than the one whose check passed" : null);
|
|
439
|
+
inFlight.add(token);
|
|
440
|
+
let merged;
|
|
441
|
+
try {
|
|
442
|
+
merged = await mergePullRequest(store, { runId: newest.id, by: found.approvedBy, flexibleShip: found.id, flexibleToken: token, clock, destination, ...(input.exec === undefined ? {} : { exec: input.exec }),
|
|
443
|
+
proceed: seen => reserveMerge(store, { ship: found.id, token, runId: newest.id, root: input.root, now: clock(), seen, prNumber }) });
|
|
444
|
+
}
|
|
445
|
+
finally {
|
|
446
|
+
inFlight.delete(token);
|
|
447
|
+
}
|
|
448
|
+
const landedElsewhere = merged.ok ? (merged.seen === undefined ? "GitHub didn't say where it merged" : destination(merged.seen)) : merged.reason === "elsewhere" ? merged.message : null;
|
|
449
|
+
if (landedElsewhere !== null) {
|
|
450
|
+
store.transact(() => {
|
|
451
|
+
const moved = store.handle.prepare("UPDATE flexible_ship SET state = 'cancelled', merge_token = NULL, merge_reserved_at = NULL, detail = ?, state_at = ? WHERE id = ? AND state IN ('completed', 'merging')")
|
|
452
|
+
.run(`${landedElsewhere} (GitHub reports it merged there, not as this Ship's merge)`.slice(0, 2000), clock().toISOString(), found.id);
|
|
453
|
+
if (Number(moved.changes) === 1)
|
|
454
|
+
store.recordAction({ at: clock().toISOString(), actor: "toolroll", repo: found.repo, taskId: input.taskId, runId: newest.id, source: "policy",
|
|
455
|
+
action: "flexible merge cancelled", outcome: "merged-elsewhere", detail: `ship ${found.id} · ${landedElsewhere}`.slice(0, 2000) });
|
|
456
|
+
});
|
|
457
|
+
return refuse("cancelled", landedElsewhere);
|
|
458
|
+
}
|
|
459
|
+
const after = rowOfTask(store, input.taskId);
|
|
460
|
+
if (merged.ok) {
|
|
461
|
+
store.transact(() => {
|
|
462
|
+
store.handle.prepare("UPDATE flexible_ship SET state = 'merged', merge_token = NULL, merge_reserved_at = NULL, state_at = ? WHERE id = ? AND state IN ('merging', 'completed')").run(clock().toISOString(), found.id);
|
|
463
|
+
store.recordAction({ at: clock().toISOString(), actor: found.approvedBy, repo: found.repo, taskId: input.taskId, runId: newest.id, source: "work", action: "flexible merged", outcome: merged.commit ?? "merged",
|
|
464
|
+
detail: `ship ${found.id} · head ${head}${after?.state === "completed" ? " · found already merged on GitHub" : ""}` });
|
|
465
|
+
});
|
|
466
|
+
return { ok: true, state: "merged" };
|
|
467
|
+
}
|
|
468
|
+
if (after?.state === "cancelled")
|
|
469
|
+
return refuse("cancelled", after.detail ?? merged.message);
|
|
470
|
+
if (after?.state === "merging" && after.mergeToken === token)
|
|
471
|
+
return settleMerging(store, after, input.exec, clock);
|
|
472
|
+
return { ok: true, state: "waiting", why: merged.message };
|
|
473
|
+
}
|
|
474
|
+
function reserveMerge(store, input) {
|
|
475
|
+
const ship = readRow(store.handle.prepare("SELECT * FROM flexible_ship WHERE id = ?").get(input.ship));
|
|
476
|
+
if (ship === null || ship.state !== "completed" || ship.taskId === null)
|
|
477
|
+
return false;
|
|
478
|
+
const elsewhere = pullRequestElsewhere(ship, input.seen, input.prNumber);
|
|
479
|
+
const problem = elsewhere ?? authorityProblem(store, ship);
|
|
480
|
+
if (problem !== null) {
|
|
481
|
+
cancelArmed(store, ship, problem, input.now);
|
|
482
|
+
return false;
|
|
483
|
+
}
|
|
484
|
+
const newest = newestRun(store, ship.taskId);
|
|
485
|
+
if (newest === null || newest.id !== input.runId || newest.headRevision !== ship.candidate || ship.mergeHead !== ship.candidate)
|
|
486
|
+
return false;
|
|
487
|
+
if (passingCheck(store, input.root, newest.id, ship, input.now) !== ship.checkReceipt)
|
|
488
|
+
return false;
|
|
489
|
+
const at = input.now.toISOString();
|
|
490
|
+
const moved = store.handle.prepare("UPDATE flexible_ship SET state = 'merging', merge_token = ?, merge_reserved_at = ?, state_at = ? WHERE id = ? AND state = 'completed'").run(input.token, at, at, ship.id);
|
|
491
|
+
if (Number(moved.changes) !== 1)
|
|
492
|
+
return false;
|
|
493
|
+
store.recordAction({ at, actor: ship.approvedBy, repo: ship.repo, taskId: ship.taskId, runId: newest.id, source: "work", action: "flexible merge reserved", outcome: ship.candidate, detail: `ship ${ship.id}` });
|
|
494
|
+
return true;
|
|
495
|
+
}
|
|
496
|
+
async function settleMerging(store, ship, exec, clock) {
|
|
497
|
+
const newest = ship.taskId === null ? null : newestRun(store, ship.taskId);
|
|
498
|
+
const publication = newest === null ? null : store.publicationForRun(newest.id);
|
|
499
|
+
if (publication === null || publication.prNumber === null)
|
|
500
|
+
return { ok: true, state: "waiting", why: "its merge's outcome can't be read yet" };
|
|
501
|
+
const viewed = await (exec ?? run)("gh", ["pr", "view", String(publication.prNumber), "--repo", ship.terms.github.repo, "--json", "state,headRefOid,mergeCommit,baseRefName,url"], { timeoutMs: 60_000 });
|
|
502
|
+
let state = "", headOid = null, commit = null, base = null, url = null;
|
|
503
|
+
try {
|
|
504
|
+
const payload = JSON.parse(viewed.stdout);
|
|
505
|
+
state = String(payload.state ?? "").toUpperCase();
|
|
506
|
+
headOid = typeof payload.headRefOid === "string" ? payload.headRefOid : null;
|
|
507
|
+
commit = typeof payload.mergeCommit?.oid === "string" ? payload.mergeCommit.oid : null;
|
|
508
|
+
base = typeof payload.baseRefName === "string" ? payload.baseRefName : null;
|
|
509
|
+
url = typeof payload.url === "string" ? payload.url : null;
|
|
510
|
+
}
|
|
511
|
+
catch {
|
|
512
|
+
state = "";
|
|
513
|
+
}
|
|
514
|
+
if (viewed.code !== 0 || state === "")
|
|
515
|
+
return { ok: true, state: "waiting", why: "GitHub couldn't be read to settle the merge" };
|
|
516
|
+
const at = clock().toISOString();
|
|
517
|
+
const elsewhere = pullRequestElsewhere(ship, { base, url }, publication.prNumber);
|
|
518
|
+
const outcome = elsewhere !== null ? "cancelled" : state === "MERGED" ? "merged" : state === "OPEN" && headOid === ship.mergeHead ? "completed" : "cancelled";
|
|
519
|
+
const why = elsewhere !== null ? `${elsewhere}${state === "MERGED" ? " (GitHub merged it there)" : ""}` : `its pull request is ${state.toLowerCase()} on GitHub${headOid !== ship.mergeHead ? " on another commit" : ""}`;
|
|
520
|
+
store.transact(() => {
|
|
521
|
+
const moved = store.handle.prepare(`UPDATE flexible_ship SET state = ?, merge_token = NULL, merge_reserved_at = NULL, state_at = ?${outcome === "cancelled" ? ", detail = ?" : ""} WHERE id = ? AND state = 'merging' AND merge_token = ?`)
|
|
522
|
+
.run(...(outcome === "cancelled" ? [outcome, at, why.slice(0, 2000), ship.id, ship.mergeToken] : [outcome, at, ship.id, ship.mergeToken]));
|
|
523
|
+
if (Number(moved.changes) !== 1)
|
|
524
|
+
return;
|
|
525
|
+
store.recordAction({ at, actor: "toolroll", repo: ship.repo, taskId: ship.taskId, runId: newest?.id ?? null, source: "policy", action: outcome === "merged" ? "flexible merged" : outcome === "completed" ? "flexible merge released" : "flexible merge cancelled",
|
|
526
|
+
outcome: outcome === "merged" ? commit ?? "merged" : outcome, detail: `ship ${ship.id} · read back from GitHub: ${state.toLowerCase()}` });
|
|
527
|
+
});
|
|
528
|
+
if (outcome === "merged")
|
|
529
|
+
return { ok: true, state: "merged" };
|
|
530
|
+
if (outcome === "completed")
|
|
531
|
+
return { ok: true, state: "waiting", why: "the merge didn't happen; it will be tried again once everything still holds" };
|
|
532
|
+
return refuse("cancelled", why);
|
|
533
|
+
}
|
|
534
|
+
function pullRequestElsewhere(ship, seen, prNumber) {
|
|
535
|
+
const address = `https://github.com/${ship.terms.github.repo}/pull/${prNumber}`;
|
|
536
|
+
if (seen.base !== ship.terms.github.base || seen.url === null || seen.url.toLowerCase() !== address.toLowerCase()) {
|
|
537
|
+
return `its pull request on GitHub targets ${seen.base ?? "an unknown branch"}${seen.url !== null && seen.url.toLowerCase() !== address.toLowerCase() ? ` at ${seen.url}` : ""}, not the signed ${ship.terms.github.repo} ${ship.terms.github.base}`;
|
|
538
|
+
}
|
|
539
|
+
return null;
|
|
540
|
+
}
|
|
541
|
+
async function settleUncertainMerges(store, exec, clock) {
|
|
542
|
+
const before = new Date(clock().getTime() - FLEXIBLE_STALE_MERGE_MS).toISOString();
|
|
543
|
+
const rows = store.handle.prepare("SELECT * FROM flexible_ship WHERE state = 'merging' AND merge_reserved_at < ?").all(before);
|
|
544
|
+
let settled = 0;
|
|
545
|
+
for (const raw of rows) {
|
|
546
|
+
const ship = readRow(raw);
|
|
547
|
+
if (ship === null || ship.mergeToken === null || inFlight.has(ship.mergeToken))
|
|
548
|
+
continue;
|
|
549
|
+
const step = await settleMerging(store, ship, exec, clock);
|
|
550
|
+
if (!step.ok || step.state !== "waiting" || rowOfTask(store, ship.taskId)?.state !== "merging")
|
|
551
|
+
settled++;
|
|
552
|
+
}
|
|
553
|
+
return settled;
|
|
554
|
+
}
|
|
555
|
+
export async function reconcileFlexibleShips(store, input) {
|
|
556
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
557
|
+
return refuse("not-available");
|
|
558
|
+
const stuck = store.handle.prepare("SELECT * FROM flexible_ship WHERE state = 'approved' ORDER BY thread, seq").all();
|
|
559
|
+
let settled = 0;
|
|
560
|
+
for (const raw of stuck) {
|
|
561
|
+
const id = String(raw["id"]), thread = String(raw["thread"]);
|
|
562
|
+
let done;
|
|
563
|
+
try {
|
|
564
|
+
done = await withFlexibleThreadLock(thread, async () => {
|
|
565
|
+
const row = store.handle.prepare("SELECT * FROM flexible_ship WHERE id = ? AND state = 'approved'").get(id);
|
|
566
|
+
if (row === undefined)
|
|
567
|
+
return false;
|
|
568
|
+
const candidate = String(row["candidate"]), branchBefore = row["branch_before"] === null ? null : String(row["branch_before"]);
|
|
569
|
+
const put = await settleInterruptedImport(store, { thread, seq: Number(row["seq"]), candidate, branchBefore, ...(input.runner === undefined ? {} : { runner: input.runner }) });
|
|
570
|
+
const words = put.ok ? `interrupted before it finished; import ref ${put.importRef}, thread branch ${put.branch}` : `interrupted before it finished; its refs couldn't be checked: ${put.message}`;
|
|
571
|
+
return store.transact(() => {
|
|
572
|
+
const moved = store.handle.prepare("UPDATE flexible_ship SET state = 'failed', reason = 'interrupted', detail = ?, state_at = ? WHERE id = ? AND state = 'approved'").run(words.slice(0, 2000), input.now.toISOString(), id);
|
|
573
|
+
if (Number(moved.changes) !== 1)
|
|
574
|
+
return false;
|
|
575
|
+
store.recordAction({ at: input.now.toISOString(), actor: "toolroll", repo: String(row["repo"]), taskId: null, runId: null, source: "policy", action: "flexible ship interrupted", outcome: "failed",
|
|
576
|
+
detail: `ship ${id} · ${words}`.slice(0, 2000) });
|
|
577
|
+
return true;
|
|
578
|
+
});
|
|
579
|
+
}, input.lockWaitMs ?? 200);
|
|
580
|
+
}
|
|
581
|
+
catch {
|
|
582
|
+
continue;
|
|
583
|
+
}
|
|
584
|
+
if (done === true)
|
|
585
|
+
settled++;
|
|
586
|
+
}
|
|
587
|
+
return { ok: true, settled };
|
|
588
|
+
}
|
|
589
|
+
export async function flexibleArmedPass(store, input) {
|
|
590
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
591
|
+
return refuse("not-available");
|
|
592
|
+
const clock = input.clock ?? (() => new Date());
|
|
593
|
+
const runner = input.runner === undefined ? {} : { runner: input.runner };
|
|
594
|
+
const reconciled = await reconcileFlexibleShips(store, { now: clock(), ...runner });
|
|
595
|
+
const uncertain = await settleUncertainMerges(store, input.exec, clock);
|
|
596
|
+
const report = { ok: true, reconciled: (reconciled.ok ? reconciled.settled : 0) + uncertain, completed: 0, merged: 0, cancelled: 0, waiting: 0 };
|
|
597
|
+
const tasks = store.handle.prepare("SELECT task_id FROM flexible_ship WHERE state IN ('armed', 'completed') ORDER BY approved_at").all().map(row => String(row["task_id"]));
|
|
598
|
+
for (const taskId of tasks) {
|
|
599
|
+
let step;
|
|
600
|
+
try {
|
|
601
|
+
step = await mergeArmedFlexible(store, { taskId, root: input.root, clock, ...runner, ...(input.exec === undefined ? {} : { exec: input.exec }) });
|
|
602
|
+
}
|
|
603
|
+
catch {
|
|
604
|
+
report.waiting++;
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
if (!step.ok) {
|
|
608
|
+
if (step.reason === "cancelled")
|
|
609
|
+
report.cancelled++;
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
report[step.state]++;
|
|
613
|
+
}
|
|
614
|
+
return report;
|
|
615
|
+
}
|
|
616
|
+
function ownersShip(store, taskId, by) {
|
|
617
|
+
const ship = shipOfTask(store, taskId) ?? rowOfTask(store, taskId);
|
|
618
|
+
if (ship === null)
|
|
619
|
+
return refuse("not-found");
|
|
620
|
+
if (ship.approvedBy !== by.name)
|
|
621
|
+
return refuse("not-owner");
|
|
622
|
+
if (ship.state === "merging")
|
|
623
|
+
return refuse("merging");
|
|
624
|
+
if (ship.state !== "armed" && ship.state !== "completed")
|
|
625
|
+
return refuse("wrong-state", ship.state);
|
|
626
|
+
const account = store.accountOf(by.name);
|
|
627
|
+
if (account === null || account.revokedAt !== null || account.generation !== by.generation)
|
|
628
|
+
return refuse("stale-generation");
|
|
629
|
+
return ship;
|
|
630
|
+
}
|
|
631
|
+
export function cancelFlexibleShip(store, input) {
|
|
632
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
633
|
+
return refuse("not-available");
|
|
634
|
+
if (machineActing())
|
|
635
|
+
return refuse("machine-proof");
|
|
636
|
+
return store.transact(() => {
|
|
637
|
+
const ship = ownersShip(store, input.taskId, input.by);
|
|
638
|
+
if ("ok" in ship)
|
|
639
|
+
return ship;
|
|
640
|
+
if (!cancelArmed(store, ship, `cancelled by ${input.by.name}`, input.now, input.by.name))
|
|
641
|
+
return refuse("wrong-state");
|
|
642
|
+
store.cancelTask(input.taskId, input.now, "its Flexible Ship was cancelled");
|
|
643
|
+
return { ok: true };
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
export function sendBackFlexible(store, input) {
|
|
647
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
648
|
+
return refuse("not-available");
|
|
649
|
+
if (machineActing())
|
|
650
|
+
return refuse("machine-proof");
|
|
651
|
+
const feedback = input.feedback.trim();
|
|
652
|
+
if (feedback === "" || feedback.length > 20_000 || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(feedback))
|
|
653
|
+
return refuse("invalid-request");
|
|
654
|
+
return store.transact(() => {
|
|
655
|
+
const ship = ownersShip(store, input.taskId, input.by);
|
|
656
|
+
if ("ok" in ship)
|
|
657
|
+
return ship;
|
|
658
|
+
const at = input.now.toISOString();
|
|
659
|
+
store.handle.prepare("UPDATE flexible_ship SET state = 'sent-back', feedback = ?, state_at = ? WHERE id = ? AND state IN ('armed', 'completed')").run(feedback, at, ship.id);
|
|
660
|
+
const cancelled = store.cancelTask(input.taskId, input.now, "sent back to its Flexible thread");
|
|
661
|
+
store.recordAction({ at, actor: input.by.name, repo: ship.repo, taskId: input.taskId, runId: null, source: "work", action: "flexible sent back", outcome: "sent-back",
|
|
662
|
+
detail: `ship ${ship.id} · thread ${ship.thread}${cancelled.ok ? " · task cancelled" : ` · task ${cancelled.reason}`}` });
|
|
663
|
+
return { ok: true, thread: ship.thread, feedback };
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
export async function removeFlexibleImport(store, input) {
|
|
667
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
668
|
+
return refuse("not-available");
|
|
669
|
+
if (machineActing())
|
|
670
|
+
return refuse("machine-proof");
|
|
671
|
+
const ship = readRow(store.handle.prepare("SELECT * FROM flexible_ship WHERE id = ?").get(input.ship));
|
|
672
|
+
if (ship === null)
|
|
673
|
+
return refuse("not-found");
|
|
674
|
+
if (ship.state !== "imported" || ship.taskId !== null)
|
|
675
|
+
return refuse("wrong-state", ship.state);
|
|
676
|
+
if (ship.approvedBy !== input.by.name)
|
|
677
|
+
return refuse("not-owner");
|
|
678
|
+
const account = store.accountOf(input.by.name);
|
|
679
|
+
if (account === null || account.revokedAt !== null || account.generation !== input.by.generation)
|
|
680
|
+
return refuse("stale-generation");
|
|
681
|
+
if (branchHeld(store, ship.thread) !== ship.candidate)
|
|
682
|
+
return refuse("wrong-state", "a later Ship holds the branch");
|
|
683
|
+
const runner = input.runner === undefined ? {} : { runner: input.runner };
|
|
684
|
+
const removed = await removeFlexibleImportRefs(store, { thread: ship.thread, seq: ship.seq, candidate: ship.candidate, branchBefore: ship.branchBefore, ...runner });
|
|
685
|
+
if (!removed.ok)
|
|
686
|
+
return removed;
|
|
687
|
+
await flexibleTaskBranch(store, { thread: ship.thread, branch: taskBranch(flexibleShipTaskId(ship.id)), at: ship.base, make: false, ...runner });
|
|
688
|
+
store.transact(() => {
|
|
689
|
+
store.handle.prepare("UPDATE flexible_ship SET state = 'removed', state_at = ? WHERE id = ? AND state = 'imported'").run(input.now.toISOString(), ship.id);
|
|
690
|
+
store.recordAction({ at: input.now.toISOString(), actor: input.by.name, repo: ship.repo, taskId: null, runId: null, source: "work", action: "flexible import removed", outcome: "removed",
|
|
691
|
+
detail: `ship ${ship.id} · ${ship.importRef}` });
|
|
692
|
+
});
|
|
693
|
+
return { ok: true };
|
|
694
|
+
}
|