spur-board 0.71.0 → 0.73.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.
@@ -204,6 +204,10 @@ const SLACK_BOT_SCOPES = [
204
204
  * range 32768-60999.
205
205
  */
206
206
  const DEFAULT_HTTP_PORT = 4777;
207
+ const DEFAULT_STAND_PORT_RANGE = {
208
+ min: 4780,
209
+ max: 4799
210
+ };
207
211
  const DEFAULT_SLACK_APP_NAME = "spur-board";
208
212
  const DEFAULT_SLACK_COMMAND = "/board";
209
213
  /**
@@ -247,6 +251,19 @@ function plainHttpAllowed(url) {
247
251
  const host = url.hostname;
248
252
  return host === "localhost" || host === "[::1]" || LOOPBACK_IPV4.test(host);
249
253
  }
254
+ /** Check raw syntax before URL normalization can hide a slash, whitespace or backslash. */
255
+ function validOrigin(value, port) {
256
+ const resolved = port === void 0 ? value : value.replaceAll("{port}", String(port));
257
+ if (!/^https?:\/\/[^/\\\s?#@{}]+$/i.test(resolved)) return false;
258
+ try {
259
+ const url = new URL(resolved);
260
+ return url.username === "" && url.password === "" && plainHttpAllowed(url);
261
+ } catch {
262
+ return false;
263
+ }
264
+ }
265
+ const originError = "Expected a bare HTTP/HTTPS origin; HTTP requires loopback, with no path, trailing slash, query, fragment, credentials or invalid placeholders";
266
+ const concreteOrigin = z.string().refine((value) => validOrigin(value), { error: originError });
250
267
  const jiraTracker = z.strictObject({
251
268
  type: z.literal("jira").describe("jira: tasks come from the Jira issues jql returns, read with JIRA_EMAIL and JIRA_API_TOKEN from secrets.env."),
252
269
  baseUrl: z.url({ protocol: /^https?$/ }).refine((value) => {
@@ -640,6 +657,15 @@ const configObject = z.strictObject({
640
657
  });
641
658
  }).prefault({}),
642
659
  http: z.strictObject({ port: z.int().min(0).max(65535).default(DEFAULT_HTTP_PORT).describe("Local HTTP API port (0 assigns a free port). The default 4777 is above 4310-4399, a margin kept for Spur's server port 4310 and the ports from 4311 upward that its MCP port takes, and avoids Spur's ports 5555 and 8730-8799 and the Linux ephemeral range 32768-60999.") }).prefault({}),
660
+ web: z.strictObject({
661
+ port: z.int().min(0).max(65535).optional().describe("Optional web listener port (0 assigns a free port); omitted means off. Set together with publicOrigin. Must differ from http.port, including when both are 0. This config does not start a listener."),
662
+ publicOrigin: z.string().optional().describe("Bare public HTTP/HTTPS origin for the web API; HTTP requires loopback. Set together with port. Every {port} is replaced with the listener port, including in hostnames. No trailing slash. The resolved origin must remain valid and HTTP loopback-only after actual-port substitution; the resolver returns no origin for an invalid actual port or resulting origin."),
663
+ spurUiOrigin: concreteOrigin.optional().describe("Optional concrete bare origin for the Spur UI, independently of the web API. HTTP requires loopback; no placeholders or trailing slash. Omitted means no configured UI origin.")
664
+ }).prefault({}),
665
+ stand: z.strictObject({ portRange: z.strictObject({
666
+ min: z.int().min(1024).max(65535).default(DEFAULT_STAND_PORT_RANGE.min).describe("Inclusive first stand port; defaults to 4780 when a range is supplied."),
667
+ max: z.int().min(1024).max(65535).default(DEFAULT_STAND_PORT_RANGE.max).describe("Inclusive last stand port; defaults to 4799 when a range is supplied.")
668
+ }).optional().describe("Optional stand port range, effectively 4780..4799 when omitted. An explicit range (including {}) must exclude http.port and web.port; an omitted range preserves legacy configs and doctor warns on overlaps. Range allocation and exclusions are deferred to #534; current stand behavior is unchanged.") }).prefault({}),
643
669
  adapters: z.strictObject({
644
670
  spur: spurAdapterSection,
645
671
  github: adapterSection(6e4),
@@ -777,6 +803,39 @@ function checkBoardWideAgainstProjects(config, ctx) {
777
803
  * `spurProjects` (`expandBoardWide`), so readers of `projects[]` see the effective bindings.
778
804
  */
779
805
  const configSchema = configObject.superRefine(checkBoardWideAgainstProjects).superRefine((config, ctx) => {
806
+ const { web } = config;
807
+ if (web.publicOrigin !== void 0 && !validOrigin(web.publicOrigin, web.port)) ctx.addIssue({
808
+ code: "custom",
809
+ path: ["web", "publicOrigin"],
810
+ message: originError
811
+ });
812
+ if (web.port === void 0 !== (web.publicOrigin === void 0)) ctx.addIssue({
813
+ code: "custom",
814
+ path: ["web", web.port === void 0 ? "port" : "publicOrigin"],
815
+ message: "Set web.port and web.publicOrigin together"
816
+ });
817
+ if (web.port !== void 0 && web.port === config.http.port) ctx.addIssue({
818
+ code: "custom",
819
+ path: ["web", "port"],
820
+ message: "Web port must differ from http.port"
821
+ });
822
+ const range = config.stand.portRange;
823
+ if (range !== void 0) {
824
+ if (range.min > range.max) ctx.addIssue({
825
+ code: "custom",
826
+ path: [
827
+ "stand",
828
+ "portRange",
829
+ "max"
830
+ ],
831
+ message: "Range maximum must be at least its minimum"
832
+ });
833
+ for (const [field, port] of [["http", config.http.port], ["web", web.port]]) if (port !== void 0 && port >= range.min && port <= range.max) ctx.addIssue({
834
+ code: "custom",
835
+ path: ["stand", "portRange"],
836
+ message: `Stand port range includes ${field}.port ${String(port)}`
837
+ });
838
+ }
780
839
  const addressee = config.slack.defaultAddressee;
781
840
  if (addressee === void 0) return;
782
841
  if (!(config.spurProjects.some(({ shortName }) => shortName === addressee) || config.projects.some((project) => project.spurProjects.some(({ shortName }) => shortName === addressee)))) ctx.addIssue({
@@ -785,6 +844,18 @@ const configSchema = configObject.superRefine(checkBoardWideAgainstProjects).sup
785
844
  message: `Unknown short name ${JSON.stringify(addressee)}: set it as spurProjects[].shortName or projects[].spurProjects[].shortName first`
786
845
  });
787
846
  }).overwrite(expandBoardWide);
847
+ /**
848
+ * Resolve validated web settings without mutation or I/O. Returns undefined when off, or when
849
+ * the effective port is not an integer in 0..65535 or its substituted origin violates the
850
+ * config origin policy. Invalid overrides never expose a URL parser error or unsafe origin.
851
+ */
852
+ function resolveWebOrigin(web, actualPort) {
853
+ if (web.port === void 0 || web.publicOrigin === void 0) return void 0;
854
+ const port = actualPort ?? web.port;
855
+ if (!Number.isInteger(port) || port < 0 || port > 65535) return void 0;
856
+ if (!validOrigin(web.publicOrigin, port)) return void 0;
857
+ return new URL(web.publicOrigin.replaceAll("{port}", String(port))).origin;
858
+ }
788
859
  /** The top-level `spurProjects` entry named `name`: a Spur project bound board-wide. */
789
860
  function boardWideSpurProject(config, name) {
790
861
  return config.spurProjects.find((entry) => entry.name === name);
@@ -1725,6 +1796,7 @@ const batchSchema = z.strictObject({
1725
1796
  usage: z.strictObject({ points: z.int().nonnegative().describe("Reported points consumed.") }).optional().describe("Reported source points consumed by this attempt."),
1726
1797
  budget: z.strictObject({
1727
1798
  remaining: z.int().min(0).describe("Requests or points the source still allows."),
1799
+ limit: z.int().positive().optional().describe("Full budget the source restores at reset; omitted when it reports none."),
1728
1800
  resetAt: z.iso.datetime().describe("When the source restores the full budget.")
1729
1801
  }).optional().describe("Request budget the source reported on this poll; omitted when it reports none.")
1730
1802
  }).superRefine((batch, ctx) => {
@@ -2642,6 +2714,11 @@ const sourceViewSchema = z.strictObject({
2642
2714
  "stale"
2643
2715
  ]).nullable().describe("Why this source is blind, or null when it is usable."),
2644
2716
  message: z.string().nullable().describe("Short explanation of the source state."),
2717
+ budget: z.strictObject({
2718
+ remaining: z.int().nonnegative().describe("Requests or points the source still allowed."),
2719
+ limit: z.int().positive().nullable().describe("Full budget the source restores at reset, or null when it reported none."),
2720
+ resetAt: z.iso.datetime().describe("When the source said it restores the full budget.")
2721
+ }).nullable().describe("Request budget from the last poll of this source that reported one, or null when none did."),
2645
2722
  stale: z.boolean().describe("Whether facts from this source exceed their freshness threshold."),
2646
2723
  warmingUp: z.boolean().describe("Whether this source needs a complete poll in this daemon run.")
2647
2724
  }).describe("Freshness and availability of one source.");
@@ -4470,4 +4547,4 @@ function assertNever(value) {
4470
4547
  throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
4471
4548
  }
4472
4549
  //#endregion
4473
- export { err as $, prSourceId as A, prFactsSchema as B, userIdSchema as C, AdapterError as D, eventPayloadSchemas as E, REVIEW_STATES as F, JIRA_PROJECT_KEY as G, ringMarker as H, SESSION_HEALTH_STATES as I, encodeActorId as J, REF_NUMBER as K, SESSION_STATUSES as L, sourceCursorSchema as M, trackerSourceId as N, batchSchema as O, PR_STATES as P, ERRORS as Q, isExternalAuthor as R, messageRefSchema as S, GATE_REASONS as T, sessionFactsSchema as U, prRefSchema as V, ticketFactsSchema as W, parseActorId as X, errorCodeOf as Y, parseRef as Z, renderMcpError as _, SLACK_BOT_SCOPES as _t, requestHashOf as a, DEFAULT_LINK as at, inboundEventSchema as b, tokenRequestStatusSchema as c, RESERVED_PROJECT as ct, buildCatalogSnapshot as d, configSchema as dt, errorContextSchema as et, roleCanUseOperation as f, defaultAddressee as ft, renderJsonError as g, DISPATCHER_MODES as gt, renderHttpProblem as h, COLUMN_IDS as ht, TOKEN_REQUEST_LIMITS as i, DEFAULT_HTTP_PORT as it, sessionTransitionSchema as j, entityRefSchema as k, BOARD_TICK_MS as l, boardWideSpurProject as lt, turnHandedSchema as m, requiredSecretKeys as mt, doctorReportSchema as n, ok as nt, tokenRequestResultSchema as o, DEFAULT_SLACK_APP_NAME as ot, OPERATIONS as p, plainHttpAllowed as pt, actorIdSchema as q, remoteDoctorReportSchema as r, successEnvelopeSchema as rt, tokenRequestSchema as s, DEFAULT_SLACK_COMMAND as st, assertNever as t, errorEnvelopeSchema as tt, SYSTEMD_SERVICE_SETTINGS as u, configBindings as ut, SPACE_IDS as v, TASK_HOLDS as vt, EVENT_KINDS as w, interactionRefSchema as x, conversationRefSchema as y, parseRingMarker as z };
4550
+ export { err as $, prSourceId as A, prFactsSchema as B, userIdSchema as C, AdapterError as D, eventPayloadSchemas as E, REVIEW_STATES as F, JIRA_PROJECT_KEY as G, ringMarker as H, SESSION_HEALTH_STATES as I, encodeActorId as J, REF_NUMBER as K, SESSION_STATUSES as L, sourceCursorSchema as M, trackerSourceId as N, batchSchema as O, PR_STATES as P, ERRORS as Q, isExternalAuthor as R, messageRefSchema as S, GATE_REASONS as T, sessionFactsSchema as U, prRefSchema as V, ticketFactsSchema as W, parseActorId as X, errorCodeOf as Y, parseRef as Z, renderMcpError as _, COLUMN_IDS as _t, requestHashOf as a, DEFAULT_LINK as at, inboundEventSchema as b, TASK_HOLDS as bt, tokenRequestStatusSchema as c, DEFAULT_STAND_PORT_RANGE as ct, buildCatalogSnapshot as d, configBindings as dt, errorContextSchema as et, roleCanUseOperation as f, configSchema as ft, renderJsonError as g, resolveWebOrigin as gt, renderHttpProblem as h, requiredSecretKeys as ht, TOKEN_REQUEST_LIMITS as i, DEFAULT_HTTP_PORT as it, sessionTransitionSchema as j, entityRefSchema as k, BOARD_TICK_MS as l, RESERVED_PROJECT as lt, turnHandedSchema as m, plainHttpAllowed as mt, doctorReportSchema as n, ok as nt, tokenRequestResultSchema as o, DEFAULT_SLACK_APP_NAME as ot, OPERATIONS as p, defaultAddressee as pt, actorIdSchema as q, remoteDoctorReportSchema as r, successEnvelopeSchema as rt, tokenRequestSchema as s, DEFAULT_SLACK_COMMAND as st, assertNever as t, errorEnvelopeSchema as tt, SYSTEMD_SERVICE_SETTINGS as u, boardWideSpurProject as ut, SPACE_IDS as v, DISPATCHER_MODES as vt, EVENT_KINDS as w, interactionRefSchema as x, conversationRefSchema as y, SLACK_BOT_SCOPES as yt, parseRingMarker as z };
@@ -1,4 +1,4 @@
1
- import { Q as ERRORS, c as tokenRequestStatusSchema, et as errorContextSchema, g as renderJsonError, o as tokenRequestResultSchema, rt as successEnvelopeSchema, tt as errorEnvelopeSchema } from "./chunk-BPwdLTBv.mjs";
1
+ import { Q as ERRORS, c as tokenRequestStatusSchema, et as errorContextSchema, g as renderJsonError, o as tokenRequestResultSchema, rt as successEnvelopeSchema, tt as errorEnvelopeSchema } from "./chunk-DL9OvxPQ.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
@@ -1,5 +1,5 @@
1
- import { d as buildCatalogSnapshot, dt as configSchema, p as OPERATIONS, pt as plainHttpAllowed } from "./chunk-BPwdLTBv.mjs";
2
- import { o as CliError, t as fetchCatalogVersion } from "./chunk-B1u_eWSX.mjs";
1
+ import { d as buildCatalogSnapshot, ft as configSchema, mt as plainHttpAllowed, p as OPERATIONS } from "./chunk-DL9OvxPQ.mjs";
2
+ import { o as CliError, t as fetchCatalogVersion } from "./chunk-aWb9sMi0.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";
package/dist/cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { Q as ERRORS, _t as SLACK_BOT_SCOPES, a as requestHashOf, dt as configSchema, f as roleCanUseOperation, mt as requiredSecretKeys, p as OPERATIONS, q as actorIdSchema, r as remoteDoctorReportSchema, rt as successEnvelopeSchema, u as SYSTEMD_SERVICE_SETTINGS } from "./chunk-BPwdLTBv.mjs";
1
+ import { Q as ERRORS, a as requestHashOf, ct as DEFAULT_STAND_PORT_RANGE, f as roleCanUseOperation, ft as configSchema, gt as resolveWebOrigin, ht as requiredSecretKeys, p as OPERATIONS, q as actorIdSchema, r as remoteDoctorReportSchema, rt as successEnvelopeSchema, u as SYSTEMD_SERVICE_SETTINGS, yt as SLACK_BOT_SCOPES } from "./chunk-DL9OvxPQ.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-DAMwWWmT.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-B1u_eWSX.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-DlDngVbH.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-aWb9sMi0.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-mUsK73x3.mjs";
5
5
  import { createHash, randomBytes, randomUUID } from "node:crypto";
6
6
  import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
7
7
  import { homedir, hostname, userInfo } from "node:os";
@@ -513,6 +513,14 @@ async function runDoctor(options = {}) {
513
513
  checks.push(result("config", false, "Create or correct config.yaml using the configuration schema."));
514
514
  return checks;
515
515
  }
516
+ const webOrigin = resolveWebOrigin(config.web);
517
+ checks.push({
518
+ ...result("web", true, ""),
519
+ present: webOrigin === void 0 ? ["off"] : ["on", webOrigin]
520
+ });
521
+ const range = config.stand.portRange ?? DEFAULT_STAND_PORT_RANGE;
522
+ const overlaps = [["http.port", config.http.port], ["web.port", config.web.port]].filter(([, port]) => port !== void 0 && port >= range.min && port <= range.max).map(([field, port]) => `${field} ${String(port)}`);
523
+ checks.push(overlaps.length === 0 ? result("stand.port_range", true, "") : warning("stand.port_range", `Implicit stand port range ${String(range.min)}..${String(range.max)} overlaps ${overlaps.join(", ")}. Set a nonoverlapping stand.portRange. Range allocation and exclusions are deferred to #534; current stand behavior is unchanged.`));
516
524
  if (options.offline) return checks;
517
525
  const unitPath = unitFile(env, home);
518
526
  let unit = null;
package/dist/client.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { a as requestTokenEnrollment, i as requestSkillReload, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./chunk-B1u_eWSX.mjs";
1
+ import { a as requestTokenEnrollment, i as requestSkillReload, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./chunk-aWb9sMi0.mjs";
2
2
  export { fetchCatalogVersion, fetchTokenStatus, requestOperation, requestSkillReload, requestTokenEnrollment };
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as err, A as prSourceId, B as prFactsSchema, C as userIdSchema, D as AdapterError, E as eventPayloadSchemas, F as REVIEW_STATES, G as JIRA_PROJECT_KEY, H as ringMarker, I as SESSION_HEALTH_STATES, J as encodeActorId, K as REF_NUMBER, L as SESSION_STATUSES, M as sourceCursorSchema, N as trackerSourceId, O as batchSchema, P as PR_STATES, Q as ERRORS, R as isExternalAuthor, S as messageRefSchema, T as GATE_REASONS, U as sessionFactsSchema, V as prRefSchema, W as ticketFactsSchema, X as parseActorId, Y as errorCodeOf, Z as parseRef$1, _t as SLACK_BOT_SCOPES, a as requestHashOf, at as DEFAULT_LINK, b as inboundEventSchema, c as tokenRequestStatusSchema, ct as RESERVED_PROJECT, d as buildCatalogSnapshot, dt as configSchema, f as roleCanUseOperation, ft as defaultAddressee, gt as DISPATCHER_MODES, h as renderHttpProblem, ht as COLUMN_IDS, i as TOKEN_REQUEST_LIMITS, j as sessionTransitionSchema, k as entityRefSchema, l as BOARD_TICK_MS, lt as boardWideSpurProject, m as turnHandedSchema, mt as requiredSecretKeys, n as doctorReportSchema, nt as ok, o as tokenRequestResultSchema, p as OPERATIONS, pt as plainHttpAllowed, q as actorIdSchema, rt as successEnvelopeSchema, s as tokenRequestSchema, st as DEFAULT_SLACK_COMMAND, t as assertNever, ut as configBindings, v as SPACE_IDS, vt as TASK_HOLDS, w as EVENT_KINDS, x as interactionRefSchema, y as conversationRefSchema, z as parseRingMarker } from "./chunk-BPwdLTBv.mjs";
1
+ import { $ as err, A as prSourceId, B as prFactsSchema, C as userIdSchema, D as AdapterError, E as eventPayloadSchemas, F as REVIEW_STATES, G as JIRA_PROJECT_KEY, H as ringMarker, I as SESSION_HEALTH_STATES, J as encodeActorId, K as REF_NUMBER, L as SESSION_STATUSES, M as sourceCursorSchema, N as trackerSourceId, O as batchSchema, P as PR_STATES, Q as ERRORS, R as isExternalAuthor, S as messageRefSchema, T as GATE_REASONS, U as sessionFactsSchema, V as prRefSchema, W as ticketFactsSchema, X as parseActorId, Y as errorCodeOf, Z as parseRef$1, _t as COLUMN_IDS, a as requestHashOf, at as DEFAULT_LINK, b as inboundEventSchema, bt as TASK_HOLDS, c as tokenRequestStatusSchema, d as buildCatalogSnapshot, dt as configBindings, f as roleCanUseOperation, ft as configSchema, h as renderHttpProblem, ht as requiredSecretKeys, i as TOKEN_REQUEST_LIMITS, j as sessionTransitionSchema, k as entityRefSchema, l as BOARD_TICK_MS, lt as RESERVED_PROJECT, m as turnHandedSchema, mt as plainHttpAllowed, n as doctorReportSchema, nt as ok, o as tokenRequestResultSchema, p as OPERATIONS, pt as defaultAddressee, q as actorIdSchema, rt as successEnvelopeSchema, s as tokenRequestSchema, st as DEFAULT_SLACK_COMMAND, t as assertNever, ut as boardWideSpurProject, v as SPACE_IDS, vt as DISPATCHER_MODES, w as EVENT_KINDS, x as interactionRefSchema, y as conversationRefSchema, yt as SLACK_BOT_SCOPES, z as parseRingMarker } from "./chunk-DL9OvxPQ.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-DAMwWWmT.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { createHash, randomUUID } from "node:crypto";
@@ -14130,6 +14130,11 @@ async function getStatus(deps, options = {}) {
14130
14130
  lastCompleteAt: last,
14131
14131
  blindReason,
14132
14132
  message: row?.blind_message ?? null,
14133
+ budget: row?.budget_remaining != null && row.budget_reset_at != null ? {
14134
+ remaining: row.budget_remaining,
14135
+ limit: row.budget_limit,
14136
+ resetAt: row.budget_reset_at
14137
+ } : null,
14133
14138
  stale: last === null || clock.now() - Date.parse(last) > config.thresholds.staleMultiplier * interval(config, source),
14134
14139
  warmingUp: !completeSince.has(source)
14135
14140
  };
@@ -17293,7 +17298,7 @@ async function updateTerminal(trx, config, taskId, at, completeSince, blind) {
17293
17298
  async function blindReason(trx, source) {
17294
17299
  return (await trx.selectFrom("source_state").select("blind_reason").where("source", "=", source).executeTakeFirst())?.blind_reason ?? null;
17295
17300
  }
17296
- async function sourceState(trx, source, state, observedAt, cursor) {
17301
+ async function sourceState(trx, source, state, observedAt, cursor, budget) {
17297
17302
  await trx.insertInto("source_state").values({
17298
17303
  source,
17299
17304
  initialized: observedAt === void 0 ? 0 : 1,
@@ -17302,7 +17307,10 @@ async function sourceState(trx, source, state, observedAt, cursor) {
17302
17307
  blind_message: state.blind?.message ?? null,
17303
17308
  cursor: cursor ?? null,
17304
17309
  observed_at: observedAt ?? null,
17305
- gone: toJson(z.array(entityRefSchema), [...state.gone])
17310
+ gone: toJson(z.array(entityRefSchema), [...state.gone]),
17311
+ budget_remaining: budget?.remaining ?? null,
17312
+ budget_limit: budget?.limit ?? null,
17313
+ budget_reset_at: budget?.resetAt ?? null
17306
17314
  }).onConflict((oc) => oc.column("source").doUpdateSet((eb) => ({
17307
17315
  initialized: observedAt === void 0 ? eb.ref("source_state.initialized") : 1,
17308
17316
  last_complete_at: state.lastCompleteAt ?? null,
@@ -17310,7 +17318,10 @@ async function sourceState(trx, source, state, observedAt, cursor) {
17310
17318
  blind_message: state.blind?.message ?? null,
17311
17319
  cursor: cursor ?? eb.ref("source_state.cursor"),
17312
17320
  observed_at: observedAt ?? eb.ref("source_state.observed_at"),
17313
- gone: toJson(z.array(entityRefSchema), [...state.gone])
17321
+ gone: toJson(z.array(entityRefSchema), [...state.gone]),
17322
+ budget_remaining: budget === void 0 ? eb.ref("source_state.budget_remaining") : budget.remaining,
17323
+ budget_limit: budget === void 0 ? eb.ref("source_state.budget_limit") : budget.limit ?? null,
17324
+ budget_reset_at: budget === void 0 ? eb.ref("source_state.budget_reset_at") : budget.resetAt
17314
17325
  }))).execute();
17315
17326
  }
17316
17327
  /**
@@ -17945,7 +17956,7 @@ function createObservationCore(deps) {
17945
17956
  const wasBlind = await blindReason(trx, source);
17946
17957
  const previousSpur = source === "spur" ? await trx.selectFrom("source_state").select("last_complete_at").where("source", "=", source).executeTakeFirst() : void 0;
17947
17958
  const spurGap = previousSpur?.last_complete_at != null && Date.parse(batch.observedAt) > Date.parse(previousSpur.last_complete_at) + config.adapters.spur.intervalMs * config.thresholds.staleMultiplier;
17948
- await sourceState(trx, source, observation.state, batch.observedAt, batch.cursor);
17959
+ await sourceState(trx, source, observation.state, batch.observedAt, batch.cursor, batch.budget);
17949
17960
  await recordUsage(trx, source, batch.usage, now);
17950
17961
  for (const probe of batch.prProbes ?? []) {
17951
17962
  if (probe.status !== "closed") continue;
@@ -19674,21 +19685,21 @@ function aliases(numbers, fields) {
19674
19685
  }
19675
19686
  const discoveryStates = (bootstrap) => bootstrap ? "OPEN" : "OPEN, MERGED, CLOSED";
19676
19687
  function discoveryQuery(bootstrap = false) {
19677
- return `query PrBatch($owner: String!, $repo: String!) { rateLimit { cost remaining resetAt } repository(owner: $owner, name: $repo) { pullRequests(first: 100, states: [${discoveryStates(bootstrap)}], orderBy: {field: UPDATED_AT, direction: DESC}) { ${DISCOVERY_FIELDS} }${bootstrap ? " mergedBaseline: pullRequests(first: 1, states: [MERGED, CLOSED], orderBy: {field: UPDATED_AT, direction: DESC}) { nodes { updatedAt } }" : ""} } }`;
19688
+ return `query PrBatch($owner: String!, $repo: String!) { rateLimit { cost limit remaining resetAt } repository(owner: $owner, name: $repo) { pullRequests(first: 100, states: [${discoveryStates(bootstrap)}], orderBy: {field: UPDATED_AT, direction: DESC}) { ${DISCOVERY_FIELDS} }${bootstrap ? " mergedBaseline: pullRequests(first: 1, states: [MERGED, CLOSED], orderBy: {field: UPDATED_AT, direction: DESC}) { nodes { updatedAt } }" : ""} } }`;
19678
19689
  }
19679
19690
  function stateQuery(numbers) {
19680
- return `query PrStates($owner: String!, $repo: String!) { rateLimit { cost remaining resetAt } ${aliases(numbers, () => "number state")} }`;
19691
+ return `query PrStates($owner: String!, $repo: String!) { rateLimit { cost limit remaining resetAt } ${aliases(numbers, () => "number state")} }`;
19681
19692
  }
19682
19693
  function indexQuery(numbers) {
19683
- return `query PrIndex($owner: String!, $repo: String!) { rateLimit { cost remaining resetAt } ${aliases(numbers, () => INDEX_FIELDS)} }`;
19694
+ return `query PrIndex($owner: String!, $repo: String!) { rateLimit { cost limit remaining resetAt } ${aliases(numbers, () => INDEX_FIELDS)} }`;
19684
19695
  }
19685
19696
  function detailQuery(numbers, closing = false) {
19686
- return `query PrDetails($owner: String!, $repo: String!) { rateLimit { cost remaining resetAt } ${aliases(numbers, (number) => prFields(number, closing))} }`;
19697
+ return `query PrDetails($owner: String!, $repo: String!) { rateLimit { cost limit remaining resetAt } ${aliases(numbers, (number) => prFields(number, closing))} }`;
19687
19698
  }
19688
19699
  function pageQuery(connection, bootstrap = false) {
19689
- if (connection === "comments") return `query PrPage($owner: String!, $repo: String!, $number: Int!, $before: String!) { rateLimit { cost remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { comments(last: 100, before: $before) { ${COMMENT_FIELDS} } } } }`;
19690
- if (connection === "pullRequests") return `query DiscoveryPage($owner: String!, $repo: String!, $after: String!) { rateLimit { cost remaining resetAt } repository(owner: $owner, name: $repo) { pullRequests(first: 100, after: $after, states: [${discoveryStates(bootstrap)}], orderBy: {field: UPDATED_AT, direction: DESC}) { ${DISCOVERY_FIELDS} } } }`;
19691
- return `query PrPage($owner: String!, $repo: String!, $number: Int!, $after: String!) { rateLimit { cost remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { ${connection === "closingIssuesReferences" ? `closingIssuesReferences(first: 100, after: $after) { ${CLOSING_FIELDS} }` : connection === "contexts" ? `statusCheckRollup { contexts(first: 100, after: $after) { nodes { ... on CheckRun { __typename name status conclusion startedAt completedAt checkSuite { createdAt } isRequired(pullRequestNumber: $number) } ... on StatusContext { __typename context state createdAt isRequired(pullRequestNumber: $number) } } pageInfo { hasNextPage endCursor } } }` : `${connection}(first: 100, after: $after) { nodes { ${connection === "reviews" ? REVIEW_FIELDS : connection === "reviewThreads" ? THREAD_FIELDS : REVIEWER_FIELDS} } pageInfo { hasNextPage endCursor } }`} } } }`;
19700
+ if (connection === "comments") return `query PrPage($owner: String!, $repo: String!, $number: Int!, $before: String!) { rateLimit { cost limit remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { comments(last: 100, before: $before) { ${COMMENT_FIELDS} } } } }`;
19701
+ if (connection === "pullRequests") return `query DiscoveryPage($owner: String!, $repo: String!, $after: String!) { rateLimit { cost limit remaining resetAt } repository(owner: $owner, name: $repo) { pullRequests(first: 100, after: $after, states: [${discoveryStates(bootstrap)}], orderBy: {field: UPDATED_AT, direction: DESC}) { ${DISCOVERY_FIELDS} } } }`;
19702
+ return `query PrPage($owner: String!, $repo: String!, $number: Int!, $after: String!) { rateLimit { cost limit remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { ${connection === "closingIssuesReferences" ? `closingIssuesReferences(first: 100, after: $after) { ${CLOSING_FIELDS} }` : connection === "contexts" ? `statusCheckRollup { contexts(first: 100, after: $after) { nodes { ... on CheckRun { __typename name status conclusion startedAt completedAt checkSuite { createdAt } isRequired(pullRequestNumber: $number) } ... on StatusContext { __typename context state createdAt isRequired(pullRequestNumber: $number) } } pageInfo { hasNextPage endCursor } } }` : `${connection}(first: 100, after: $after) { nodes { ${connection === "reviews" ? REVIEW_FIELDS : connection === "reviewThreads" ? THREAD_FIELDS : REVIEWER_FIELDS} } pageInfo { hasNextPage endCursor } }`} } } }`;
19692
19703
  }
19693
19704
  /**
19694
19705
  * The failure that GraphQL `errors` mean for the whole request, in rule order: a rate limit is
@@ -19766,10 +19777,14 @@ var GithubClient = class {
19766
19777
  const failure = graphqlFailure(errors, query, response.headers, this.now());
19767
19778
  if (failure !== null) throw failure;
19768
19779
  const data = parseWire(dataWire, wire.data, MALFORMED$3, ["data"]);
19780
+ const limit = z.object({ rateLimit: z.object({ limit: z.int().positive() }) }).safeParse(wire.data);
19769
19781
  return {
19770
19782
  data,
19771
19783
  errors,
19772
- budget: data.rateLimit
19784
+ budget: limit.success ? {
19785
+ ...data.rateLimit,
19786
+ limit: limit.data.rateLimit.limit
19787
+ } : data.rateLimit
19773
19788
  };
19774
19789
  }
19775
19790
  };
@@ -21066,7 +21081,10 @@ function matchesFilter(issue, tracker) {
21066
21081
  if (tracker.label !== void 0) return issue.labels.some((label) => label.name === tracker.label);
21067
21082
  return issue.milestone?.title === tracker.milestone;
21068
21083
  }
21069
- /** The REST `core` budget from GitHub's rate-limit headers; undefined when either is invalid. */
21084
+ /**
21085
+ * The REST `core` budget from GitHub's rate-limit headers; undefined when remaining or reset is
21086
+ * invalid. An invalid `x-ratelimit-limit` is left out of the budget.
21087
+ */
21070
21088
  function restBudget(headers) {
21071
21089
  const remaining = headers.get("x-ratelimit-remaining");
21072
21090
  const reset = headers.get("x-ratelimit-reset");
@@ -21077,7 +21095,12 @@ function restBudget(headers) {
21077
21095
  if (!Number.isSafeInteger(count) || Number.isNaN(resetAt.getTime())) return void 0;
21078
21096
  const iso = resetAt.toISOString();
21079
21097
  if (!/^\d{4}-/.test(iso)) return void 0;
21080
- return {
21098
+ const limit = Number(headers.get("x-ratelimit-limit")?.match(/^\d+$/)?.[0]);
21099
+ return Number.isSafeInteger(limit) && limit > 0 ? {
21100
+ remaining: count,
21101
+ limit,
21102
+ resetAt: iso
21103
+ } : {
21081
21104
  remaining: count,
21082
21105
  resetAt: iso
21083
21106
  };
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { Q as ERRORS, _ as renderMcpError, p as OPERATIONS } from "./chunk-BPwdLTBv.mjs";
2
- import { o as CliError, r as requestOperation } from "./chunk-B1u_eWSX.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-DlDngVbH.mjs";
1
+ import { Q as ERRORS, _ as renderMcpError, p as OPERATIONS } from "./chunk-DL9OvxPQ.mjs";
2
+ import { o as CliError, r as requestOperation } from "./chunk-aWb9sMi0.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-mUsK73x3.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";
@@ -0,0 +1,5 @@
1
+ -- Request budget each source reported on its last batch that carried one. observe writes the three
2
+ -- columns together from one batch or leaves them alone; reportSourceState never changes them.
3
+ ALTER TABLE source_state ADD COLUMN budget_remaining INTEGER;
4
+ ALTER TABLE source_state ADD COLUMN budget_limit INTEGER;
5
+ ALTER TABLE source_state ADD COLUMN budget_reset_at TEXT;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.71.0",
3
+ "version": "0.73.0",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"