toolroll 0.9.118 → 0.9.119

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +14 -14
  3. package/dist/assignment.js +40 -29
  4. package/dist/browser/workspace.css +1 -1
  5. package/dist/browser/workspace.js +32 -31
  6. package/dist/builder.js +286 -236
  7. package/dist/central-recovery-stage.js +3 -3
  8. package/dist/check-failure.js +2 -2
  9. package/dist/check-levels.js +3 -0
  10. package/dist/check-report.js +58 -7
  11. package/dist/contracts/console-api.js +4 -1
  12. package/dist/contracts/engine-api.js +1 -0
  13. package/dist/contracts/release-check.js +7 -4
  14. package/dist/contracts/release-terms.js +11 -2
  15. package/dist/contracts/verification-receipt.js +1 -1
  16. package/dist/deploy-gate.js +7 -1
  17. package/dist/direct-chat.js +3 -3
  18. package/dist/easy-start.js +8 -6
  19. package/dist/engine-reads.js +72 -0
  20. package/dist/flexible-conversation-schema.js +24 -0
  21. package/dist/flexible-conversation.js +162 -0
  22. package/dist/flexible-custody.js +3 -0
  23. package/dist/flexible-import.js +51 -0
  24. package/dist/flexible-session.js +84 -11
  25. package/dist/install-mode.js +1 -1
  26. package/dist/local-landing.js +500 -0
  27. package/dist/local-owner.js +1 -0
  28. package/dist/operate.js +143 -22
  29. package/dist/passwordless.js +1 -1
  30. package/dist/project-delete.js +1 -0
  31. package/dist/rehearsal.js +27 -0
  32. package/dist/release-adapters.js +170 -2
  33. package/dist/release-approval.js +11 -8
  34. package/dist/release-card.js +7 -2
  35. package/dist/release-carry.js +1 -1
  36. package/dist/release-cli.js +115 -14
  37. package/dist/release-main-proof.js +49 -0
  38. package/dist/release-main.js +110 -0
  39. package/dist/release-recheck.js +10 -3
  40. package/dist/release.js +221 -33
  41. package/dist/reply-shape.js +6 -1
  42. package/dist/result-actions.js +7 -1
  43. package/dist/result-follow-ups.js +8 -4
  44. package/dist/serve.js +31 -14
  45. package/dist/server/direct-chat.js +88 -3
  46. package/dist/server/engine-api.js +43 -5
  47. package/dist/server/render-results.js +3 -1
  48. package/dist/server/render-tasks.js +10 -1
  49. package/dist/server/route-table.js +9 -0
  50. package/dist/server/settings.js +31 -7
  51. package/dist/server/task-views.js +15 -0
  52. package/dist/server/tasks.js +63 -3
  53. package/dist/settings-groups-ui.js +2 -2
  54. package/dist/store.js +29 -4
  55. package/dist/surface.js +9 -1
  56. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  57. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  58. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  59. package/dist/tui/linux-x64/toolroll-tui +0 -0
  60. package/dist/verification-evidence.js +17 -6
  61. package/dist/workspace-ui.js +1 -1
  62. package/package.json +2 -1
  63. package/scripts/release-proof.mjs +240 -0
package/dist/store.js CHANGED
@@ -39,6 +39,7 @@ import { V180_SCHEMA, V180_STEPS } from "./agent-change-schema.js";
39
39
  import { V181_REQUIRED_COLUMNS, V181_SCHEMA, V181_STEPS, V181_TABLES, V182_REQUIRED_COLUMNS, V182_SCHEMA, V182_STEPS, V182_TABLES, V183_ADDED_COLUMNS, V183_STEPS, V184_ADDED_COLUMNS, V184_STEPS } from "./direct-chat-schema.js";
40
40
  import { V177_STEPS, V177_SCHEMA, V177_OBJECTS, WORKSPACE_ID_PATTERN, RECOVERY_GENERATION_PATTERN } from "./workspace-identity-schema.js";
41
41
  import { V174_OBJECTS, V174_SCHEMA, V174_STEPS } from "./flexible-everyday-schema.js";
42
+ import { V185_OBJECTS, V185_SCHEMA, V185_STEPS } from "./flexible-conversation-schema.js";
42
43
  import { endThreadAuthorityFor } from "./flexible-authority-end.js";
43
44
  import { relayCancel } from "./flexible-relay-cancel.js";
44
45
  import { endLapsedFlexible } from "./flexible.js";
@@ -845,7 +846,7 @@ export function checkSuitesOf(value) {
845
846
  }
846
847
  }
847
848
  const REGISTERED_AT_FILING = "again, as it was filed";
848
- export const SCHEMA_VERSION = 184;
849
+ export const SCHEMA_VERSION = 185;
849
850
  export const V179_STEPS = Object.freeze(["antigravity-provider"]);
850
851
  export const V118_MERGED_TABLES = Object.freeze({ api_token: "person", coordinator_credential: "coordinator", lead_credential: "lead" });
851
852
  const V118_REFERENCES = /REFERENCES (?:coordinator_credential\(cid\)|api_token\(id\))/g;
@@ -911,7 +912,7 @@ export const V115_DROPPED_TABLES = Object.freeze([
911
912
  "fallback_config", "fallback_cycle", "fallback_transition",
912
913
  ]);
913
914
  const V115_DROPPED_REFERENCES = /\s+REFERENCES (?:contestant|contest|tournament_terms|session_turn|attended_authorization|held_session|fallback_cycle|fallback_config|fallback_transition|routine|routine_fire)\(id\)(?: ON DELETE CASCADE)?/g;
914
- export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184]);
915
+ export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185]);
915
916
  export const V119_ADDED_COLUMNS = Object.freeze({
916
917
  task_ref: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
917
918
  run: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
@@ -1454,7 +1455,7 @@ export { V156_STEPS };
1454
1455
  export { V157_STEPS };
1455
1456
  export { V158_STEPS };
1456
1457
  export { V159_STEPS };
1457
- export { V160_STEPS, V161_STEPS, V162_STEPS, V163_STEPS, V164_STEPS, V165_STEPS, V166_STEPS, V167_STEPS, V168_STEPS, V169_STEPS, V170_STEPS, V171_STEPS, V172_STEPS, V173_STEPS, V174_STEPS, V175_STEPS, V176_STEPS, V177_STEPS, V178_STEPS, V180_STEPS, V181_STEPS, V182_STEPS, V183_STEPS, V184_STEPS };
1458
+ export { V160_STEPS, V161_STEPS, V162_STEPS, V163_STEPS, V164_STEPS, V165_STEPS, V166_STEPS, V167_STEPS, V168_STEPS, V169_STEPS, V170_STEPS, V171_STEPS, V172_STEPS, V173_STEPS, V174_STEPS, V175_STEPS, V176_STEPS, V177_STEPS, V178_STEPS, V180_STEPS, V181_STEPS, V182_STEPS, V183_STEPS, V184_STEPS, V185_STEPS };
1458
1459
  export const RELEASE_ONCE_SCHEMA = `
1459
1460
  CREATE TABLE IF NOT EXISTS release_authority (
1460
1461
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -4243,7 +4244,7 @@ function initializeStore(db, file, options = {}) {
4243
4244
  throw new Error(`${file}: ${problem}; refusing to move chat history it cannot name`);
4244
4245
  }
4245
4246
  if (preflight === SCHEMA_VERSION && !findingSourcesStale(db)) {
4246
- const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db) ?? flexibleTermsShapeProblem(db) ?? flexibleThreadShapeProblem(db) ?? typedByPersonShapeProblem(db) ?? flexibleTurnsShapeProblem(db) ?? flexibleLaunchShapeProblem(db) ?? flexibleRelayShapeProblem(db) ?? flexibleAnswersShapeProblem(db) ?? flexibleShipShapeProblem(db) ?? taskSizingShapeProblem(db) ?? agentSaidShapeProblem(db) ?? flexibleSettingShapeProblem(db) ?? flexibleSignInShapeProblem(db) ?? planProblemsShapeProblem(db) ?? flexibleEverydayShapeProblem(db) ?? flexibleInteractiveShapeProblem(db) ?? subagentBackupShapeProblem(db) ?? workspaceIdentityShapeProblem(db) ?? pendingAgentChangeShapeProblem(db) ?? directChatShapeProblem(db) ?? directChatPhase1bShapeProblem(db) ?? directChatHardeningShapeProblem(db);
4247
+ const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db) ?? flexibleTermsShapeProblem(db) ?? flexibleThreadShapeProblem(db) ?? typedByPersonShapeProblem(db) ?? flexibleTurnsShapeProblem(db) ?? flexibleLaunchShapeProblem(db) ?? flexibleRelayShapeProblem(db) ?? flexibleAnswersShapeProblem(db) ?? flexibleShipShapeProblem(db) ?? taskSizingShapeProblem(db) ?? agentSaidShapeProblem(db) ?? flexibleSettingShapeProblem(db) ?? flexibleSignInShapeProblem(db) ?? planProblemsShapeProblem(db) ?? flexibleEverydayShapeProblem(db) ?? flexibleInteractiveShapeProblem(db) ?? subagentBackupShapeProblem(db) ?? workspaceIdentityShapeProblem(db) ?? pendingAgentChangeShapeProblem(db) ?? directChatShapeProblem(db) ?? directChatPhase1bShapeProblem(db) ?? directChatHardeningShapeProblem(db) ?? flexibleConversationShapeProblem(db);
4247
4248
  if (missing !== null)
4248
4249
  throw new Error(`${file}: refusing to open — ${missing}, though the schema says v${SCHEMA_VERSION}`);
4249
4250
  db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
@@ -4728,6 +4729,11 @@ CREATE INDEX IF NOT EXISTS run_checkpoint_by_task ON run_checkpoint (task_ref, i
4728
4729
  if (directChatEffortDamaged !== null)
4729
4730
  throw new Error(`${file}: refusing to open — ${directChatEffortDamaged}`);
4730
4731
  step("direct-chat-effort-usage-columns");
4732
+ db.exec(V185_SCHEMA);
4733
+ const conversationDamaged = flexibleConversationShapeProblem(db);
4734
+ if (conversationDamaged !== null)
4735
+ throw new Error(`${file}: refusing to open — ${conversationDamaged}`);
4736
+ step("flexible-conversation");
4731
4737
  if (!fresh)
4732
4738
  reclaimDatabase(db, "migration");
4733
4739
  const expectedMarker = preflight < 0 ? preflight : -preflight;
@@ -19665,3 +19671,22 @@ function directChatEffortUsageShapeProblem(db) {
19665
19671
  }
19666
19672
  return null;
19667
19673
  }
19674
+ function flexibleConversationShapeProblem(db) {
19675
+ const statements = V185_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
19676
+ for (const [type, name] of V185_OBJECTS) {
19677
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
19678
+ if (row === undefined)
19679
+ return `the interactive agent threads ${type} ${name} is missing`;
19680
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
19681
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want.replace(/;$/, "")).trim())
19682
+ return `the interactive agent threads ${type} ${name} has an unknown shape`;
19683
+ }
19684
+ return null;
19685
+ }
19686
+ export function verifyCommandAt(store, repo, at) {
19687
+ const when = at.toISOString();
19688
+ const row = store.handle
19689
+ .prepare("SELECT * FROM verify_command WHERE repo = ? AND approved_at <= ? AND (revoked_at IS NULL OR revoked_at > ?) ORDER BY id DESC LIMIT 1")
19690
+ .get(repo, when, when);
19691
+ return row === undefined ? null : { ...readVerifyCommand(row), revokedAt: null, revokedBy: null };
19692
+ }
package/dist/surface.js CHANGED
@@ -309,6 +309,13 @@ const GUIDE_ROWS = [
309
309
  { name: "digest", takesValue: true, meaning: "the exact receipt from assignment show; accepts and finishes exactly that result" },
310
310
  { name: "despite", takesValue: true, meaning: "accept with this reason, without finishing; never combines with --finish or --digest (--note is its alias)" }],
311
311
  notableReasons: ["usage", "unknown-task", "no-run", "not-ready"] },
312
+ { ...operator("task land", "put accepted work on the project's own branch when it has no pull requests: bare shows exactly what lands where; --yes --key <key> lands it as a fast-forward; --undo reverts it with a new commit"),
313
+ positionals: [{ name: "id", required: true, meaning: "the task" }],
314
+ flags: [jsonFlag, dbFlag, { name: "into", takesValue: true, meaning: "land on this branch instead of the recorded one (the yes records it)" },
315
+ { name: "undo", takesValue: false, meaning: "revert the landing with a new commit on the branch" },
316
+ { name: "yes", takesValue: false, meaning: "land it; needs --key" },
317
+ { name: "key", takesValue: true, meaning: "the key the bare call showed: what lands is what you read" }],
318
+ notableReasons: ["usage", "not-complete", "checks", "dirty", "moved", "occupied", "stale"] },
312
319
  operator("task repair", "inspect or approve a repair draft; --yes starts the repair a failed check is waiting for, under the normal plan approval"),
313
320
  operatorRead("task handover", "where a task stands, from Toolroll's records: revision, decisions, rejected approaches, open findings, checks and the next action"),
314
321
  operator("task before-after", "before-and-after evidence: read it, save a failing result, or rerun the same check on the latest commit with no agent"),
@@ -492,7 +499,7 @@ const REMOTE_FOLLOW_THROUGH = [
492
499
  ];
493
500
  const REMOTE_STEP_UP = [
494
501
  "proposals", "decide", "task regate", "task approve", "task accept", "task merge", "run settle",
495
- "task archive", "task restore", "task tidy", "knowledge apply",
502
+ "task archive", "task restore", "task tidy", "task land", "knowledge apply",
496
503
  "memory decide", "memory retire", "memory apply", "memory tidy", "memory restore", "memory unmerge",
497
504
  "flows card approve", "flows card send-back", "flows script approve", "flows unattended",
498
505
  "approver list", "approver add", "people list", "people invite", "people projects", "people revoke",
@@ -541,6 +548,7 @@ const LOCAL_ALLOW = {
541
548
  "task continue": "resume-run",
542
549
  "task unhold": "resume-run",
543
550
  "task complete": "complete-task",
551
+ "task land": "land-task",
544
552
  "task plan": "request-plan",
545
553
  "task requeue": "retry-build",
546
554
  "task revise": "request-revision",
Binary file
Binary file
Binary file
Binary file
@@ -7,14 +7,17 @@ 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";
13
16
  export const VERIFICATION_RECEIPT_CAPTURE = "machine verification receipt v1";
14
17
  const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
15
18
  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
19
  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";
20
+ export const coveragePasses = (coverage) => coverage === undefined || coverage === "full" || coverage === "composed" || coverage === "deploy";
18
21
  export function effectiveCheckFacts(raw, facts) {
19
22
  if (facts === null || coveragePasses(facts.coverage))
20
23
  return { result: raw, facts };
@@ -41,7 +44,7 @@ export function sealVerificationReceipt(store, root, runId, head, command, resul
41
44
  const hits = scanForSecrets(raw);
42
45
  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
46
  }
44
- export function verificationEvidence(store, root, runId) {
47
+ export function verificationEvidence(store, root, runId, asOf) {
45
48
  const fail = (problem) => ({ ok: false, problem });
46
49
  const source = store.getRun(runId);
47
50
  if (!source)
@@ -53,7 +56,8 @@ export function verificationEvidence(store, root, runId) {
53
56
  const verified = (machine?.machineVerdict ?? machine?.verdict) === "verified";
54
57
  if (!receipts.length && !verified && runCheckLevel(store, runId) === "off")
55
58
  return { ok: true, bytes: null, digest: hash(null) };
56
- const command = repo ? sealedCommandKey(root, receipts) === quickVerifyKey(repo) ? liveQuickCommand(store, repo) : store.liveVerifyCommand(repo) : null;
59
+ const commandOf = (key) => asOf === undefined ? store.liveVerifyCommand(key) : verifyCommandAt(store, key, asOf);
60
+ const command = repo ? sealedCommandKey(root, receipts) === quickVerifyKey(repo) ? asOf === undefined ? liveQuickCommand(store, repo) : commandOf(quickVerifyKey(repo)) : commandOf(repo) : null;
57
61
  if (!command && !receipts.length && !verified)
58
62
  return { ok: true, bytes: null, digest: hash(null) };
59
63
  if (!command || command.approvedAt > source.startedAt)
@@ -94,7 +98,7 @@ export function verificationEvidence(store, root, runId) {
94
98
  if (!brief || !readObservationEvidence(store, root, runId) || !reused || reused.run !== brief.sourceRun || reused.run >= runId || reused.digest !== brief.gateDigest ||
95
99
  source.baseRevision !== brief.head || source.headRevision !== brief.head || checked.executedHere !== false)
96
100
  return fail("The reused gate is not bound to an unchanged observation follow-up.");
97
- const original = verificationEvidence(store, root, reused.run);
101
+ const original = verificationEvidence(store, root, reused.run, asOf);
98
102
  if (!original.ok || !original.bytes || original.digest !== reused.digest)
99
103
  return fail("The original passing gate no longer verifies.");
100
104
  const previousRead = readVerificationView(original.bytes);
@@ -131,6 +135,13 @@ export function verificationEvidence(store, root, runId) {
131
135
  }
132
136
  if ((checked.coverage === "composed") !== (checked.composed !== undefined))
133
137
  return fail("The release check's coverage and its links disagree.");
138
+ if (checked.coverage === "deploy") {
139
+ const inventory = readSealedJson(store, root, runId, CHECK_INVENTORY_CAPTURE);
140
+ const sealed = inventory === null ? null : parseContract(sealedInventorySchema, inventory.value);
141
+ const purpose = store.getScope(store.refById(source.taskRef)?.externalId ?? "")?.releaseCheck ?? null;
142
+ if (sealed === null || !sealed.ok || sealed.value.sealed.deploy !== true || purposeCheckMode(purpose) !== "deploy")
143
+ return fail("A deploy check's receipt isn't for a release from main sealed with the deploy check.");
144
+ }
134
145
  if (!coveragePasses(checked.coverage) && checked.result.configured && checked.result.ran && checked.result.exitCode === 0)
135
146
  return fail("The release check reads as passed, but its coverage fell short.");
136
147
  if (checked.composed !== undefined) {
@@ -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. The branch stays; publishing isn't set up."
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.118",
3
+ "version": "0.9.119",
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
+ }