spur-board 0.119.0 → 0.121.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/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as encodeActorId, A as eventPayloadSchemas, At as isTodoGroupColumn, B as REVIEW_STATES, C as messageRefSchema, Ct as COLUMN_GROUPS, D as sortSkillFiles, Dt as SLACK_BOT_SCOPES, E as skillReloadFilesSchema, Et as ITEM_KINDS, F as prSourceId, G as prFactsSchema, H as SESSION_STATUSES, I as sessionTransitionSchema, J as sessionFactsSchema, K as prRefSchema, L as sourceCursorSchema, M as batchSchema, N as defaultBranchFactSchema, O as EVENT_KINDS, Ot as TASK_HOLDS, P as entityRefSchema, Q as actorIdSchema, R as trackerSourceId, S as interactionRefSchema, St as COLUMNS, Tt as DISPATCHER_MODES, U as isExternalAuthor, V as SESSION_HEALTH_STATES, W as parseRingMarker, X as JIRA_PROJECT_KEY, Y as ticketFactsSchema, Z as REF_NUMBER, _t as configSchema, a as requestHashOf, b as conversationRefSchema, bt as requiredSecretKeys, c as tokenRequestStatusSchema, ct as successEnvelopeSchema, d as buildCatalogSnapshot, et as errorCodeOf, f as roleCanUseOperation, ft as DEFAULT_SLACK_COMMAND, g as renderHttpProblem, gt as configBindings, h as turnHandedSchema, ht as boardWideSpurProject, i as TOKEN_REQUEST_LIMITS, it as err, j as AdapterError, k as GATE_REASONS, kt as VIAS, l as BOARD_TICK_MS, m as defaultBranchViewSchema, mt as RESERVED_PROJECT, n as doctorReportSchema, nt as parseRef$1, o as tokenRequestResultSchema, p as OPERATIONS, q as ringMarker, rt as ERRORS, s as tokenRequestSchema, st as ok, t as assertNever, tt as parseActorId, ut as DEFAULT_LINK, vt as defaultAddressee, w as userIdSchema, wt as COLUMN_IDS, x as inboundEventSchema, xt as resolveWebOrigin, y as SPACE_IDS, yt as plainHttpAllowed, z as PR_STATES } from "./chunk-CkMLCW2S.mjs";
1
+ import { $ as encodeActorId, A as eventPayloadSchemas, At as isTodoGroupColumn, B as REVIEW_STATES, C as messageRefSchema, Ct as COLUMN_GROUPS, D as sortSkillFiles, Dt as SLACK_BOT_SCOPES, E as skillReloadFilesSchema, Et as ITEM_KINDS, F as prSourceId, G as prFactsSchema, H as SESSION_STATUSES, I as sessionTransitionSchema, J as sessionFactsSchema, K as prRefSchema, L as sourceCursorSchema, M as batchSchema, N as defaultBranchFactSchema, O as EVENT_KINDS, Ot as TASK_HOLDS, P as entityRefSchema, Q as actorIdSchema, R as trackerSourceId, S as interactionRefSchema, St as COLUMNS, Tt as DISPATCHER_MODES, U as isExternalAuthor, V as SESSION_HEALTH_STATES, W as parseRingMarker, X as JIRA_PROJECT_KEY, Y as ticketFactsSchema, Z as REF_NUMBER, _t as configSchema, a as requestHashOf, b as conversationRefSchema, bt as requiredSecretKeys, c as tokenRequestStatusSchema, ct as successEnvelopeSchema, d as buildCatalogSnapshot, et as errorCodeOf, f as roleCanUseOperation, ft as DEFAULT_SLACK_COMMAND, g as renderHttpProblem, gt as configBindings, h as turnHandedSchema, ht as boardWideSpurProject, i as TOKEN_REQUEST_LIMITS, it as err, j as AdapterError, k as GATE_REASONS, kt as VIAS, l as BOARD_TICK_MS, m as defaultBranchViewSchema, mt as RESERVED_PROJECT, n as doctorReportSchema, nt as parseRef$1, o as tokenRequestResultSchema, p as OPERATIONS, q as ringMarker, rt as ERRORS, s as tokenRequestSchema, st as ok, t as assertNever, tt as parseActorId, ut as DEFAULT_LINK, vt as defaultAddressee, w as userIdSchema, wt as COLUMN_IDS, x as inboundEventSchema, xt as resolveWebOrigin, y as SPACE_IDS, yt as plainHttpAllowed, z as PR_STATES } from "./chunk-w6KrYs3j.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";
@@ -8419,6 +8419,9 @@ function emptyAllowed(entry) {
8419
8419
  if (entry.grants === "any" || entry.grants.some((rule) => rule.grant !== "operator")) throw new Error(`Taskless operation ${entry.id} must remain operator-only`);
8420
8420
  return true;
8421
8421
  }
8422
+ function operatorAckRefused(entry, actor, target) {
8423
+ return entry.id === "inbox.ack" && actor === "operator" && target.kind === "found" && target.id?.startsWith("T") !== true;
8424
+ }
8422
8425
  /** Parse, replay, authorize, then apply one catalog mutation in one transaction. */
8423
8426
  function createApply(deps) {
8424
8427
  const { store, clock, config } = deps;
@@ -8457,7 +8460,10 @@ function createApply(deps) {
8457
8460
  const ackMismatch = ackIds !== void 0 && (resolved.length !== ackIds.length || resolved.some((target, index) => target.id !== ackIds[index]));
8458
8461
  const targets = resolved.length === 0 ? [{ kind: "missing" }] : ackMismatch ? [...resolved, { kind: "missing" }] : resolved;
8459
8462
  for (const target of targets) {
8460
- const decision = authorize(entry.grants, actor, {
8463
+ const decision = operatorAckRefused(entry, actor, target) ? {
8464
+ status: "denied",
8465
+ hint: "The operator token acks only turns: board inbox ack T<number>."
8466
+ } : authorize(entry.grants, actor, {
8461
8467
  config,
8462
8468
  target,
8463
8469
  ...mode === void 0 ? {} : { mode }
@@ -10582,7 +10588,7 @@ async function ringTask(trx, notificationId, dedupeKey) {
10582
10588
  const owner = notificationId !== void 0 ? trx.selectFrom("notification").select("task_id").where("id", "=", notificationId) : trx.selectFrom("comment").select("task_id").where("id", "=", Number(commentId));
10583
10589
  return trx.selectFrom("task").selectAll().where("id", "in", owner).executeTakeFirst();
10584
10590
  }
10585
- /** Stop notifications acknowledged by the addressed session. */
10591
+ /** Stop notifications acknowledged by the addressed session, or by any actor on a `takeover`. */
10586
10592
  async function acknowledgeNotification(trx, input) {
10587
10593
  let query = trx.selectFrom("notification").selectAll().where("acked_at", "is", null);
10588
10594
  if (input.blockId !== void 0) query = query.where("block_id", "=", input.blockId).where("kind", "=", "block");
@@ -10592,7 +10598,7 @@ async function acknowledgeNotification(trx, input) {
10592
10598
  const notices = await query.orderBy("id", "desc").execute();
10593
10599
  const n = notices[0];
10594
10600
  if (n === void 0) return false;
10595
- if (!await notificationAddressedTo(trx, n, input.actor, input.config)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
10601
+ if (input.takeover !== true && !await notificationAddressedTo(trx, n, input.actor, input.config)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
10596
10602
  for (const notice of notices) {
10597
10603
  await trx.updateTable("notification").set({ acked_at: input.at.toISOString() }).where("id", "=", notice.id).execute();
10598
10604
  if (notice.rings === 0) await releaseAfterCourseNote(trx, notice, input.at);
@@ -11457,6 +11463,7 @@ function listenApiServer(app, port) {
11457
11463
  const handedSchema = z.array(turnHandedSchema);
11458
11464
  const turnItemKey = (turnId) => `turn:${String(turnId)}`;
11459
11465
  const turnRef = (turnId) => `T${String(turnId)}`;
11466
+ const taskProject = async (trx, id) => (await trx.selectFrom("task").select("project").where("id", "=", id).executeTakeFirstOrThrow()).project;
11460
11467
  /**
11461
11468
  * Who executes a column's turn: its orchestrator project, the operator, or for a column with
11462
11469
  * no orchestrator the live worker, else the operator.
@@ -11533,7 +11540,8 @@ async function openTurn(trx, input) {
11533
11540
  /**
11534
11541
  * Takes a turn for `actor`. False for a missing, closed, operator or taken worker turn. An
11535
11542
  * untaken turn needs its unread notification addressed to the actor; a taken orchestrator turn
11536
- * may be taken over by whoever its notification is now addressed to. Others get `forbidden`.
11543
+ * may be taken over by whoever its notification is now addressed to. An operator on the task's
11544
+ * project may take any open orchestrator turn, taken or not. Others get `forbidden`.
11537
11545
  * Every take starts a new ownership episode: an unsent reminder of an earlier one is acked, so
11538
11546
  * `ringStillCurrent` drops its ring.
11539
11547
  */
@@ -11541,15 +11549,16 @@ async function takeTurn(trx, input) {
11541
11549
  const { turnId, actor, at, config } = input;
11542
11550
  const turn = await trx.selectFrom("turn").selectAll().where("id", "=", turnId).executeTakeFirst();
11543
11551
  if (turn === void 0 || turn.closed_at !== null || turn.role === "operator") return false;
11552
+ const project = await taskProject(trx, turn.task_id);
11553
+ const orchestrated = parseAddressee(turn.role).kind === "orchestrator";
11554
+ const takeover = orchestrated && isOperator(actor, config, project);
11544
11555
  if (turn.acked_at === null) {
11545
11556
  if (!await acknowledgeNotification(trx, {
11546
- turnId,
11547
- actor,
11548
- at,
11549
- config
11557
+ ...input,
11558
+ takeover
11550
11559
  })) return false;
11551
- } else {
11552
- if (parseAddressee(turn.role).kind !== "orchestrator") return false;
11560
+ } else if (!orchestrated) return false;
11561
+ else if (!takeover) {
11553
11562
  const notice = await turnNotification(trx, turnId);
11554
11563
  if (notice === void 0 || !await notificationAddressedTo(trx, notice, actor, config)) throw new CommandError("forbidden", "Only the addressed task role can take this turn.");
11555
11564
  }
@@ -11558,7 +11567,7 @@ async function takeTurn(trx, input) {
11558
11567
  acked_at: at.toISOString()
11559
11568
  }).where("id", "=", turnId).execute();
11560
11569
  await trx.updateTable("notification").set({ acked_at: at.toISOString() }).where("turn_id", "=", turnId).where("kind", "=", "turn_reminder").where("acked_at", "is", null).where("exhausted_at", "is", null).execute();
11561
- await emit(trx, "turn_taken", (await trx.selectFrom("task").select("project").where("id", "=", turn.task_id).executeTakeFirstOrThrow()).project, turn.task_id, at.toISOString(), {
11570
+ await emit(trx, "turn_taken", project, turn.task_id, at.toISOString(), {
11562
11571
  turn: turnRef(turnId),
11563
11572
  taker: actor
11564
11573
  }, actor);
@@ -11566,21 +11575,23 @@ async function takeTurn(trx, input) {
11566
11575
  }
11567
11576
  /**
11568
11577
  * Closes every unclosed turn of a task: its rings stop and its items end as "condition ended".
11569
- * A ring already queued is dropped by the sender (`ringStillCurrent`).
11578
+ * A ring already queued is dropped by the sender (`ringStillCurrent`). `turn_closed` names
11579
+ * `actor` when given, else `system`.
11570
11580
  */
11571
11581
  async function closeTurns(trx, input) {
11572
- const { taskId, reason, at } = input;
11582
+ const { taskId, reason, at, actor } = input;
11573
11583
  const closed = await trx.updateTable("turn").set({
11574
11584
  closed_at: at.toISOString(),
11575
11585
  closed_reason: reason
11576
11586
  }).where("task_id", "=", taskId).where("closed_at", "is", null).returning("id").execute();
11577
11587
  if (closed.length === 0) return;
11578
- const task = await trx.selectFrom("task").select("project").where("id", "=", taskId).executeTakeFirstOrThrow();
11588
+ const project = await taskProject(trx, taskId);
11579
11589
  for (const { id } of closed) {
11580
- await emit(trx, "turn_closed", task.project, taskId, at.toISOString(), {
11590
+ const closedPayload = {
11581
11591
  turn: turnRef(id),
11582
11592
  outcome: reason
11583
- });
11593
+ };
11594
+ await emit(trx, "turn_closed", project, taskId, at.toISOString(), closedPayload, actor);
11584
11595
  await closeTurnNotification(trx, id, at);
11585
11596
  const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", turnItemKey(id)).where("cleared_at", "is", null).executeTakeFirst();
11586
11597
  if (item !== void 0) await clearItem(trx, item.id, at);
@@ -15128,9 +15139,10 @@ function threadsGated(project) {
15128
15139
  }
15129
15140
  /**
15130
15141
  * Dev's failing reasons. `threads` adds the resolved-threads condition: it holds for the gate of
15131
- * every column at or right of the leftmost column requiring resolved threads.
15142
+ * every column at or right of the leftmost column requiring resolved threads. Red checks fail Dev
15143
+ * whatever `checksGate` is; pending checks hold Dev only when `checksGate` is Dev.
15132
15144
  */
15133
- function devReasons(facts, columns, waived, threads) {
15145
+ function devReasons(facts, project, waived, threads) {
15134
15146
  const { pr } = facts;
15135
15147
  if (pr === null) return ["no_pr"];
15136
15148
  if (pr.state === "closed") return ["pr_closed"];
@@ -15138,27 +15150,42 @@ function devReasons(facts, columns, waived, threads) {
15138
15150
  if (pr.draft) reasons.push("pr_draft");
15139
15151
  const verdict = checksVerdict(pr, waived);
15140
15152
  if (verdict === "red") reasons.push("checks_red");
15141
- if (verdict === "pending") reasons.push("checks_pending");
15153
+ if (verdict === "pending" && project.checksGate === "dev") reasons.push("checks_pending");
15142
15154
  if (pr.mergeable === "conflicting") reasons.push("conflict");
15143
15155
  if (pr.mergeable === "unknown") reasons.push("mergeable_unknown");
15144
15156
  if (facts.unhandledExternalComments > 0) reasons.push("external_comments");
15145
15157
  if (facts.commentHistory === "incomplete") reasons.push("comment_history_incomplete");
15146
15158
  if (threads && facts.unresolvedThreads > 0) reasons.push("unresolved_threads");
15147
- if (!executorDone("dev", facts, columns)) reasons.push("no_submit_on_head");
15159
+ if (!executorDone("dev", facts, project.columns)) reasons.push("no_submit_on_head");
15148
15160
  return reasons;
15149
15161
  }
15150
15162
  /**
15163
+ * The check reasons of a `checksGate` column right of Dev: red or pending checks on the open PR's
15164
+ * head. Dev already fails on red, so in a cumulative gate only pending reaches this column.
15165
+ */
15166
+ function gateCheckReasons(facts, waived) {
15167
+ const { pr } = facts;
15168
+ if (pr === null || pr.state !== "open") return [];
15169
+ const verdict = checksVerdict(pr, waived);
15170
+ return verdict === "red" ? ["checks_red"] : verdict === "pending" ? ["checks_pending"] : [];
15171
+ }
15172
+ /**
15151
15173
  * The failing reasons of one column's exit condition. Only Dev's resolved-threads condition depends
15152
15174
  * on the column asked: `threads` says whether it counts. A `gate_broken` move re-evaluates at Dev,
15153
15175
  * where that condition may not count, so a reason or hand-over that must survive it keys on the
15154
15176
  * facts and `threadsGated(project)` (`withThreads`, `turnThreads`), and `explainGates` takes
15155
15177
  * `blockedIn` from `evaluateGate`.
15156
15178
  */
15157
- function columnCondition(column, facts, columns, waived, threads) {
15179
+ function columnCondition(column, facts, project, waived, threads) {
15180
+ if (column === "dev") return devReasons(facts, project, waived, threads);
15181
+ const own = ownCondition(column, facts, project.columns);
15182
+ return column === project.checksGate ? [...gateCheckReasons(facts, waived), ...own] : own;
15183
+ }
15184
+ /** The failing reasons of a column's exit condition other than Dev, without checks. */
15185
+ function ownCondition(column, facts, columns) {
15158
15186
  if (isTodoGroupColumn(column)) return [];
15159
15187
  switch (column) {
15160
15188
  case "done": return [];
15161
- case "dev": return devReasons(facts, columns, waived, threads);
15162
15189
  case "review":
15163
15190
  case "product-review": return executorDone(column, facts, columns) ? [] : ["no_review_on_head"];
15164
15191
  case "external-review": return facts.externalReviewApproved ? [] : ["not_approved"];
@@ -15184,7 +15211,7 @@ function evaluateGate(column, facts, project) {
15184
15211
  for (const id of COLUMN_IDS.slice(0, COLUMN_IDS.indexOf(column) + 1)) {
15185
15212
  if (project.columns.find((c) => c.id === id)?.enabled !== true) continue;
15186
15213
  if (id === "dev" && waived) marker = { checksWaivedBy: "reposWithoutCi" };
15187
- const [first, ...rest] = columnCondition(id, facts, project.columns, waived, threads);
15214
+ const [first, ...rest] = columnCondition(id, facts, project, waived, threads);
15188
15215
  if (first !== void 0) return {
15189
15216
  ok: false,
15190
15217
  column: id,
@@ -15199,7 +15226,7 @@ function evaluateGate(column, facts, project) {
15199
15226
  }
15200
15227
  /**
15201
15228
  * The exit conditions of each column outside the Todo group, which has none, in the order the
15202
- * gates report their reasons.
15229
+ * gates report their reasons, with checks green at Dev.
15203
15230
  */
15204
15231
  const COLUMN_CONDITIONS = {
15205
15232
  dev: [
@@ -15219,7 +15246,25 @@ const COLUMN_CONDITIONS = {
15219
15246
  "ready-to-merge": ["merged"],
15220
15247
  done: []
15221
15248
  };
15222
- /** The condition each gate reason fails. */
15249
+ /**
15250
+ * The exit conditions of `column` under `checksGate`: with a gate right of Dev, Dev requires
15251
+ * checks not red, and the gate column requires checks green before its own conditions.
15252
+ */
15253
+ function columnConditions(column, checksGate) {
15254
+ if (checksGate === "dev") return COLUMN_CONDITIONS[column];
15255
+ if (column === "dev") return COLUMN_CONDITIONS.dev.map((condition) => condition === "checks_green" ? "checks_not_red" : condition);
15256
+ if (column === checksGate) return ["checks_green", ...COLUMN_CONDITIONS[column]];
15257
+ return COLUMN_CONDITIONS[column];
15258
+ }
15259
+ /**
15260
+ * The condition a gate reason fails in `column`: with a gate right of Dev, red checks fail Dev's
15261
+ * checks not red, and every other check reason fails checks green.
15262
+ */
15263
+ function conditionOf(reason, column, checksGate) {
15264
+ if (reason === "checks_red" && column === "dev" && checksGate !== "dev") return "checks_not_red";
15265
+ return CONDITION_OF[reason];
15266
+ }
15267
+ /** The condition each gate reason fails, with checks green at Dev. */
15223
15268
  const CONDITION_OF = {
15224
15269
  no_pr: "pr_open",
15225
15270
  pr_closed: "pr_open",
@@ -15252,13 +15297,13 @@ function explainGates(facts, project) {
15252
15297
  return {
15253
15298
  gates: COLUMN_IDS.map((column) => {
15254
15299
  const enabled = project.columns.find((c) => c.id === column)?.enabled === true;
15255
- const reasons = merged ? [] : columnCondition(column, facts, project.columns, waived, threads);
15300
+ const reasons = merged ? [] : columnCondition(column, facts, project, waived, threads);
15256
15301
  if (enabled && !merged && column === "dev" && waived) checksWaivedBy = "reposWithoutCi";
15257
15302
  const gate = evaluateGate(column, facts, project);
15258
15303
  const blockedIn = gate.ok ? null : gate.column;
15259
15304
  const stopped = reasons.some((reason) => STOPS_DEV.has(reason));
15260
- const conditions = (isTodoGroupColumn(column) ? [] : COLUMN_CONDITIONS[column]).map((condition) => {
15261
- const reason = reasons.find((r) => CONDITION_OF[r] === condition) ?? null;
15305
+ const conditions = (isTodoGroupColumn(column) ? [] : columnConditions(column, project.checksGate)).map((condition) => {
15306
+ const reason = reasons.find((r) => conditionOf(r, column, project.checksGate) === condition) ?? null;
15262
15307
  if (reason === null) return {
15263
15308
  condition,
15264
15309
  state: stopped ? "unchecked" : "met",
@@ -15459,11 +15504,13 @@ function dispatch(input) {
15459
15504
  if (column === "external-review" && executor === "none") return result(null);
15460
15505
  if (reasons.includes("pr_closed") && !handsBack) return result(null);
15461
15506
  switch (turn.visit) {
15462
- case "none": return result({
15463
- column,
15464
- reasons,
15465
- kind: "entry"
15466
- });
15507
+ case "none":
15508
+ if (column !== "dev" && reasons.every((reason) => HOLD_ONLY.has(reason))) return result(null);
15509
+ return result({
15510
+ column,
15511
+ reasons,
15512
+ kind: "entry"
15513
+ });
15467
15514
  case "unclosed": return result(turn.operatorUntaken && executor === "none" && workerLive ? {
15468
15515
  column,
15469
15516
  reasons,
@@ -15688,6 +15735,99 @@ async function shadowCourseCheck(trx, taskId, move, project) {
15688
15735
  const after = countCycles([...past, current], move.from, every).count;
15689
15736
  return after > before && after % every === 0;
15690
15737
  }
15738
+ // ../core/src/app/cancelled-checks.ts
15739
+ /** Complete scheduled polls after the sighting that confirm a cancel as red. */
15740
+ const CANCEL_CONFIRM_POLLS = 2;
15741
+ const cancelledChecksSchema = z.strictObject({
15742
+ headSha: prFactsSchema.shape.headSha,
15743
+ cancelled: z.array(z.strictObject({
15744
+ name: z.string().min(1),
15745
+ completedAt: z.string().nullable(),
15746
+ polls: z.int().min(0)
15747
+ }))
15748
+ });
15749
+ const cancelledChecksKey = (source, ref) => `checks-cancel:${source}:pr:${ref.repo.toLowerCase()}#${String(ref.number)}`;
15750
+ /** The stored counts on `headSha`; none when the row is absent, unreadable or for another head. */
15751
+ async function countsOnHead(trx, key, headSha) {
15752
+ const row = await trx.selectFrom("meta").select("value").where("key", "=", key).executeTakeFirst();
15753
+ if (row === void 0) return [];
15754
+ try {
15755
+ const saved = parseJson(cancelledChecksSchema, row.value);
15756
+ return saved.headSha.toLowerCase() === headSha.toLowerCase() ? saved.cancelled : [];
15757
+ } catch {
15758
+ return [];
15759
+ }
15760
+ }
15761
+ /** The cancelled checks on head, once each by name and completion time. */
15762
+ function cancelledOnHead(fact) {
15763
+ const seen = /* @__PURE__ */ new Set();
15764
+ return [...fact.requiredChecks, ...fact.checks].flatMap((check) => {
15765
+ if (check.state !== "cancelled") return [];
15766
+ const id = JSON.stringify([check.name, check.completedAt]);
15767
+ if (seen.has(id)) return [];
15768
+ seen.add(id);
15769
+ return [{
15770
+ name: check.name,
15771
+ completedAt: check.completedAt
15772
+ }];
15773
+ });
15774
+ }
15775
+ const sameRun = (left, right) => left.name === right.name && left.completedAt === right.completedAt;
15776
+ /**
15777
+ * Counts the polls since each cancelled check on the PR head was first seen: a new entry starts at
15778
+ * 0, a scheduled complete poll adds 1, and a head change starts over. It deletes the row of a PR
15779
+ * that is not open or has no cancelled check. Returns true when this poll confirms a cancel.
15780
+ */
15781
+ async function countCancelledChecks(trx, source, fact, scheduled) {
15782
+ const key = cancelledChecksKey(source, fact);
15783
+ const cancelled = fact.state === "open" ? cancelledOnHead(fact) : [];
15784
+ if (cancelled.length === 0) {
15785
+ await trx.deleteFrom("meta").where("key", "=", key).execute();
15786
+ return false;
15787
+ }
15788
+ const head = fact.headSha.toLowerCase();
15789
+ const previous = await countsOnHead(trx, key, head);
15790
+ let confirmed = false;
15791
+ const next = cancelled.map((check) => {
15792
+ const before = previous.find((entry) => sameRun(entry, check));
15793
+ if (before === void 0) return {
15794
+ ...check,
15795
+ polls: 0
15796
+ };
15797
+ if (!scheduled || before.polls >= CANCEL_CONFIRM_POLLS) return before;
15798
+ if (before.polls + 1 === CANCEL_CONFIRM_POLLS) confirmed = true;
15799
+ return {
15800
+ ...before,
15801
+ polls: before.polls + 1
15802
+ };
15803
+ });
15804
+ const value = toJson(cancelledChecksSchema, {
15805
+ headSha: head,
15806
+ cancelled: next
15807
+ });
15808
+ await trx.insertInto("meta").values({
15809
+ key,
15810
+ value
15811
+ }).onConflict((oc) => oc.column("key").doUpdateSet({ value })).execute();
15812
+ return confirmed;
15813
+ }
15814
+ /**
15815
+ * The PR with each cancelled check on head that is not confirmed yet read as pending: no stored
15816
+ * count for it on this head, or fewer than two complete polls since its sighting.
15817
+ */
15818
+ async function withUnconfirmedCancels(trx, source, pr) {
15819
+ if (cancelledOnHead(pr).length === 0) return pr;
15820
+ const counted = await countsOnHead(trx, cancelledChecksKey(source, pr), pr.headSha);
15821
+ const map = (checks) => checks.map((check) => check.state === "cancelled" && !counted.some((entry) => sameRun(entry, check) && entry.polls >= CANCEL_CONFIRM_POLLS) ? {
15822
+ ...check,
15823
+ state: "pending"
15824
+ } : check);
15825
+ return {
15826
+ ...pr,
15827
+ checks: map(pr.checks),
15828
+ requiredChecks: map(pr.requiredChecks)
15829
+ };
15830
+ }
15691
15831
  // ../core/src/domain/health.ts
15692
15832
  const ENDED_WORKER_KINDS = {
15693
15833
  complete: "worker_completed",
@@ -16513,13 +16653,13 @@ async function voidSubmits(trx, taskId, to, at) {
16513
16653
  /**
16514
16654
  * Moves a task left to `to` as a new visit: bumps `column_epoch` and `left_moves`, voids the
16515
16655
  * submits of `to` and right of it, closes its turns (`returned` for a `task.return` of `turn`,
16516
- * else `moved`) and journals `task_moved`. In `on` mode a counted return that reaches the
16656
+ * else `moved`, named on `turn_closed` as `closedBy` when given) and journals `task_moved`. In `on` mode a counted return that reaches the
16517
16657
  * column's cycle limit raises its cycle-limit block; otherwise one that reaches its course check
16518
16658
  * raises the course check. Either holds the task, and
16519
16659
  * `limitReached` tells the dispatcher to stop the cascade.
16520
16660
  */
16521
16661
  async function moveLeft(trx, input) {
16522
- const { task, to, at, actor, config, turn, block, reason, gate, findings } = input;
16662
+ const { task, to, at, actor, config, turn, block, reason, gate, findings, closedBy } = input;
16523
16663
  const moved = await trx.updateTable("task").set({
16524
16664
  column: to,
16525
16665
  column_epoch: task.column_epoch + 1,
@@ -16530,7 +16670,8 @@ async function moveLeft(trx, input) {
16530
16670
  await closeTurns(trx, {
16531
16671
  taskId: task.id,
16532
16672
  reason: turn === void 0 ? "moved" : "returned",
16533
- at
16673
+ at,
16674
+ actor: closedBy
16534
16675
  });
16535
16676
  await emit(trx, "task_moved", task.project, task.id, at.toISOString(), {
16536
16677
  from: task.column,
@@ -16985,10 +17126,11 @@ async function readInput(trx, task, project, mode, blind, config, clock) {
16985
17126
  column,
16986
17127
  project: {
16987
17128
  columns: project.columns,
16988
- reposWithoutCi: project.reposWithoutCi
17129
+ reposWithoutCi: project.reposWithoutCi,
17130
+ checksGate: project.checksGate
16989
17131
  },
16990
17132
  facts: {
16991
- pr,
17133
+ pr: pr !== null && pr.state === "open" && project.checksGate !== "dev" ? await withUnconfirmedCancels(trx, prSourceId(project.id, pr.repo), pr) : pr,
16992
17134
  externalReviewApproved: pr !== null && externalApproval(pr, project.operatorGithubLogin),
16993
17135
  commentHistory: pr?.feedbackComplete === true ? "complete" : "incomplete",
16994
17136
  unhandledExternalComments: unhandled.length,
@@ -17688,11 +17830,17 @@ function createTaskQueries(deps) {
17688
17830
  const { gates, checksWaivedBy } = explainGates(facts, read.input.project);
17689
17831
  const gate = evaluateGate(column, facts, read.input.project);
17690
17832
  const head = facts.pr?.headSha.toLowerCase();
17691
- const waiting = gate.ok || head === void 0 ? [] : gate.reasons.filter((reason) => HOLD_ONLY.has(reason)).map((reason) => ({
17833
+ const { checksGate } = project;
17834
+ const waitText = (reason, sha) => reason === "checks_pending" && checksGate !== "dev" ? `checks running, exit from ${checksGate} waits for green` : `${WAITING_FOR[reason]} on ${sha}`;
17835
+ const waiting = gate.ok || head === void 0 ? [] : gate.reasons.flatMap((reason) => HOLD_ONLY.has(reason) ? [{
17692
17836
  reason,
17693
17837
  head,
17694
- text: `${WAITING_FOR[reason]} on ${head}`
17695
- }));
17838
+ text: waitText(reason, head)
17839
+ }] : reason === "checks_red" && checksGate !== "dev" ? [{
17840
+ reason,
17841
+ head,
17842
+ text: "checks red"
17843
+ }] : []);
17696
17844
  const holds = [...dispatchHolds(read.input), ...read.ticketUnconfirmed ? ["ticket_unconfirmed"] : []].sort((left, right) => TASK_HOLDS.indexOf(left) - TASK_HOLDS.indexOf(right));
17697
17845
  const heldBy = holds.includes("cycle_limit") ? await holdBlocks(trx, task.id) : [];
17698
17846
  const pending = read.pending?.state === "pending" ? read.pending : void 0;
@@ -18059,6 +18207,8 @@ function createTurnMutations(deps) {
18059
18207
  });
18060
18208
  return taskById(trx, id);
18061
18209
  }
18210
+ /** The operator who closes a turn is named on `turn_closed`; any other closer stays `system`. */
18211
+ const operatorCloser = (task, actor) => isOperator(actor, config, task.project) ? actor : void 0;
18062
18212
  async function submitShadow(trx, input, ctx) {
18063
18213
  const task = await shadowTask(trx, input.turn, config);
18064
18214
  if (task === void 0) throw new CommandError("not_found", "Check the task key.");
@@ -18112,7 +18262,8 @@ function createTurnMutations(deps) {
18112
18262
  await closeTurns(trx, {
18113
18263
  taskId: task.id,
18114
18264
  reason: "submitted",
18115
- at: new Date(ctx.at)
18265
+ at: new Date(ctx.at),
18266
+ actor: operatorCloser(task, ctx.actor)
18116
18267
  });
18117
18268
  await emit(trx, "task_submitted", task.project, task.id, ctx.at, {
18118
18269
  turn: input.turn,
@@ -18145,7 +18296,8 @@ function createTurnMutations(deps) {
18145
18296
  config,
18146
18297
  turn: turnLabel(turn.id),
18147
18298
  block: `B${String(block.id)}`,
18148
- findings: input.findings
18299
+ findings: input.findings,
18300
+ closedBy: operatorCloser(task, ctx.actor)
18149
18301
  });
18150
18302
  const moved = await dispatched(trx, task.id, ctx.at, ctx.actor);
18151
18303
  return {
@@ -18321,7 +18473,8 @@ function createOperationRegistry(deps) {
18321
18473
  role: spur.role,
18322
18474
  displayName: spur.displayName ?? spur.name
18323
18475
  })),
18324
- ticketBrowseBase: ticketBrowseBase(project.tracker)
18476
+ ticketBrowseBase: ticketBrowseBase(project.tracker),
18477
+ checksGate: project.checksGate
18325
18478
  })),
18326
18479
  web: {
18327
18480
  publicOrigin: webOrigin() ?? null,
@@ -18724,7 +18877,11 @@ async function ticket(trx, config, fact, at, source) {
18724
18877
  function comparableFacts(facts, timestamp) {
18725
18878
  return JSON.stringify(Object.fromEntries(Object.entries(facts).filter(([key]) => key !== timestamp)));
18726
18879
  }
18727
- async function pr(trx, config, fact, at, source) {
18880
+ /**
18881
+ * Applies one PR fact. `scheduled` is a complete scheduled poll, the only kind that advances the
18882
+ * cancelled-check count. Returns true when this poll confirmed a cancelled check as red.
18883
+ */
18884
+ async function pr(trx, config, fact, at, source, scheduled) {
18728
18885
  await trx.deleteFrom("source_miss").where("source", "=", source).where("ref_key", "=", refKey({
18729
18886
  kind: "pr",
18730
18887
  repo: fact.repo,
@@ -18769,7 +18926,8 @@ async function pr(trx, config, fact, at, source) {
18769
18926
  at
18770
18927
  });
18771
18928
  const project = projectForSource(config, source);
18772
- if (project === void 0) return;
18929
+ if (project === void 0) return false;
18930
+ const confirmed = project.checksGate !== "dev" && await countCancelledChecks(trx, source, fact, scheduled);
18773
18931
  for (const key of fact.ticketKeys) {
18774
18932
  const task = await trx.selectFrom("task").selectAll().where("project", "=", project.id).where("key", "=", key).executeTakeFirst();
18775
18933
  if (task === void 0 || task.membership === "archived") continue;
@@ -18802,7 +18960,7 @@ async function pr(trx, config, fact, at, source) {
18802
18960
  else await trx.updateTable("link").set({ pr_open: 1 }).where("id", "=", link.id).execute();
18803
18961
  }
18804
18962
  await applyPendingReopen(trx, fact, at);
18805
- if (!changed) return;
18963
+ if (!changed) return confirmed;
18806
18964
  const links = await trx.selectFrom("link").select(["task_id"]).where("entity", "=", "pr").where(sql`lower(repo) = ${fact.repo.toLowerCase()}`).where("number", "=", fact.number).execute();
18807
18965
  for (const link of links) {
18808
18966
  const task = await trx.selectFrom("task").selectAll().where("id", "=", link.task_id).executeTakeFirstOrThrow();
@@ -18843,6 +19001,7 @@ async function pr(trx, config, fact, at, source) {
18843
19001
  await emit(trx, "pr_facts_changed", task.project, task.id, at, { facts: fact });
18844
19002
  await markTaskChanged(trx, task.id, at);
18845
19003
  }
19004
+ return confirmed;
18846
19005
  }
18847
19006
  function branchHasKey(branch, key) {
18848
19007
  const text = branch.toLowerCase();
@@ -19239,9 +19398,10 @@ function createObservationCore(deps) {
19239
19398
  const rank = (item) => item.kind === "ticket" ? 0 : item.kind === "pr" ? 1 : item.facts.links["board-worker"] === void 0 ? 3 : 2;
19240
19399
  return rank(left) - rank(right);
19241
19400
  });
19401
+ const confirmedCancels = [];
19242
19402
  for (const item of orderedItems) if (item.kind === "ticket") await ticket(trx, config, item.facts, batch.observedAt, source);
19243
19403
  else if (item.kind === "pr") {
19244
- await pr(trx, config, item.facts, batch.observedAt, source);
19404
+ if (await pr(trx, config, item.facts, batch.observedAt, source, observation.effectiveComplete)) confirmedCancels.push(item.facts);
19245
19405
  await holdContinuation(trx, source, item);
19246
19406
  } else await session(trx, config, item.facts, batch.observedAt, source, ambiguous, batch.sessionTransitions !== void 0);
19247
19407
  for (const edge of batch.sessionTransitions ?? []) await sessionTransition(trx, config, edge);
@@ -19316,6 +19476,12 @@ function createObservationCore(deps) {
19316
19476
  if (observation.effectiveComplete && !completeSince.has(source) || recovered) await dispatchSource(trx, source, dispatchContext);
19317
19477
  if (observation.effectiveComplete) await dispatchDoneTickets(trx, source, dispatchContext);
19318
19478
  await dispatchMergedTickets(trx, source, dispatchContext);
19479
+ const confirmedTasks = [];
19480
+ for (const fact of confirmedCancels) {
19481
+ const links = await trx.selectFrom("link").select("task_id").where("entity", "=", "pr").where(sql`lower(repo) = ${fact.repo.toLowerCase()}`).where("number", "=", fact.number).execute();
19482
+ confirmedTasks.push(...links.map((link) => link.task_id));
19483
+ }
19484
+ if (confirmedTasks.length > 0) await dispatchTasks(trx, confirmedTasks, dispatchContext);
19319
19485
  await dispatchJournaled(trx, dispatchContext);
19320
19486
  await reconcileItems(trx, config, now, currentComplete.has("spur"), warnSkipped, source === "spur" && observation.effectiveComplete && (!completeSince.has("spur") || spurGap) ? Date.parse(batch.observedAt) : void 0);
19321
19487
  if (deps.productVersion !== void 0) await enqueueLiveAfterFirstPoll(trx, {
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { p as OPERATIONS, rt as ERRORS, v as renderMcpError } from "./chunk-CkMLCW2S.mjs";
2
- import { o as CliError, r as requestOperation } from "./chunk-B1Mpg_7f.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-CBZ5yyYo.mjs";
1
+ import { p as OPERATIONS, rt as ERRORS, v as renderMcpError } from "./chunk-w6KrYs3j.mjs";
2
+ import { o as CliError, r as requestOperation } from "./chunk-DS95rV33.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-DywuekMO.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";