spur-board 0.130.0 → 0.132.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.
@@ -1,5 +1,5 @@
1
- import { bt as plainHttpAllowed, d as buildCatalogSnapshot, p as OPERATIONS, vt as configSchema } from "./chunk-CgQL6u77.mjs";
2
- import { o as CliError, t as fetchCatalogVersion } from "./chunk-2vFOidpZ.mjs";
1
+ import { bt as plainHttpAllowed, d as buildCatalogSnapshot, p as OPERATIONS, vt as configSchema } from "./chunk-CY_rWPWy.mjs";
2
+ import { o as CliError, t as fetchCatalogVersion } from "./chunk-DfehZM2s.mjs";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
@@ -3054,6 +3054,7 @@ const defaultBranchViewSchema = z.strictObject({
3054
3054
  const sourceViewSchema = z.strictObject({
3055
3055
  pointsLastHour: z.int().nonnegative().optional().describe("Reported source points consumed during the preceding hour."),
3056
3056
  source: z.string().min(1).describe("Adapter source identifier."),
3057
+ project: z.string().min(1).nullable().describe("Board project whose tracker or repository this source polls; null for the shared spur source."),
3057
3058
  observedAt: z.iso.datetime().nullable().describe("Time of the latest observation, if any."),
3058
3059
  lastCompleteAt: z.iso.datetime().nullable().describe("Time of the latest complete observation."),
3059
3060
  blindReason: z.enum([
@@ -3068,6 +3069,7 @@ const sourceViewSchema = z.strictObject({
3068
3069
  resetAt: z.iso.datetime().describe("When the source said it restores the full budget.")
3069
3070
  }).nullable().describe("Request budget from the last poll of this source that reported one, or null when none did."),
3070
3071
  stale: z.boolean().describe("Whether facts from this source exceed their freshness threshold."),
3072
+ waitsForBudget: z.boolean().describe("Whether the daemon's adapter runner has put off this source's next regular poll for a rate limit: the last regular poll in this daemon run either reported a budget under github.reserveRemaining (GitHub sources, complete or not) or failed as throttled, with or without a retry time (any source), or failed in any other way while the last budget a poll of this run reported, an on-demand refresh included, is under github.reserveRemaining with a future reset (this case also ends at that reset), and the paused poll has not started yet. Held in memory, so false after a restart until a poll pauses again; a stored budget or an on-demand refresh never sets it."),
3071
3073
  healthySince: z.iso.datetime().nullable().describe("When this source became usable (not blind) in this daemon run: its first non-blind observation since daemon start or since it was last blind. Stale, warming-up or budget-wait spells that did not make it blind do not move it. Null while blind or before that observation. Resets when the daemon restarts; compare with daemon.startedAt."),
3072
3074
  warmingUp: z.boolean().describe("Whether this source needs a complete poll in this daemon run."),
3073
3075
  defaultBranch: defaultBranchViewSchema.nullable().optional().describe("GitHub pull request sources only: the default-branch colour, red when the latest check run of a push-triggered workflow finished without success (failed, cancelled, timed out) or a commit status failed (scheduled and other runs ignored, branch protection not read); null until a poll reads it.")
@@ -3267,16 +3269,16 @@ const serviceSchema = z.strictObject({
3267
3269
  reason: z.string().nullable().describe("Why the service is not healthy, from its first worst source for github, jira and spur; null when healthy.")
3268
3270
  }).describe("Health of one service.");
3269
3271
  const statusInputSchema = z.strictObject({
3270
- project: project$1,
3272
+ project: z.string().min(1).max(256).optional().describe("Project to limit the answer to, except sources and services, which always cover every project the caller may see; absent means every project the caller may see."),
3271
3273
  detail: z.boolean().optional().describe("Include full ticket, pull request and session facts; absent means compact rows.")
3272
3274
  });
3273
3275
  const statusOutputSchema = z.strictObject({
3274
3276
  items: z.array(statusItemSchema).describe("Actionable items in priority order."),
3275
- warmingUp: z.boolean().describe("Whether required sources still need a complete poll."),
3277
+ warmingUp: z.boolean().describe("Whether a source of the requested projects or spur still needs a complete poll."),
3276
3278
  spurUnavailable: z.string().nullable().describe("One combined Spur availability line, or null when available."),
3277
3279
  hostLoad: z.string().nullable().describe("Host-load episode line, or null when absent."),
3278
3280
  host: hostSchema,
3279
- services: z.array(serviceSchema).describe("One health row per service: daemon, each chat gateway, then github, spur and jira when sources lists one. Daemon and gateway rows are board-wide; source services roll up only the sources listed."),
3281
+ services: z.array(serviceSchema).describe("One health row per service: daemon, each chat gateway, then github, spur and jira when sources lists one. Daemon and gateway rows are board-wide; source services roll up the sources listed, which cover every project the caller may see whatever project says."),
3280
3282
  transport: z.array(z.strictObject({
3281
3283
  gateway: z.string().min(1).describe("Chat gateway kind."),
3282
3284
  state: z.enum(["up", "down"]).describe("down while delivery to any space of the gateway is suspended."),
@@ -3284,7 +3286,7 @@ const statusOutputSchema = z.strictObject({
3284
3286
  reason: z.string().nullable().describe("Reason of the earliest outage, or null when up."),
3285
3287
  spaces: z.array(z.enum(SPACE_IDS)).describe("Spaces whose delivery is suspended.")
3286
3288
  }).describe("Transport health of one gateway.")).describe("Transport health of each chat gateway."),
3287
- sources: z.array(sourceViewSchema).describe("Freshness and availability of each source."),
3289
+ sources: z.array(sourceViewSchema).describe("Freshness and availability of each source of every project the caller may see, whatever project says, with spur first."),
3288
3290
  tasks: z.array(statusTaskSchema).describe("Tasks with state, turn, PR summary arrays and navigation; full facts with detail."),
3289
3291
  columnGroups: z.array(z.strictObject({
3290
3292
  id: z.enum(COLUMN_GROUPS).describe("Column group."),
@@ -1,4 +1,4 @@
1
- import { _ as renderJsonError, at as errorContextSchema, c as tokenRequestStatusSchema, ct as successEnvelopeSchema, o as tokenRequestResultSchema, ot as errorEnvelopeSchema, rt as ERRORS } from "./chunk-CgQL6u77.mjs";
1
+ import { _ as renderJsonError, at as errorContextSchema, c as tokenRequestStatusSchema, ct as successEnvelopeSchema, o as tokenRequestResultSchema, ot as errorEnvelopeSchema, rt as ERRORS } from "./chunk-CY_rWPWy.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
package/dist/cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { D as sortSkillFiles, Ot as SLACK_BOT_SCOPES, Q as actorIdSchema, St as resolveWebOrigin, T as skillReloadFileSchema, a as requestHashOf, ct as successEnvelopeSchema, f as roleCanUseOperation, p as OPERATIONS, pt as DEFAULT_STAND_PORT_RANGE, r as remoteDoctorReportSchema, rt as ERRORS, u as SYSTEMD_SERVICE_SETTINGS, vt as configSchema, xt as requiredSecretKeys } from "./chunk-CgQL6u77.mjs";
1
+ import { D as sortSkillFiles, Ot as SLACK_BOT_SCOPES, Q as actorIdSchema, St as resolveWebOrigin, T as skillReloadFileSchema, a as requestHashOf, ct as successEnvelopeSchema, f as roleCanUseOperation, p as OPERATIONS, pt as DEFAULT_STAND_PORT_RANGE, r as remoteDoctorReportSchema, rt as ERRORS, u as SYSTEMD_SERVICE_SETTINGS, vt as configSchema, xt as requiredSecretKeys } from "./chunk-CY_rWPWy.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-Bzb7aI8R.mjs";
3
- import { a as requestTokenEnrollment, c as renderCliError, i as requestSkillReload, l as escapeTerminalControls, n as fetchTokenStatus, o as CliError, r as requestOperation, s as errorExitCode } from "./chunk-2vFOidpZ.mjs";
4
- import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./chunk-B9WekLbU.mjs";
3
+ import { a as requestTokenEnrollment, c as renderCliError, i as requestSkillReload, l as escapeTerminalControls, n as fetchTokenStatus, o as CliError, r as requestOperation, s as errorExitCode } from "./chunk-DfehZM2s.mjs";
4
+ import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./chunk-BUWlIiQd.mjs";
5
5
  import { createHash, randomBytes, randomUUID } from "node:crypto";
6
6
  import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
7
7
  import { homedir, hostname, tmpdir, userInfo } from "node:os";
package/dist/client.mjs CHANGED
@@ -1 +1 @@
1
- export { t as fetchCatalogVersion, n as fetchTokenStatus, r as requestOperation, i as requestSkillReload, a as requestTokenEnrollment } from "./chunk-2vFOidpZ.mjs";
1
+ export { t as fetchCatalogVersion, n as fetchTokenStatus, r as requestOperation, i as requestSkillReload, a as requestTokenEnrollment } from "./chunk-DfehZM2s.mjs";
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as encodeActorId, A as eventPayloadSchemas, At as TODO_GROUP_COLUMN_IDS, B as REVIEW_STATES, C as messageRefSchema, Ct as COLUMNS, D as sortSkillFiles, Dt as ITEM_KINDS, E as skillReloadFilesSchema, Et as DISPATCHER_MODES, 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, Mt as isTodoGroupColumn, N as defaultBranchFactSchema, O as EVENT_KINDS, Ot as SLACK_BOT_SCOPES, P as entityRefSchema, Q as actorIdSchema, R as trackerSourceId, S as interactionRefSchema, St as resolveWebOrigin, Tt as COLUMN_IDS, 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 configBindings, a as requestHashOf, b as conversationRefSchema, bt as plainHttpAllowed, 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 columnTurnTimings, h as turnHandedSchema, ht as boardWideSpurProject, i as TOKEN_REQUEST_LIMITS, it as err, j as AdapterError, jt as VIAS, k as GATE_REASONS, kt as TASK_HOLDS, 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 configSchema, w as userIdSchema, wt as COLUMN_GROUPS, x as inboundEventSchema, xt as requiredSecretKeys, y as SPACE_IDS, yt as defaultAddressee, z as PR_STATES } from "./chunk-CgQL6u77.mjs";
1
+ import { $ as encodeActorId, A as eventPayloadSchemas, At as TODO_GROUP_COLUMN_IDS, B as REVIEW_STATES, C as messageRefSchema, Ct as COLUMNS, D as sortSkillFiles, Dt as ITEM_KINDS, E as skillReloadFilesSchema, Et as DISPATCHER_MODES, 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, Mt as isTodoGroupColumn, N as defaultBranchFactSchema, O as EVENT_KINDS, Ot as SLACK_BOT_SCOPES, P as entityRefSchema, Q as actorIdSchema, R as trackerSourceId, S as interactionRefSchema, St as resolveWebOrigin, Tt as COLUMN_IDS, 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 configBindings, a as requestHashOf, b as conversationRefSchema, bt as plainHttpAllowed, 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 columnTurnTimings, h as turnHandedSchema, ht as boardWideSpurProject, i as TOKEN_REQUEST_LIMITS, it as err, j as AdapterError, jt as VIAS, k as GATE_REASONS, kt as TASK_HOLDS, 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 configSchema, w as userIdSchema, wt as COLUMN_GROUPS, x as inboundEventSchema, xt as requiredSecretKeys, y as SPACE_IDS, yt as defaultAddressee, z as PR_STATES } from "./chunk-CY_rWPWy.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-Bzb7aI8R.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { createHash, randomUUID } from "node:crypto";
@@ -8298,6 +8298,15 @@ async function turnReturn(db, turn) {
8298
8298
  };
8299
8299
  }
8300
8300
  }
8301
+ /**
8302
+ * The open `code` block of the return that opened `turn`'s visit while it is still addressed to
8303
+ * the turn's role, else undefined. Taking the turn reads it; the turn's submit closes it.
8304
+ */
8305
+ async function openReturnBlock(db, turn) {
8306
+ const returned = await turnReturn(db, turn);
8307
+ if (returned === void 0) return void 0;
8308
+ return db.selectFrom("block").selectAll().where("id", "=", Number(returned.block.slice(1))).where("task_id", "=", turn.task_id).where("state", "=", "open").where("type", "=", "code").where("addressee_role", "=", turn.role).executeTakeFirst();
8309
+ }
8301
8310
  function taskView(task) {
8302
8311
  return {
8303
8312
  key: task.key,
@@ -12301,6 +12310,15 @@ async function closeBlockIfOpen(trx, blockId, ctx, outcome, outcomeReason) {
12301
12310
  if (block === void 0) return;
12302
12311
  await closeOpenBlock(trx, await blockSubject(trx, block), block, ctx, outcome, outcomeReason);
12303
12312
  }
12313
+ /**
12314
+ * Closes the open `code` block of the return that opened `turn`'s visit (`openReturnBlock`) as
12315
+ * done at `sha`: the turn's submit, once confirmed, answered it. A pending submit waits, so a
12316
+ * voided one leaves the block to the next submit.
12317
+ */
12318
+ async function answerReturn(trx, task, turn, ctx, sha) {
12319
+ const block = await openReturnBlock(trx, turn);
12320
+ if (block !== void 0) await closeOpenBlock(trx, taskSubject(task), block, ctx, "done", sha);
12321
+ }
12304
12322
  /** The thread messages that close an operator conversation, compared after trimming. */
12305
12323
  const CLOSE_COMMANDS = /* @__PURE__ */ new Set([
12306
12324
  "close",
@@ -12677,14 +12695,29 @@ function createBlockMutations(config) {
12677
12695
  if (unread !== void 0) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
12678
12696
  throw new CommandError("not_found", "No unread block notification.");
12679
12697
  }
12680
- /** Takes a turn; a turn the caller took or was rung for before it closed is already handled. */
12698
+ /**
12699
+ * Takes a turn; a turn the caller took or was rung for before it closed is already handled.
12700
+ * Taking the Dev turn of a return also reads the return's open `code` block
12701
+ * (`openReturnBlock`), so its rings stop and it never raises `worker_not_reading`.
12702
+ */
12681
12703
  async function ackTurn(trx, id, ctx) {
12704
+ const at = new Date(ctx.at);
12682
12705
  if (await takeTurn(trx, {
12683
12706
  turnId: id,
12684
12707
  actor: ctx.actor,
12685
- at: new Date(ctx.at),
12708
+ at,
12686
12709
  config
12687
- })) return "acked";
12710
+ })) {
12711
+ const block = await openReturnBlock(trx, await trx.selectFrom("turn").selectAll().where("id", "=", id).executeTakeFirstOrThrow());
12712
+ if (block !== void 0) await acknowledgeNotification(trx, {
12713
+ blockId: block.id,
12714
+ actor: ctx.actor,
12715
+ at,
12716
+ config,
12717
+ takeover: true
12718
+ });
12719
+ return "acked";
12720
+ }
12688
12721
  const turn = await trx.selectFrom("turn").selectAll().where("id", "=", id).executeTakeFirst();
12689
12722
  if (turn?.acked_by === ctx.actor) return "handled";
12690
12723
  if (turn !== void 0 && turn.closed_at !== null) {
@@ -15432,13 +15465,30 @@ async function supersedeSubmit(trx, task, pending, at) {
15432
15465
  supersededByMerge: pending.head
15433
15466
  });
15434
15467
  }
15435
- /** Counts a pending submit a poll confirmed: from its receipt time, on the linked PR. */
15436
- async function confirmSubmit(trx, pending) {
15437
- await trx.updateTable("submission").set((eb) => ({
15468
+ /**
15469
+ * Counts a pending submit a poll confirmed: from its receipt time, on the linked PR. The turn it
15470
+ * closed answered its visit's return, so the return's code block closes at the confirmed head.
15471
+ */
15472
+ async function confirmSubmit(trx, task, pending, at) {
15473
+ const row = await trx.updateTable("submission").set((eb) => ({
15438
15474
  pending_until: null,
15439
15475
  pr_repo: eb.fn.coalesce("pr_repo", eb.val(pending.pr.repo)),
15440
15476
  pr_number: eb.fn.coalesce("pr_number", eb.val(pending.pr.number))
15441
- })).where("id", "=", pending.id).execute();
15477
+ })).where("id", "=", pending.id).returning([
15478
+ "column",
15479
+ "epoch",
15480
+ "author"
15481
+ ]).executeTakeFirstOrThrow();
15482
+ const turn = await trx.selectFrom("turn").select([
15483
+ "task_id",
15484
+ "column",
15485
+ "epoch",
15486
+ "role"
15487
+ ]).where("task_id", "=", task.id).where("column", "=", row.column).where("epoch", "=", row.epoch).where("acked_by", "=", row.author).where("closed_reason", "=", "submitted").orderBy("id", "desc").executeTakeFirst();
15488
+ if (turn !== void 0) await answerReturn(trx, task, turn, {
15489
+ actor: row.author,
15490
+ at: at.toISOString()
15491
+ }, pending.sha);
15442
15492
  }
15443
15493
  /**
15444
15494
  * Re-evaluates the gates of each task and applies the cascade: in `on` mode it moves the column
@@ -15458,7 +15508,7 @@ async function dispatchTasks(trx, taskIds, ctx) {
15458
15508
  if (read === null) continue;
15459
15509
  if (read.pending?.state === "superseded") await supersedeSubmit(trx, task, read.pending, ctx.at);
15460
15510
  if (read.ticketUnconfirmed) continue;
15461
- if (read.pending?.state === "confirmed") await confirmSubmit(trx, read.pending);
15511
+ if (read.pending?.state === "confirmed") await confirmSubmit(trx, task, read.pending, ctx.at);
15462
15512
  const result = dispatch(read.input);
15463
15513
  if (mode === "shadow") await applyShadow(trx, task, project, result, ctx.at);
15464
15514
  else await applyOn(trx, task, read, result, ctx);
@@ -16512,7 +16562,7 @@ function pickTime(values, pick) {
16512
16562
  return chosen;
16513
16563
  }
16514
16564
  /** One source's health: failing when blind, degraded while not fully usable, else healthy. */
16515
- function sourceHealth(source, config, now) {
16565
+ function sourceHealth(source) {
16516
16566
  if (source.blindReason !== null) {
16517
16567
  const message = source.message === null ? "" : `: ${source.message}`;
16518
16568
  return {
@@ -16524,11 +16574,10 @@ function sourceHealth(source, config, now) {
16524
16574
  state: "degraded",
16525
16575
  reason
16526
16576
  });
16577
+ if (source.waitsForBudget) return degraded(`${source.source} waits for its rate budget`);
16527
16578
  if (source.lastCompleteAt === null) return degraded(`${source.source} ${source.warmingUp ? "warming up" : "never completed"}`);
16528
16579
  if (source.stale) return degraded(`${source.source} stale`);
16529
16580
  if (source.warmingUp) return degraded(`${source.source} warming up`);
16530
- const { budget } = source;
16531
- if (source.source.startsWith("github") && budget !== null && budget.remaining < config.github.reserveRemaining && Date.parse(budget.resetAt) > now) return degraded(`${source.source} waits for its rate budget until ${budget.resetAt}`);
16532
16581
  return {
16533
16582
  state: "healthy",
16534
16583
  reason: null
@@ -16539,7 +16588,7 @@ function sourceHealth(source, config, now) {
16539
16588
  * rolled up from the given sources only.
16540
16589
  */
16541
16590
  function services(input) {
16542
- const { config, now, daemon } = input;
16591
+ const { now, daemon } = input;
16543
16592
  const lastTick = daemon.lastDispatchAt ?? daemon.startedAt;
16544
16593
  const stalled = now - Date.parse(lastTick) > DAEMON_STALL_MS;
16545
16594
  const rows = [{
@@ -16572,7 +16621,7 @@ function services(input) {
16572
16621
  ]) {
16573
16622
  const members = input.sources.filter((source) => SOURCE_SERVICES[source.source.split(":")[0] ?? ""] === service);
16574
16623
  if (members.length === 0) continue;
16575
- const worst = members.map((source) => sourceHealth(source, config, now)).reduce((a, b) => STATE_RANK[b.state] > STATE_RANK[a.state] ? b : a);
16624
+ const worst = members.map(sourceHealth).reduce((a, b) => STATE_RANK[b.state] > STATE_RANK[a.state] ? b : a);
16576
16625
  rows.push({
16577
16626
  service,
16578
16627
  state: worst.state,
@@ -16811,7 +16860,8 @@ async function getStatus(deps, options = {}) {
16811
16860
  const { project: projectId, visibleProjects, detail = false } = options;
16812
16861
  const includeBoardItems = options.includeBoardItems ?? visibleProjects === void 0;
16813
16862
  const operatorProjects = options.operatorProjects ?? /* @__PURE__ */ new Set();
16814
- const projects = projectId === void 0 ? config.projects.filter((project) => visibleProjects === void 0 || visibleProjects.has(project.id)) : config.projects.filter((project) => project.id === projectId && (visibleProjects === void 0 || visibleProjects.has(project.id)));
16863
+ const visible = config.projects.filter((project) => visibleProjects === void 0 || visibleProjects.has(project.id));
16864
+ const projects = projectId === void 0 ? visible : visible.filter((project) => project.id === projectId);
16815
16865
  if (projects.length === 0) throw new CommandError("not_found", "Check the project ID.");
16816
16866
  const projectIds = new Set(projects.map((project) => project.id));
16817
16867
  const rows = await store.db.selectFrom("task").selectAll().where("membership", "!=", "archived").execute();
@@ -16969,16 +17019,19 @@ async function getStatus(deps, options = {}) {
16969
17019
  health
16970
17020
  };
16971
17021
  });
16972
- const required = /* @__PURE__ */ new Set(["spur", ...projects.flatMap((project) => [trackerSourceId(project), ...project.repos.map((repo) => prSourceId(project.id, repo))])]);
17022
+ const sourceIds = (scope) => /* @__PURE__ */ new Set(["spur", ...scope.flatMap((project) => [trackerSourceId(project), ...project.repos.map((repo) => prSourceId(project.id, repo))])]);
17023
+ const required = sourceIds(projects);
17024
+ const boardSources = sourceIds(visible);
16973
17025
  const costs = await store.db.selectFrom("source_cost").select(["source", "points"]).where("at", ">", (/* @__PURE__ */ new Date(clock.now() - 36e5)).toISOString()).where("at", "<=", new Date(clock.now()).toISOString()).execute();
16974
17026
  const points = /* @__PURE__ */ new Map();
16975
17027
  for (const cost of costs) points.set(cost.source, (points.get(cost.source) ?? 0) + cost.points);
16976
- const sources = [...required].map((source) => {
17028
+ const sources = [...boardSources].map((source) => {
16977
17029
  const row = sourceById.get(source);
16978
17030
  const last = row?.last_complete_at ?? null;
16979
17031
  const blindReason = row?.blind_reason === "auth" || row?.blind_reason === "config" || row?.blind_reason === "stale" ? row.blind_reason : null;
16980
17032
  return {
16981
17033
  source,
17034
+ project: projectForSource(config, source)?.id ?? null,
16982
17035
  ...source.startsWith("github:") && {
16983
17036
  pointsLastHour: points.get(source) ?? 0,
16984
17037
  defaultBranch: parseDefaultBranch(row?.default_branch)
@@ -16992,6 +17045,7 @@ async function getStatus(deps, options = {}) {
16992
17045
  limit: row.budget_limit,
16993
17046
  resetAt: row.budget_reset_at
16994
17047
  } : null,
17048
+ waitsForBudget: deps.budgetWaits?.has(source) ?? false,
16995
17049
  stale: last === null || clock.now() - Date.parse(last) > config.thresholds.staleMultiplier * sourceInterval(config, source),
16996
17050
  healthySince: deps.healthySince?.get(source) ?? null,
16997
17051
  warmingUp: !completeSince.has(source)
@@ -17047,12 +17101,11 @@ async function getStatus(deps, options = {}) {
17047
17101
  });
17048
17102
  return {
17049
17103
  items,
17050
- warmingUp: sources.some((source) => source.warmingUp),
17104
+ warmingUp: sources.some((source) => required.has(source.source) && source.warmingUp),
17051
17105
  spurUnavailable: spur?.blind_reason === null || spur === void 0 ? null : `Spur unavailable: ${spur.blind_message ?? spur.blind_reason}`,
17052
17106
  hostLoad: host?.value !== void 0 && host.value !== "null" ? "Host under load" : null,
17053
17107
  host: deps.host ?? null,
17054
17108
  services: services({
17055
- config,
17056
17109
  now: clock.now(),
17057
17110
  daemon,
17058
17111
  transport,
@@ -18736,6 +18789,7 @@ function createTurnMutations(deps) {
18736
18789
  column: turn.column,
18737
18790
  epoch: turn.epoch
18738
18791
  }, ctx, completeSince, config.projects.find((entry) => entry.id === task.project)?.dispatcher.submitConfirmMs);
18792
+ if (confirmed !== "pending") await answerReturn(trx, task, turn, ctx, input.sha);
18739
18793
  await closeTurns(trx, {
18740
18794
  taskId: task.id,
18741
18795
  reason: "submitted",
@@ -18919,6 +18973,7 @@ function createOperationRegistry(deps) {
18919
18973
  lastDispatchAt: lastDispatchAt()
18920
18974
  },
18921
18975
  healthySince: deps.healthySince,
18976
+ budgetWaits: deps.budgetWaits?.(),
18922
18977
  host: deps.hostMetrics?.()
18923
18978
  }, {
18924
18979
  project: input.project,
@@ -24102,27 +24157,34 @@ function throttledRetryAt(error) {
24102
24157
  /** The wait before the next poll and the new failure count. */
24103
24158
  function nextDelay(input) {
24104
24159
  const { outcome, intervalMs, failures, now } = input;
24105
- if (outcome.kind === "delivered") return {
24106
- delayMs: budgetPause(outcome.budget, input.reserveRemaining, intervalMs, now) ?? jitter(intervalMs),
24107
- failures: 0
24108
- };
24160
+ if (outcome.kind === "delivered") {
24161
+ const pause = budgetPause(outcome.budget, input.reserveRemaining, intervalMs, now);
24162
+ return {
24163
+ delayMs: pause ?? jitter(intervalMs),
24164
+ failures: 0,
24165
+ budgetWait: pause !== void 0
24166
+ };
24167
+ }
24109
24168
  const { error } = outcome;
24110
24169
  if (error instanceof AdapterError) {
24111
24170
  if (error.kind === "auth" || error.kind === "config") return {
24112
24171
  delayMs: jitter(input.authRetryMs),
24113
- failures
24172
+ failures,
24173
+ budgetWait: false
24114
24174
  };
24115
24175
  const retryAt = throttledRetryAt(error);
24116
24176
  if (retryAt !== void 0) return {
24117
24177
  delayMs: Math.max(retryAt - now, intervalMs),
24118
- failures
24178
+ failures,
24179
+ budgetWait: true
24119
24180
  };
24120
24181
  }
24121
24182
  const next = failures + 1;
24122
24183
  const cap = Math.max(MAX_BACKOFF_MS, intervalMs);
24123
24184
  return {
24124
24185
  delayMs: jitter(Math.min(intervalMs * 2 ** next, cap)),
24125
- failures: next
24186
+ failures: next,
24187
+ budgetWait: error instanceof AdapterError && error.kind === "throttled"
24126
24188
  };
24127
24189
  }
24128
24190
  /** The time after which a source without a new complete observation is blind stale. */
@@ -24216,9 +24278,11 @@ const MAX_TIMER_MS = 2147483647;
24216
24278
  const DEMAND_RETRY_WAITS_MS = [1e3, 2e3];
24217
24279
  function startRunner(options) {
24218
24280
  const startedAt = options.now();
24219
- const sources = options.entries.map((entry) => runSource(entry, options, startedAt));
24281
+ const budgetWaits = /* @__PURE__ */ new Set();
24282
+ const sources = options.entries.map((entry) => runSource(entry, options, startedAt, budgetWaits));
24220
24283
  const byId = new Map(sources.map((source) => [source.id, source]));
24221
24284
  return {
24285
+ budgetWaits,
24222
24286
  firstAttempts: Promise.all(sources.map(async (source) => ({
24223
24287
  source: source.id,
24224
24288
  outcome: await source.firstAttempt
@@ -24241,7 +24305,7 @@ const stoppedError = {
24241
24305
  kind: "stopped",
24242
24306
  message: "The adapter runner is stopping"
24243
24307
  };
24244
- function runSource(entry, options, runnerStartMs) {
24308
+ function runSource(entry, options, runnerStartMs, budgetWaits) {
24245
24309
  const { adapter, reserveRemaining } = entry;
24246
24310
  const { core, config } = options;
24247
24311
  const { now } = options;
@@ -24277,11 +24341,15 @@ function runSource(entry, options, runnerStartMs) {
24277
24341
  const pending = /* @__PURE__ */ new Set();
24278
24342
  /** Until when a regular throttled failure forbids calling the source. */
24279
24343
  let throttledUntilMs;
24344
+ /** The last budget a regular or on-demand poll of this run reported. */
24345
+ let lastBudget;
24280
24346
  /** Tail of the single-flight chain: regular polls and on-demand requests, one at a time. */
24281
24347
  let chain = Promise.resolve();
24282
24348
  let pollTimer;
24283
24349
  let deadlineTimer;
24284
24350
  let hardBoundTimer;
24351
+ /** Ends a remembered-budget wait at the budget's reset. */
24352
+ let waitTimer;
24285
24353
  let reports = Promise.resolve();
24286
24354
  let lastReported;
24287
24355
  function state() {
@@ -24353,10 +24421,24 @@ function runSource(entry, options, runnerStartMs) {
24353
24421
  chain = result.then(noop, noop);
24354
24422
  return result;
24355
24423
  }
24356
- function schedule(delayMs) {
24424
+ /**
24425
+ * Arms the next regular poll; `budgetWait` marks it as put off for the rate budget. With
24426
+ * `waitEndsAt`, the mark ends at that time even if the poll is due later.
24427
+ */
24428
+ function schedule(delayMs, budgetWait, waitEndsAt) {
24357
24429
  if (stopping) return;
24430
+ clearTimeout(waitTimer);
24431
+ waitTimer = void 0;
24432
+ if (budgetWait) budgetWaits.add(source);
24433
+ if (budgetWait && waitEndsAt !== void 0) waitTimer = setTimeout(() => {
24434
+ waitTimer = void 0;
24435
+ budgetWaits.delete(source);
24436
+ }, Math.min(Math.max(waitEndsAt - now(), 0), MAX_TIMER_MS));
24358
24437
  pollTimer = setTimeout(() => {
24359
24438
  pollTimer = void 0;
24439
+ clearTimeout(waitTimer);
24440
+ waitTimer = void 0;
24441
+ budgetWaits.delete(source);
24360
24442
  run(poll);
24361
24443
  }, Math.min(delayMs, MAX_TIMER_MS));
24362
24444
  }
@@ -24446,6 +24528,7 @@ function runSource(entry, options, runnerStartMs) {
24446
24528
  kind: "delivered",
24447
24529
  budget: parsed.data.budget
24448
24530
  };
24531
+ lastBudget = parsed.data.budget ?? lastBudget;
24449
24532
  }
24450
24533
  } catch (error) {
24451
24534
  if (aborted()) return;
@@ -24475,7 +24558,9 @@ function runSource(entry, options, runnerStartMs) {
24475
24558
  throttledUntilMs = outcome.kind === "failed" ? throttledRetryAt(outcome.error) : void 0;
24476
24559
  if (!options.oneShot) armDeadline();
24477
24560
  await report(usage);
24478
- if (!options.oneShot) schedule(delay.delayMs);
24561
+ const underReserve = reserveRemaining !== void 0 && lastBudget !== void 0 && lastBudget.remaining < reserveRemaining && Date.parse(lastBudget.resetAt) > now();
24562
+ const fallback = !delay.budgetWait && outcome.kind === "failed" && underReserve;
24563
+ if (!options.oneShot) schedule(delay.delayMs, delay.budgetWait || fallback, fallback && lastBudget !== void 0 ? Date.parse(lastBudget.resetAt) : void 0);
24479
24564
  return outcome;
24480
24565
  }
24481
24566
  /**
@@ -24568,6 +24653,7 @@ function runSource(entry, options, runnerStartMs) {
24568
24653
  counts = recoveredCounts;
24569
24654
  gone = recoveredGone;
24570
24655
  lastReported = JSON.stringify(committed);
24656
+ lastBudget = parsed.data.budget ?? lastBudget;
24571
24657
  return ok(value);
24572
24658
  });
24573
24659
  reports = accepted.then(noop, noop);
@@ -24661,7 +24747,9 @@ function runSource(entry, options, runnerStartMs) {
24661
24747
  clearTimeout(pollTimer);
24662
24748
  clearTimeout(deadlineTimer);
24663
24749
  clearTimeout(hardBoundTimer);
24664
- pollTimer = deadlineTimer = hardBoundTimer = void 0;
24750
+ clearTimeout(waitTimer);
24751
+ pollTimer = deadlineTimer = hardBoundTimer = waitTimer = void 0;
24752
+ budgetWaits.delete(source);
24665
24753
  controller?.abort();
24666
24754
  for (const cancel of [...pending]) cancel();
24667
24755
  await chain;
@@ -25113,6 +25201,7 @@ function startAdapters(config, core, options) {
25113
25201
  onFailure: options.onPollFailure
25114
25202
  });
25115
25203
  return {
25204
+ budgetWaits: runner.budgetWaits,
25116
25205
  firstAttempts: runner.firstAttempts,
25117
25206
  pollPr: runner.pollPr,
25118
25207
  async stop() {
@@ -26364,7 +26453,8 @@ function createJob(options) {
26364
26453
  * Compose the board's timer and adapter runner without adding lifecycle state to main. `tick`
26365
26454
  * runs the board-core job once more behind its active run and resolves when that run settles.
26366
26455
  * `pollPr` forwards to the running runner: `stopped` before its start and after its stop,
26367
- * `unsupported` for a runner without on-demand polls.
26456
+ * `unsupported` for a runner without on-demand polls. `budgetWaits` reads the running runner's
26457
+ * rate budget pauses, none before its start and after its stop.
26368
26458
  */
26369
26459
  function createBoardModules(ctxFor, options = {}) {
26370
26460
  const coreCtx = ctxFor("board-core");
@@ -26449,7 +26539,8 @@ function createBoardModules(ctxFor, options = {}) {
26449
26539
  return {
26450
26540
  entries,
26451
26541
  tick: () => boardCore.trigger(),
26452
- pollPr
26542
+ pollPr,
26543
+ budgetWaits: () => runner?.budgetWaits
26453
26544
  };
26454
26545
  }
26455
26546
  // ../daemon/src/host-metrics.ts
@@ -27613,6 +27704,7 @@ function createDaemonModules(ctxFor, ports = {}) {
27613
27704
  gateways: gateway === void 0 ? [] : [gateway.kind],
27614
27705
  reapplyInbound: () => inbound?.reapply,
27615
27706
  prPoller: () => boardModules.pollPr,
27707
+ budgetWaits: () => boardModules.budgetWaits(),
27616
27708
  ...ports.productVersion === void 0 ? {} : { productVersion: ports.productVersion },
27617
27709
  lastDispatchAt: () => lastDispatchAt,
27618
27710
  webOrigin: () => webPort === void 0 ? void 0 : resolveWebOrigin(board.config.web, webPort)
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { p as OPERATIONS, rt as ERRORS, v as renderMcpError } from "./chunk-CgQL6u77.mjs";
2
- import { o as CliError, r as requestOperation } from "./chunk-2vFOidpZ.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-B9WekLbU.mjs";
1
+ import { p as OPERATIONS, rt as ERRORS, v as renderMcpError } from "./chunk-CY_rWPWy.mjs";
2
+ import { o as CliError, r as requestOperation } from "./chunk-DfehZM2s.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-BUWlIiQd.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";