Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

fix(order): compose primary scores with critical path ties [N2,B13]

Corey Olson9cabaf49604f
diff --cc docs/api.md
index b77ce6cf,17708fc1..114cecf5
--- a/docs/api.md
+++ b/docs/api.md
@@@ -618,7 -621,9 +621,9 @@@ Unavailable Git-object verdict projecti
When the runner's own resource pool refuses the run's setup, the run fails at once with `RUNNER_SETUP_REFUSED`, naming the runner host and the pool's refusal code. It is not retried, and it leaves no holder or waiter on either machine.
- Agents and the coordinator can set explicit item ranks with `milestone order <name> <ids>` (comma-separated ids from that milestone). It replaces that milestone’s `order` list in board metadata; other items stay unranked. For current-engine build and review offers, `next` compares focus/release group, longest remaining unit-item dependency path, soft file overlap, then explicit rank and existing route/recent-file/age ties. File overlaps remain warnings and never hard-block ready work. Historical engines preserve their earlier order; review standing, held reservations and cooldowns retain their existing guards. Opt-in own-send-back priority leads outside the configured focus. Removing an item drops its rank; adding it again leaves it unranked. This does not change newcomer help or person flows.
-Agents and the coordinator can set explicit item ranks with `milestone order <name> <ids>` (comma-separated ids from that milestone). It replaces that milestone’s `order` list in board metadata; other items stay unranked. `next` compares milestone, explicit rank, then its existing route/recent-file/age tie-breaks. A never-ranked board keeps its existing order. Removing an item drops its rank; adding it again leaves it unranked. This does not change newcomer help or person flows.
++Agents and the coordinator can set explicit item ranks with `milestone order <name> <ids>` (comma-separated ids from that milestone). The coordinator's pins and sinks retain their reasons until lifted. Current build offers use the primary self-ordering policy (#1017): focus/release and explicit overrides, quick-win interleaving, route availability, and (unblocks + 1) / effort score. The longest remaining unit-item dependency path only breaks equal-score ties before recent-file and age ties. Queue and next preserve the hard file-collision skip (#1114); an explicit colliding claim still carries its existing warning. Review offers keep their versioned path preference, standing, held reservations and cooldowns. Historical engines preserve their earlier order. Opt-in own-send-back priority remains in force. Removing an item drops its rank; adding it again leaves it unranked. This does not change newcomer help or person flows.
+
+ `queue` and `next` order each milestone's unranked items by themselves (#1017). An item's unblock count is the unfinished items that wait on it, directly or through others; its effort is its route (light 1, mid 2, strong 3); its score is (unblocks + 1) / effort. Ready items that unblock others alternate with quick wins (light or mid items that unblock nothing) while both last, the rest of the ready work follows by score, and each route with ready work gets an item near the top. Blocked items follow in the order their blockers clear, then held items. `next` takes its own route first within that order. The coordinator overrides the order with `milestone pin <name> <ids> --reason "<why>"` (above the computed order, after any `milestone order` ranks) or `milestone sink <name> <ids> --reason "<why>"` (below it), and `milestone lift <name> <ids>` removes either; an override stays through every re-rank until lifted. Pins extend the milestone's `order`, sinks are its `sunk` list, and each reason is in its `reasons` map by item id. Each `queue` item carries `unblocks:number`, `effort:number` and `why:string`, and text `queue` prints them under the item.
`resume` on the coordinator seat includes `rigor: {undrafted: [...]}`, naming each repeated cause that has no live or approved proved draft. Each entry retains the ordinary Rigor cause key, item evidence and commits. The text resume names the proof-bearing `pullboard rigor draft` command. Declined repeats stay quiet until a new item repeats them. `needsYou` may contain an individual `kind: "rigor-draft"` call with `cause`, `evidence`, `proof`, a qualified spec or doctrine `target`, and `what: "Approve or Decline"`. An ordinary draft remains in the existing aggregate count; a Rigor draft is not counted twice. These fields add no person permission: the existing person-only approval and decline channels still apply.
diff --cc docs/formats.md
index 0f1288b4,5b52c72f..6d4c6695
--- a/docs/formats.md
+++ b/docs/formats.md
@@@ -577,8 -579,6 +579,8 @@@ The engine-68 `recordSpecApprovalBaseli
`order` opts into next ordering: a builder’s own send-back, scarce review eligibility, release, downstream demand, signed-bar readiness, then coordinator rank. The readiness tier stays inert until the signed-readiness predicate is available (#1110); it never guesses a sign-off from prose. The other inputs retain their separate meanings; `reviewsFirst` selects review versus build and does not turn ordering on. Takeover and landing behavior are separate changes. The move carries `{agentId,key,value,reason,window}`; its native `line_setting` event carries `{key,value,reason,window}` with the board's actor and time outside that detail. Latest values live under `board_meta` keys `line_setting:<name>`, and ordered engine replay updates them and appends the same evidence. The unassigned `LINE_SETTINGS_ENGINE` leaf receives its permanent number at landing. Older engine records cannot request this new operation. Range, unknown-key, missing-reason and invalid-window refusals have named codes. The existing settings API reports each input as `scope: "board"`, key `line.<name>`, with off as its default and the board SQLite file as its source; it does not expose reason text or evidence payloads through that inventory.
- The critical-path engine, numbered at landing, orders ready build and review offers within each focus/release group by the longest remaining dependency path. Each unfinished item counts as one unit; verified and withdrawn work contributes none. This is the unit-duration Hu ordering, not a claim of measured completion-time estimates. Equal paths prefer fewer overlaps with live claimed, submitted or accepted-not-landed files, then retain existing rank, route, recent-file and age ties. An overlap never makes ready work unavailable. The opt-in own-send-back priority remains ahead of release ordering outside the configured focus; within the focus, longest path leads. Queue display and next share this rule; dependency, hold, route and reviewer-authority guards remain in force. Earlier engine records retain their original ordering and hard file-collision policy.
++The critical-path engine, numbered at landing, adds a longest-remaining-path tie-break inside the primary self-ordering policy (#1017). That policy retains release/focus groups, coordinator pins and sinks, route availability, quick-win interleaving and (unblocks + 1) / effort scores. Only equal primary scores use the remaining unit-item dependency path before recent-file and age ties. Verified and withdrawn work contributes no remaining path. Build offers and queue availability preserve the hard file-collision skip (#1114), even when the colliding item is the only otherwise-ready work. Review offers retain their versioned critical-chain preference and all reviewer-authority guards. Opt-in own-send-back priority and historical engine ordering remain in force. This is a unit-duration ordering, not a measured completion-time forecast. This precedence follows coordinator ruling 29931 and the sharpened #1210 criterion.
+
With `collisionFreeBatch` on, landing selection previews each reviewed commit against the immutable trunk and reads the resulting Git changed paths, including both rename paths. Overlapping later verdicts wait without reopening; disjoint items still join the current batch. Deferred items keep their recorded place ahead of newer acceptances, even after merge-only re-acceptance. This priority applies only while the setting is on and the item remains accepted and unlanded with the identical submitted commit and frozen digest; new source or a new bar loses that old priority. Once the first batch lands, each deferred item receives one item-addressed reviewer notice in the same atomic landed transition. Existing verdict freshness is unchanged: if main touched the deferred review, its reviewer merges the new trunk and records a merge-only re-accept without a builder cycle or reopening. The default off path keeps existing composition. The control has its own replay-engine boundary; it does not infer paths from briefs.
Landing queue grants, first queue entries and releases are shared ordered transitions. New landing-local-heartbeat engine moves leave renewal and repeated-poll events out of history; old engine receipts keep their recorded meaning. `local:landing-lease:<token>` board metadata binds a physical board id, token/generation, process, branch and coordinator lineage to its local deadline. It is excluded from exports, imports and semantic digests and is retained only on the receiving physical board during a same-board relay snapshot restore. A linked foreign holder has no clock-based expiry: release or coordinator takeover fences it; local heartbeat deadlines never authorize another machine to merge.
diff --cc src/board.js
index 8c85ddae,351e5ac5..ce7c3705
--- a/src/board.js
+++ b/src/board.js
@@@ -1,8 -1,4 +1,9 @@@
import { requireFactKind } from './item-notes.js';
+import {
+ criticalPathEnabled,
+ criticalPathOrder,
++ remainingPaths,
+} from './critical-path-order.js';
import { activityNewsFlag } from './activity-news.js';
import { migrateEventLogVersion } from './board-event-log-migrate.js';
import {
@@@ -1888,38 -1887,17 +1893,23 @@@ function postRigorNotices(board, trigge
}
- /** Explicit item ranks belong to the same first unfinished milestone as its priority [N2,B13]. */
- function milestoneRanks(board, priority) {
- if ((board.executionEngineVersion ?? ENGINE_VERSION) < MILESTONE_RANK_ENGINE) return () => 0;
- const ranks = new Map();
- for (const [index, milestone] of milestones(board).entries()) {
- for (const [rank, id] of (milestone.order ?? []).entries()) {
- if (milestone.items.includes(id) && priority({ item_id: id }) === index && !ranks.has(id)) ranks.set(id, rank);
- }
- }
- return entry => ranks.get(entry.item_id) ?? Number.MAX_SAFE_INTEGER;
- }
-
- /** Share focus/release, remaining path and soft overlap ordering across build offers and queue display. */
- export function buildOrder(board, { warm = [], agentId, readiness = barReadyForOrder, releasedClaims = [] } = {}) {
- const milestonePriority = milestonePriorities(board);
-/** Make the shared build-queue comparator once: milestone, explicit rank, then the self-ordered queue (#1017; older engines: route, recent files, oldest). */
-export function buildOrder(board, { warm = [], agentId, readiness = barReadyForOrder, tierFirst = false, priority } = {}) {
++/** Share milestone policy, primary computed order and equal-score path ties across queue and health. */
++export function buildOrder(board, { warm = [], agentId, readiness = barReadyForOrder, releasedClaims = [], tierFirst = false, priority } = {}) {
+ const milestonePriority = priority ?? milestonePriorities(board);
+ const items = listItems(board, { all: true });
const rank = milestoneRanks(board, milestonePriority);
const recent = new Set(warm);
-- const shared = (entry) => itemFiles(entry).filter((path) => recent.has(path)).length;
- const fallback = (first, second) => milestonePriority(first) - milestonePriority(second)
- || rank(first) - rank(second)
- || ROUTES.indexOf(second.item_route) - ROUTES.indexOf(first.item_route)
- || shared(second) - shared(first) || first.item_id - second.item_id;
- const previous = lineOrderEnabled(board) ? lineBuildOrder({ agentId, release: milestonePriority, rank, items, ready: item => readiness(board, item), fallback }) : fallback;
- const fallback = workOrderCompare(board, { priority: milestonePriority, rank, shared, tierFirst }) ?? ((first, second) => milestonePriority(first) - milestonePriority(second)
++ const shared = entry => itemFiles(entry).filter(path => recent.has(path)).length;
+ const focus = milestoneFocus(board);
+ const group = item => focus?.ids.has(item.item_id) ? -1 : milestonePriority(item);
- if (!criticalPathEnabled(board)) return focusOrder(board, previous);
- const paths = criticalPathOrder({ items, group, fallback: previous, releasedClaims });
- const returnHome = lineOrderEnabled(board);
- const returning = item => returnHome && !focus?.ids.has(item.item_id)
- && item.item_verdict === 'REJECT' && item.item_built_by === agentId;
- return focusOrder(board, (first, second) => Number(returning(second)) - Number(returning(first)) || paths(first, second));
++ const paths = criticalPathEnabled(board) ? remainingPaths(items, group) : new Map();
++ const tieBreak = (first, second) => (paths.get(second.item_id) ?? 0) - (paths.get(first.item_id) ?? 0);
++ const fallback = workOrderCompare(board, { priority: milestonePriority, rank, shared, tierFirst, tieBreak }) ?? ((first, second) => milestonePriority(first) - milestonePriority(second)
+ || rank(first) - rank(second)
+ || ROUTES.indexOf(second.item_route) - ROUTES.indexOf(first.item_route)
+ || shared(second) - shared(first) || first.item_id - second.item_id);
- return focusOrder(board, lineOrderEnabled(board) ? lineBuildOrder({ agentId, release: milestonePriority, rank, items: listItems(board, { all: true }), ready: item => readiness(board, item), fallback }) : fallback);
++ return focusOrder(board, lineOrderEnabled(board)
++ ? lineBuildOrder({ agentId, release: milestonePriority, rank, items, ready: item => readiness(board, item), fallback }) : fallback);
}
/**
@@@ -2032,9 -2006,8 +2022,9 @@@ export function nextFor(board, { agentI
const reserved = firstRefusalReason(board, entry.item_id, agentId);
if (reserved) { reasons.push(reserved); continue; }
const collisions = itemFileCollisions(entry, inFlight);
- if (collisions.length && !criticalPathEnabled(board)) { reasons.push(...collisions); continue; }
+ if (collisions.length) { reasons.push(...collisions); continue; }
- if (!waiting.length) return { item: entry, reasons: focusReasons(board, entry, reasons), shared };
+ if (!waiting.length) return { item: entry, reasons: focusReasons(board, entry,
+ [...reasons, ...collisions.map(reason => reason.replace(' waits for ', ' overlaps with '))]), shared };
reasons.push(`#${entry.item_id} waits on ${waiting.map(waitingOn).join(', ')}`);
}
if (!mine.length && !reasons.length) reasons.push(idleReason(items, lane, routed));
diff --cc src/critical-path-engine.js
index 02138290,00000000..8d93a8f2
mode 100644,000000..100644
--- a/src/critical-path-engine.js
+++ b/src/critical-path-engine.js
@@@ -1,3 -1,0 +1,3 @@@
- /** Critical-chain ordering and soft overlaps acquire their replay boundary at landing [N2,H16]. */
++/** Critical-chain tie-breaking acquires its replay boundary at landing [N2,H16]. */
+import { unassignedEngine } from './engine-next.js';
+export const CRITICAL_PATH_ENGINE = unassignedEngine();
diff --cc src/queue.js
index 38df1962,c2e1ab34..d6261e47
--- a/src/queue.js
+++ b/src/queue.js
@@@ -47,8 -51,7 +51,8 @@@ function waitsOf(board, item, inFlight
.filter((before) => before && before.item_status !== 'verified')
.map((before) => `#${before.item_id} (${before.item_status})`);
const lane = laneHold(board, item.item_lane);
- const collisions = criticalPathEnabled(board) ? [] : itemFileCollisions(item, inFlight);
- return [...after, ...itemFileCollisions(item, inFlight), ...(item.item_hold_reason ? [`held: ${item.item_hold_reason}`] : []), ...(lane ? [`${item.item_lane} lane held: ${lane.hold_reason}`] : [])];
++ const collisions = itemFileCollisions(item, inFlight);
+ return [...after, ...collisions, ...(item.item_hold_reason ? [`held: ${item.item_hold_reason}`] : []), ...(lane ? [`${item.item_lane} lane held: ${lane.hold_reason}`] : [])];
}
/**
diff --cc src/work-order.js
index 00000000,0ee5882e..2b3a252a
mode 000000,100644..100644
--- a/src/work-order.js
+++ b/src/work-order.js
@@@ -1,0 -1,214 +1,214 @@@
+ /**
+ * The queue orders itself (#1017) [N22,B13]. Within each release, an item's unblock count (unfinished items that
+ * wait on it, directly or through others) and effort (its route: light 1, mid 2, strong 3) give a score of
+ * (unblocks + 1) / effort. Ready items that unblock others alternate with quick wins (light or mid, unblocking
+ * nothing) at the top; the rest of the ready work follows by score so effort levels stay mixed; every route with
+ * ready work gets an item near the top; blocked items follow in the order their blockers clear, and held items
+ * last. The coordinator's pins sit above that order and its sinks below it, each with its reason, until lifted.
+ *
+ * Pure reads over the board, so pullboard queue, next and health share one order. Recorded moves below
+ * WORK_ORDER_ENGINE keep their old milestone, rank, route and age order.
+ */
+ import {
+ ENGINE_VERSION,
+ MILESTONE_RANK_ENGINE,
+ } from './machine.js';
+ import { WORK_ORDER_ENGINE } from './work-order-engine.js';
+ import { milestones } from './board-read-auxiliary.js';
+ import { listItems } from './board-query.js';
+ import { ROUTES } from './route-escalation.js';
+
+ /** Effort per route: what one item of that route costs to build. */
+ export const EFFORT = Object.freeze({ light: 1, mid: 2, strong: 3 });
+
+ /** Explicit item ranks belong to the same first unfinished milestone as its priority [N2,B13]. */
+ export function milestoneRanks(board, priority) {
+ if ((board.executionEngineVersion ?? ENGINE_VERSION) < MILESTONE_RANK_ENGINE) return () => 0;
+ const ranks = new Map();
+ for (const [index, milestone] of milestones(board).entries()) {
+ for (const [rank, id] of (milestone.order ?? []).entries()) {
+ if (milestone.items.includes(id) && priority({ item_id: id }) === index && !ranks.has(id)) ranks.set(id, rank);
+ }
+ }
+ return entry => ranks.get(entry.item_id) ?? Number.MAX_SAFE_INTEGER;
+ }
+
+ /** True when this board's moves run at or above the self-ordering engine. */
+ export function workOrderActive(board) {
+ return (board.executionEngineVersion ?? ENGINE_VERSION) >= WORK_ORDER_ENGINE;
+ }
+
+ /** The item numbers an item waits on, as recorded. */
+ function afterIds(item) {
+ return item.item_after ? item.item_after.split(',').map(Number) : [];
+ }
+
+ /**
+ * The coordinator's overrides for each item in the first unfinished milestone that lists it: its pin reason or
+ * its sink reason. A pin with no reason is an older milestone order.
+ *
+ * @param {any} board
+ * @param {(entry: any) => number} priority
+ * @returns {{ sunk: Set<number>, reasons: Map<number, string> }}
+ */
+ export function milestoneOverrides(board, priority) {
+ const sunk = new Set();
+ const reasons = new Map();
+ for (const [index, milestone] of milestones(board).entries()) {
+ for (const id of milestone.sunk ?? []) if (priority({ item_id: id }) === index) sunk.add(id);
+ for (const [id, reason] of Object.entries(milestone.reasons ?? {})) if (priority({ item_id: Number(id) }) === index && !reasons.has(Number(id))) reasons.set(Number(id), reason);
+ }
+ return { sunk, reasons };
+ }
+
+ /**
+ * Each unfinished item's unblock count: the unfinished items that wait on it, directly or through others.
+ *
+ * @param {any[]} unfinished
+ * @returns {Map<number, number>}
+ */
+ export function unblockCounts(unfinished) {
+ const waiters = new Map();
+ for (const item of unfinished) for (const id of afterIds(item)) waiters.set(id, [...(waiters.get(id) ?? []), item.item_id]);
+ const counts = new Map();
+ for (const item of unfinished) {
+ const seen = new Set();
+ const stack = [...(waiters.get(item.item_id) ?? [])];
+ while (stack.length) {
+ const id = stack.pop();
+ if (seen.has(id) || id === item.item_id) continue;
+ seen.add(id);
+ stack.push(...(waiters.get(id) ?? []));
+ }
+ counts.set(item.item_id, seen.size);
+ }
+ return counts;
+ }
+
+ /**
+ * How many blockers deep an item sits: 0 when everything it waits on is verified, as next requires. A withdrawn
+ * blocker never clears, so it counts as one level. A cycle counts once.
+ *
+ * @param {Map<number, any>} open unfinished items by id
+ * @param {Set<number>} withdrawn
+ * @returns {(item: any) => number}
+ */
+ function blockerDepth(open, withdrawn) {
+ const depths = new Map();
+ const depth = (item, visiting = new Set()) => {
+ if (depths.has(item.item_id)) return depths.get(item.item_id);
+ if (visiting.has(item.item_id)) return 0;
+ visiting.add(item.item_id);
+ const blockers = afterIds(item).map((id) => open.get(id)).filter(Boolean);
+ const never = afterIds(item).some((id) => withdrawn.has(id));
+ const value = blockers.length || never ? 1 + Math.max(0, ...blockers.map((blocker) => depth(blocker, visiting))) : 0;
+ depths.set(item.item_id, value);
+ return value;
+ };
+ return (item) => depth(item);
+ }
+
+ /** Interleave unblockers and quick wins while both last; the rest of the ready work follows by score. */
+ function readySequence(ready, byScore) {
+ const unblockers = ready.filter((entry) => entry.unblocks > 0).sort(byScore);
+ const quick = ready.filter((entry) => entry.unblocks === 0 && entry.item.item_route !== 'strong').sort(byScore);
+ const zipped = [];
+ const pairs = Math.min(unblockers.length, quick.length);
+ for (let index = 0; index < pairs; index++) zipped.push(unblockers[index], quick[index]);
+ const rest = ready.filter((entry) => !zipped.includes(entry)).sort(byScore);
+ return routesNearTop([...zipped, ...rest]);
+ }
+
+ /** Lift each route's best ready item into the top, so no route with ready work waits behind the others. */
+ function routesNearTop(sequence) {
+ const routes = [...new Set(sequence.map((entry) => entry.item.item_route))];
+ const head = sequence.slice(0, routes.length);
+ for (const route of routes) {
+ if (head.some((entry) => entry.item.item_route === route)) continue;
+ head.push(sequence.find((entry) => entry.item.item_route === route));
+ }
+ return [...head, ...sequence.filter((entry) => !head.includes(entry))];
+ }
+
+ /** Why an item sits where it does, in the queue's words. */
+ function whyOf(entry) {
+ if (entry.kind === 'held') return 'held by the coordinator';
+ if (entry.kind === 'blocked') return `blocked: ${entry.depth === 1 ? 'rises when its blocker lands' : `${entry.depth} blockers deep`}`;
+ if (entry.unblocks > 0) return `ready and unblocks ${entry.unblocks}`;
+ if (entry.item.item_route !== 'strong') return 'ready quick win';
+ return 'ready work by score';
+ }
+
+ /**
+ * The computed order of every unfinished item, release by release.
+ *
+ * @param {any} board
- * @param {{ priority: (entry: any) => number, shared?: (entry: any) => number }} options
++ * @param {{ priority: (entry: any) => number, shared?: (entry: any) => number, tieBreak?: (first: any, second: any) => number }} options
+ * @returns {Map<number, { position: number, unblocks: number, effort: number, score: number, why: string }>}
+ */
-export function computedOrder(board, { priority, shared = () => 0 }) {
++export function computedOrder(board, { priority, shared = () => 0, tieBreak = () => 0 }) {
+ // Only unfinished items and withdrawn ids matter, so a large board's finished history is never read.
+ const unfinished = listItems(board);
+ const withdrawn = new Set(board.db.prepare("SELECT item_id FROM item WHERE item_status = 'withdrawn'").all().map((row) => row.item_id));
+ const counts = unblockCounts(unfinished);
+ const depthOf = blockerDepth(new Map(unfinished.map((item) => [item.item_id, item])), withdrawn);
+ const entries = unfinished.map((item) => {
+ const unblocks = counts.get(item.item_id) ?? 0;
+ const effort = EFFORT[item.item_route] ?? EFFORT.strong;
+ const depth = depthOf(item);
+ return { item, unblocks, effort, score: (unblocks + 1) / effort, depth,
+ kind: item.item_hold_reason ? 'held' : depth ? 'blocked' : 'ready', release: priority(item) };
+ });
- const byScore = (first, second) => second.score - first.score || shared(second.item) - shared(first.item) || first.item.item_id - second.item.item_id;
++ const byScore = (first, second) => second.score - first.score || tieBreak(first.item, second.item) || shared(second.item) - shared(first.item) || first.item.item_id - second.item.item_id;
+ const order = new Map();
+ for (const release of [...new Set(entries.map((entry) => entry.release))].sort((a, b) => a - b)) {
+ const group = entries.filter((entry) => entry.release === release);
+ const blocked = group.filter((entry) => entry.kind === 'blocked').sort((first, second) => first.depth - second.depth || byScore(first, second));
+ const held = group.filter((entry) => entry.kind === 'held').sort(byScore);
+ [...readySequence(group.filter((entry) => entry.kind === 'ready'), byScore), ...blocked, ...held].forEach((entry, position) => {
+ order.set(entry.item.item_id, { position, unblocks: entry.unblocks, effort: entry.effort, score: entry.score, why: whyOf(entry) });
+ });
+ }
+ return order;
+ }
+
+ /**
+ * The self-ordering comparator for buildOrder: release, coordinator pin, coordinator sink, then the computed
+ * order. With `tierFirst`, next's own route comes before the computed order, so an agent claims its tier first
+ * (B13). Null below WORK_ORDER_ENGINE, where buildOrder keeps its recorded order.
+ *
+ * @param {any} board
- * @param {{ priority: (entry: any) => number, rank: (entry: any) => number, shared: (entry: any) => number, tierFirst?: boolean }} options
++ * @param {{ priority: (entry: any) => number, rank: (entry: any) => number, shared: (entry: any) => number, tierFirst?: boolean, tieBreak?: (first: any, second: any) => number }} options
+ * @returns {((first: any, second: any) => number) | null}
+ */
-export function workOrderCompare(board, { priority, rank, shared, tierFirst = false }) {
++export function workOrderCompare(board, { priority, rank, shared, tierFirst = false, tieBreak = () => 0 }) {
+ if (!workOrderActive(board)) return null;
- const order = computedOrder(board, { priority, shared });
++ const order = computedOrder(board, { priority, shared, tieBreak });
+ const { sunk } = milestoneOverrides(board, priority);
+ const position = (entry) => order.get(entry.item_id)?.position ?? Number.MAX_SAFE_INTEGER;
+ return (first, second) => priority(first) - priority(second)
+ || rank(first) - rank(second)
+ || Number(sunk.has(first.item_id)) - Number(sunk.has(second.item_id))
+ || (tierFirst ? ROUTES.indexOf(second.item_route) - ROUTES.indexOf(first.item_route) : 0)
+ || position(first) - position(second)
+ || first.item_id - second.item_id;
+ }
+
+ /**
+ * Each item's place in the queue as pullable work explains it: unblock count, effort and why it sits there.
+ *
+ * @param {any} board
+ * @param {{ priority: (entry: any) => number, rank: (entry: any) => number }} options
+ * @returns {(item: any) => { unblocks: number, effort: number, why: string }}
+ */
+ export function queueReasons(board, { priority, rank }) {
+ const order = computedOrder(board, { priority });
+ const { sunk, reasons } = milestoneOverrides(board, priority);
+ return (item) => {
+ const computed = order.get(item.item_id) ?? { unblocks: 0, effort: EFFORT[item.item_route] ?? EFFORT.strong, why: 'finished' };
+ const reason = reasons.get(item.item_id);
+ const why = rank(item) !== Number.MAX_SAFE_INTEGER ? `pinned by the coordinator: ${reason ?? 'milestone order'}`
+ : sunk.has(item.item_id) ? `sunk by the coordinator: ${reason ?? 'no reason recorded'}` : computed.why;
+ return { unblocks: computed.unblocks, effort: computed.effort, why };
+ };
+ }