spur-board 0.131.0 → 0.133.0
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/dist/{chunk-DfehZM2s.mjs → chunk-BC8T5XHO.mjs} +1 -1
- package/dist/{chunk-CY_rWPWy.mjs → chunk-CcqlB4rN.mjs} +52 -5
- package/dist/{chunk-BUWlIiQd.mjs → chunk-CjHIyoJR.mjs} +2 -2
- package/dist/cli.mjs +3 -3
- package/dist/client.mjs +1 -1
- package/dist/daemon.mjs +609 -57
- package/dist/mcp.mjs +3 -3
- package/dist/web/assets/index-DrlglJWZ.js +64 -0
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/skills/spur-board/SKILL.md +9 -0
- package/skills/spur-board/references/how-board-works-columns.md +5 -4
- package/skills/spur-board/references/how-board-works-inbox.md +1 -0
- package/skills/spur-board/references/how-board-works-turns.md +2 -0
- package/skills/spur-board/references/worker-flow.md +13 -2
- package/dist/web/assets/index-CFUr0JGj.js +0 -64
package/dist/daemon.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as REF_NUMBER, A as eventPayloadSchemas, At as ITEM_KINDS, B as REVIEW_DECISIONS, C as messageRefSchema, Ct as plainHttpAllowed, D as sortSkillFiles, Dt as COLUMN_GROUPS, E as skillReloadFilesSchema, Et as COLUMNS, F as prSourceId, Ft as isTodoGroupColumn, G as parseRingMarker, H as SESSION_HEALTH_STATES, I as sessionTransitionSchema, J as prReviewRuleSchema, K as prFactsSchema, L as sourceCursorSchema, M as batchSchema, Mt as TASK_HOLDS, N as defaultBranchFactSchema, Nt as TODO_GROUP_COLUMN_IDS, O as EVENT_KINDS, Ot as COLUMN_IDS, P as entityRefSchema, Pt as VIAS, Q as JIRA_PROJECT_KEY, R as trackerSourceId, S as interactionRefSchema, St as defaultAddressee, Tt as resolveWebOrigin, U as SESSION_STATUSES, V as REVIEW_STATES, W as isExternalAuthor, X as sessionFactsSchema, Y as ringMarker, Z as ticketFactsSchema, _t as approvalRuleOf, a as requestHashOf, at as ERRORS, b as conversationRefSchema, bt as configBindings, c as tokenRequestStatusSchema, d as buildCatalogSnapshot, et as actorIdSchema, f as roleCanUseOperation, ft as DEFAULT_LINK, g as renderHttpProblem, gt as RESERVED_PROJECT, h as turnHandedSchema, i as TOKEN_REQUEST_LIMITS, it as parseRef$1, j as AdapterError, jt as SLACK_BOT_SCOPES, k as GATE_REASONS, kt as DISPATCHER_MODES, l as BOARD_TICK_MS, lt as ok, m as defaultBranchViewSchema, mt as DEFAULT_SLACK_COMMAND, n as doctorReportSchema, nt as errorCodeOf, o as tokenRequestResultSchema, ot as err, p as OPERATIONS, q as prRefSchema, rt as parseActorId, s as tokenRequestSchema, t as assertNever, tt as encodeActorId, ut as successEnvelopeSchema, vt as boardWideSpurProject, w as userIdSchema, wt as requiredSecretKeys, x as inboundEventSchema, xt as configSchema, y as SPACE_IDS, yt as columnTurnTimings, z as PR_STATES } from "./chunk-CcqlB4rN.mjs";
|
|
2
2
|
import { t as apiBaseUrl } from "./chunk-Bzb7aI8R.mjs";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import { createHash, randomUUID } from "node:crypto";
|
|
@@ -8298,6 +8298,15 @@ async function turnReturn(db, turn) {
|
|
|
8298
8298
|
};
|
|
8299
8299
|
}
|
|
8300
8300
|
}
|
|
8301
|
+
/**
|
|
8302
|
+
* The open `code` block of the return that opened `turn`'s visit while it is still addressed to
|
|
8303
|
+
* the turn's role, else undefined. Taking the turn reads it; the turn's submit closes it.
|
|
8304
|
+
*/
|
|
8305
|
+
async function openReturnBlock(db, turn) {
|
|
8306
|
+
const returned = await turnReturn(db, turn);
|
|
8307
|
+
if (returned === void 0) return void 0;
|
|
8308
|
+
return db.selectFrom("block").selectAll().where("id", "=", Number(returned.block.slice(1))).where("task_id", "=", turn.task_id).where("state", "=", "open").where("type", "=", "code").where("addressee_role", "=", turn.role).executeTakeFirst();
|
|
8309
|
+
}
|
|
8301
8310
|
function taskView(task) {
|
|
8302
8311
|
return {
|
|
8303
8312
|
key: task.key,
|
|
@@ -8778,6 +8787,8 @@ const BLOCK_KEY = "block:";
|
|
|
8778
8787
|
const CONVERSATION_KEY = "conversation:";
|
|
8779
8788
|
/** The item of a named-orchestrator column whose untaken turns have no live session to ring. */
|
|
8780
8789
|
const NO_SESSION_KEY = "no-session:";
|
|
8790
|
+
/** The item of a github-rules task whose PR head GitHub has left undecided in External Review. */
|
|
8791
|
+
const REVIEW_RULE_KEY = "review-rule:";
|
|
8781
8792
|
/** The block an item is about: its ledger block, else the block its key names. */
|
|
8782
8793
|
function itemBlockRef(item) {
|
|
8783
8794
|
if (item.block_id !== null) return item.block_id;
|
|
@@ -12301,6 +12312,15 @@ async function closeBlockIfOpen(trx, blockId, ctx, outcome, outcomeReason) {
|
|
|
12301
12312
|
if (block === void 0) return;
|
|
12302
12313
|
await closeOpenBlock(trx, await blockSubject(trx, block), block, ctx, outcome, outcomeReason);
|
|
12303
12314
|
}
|
|
12315
|
+
/**
|
|
12316
|
+
* Closes the open `code` block of the return that opened `turn`'s visit (`openReturnBlock`) as
|
|
12317
|
+
* done at `sha`: the turn's submit, once confirmed, answered it. A pending submit waits, so a
|
|
12318
|
+
* voided one leaves the block to the next submit.
|
|
12319
|
+
*/
|
|
12320
|
+
async function answerReturn(trx, task, turn, ctx, sha) {
|
|
12321
|
+
const block = await openReturnBlock(trx, turn);
|
|
12322
|
+
if (block !== void 0) await closeOpenBlock(trx, taskSubject(task), block, ctx, "done", sha);
|
|
12323
|
+
}
|
|
12304
12324
|
/** The thread messages that close an operator conversation, compared after trimming. */
|
|
12305
12325
|
const CLOSE_COMMANDS = /* @__PURE__ */ new Set([
|
|
12306
12326
|
"close",
|
|
@@ -12677,14 +12697,29 @@ function createBlockMutations(config) {
|
|
|
12677
12697
|
if (unread !== void 0) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
|
|
12678
12698
|
throw new CommandError("not_found", "No unread block notification.");
|
|
12679
12699
|
}
|
|
12680
|
-
/**
|
|
12700
|
+
/**
|
|
12701
|
+
* Takes a turn; a turn the caller took or was rung for before it closed is already handled.
|
|
12702
|
+
* Taking the Dev turn of a return also reads the return's open `code` block
|
|
12703
|
+
* (`openReturnBlock`), so its rings stop and it never raises `worker_not_reading`.
|
|
12704
|
+
*/
|
|
12681
12705
|
async function ackTurn(trx, id, ctx) {
|
|
12706
|
+
const at = new Date(ctx.at);
|
|
12682
12707
|
if (await takeTurn(trx, {
|
|
12683
12708
|
turnId: id,
|
|
12684
12709
|
actor: ctx.actor,
|
|
12685
|
-
at
|
|
12710
|
+
at,
|
|
12686
12711
|
config
|
|
12687
|
-
}))
|
|
12712
|
+
})) {
|
|
12713
|
+
const block = await openReturnBlock(trx, await trx.selectFrom("turn").selectAll().where("id", "=", id).executeTakeFirstOrThrow());
|
|
12714
|
+
if (block !== void 0) await acknowledgeNotification(trx, {
|
|
12715
|
+
blockId: block.id,
|
|
12716
|
+
actor: ctx.actor,
|
|
12717
|
+
at,
|
|
12718
|
+
config,
|
|
12719
|
+
takeover: true
|
|
12720
|
+
});
|
|
12721
|
+
return "acked";
|
|
12722
|
+
}
|
|
12688
12723
|
const turn = await trx.selectFrom("turn").selectAll().where("id", "=", id).executeTakeFirst();
|
|
12689
12724
|
if (turn?.acked_by === ctx.actor) return "handled";
|
|
12690
12725
|
if (turn !== void 0 && turn.closed_at !== null) {
|
|
@@ -13035,7 +13070,9 @@ function createMembershipMutations(config) {
|
|
|
13035
13070
|
const HOLD_ONLY = /* @__PURE__ */ new Set([
|
|
13036
13071
|
"mergeable_unknown",
|
|
13037
13072
|
"checks_pending",
|
|
13038
|
-
"comment_history_incomplete"
|
|
13073
|
+
"comment_history_incomplete",
|
|
13074
|
+
"merge_state_unknown",
|
|
13075
|
+
"review_rule_unreadable"
|
|
13039
13076
|
]);
|
|
13040
13077
|
/** Neutral passes like success. Skipped is red: a skipped required check reports no more. */
|
|
13041
13078
|
const VERDICT = {
|
|
@@ -13108,7 +13145,7 @@ function threadsGated(project) {
|
|
|
13108
13145
|
function devReasons(facts, project, waived, threads) {
|
|
13109
13146
|
const opening = CONDITION_DEFINITIONS.pr_open.reasons(facts, project, "dev", waived);
|
|
13110
13147
|
if (opening.length > 0) return opening;
|
|
13111
|
-
return columnConditions("dev", project
|
|
13148
|
+
return columnConditions("dev", project).flatMap((id) => id === "threads_resolved" && !threads ? [] : CONDITION_DEFINITIONS[id].reasons(facts, project, "dev", waived));
|
|
13112
13149
|
}
|
|
13113
13150
|
/**
|
|
13114
13151
|
* The check reasons of a `checksGate` column right of Dev: red or pending checks on the open PR's
|
|
@@ -13130,7 +13167,7 @@ function gateCheckReasons(facts, waived) {
|
|
|
13130
13167
|
function columnCondition(column, facts, project, waived, threads) {
|
|
13131
13168
|
if (column === "dev") return devReasons(facts, project, waived, threads);
|
|
13132
13169
|
if (isTodoGroupColumn(column)) return [];
|
|
13133
|
-
return columnConditions(column, project
|
|
13170
|
+
return [...new Set(columnConditions(column, project).flatMap((id) => CONDITION_DEFINITIONS[id].reasons(facts, project, column, waived)))];
|
|
13134
13171
|
}
|
|
13135
13172
|
/** The positive rule and its predicate have one owner for evaluation and policy reads. */
|
|
13136
13173
|
const CONDITION_DEFINITIONS = {
|
|
@@ -13176,13 +13213,26 @@ const CONDITION_DEFINITIONS = {
|
|
|
13176
13213
|
},
|
|
13177
13214
|
approved: {
|
|
13178
13215
|
text: "Approved by an external reviewer.",
|
|
13179
|
-
reasons: (
|
|
13216
|
+
reasons: ({ externalReviewApproved, reviewRule }) => reviewRule?.changesRequested === true ? ["changes_requested"] : reviewRule?.approved ?? externalReviewApproved ? [] : ["not_approved"]
|
|
13217
|
+
},
|
|
13218
|
+
review_rule_satisfied: {
|
|
13219
|
+
text: "GitHub's review rule for the base branch, from branch protection and rulesets, is satisfied on the current PR head: a required check completed, or, when none is required, every check except skipped ones green and at least one (no checks at all also counts); no changes requested, GitHub's review decision counting only once the merge state is computed; and the merge not blocked. A required check, one GitHub marks required or a context the rule lists, that is pending or missing holds the head on CI unless the merge state is clean, unstable or has hooks; only a run GitHub marks required completes a listed context.",
|
|
13220
|
+
reasons: ({ reviewRule }) => reviewRule === void 0 || reviewRule.changesRequested ? [] : [...RULE_REASONS[reviewRule.decision]]
|
|
13180
13221
|
},
|
|
13181
13222
|
merged: {
|
|
13182
13223
|
text: "The pull request is merged.",
|
|
13183
13224
|
reasons: (facts) => facts.pr?.state === "merged" ? [] : ["not_merged"]
|
|
13184
13225
|
}
|
|
13185
13226
|
};
|
|
13227
|
+
/** The review rule reason of each decision; changes requested fails `approved` instead. */
|
|
13228
|
+
const RULE_REASONS = {
|
|
13229
|
+
satisfied: [],
|
|
13230
|
+
blocked: ["review_rule_blocked"],
|
|
13231
|
+
checks_pending: ["checks_pending"],
|
|
13232
|
+
unresolved_threads: ["unresolved_threads"],
|
|
13233
|
+
unreadable: ["review_rule_unreadable"],
|
|
13234
|
+
undecided: ["merge_state_unknown"]
|
|
13235
|
+
};
|
|
13186
13236
|
/** Effective ownership differs from legacy task explanations: thread failures still name Dev. */
|
|
13187
13237
|
function describeConditions(column, project) {
|
|
13188
13238
|
if (isTodoGroupColumn(column)) return [{
|
|
@@ -13190,7 +13240,7 @@ function describeConditions(column, project) {
|
|
|
13190
13240
|
text: "Work has started: an open PR, or a live worker with a fresh, non-blind Spur source and no reopened ticket. A reopened ticket needs an open PR. Source readiness and holds still apply; no executor turn opens in the Todo group."
|
|
13191
13241
|
}];
|
|
13192
13242
|
const from = threadsFrom(project);
|
|
13193
|
-
const ids = columnConditions(column, project
|
|
13243
|
+
const ids = columnConditions(column, project).filter((id) => id !== "threads_resolved" || from === column);
|
|
13194
13244
|
if (from === column && column !== "dev") {
|
|
13195
13245
|
const checks = ids[0] === "checks_green" ? 1 : 0;
|
|
13196
13246
|
ids.splice(checks, 0, "threads_resolved");
|
|
@@ -13253,10 +13303,15 @@ const COLUMN_CONDITIONS = {
|
|
|
13253
13303
|
done: []
|
|
13254
13304
|
};
|
|
13255
13305
|
/**
|
|
13256
|
-
* The exit conditions of `column`
|
|
13257
|
-
* checks not red, and the gate column requires checks green before its own conditions.
|
|
13306
|
+
* The exit conditions of `column` in `project`: with a `checksGate` right of Dev, Dev requires
|
|
13307
|
+
* checks not red, and the gate column requires checks green before its own conditions. Under
|
|
13308
|
+
* `approvalRule: github-rules`, External Review also requires the review rule satisfied.
|
|
13258
13309
|
*/
|
|
13259
|
-
function columnConditions(column,
|
|
13310
|
+
function columnConditions(column, project) {
|
|
13311
|
+
const conditions = checkConditions(column, project.checksGate);
|
|
13312
|
+
return column === "external-review" && approvalRuleOf(project) === "github-rules" ? [...conditions, "review_rule_satisfied"] : conditions;
|
|
13313
|
+
}
|
|
13314
|
+
function checkConditions(column, checksGate) {
|
|
13260
13315
|
if (checksGate === "dev") return COLUMN_CONDITIONS[column];
|
|
13261
13316
|
if (column === "dev") return COLUMN_CONDITIONS.dev.map((condition) => condition === "checks_green" ? "checks_not_red" : condition);
|
|
13262
13317
|
if (column === checksGate) return ["checks_green", ...COLUMN_CONDITIONS[column]];
|
|
@@ -13264,7 +13319,8 @@ function columnConditions(column, checksGate) {
|
|
|
13264
13319
|
}
|
|
13265
13320
|
/**
|
|
13266
13321
|
* The condition a gate reason fails in `column`: with a gate right of Dev, red checks fail Dev's
|
|
13267
|
-
* checks not red, and every other check reason fails checks green.
|
|
13322
|
+
* checks not red, and every other check reason fails checks green. External Review under
|
|
13323
|
+
* github-rules reads each condition's own reasons instead (`explainGates`).
|
|
13268
13324
|
*/
|
|
13269
13325
|
function conditionOf(reason, column, checksGate) {
|
|
13270
13326
|
if (reason === "checks_red" && column === "dev" && checksGate !== "dev") return "checks_not_red";
|
|
@@ -13285,6 +13341,10 @@ const CONDITION_OF = {
|
|
|
13285
13341
|
no_submit_on_head: "submit_on_head",
|
|
13286
13342
|
no_review_on_head: "review_on_head",
|
|
13287
13343
|
not_approved: "approved",
|
|
13344
|
+
changes_requested: "approved",
|
|
13345
|
+
review_rule_blocked: "review_rule_satisfied",
|
|
13346
|
+
merge_state_unknown: "review_rule_satisfied",
|
|
13347
|
+
review_rule_unreadable: "review_rule_satisfied",
|
|
13288
13348
|
not_merged: "merged"
|
|
13289
13349
|
};
|
|
13290
13350
|
/** Reasons that stop Dev's evaluation: the rest of its conditions are not checked. */
|
|
@@ -13308,8 +13368,11 @@ function explainGates(facts, project) {
|
|
|
13308
13368
|
const gate = evaluateGate(column, facts, project);
|
|
13309
13369
|
const blockedIn = gate.ok ? null : gate.column;
|
|
13310
13370
|
const stopped = reasons.some((reason) => STOPS_DEV.has(reason));
|
|
13311
|
-
const
|
|
13312
|
-
|
|
13371
|
+
const own = isTodoGroupColumn(column) ? [] : columnConditions(column, project);
|
|
13372
|
+
const direct = own.includes("review_rule_satisfied");
|
|
13373
|
+
const conditions = own.map((condition) => {
|
|
13374
|
+
const mine = direct ? CONDITION_DEFINITIONS[condition].reasons(facts, project, column, waived) : [];
|
|
13375
|
+
const reason = reasons.find((r) => direct ? mine.includes(r) : conditionOf(r, column, project.checksGate) === condition) ?? null;
|
|
13313
13376
|
if (reason === null) return {
|
|
13314
13377
|
condition,
|
|
13315
13378
|
state: stopped ? "unchecked" : "met",
|
|
@@ -13847,6 +13910,262 @@ async function withUnconfirmedCancels(trx, source, pr) {
|
|
|
13847
13910
|
requiredChecks: map(pr.requiredChecks)
|
|
13848
13911
|
};
|
|
13849
13912
|
}
|
|
13913
|
+
// ../core/src/domain/review-rule.ts
|
|
13914
|
+
function requiredCheckState(pr, rule) {
|
|
13915
|
+
const listed = rule?.requiredChecks ?? [];
|
|
13916
|
+
const running = (check) => check.state === "expected" || check.state === "pending";
|
|
13917
|
+
if (pr.requiredChecks.length === 0 && listed.length === 0) {
|
|
13918
|
+
if (pr.checks.length === 0) return "done";
|
|
13919
|
+
const optional = pr.checks.filter((check) => check.state !== "skipped");
|
|
13920
|
+
return optional.length > 0 && optional.every((check) => VERDICT[check.state] === "green") ? "done" : "none";
|
|
13921
|
+
}
|
|
13922
|
+
if (pr.requiredChecks.every(running)) return "none";
|
|
13923
|
+
const completed = (context) => pr.requiredChecks.some((check) => check.name === context && !running(check));
|
|
13924
|
+
return pr.requiredChecks.some(running) || listed.some((context) => !completed(context)) ? "pending" : "done";
|
|
13925
|
+
}
|
|
13926
|
+
/** The verdict of one read; see `ReviewRuleVerdict` for the order. */
|
|
13927
|
+
function reviewRuleVerdict(pr, rule, changesRequested, unresolvedThreads) {
|
|
13928
|
+
const checks = requiredCheckState(pr, rule);
|
|
13929
|
+
if (pr.draft || pr.mergeable === "conflicting") return "dev";
|
|
13930
|
+
if (pr.mergeable === "unknown" || pr.mergeState === "unknown") return checks !== "done" ? "checks_pending" : rule === null ? "unreadable" : "unknown";
|
|
13931
|
+
if (checks === "none") return "checks_pending";
|
|
13932
|
+
if (changesRequested) return "changes_requested";
|
|
13933
|
+
if (rule !== null && (pr.mergeState === "clean" || pr.mergeState === "unstable" || pr.mergeState === "has_hooks")) return "satisfied";
|
|
13934
|
+
if (checks === "pending") return "checks_pending";
|
|
13935
|
+
if (rule === null) return "unreadable";
|
|
13936
|
+
if (pr.mergeState !== "blocked") return "undecided";
|
|
13937
|
+
return unresolvedThreads > 0 ? "unresolved_threads" : "blocked";
|
|
13938
|
+
}
|
|
13939
|
+
/**
|
|
13940
|
+
* The one rule for a read of a head, given the decision stored for it:
|
|
13941
|
+
* - GitHub's answer (`satisfied`, or a block with the required checks completed: `blocked` and
|
|
13942
|
+
* `unresolved_threads`) stores it, stops the clock, and the gate reads it over the stored
|
|
13943
|
+
* decision as recorded: a block counts, a satisfied state only through a stored satisfied one
|
|
13944
|
+
* (the project's own read stores it first; another project's read stores nothing), and over no
|
|
13945
|
+
* stored decision the head stays undecided.
|
|
13946
|
+
* - Every other read keeps the stored decision and holds the head: a pending or missing required
|
|
13947
|
+
* check as `checks_pending`, a rule the token could not read as `unreadable`, anything else as
|
|
13948
|
+
* `undecided`. Draft, conflict and changes requested fail Dev's conditions or `approved`.
|
|
13949
|
+
* - The clock runs only while the head has no stored decision, the read is unknown, undecided or
|
|
13950
|
+
* unreadable, and nobody is known to ask for changes (`requested`: a reviewer's latest review or
|
|
13951
|
+
* GitHub's review verdict, also on an unknown merge state).
|
|
13952
|
+
*/
|
|
13953
|
+
function ruleTransition(stored, verdict, requested) {
|
|
13954
|
+
if (verdict === "satisfied" || verdict === "blocked" || verdict === "unresolved_threads") return {
|
|
13955
|
+
decision: verdict === "satisfied" ? "satisfied" : "blocked",
|
|
13956
|
+
gate: stored === null ? "undecided" : verdict === "satisfied" ? stored : verdict,
|
|
13957
|
+
clock: false
|
|
13958
|
+
};
|
|
13959
|
+
return {
|
|
13960
|
+
decision: stored,
|
|
13961
|
+
gate: verdict === "checks_pending" || verdict === "unreadable" ? verdict : "undecided",
|
|
13962
|
+
clock: stored === null && !requested && (verdict === "unknown" || verdict === "undecided" || verdict === "unreadable")
|
|
13963
|
+
};
|
|
13964
|
+
}
|
|
13965
|
+
/**
|
|
13966
|
+
* The latest reviews of external reviewers: not the agents' login, and not a login that wrote
|
|
13967
|
+
* bot feedback on the PR.
|
|
13968
|
+
*/
|
|
13969
|
+
function externalReviews(pr, agentLogin) {
|
|
13970
|
+
const external = (login) => login.toLowerCase() !== agentLogin.toLowerCase() && !(pr.feedback ?? []).some((entry) => entry.author?.type === "bot" && entry.author.login.toLowerCase() === login.toLowerCase());
|
|
13971
|
+
return pr.reviews.filter((review) => external(review.reviewer));
|
|
13972
|
+
}
|
|
13973
|
+
/**
|
|
13974
|
+
* Changes requested by GitHub's review verdict, or by an external reviewer's latest review. While
|
|
13975
|
+
* GitHub has not computed mergeability or the merge state, its verdict does not count, so the head
|
|
13976
|
+
* holds as on any unknown read instead of moving the task; a reviewer's latest review always counts, as
|
|
13977
|
+
* under any-approval.
|
|
13978
|
+
*/
|
|
13979
|
+
function changesRequested(pr, reviewDecision, agentLogin) {
|
|
13980
|
+
const unknown = pr.mergeable === "unknown" || pr.mergeState === "unknown";
|
|
13981
|
+
return reviewDecision === "changes_requested" && !unknown || externalReviews(pr, agentLogin).some((review) => review.state === "changes_requested");
|
|
13982
|
+
}
|
|
13983
|
+
// ../core/src/app/review-rule.ts
|
|
13984
|
+
/** How long a head may stay undecided in External Review before the operator gets an item. */
|
|
13985
|
+
const REVIEW_RULE_UNDECIDED_MS = 18e5;
|
|
13986
|
+
const storedSchema = z.strictObject({
|
|
13987
|
+
headSha: prFactsSchema.shape.headSha,
|
|
13988
|
+
decision: z.enum(["satisfied", "blocked"]).nullable(),
|
|
13989
|
+
reviewDecision: prReviewRuleSchema.shape.reviewDecision,
|
|
13990
|
+
rule: prReviewRuleSchema.shape.rule,
|
|
13991
|
+
/**
|
|
13992
|
+
* When this head's undecided GitHub answer started (`ruleTransition`'s clock). Null while a
|
|
13993
|
+
* decision is stored or the read names someone to act.
|
|
13994
|
+
*/
|
|
13995
|
+
undecidedSince: z.iso.datetime().nullable(),
|
|
13996
|
+
/**
|
|
13997
|
+
* GitHub's raw values for the item, frozen at the first reconcile 30 minutes after
|
|
13998
|
+
* `undecidedSince`. The PR's tasks share it; each item's summary adds its own task key.
|
|
13999
|
+
*/
|
|
14000
|
+
raised: z.string().nullable(),
|
|
14001
|
+
/**
|
|
14002
|
+
* When a read last changed the row; a reused read that changes nothing keeps it. Rows written
|
|
14003
|
+
* before the field have none and count as the oldest.
|
|
14004
|
+
*/
|
|
14005
|
+
observedAt: z.iso.datetime().optional()
|
|
14006
|
+
});
|
|
14007
|
+
const prSuffix = (ref) => `:pr:${ref.repo.toLowerCase()}#${String(ref.number)}`;
|
|
14008
|
+
const reviewRuleKey = (source, ref) => `review-rule:${source}${prSuffix(ref)}`;
|
|
14009
|
+
const parseStored = (value) => {
|
|
14010
|
+
try {
|
|
14011
|
+
return parseJson(storedSchema, value);
|
|
14012
|
+
} catch {
|
|
14013
|
+
return null;
|
|
14014
|
+
}
|
|
14015
|
+
};
|
|
14016
|
+
/** The stored row of `pr` on its current head; null when absent, unreadable or on another head. */
|
|
14017
|
+
async function rowOnHead(trx, source, pr) {
|
|
14018
|
+
const row = await trx.selectFrom("meta").select("value").where("key", "=", reviewRuleKey(source, pr)).executeTakeFirst();
|
|
14019
|
+
const stored = row === void 0 ? null : parseStored(row.value);
|
|
14020
|
+
return stored?.headSha.toLowerCase() === pr.headSha.toLowerCase() ? stored : null;
|
|
14021
|
+
}
|
|
14022
|
+
/**
|
|
14023
|
+
* The base branch rule of the most recently changed row on the head among every source's rows of
|
|
14024
|
+
* the PR: the rule belongs to the repo and base branch, so another project's newer read of it
|
|
14025
|
+
* counts too. `own` wins a tie. Only the rule is shared; each source keeps its own decision.
|
|
14026
|
+
*/
|
|
14027
|
+
async function newestRule(trx, pr, own) {
|
|
14028
|
+
const suffix = prSuffix(pr);
|
|
14029
|
+
const rows = await trx.selectFrom("meta").select("value").where("key", "like", "review-rule:%").where(sql`substr(key, ${-suffix.length}) = ${suffix}`).execute();
|
|
14030
|
+
let newest = own;
|
|
14031
|
+
for (const row of rows) {
|
|
14032
|
+
const stored = parseStored(row.value);
|
|
14033
|
+
if (stored?.headSha.toLowerCase() !== pr.headSha.toLowerCase()) continue;
|
|
14034
|
+
if ((stored.observedAt ?? "") > (newest.observedAt ?? "")) newest = stored;
|
|
14035
|
+
}
|
|
14036
|
+
return newest.rule;
|
|
14037
|
+
}
|
|
14038
|
+
/**
|
|
14039
|
+
* One read of `pr` under the review verdict and rule beside it, over the head's stored decision
|
|
14040
|
+
* (`ruleTransition`). `requested` is a changes request as the gate counts it.
|
|
14041
|
+
*/
|
|
14042
|
+
function readOf(pr, reviewRule, stored, agentLogin) {
|
|
14043
|
+
const requested = changesRequested(pr, reviewRule.reviewDecision, agentLogin);
|
|
14044
|
+
return {
|
|
14045
|
+
requested,
|
|
14046
|
+
...ruleTransition(stored, reviewRuleVerdict(pr, reviewRule.rule, requested, pr.reviewThreads.filter((thread) => !thread.resolved).length), requested || reviewRule.reviewDecision === "changes_requested")
|
|
14047
|
+
};
|
|
14048
|
+
}
|
|
14049
|
+
/**
|
|
14050
|
+
* Records one full read's review rule for a github-rules project's source. A PR that is not open
|
|
14051
|
+
* drops its row; an item without a review rule says nothing new. The adapter sends a reused read
|
|
14052
|
+
* with its first read's review rule again, which rewrites no unchanged row and writes a lost one
|
|
14053
|
+
* back, as after a rolled-back observation. A new head starts without a decision; the stored
|
|
14054
|
+
* decision and the 30-minute clock follow `ruleTransition`. Returns true when the decision,
|
|
14055
|
+
* GitHub's verdict or the rule changed.
|
|
14056
|
+
*/
|
|
14057
|
+
async function recordReviewRule(trx, source, fact, reviewRule, at, agentLogin) {
|
|
14058
|
+
const key = reviewRuleKey(source, fact);
|
|
14059
|
+
if (fact.state !== "open") return (await trx.deleteFrom("meta").where("key", "=", key).executeTakeFirst()).numDeletedRows > 0n;
|
|
14060
|
+
if (reviewRule === void 0) return false;
|
|
14061
|
+
const old = await rowOnHead(trx, source, fact);
|
|
14062
|
+
const { decision, clock } = readOf(fact, reviewRule, old?.decision ?? null, agentLogin);
|
|
14063
|
+
const next = {
|
|
14064
|
+
headSha: fact.headSha.toLowerCase(),
|
|
14065
|
+
decision,
|
|
14066
|
+
reviewDecision: reviewRule.reviewDecision,
|
|
14067
|
+
rule: reviewRule.rule,
|
|
14068
|
+
undecidedSince: clock ? old?.undecidedSince ?? at : null,
|
|
14069
|
+
raised: clock ? old?.raised ?? null : null,
|
|
14070
|
+
observedAt: at
|
|
14071
|
+
};
|
|
14072
|
+
if (old !== null && toJson(storedSchema, {
|
|
14073
|
+
...old,
|
|
14074
|
+
observedAt: at
|
|
14075
|
+
}) === toJson(storedSchema, next)) return false;
|
|
14076
|
+
const value = toJson(storedSchema, next);
|
|
14077
|
+
await trx.insertInto("meta").values({
|
|
14078
|
+
key,
|
|
14079
|
+
value
|
|
14080
|
+
}).onConflict((oc) => oc.column("key").doUpdateSet({ value })).execute();
|
|
14081
|
+
return old === null || old.decision !== next.decision || old.reviewDecision !== next.reviewDecision || JSON.stringify(old.rule) !== JSON.stringify(next.rule);
|
|
14082
|
+
}
|
|
14083
|
+
/**
|
|
14084
|
+
* The gate's read of `pr`: the project's own source row on the current head, under the newest base
|
|
14085
|
+
* branch rule any source read for the head (`newestRule`), and the PR's facts, which may come from
|
|
14086
|
+
* another project's newer read; that read changes no row. Without a row on the head GitHub's
|
|
14087
|
+
* answer is undecided.
|
|
14088
|
+
*/
|
|
14089
|
+
async function gateRead(trx, source, pr, agentLogin) {
|
|
14090
|
+
const row = await rowOnHead(trx, source, pr);
|
|
14091
|
+
const approved = externalReviews(pr, agentLogin).some((review) => review.state === "approved");
|
|
14092
|
+
if (row === null) return {
|
|
14093
|
+
approved,
|
|
14094
|
+
changesRequested: changesRequested(pr, null, agentLogin),
|
|
14095
|
+
decision: "undecided",
|
|
14096
|
+
row,
|
|
14097
|
+
clock: false
|
|
14098
|
+
};
|
|
14099
|
+
const rule = await newestRule(trx, pr, row);
|
|
14100
|
+
const read = readOf(pr, {
|
|
14101
|
+
reviewDecision: row.reviewDecision,
|
|
14102
|
+
rule
|
|
14103
|
+
}, row.decision, agentLogin);
|
|
14104
|
+
return {
|
|
14105
|
+
approved,
|
|
14106
|
+
changesRequested: read.requested,
|
|
14107
|
+
decision: read.gate,
|
|
14108
|
+
row,
|
|
14109
|
+
clock: read.clock
|
|
14110
|
+
};
|
|
14111
|
+
}
|
|
14112
|
+
/** What External Review reads under github-rules (`gateRead`). */
|
|
14113
|
+
async function storedReviewRule(trx, source, pr, agentLogin) {
|
|
14114
|
+
const { approved, changesRequested: requested, decision } = await gateRead(trx, source, pr, agentLogin);
|
|
14115
|
+
return {
|
|
14116
|
+
approved,
|
|
14117
|
+
changesRequested: requested,
|
|
14118
|
+
decision
|
|
14119
|
+
};
|
|
14120
|
+
}
|
|
14121
|
+
const upper = (value) => value === null ? "null" : value.toUpperCase();
|
|
14122
|
+
/**
|
|
14123
|
+
* The items of github-rules tasks in External Review whose head has stayed undecided for
|
|
14124
|
+
* `REVIEW_RULE_UNDECIDED_MS` and whose gate, read as `readInput` reads it, still runs the clock: a
|
|
14125
|
+
* newer read of the head by another project's source can name someone to act first or carry
|
|
14126
|
+
* GitHub's answer, and then no item is raised or kept. GitHub's values are frozen in the row at
|
|
14127
|
+
* the first reconcile past the threshold and again when the cause changes, so a later poll or a
|
|
14128
|
+
* restart keeps the item as raised.
|
|
14129
|
+
*/
|
|
14130
|
+
async function reviewRuleItems(trx, config, now, tasks) {
|
|
14131
|
+
const candidates = [];
|
|
14132
|
+
for (const task of tasks) {
|
|
14133
|
+
if (task.column !== "external-review") continue;
|
|
14134
|
+
const project = config.projects.find((entry) => entry.id === task.project);
|
|
14135
|
+
if (project === void 0 || approvalRuleOf(project) !== "github-rules") continue;
|
|
14136
|
+
const link = await taskPr(trx, task.id);
|
|
14137
|
+
if (link === null || !link.open) continue;
|
|
14138
|
+
const pr = parsePr((await trx.selectFrom("pr_snapshot").select("detail").where(sql`lower(repo) = ${link.repo.toLowerCase()}`).where("number", "=", link.number).executeTakeFirst())?.detail);
|
|
14139
|
+
if (pr === null || pr.state !== "open") continue;
|
|
14140
|
+
const source = prSourceId(project.id, pr.repo);
|
|
14141
|
+
const gate = await gateRead(trx, source, project.checksGate === "dev" ? pr : await withUnconfirmedCancels(trx, source, pr), project.operatorGithubLogin);
|
|
14142
|
+
const row = gate.row;
|
|
14143
|
+
if (row?.undecidedSince == null || !gate.clock) continue;
|
|
14144
|
+
if (now - Date.parse(row.undecidedSince) < REVIEW_RULE_UNDECIDED_MS) continue;
|
|
14145
|
+
const ref = `${pr.repo.toLowerCase()}#${String(pr.number)}`;
|
|
14146
|
+
const what = gate.decision === "unreadable" ? `The GitHub review rule for the base branch of ${ref} could not be read` : `GitHub has not decided the review rule of ${ref}`;
|
|
14147
|
+
let raised = row.raised;
|
|
14148
|
+
if (raised === null || !raised.startsWith(what)) {
|
|
14149
|
+
raised = `${what} on ${row.headSha.slice(0, 7)}: undecided for 30 minutes on this head (mergeStateStatus=${upper(pr.mergeState)}, mergeable=${upper(pr.mergeable)}, reviewDecision=${upper(row.reviewDecision)})`;
|
|
14150
|
+
const value = toJson(storedSchema, {
|
|
14151
|
+
...row,
|
|
14152
|
+
raised
|
|
14153
|
+
});
|
|
14154
|
+
await trx.updateTable("meta").set({ value }).where("key", "=", reviewRuleKey(source, pr)).execute();
|
|
14155
|
+
}
|
|
14156
|
+
const summary = `${task.key}: ${raised}`;
|
|
14157
|
+
candidates.push({
|
|
14158
|
+
key: `${REVIEW_RULE_KEY}${String(task.id)}:${ref}:${row.headSha}`,
|
|
14159
|
+
kind: "board_observation",
|
|
14160
|
+
taskId: task.id,
|
|
14161
|
+
summary,
|
|
14162
|
+
factAt: row.undecidedSince,
|
|
14163
|
+
source,
|
|
14164
|
+
priority: 4
|
|
14165
|
+
});
|
|
14166
|
+
}
|
|
14167
|
+
return candidates;
|
|
14168
|
+
}
|
|
13850
14169
|
// ../core/src/domain/health.ts
|
|
13851
14170
|
const ENDED_WORKER_KINDS = {
|
|
13852
14171
|
complete: "worker_completed",
|
|
@@ -14528,6 +14847,7 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurC
|
|
|
14528
14847
|
const held = await trx.selectFrom("operator_item").select("item_key").where("item_key", "like", `${NO_SESSION_KEY}%`).where("cleared_at", "is", null).execute();
|
|
14529
14848
|
heldKeys.push(...held.map((item) => item.item_key));
|
|
14530
14849
|
} else candidates.push(...await turnsWithoutSession(trx, config, now, taskById));
|
|
14850
|
+
candidates.push(...await reviewRuleItems(trx, config, now, tasks));
|
|
14531
14851
|
const ordered = orderItems(candidates);
|
|
14532
14852
|
const seen = /* @__PURE__ */ new Set([...ordered.map((item) => item.key), ...heldKeys]);
|
|
14533
14853
|
for (const flag of health.held) {
|
|
@@ -14993,8 +15313,7 @@ async function blindSources(trx, complete) {
|
|
|
14993
15313
|
}
|
|
14994
15314
|
/** Whether the external reviewers approved: one approval, and no changes requested by one. */
|
|
14995
15315
|
function externalApproval(pr, agentLogin) {
|
|
14996
|
-
const
|
|
14997
|
-
const reviews = pr.reviews.filter((review) => external(review.reviewer));
|
|
15316
|
+
const reviews = externalReviews(pr, agentLogin);
|
|
14998
15317
|
return reviews.some((review) => review.state === "approved") && !reviews.some((review) => review.state === "changes_requested");
|
|
14999
15318
|
}
|
|
15000
15319
|
/**
|
|
@@ -15297,6 +15616,8 @@ async function readInput(trx, task, project, mode, blind, config, clock) {
|
|
|
15297
15616
|
const handed = pr?.feedbackComplete === true ? unhandled : [];
|
|
15298
15617
|
const column = mode === "shadow" ? task.shadow_column ?? task.column : task.column;
|
|
15299
15618
|
const unclosed = last?.closed_at === null ? last : void 0;
|
|
15619
|
+
const gatePr = pr !== null && pr.state === "open" && project.checksGate !== "dev" ? await withUnconfirmedCancels(trx, prSourceId(project.id, pr.repo), pr) : pr;
|
|
15620
|
+
const reviewRule = gatePr !== null && approvalRuleOf(project) === "github-rules" ? await storedReviewRule(trx, prSourceId(project.id, gatePr.repo), gatePr, project.operatorGithubLogin) : void 0;
|
|
15300
15621
|
const held = mode === "on" && await trx.selectFrom("operator_item").select("id").where((eb) => eb.or([eb("item_key", "like", `${cycleKeyPrefix(task.id)}%`), eb("item_key", "like", `${courseKeyPrefix(task.id)}%`)])).where("cleared_at", "is", null).executeTakeFirst() !== void 0;
|
|
15301
15622
|
return {
|
|
15302
15623
|
input: {
|
|
@@ -15307,8 +15628,9 @@ async function readInput(trx, task, project, mode, blind, config, clock) {
|
|
|
15307
15628
|
checksGate: project.checksGate
|
|
15308
15629
|
},
|
|
15309
15630
|
facts: {
|
|
15310
|
-
pr:
|
|
15631
|
+
pr: gatePr,
|
|
15311
15632
|
externalReviewApproved: pr !== null && externalApproval(pr, project.operatorGithubLogin),
|
|
15633
|
+
...reviewRule === void 0 ? {} : { reviewRule },
|
|
15312
15634
|
commentHistory: pr?.feedbackComplete === true ? "complete" : "incomplete",
|
|
15313
15635
|
unhandledExternalComments: unhandled.length,
|
|
15314
15636
|
unresolvedThreads: pr === null ? 0 : pr.reviewThreads.filter((thread) => !thread.resolved).length,
|
|
@@ -15432,13 +15754,30 @@ async function supersedeSubmit(trx, task, pending, at) {
|
|
|
15432
15754
|
supersededByMerge: pending.head
|
|
15433
15755
|
});
|
|
15434
15756
|
}
|
|
15435
|
-
/**
|
|
15436
|
-
|
|
15437
|
-
|
|
15757
|
+
/**
|
|
15758
|
+
* Counts a pending submit a poll confirmed: from its receipt time, on the linked PR. The turn it
|
|
15759
|
+
* closed answered its visit's return, so the return's code block closes at the confirmed head.
|
|
15760
|
+
*/
|
|
15761
|
+
async function confirmSubmit(trx, task, pending, at) {
|
|
15762
|
+
const row = await trx.updateTable("submission").set((eb) => ({
|
|
15438
15763
|
pending_until: null,
|
|
15439
15764
|
pr_repo: eb.fn.coalesce("pr_repo", eb.val(pending.pr.repo)),
|
|
15440
15765
|
pr_number: eb.fn.coalesce("pr_number", eb.val(pending.pr.number))
|
|
15441
|
-
})).where("id", "=", pending.id).
|
|
15766
|
+
})).where("id", "=", pending.id).returning([
|
|
15767
|
+
"column",
|
|
15768
|
+
"epoch",
|
|
15769
|
+
"author"
|
|
15770
|
+
]).executeTakeFirstOrThrow();
|
|
15771
|
+
const turn = await trx.selectFrom("turn").select([
|
|
15772
|
+
"task_id",
|
|
15773
|
+
"column",
|
|
15774
|
+
"epoch",
|
|
15775
|
+
"role"
|
|
15776
|
+
]).where("task_id", "=", task.id).where("column", "=", row.column).where("epoch", "=", row.epoch).where("acked_by", "=", row.author).where("closed_reason", "=", "submitted").orderBy("id", "desc").executeTakeFirst();
|
|
15777
|
+
if (turn !== void 0) await answerReturn(trx, task, turn, {
|
|
15778
|
+
actor: row.author,
|
|
15779
|
+
at: at.toISOString()
|
|
15780
|
+
}, pending.sha);
|
|
15442
15781
|
}
|
|
15443
15782
|
/**
|
|
15444
15783
|
* Re-evaluates the gates of each task and applies the cascade: in `on` mode it moves the column
|
|
@@ -15458,7 +15797,7 @@ async function dispatchTasks(trx, taskIds, ctx) {
|
|
|
15458
15797
|
if (read === null) continue;
|
|
15459
15798
|
if (read.pending?.state === "superseded") await supersedeSubmit(trx, task, read.pending, ctx.at);
|
|
15460
15799
|
if (read.ticketUnconfirmed) continue;
|
|
15461
|
-
if (read.pending?.state === "confirmed") await confirmSubmit(trx, read.pending);
|
|
15800
|
+
if (read.pending?.state === "confirmed") await confirmSubmit(trx, task, read.pending, ctx.at);
|
|
15462
15801
|
const result = dispatch(read.input);
|
|
15463
15802
|
if (mode === "shadow") await applyShadow(trx, task, project, result, ctx.at);
|
|
15464
15803
|
else await applyOn(trx, task, read, result, ctx);
|
|
@@ -17516,7 +17855,14 @@ const WHY_MOVES = 5;
|
|
|
17516
17855
|
const WAITING_FOR = {
|
|
17517
17856
|
checks_pending: "waiting for CI",
|
|
17518
17857
|
mergeable_unknown: "waiting for GitHub to compute mergeability",
|
|
17519
|
-
comment_history_incomplete: "waiting for the board to read the full PR comment history"
|
|
17858
|
+
comment_history_incomplete: "waiting for the board to read the full PR comment history",
|
|
17859
|
+
merge_state_unknown: "GitHub has not computed the merge state yet",
|
|
17860
|
+
review_rule_unreadable: "the GitHub review rule for the base branch could not be read"
|
|
17861
|
+
};
|
|
17862
|
+
/** The review rule waits of `approvalRule: github-rules` that are not hold-only, as `--why` names them. */
|
|
17863
|
+
const RULE_WAITS = {
|
|
17864
|
+
review_rule_blocked: "merge blocked by the GitHub review rule",
|
|
17865
|
+
changes_requested: "changes requested"
|
|
17520
17866
|
};
|
|
17521
17867
|
function visibleProjects(config, actor) {
|
|
17522
17868
|
return new Set(config.projects.filter((project) => authorize([{ grant: "operator" }, { grant: "project-agent" }], actor, {
|
|
@@ -17597,7 +17943,7 @@ function createTaskQueries(deps) {
|
|
|
17597
17943
|
const gate = evaluateGate(column, facts, read.input.project);
|
|
17598
17944
|
const head = facts.pr?.headSha.toLowerCase();
|
|
17599
17945
|
const { checksGate } = project;
|
|
17600
|
-
const waitText = (reason, sha) => reason === "checks_pending" && checksGate !== "dev" ? `checks running, exit from ${checksGate} waits for green` : `${WAITING_FOR[reason]} on ${sha}`;
|
|
17946
|
+
const waitText = (reason, sha) => reason === "checks_pending" && checksGate !== "dev" ? `checks running, exit from ${checksGate} waits for green` : reason === "merge_state_unknown" || reason === "review_rule_unreadable" ? WAITING_FOR[reason] : `${WAITING_FOR[reason]} on ${sha}`;
|
|
17601
17947
|
const waiting = gate.ok || head === void 0 ? [] : gate.reasons.flatMap((reason) => HOLD_ONLY.has(reason) ? [{
|
|
17602
17948
|
reason,
|
|
17603
17949
|
head,
|
|
@@ -17606,6 +17952,10 @@ function createTaskQueries(deps) {
|
|
|
17606
17952
|
reason,
|
|
17607
17953
|
head,
|
|
17608
17954
|
text: "checks red"
|
|
17955
|
+
}] : Object.hasOwn(RULE_WAITS, reason) ? [{
|
|
17956
|
+
reason,
|
|
17957
|
+
head,
|
|
17958
|
+
text: RULE_WAITS[reason]
|
|
17609
17959
|
}] : []);
|
|
17610
17960
|
const holds = [...dispatchHolds(read.input), ...read.ticketUnconfirmed ? ["ticket_unconfirmed"] : []].sort((left, right) => TASK_HOLDS.indexOf(left) - TASK_HOLDS.indexOf(right));
|
|
17611
17961
|
const heldBy = holds.includes("cycle_limit") ? await holdBlocks(trx, task.id) : [];
|
|
@@ -18739,6 +19089,7 @@ function createTurnMutations(deps) {
|
|
|
18739
19089
|
column: turn.column,
|
|
18740
19090
|
epoch: turn.epoch
|
|
18741
19091
|
}, ctx, completeSince, config.projects.find((entry) => entry.id === task.project)?.dispatcher.submitConfirmMs);
|
|
19092
|
+
if (confirmed !== "pending") await answerReturn(trx, task, turn, ctx, input.sha);
|
|
18742
19093
|
await closeTurns(trx, {
|
|
18743
19094
|
taskId: task.id,
|
|
18744
19095
|
reason: "submitted",
|
|
@@ -19379,9 +19730,11 @@ function comparableFacts(facts, timestamp) {
|
|
|
19379
19730
|
}
|
|
19380
19731
|
/**
|
|
19381
19732
|
* Applies one PR fact. `scheduled` is a complete scheduled poll, the only kind that advances the
|
|
19382
|
-
* cancelled-check count
|
|
19733
|
+
* cancelled-check count; `reviewRule` is the full read's review rule of a github-rules source.
|
|
19734
|
+
* Returns true when this poll confirmed a cancelled check as red, or changed the review rule with
|
|
19735
|
+
* the facts unchanged: no fact event dispatches the PR's tasks then.
|
|
19383
19736
|
*/
|
|
19384
|
-
async function pr(trx, config, fact, at, source, scheduled) {
|
|
19737
|
+
async function pr(trx, config, fact, at, source, scheduled, reviewRule) {
|
|
19385
19738
|
await trx.deleteFrom("source_miss").where("source", "=", source).where("ref_key", "=", refKey({
|
|
19386
19739
|
kind: "pr",
|
|
19387
19740
|
repo: fact.repo,
|
|
@@ -19428,6 +19781,7 @@ async function pr(trx, config, fact, at, source, scheduled) {
|
|
|
19428
19781
|
const project = projectForSource(config, source);
|
|
19429
19782
|
if (project === void 0) return false;
|
|
19430
19783
|
const confirmed = project.checksGate !== "dev" && await countCancelledChecks(trx, source, fact, scheduled);
|
|
19784
|
+
const ruled = approvalRuleOf(project) === "github-rules" && await recordReviewRule(trx, source, fact, reviewRule, at, project.operatorGithubLogin);
|
|
19431
19785
|
for (const key of fact.ticketKeys) {
|
|
19432
19786
|
const task = await trx.selectFrom("task").selectAll().where("project", "=", project.id).where("key", "=", key).executeTakeFirst();
|
|
19433
19787
|
if (task === void 0 || task.membership === "archived") continue;
|
|
@@ -19460,7 +19814,7 @@ async function pr(trx, config, fact, at, source, scheduled) {
|
|
|
19460
19814
|
else await trx.updateTable("link").set({ pr_open: 1 }).where("id", "=", link.id).execute();
|
|
19461
19815
|
}
|
|
19462
19816
|
await applyPendingReopen(trx, fact, at);
|
|
19463
|
-
if (!changed) return confirmed;
|
|
19817
|
+
if (!changed) return confirmed || ruled;
|
|
19464
19818
|
const links = await trx.selectFrom("link").select(["task_id"]).where("entity", "=", "pr").where(sql`lower(repo) = ${fact.repo.toLowerCase()}`).where("number", "=", fact.number).execute();
|
|
19465
19819
|
for (const link of links) {
|
|
19466
19820
|
const task = await trx.selectFrom("task").selectAll().where("id", "=", link.task_id).executeTakeFirstOrThrow();
|
|
@@ -19908,7 +20262,7 @@ function createObservationCore(deps) {
|
|
|
19908
20262
|
const confirmedCancels = [];
|
|
19909
20263
|
for (const item of orderedItems) if (item.kind === "ticket") await ticket(trx, config, item.facts, batch.observedAt, source);
|
|
19910
20264
|
else if (item.kind === "pr") {
|
|
19911
|
-
if (await pr(trx, config, item.facts, batch.observedAt, source, observation.effectiveComplete)) confirmedCancels.push(item.facts);
|
|
20265
|
+
if (await pr(trx, config, item.facts, batch.observedAt, source, observation.effectiveComplete, item.reviewRule)) confirmedCancels.push(item.facts);
|
|
19912
20266
|
await holdContinuation(trx, source, item);
|
|
19913
20267
|
} else await session(trx, config, item.facts, batch.observedAt, source, ambiguous, batch.sessionTransitions !== void 0);
|
|
19914
20268
|
for (const edge of batch.sessionTransitions ?? []) await sessionTransition(trx, config, edge);
|
|
@@ -21978,6 +22332,9 @@ const graphErrorWire = z.object({
|
|
|
21978
22332
|
function deniedReference(error) {
|
|
21979
22333
|
return (error.type === "FORBIDDEN" || error.type === "NOT_FOUND") && error.path?.includes("closingIssuesReferences") === true;
|
|
21980
22334
|
}
|
|
22335
|
+
function deniedBranchRule(error) {
|
|
22336
|
+
return (error.type === "FORBIDDEN" || error.type === "NOT_FOUND") && error.path?.[2] === "baseRef";
|
|
22337
|
+
}
|
|
21981
22338
|
const graphEnvelopeWire = z.object({
|
|
21982
22339
|
errors: z.array(graphErrorWire).optional(),
|
|
21983
22340
|
data: z.unknown()
|
|
@@ -22007,8 +22364,9 @@ const REVIEW_FIELDS = "id author { __typename login } state commit { oid } submi
|
|
|
22007
22364
|
const COMMENT_FIELDS = "nodes { id author { __typename login } createdAt body url lastEditedAt } pageInfo { hasPreviousPage startCursor }";
|
|
22008
22365
|
const THREAD_FIELDS = "id isResolved isOutdated comments(last: 100) { nodes { id url lastEditedAt pullRequestReview { id } } }";
|
|
22009
22366
|
const CLOSING_FIELDS = "nodes { number repository { nameWithOwner } } pageInfo { hasNextPage endCursor }";
|
|
22010
|
-
const
|
|
22011
|
-
|
|
22367
|
+
const BRANCH_RULE_FIELDS = "refUpdateRule { pattern requiredApprovingReviewCount requiresCodeOwnerReviews requiresConversationResolution requiredStatusCheckContexts } rules(first: 100) { nodes { type parameters { __typename ... on PullRequestParameters { requiredApprovingReviewCount requireCodeOwnerReview requiredReviewThreadResolution } ... on RequiredStatusChecksParameters { requiredStatusChecks { context } } } } pageInfo { hasNextPage } }";
|
|
22368
|
+
const prFields = (number, closing = false, reviewRule = false) => `id number url title updatedAt mergedAt closedAt state isDraft mergeable mergeStateStatus
|
|
22369
|
+
author { login } headRefName headRefOid${reviewRule ? `\n reviewDecision baseRef { ${BRANCH_RULE_FIELDS} }` : ""}
|
|
22012
22370
|
statusCheckRollup { contexts(first: 100) { nodes {
|
|
22013
22371
|
... on CheckRun { __typename name status conclusion startedAt completedAt checkSuite { createdAt workflowRun { workflow { id } } app { id } } isRequired(pullRequestNumber: ${String(number)}) }
|
|
22014
22372
|
... on StatusContext { __typename context state createdAt isRequired(pullRequestNumber: ${String(number)}) }
|
|
@@ -22030,11 +22388,12 @@ function discoveryQuery(bootstrap = false) {
|
|
|
22030
22388
|
function stateQuery(numbers) {
|
|
22031
22389
|
return `query PrStates($owner: String!, $repo: String!) { rateLimit { cost limit remaining resetAt } ${aliases(numbers, () => "number state")} }`;
|
|
22032
22390
|
}
|
|
22033
|
-
function indexQuery(numbers) {
|
|
22034
|
-
|
|
22391
|
+
function indexQuery(numbers, reviewRule = false) {
|
|
22392
|
+
const fields = reviewRule ? `${INDEX_FIELDS} reviewDecision` : INDEX_FIELDS;
|
|
22393
|
+
return `query PrIndex($owner: String!, $repo: String!) { rateLimit { cost limit remaining resetAt } ${aliases(numbers, () => fields)} }`;
|
|
22035
22394
|
}
|
|
22036
|
-
function detailQuery(numbers, closing = false) {
|
|
22037
|
-
return `query PrDetails($owner: String!, $repo: String!) { rateLimit { cost limit remaining resetAt } ${aliases(numbers, (number) => prFields(number, closing))} }`;
|
|
22395
|
+
function detailQuery(numbers, closing = false, reviewRule = false) {
|
|
22396
|
+
return `query PrDetails($owner: String!, $repo: String!) { rateLimit { cost limit remaining resetAt } ${aliases(numbers, (number) => prFields(number, closing, reviewRule))} }`;
|
|
22038
22397
|
}
|
|
22039
22398
|
function pageQuery(connection, bootstrap = false) {
|
|
22040
22399
|
if (connection === "comments") return `query PrPage($owner: String!, $repo: String!, $number: Int!, $before: String!) { rateLimit { cost limit remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { comments(last: 100, before: $before) { ${COMMENT_FIELDS} } } } }`;
|
|
@@ -22277,7 +22636,7 @@ const branchStatusWire = z.object({
|
|
|
22277
22636
|
targetUrl: z.string().nullish()
|
|
22278
22637
|
});
|
|
22279
22638
|
const branchContextWire = z.discriminatedUnion("__typename", [branchCheckRunWire, branchStatusWire]);
|
|
22280
|
-
const defaultBranchWire = z.object({ defaultBranchRef: z.object({
|
|
22639
|
+
const defaultBranchWire$1 = z.object({ defaultBranchRef: z.object({
|
|
22281
22640
|
name: z.string(),
|
|
22282
22641
|
target: z.object({
|
|
22283
22642
|
__typename: z.literal("Commit"),
|
|
@@ -22305,7 +22664,7 @@ const RUNNING = /* @__PURE__ */ new Set(["pending", "expected"]);
|
|
|
22305
22664
|
* becomes null.
|
|
22306
22665
|
*/
|
|
22307
22666
|
function defaultBranchFact(repository) {
|
|
22308
|
-
const parsed = defaultBranchWire.safeParse(repository);
|
|
22667
|
+
const parsed = defaultBranchWire$1.safeParse(repository);
|
|
22309
22668
|
if (!parsed.success) return void 0;
|
|
22310
22669
|
const { name: branch, target } = parsed.data.defaultBranchRef;
|
|
22311
22670
|
const { nodes, pageInfo } = target.statusCheckRollup.contexts;
|
|
@@ -22339,6 +22698,74 @@ function defaultBranchFact(repository) {
|
|
|
22339
22698
|
sha: target.oid
|
|
22340
22699
|
}).data;
|
|
22341
22700
|
}
|
|
22701
|
+
// ../adapters/src/github/branchRule.ts
|
|
22702
|
+
const parametersWire = z.object({
|
|
22703
|
+
__typename: z.string(),
|
|
22704
|
+
requiredApprovingReviewCount: z.int().min(0).nullish(),
|
|
22705
|
+
requireCodeOwnerReview: z.boolean().nullish(),
|
|
22706
|
+
requiredReviewThreadResolution: z.boolean().nullish(),
|
|
22707
|
+
requiredStatusChecks: z.array(z.object({ context: z.string() })).nullish()
|
|
22708
|
+
}).nullish();
|
|
22709
|
+
const branchRuleWire = z.object({
|
|
22710
|
+
refUpdateRule: z.object({
|
|
22711
|
+
requiredApprovingReviewCount: z.int().min(0).nullish(),
|
|
22712
|
+
requiresCodeOwnerReviews: z.boolean().nullish(),
|
|
22713
|
+
requiresConversationResolution: z.boolean().nullish(),
|
|
22714
|
+
requiredStatusCheckContexts: z.array(z.string().nullable()).nullish()
|
|
22715
|
+
}).nullish(),
|
|
22716
|
+
rules: z.object({
|
|
22717
|
+
nodes: z.array(z.object({
|
|
22718
|
+
type: z.string(),
|
|
22719
|
+
parameters: parametersWire
|
|
22720
|
+
}).nullable()),
|
|
22721
|
+
pageInfo: z.object({ hasNextPage: z.boolean() }).nullish()
|
|
22722
|
+
}).nullish()
|
|
22723
|
+
});
|
|
22724
|
+
/**
|
|
22725
|
+
* The merged rule: the largest approval count, a code owner review or resolved conversations
|
|
22726
|
+
* when any source requires one, and every required check once. A ruleset counts as a source only
|
|
22727
|
+
* through a pull request or required status checks rule. Null when the rules run past the one
|
|
22728
|
+
* page read or come without `pageInfo` to confirm they do not, as for a rule the token could not
|
|
22729
|
+
* read: an unread rule may require a check or a review. No `rules` at all reads as no rulesets.
|
|
22730
|
+
*/
|
|
22731
|
+
function branchRuleOf(wire) {
|
|
22732
|
+
const rules = wire?.rules;
|
|
22733
|
+
if (rules !== null && rules !== void 0 && rules.pageInfo?.hasNextPage !== false) return null;
|
|
22734
|
+
const protection = wire?.refUpdateRule ?? null;
|
|
22735
|
+
const nodes = wire?.rules?.nodes ?? [];
|
|
22736
|
+
const parametersOf = (type, typename) => nodes.flatMap((node) => node?.type === type && node.parameters?.__typename === typename ? [node.parameters] : []);
|
|
22737
|
+
const pullRequests = parametersOf("PULL_REQUEST", "PullRequestParameters");
|
|
22738
|
+
const statusChecks = parametersOf("REQUIRED_STATUS_CHECKS", "RequiredStatusChecksParameters");
|
|
22739
|
+
const counts = [protection?.requiredApprovingReviewCount, ...pullRequests.map((rule) => rule.requiredApprovingReviewCount)].filter((count) => typeof count === "number");
|
|
22740
|
+
const checks = [...protection?.requiredStatusCheckContexts ?? [], ...statusChecks.flatMap((rule) => (rule.requiredStatusChecks ?? []).map((check) => check.context))].filter((name) => typeof name === "string" && name.length > 0);
|
|
22741
|
+
return {
|
|
22742
|
+
sources: [...protection === null ? [] : ["branch-protection"], ...pullRequests.length + statusChecks.length === 0 ? [] : ["ruleset"]],
|
|
22743
|
+
approvals: counts.length === 0 ? null : Math.max(...counts),
|
|
22744
|
+
codeOwners: protection?.requiresCodeOwnerReviews === true || pullRequests.some((rule) => rule.requireCodeOwnerReview === true),
|
|
22745
|
+
conversationResolution: protection?.requiresConversationResolution === true || pullRequests.some((rule) => rule.requiredReviewThreadResolution === true),
|
|
22746
|
+
requiredChecks: [...new Set(checks)]
|
|
22747
|
+
};
|
|
22748
|
+
}
|
|
22749
|
+
const defaultBranchWire = z.object({ defaultBranchRef: branchRuleWire.extend({ name: z.string().min(1) }).nullable() });
|
|
22750
|
+
/**
|
|
22751
|
+
* Reads the review rule of `repo`'s default branch; null when the repository has no default
|
|
22752
|
+
* branch, and a null rule when the branch has more ruleset rules than one read returns. Any
|
|
22753
|
+
* GraphQL error rejects with a transient `AdapterError`.
|
|
22754
|
+
*/
|
|
22755
|
+
async function readBranchRule(repo, { token, now, fetch: fetcher, signal }) {
|
|
22756
|
+
const [owner, name] = repo.split("/");
|
|
22757
|
+
if (!owner || !name) throw new AdapterError("config", "Invalid repository");
|
|
22758
|
+
const response = await new GithubClient(token, now, fetcher).query(`query BranchRule($owner: String!, $repo: String!) { rateLimit { remaining resetAt } repository(owner: $owner, name: $repo) { defaultBranchRef { name ${BRANCH_RULE_FIELDS} } } }`, {
|
|
22759
|
+
owner,
|
|
22760
|
+
repo: name
|
|
22761
|
+
}, signal);
|
|
22762
|
+
if (response.errors.length > 0) throw new AdapterError("transient", "GitHub rule read failed");
|
|
22763
|
+
const branch = parseWire(defaultBranchWire, response.data["repository"], "Malformed GitHub response", ["data", "repository"]).defaultBranchRef;
|
|
22764
|
+
return branch === null ? null : {
|
|
22765
|
+
branch: branch.name,
|
|
22766
|
+
rule: branchRuleOf(branch)
|
|
22767
|
+
};
|
|
22768
|
+
}
|
|
22342
22769
|
// ../adapters/src/github/feedbackLinks.ts
|
|
22343
22770
|
const threadCommentWire = z.object({
|
|
22344
22771
|
id: z.string().min(1),
|
|
@@ -22449,7 +22876,9 @@ const prWire = z.object({
|
|
|
22449
22876
|
requestedReviewer: reviewerWire,
|
|
22450
22877
|
asCodeOwner: z.boolean()
|
|
22451
22878
|
})),
|
|
22452
|
-
closingIssuesReferences: closingWire
|
|
22879
|
+
closingIssuesReferences: closingWire,
|
|
22880
|
+
reviewDecision: z.string().nullish(),
|
|
22881
|
+
baseRef: branchRuleWire.nullish()
|
|
22453
22882
|
});
|
|
22454
22883
|
/** The key rule of a github-issues project's tracker repo, built from `projects[].link`. */
|
|
22455
22884
|
function issuesRule(repo, link) {
|
|
@@ -22719,6 +23148,21 @@ function normalizePr(repo, value, rule, feedbackComplete, held = []) {
|
|
|
22719
23148
|
if (!parsed.success) throw new AdapterError("transient", "Malformed GitHub PR facts", { cause: parsed.error });
|
|
22720
23149
|
return parsed.data;
|
|
22721
23150
|
}
|
|
23151
|
+
/**
|
|
23152
|
+
* GitHub's review decision and the base branch's review rule of a PR read with them selected;
|
|
23153
|
+
* undefined when the read did not select them. An unknown decision reads as null; a rule the token
|
|
23154
|
+
* was denied (`ruleDenied`) or one with more ruleset rules than the read returns reads as null, not
|
|
23155
|
+
* as a branch without one.
|
|
23156
|
+
*/
|
|
23157
|
+
function normalizeReviewRule(value, ruleDenied = false) {
|
|
23158
|
+
const wire = parseWire(prWire, value, "Malformed GitHub PR response");
|
|
23159
|
+
if (wire.reviewDecision === void 0 && wire.baseRef === void 0) return void 0;
|
|
23160
|
+
const decision = wire.reviewDecision?.toLowerCase();
|
|
23161
|
+
return prReviewRuleSchema.parse({
|
|
23162
|
+
reviewDecision: REVIEW_DECISIONS.find((known) => known === decision) ?? null,
|
|
23163
|
+
rule: ruleDenied ? null : branchRuleOf(wire.baseRef)
|
|
23164
|
+
});
|
|
23165
|
+
}
|
|
22722
23166
|
const counted = (node) => z.object({
|
|
22723
23167
|
totalCount: z.int().nonnegative(),
|
|
22724
23168
|
nodes: z.array(node)
|
|
@@ -22731,6 +23175,7 @@ const indexAliasWire = z.object({ pullRequest: z.object({
|
|
|
22731
23175
|
mergeable: z.string(),
|
|
22732
23176
|
mergeStateStatus: z.string(),
|
|
22733
23177
|
headRefOid: z.string(),
|
|
23178
|
+
reviewDecision: z.string().nullish(),
|
|
22734
23179
|
statusCheckRollup: z.object({
|
|
22735
23180
|
state: z.string(),
|
|
22736
23181
|
contexts: counted(z.union([z.object({
|
|
@@ -22831,6 +23276,7 @@ function githubSources(config, options) {
|
|
|
22831
23276
|
const id = prSourceId(project.id, repo);
|
|
22832
23277
|
const client = new GithubClient(options.token, options.now, options.fetch);
|
|
22833
23278
|
const keys = projectKeyRule(project.tracker, project.link, repo);
|
|
23279
|
+
const reviewRule = approvalRuleOf(project) === "github-rules";
|
|
22834
23280
|
const cache = /* @__PURE__ */ new Map();
|
|
22835
23281
|
async function withUsage(signal, read) {
|
|
22836
23282
|
try {
|
|
@@ -22864,7 +23310,8 @@ function githubSources(config, options) {
|
|
|
22864
23310
|
now: options.now,
|
|
22865
23311
|
ctx,
|
|
22866
23312
|
reserveRemaining: config.github.reserveRemaining,
|
|
22867
|
-
cache
|
|
23313
|
+
cache,
|
|
23314
|
+
reviewRule
|
|
22868
23315
|
})),
|
|
22869
23316
|
pollPr: (ref, ctx) => withUsage(ctx.signal, () => pollOnePr({
|
|
22870
23317
|
id,
|
|
@@ -22874,7 +23321,8 @@ function githubSources(config, options) {
|
|
|
22874
23321
|
now: options.now,
|
|
22875
23322
|
ref,
|
|
22876
23323
|
ctx,
|
|
22877
|
-
cache
|
|
23324
|
+
cache,
|
|
23325
|
+
reviewRule
|
|
22878
23326
|
}))
|
|
22879
23327
|
}
|
|
22880
23328
|
});
|
|
@@ -23095,7 +23543,8 @@ function malformed(acc, error, ref) {
|
|
|
23095
23543
|
}
|
|
23096
23544
|
}
|
|
23097
23545
|
async function processPr(scope, acc, number, alias, data, scopedErrors, ref) {
|
|
23098
|
-
const
|
|
23546
|
+
const ruleDenied = scopedErrors.some(deniedBranchRule);
|
|
23547
|
+
const errors = withoutDeniedReferences(scopedErrors).filter((entry) => !deniedBranchRule(entry));
|
|
23099
23548
|
requireCheckAccess(errors);
|
|
23100
23549
|
const error = errors[0];
|
|
23101
23550
|
if (error !== void 0) {
|
|
@@ -23150,17 +23599,26 @@ async function processPr(scope, acc, number, alias, data, scopedErrors, ref) {
|
|
|
23150
23599
|
malformed(acc, facts, ref);
|
|
23151
23600
|
return;
|
|
23152
23601
|
}
|
|
23602
|
+
const reviewRule = scope.reviewRule ? content(() => normalizeReviewRule(pr, ruleDenied)) : void 0;
|
|
23603
|
+
if (reviewRule instanceof AdapterError) {
|
|
23604
|
+
malformed(acc, reviewRule, ref);
|
|
23605
|
+
return;
|
|
23606
|
+
}
|
|
23153
23607
|
const { continuation } = feedback;
|
|
23154
23608
|
acc.items.push({
|
|
23155
23609
|
kind: "pr",
|
|
23156
23610
|
facts,
|
|
23157
|
-
...continuation === void 0 ? {} : { continuation }
|
|
23611
|
+
...continuation === void 0 ? {} : { continuation },
|
|
23612
|
+
...reviewRule === void 0 ? {} : { reviewRule }
|
|
23158
23613
|
});
|
|
23159
23614
|
if (ref) acc.entities.push({
|
|
23160
23615
|
ref,
|
|
23161
23616
|
status: "ok"
|
|
23162
23617
|
});
|
|
23163
|
-
return
|
|
23618
|
+
return {
|
|
23619
|
+
facts,
|
|
23620
|
+
...reviewRule === void 0 ? {} : { reviewRule }
|
|
23621
|
+
};
|
|
23164
23622
|
}
|
|
23165
23623
|
/** The entry of one PR in a per-PR list of the poll context. */
|
|
23166
23624
|
function entryFor(entries, repo, number) {
|
|
@@ -23269,9 +23727,9 @@ async function readDiscovery(scope, acc, ctx, login) {
|
|
|
23269
23727
|
};
|
|
23270
23728
|
}
|
|
23271
23729
|
/** Reads the light index of `numbers`; a PR left out of the map is read in full. */
|
|
23272
|
-
async function readIndex(scope, acc, numbers) {
|
|
23730
|
+
async function readIndex(scope, acc, numbers, reviewRule) {
|
|
23273
23731
|
const entries = /* @__PURE__ */ new Map();
|
|
23274
|
-
for (const chunk of chunks(numbers, INDEX_CHUNK)) for (const { numbers: sent, response } of await sendChunk(scope, chunk, indexQuery)) {
|
|
23732
|
+
for (const chunk of chunks(numbers, INDEX_CHUNK)) for (const { numbers: sent, response } of await sendChunk(scope, chunk, (part) => indexQuery(part, reviewRule))) {
|
|
23275
23733
|
if (response === void 0) continue;
|
|
23276
23734
|
acc.budget = response.budget;
|
|
23277
23735
|
if (unscoped(response.errors, aliasesOf(sent))) continue;
|
|
@@ -23284,7 +23742,7 @@ async function readIndex(scope, acc, numbers) {
|
|
|
23284
23742
|
}
|
|
23285
23743
|
return entries;
|
|
23286
23744
|
}
|
|
23287
|
-
async function pollRepository({ id, repo, login, keys, client, now, ctx, reserveRemaining, cache }) {
|
|
23745
|
+
async function pollRepository({ id, repo, login, keys, client, now, ctx, reserveRemaining, cache, reviewRule }) {
|
|
23288
23746
|
const observedAt = sourceCursorSchema.parse(new Date(now()).toISOString());
|
|
23289
23747
|
const bootstrap = ctx.cursor === void 0;
|
|
23290
23748
|
const [owner, name] = repo.split("/");
|
|
@@ -23348,16 +23806,19 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
|
|
|
23348
23806
|
const numbers = [...byNumber.keys(), ...found.numbers.filter((number) => !byNumber.has(number) && cache.has(number))];
|
|
23349
23807
|
const fresh = found.numbers.filter((number) => !byNumber.has(number) && !cache.has(number));
|
|
23350
23808
|
for (const number of cache.keys()) if (!byNumber.has(number) && discovery.ok && !found.numbers.includes(number)) cache.delete(number);
|
|
23351
|
-
const entries = await readIndex(request, acc, numbers);
|
|
23809
|
+
const entries = await readIndex(request, acc, numbers, reviewRule);
|
|
23352
23810
|
const cursorKey = (number) => JSON.stringify([entryFor(ctx.feedbackCursors, repo, number) ?? "none", entryFor(ctx.continuations, repo, number) ?? "none"]);
|
|
23353
23811
|
const changed = [];
|
|
23354
23812
|
for (const number of numbers) {
|
|
23355
|
-
const
|
|
23813
|
+
const cached = cache.get(number);
|
|
23814
|
+
const facts = reusable(cached, entries.get(number), cursorKey(number), now());
|
|
23356
23815
|
const ref = byNumber.get(number);
|
|
23357
23816
|
if (facts !== void 0) {
|
|
23817
|
+
const reviewRule = cached?.reviewRule;
|
|
23358
23818
|
acc.items.push({
|
|
23359
23819
|
kind: "pr",
|
|
23360
|
-
facts
|
|
23820
|
+
facts,
|
|
23821
|
+
...reviewRule === void 0 ? {} : { reviewRule }
|
|
23361
23822
|
});
|
|
23362
23823
|
if (ref !== void 0) acc.entities.push({
|
|
23363
23824
|
ref,
|
|
@@ -23377,7 +23838,8 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
|
|
|
23377
23838
|
signal: ctx.signal,
|
|
23378
23839
|
...ctx.feedbackCursors === void 0 ? {} : { feedbackCursors: ctx.feedbackCursors },
|
|
23379
23840
|
...ctx.continuations === void 0 ? {} : { continuations: ctx.continuations },
|
|
23380
|
-
states: true
|
|
23841
|
+
states: true,
|
|
23842
|
+
reviewRule
|
|
23381
23843
|
};
|
|
23382
23844
|
let discoveredOk = true;
|
|
23383
23845
|
const unread = (chunk) => {
|
|
@@ -23398,7 +23860,7 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
|
|
|
23398
23860
|
unread(chunk);
|
|
23399
23861
|
continue;
|
|
23400
23862
|
}
|
|
23401
|
-
const segments = await sendChunk(request, chunk, (sent) => detailQuery(sent, closing));
|
|
23863
|
+
const segments = await sendChunk(request, chunk, (sent) => detailQuery(sent, closing, reviewRule));
|
|
23402
23864
|
for (const { response } of segments) if (response !== void 0) acc.budget = response.budget;
|
|
23403
23865
|
for (const { numbers: sent, response } of segments) {
|
|
23404
23866
|
if (response === void 0) {
|
|
@@ -23410,14 +23872,14 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
|
|
|
23410
23872
|
const alias = `pr${String(i)}`;
|
|
23411
23873
|
const ref = byNumber.get(number);
|
|
23412
23874
|
const errors = scoped(response.errors, alias);
|
|
23413
|
-
const
|
|
23414
|
-
if (
|
|
23875
|
+
const read = await processPr(scope, acc, number, alias, response.data, errors, ref);
|
|
23876
|
+
if (read === void 0) {
|
|
23415
23877
|
if (found.numbers.includes(number)) discoveredOk = false;
|
|
23416
23878
|
continue;
|
|
23417
23879
|
}
|
|
23418
23880
|
cache.set(number, {
|
|
23419
23881
|
fingerprint: entries.get(number)?.fingerprint ?? null,
|
|
23420
|
-
|
|
23882
|
+
...read,
|
|
23421
23883
|
cursorKey: cursorKey(number),
|
|
23422
23884
|
readAt: now()
|
|
23423
23885
|
});
|
|
@@ -23450,13 +23912,13 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
|
|
|
23450
23912
|
...discovery.defaultBranch === void 0 ? {} : { defaultBranch: discovery.defaultBranch }
|
|
23451
23913
|
};
|
|
23452
23914
|
}
|
|
23453
|
-
async function pollOnePr({ id, repo, keys, client, now, ref, ctx, cache }) {
|
|
23915
|
+
async function pollOnePr({ id, repo, keys, client, now, ref, ctx, cache, reviewRule }) {
|
|
23454
23916
|
const { signal } = ctx;
|
|
23455
23917
|
const observedAt = new Date(now()).toISOString();
|
|
23456
23918
|
const [owner, name] = repo.split("/");
|
|
23457
23919
|
if (!owner || !name) throw new AdapterError("config", "Invalid repository");
|
|
23458
23920
|
cache.delete(ref.number);
|
|
23459
|
-
const response = await client.query(detailQuery([ref.number], closingSelected(keys)), {
|
|
23921
|
+
const response = await client.query(detailQuery([ref.number], closingSelected(keys), reviewRule), {
|
|
23460
23922
|
owner,
|
|
23461
23923
|
repo: name
|
|
23462
23924
|
}, signal);
|
|
@@ -23471,7 +23933,8 @@ async function pollOnePr({ id, repo, keys, client, now, ref, ctx, cache }) {
|
|
|
23471
23933
|
signal,
|
|
23472
23934
|
...ctx.feedbackCursors === void 0 ? {} : { feedbackCursors: ctx.feedbackCursors },
|
|
23473
23935
|
...ctx.continuations === void 0 ? {} : { continuations: ctx.continuations },
|
|
23474
|
-
states: false
|
|
23936
|
+
states: false,
|
|
23937
|
+
reviewRule
|
|
23475
23938
|
}, acc, ref.number, "pr0", response.data, scoped(response.errors, "pr0"), ref);
|
|
23476
23939
|
if (signal.aborted) throw new AdapterError("transient", "GitHub poll aborted");
|
|
23477
23940
|
rethrowLoneParseFailure(acc);
|
|
@@ -26950,6 +27413,91 @@ function linkRulesCheck(outcomes) {
|
|
|
26950
27413
|
};
|
|
26951
27414
|
return warning(id, fitFix(problems, problems.some((segment) => segment.unmatched) ? ` ${LINK_RULES_TAIL}` : "", `link rules miss recent PRs in ${String(problems.length)} projects; change projects[].link to the repo's branch and PR title rules.`));
|
|
26952
27415
|
}
|
|
27416
|
+
const REVIEW_RULE_TOKEN_FIX = "Add GITHUB_TOKEN to secrets.env, then rerun board doctor to read the review rule of each approvalRule github-rules repo.";
|
|
27417
|
+
const REVIEW_RULE_ADD_TAIL = " Require an approval or code owner review on the default branch";
|
|
27418
|
+
const REVIEW_RULE_REMOVE_TAIL = ", or remove approvalRule";
|
|
27419
|
+
const REVIEW_RULE_READ_TAIL = " Give the token read access to the default branch's branch protection and rulesets, then rerun board doctor.";
|
|
27420
|
+
/** The repos of the projects whose External Review sets `approvalRule: github-rules`. */
|
|
27421
|
+
function ruledRepos(config) {
|
|
27422
|
+
return config.projects.flatMap((project) => approvalRuleOf(project) === "github-rules" ? project.repos.map((repo) => ({
|
|
27423
|
+
project,
|
|
27424
|
+
repo
|
|
27425
|
+
})) : []);
|
|
27426
|
+
}
|
|
27427
|
+
function readReviewRules(ctx, fetcher, deadlineMs, token) {
|
|
27428
|
+
return Promise.all(ruledRepos(ctx.config).map(async ({ project, repo }) => ({
|
|
27429
|
+
project,
|
|
27430
|
+
repo,
|
|
27431
|
+
read: await deadlineCall(ctx, deadlineMs, "doctor.review_rule", "GitHub review rule read failed", async (signal) => ({ found: await readBranchRule(repo, {
|
|
27432
|
+
token,
|
|
27433
|
+
now: () => ctx.clock.now(),
|
|
27434
|
+
fetch: fetcher,
|
|
27435
|
+
signal
|
|
27436
|
+
}) }))
|
|
27437
|
+
})));
|
|
27438
|
+
}
|
|
27439
|
+
const yesNo = (value) => value ? "yes" : "no";
|
|
27440
|
+
const RULE_SOURCE_TEXT = {
|
|
27441
|
+
"branch-protection": "branch protection",
|
|
27442
|
+
ruleset: "ruleset"
|
|
27443
|
+
};
|
|
27444
|
+
function ruleSegment({ project, repo, read }) {
|
|
27445
|
+
const problem = (text, cause) => ({
|
|
27446
|
+
problem: true,
|
|
27447
|
+
unmatched: false,
|
|
27448
|
+
project: project.id,
|
|
27449
|
+
cause,
|
|
27450
|
+
text: () => `${project.id} ${repo}: ${text}`
|
|
27451
|
+
});
|
|
27452
|
+
if (read === null) return problem("could not read the review rule", "unread");
|
|
27453
|
+
if (read.found === null) return problem("no default branch", "unfollowed");
|
|
27454
|
+
const { branch, rule } = read.found;
|
|
27455
|
+
const where = `${project.id} ${repo}@${branchText(branch)}`;
|
|
27456
|
+
const unfollowed = (text) => ({
|
|
27457
|
+
problem: true,
|
|
27458
|
+
unmatched: false,
|
|
27459
|
+
project: project.id,
|
|
27460
|
+
cause: "unfollowed",
|
|
27461
|
+
text: () => `${where}: ${text}, no review rule to follow`
|
|
27462
|
+
});
|
|
27463
|
+
if (rule === null) return {
|
|
27464
|
+
problem: true,
|
|
27465
|
+
unmatched: false,
|
|
27466
|
+
project: project.id,
|
|
27467
|
+
cause: "unread",
|
|
27468
|
+
text: () => `${where}: could not confirm all ruleset rules were read`
|
|
27469
|
+
};
|
|
27470
|
+
if (rule.sources.length === 0) return unfollowed("no branch protection or ruleset");
|
|
27471
|
+
const sources = rule.sources.map((source) => RULE_SOURCE_TEXT[source]).join(" and ");
|
|
27472
|
+
const checks = rule.requiredChecks.length === 0 ? "none" : rule.requiredChecks.join(", ");
|
|
27473
|
+
const summary = `${sources}: ${String(rule.approvals ?? 0)} approvals, code owners ${yesNo(rule.codeOwners)}, resolved conversations ${yesNo(rule.conversationResolution)}, checks ${checks}`;
|
|
27474
|
+
if ((rule.approvals ?? 0) === 0 && !rule.codeOwners && !rule.conversationResolution) return unfollowed(summary);
|
|
27475
|
+
return {
|
|
27476
|
+
problem: false,
|
|
27477
|
+
unmatched: false,
|
|
27478
|
+
project: project.id,
|
|
27479
|
+
cause: null,
|
|
27480
|
+
text: () => `${where}: ${summary}`
|
|
27481
|
+
};
|
|
27482
|
+
}
|
|
27483
|
+
function reviewRuleCheck(outcomes) {
|
|
27484
|
+
const id = "github.review_rule";
|
|
27485
|
+
if (outcomes === null) return warning(id, REVIEW_RULE_TOKEN_FIX);
|
|
27486
|
+
const segments = outcomes.map(ruleSegment);
|
|
27487
|
+
const problems = segments.filter((segment) => segment.problem);
|
|
27488
|
+
if (problems.length === 0) return {
|
|
27489
|
+
id,
|
|
27490
|
+
status: "pass",
|
|
27491
|
+
blocking: false,
|
|
27492
|
+
fix: fitFix(segments, "", `Read the review rule of ${String(segments.length)} repos.`)
|
|
27493
|
+
};
|
|
27494
|
+
const has = (cause) => problems.some((segment) => segment.cause === cause);
|
|
27495
|
+
const gatedIn = new Set(segments.filter((segment) => segment.cause !== "unfollowed").map((segment) => segment.project));
|
|
27496
|
+
const removable = problems.every((segment) => segment.cause !== "unfollowed" || !gatedIn.has(segment.project));
|
|
27497
|
+
const addTail = `${REVIEW_RULE_ADD_TAIL}${removable ? REVIEW_RULE_REMOVE_TAIL : ""}.`;
|
|
27498
|
+
const tail = `${has("unfollowed") ? addTail : ""}${has("unread") ? REVIEW_RULE_READ_TAIL : ""}`;
|
|
27499
|
+
return warning(id, fitFix([...problems, ...segments.filter((segment) => !segment.problem)], tail, `${String(problems.length)} repos have no review rule to follow or could not be read.${tail}`));
|
|
27500
|
+
}
|
|
26953
27501
|
const CURATOR_TAIL = "Start a Spur session of each curator with no live session.";
|
|
26954
27502
|
function curatorSessionsCheck(entries) {
|
|
26955
27503
|
const id = "curator.sessions";
|
|
@@ -27144,6 +27692,9 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
|
|
|
27144
27692
|
const jiraTrackers = config.projects.flatMap((project) => project.tracker.type === "jira" ? [project.tracker] : []);
|
|
27145
27693
|
const slackConfigured = Boolean(config.slack.channels.feed || config.slack.channels.orchestrators);
|
|
27146
27694
|
const linkSamples = sampleLinks(ctx, fetcher, deadlineMs, secrets["GITHUB_TOKEN"]);
|
|
27695
|
+
const ruled = ruledRepos(config).length > 0;
|
|
27696
|
+
const ruleToken = secrets["GITHUB_TOKEN"];
|
|
27697
|
+
const reviewRules = ruled && ruleToken !== void 0 ? readReviewRules(ctx, fetcher, deadlineMs, ruleToken) : null;
|
|
27147
27698
|
const missing = requiredSecretKeys(config).filter((name) => !secrets[name]);
|
|
27148
27699
|
checks.push(check("secrets", missing.length === 0, `Add ${missing.join(", ")} to the private secrets.env file.`));
|
|
27149
27700
|
const jiraEmail = secrets["JIRA_EMAIL"];
|
|
@@ -27164,6 +27715,7 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
|
|
|
27164
27715
|
const githubFindings = githubToken === void 0 ? [githubFail(GITHUB_FIX)] : await Promise.all([...githubRepos].map((repo) => githubRepoFinding(ctx, fetcher, deadlineMs, githubToken, repo)));
|
|
27165
27716
|
checks.push(githubCheck(githubFindings));
|
|
27166
27717
|
checks.push(linkRulesCheck(await linkSamples));
|
|
27718
|
+
if (ruled) checks.push(reviewRuleCheck(reviewRules === null ? null : await reviewRules));
|
|
27167
27719
|
const probe = spurSendRequest(config.adapters.spur.baseUrl, SPUR_PROBE_SESSION, "spur-board doctor probe");
|
|
27168
27720
|
const [spur, spurSend] = await Promise.all([request(ctx, fetcher, deadlineMs, "spur", new URL("sessions", apiBaseUrl(config.adapters.spur.baseUrl))), request(ctx, fetcher, deadlineMs, "spur.send", probe.url, probe.init)]);
|
|
27169
27721
|
checks.push(check("spur.api", spur?.ok === true, "Start or correct the configured Spur API."));
|