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
package/dist/task-base.js
CHANGED
|
@@ -10,11 +10,29 @@ export const readGit = (cwd, args) => {
|
|
|
10
10
|
};
|
|
11
11
|
const commits = (count) => `${count} commit${count === 1 ? "" : "s"}`;
|
|
12
12
|
export function baseStandingWords(view) {
|
|
13
|
-
const short = view.base.slice(0, 8);
|
|
13
|
+
const short = view.family === true ? `Whole change since ${view.base.slice(0, 8)} (includes earlier attempts' work that's still in it)` : view.base.slice(0, 8);
|
|
14
14
|
if (view.main === null || view.behind === null)
|
|
15
15
|
return short;
|
|
16
16
|
return view.behind === 0 ? `${short} · Up to date with ${view.main}` : `${short} · Behind ${view.main} by ${commits(view.behind)}`;
|
|
17
17
|
}
|
|
18
|
+
export function familyStartOf(store, taskRef) {
|
|
19
|
+
const id = store.externalIdFor(taskRef);
|
|
20
|
+
const ref = id === null ? null : store.lookupRef(id);
|
|
21
|
+
if (id === null || ref === null || ref.revisionOf === null)
|
|
22
|
+
return null;
|
|
23
|
+
const ancestry = store.revisionAncestryStatus(id);
|
|
24
|
+
const rootId = ancestry.chain[ancestry.chain.length - 1];
|
|
25
|
+
const root = ancestry.problem !== null || rootId === undefined || rootId === id ? null : store.lookupRef(rootId);
|
|
26
|
+
if (root === null || root.repo !== ref.repo)
|
|
27
|
+
return null;
|
|
28
|
+
const first = store.runsFor(root.id).filter(one => one.role === "builder" && one.branch !== null && one.baseRevision !== null).sort((a, b) => a.id - b.id)[0];
|
|
29
|
+
if (first === undefined || first.branch === null)
|
|
30
|
+
return null;
|
|
31
|
+
return store.firstBuilderBase(root.id, first.branch) ?? first.baseRevision;
|
|
32
|
+
}
|
|
33
|
+
export function wholeChangeBaseOf(store, taskRef, branch) {
|
|
34
|
+
return familyStartOf(store, taskRef) ?? store.firstBuilderBase(taskRef, branch);
|
|
35
|
+
}
|
|
18
36
|
export function freshBaseFor(store, taskId, branch, main) {
|
|
19
37
|
const ref = store.lookupRef(taskId);
|
|
20
38
|
if (ref === null || ref.revisionOf !== null || store.getScope(taskId)?.candidate != null || store.filedViaOf(taskId)?.startsWith("coding:") === true)
|
|
@@ -30,12 +48,13 @@ export function taskBaseOf(store, taskId, git = readGit) {
|
|
|
30
48
|
return null;
|
|
31
49
|
const branch = latest.branch;
|
|
32
50
|
const move = store.latestBranchBaseMove(ref.id, branch);
|
|
33
|
-
const
|
|
51
|
+
const family = familyStartOf(store, ref.id);
|
|
52
|
+
const base = family ?? (move !== null && move.afterRun >= latest.id ? move.to : store.recordedBranchBase(ref.id, branch) ?? latest.baseRevision);
|
|
34
53
|
const main = git(ref.repo, ["symbolic-ref", "--short", "-q", "HEAD"]) || null;
|
|
35
54
|
const counted = main === null ? null : git(ref.repo, ["rev-list", "--count", `${base}..refs/heads/${main}`]);
|
|
36
55
|
const behind = counted === null || !/^\d+$/.test(counted) ? null : Number(counted);
|
|
37
|
-
const view = { base, branch, main: behind === null ? null : main, behind };
|
|
38
|
-
return { ...view, words: `Base ${baseStandingWords(view)}` };
|
|
56
|
+
const view = { base, branch, main: behind === null ? null : main, behind, ...(family === null ? {} : { family: true }) };
|
|
57
|
+
return { ...view, words: family === null ? `Base ${baseStandingWords(view)}` : baseStandingWords(view) };
|
|
39
58
|
}
|
|
40
59
|
export function recentGitReads(git = readGit, ttlMs = 15_000, entries = 64, now = Date.now) {
|
|
41
60
|
const kept = new Map();
|
package/dist/task-outcome-cli.js
CHANGED
|
@@ -15,6 +15,7 @@ import { proveRunStopped } from './stop-proof.js';
|
|
|
15
15
|
import { familyChangedFiles } from './result-completion.js';
|
|
16
16
|
import { activeRemote } from './remote-run.js';
|
|
17
17
|
import { underAgent } from './prompt.js';
|
|
18
|
+
import { landingOf, publishesThroughPullRequests } from './local-landing.js';
|
|
18
19
|
export async function runTaskOutcomeCommand(action, positional, flags, context) {
|
|
19
20
|
const command = context.command ?? `task ${action}`;
|
|
20
21
|
const emit = (result, lines) => {
|
|
@@ -96,7 +97,7 @@ export async function runTaskOutcomeCommand(action, positional, flags, context)
|
|
|
96
97
|
return emit(changed);
|
|
97
98
|
const assignment = 'body' in changed ? changed.body : changed.assignment;
|
|
98
99
|
return emit({ ok: true, result: assignment }, [`${current.rootId} · Accepted`, `Result: ${current.activeTaskId} · build #${current.receipt.runId} · ${current.receipt.head?.slice(0, 7) ?? 'no commit'}`,
|
|
99
|
-
...(current.readiness?.checksOff ? [] : [current.receipt.checks.detail])]);
|
|
100
|
+
...(current.readiness?.checksOff ? [] : [current.receipt.checks.detail]), ...landNext(store, current.rootId, current.receipt.head)]);
|
|
100
101
|
}
|
|
101
102
|
const feedback = flags.get('feedback'), runFlag = flags.get('run'), sourceFlag = flags.get('source'), keyFlag = flags.get('key');
|
|
102
103
|
if (typeof feedback !== 'string' || !feedback.trim())
|
|
@@ -232,8 +233,16 @@ export async function runLocalCompletion(positional, flags, context) {
|
|
|
232
233
|
`${assignment.rootId} · ${done.replayed ? 'Already accepted' : 'Accepted'}`,
|
|
233
234
|
`Result: ${receipt.taskId} · build #${receipt.runId} · ${receipt.head?.slice(0, 7) ?? 'no commit'}`,
|
|
234
235
|
...(assignment.readiness?.checksOff ? [] : [receipt.checks.detail]),
|
|
236
|
+
...landNext(store, assignment.rootId, receipt.head),
|
|
235
237
|
]);
|
|
236
238
|
}
|
|
239
|
+
function landNext(store, rootId, head) {
|
|
240
|
+
const repo = store.lookupRef(rootId)?.repo ?? null;
|
|
241
|
+
if (repo === null || head === null || publishesThroughPullRequests(store, repo))
|
|
242
|
+
return [];
|
|
243
|
+
const landed = landingOf(store, rootId);
|
|
244
|
+
return landed !== null && !landed.undone ? [] : [`Next: toolroll task land ${rootId}`];
|
|
245
|
+
}
|
|
237
246
|
export function reviseAsLocalOwner(store, taskId, input, now, evidenceRoot) {
|
|
238
247
|
const fail = (reason, message) => ({ ok: false, reason, message });
|
|
239
248
|
try {
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -7,14 +7,18 @@ import { readVerificationReceipt } from "./contracts/verification-receipt.js";
|
|
|
7
7
|
import { LEGACY_GATE_SOURCE, readVerificationView } from "./contracts/verification-view.js";
|
|
8
8
|
import { readCandidateEndpoints, savedInventoryPaths } from "./contracts/diff-stat.js";
|
|
9
9
|
import { liveQuickCommand, quickVerifyKey, runCheckLevel } from "./check-levels.js";
|
|
10
|
-
import { CHECK_INVENTORY_CAPTURE, CHECK_REPORT_CAPTURE } from "./check-report.js";
|
|
10
|
+
import { CHECK_INVENTORY_CAPTURE, CHECK_REPORT_CAPTURE, readSealedJson } from "./check-report.js";
|
|
11
|
+
import { parseContract } from "./contracts/contract.js";
|
|
12
|
+
import { sealedInventorySchema } from "./contracts/release-check.js";
|
|
13
|
+
import { purposeCheckMode } from "./contracts/release-terms.js";
|
|
11
14
|
import { provedComposition } from "./release-recheck.js";
|
|
12
|
-
import { checkAttemptOf } from "./store.js";
|
|
15
|
+
import { checkAttemptOf, verifyCommandAt } from "./store.js";
|
|
16
|
+
import { familyStartOf } from "./task-base.js";
|
|
13
17
|
export const VERIFICATION_RECEIPT_CAPTURE = "machine verification receipt v1";
|
|
14
18
|
const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
15
19
|
const binding = (a) => ({ artifactId: a.id, sha256: a.sha256, bytesStored: a.bytesStored, bytesOriginal: a.bytesOriginal, truncated: a.truncated, redacted: a.redacted, captureStatus: a.captureStatus });
|
|
16
20
|
export const isVerificationReceipt = (a) => a.kind === "structured-output" && (a.capture === VERIFICATION_RECEIPT_CAPTURE || a.capture === "machine verification reuse v1");
|
|
17
|
-
export const coveragePasses = (coverage) => coverage === undefined || coverage === "full" || coverage === "composed";
|
|
21
|
+
export const coveragePasses = (coverage) => coverage === undefined || coverage === "full" || coverage === "composed" || coverage === "deploy";
|
|
18
22
|
export function effectiveCheckFacts(raw, facts) {
|
|
19
23
|
if (facts === null || coveragePasses(facts.coverage))
|
|
20
24
|
return { result: raw, facts };
|
|
@@ -41,7 +45,7 @@ export function sealVerificationReceipt(store, root, runId, head, command, resul
|
|
|
41
45
|
const hits = scanForSecrets(raw);
|
|
42
46
|
storeEvidence(store, root, runId, "structured-output", "verification-receipt.json", Buffer.from(hits.length ? redactSecretLines(raw, hits) : raw), reusedFrom === undefined ? VERIFICATION_RECEIPT_CAPTURE : "machine verification reuse v1", now, { captureStatus: "ok", redacted: hits.length > 0 });
|
|
43
47
|
}
|
|
44
|
-
export function verificationEvidence(store, root, runId) {
|
|
48
|
+
export function verificationEvidence(store, root, runId, asOf) {
|
|
45
49
|
const fail = (problem) => ({ ok: false, problem });
|
|
46
50
|
const source = store.getRun(runId);
|
|
47
51
|
if (!source)
|
|
@@ -53,7 +57,8 @@ export function verificationEvidence(store, root, runId) {
|
|
|
53
57
|
const verified = (machine?.machineVerdict ?? machine?.verdict) === "verified";
|
|
54
58
|
if (!receipts.length && !verified && runCheckLevel(store, runId) === "off")
|
|
55
59
|
return { ok: true, bytes: null, digest: hash(null) };
|
|
56
|
-
const
|
|
60
|
+
const commandOf = (key) => asOf === undefined ? store.liveVerifyCommand(key) : verifyCommandAt(store, key, asOf);
|
|
61
|
+
const command = repo ? sealedCommandKey(root, receipts) === quickVerifyKey(repo) ? asOf === undefined ? liveQuickCommand(store, repo) : commandOf(quickVerifyKey(repo)) : commandOf(repo) : null;
|
|
57
62
|
if (!command && !receipts.length && !verified)
|
|
58
63
|
return { ok: true, bytes: null, digest: hash(null) };
|
|
59
64
|
if (!command || command.approvedAt > source.startedAt)
|
|
@@ -94,7 +99,7 @@ export function verificationEvidence(store, root, runId) {
|
|
|
94
99
|
if (!brief || !readObservationEvidence(store, root, runId) || !reused || reused.run !== brief.sourceRun || reused.run >= runId || reused.digest !== brief.gateDigest ||
|
|
95
100
|
source.baseRevision !== brief.head || source.headRevision !== brief.head || checked.executedHere !== false)
|
|
96
101
|
return fail("The reused gate is not bound to an unchanged observation follow-up.");
|
|
97
|
-
const original = verificationEvidence(store, root, reused.run);
|
|
102
|
+
const original = verificationEvidence(store, root, reused.run, asOf);
|
|
98
103
|
if (!original.ok || !original.bytes || original.digest !== reused.digest)
|
|
99
104
|
return fail("The original passing gate no longer verifies.");
|
|
100
105
|
const previousRead = readVerificationView(original.bytes);
|
|
@@ -131,6 +136,13 @@ export function verificationEvidence(store, root, runId) {
|
|
|
131
136
|
}
|
|
132
137
|
if ((checked.coverage === "composed") !== (checked.composed !== undefined))
|
|
133
138
|
return fail("The release check's coverage and its links disagree.");
|
|
139
|
+
if (checked.coverage === "deploy") {
|
|
140
|
+
const inventory = readSealedJson(store, root, runId, CHECK_INVENTORY_CAPTURE);
|
|
141
|
+
const sealed = inventory === null ? null : parseContract(sealedInventorySchema, inventory.value);
|
|
142
|
+
const purpose = store.getScope(store.refById(source.taskRef)?.externalId ?? "")?.releaseCheck ?? null;
|
|
143
|
+
if (sealed === null || !sealed.ok || sealed.value.sealed.deploy !== true || purposeCheckMode(purpose) !== "deploy")
|
|
144
|
+
return fail("A deploy check's receipt isn't for a release from main sealed with the deploy check.");
|
|
145
|
+
}
|
|
134
146
|
if (!coveragePasses(checked.coverage) && checked.result.configured && checked.result.ran && checked.result.exitCode === 0)
|
|
135
147
|
return fail("The release check reads as passed, but its coverage fell short.");
|
|
136
148
|
if (checked.composed !== undefined) {
|
|
@@ -266,7 +278,8 @@ export function assessmentFromSavedEvidence(store, root, runId) {
|
|
|
266
278
|
try {
|
|
267
279
|
const view = readVerificationView(gate.bytes);
|
|
268
280
|
const base = source.branch ? store.firstBuilderBase(source.taskRef, source.branch) ?? source.baseRevision : source.baseRevision;
|
|
269
|
-
const
|
|
281
|
+
const family = familyStartOf(store, source.taskRef);
|
|
282
|
+
const paths = (family === null ? null : savedInventoryPaths(stat, source.headRevision, family)) ?? savedInventoryPaths(stat, source.headRevision, base);
|
|
270
283
|
if (!view.ok || paths === null)
|
|
271
284
|
return null;
|
|
272
285
|
const receipt = view.value;
|
package/dist/workspace-ui.js
CHANGED
|
@@ -349,7 +349,7 @@ export function acceptWordsOf(facts) {
|
|
|
349
349
|
const joined = parts.length <= 1 ? parts.join("") : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
|
|
350
350
|
const effect = facts.action === "accept" ? "Records that you accept it. The task stays open."
|
|
351
351
|
: facts.publishing === "pull-request" ? "Finishes the task. No pull request opens; you can open one from the task after."
|
|
352
|
-
: facts.publishing === "off" ? "Finishes the task.
|
|
352
|
+
: facts.publishing === "off" ? "Finishes the task. Then you can land it on your project's branch."
|
|
353
353
|
: "Finishes the task. Nothing is published.";
|
|
354
354
|
const checksGap = facts.checks !== "passed" && facts.checks !== "off";
|
|
355
355
|
return { label: ready ? "Accept" : checksGap ? "Accept without checks" : "Accept anyway", ready, why: ready ? null : `${joined.charAt(0).toUpperCase()}${joined.slice(1)}.`, effect };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toolroll",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.120",
|
|
4
4
|
"description": "Your agents build. You decide. A control plane for coding agents — Claude Code, Codex, Gemini: approve the exact scope once, get results back Ready with the diff, the passing check and screenshots. Runs on your machine.",
|
|
5
5
|
"directories": {
|
|
6
6
|
"doc": "docs"
|
|
@@ -124,6 +124,7 @@
|
|
|
124
124
|
"scripts/fixtures/pilot-scenarios.mjs",
|
|
125
125
|
"scripts/proof-preflight.mjs",
|
|
126
126
|
"scripts/restart-certification.mjs",
|
|
127
|
+
"scripts/release-proof.mjs",
|
|
127
128
|
"scripts/launchd-certification.mjs",
|
|
128
129
|
"scripts/fixtures/restart-service.mjs",
|
|
129
130
|
"THIRD_PARTY_NOTICES.md"
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Independent proof that a commit on main was tested before it merged (docs/plans/test-matrix.md): publish.yml runs it
|
|
4
|
+
* on a release tag before npm publication, and main-push.yml on each push to main before it skips the full CI run.
|
|
5
|
+
*
|
|
6
|
+
* node scripts/release-proof.mjs verify --repo <owner/name> --sha <commit> --required <JSON {check name: workflow file}>
|
|
7
|
+
*
|
|
8
|
+
* The commit stands only when, read from GitHub's API with the workflow's own read-only GITHUB_TOKEN:
|
|
9
|
+
* - it is the squash merge (one parent) of exactly one merged pull request into main, by GitHub's merge_commit_sha;
|
|
10
|
+
* - that pull request's head commit has the same tree;
|
|
11
|
+
* - for each workflow named in `required`, the newest run GitHub Actions made on that head commit, for that pull
|
|
12
|
+
* request's branch in this repository, from its pull request (event pull_request), is complete, and in its latest
|
|
13
|
+
* attempt every check the list
|
|
14
|
+
* names for that workflow is exactly one job that concluded `success` (skipped is not success).
|
|
15
|
+
* Anything missing, unreadable, ambiguous or different is no proof. The list in each workflow file must equal
|
|
16
|
+
* src/release.ts REQUIRED_PR_CHECKS (src/ci-workflow.test.ts holds them equal). This proves what GitHub recorded; it
|
|
17
|
+
* relies on main's branch protection requiring every one of those checks, which `toolroll release` refuses to merge
|
|
18
|
+
* without.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const SHA = /^[0-9a-f]{40}$/;
|
|
22
|
+
const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
23
|
+
/** The events whose runs may prove each workflow's checks. */
|
|
24
|
+
export const PROOF_EVENTS = {
|
|
25
|
+
".github/workflows/ci.yml": ["pull_request"],
|
|
26
|
+
".github/workflows/release-candidate.yml": ["pull_request"],
|
|
27
|
+
};
|
|
28
|
+
const workflowIs = (path, file) => {
|
|
29
|
+
if (typeof path !== "string") return false;
|
|
30
|
+
if (path === file) return true;
|
|
31
|
+
// Same rule as release.ts: ci.yml@evil.yml (also with @ref appended) is another workflow, not ci.yml's ref.
|
|
32
|
+
const ref = path.startsWith(`${file}@`) ? path.slice(file.length + 1) : "";
|
|
33
|
+
return /^[A-Za-z0-9._+/-]+$/.test(ref) && !/\.ya?ml$/i.test(ref);
|
|
34
|
+
};
|
|
35
|
+
const mergedPulls = (pulls, repo, sha) => (Array.isArray(pulls) ? pulls : []).filter(pr => pr?.merged_at != null && pr?.merge_commit_sha === sha && pr?.base?.ref === "main" && pr?.base?.repo?.full_name === repo);
|
|
36
|
+
/**
|
|
37
|
+
* GitHub empties a run's pull_requests once its pull request has merged and the branch is gone, so an empty binding stands
|
|
38
|
+
* only when the branch has had exactly one pull request in this repository, ever: `number`, into main. A pull_request run
|
|
39
|
+
* on that branch, from this repository, can then only be that pull request's.
|
|
40
|
+
*/
|
|
41
|
+
const onlyPullFrom = (branchPulls, number, { repo, branch }) => Array.isArray(branchPulls) && branchPulls.length === 1
|
|
42
|
+
&& branchPulls[0]?.number === number && branchPulls[0]?.base?.ref === "main" && branchPulls[0]?.base?.repo?.full_name === repo
|
|
43
|
+
&& branchPulls[0]?.head?.ref === branch && branchPulls[0]?.head?.repo?.full_name === repo;
|
|
44
|
+
const timestamp = value => typeof value === "string" ? Date.parse(value) : NaN;
|
|
45
|
+
|
|
46
|
+
/** The `required` list, checked: a non-empty object of distinct check names, each mapped to a workflow PROOF_EVENTS knows. */
|
|
47
|
+
export function parseRequired(text) {
|
|
48
|
+
let parsed;
|
|
49
|
+
try { parsed = JSON.parse(text); } catch { return null; }
|
|
50
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
51
|
+
const entries = Object.entries(parsed);
|
|
52
|
+
if (entries.length === 0 || entries.some(([name, file]) => name.trim() === "" || typeof file !== "string" || !Object.hasOwn(PROOF_EVENTS, file))) return null;
|
|
53
|
+
return parsed;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The run that may prove `file`'s checks on `head`: the newest GitHub Actions made of that workflow, on that commit, for
|
|
57
|
+
* that branch of this repository, from an event the workflow may prove with. Undefined when there is none. */
|
|
58
|
+
export function provingRun(runs, file, { repo, head, branch }) {
|
|
59
|
+
const events = PROOF_EVENTS[file] ?? [];
|
|
60
|
+
return (Array.isArray(runs) ? runs : []).filter(run => workflowIs(run?.path, file) && run?.head_sha === head && run?.head_branch === branch && events.includes(run?.event)
|
|
61
|
+
&& run?.repository?.full_name === repo && run?.head_repository?.full_name === repo && Number.isSafeInteger(run?.id) && run.id > 0)
|
|
62
|
+
.sort((a, b) => b.id - a.id)[0];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Why `sha` isn't proven, or null when it is. Every input is GitHub's own answer: `commit` and `headCommit` from
|
|
67
|
+
* git/commits, `pulls` from commits/{sha}/pulls, `runs` from actions/runs?head_sha (with its total_count), `jobs` maps a
|
|
68
|
+
* run id to its latest attempt's jobs, `branchPulls` from pulls?state=all&head={owner}:{branch}.
|
|
69
|
+
*/
|
|
70
|
+
export function proofProblem({ repo, sha, required, commit, pulls, headCommit, runs, runsTotal, jobs, branchPulls }) {
|
|
71
|
+
if (!REPO.test(repo ?? "") || !SHA.test(sha ?? "")) return "no repository or commit to prove";
|
|
72
|
+
if (parseRequired(JSON.stringify(required)) === null) return "no list of required checks";
|
|
73
|
+
if (commit?.sha !== sha || !SHA.test(commit?.tree?.sha ?? "")) return `GitHub doesn't describe ${sha.slice(0, 7)}`;
|
|
74
|
+
if (!Array.isArray(commit.parents) || commit.parents.length !== 1) return `${sha.slice(0, 7)} isn't a squash merge (it has ${Array.isArray(commit.parents) ? commit.parents.length : "no"} parents)`;
|
|
75
|
+
const merged = mergedPulls(pulls, repo, sha);
|
|
76
|
+
if (merged.length !== 1) return `${sha.slice(0, 7)} is the merge of ${merged.length === 0 ? "no" : merged.length} merged pull request${merged.length === 1 ? "" : "s"} into main`;
|
|
77
|
+
const pr = merged[0], head = pr.head?.sha, branch = pr.head?.ref;
|
|
78
|
+
const mergedAt = timestamp(pr.merged_at);
|
|
79
|
+
if (!Number.isSafeInteger(pr.number) || pr.number < 1 || !Number.isFinite(mergedAt)) return "no pull request number or merge time";
|
|
80
|
+
if (!SHA.test(head ?? "") || typeof branch !== "string" || branch === "" || pr.head?.repo?.full_name !== repo) return `pull request #${pr.number} has no head commit in ${repo}`;
|
|
81
|
+
if (headCommit?.sha !== head || typeof headCommit?.tree?.sha !== "string") return `GitHub doesn't describe pull request #${pr.number}'s head ${head.slice(0, 7)}`;
|
|
82
|
+
if (headCommit.tree.sha !== commit.tree.sha) return `${sha.slice(0, 7)}'s tree isn't pull request #${pr.number}'s head tree (${head.slice(0, 7)})`;
|
|
83
|
+
if (!Array.isArray(runs) || !Number.isSafeInteger(runsTotal) || runsTotal !== runs.length
|
|
84
|
+
|| runs.some(run => !Number.isSafeInteger(run?.id) || run.id < 1 || run.head_sha !== head)
|
|
85
|
+
|| new Set(runs.map(run => run.id)).size !== runs.length) return `GitHub's workflow runs on ${head.slice(0, 7)} can't be read whole`;
|
|
86
|
+
const byWorkflow = new Map();
|
|
87
|
+
for (const [name, file] of Object.entries(required)) byWorkflow.set(file, [...(byWorkflow.get(file) ?? []), name]);
|
|
88
|
+
for (const [file, names] of byWorkflow) {
|
|
89
|
+
const events = PROOF_EVENTS[file];
|
|
90
|
+
if (events === undefined) return `no proof rule for ${file}`;
|
|
91
|
+
const newest = provingRun(runs, file, { repo, head, branch });
|
|
92
|
+
if (newest === undefined) return `no ${file} run on pull request #${pr.number}'s head ${head.slice(0, 7)}`;
|
|
93
|
+
// Select the newest run first: an invalid binding on it must not resurrect an older green run.
|
|
94
|
+
const bound = newest.pull_requests;
|
|
95
|
+
if (!Array.isArray(bound) || !(bound.length === 0 ? onlyPullFrom(branchPulls, pr.number, { repo, branch }) : bound.length === 1 && bound[0]?.number === pr.number
|
|
96
|
+
&& bound[0]?.base?.ref === "main" && bound[0]?.base?.repo?.url === `https://api.github.com/repos/${repo}`
|
|
97
|
+
&& bound[0]?.head?.sha === head && bound[0]?.head?.ref === branch && bound[0]?.head?.repo?.url === `https://api.github.com/repos/${repo}`)) return `${file} run ${newest.id}: invalid pull request binding`;
|
|
98
|
+
if (!Number.isSafeInteger(newest.run_attempt) || newest.run_attempt < 1) return `${file} run ${newest.id}: no latest attempt`;
|
|
99
|
+
if (newest.status !== "completed") return `${file} run ${newest.id} on ${head.slice(0, 7)} hasn't finished`;
|
|
100
|
+
const ran = jobs?.get?.(newest.id);
|
|
101
|
+
if (!Array.isArray(ran)) return `${file} run ${newest.id}'s jobs can't be read`;
|
|
102
|
+
for (const name of names) {
|
|
103
|
+
const named = ran.filter(job => job?.name === name);
|
|
104
|
+
if (named.length !== 1) return `${name}: ${named.length === 0 ? "no" : named.length} job${named.length === 1 ? "" : "s"} of that name in ${file} run ${newest.id}`;
|
|
105
|
+
const job = named[0];
|
|
106
|
+
if (job.head_sha !== head || job.run_id !== newest.id) return `${name}: its job isn't on ${head.slice(0, 7)} in run ${newest.id}`;
|
|
107
|
+
if (job.status !== "completed" || job.conclusion !== "success") return `${name}: ${job.status !== "completed" ? String(job.status) : String(job.conclusion)} in ${file} run ${newest.id}${job.conclusion === "skipped" ? " (a skipped job is not a tested one)" : ""}`;
|
|
108
|
+
if (!Number.isFinite(timestamp(job.completed_at)) || timestamp(job.completed_at) > mergedAt) return `${name}: not proven passed before pull request #${pr.number} merged`;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const flag = (args, name) => { const at = args.indexOf(`--${name}`); return at === -1 ? undefined : args[at + 1]; };
|
|
115
|
+
|
|
116
|
+
/** One GitHub API read, with the workflow's token sent to GitHub's API alone. */
|
|
117
|
+
async function fetchApi(path) {
|
|
118
|
+
const token = process.env.GITHUB_TOKEN;
|
|
119
|
+
if (typeof token !== "string" || token === "") throw new Error("no GITHUB_TOKEN");
|
|
120
|
+
const response = await fetch(`https://api.github.com/${path}`, {
|
|
121
|
+
headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28" }, redirect: "error",
|
|
122
|
+
});
|
|
123
|
+
if (!response.ok) throw new Error(`GitHub answered ${response.status} for ${path.replace(/\?.*/, "")}`);
|
|
124
|
+
return response.json();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Read every page, refusing truncation, duplicate rows and changing totals. Never follow a response-supplied URL. */
|
|
128
|
+
async function pages(api, path, key, identity) {
|
|
129
|
+
const all = [], seen = new Set();
|
|
130
|
+
let total;
|
|
131
|
+
for (let page = 1; page <= 100; page++) {
|
|
132
|
+
const body = await api(`${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`);
|
|
133
|
+
const rows = key === undefined ? body : body?.[key];
|
|
134
|
+
if (!Array.isArray(rows) || rows.length > 100) throw new Error(`${path}: unreadable page`);
|
|
135
|
+
if (key !== undefined) {
|
|
136
|
+
if (!Number.isSafeInteger(body.total_count) || body.total_count < 0 || (total !== undefined && total !== body.total_count)) throw new Error(`${path}: unreadable or changing total`);
|
|
137
|
+
total = body.total_count;
|
|
138
|
+
}
|
|
139
|
+
for (const row of rows) {
|
|
140
|
+
if (row === null || typeof row !== "object") throw new Error(`${path}: unreadable row`);
|
|
141
|
+
if (identity !== undefined) {
|
|
142
|
+
const id = row[identity];
|
|
143
|
+
if (!Number.isSafeInteger(id) || id < 1 || seen.has(id)) throw new Error(`${path}: missing or duplicate ${identity}`);
|
|
144
|
+
seen.add(id);
|
|
145
|
+
}
|
|
146
|
+
all.push(row);
|
|
147
|
+
}
|
|
148
|
+
if (total !== undefined && all.length > total) throw new Error(`${path}: too many rows`);
|
|
149
|
+
if (rows.length < 100 || all.length === total) {
|
|
150
|
+
if (total !== undefined && all.length !== total) throw new Error(`${path}: incomplete list`);
|
|
151
|
+
return all;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
throw new Error(`${path}: pagination limit; no complete proof`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The current remote tag, peeled without trusting a checkout's cached refs (including annotated tags). */
|
|
158
|
+
export async function verifyTag(repo, sha, tag, api = fetchApi) {
|
|
159
|
+
if (typeof tag !== "string" || !/^v[0-9A-Za-z][0-9A-Za-z.+_-]*$/.test(tag)) throw new Error("--tag must name a version tag");
|
|
160
|
+
const ref = await api(`repos/${repo}/git/ref/tags/${encodeURIComponent(tag)}`);
|
|
161
|
+
if (ref?.ref !== `refs/tags/${tag}`) throw new Error("GitHub didn't describe the exact tag");
|
|
162
|
+
let object = ref.object;
|
|
163
|
+
const seen = new Set();
|
|
164
|
+
while (object?.type === "tag") {
|
|
165
|
+
if (!SHA.test(object.sha ?? "") || seen.has(object.sha) || seen.size >= 8) throw new Error("unreadable tag chain");
|
|
166
|
+
seen.add(object.sha);
|
|
167
|
+
const peeled = await api(`repos/${repo}/git/tags/${object.sha}`);
|
|
168
|
+
if (peeled?.sha !== object.sha) throw new Error("GitHub described another tag object");
|
|
169
|
+
object = peeled.object;
|
|
170
|
+
}
|
|
171
|
+
if (object?.type !== "commit" || object.sha !== sha) throw new Error(`${tag} no longer names the proven commit ${sha}`);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The whole proof, as publish.yml runs it: every read below, then proofProblem. `api(path)` is one GitHub API read that
|
|
176
|
+
* answers parsed JSON or throws (publish.yml: fetch with the workflow's token; `toolroll release`: the plane's signed-in
|
|
177
|
+
* gh, its own reader). Resolves `{ ok: true, pr, head, branch, tree }` or `{ ok: false, why }`; never trusts a checkout.
|
|
178
|
+
*/
|
|
179
|
+
export async function proveRelease({ repo, sha, required }, api = fetchApi) {
|
|
180
|
+
try {
|
|
181
|
+
if (!REPO.test(repo ?? "") || !SHA.test(sha ?? "")) throw new Error("--repo owner/name and --sha <40 hex> are required");
|
|
182
|
+
if (parseRequired(JSON.stringify(required ?? null)) === null) throw new Error("--required must map each check name to a workflow this proof knows");
|
|
183
|
+
const commit = await api(`repos/${repo}/git/commits/${sha}`);
|
|
184
|
+
const pulls = await pages(api, `repos/${repo}/commits/${sha}/pulls`, undefined, "number");
|
|
185
|
+
const merged = mergedPulls(pulls, repo, sha);
|
|
186
|
+
if (merged.length !== 1) throw new Error(`expected exactly one merged pull request into main, found ${merged.length}`);
|
|
187
|
+
const pr = merged[0];
|
|
188
|
+
const head = pr?.head?.sha;
|
|
189
|
+
const headCommit = SHA.test(head ?? "") ? await api(`repos/${repo}/git/commits/${head}`) : null;
|
|
190
|
+
if (!SHA.test(head ?? "") || !Number.isSafeInteger(pr.number) || pr.number < 1) throw new Error("no pull request head or number");
|
|
191
|
+
// One parent alone also describes the last commit of a multi-commit rebase. A squash adds exactly one commit,
|
|
192
|
+
// whose parent was already in the tested head's history (the release coordinator requires an up-to-date head).
|
|
193
|
+
const comparison = await api(`repos/${repo}/compare/${head}...${sha}`);
|
|
194
|
+
if (comparison?.base_commit?.sha !== head || comparison?.ahead_by !== 1
|
|
195
|
+
|| !SHA.test(commit?.parents?.[0]?.sha ?? "") || comparison?.merge_base_commit?.sha !== commit.parents[0].sha
|
|
196
|
+
|| !Array.isArray(comparison.commits) || comparison.commits.length !== 1 || comparison.commits[0]?.sha !== sha) throw new Error("not a single squash commit on the tested head's ancestry");
|
|
197
|
+
const owner = repo.split("/")[0];
|
|
198
|
+
const branchPulls = await pages(api, `repos/${repo}/pulls?state=all&head=${encodeURIComponent(`${owner}:${pr?.head?.ref ?? ""}`)}`, undefined, "number");
|
|
199
|
+
const runsPath = `repos/${repo}/actions/runs?head_sha=${head}`;
|
|
200
|
+
const runs = await pages(api, runsPath, "workflow_runs", "id");
|
|
201
|
+
const jobs = new Map();
|
|
202
|
+
for (const file of new Set(Object.values(required))) {
|
|
203
|
+
const newest = provingRun(runs, file, { repo, head, branch: pr?.head?.ref });
|
|
204
|
+
if (newest === undefined || !Number.isSafeInteger(newest.run_attempt) || newest.run_attempt < 1) continue;
|
|
205
|
+
jobs.set(newest.id, await pages(api, `repos/${repo}/actions/runs/${newest.id}/attempts/${newest.run_attempt}/jobs`, "jobs", "id"));
|
|
206
|
+
}
|
|
207
|
+
// GitHub's run PR metadata changes on retargeting. As in readCheckRuns, refuse a PR that ever changed base.
|
|
208
|
+
const timeline = await pages(api, `repos/${repo}/issues/${pr.number}/timeline`);
|
|
209
|
+
if (timeline.some(event => typeof event.event !== "string" || event.event === "base_ref_changed")) throw new Error("pull request base changed or its timeline is unreadable");
|
|
210
|
+
// The attempt may have changed while we paged through its jobs. Do not combine the old attempt with a new run.
|
|
211
|
+
const fresh = await pages(api, runsPath, "workflow_runs", "id");
|
|
212
|
+
for (const file of new Set(Object.values(required))) {
|
|
213
|
+
const before = provingRun(runs, file, { repo, head, branch: pr.head.ref });
|
|
214
|
+
const after = provingRun(fresh, file, { repo, head, branch: pr.head.ref });
|
|
215
|
+
if (before?.id !== after?.id || before?.run_attempt !== after?.run_attempt || before?.status !== after?.status) throw new Error(`${file}: newest run or attempt changed during proof`);
|
|
216
|
+
}
|
|
217
|
+
const problem = proofProblem({ repo, sha, required, commit, pulls, headCommit, runs: fresh, runsTotal: fresh.length, jobs, branchPulls });
|
|
218
|
+
if (problem !== null) return { ok: false, why: problem };
|
|
219
|
+
return { ok: true, pr: pr.number, head, branch: pr.head.ref, tree: commit.tree.sha };
|
|
220
|
+
} catch (error) { return { ok: false, why: String(error?.message ?? error) }; }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {
|
|
224
|
+
const [command, ...args] = process.argv.slice(2);
|
|
225
|
+
try {
|
|
226
|
+
if (command !== "verify" && command !== "tag") { console.error("usage: release-proof.mjs verify|tag --repo <owner/name> --sha <commit> [--required <JSON>] [--tag <version>]"); process.exit(2); }
|
|
227
|
+
const repo = flag(args, "repo") ?? "", sha = flag(args, "sha") ?? "", required = parseRequired(flag(args, "required") ?? "");
|
|
228
|
+
if (!REPO.test(repo) || !SHA.test(sha)) throw new Error("--repo owner/name and --sha <40 hex> are required");
|
|
229
|
+
if (command === "tag") {
|
|
230
|
+
await verifyTag(repo, sha, flag(args, "tag"));
|
|
231
|
+
console.log(`The remote tag still names ${sha}.`);
|
|
232
|
+
process.exit(0);
|
|
233
|
+
}
|
|
234
|
+
if (required === null) throw new Error("--required must map each check name to a workflow this proof knows");
|
|
235
|
+
const proven = await proveRelease({ repo, sha, required });
|
|
236
|
+
if (!proven.ok) { console.error(`Not proven: ${proven.why}.`); process.exit(1); }
|
|
237
|
+
if (args.includes("--tag")) await verifyTag(repo, sha, flag(args, "tag"));
|
|
238
|
+
console.log(`${sha} is pull request #${proven.pr}'s head tree (${proven.head}), and every one of its ${Object.keys(required).length} required checks passed there.`);
|
|
239
|
+
} catch (error) { console.error(`Not proven: ${String(error?.message ?? error)}.`); process.exit(1); }
|
|
240
|
+
}
|