spur-board 0.134.1 → 0.136.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 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-BA7MJmCk.mjs";
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-CRtgKvgx.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";
@@ -13691,11 +13691,47 @@ function counted$2(move, blocked) {
13691
13691
  causes: [first, ...rest]
13692
13692
  };
13693
13693
  }
13694
+ /** The counter that takes every round caused by an external change request. */
13695
+ const EXTERNAL_COUNTER = "external-review";
13696
+ /** Return causes that come from an external change request. */
13697
+ const EXTERNAL_CAUSES = ["external_comments", "changes_requested"];
13698
+ /** The project's External Review column when it is enabled. */
13699
+ const externalColumn = (project) => project.columns.find((column) => column.id === "external-review" && column.enabled);
13700
+ /** Whether a return came from external feedback: an external cause, and not its executor. */
13701
+ const externalCause = (causes) => !causes.includes("executor") && causes.some((cause) => EXTERNAL_CAUSES.includes(cause));
13694
13702
  /**
13695
- * The counted returns from `column`: `cycle` since the last close of its cycle-limit item, and
13696
- * `course` since the last close of its course-check item.
13703
+ * The column whose course count an entry adds to. An external round, and a return caused by
13704
+ * external comments while External Review is enabled, count under External Review, whatever
13705
+ * column the task left. An executor return, and every other return, stay on the column it left.
13697
13706
  */
13698
- async function returnCounts(trx, taskId, column) {
13707
+ function courseCounter(entry, project) {
13708
+ if (entry.kind === "external_round") return EXTERNAL_COUNTER;
13709
+ return externalCause(entry.causes) && externalColumn(project) !== void 0 ? EXTERNAL_COUNTER : entry.column;
13710
+ }
13711
+ const reviewsSchema = prFactsSchema.shape.reviews;
13712
+ /**
13713
+ * The task's cycle events alone, as `courseRounds` gives them: its moves and limit resets, with
13714
+ * no PR history read. Enough for a cycle limit, which counts returns and nothing else.
13715
+ */
13716
+ async function cycleEvents(trx, taskId) {
13717
+ return (await courseRounds(trx, taskId, {
13718
+ columns: [],
13719
+ operatorGithubLogin: ""
13720
+ }, false)).cycle;
13721
+ }
13722
+ /**
13723
+ * The task's journal replayed for its counts, in journal order: the cycle events, and the
13724
+ * course rounds with the resets of each counter. A return is resolved against the PR active
13725
+ * when it happened: the newest open PR among the facts journaled before it. Its head is that
13726
+ * PR's head then, or unknown without one; a return for external feedback takes the head of the
13727
+ * PR's latest external change request made since the dispatcher last moved the task, so a push
13728
+ * seen in the same poll does not take its place. A correction is no boundary: a request it
13729
+ * bounces on is still unhandled and is the return's cause. External Review counts each head of
13730
+ * external feedback (rounds and such returns) once, resets ignored; a later one on a counted
13731
+ * head adds to the cycle events only. `externalHeads` are those heads. With `history` false it
13732
+ * reads no PR history and gives the cycle events alone.
13733
+ */
13734
+ async function courseRounds(trx, taskId, project, history = true) {
13699
13735
  const prefixes = {
13700
13736
  cycle: cycleKeyPrefix(taskId),
13701
13737
  course: courseKeyPrefix(taskId)
@@ -13708,35 +13744,172 @@ async function returnCounts(trx, taskId, column) {
13708
13744
  column: item.item_key.slice(prefixes[count].length)
13709
13745
  }];
13710
13746
  }));
13711
- const rows = await trx.selectFrom("event").select(["kind", "payload"]).where("task_id", "=", taskId).where("kind", "in", ["task_moved", "from_you_cleared"]).orderBy("id").execute();
13712
- const events = {
13747
+ const facts = (path) => sql`json_extract(payload, ${"$.facts." + path})`;
13748
+ const rows = await trx.selectFrom("event").select([
13749
+ "id",
13750
+ "at",
13751
+ "kind",
13752
+ sql`case when kind = 'pr_facts_changed' then '' else payload end`.as("payload"),
13753
+ facts("repo").as("repo"),
13754
+ sql`json_extract(payload, '$.facts.number')`.as("number"),
13755
+ facts("state").as("state"),
13756
+ facts("headSha").as("head")
13757
+ ]).where("task_id", "=", taskId).where("kind", "in", history ? [
13758
+ "task_moved",
13759
+ "from_you_cleared",
13760
+ "external_round",
13761
+ "pr_facts_changed"
13762
+ ] : ["task_moved", "from_you_cleared"]).orderBy("id").execute();
13763
+ /** Each PR's latest facts so far, with the id of its first facts row. */
13764
+ const prs = /* @__PURE__ */ new Map();
13765
+ /** The PR active now: the newest open one by first facts. */
13766
+ const active = () => [...prs.values()].filter((entry) => entry.state === "open").sort((left, right) => right.first - left.first)[0];
13767
+ const replay = {
13713
13768
  cycle: [],
13714
- course: []
13769
+ course: [],
13770
+ externalHeads: /* @__PURE__ */ new Set()
13715
13771
  };
13716
- for (const row of rows) {
13717
- if (row.kind === "from_you_cleared") {
13718
- const cleared = eventPayloadSchemas.from_you_cleared.safeParse(JSON.parse(row.payload));
13719
- const reset = cleared.success ? resetOf.get(cleared.data.item) : void 0;
13720
- if (reset !== void 0 && isColumn(reset.column)) events[reset.count].push({
13721
- kind: "limit_reset",
13722
- column: reset.column
13723
- });
13724
- continue;
13725
- }
13772
+ /**
13773
+ * The course entries in journal order; a return for external feedback names the facts row of
13774
+ * its PR and the visit start, to take the head of the change request it came from.
13775
+ */
13776
+ const queue = [];
13777
+ let enteredAt = Number.NEGATIVE_INFINITY;
13778
+ for (const row of rows) if (row.kind === "pr_facts_changed") {
13779
+ if (row.repo === null || row.number === null) continue;
13780
+ const key = `${row.repo.toLowerCase()}#${String(row.number)}`;
13781
+ prs.set(key, {
13782
+ ...row,
13783
+ first: prs.get(key)?.first ?? row.id
13784
+ });
13785
+ } else if (row.kind === "from_you_cleared") {
13786
+ const cleared = eventPayloadSchemas.from_you_cleared.safeParse(JSON.parse(row.payload));
13787
+ const reset = cleared.success ? resetOf.get(cleared.data.item) : void 0;
13788
+ if (reset === void 0 || !isColumn(reset.column)) continue;
13789
+ if (reset.count === "cycle") replay.cycle.push({
13790
+ kind: "limit_reset",
13791
+ column: reset.column
13792
+ });
13793
+ else if (history) queue.push({
13794
+ entry: {
13795
+ kind: "reset",
13796
+ counter: reset.column
13797
+ },
13798
+ external: false
13799
+ });
13800
+ } else if (row.kind === "external_round") {
13801
+ const round = eventPayloadSchemas.external_round.safeParse(JSON.parse(row.payload));
13802
+ if (round.success) queue.push({
13803
+ entry: externalRound(round.data, project),
13804
+ external: true
13805
+ });
13806
+ } else if (row.kind === "task_moved") {
13807
+ const since = enteredAt;
13808
+ enteredAt = Date.parse(row.at);
13726
13809
  const moved = eventPayloadSchemas.task_moved.safeParse(JSON.parse(row.payload));
13727
13810
  const event = moved.success ? counted$2(moved.data, moved.data.block !== void 0) : null;
13728
- if (event === null) continue;
13729
- events.cycle.push(event);
13730
- events.course.push(event);
13811
+ if (event?.kind !== "return") continue;
13812
+ replay.cycle.push(event);
13813
+ if (!history || countCycles([event], event.column, Infinity).count === 0) continue;
13814
+ const counter = courseCounter(event, project);
13815
+ const external = counter === "external-review" && externalCause(event.causes);
13816
+ const pr = active();
13817
+ const cause = event.causes.includes("executor") ? "executor" : external ? "external" : "other";
13818
+ const head = pr?.head?.toLowerCase() ?? null;
13819
+ queue.push({
13820
+ entry: {
13821
+ kind: "return",
13822
+ counter,
13823
+ from: event.column,
13824
+ head,
13825
+ cause
13826
+ },
13827
+ external,
13828
+ ...external && pr !== void 0 ? { reviewed: {
13829
+ id: pr.id,
13830
+ since
13831
+ } } : {}
13832
+ });
13731
13833
  }
13732
- return {
13733
- cycle: countCycles(events.cycle, column, Infinity).count,
13734
- course: countCycles(events.course, column, Infinity).count
13735
- };
13834
+ const used = [...new Set(queue.flatMap(({ reviewed }) => reviewed ? [reviewed.id] : []))];
13835
+ const reviewed = used.length === 0 ? [] : await trx.selectFrom("event").select([
13836
+ "id",
13837
+ facts("reviews").as("reviews"),
13838
+ sql`(select json_group_array(lower(json_extract(value, '$.author.login'))) from json_each(event.payload, '$.facts.feedback') where json_extract(value, '$.author.type') = 'bot')`.as("bots")
13839
+ ]).where(sql`id in (select value from json_each(${JSON.stringify(used)}))`).execute();
13840
+ /** The head of the latest external change request in facts row `id` made after `since`. */
13841
+ const reviewedHead = (id, since) => {
13842
+ const row = reviewed.find((entry) => entry.id === id);
13843
+ const reviews = reviewsSchema.safeParse(JSON.parse(row?.reviews ?? "null"));
13844
+ if (row === void 0 || !reviews.success) return null;
13845
+ const bots = new Set(JSON.parse(row.bots));
13846
+ return reviews.data.filter((review) => review.state === "changes_requested" && Date.parse(review.submittedAt) > since && review.reviewer.toLowerCase() !== project.operatorGithubLogin.toLowerCase() && !bots.has(review.reviewer.toLowerCase())).sort((left, right) => Date.parse(right.submittedAt) - Date.parse(left.submittedAt))[0]?.commitSha.toLowerCase() ?? null;
13847
+ };
13848
+ for (const { entry, external, reviewed: lookup } of queue) {
13849
+ const head = lookup === void 0 ? null : reviewedHead(lookup.id, lookup.since);
13850
+ const round = head === null || entry.kind !== "return" ? entry : {
13851
+ ...entry,
13852
+ head
13853
+ };
13854
+ if (external && round.kind !== "reset" && round.head !== null) {
13855
+ if (replay.externalHeads.has(round.head)) continue;
13856
+ replay.externalHeads.add(round.head);
13857
+ }
13858
+ replay.course.push(round);
13859
+ }
13860
+ return replay;
13861
+ }
13862
+ /** An `external_round` as the round it counts. */
13863
+ const externalRound = (round, project) => ({
13864
+ kind: "external_round",
13865
+ counter: courseCounter({ kind: "external_round" }, project),
13866
+ reviewer: round.reviewer,
13867
+ head: round.head.toLowerCase()
13868
+ });
13869
+ /** The rounds counted under `counter` since the last close of its course-check item. */
13870
+ function roundsSince(course, counter) {
13871
+ const rounds = [];
13872
+ for (const entry of course) {
13873
+ if (entry.counter !== counter) continue;
13874
+ if (entry.kind === "reset") rounds.length = 0;
13875
+ else rounds.push(entry);
13876
+ }
13877
+ return rounds;
13878
+ }
13879
+ /** The task's replay, read on first use and reused for the rest of one dispatcher pass. */
13880
+ function replayOnce(trx, taskId, project) {
13881
+ let replay;
13882
+ return () => replay ??= courseRounds(trx, taskId, project);
13883
+ }
13884
+ /**
13885
+ * Raises the course check of `counter` when its rounds since the last check reach the column's
13886
+ * `courseCheck`. Returns the
13887
+ * open item, or null when nothing is due.
13888
+ */
13889
+ async function raiseCourseDue(trx, input) {
13890
+ const { task, project, config, at, counter } = input;
13891
+ const threshold = project.columns.find((column) => column.id === counter)?.courseCheck ?? 0;
13892
+ if (threshold <= 0) return null;
13893
+ const replay = input.replay ?? await courseRounds(trx, task.id, project);
13894
+ const count = roundsSince(replay.course, counter).length;
13895
+ if (count < threshold) return null;
13896
+ return raiseCourseCheck(trx, {
13897
+ task,
13898
+ column: counter,
13899
+ count,
13900
+ at,
13901
+ config,
13902
+ replay
13903
+ });
13904
+ }
13905
+ /** Whether a reviewer is external: not the agent login and not a bot that left feedback. */
13906
+ function externalReviewer(pr, agentLogin, login) {
13907
+ return login.toLowerCase() !== agentLogin.toLowerCase() && !(pr.feedback ?? []).some((entry) => entry.author?.type === "bot" && entry.author.login.toLowerCase() === login.toLowerCase());
13736
13908
  }
13737
13909
  /**
13738
13910
  * Raises the course check of a task's column, once while it is open: a `system` question to the
13739
- * column's `courseCheckTo` addressee (`courseAddressee`), with the open findings in its reason.
13911
+ * column's `courseCheckTo` addressee (`courseAddressee`), with the counted rounds and the open
13912
+ * findings in its reason.
13740
13913
  * The answer to the block resets the course count.
13741
13914
  */
13742
13915
  async function raiseCourseCheck(trx, input) {
@@ -13747,7 +13920,13 @@ async function raiseCourseCheck(trx, input) {
13747
13920
  const url = taskUrl(task, config);
13748
13921
  const block = await openSystemBlock(trx, {
13749
13922
  task,
13750
- reason: await courseSummary(trx, task, column, count, url),
13923
+ reason: await courseSummary(trx, task, {
13924
+ column,
13925
+ count,
13926
+ url,
13927
+ config,
13928
+ replay: input.replay
13929
+ }),
13751
13930
  at: at.toISOString(),
13752
13931
  config,
13753
13932
  addressee: courseAddressee(config, task.project, column)
@@ -13755,7 +13934,7 @@ async function raiseCourseCheck(trx, input) {
13755
13934
  return raiseItem(trx, {
13756
13935
  itemKey,
13757
13936
  kind: "course_check",
13758
- text: `${task.key}: course check after ${String(count)} returns from ${column}`,
13937
+ text: column === "external-review" ? `${task.key}: course check after ${countOf(count, EXTERNAL_ROUNDS)}` : `${task.key}: course check after ${String(count)} returns from ${column}`,
13759
13938
  url,
13760
13939
  taskId: task.id,
13761
13940
  blockId: block.id,
@@ -13777,14 +13956,44 @@ function courseAddressee(config, projectId, column) {
13777
13956
  const orchestrated = columns.find((c) => c.id === column && c.orchestrator === to) ?? columns.find((c) => c.orchestrator === to);
13778
13957
  return orchestrated === void 0 ? fallback : `orchestrator:${orchestrated.id}`;
13779
13958
  }
13780
- /** The question of a course check: the count, the open findings and the links. */
13781
- async function courseSummary(trx, task, column, count, url) {
13959
+ /** How External Review's course question counts each kind of round: `[singular, plural]`. */
13960
+ const ROUND_KINDS = {
13961
+ executor: ["executor return", "executor returns"],
13962
+ external: ["return for external comments", "returns for external comments"],
13963
+ other: ["other return", "other returns"],
13964
+ request: ["change request on a new head", "change requests on new heads"]
13965
+ };
13966
+ /** External Review's rounds, in the singular for one. */
13967
+ const EXTERNAL_ROUNDS = ["external review round", "external review rounds"];
13968
+ /** `n` of a thing, in the singular form for one. */
13969
+ const countOf = (n, [one, many]) => `${String(n)} ${n === 1 ? one : many}`;
13970
+ /** The question of a course check: the count, the counted rounds, the open findings and the links. */
13971
+ async function courseSummary(trx, task, input) {
13972
+ const { column, count, url, config } = input;
13782
13973
  const pr = await prFacts(trx, task.id);
13783
13974
  const current = pr?.headSha.toLowerCase();
13784
13975
  const short = (sha) => sha.toLowerCase() === current ? `${sha.slice(0, 7)} (current head)` : sha.slice(0, 7);
13976
+ const project = config.projects.find((entry) => entry.id === task.project) ?? {
13977
+ columns: [],
13978
+ operatorGithubLogin: ""
13979
+ };
13980
+ const rounds = roundsSince((input.replay ?? await courseRounds(trx, task.id, project)).course, column);
13981
+ const external = column === EXTERNAL_COUNTER;
13982
+ const kinds = rounds.map((round) => round.kind === "external_round" ? "request" : round.cause);
13983
+ const split = Object.entries(ROUND_KINDS).map(([kind, forms]) => ({
13984
+ n: kinds.filter((entry) => entry === kind).length,
13985
+ forms
13986
+ })).filter(({ n }) => n > 0).map(({ n, forms }) => countOf(n, forms)).join(", ");
13785
13987
  const findings = await openFindings(trx, task.id);
13786
13988
  const lines = [
13787
- `course check: ${String(count)} returns to Dev from ${column} since the last check`,
13989
+ external ? `course check: ${countOf(count, EXTERNAL_ROUNDS)} since the last check: ${split}` : `course check: ${String(count)} returns to Dev from ${column} since the last check`,
13990
+ rounds.length === 0 ? "Counted rounds: none recorded" : "Counted rounds:",
13991
+ ...rounds.map((round) => {
13992
+ const head = round.head === null ? "unknown head" : short(round.head);
13993
+ if (round.kind === "external_round") return `- change request by ${round.reviewer} on ${head}`;
13994
+ if (external && round.cause === "executor") return `- return to Dev by the ${round.from} executor on ${head}`;
13995
+ return round.cause === "external" ? `- return to Dev from ${round.from} for external comments on ${head}` : `- return to Dev from ${round.from} on ${head}`;
13996
+ }),
13788
13997
  findings.length === 0 ? "Open findings: none on the board" : "Open findings:",
13789
13998
  ...findings.map((finding) => `- B${String(finding.id)} by ${finding.author.replace(/^agent:/, "")} on ${finding.head === null ? "unknown head" : short(finding.head)}: ${capPoints(finding.text, MAX_FINDING)}`)
13790
13999
  ];
@@ -13854,6 +14063,255 @@ async function shadowCourseCheck(trx, taskId, move, project) {
13854
14063
  const after = countCycles([...past, current], move.from, every).count;
13855
14064
  return after > before && after % every === 0;
13856
14065
  }
14066
+ // ../core/src/app/status-views.ts
14067
+ /** The column groups with their built-in columns in canonical order, the same for every project. */
14068
+ function columnGroupViews() {
14069
+ return COLUMN_GROUPS.map((id) => ({
14070
+ id,
14071
+ columns: COLUMNS.filter((c) => c.group === id).map((c) => c.id)
14072
+ }));
14073
+ }
14074
+ /** Factual PR rollup; the caller owns snapshot freshness and all reads. */
14075
+ function summarizePr(fact, factAt, unconfirmed) {
14076
+ const checks = fact.requiredChecks.length > 0 ? fact.requiredChecks : fact.checks;
14077
+ return {
14078
+ repo: fact.repo,
14079
+ number: fact.number,
14080
+ checks: {
14081
+ pass: checks.filter((check) => check.state === "success" || check.state === "neutral").length,
14082
+ pending: checks.filter((check) => check.state === "expected" || check.state === "pending").length,
14083
+ fail: checks.filter((check) => ![
14084
+ "success",
14085
+ "neutral",
14086
+ "expected",
14087
+ "pending"
14088
+ ].includes(check.state)).length
14089
+ },
14090
+ mergeable: fact.mergeable,
14091
+ threads: {
14092
+ unresolved: fact.reviewThreads.filter((thread) => !thread.resolved).length,
14093
+ total: fact.reviewThreads.length
14094
+ },
14095
+ reviewsOnHead: {
14096
+ approved: fact.reviews.filter((review) => review.commitSha === fact.headSha && review.state === "approved").map((review) => review.reviewer),
14097
+ changesRequested: fact.reviews.filter((review) => review.commitSha === fact.headSha && review.state === "changes_requested").map((review) => review.reviewer)
14098
+ },
14099
+ draft: fact.draft,
14100
+ factAt,
14101
+ unconfirmed
14102
+ };
14103
+ }
14104
+ /** Load compact unclosed turn scalars once for the visible page. */
14105
+ async function readStatusTurns(db, projectIds) {
14106
+ const turnRows = await db.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").leftJoin("notification", (join) => join.onRef("notification.turn_id", "=", "turn.id").on("notification.kind", "=", "turn").on("notification.id", "=", (eb) => eb.selectFrom("notification as newest").select((eb) => eb.fn.max("newest.id").as("id")).whereRef("newest.turn_id", "=", "turn.id").where("newest.kind", "=", "turn"))).select([
14107
+ "turn.id",
14108
+ "turn.task_id",
14109
+ "turn.column",
14110
+ "turn.role",
14111
+ "turn.reason",
14112
+ "turn.head_sha",
14113
+ "turn.created_at",
14114
+ "turn.acked_by",
14115
+ "turn.acked_at"
14116
+ ]).select(["task.key as task_key", "notification.recipient_session"]).select((eb) => eb.selectFrom("operator_item").select((eb) => eb.fn.min("operator_item.fact_at").as("fact_at")).where("operator_item.cleared_at", "is", null).where("operator_item.item_key", ">=", sql`'turn-stall:' || ${sql.ref("turn.id")} || ':'`).where("operator_item.item_key", "<", sql`'turn-stall:' || ${sql.ref("turn.id")} || ';'`).as("stalled_since")).where("turn.closed_at", "is", null).where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).execute();
14117
+ return new Map(turnRows.map((turn) => [turn.task_id, {
14118
+ id: `T${String(turn.id)}`,
14119
+ task: turn.task_key,
14120
+ column: turn.column,
14121
+ addressee: turn.role,
14122
+ reason: turn.reason,
14123
+ head: turn.head_sha,
14124
+ at: turn.created_at,
14125
+ taken: turn.acked_by === null || turn.acked_at === null ? null : {
14126
+ by: turn.acked_by,
14127
+ at: turn.acked_at
14128
+ },
14129
+ addressedTo: turn.acked_at === null ? turn.recipient_session : null,
14130
+ stalledSince: turn.stalled_since
14131
+ }]));
14132
+ }
14133
+ /**
14134
+ * Load the return marker of each visible Dev task once for the page: set while the newest column
14135
+ * change of the task (a move, a non-shadow correction, a submit or an add) is the `task.return`
14136
+ * move into Dev, which journals its turn and block.
14137
+ */
14138
+ async function readStatusReturns(db, projectIds) {
14139
+ const rows = await db.selectFrom("task").innerJoin("event", (join) => join.onRef("event.task_id", "=", "task.id").on("event.id", "=", (eb) => eb.selectFrom("event as newest").select("newest.id").whereRef("newest.task_id", "=", "task.id").where((eb) => eb.or([eb("newest.kind", "in", [
14140
+ "task_moved",
14141
+ "task_submitted",
14142
+ "task_added"
14143
+ ]), eb.and([eb("newest.kind", "=", "task_corrected"), eb(sql`coalesce(json_extract(newest.payload, '$.shadow'), 0)`, "=", 0)])])).orderBy("newest.id", "desc").limit(1))).select([
14144
+ "task.id as task_id",
14145
+ "event.at",
14146
+ "event.actor",
14147
+ "event.actor_ref",
14148
+ "event.payload"
14149
+ ]).where("task.column", "=", "dev").where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).where("event.kind", "=", "task_moved").execute();
14150
+ const returns = /* @__PURE__ */ new Map();
14151
+ for (const row of rows) {
14152
+ const parsed = eventPayloadSchemas.task_moved.safeParse(JSON.parse(row.payload));
14153
+ if (!parsed.success) continue;
14154
+ const { from, to, turn, block, findings } = parsed.data;
14155
+ if (turn === void 0 || block === void 0 || to !== "dev") continue;
14156
+ returns.set(row.task_id, {
14157
+ from,
14158
+ at: row.at,
14159
+ by: eventActor(row),
14160
+ block,
14161
+ findings: findings ?? null
14162
+ });
14163
+ }
14164
+ return returns;
14165
+ }
14166
+ /**
14167
+ * Load the open blocks of visible tasks once for the page, oldest first, each with the session
14168
+ * the newest block notification for its current addressee role went to.
14169
+ */
14170
+ async function readStatusBlocks(db, projectIds) {
14171
+ const rows = await db.selectFrom("block").innerJoin("task", "task.id", "block.task_id").leftJoin("notification", (join) => join.onRef("notification.block_id", "=", "block.id").on("notification.kind", "=", "block").onRef("notification.role", "=", "block.addressee_role").on("notification.id", "=", (eb) => eb.selectFrom("notification as newest").select((eb) => eb.fn.max("newest.id").as("id")).whereRef("newest.block_id", "=", "block.id").where("newest.kind", "=", "block").whereRef("newest.role", "=", "block.addressee_role"))).select([
14172
+ "block.id",
14173
+ "task.id as task_id",
14174
+ "block.addressee_role"
14175
+ ]).select("notification.recipient_session").where("block.state", "=", "open").where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).orderBy("block.id").execute();
14176
+ const blocks = /* @__PURE__ */ new Map();
14177
+ for (const row of rows) {
14178
+ const list = blocks.get(row.task_id) ?? [];
14179
+ list.push({
14180
+ id: `B${String(row.id)}`,
14181
+ addressee: row.addressee_role,
14182
+ session: row.addressee_role === "operator" ? null : row.recipient_session
14183
+ });
14184
+ blocks.set(row.task_id, list);
14185
+ }
14186
+ return blocks;
14187
+ }
14188
+ /**
14189
+ * Latest real entry into each visible task's current column, ordered by journal position; with
14190
+ * `taskId`, of that task only, read through the event index on `(task_id, id)`.
14191
+ */
14192
+ async function readStatusColumnEntries(db, projectIds, taskId) {
14193
+ return await db.selectFrom("event").innerJoin((eb) => eb.selectFrom("event as entry").innerJoin("task", "task.id", "entry.task_id").select((eb) => eb.fn.max("entry.id").as("id")).where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).$if(taskId !== void 0, (query) => query.where("entry.task_id", "=", taskId ?? 0)).where(sql`(json_extract(entry.payload, '$.to') = task.column OR (
14194
+ entry.kind = 'task_added' AND entry.at = task.created_at AND json_extract(entry.payload, '$.column') = task.column AND entry.id = (
14195
+ SELECT MIN(original.id) FROM event original WHERE original.task_id = task.id AND original.kind = 'task_added'
14196
+ )
14197
+ ))`).where(sql`(entry.kind in ('task_added', 'task_moved', 'task_manually_moved') or (entry.kind = 'task_corrected' and json_extract(entry.payload, '$.shadow') = 0))`).groupBy("entry.task_id").as("latest"), (join) => join.onRef("latest.id", "=", "event.id")).select([
14198
+ "event.task_id",
14199
+ "event.at",
14200
+ "event.id"
14201
+ ]).execute();
14202
+ }
14203
+ function sourceInterval(config, source) {
14204
+ if (source === "spur") return config.adapters.spur.intervalMs;
14205
+ if (source.startsWith("jira:")) return config.adapters.jira.intervalMs;
14206
+ if (source.startsWith("github-issues:")) return config.adapters.githubIssues.intervalMs;
14207
+ return config.adapters.github.intervalMs;
14208
+ }
14209
+ /** Counts of each value, rendered as `<n> <value>` in the given order. */
14210
+ function counts(values, order) {
14211
+ return order.map((value) => [value, values.filter((entry) => entry === value).length]).filter(([, n]) => n > 0).map(([value, n]) => `${String(n)} ${value}`).join(", ");
14212
+ }
14213
+ /** Session facts rendered in status detail. */
14214
+ function sessionView(fact) {
14215
+ return {
14216
+ ...fact,
14217
+ links: Object.entries(fact.links).map(([label, url]) => ({
14218
+ label,
14219
+ url
14220
+ }))
14221
+ };
14222
+ }
14223
+ /** Order group visits in their own slots, preserving non-group relative ordering. */
14224
+ function orderTodoGroupRows(rows, entries, projects) {
14225
+ const columnEntries = new Map(entries.map((entry) => [entry.task_id, entry.at]));
14226
+ const entryOrder = new Map(entries.map((entry) => [entry.task_id, entry.id]));
14227
+ for (const project of projects) for (const column of TODO_GROUP_COLUMN_IDS) {
14228
+ const slots = rows.flatMap((row, index) => row.project === project.id && row.column === column ? [index] : []);
14229
+ const ordered = slots.map((index) => rows[index]).filter((row) => row !== void 0).sort((left, right) => Date.parse(columnEntries.get(left.id) ?? left.created_at) - Date.parse(columnEntries.get(right.id) ?? right.created_at) || (entryOrder.get(left.id) ?? 0) - (entryOrder.get(right.id) ?? 0) || left.id - right.id);
14230
+ for (const [index, slot] of slots.entries()) {
14231
+ const row = ordered[index];
14232
+ if (row !== void 0) rows[slot] = row;
14233
+ }
14234
+ }
14235
+ }
14236
+ // ../core/src/app/external-rounds.ts
14237
+ /**
14238
+ * While the task is in Dev with the dispatcher on and External Review's course check on, records
14239
+ * one `external_round` for each external change request on the open PR that came after the task
14240
+ * entered Dev, on a head not yet counted under External Review: by an earlier round or by a
14241
+ * return counted there, resets ignored, and not while the PR's GitHub source is `blind` (no
14242
+ * complete poll since the start, or blind).
14243
+ */
14244
+ async function recordExternalRounds(trx, input) {
14245
+ const { task, project, at, blind } = input;
14246
+ if (!counting(task, project)) return;
14247
+ const pr = await prFacts(trx, task.id);
14248
+ const requests = pr?.state === "open" ? pr.reviews.filter((review) => review.state === "changes_requested" && externalReviewer(pr, project.operatorGithubLogin, review.reviewer)) : [];
14249
+ if (pr === null || requests.length === 0 || blind(prSourceId(project.id, pr.repo))) return;
14250
+ const [entry] = await readStatusColumnEntries(trx, /* @__PURE__ */ new Set([task.project]), task.id);
14251
+ const entered = Date.parse(entry?.at ?? task.created_at);
14252
+ const after = requests.filter((review) => Date.parse(review.submittedAt) > entered).sort((left, right) => Date.parse(left.submittedAt) - Date.parse(right.submittedAt) || left.reviewer.localeCompare(right.reviewer));
14253
+ if (after.length === 0) return;
14254
+ const replay = await input.replay();
14255
+ const counted = replay.externalHeads;
14256
+ for (const review of after) {
14257
+ const head = review.commitSha.toLowerCase();
14258
+ if (counted.has(head)) continue;
14259
+ counted.add(head);
14260
+ await emit(trx, "external_round", task.project, task.id, at.toISOString(), {
14261
+ repo: pr.repo,
14262
+ pr: pr.number,
14263
+ head,
14264
+ reviewer: review.reviewer
14265
+ });
14266
+ replay.course.push(externalRound({
14267
+ reviewer: review.reviewer,
14268
+ head
14269
+ }, project));
14270
+ }
14271
+ }
14272
+ /** The columns a return from External Review can go to: every column left of it. */
14273
+ const LEFT_OF_EXTERNAL = COLUMN_IDS.slice(0, COLUMN_IDS.indexOf(EXTERNAL_COUNTER));
14274
+ /** Gate reasons that give a return a cause its cycle limit counts (`countCycles`). */
14275
+ const COUNTED_GATE = GATE_REASONS.filter((reason) => countCycles(returnCauses([reason], false).map((cause) => ({
14276
+ kind: "return",
14277
+ column: EXTERNAL_COUNTER,
14278
+ causes: [cause]
14279
+ })), EXTERNAL_COUNTER, Infinity).count > 0);
14280
+ /**
14281
+ * Whether the task's journal may hold a round External Review's counter takes (`courseCounter`):
14282
+ * an `external_round`, a move whose gate holds an external cause (`EXTERNAL_CAUSES`) from any
14283
+ * column, or a left move from External Review with a counted cause: its executor's (a block) or a
14284
+ * counted gate reason (`COUNTED_GATE`). A push-only return (`no_submit_on_head`) counts nowhere
14285
+ * and matches nothing. A superset of the counted entries: a move it lets through only costs a
14286
+ * replay, and none it drops can count. Without one the deferred raise reads no PR history. One
14287
+ * row at most, through the event task index.
14288
+ */
14289
+ async function mayCount(trx, taskId) {
14290
+ return await trx.selectFrom("event").select("id").where("task_id", "=", taskId).where(sql`(kind = 'external_round' or (kind = 'task_moved' and (exists (select 1 from json_each(event.payload, '$.gate') where value in (select value from json_each(${JSON.stringify(EXTERNAL_CAUSES)}))) or (json_extract(payload, '$.from') = ${EXTERNAL_COUNTER} and json_extract(payload, '$.to') in (select value from json_each(${JSON.stringify(LEFT_OF_EXTERNAL)})) and (json_extract(payload, '$.block') is not null or exists (select 1 from json_each(event.payload, '$.gate') where value in (select value from json_each(${JSON.stringify(COUNTED_GATE)}))))))))`).limit(1).executeTakeFirst() !== void 0;
14291
+ }
14292
+ /** Whether External Review counts the task's Dev rounds: dispatcher on, in Dev, its check on. */
14293
+ function counting(task, project) {
14294
+ const external = externalColumn(project);
14295
+ return project.dispatcher.mode === "on" && task.column === "dev" && external !== void 0 && external.courseCheck > 0;
14296
+ }
14297
+ /**
14298
+ * Raises External Review's course check of a task in Dev once its rounds since the last check
14299
+ * reach its `courseCheck`, returns alone included: a check a return reached while another item
14300
+ * held the task. The dispatcher calls it only in a pass that leaves the task unheld in Dev, after
14301
+ * its decision, so completion and every other move go first. Returns whether it raised.
14302
+ */
14303
+ async function raiseDeferredCourseCheck(trx, input) {
14304
+ const { task, project, config, at } = input;
14305
+ if (!counting(task, project) || !await mayCount(trx, task.id)) return false;
14306
+ return await raiseCourseDue(trx, {
14307
+ task,
14308
+ project,
14309
+ config,
14310
+ at,
14311
+ counter: courseCounter({ kind: "external_round" }, project),
14312
+ replay: await input.replay()
14313
+ }) !== null;
14314
+ }
13857
14315
  // ../core/src/app/cancelled-checks.ts
13858
14316
  /** Complete scheduled polls after the sighting that confirm a cancel as red. */
13859
14317
  const CANCEL_CONFIRM_POLLS = 2;
@@ -15216,8 +15674,8 @@ async function voidSubmits(trx, taskId, to, at) {
15216
15674
  * Moves a task left to `to` as a new visit: bumps `column_epoch` and `left_moves`, voids the
15217
15675
  * submits of `to` and right of it, closes its turns (`returned` for a `task.return` of `turn`,
15218
15676
  * else `moved`, named on `turn_closed` as `closedBy` when given) and journals `task_moved`. In `on` mode a counted return that reaches the
15219
- * column's cycle limit raises its cycle-limit block; otherwise one that reaches its course check
15220
- * raises the course check. Either holds the task, and
15677
+ * column's cycle limit raises its cycle-limit block; otherwise one that reaches the course check
15678
+ * of the column it counts under (`courseCounter`) raises that course check. Either holds the task, and
15221
15679
  * `limitReached` tells the dispatcher to stop the cascade.
15222
15680
  */
15223
15681
  async function moveLeft(trx, input) {
@@ -15250,8 +15708,7 @@ async function moveLeft(trx, input) {
15250
15708
  task: moved,
15251
15709
  limitReached: false
15252
15710
  };
15253
- const counts = await returnCounts(trx, task.id, task.column);
15254
- if (counts.cycle >= column.cycleLimit) {
15711
+ if (countCycles(await cycleEvents(trx, task.id), task.column, Infinity).count >= column.cycleLimit) {
15255
15712
  await raiseCycleLimit(trx, {
15256
15713
  task: moved,
15257
15714
  column: task.column,
@@ -15263,22 +15720,19 @@ async function moveLeft(trx, input) {
15263
15720
  limitReached: true
15264
15721
  };
15265
15722
  }
15266
- if (column.courseCheck > 0 && counts.course >= column.courseCheck) {
15267
- await raiseCourseCheck(trx, {
15268
- task: moved,
15269
- column: task.column,
15270
- count: counts.course,
15271
- at,
15272
- config
15273
- });
15274
- return {
15275
- task: moved,
15276
- limitReached: true
15277
- };
15278
- }
15279
15723
  return {
15280
15724
  task: moved,
15281
- limitReached: false
15725
+ limitReached: await raiseCourseDue(trx, {
15726
+ task: moved,
15727
+ project,
15728
+ config,
15729
+ at,
15730
+ counter: courseCounter({
15731
+ kind: "return",
15732
+ column: task.column,
15733
+ causes: returnCauses(gate ?? [], block !== void 0)
15734
+ }, project)
15735
+ }) !== null
15282
15736
  };
15283
15737
  }
15284
15738
  /**
@@ -15902,12 +16356,34 @@ async function dispatchTasks(trx, taskIds, ctx) {
15902
16356
  const project = ctx.config.projects.find((entry) => entry.id === task.project);
15903
16357
  if (project === void 0) continue;
15904
16358
  const mode = project.dispatcher.mode;
16359
+ const replay = replayOnce(trx, task.id, project);
16360
+ if (mode === "on") await recordExternalRounds(trx, {
16361
+ task,
16362
+ project,
16363
+ at: ctx.at,
16364
+ blind,
16365
+ replay
16366
+ });
15905
16367
  const read = await readInput(trx, task, project, mode, blind, ctx.config, ctx);
15906
16368
  if (read === null) continue;
15907
16369
  if (read.pending?.state === "superseded") await supersedeSubmit(trx, task, read.pending, ctx.at);
15908
16370
  if (read.ticketUnconfirmed) continue;
15909
16371
  if (read.pending?.state === "confirmed") await confirmSubmit(trx, task, read.pending, ctx.at);
15910
- const result = dispatch(read.input);
16372
+ let result = dispatch(read.input);
16373
+ const devWaitsForSpur = (project.columns.find((column) => column.id === "dev")?.orchestrator ?? "none") === "none";
16374
+ if (mode === "on" && result.moves.length === 0 && dispatchHolds({
16375
+ ...read.input,
16376
+ spurBlind: devWaitsForSpur && read.input.spurBlind
16377
+ }).length === 0 && await raiseDeferredCourseCheck(trx, {
16378
+ task,
16379
+ project,
16380
+ config: ctx.config,
16381
+ at: ctx.at,
16382
+ replay
16383
+ })) result = dispatch({
16384
+ ...read.input,
16385
+ cycleHeld: true
16386
+ });
15911
16387
  if (mode === "shadow") await applyShadow(trx, task, project, result, ctx.at);
15912
16388
  else await applyOn(trx, task, read, result, ctx);
15913
16389
  }
@@ -17041,173 +17517,6 @@ async function readOutageEnds(db) {
17041
17517
  }
17042
17518
  return outageEnds;
17043
17519
  }
17044
- // ../core/src/app/status-views.ts
17045
- /** The column groups with their built-in columns in canonical order, the same for every project. */
17046
- function columnGroupViews() {
17047
- return COLUMN_GROUPS.map((id) => ({
17048
- id,
17049
- columns: COLUMNS.filter((c) => c.group === id).map((c) => c.id)
17050
- }));
17051
- }
17052
- /** Factual PR rollup; the caller owns snapshot freshness and all reads. */
17053
- function summarizePr(fact, factAt, unconfirmed) {
17054
- const checks = fact.requiredChecks.length > 0 ? fact.requiredChecks : fact.checks;
17055
- return {
17056
- repo: fact.repo,
17057
- number: fact.number,
17058
- checks: {
17059
- pass: checks.filter((check) => check.state === "success" || check.state === "neutral").length,
17060
- pending: checks.filter((check) => check.state === "expected" || check.state === "pending").length,
17061
- fail: checks.filter((check) => ![
17062
- "success",
17063
- "neutral",
17064
- "expected",
17065
- "pending"
17066
- ].includes(check.state)).length
17067
- },
17068
- mergeable: fact.mergeable,
17069
- threads: {
17070
- unresolved: fact.reviewThreads.filter((thread) => !thread.resolved).length,
17071
- total: fact.reviewThreads.length
17072
- },
17073
- reviewsOnHead: {
17074
- approved: fact.reviews.filter((review) => review.commitSha === fact.headSha && review.state === "approved").map((review) => review.reviewer),
17075
- changesRequested: fact.reviews.filter((review) => review.commitSha === fact.headSha && review.state === "changes_requested").map((review) => review.reviewer)
17076
- },
17077
- draft: fact.draft,
17078
- factAt,
17079
- unconfirmed
17080
- };
17081
- }
17082
- /** Load compact unclosed turn scalars once for the visible page. */
17083
- async function readStatusTurns(db, projectIds) {
17084
- const turnRows = await db.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").leftJoin("notification", (join) => join.onRef("notification.turn_id", "=", "turn.id").on("notification.kind", "=", "turn").on("notification.id", "=", (eb) => eb.selectFrom("notification as newest").select((eb) => eb.fn.max("newest.id").as("id")).whereRef("newest.turn_id", "=", "turn.id").where("newest.kind", "=", "turn"))).select([
17085
- "turn.id",
17086
- "turn.task_id",
17087
- "turn.column",
17088
- "turn.role",
17089
- "turn.reason",
17090
- "turn.head_sha",
17091
- "turn.created_at",
17092
- "turn.acked_by",
17093
- "turn.acked_at"
17094
- ]).select(["task.key as task_key", "notification.recipient_session"]).select((eb) => eb.selectFrom("operator_item").select((eb) => eb.fn.min("operator_item.fact_at").as("fact_at")).where("operator_item.cleared_at", "is", null).where("operator_item.item_key", ">=", sql`'turn-stall:' || ${sql.ref("turn.id")} || ':'`).where("operator_item.item_key", "<", sql`'turn-stall:' || ${sql.ref("turn.id")} || ';'`).as("stalled_since")).where("turn.closed_at", "is", null).where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).execute();
17095
- return new Map(turnRows.map((turn) => [turn.task_id, {
17096
- id: `T${String(turn.id)}`,
17097
- task: turn.task_key,
17098
- column: turn.column,
17099
- addressee: turn.role,
17100
- reason: turn.reason,
17101
- head: turn.head_sha,
17102
- at: turn.created_at,
17103
- taken: turn.acked_by === null || turn.acked_at === null ? null : {
17104
- by: turn.acked_by,
17105
- at: turn.acked_at
17106
- },
17107
- addressedTo: turn.acked_at === null ? turn.recipient_session : null,
17108
- stalledSince: turn.stalled_since
17109
- }]));
17110
- }
17111
- /**
17112
- * Load the return marker of each visible Dev task once for the page: set while the newest column
17113
- * change of the task (a move, a non-shadow correction, a submit or an add) is the `task.return`
17114
- * move into Dev, which journals its turn and block.
17115
- */
17116
- async function readStatusReturns(db, projectIds) {
17117
- const rows = await db.selectFrom("task").innerJoin("event", (join) => join.onRef("event.task_id", "=", "task.id").on("event.id", "=", (eb) => eb.selectFrom("event as newest").select("newest.id").whereRef("newest.task_id", "=", "task.id").where((eb) => eb.or([eb("newest.kind", "in", [
17118
- "task_moved",
17119
- "task_submitted",
17120
- "task_added"
17121
- ]), eb.and([eb("newest.kind", "=", "task_corrected"), eb(sql`coalesce(json_extract(newest.payload, '$.shadow'), 0)`, "=", 0)])])).orderBy("newest.id", "desc").limit(1))).select([
17122
- "task.id as task_id",
17123
- "event.at",
17124
- "event.actor",
17125
- "event.actor_ref",
17126
- "event.payload"
17127
- ]).where("task.column", "=", "dev").where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).where("event.kind", "=", "task_moved").execute();
17128
- const returns = /* @__PURE__ */ new Map();
17129
- for (const row of rows) {
17130
- const parsed = eventPayloadSchemas.task_moved.safeParse(JSON.parse(row.payload));
17131
- if (!parsed.success) continue;
17132
- const { from, to, turn, block, findings } = parsed.data;
17133
- if (turn === void 0 || block === void 0 || to !== "dev") continue;
17134
- returns.set(row.task_id, {
17135
- from,
17136
- at: row.at,
17137
- by: eventActor(row),
17138
- block,
17139
- findings: findings ?? null
17140
- });
17141
- }
17142
- return returns;
17143
- }
17144
- /**
17145
- * Load the open blocks of visible tasks once for the page, oldest first, each with the session
17146
- * the newest block notification for its current addressee role went to.
17147
- */
17148
- async function readStatusBlocks(db, projectIds) {
17149
- const rows = await db.selectFrom("block").innerJoin("task", "task.id", "block.task_id").leftJoin("notification", (join) => join.onRef("notification.block_id", "=", "block.id").on("notification.kind", "=", "block").onRef("notification.role", "=", "block.addressee_role").on("notification.id", "=", (eb) => eb.selectFrom("notification as newest").select((eb) => eb.fn.max("newest.id").as("id")).whereRef("newest.block_id", "=", "block.id").where("newest.kind", "=", "block").whereRef("newest.role", "=", "block.addressee_role"))).select([
17150
- "block.id",
17151
- "task.id as task_id",
17152
- "block.addressee_role"
17153
- ]).select("notification.recipient_session").where("block.state", "=", "open").where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).orderBy("block.id").execute();
17154
- const blocks = /* @__PURE__ */ new Map();
17155
- for (const row of rows) {
17156
- const list = blocks.get(row.task_id) ?? [];
17157
- list.push({
17158
- id: `B${String(row.id)}`,
17159
- addressee: row.addressee_role,
17160
- session: row.addressee_role === "operator" ? null : row.recipient_session
17161
- });
17162
- blocks.set(row.task_id, list);
17163
- }
17164
- return blocks;
17165
- }
17166
- /** Latest real entry into each visible task's current column, ordered by journal position. */
17167
- async function readStatusColumnEntries(db, projectIds) {
17168
- return await db.selectFrom("event").innerJoin((eb) => eb.selectFrom("event as entry").innerJoin("task", "task.id", "entry.task_id").select((eb) => eb.fn.max("entry.id").as("id")).where("task.membership", "!=", "archived").where("task.project", "in", [...projectIds]).where(sql`(json_extract(entry.payload, '$.to') = task.column OR (
17169
- entry.kind = 'task_added' AND entry.at = task.created_at AND json_extract(entry.payload, '$.column') = task.column AND entry.id = (
17170
- SELECT MIN(original.id) FROM event original WHERE original.task_id = task.id AND original.kind = 'task_added'
17171
- )
17172
- ))`).where(sql`(entry.kind in ('task_added', 'task_moved', 'task_manually_moved') or (entry.kind = 'task_corrected' and json_extract(entry.payload, '$.shadow') = 0))`).groupBy("entry.task_id").as("latest"), (join) => join.onRef("latest.id", "=", "event.id")).select([
17173
- "event.task_id",
17174
- "event.at",
17175
- "event.id"
17176
- ]).execute();
17177
- }
17178
- function sourceInterval(config, source) {
17179
- if (source === "spur") return config.adapters.spur.intervalMs;
17180
- if (source.startsWith("jira:")) return config.adapters.jira.intervalMs;
17181
- if (source.startsWith("github-issues:")) return config.adapters.githubIssues.intervalMs;
17182
- return config.adapters.github.intervalMs;
17183
- }
17184
- /** Counts of each value, rendered as `<n> <value>` in the given order. */
17185
- function counts(values, order) {
17186
- return order.map((value) => [value, values.filter((entry) => entry === value).length]).filter(([, n]) => n > 0).map(([value, n]) => `${String(n)} ${value}`).join(", ");
17187
- }
17188
- /** Session facts rendered in status detail. */
17189
- function sessionView(fact) {
17190
- return {
17191
- ...fact,
17192
- links: Object.entries(fact.links).map(([label, url]) => ({
17193
- label,
17194
- url
17195
- }))
17196
- };
17197
- }
17198
- /** Order group visits in their own slots, preserving non-group relative ordering. */
17199
- function orderTodoGroupRows(rows, entries, projects) {
17200
- const columnEntries = new Map(entries.map((entry) => [entry.task_id, entry.at]));
17201
- const entryOrder = new Map(entries.map((entry) => [entry.task_id, entry.id]));
17202
- for (const project of projects) for (const column of TODO_GROUP_COLUMN_IDS) {
17203
- const slots = rows.flatMap((row, index) => row.project === project.id && row.column === column ? [index] : []);
17204
- const ordered = slots.map((index) => rows[index]).filter((row) => row !== void 0).sort((left, right) => Date.parse(columnEntries.get(left.id) ?? left.created_at) - Date.parse(columnEntries.get(right.id) ?? right.created_at) || (entryOrder.get(left.id) ?? 0) - (entryOrder.get(right.id) ?? 0) || left.id - right.id);
17205
- for (const [index, slot] of slots.entries()) {
17206
- const row = ordered[index];
17207
- if (row !== void 0) rows[slot] = row;
17208
- }
17209
- }
17210
- }
17211
17520
  // ../core/src/app/status.ts
17212
17521
  /** End reasons in the words of the "worker ended" item (`ENDED_WORKER_LABELS`, fromYou.ts). */
17213
17522
  const END_WORDS = {
@@ -17607,6 +17916,7 @@ const EVENT_SUMMARIES = {
17607
17916
  task_shadow_moved: "Shadow move",
17608
17917
  task_corrected: "Column corrected by the operator",
17609
17918
  task_manually_moved: "Task manually moved by the operator",
17919
+ external_round: "External change-request round",
17610
17920
  dispatcher_mode_changed: "Dispatcher mode changed",
17611
17921
  turn_opened: "Turn opened",
17612
17922
  turn_taken: "Turn taken",
@@ -17803,6 +18113,7 @@ const SUMMARIES = {
17803
18113
  pr_state_changed: (p) => `PR ${ref$1(p.repo, p.pr)}: ${from(p.from, p.to)}`,
17804
18114
  ticket_status_changed: (p) => `Ticket status: ${from(p.from, p.to)}`,
17805
18115
  review_submitted: (p) => `Review by ${p.reviewer} on ${ref$1(p.repo, p.pr)}: ${p.state}`,
18116
+ external_round: (p) => `External change request by ${p.reviewer} on ${ref$1(p.repo, p.pr)} at ${p.head.slice(0, 7)}: a course-check round`,
17806
18117
  task_moved: (p) => `Moved ${p.from} → ${p.to}${optional(": ", p.reason)}${gates(p.gate)}`,
17807
18118
  task_shadow_moved: (p) => `Would move ${p.from} → ${p.to} (shadow mode): ${p.reason}${gates(p.gate)}${p.courseCheck === true ? ", with a course check" : ""}`,
17808
18119
  block_opened: (p) => `Block ${p.block} opened: ${p.type} for ${p.addressee}`,
@@ -18308,7 +18619,7 @@ async function describeProject(trx, config, project) {
18308
18619
  }, curator !== null, heldByActor).addressee;
18309
18620
  }
18310
18621
  }
18311
- const returns = returnRules(column.id, metadata.returnable, kind === "dispatcher", from);
18622
+ const returns = returnRules(column.id, metadata.returnable, kind === "dispatcher", from, externalRule(project, column.id));
18312
18623
  const next = nextColumn(project, column.id);
18313
18624
  const timings = columnTurnTimings(config, project.id, column.id);
18314
18625
  const quietAfterMs = stuckTurnAfterMs(config, project.id, {
@@ -18366,14 +18677,31 @@ async function describeProject(trx, config, project) {
18366
18677
  columns
18367
18678
  };
18368
18679
  }
18369
- function returnRules(column, returnable, dispatcher, from) {
18680
+ /** The column help of External Review while its course check is on. */
18681
+ const EXTERNAL_ROUNDS_RULE = "Returns for external comments (a changes-requested review is one) from any column, and each external change request on a new PR head while the task is in Dev, count toward this column's courseCheck, once per head; cycleLimit stays with the column the task left.";
18682
+ /** The column help of External Review while its course check is 0. */
18683
+ const EXTERNAL_ROUNDS_OFF = "Returns for external comments from any column count toward this column's courseCheck, which is 0: they raise no course check, and change requests on new PR heads in Dev are not counted; cycleLimit stays with the column the task left.";
18684
+ /** The column help of every other returnable column while External Review is enabled. */
18685
+ const EXTERNAL_RETURNS_ELSEWHERE = "Returns for external comments count toward External Review's courseCheck, not this column's; this column's cycleLimit still counts them.";
18686
+ /**
18687
+ * The column help line on where returns for external comments count (`courseCounter`), or null
18688
+ * when External Review is not enabled and every return counts on the column it left.
18689
+ */
18690
+ function externalRule(project, column) {
18691
+ const external = externalColumn(project);
18692
+ if (external === void 0) return null;
18693
+ if (column !== "external-review") return EXTERNAL_RETURNS_ELSEWHERE;
18694
+ return external.courseCheck > 0 ? EXTERNAL_ROUNDS_RULE : EXTERNAL_ROUNDS_OFF;
18695
+ }
18696
+ function returnRules(column, returnable, dispatcher, from, external) {
18370
18697
  if (column === "done") return ["A reopened ticket without a merged PR returns to Todo, not Dev."];
18371
18698
  if (!returnable) return [];
18372
18699
  return [
18373
18700
  ...!dispatcher ? ["The executor can return its taken turn to Dev with findings."] : [],
18374
18701
  "A missing or closed PR, red checks, unhandled external feedback (including changes requested), merge conflicts or a draft PR can break an upstream gate and return the task to Dev; reopened tickets may instead return to Todo.",
18375
18702
  ...from !== void 0 && COLUMN_IDS.indexOf(from) <= COLUMN_IDS.indexOf(column) ? ["Unresolved review threads, outdated ones included, return the task to Dev from the effective thread gate onward."] : [],
18376
- "A new PR head invalidates head-bound marks and submissions and can return the task to Dev. A taken turn otherwise defers broken upstream gates until submit. Pending checks, unknown mergeability and incomplete history alone hold the task without returning it."
18703
+ "A new PR head invalidates head-bound marks and submissions and can return the task to Dev. A taken turn otherwise defers broken upstream gates until submit. Pending checks, unknown mergeability and incomplete history alone hold the task without returning it.",
18704
+ ...external === null ? [] : [external]
18377
18705
  ];
18378
18706
  }
18379
18707
  // ../core/src/app/links.ts