spur-board 0.82.1 → 0.83.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.
@@ -2829,6 +2829,7 @@ const sourceViewSchema = z.strictObject({
2829
2829
  resetAt: z.iso.datetime().describe("When the source said it restores the full budget.")
2830
2830
  }).nullable().describe("Request budget from the last poll of this source that reported one, or null when none did."),
2831
2831
  stale: z.boolean().describe("Whether facts from this source exceed their freshness threshold."),
2832
+ 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."),
2832
2833
  warmingUp: z.boolean().describe("Whether this source needs a complete poll in this daemon run.")
2833
2834
  }).describe("Freshness and availability of one source.");
2834
2835
  errorDetailSchema.extend({
@@ -2857,6 +2858,28 @@ const statusBindingsSchema = z.strictObject({
2857
2858
  source: z.enum(ADDRESSEE_SOURCES).describe("config: slack.defaultAddressee; board-wide: the board-wide operator; project: the operator of the first board project, in config order, that lists one.")
2858
2859
  }).nullable().describe("Who an orchestrators-channel message without a known @shortName goes to; null when it is left unhandled or answered with the prefixes.")
2859
2860
  }).describe("Effective column orchestrators, operators and default Slack addressee.");
2861
+ const hostUsageSchema = (total, available, used) => z.strictObject({
2862
+ totalBytes: z.number().nonnegative().describe(total),
2863
+ availableBytes: z.number().nonnegative().describe(available),
2864
+ usedPercent: z.number().min(0).max(100).describe(used)
2865
+ }).nullable();
2866
+ const hostSchema = z.strictObject({
2867
+ sampledAt: z.iso.datetime().describe("When the daemon took this sample, ISO 8601 UTC. It samples every 30 seconds; reads never take a new sample, so an old value means sampling is stuck."),
2868
+ cpuPercent: z.number().min(0).max(100).nullable().describe("Host CPU busy percent over all cores since the previous sample, one decimal; null on the first sample or when unreadable."),
2869
+ memory: hostUsageSchema("Total host memory in bytes.", "Host memory available for new work without swapping, in bytes.", "Percent of host memory in use: total minus available, over total; one decimal.").describe("Host memory; null when unreadable."),
2870
+ disk: hostUsageSchema("Size of the volume in bytes, root-reserved blocks included.", "Free bytes an unprivileged user can still write, without root-reserved blocks.", "Percent of the volume in use, as df shows it: used over used plus available, without root-reserved blocks; one decimal.").describe("The volume holding the board data; null when unreadable.")
2871
+ }).nullable().describe("Host CPU, memory and data-volume disk usage from the last sample of the daemon; null before the first sample.");
2872
+ const serviceSchema = z.strictObject({
2873
+ service: z.string().min(1).describe("daemon, github, jira, spur, or a chat gateway kind such as slack."),
2874
+ state: z.enum([
2875
+ "healthy",
2876
+ "degraded",
2877
+ "failing"
2878
+ ]).describe("failing: a blind source or a gateway that is down; degraded: a source that never completed, is stale, warms up or waits for its rate budget, or a daemon with no completed board tick for over 120 seconds; else healthy. A source service takes its worst source."),
2879
+ since: z.iso.datetime().nullable().describe("Healthy: since when the service has been usable in this daemon run. That is daemon.startedAt for the daemon, the latest healthySince of its sources for github, jira and spur, and for a gateway the end of its last recorded outage or daemon.startedAt, whichever is later. Failing gateway: when the outage started. Otherwise null."),
2880
+ lastGoodAt: z.iso.datetime().nullable().describe("Last sign of work: the last completed board tick for the daemon, the oldest latest observation of its sources for github, jira and spur (null when one has none); null for a gateway."),
2881
+ reason: z.string().nullable().describe("Why the service is not healthy, from its first worst source for github, jira and spur; null when healthy.")
2882
+ }).describe("Health of one service.");
2860
2883
  const statusInputSchema = z.strictObject({
2861
2884
  project: project$1,
2862
2885
  detail: z.boolean().optional().describe("Include full ticket, pull request and session facts; absent means compact rows.")
@@ -2866,6 +2889,8 @@ const statusOutputSchema = z.strictObject({
2866
2889
  warmingUp: z.boolean().describe("Whether required sources still need a complete poll."),
2867
2890
  spurUnavailable: z.string().nullable().describe("One combined Spur availability line, or null when available."),
2868
2891
  hostLoad: z.string().nullable().describe("Host-load episode line, or null when absent."),
2892
+ host: hostSchema,
2893
+ 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."),
2869
2894
  transport: z.array(z.strictObject({
2870
2895
  gateway: z.string().min(1).describe("Chat gateway kind."),
2871
2896
  state: z.enum(["up", "down"]).describe("down while delivery to any space of the gateway is suspended."),
@@ -3010,6 +3035,13 @@ const daemon = {
3010
3035
  startedAt: "2026-01-05T08:00:00.000Z",
3011
3036
  lastDispatchAt: at
3012
3037
  };
3038
+ const daemonService = {
3039
+ service: "daemon",
3040
+ state: "healthy",
3041
+ since: daemon.startedAt,
3042
+ lastGoodAt: at,
3043
+ reason: null
3044
+ };
3013
3045
  const task = {
3014
3046
  key: "PROJ-123",
3015
3047
  project: "web",
@@ -3202,7 +3234,7 @@ const OPERATIONS = [
3202
3234
  id: "status.get",
3203
3235
  web: true,
3204
3236
  kind: "query",
3205
- description: "List items, freshness and tasks with turns, PR summaries and navigation; detail adds full facts.",
3237
+ description: "List items, freshness, service health, host metrics, tasks with turns and PRs; detail adds facts.",
3206
3238
  mcp: {
3207
3239
  whenToUse: "Get a board overview.",
3208
3240
  whenNotToUse: "Use task_get for one task."
@@ -3227,6 +3259,21 @@ const OPERATIONS = [
3227
3259
  warmingUp: true,
3228
3260
  spurUnavailable: null,
3229
3261
  hostLoad: null,
3262
+ host: {
3263
+ sampledAt: at,
3264
+ cpuPercent: 12.5,
3265
+ memory: {
3266
+ totalBytes: 17179869184,
3267
+ availableBytes: 8589934592,
3268
+ usedPercent: 50
3269
+ },
3270
+ disk: {
3271
+ totalBytes: 107374182400,
3272
+ availableBytes: 64424509440,
3273
+ usedPercent: 40
3274
+ }
3275
+ },
3276
+ services: [daemonService],
3230
3277
  transport: [],
3231
3278
  sources: [],
3232
3279
  tasks: [{
@@ -3279,6 +3326,8 @@ const OPERATIONS = [
3279
3326
  warmingUp: false,
3280
3327
  spurUnavailable: null,
3281
3328
  hostLoad: null,
3329
+ host: null,
3330
+ services: [daemonService],
3282
3331
  transport: [],
3283
3332
  sources: [],
3284
3333
  tasks: [{
@@ -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-DidRk5le.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-B-1Dlzi3.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, ft as configSchema, mt as plainHttpAllowed, p as OPERATIONS } from "./chunk-DidRk5le.mjs";
2
- import { o as CliError, t as fetchCatalogVersion } from "./chunk-Bwz_FohV.mjs";
1
+ import { d as buildCatalogSnapshot, ft as configSchema, mt as plainHttpAllowed, p as OPERATIONS } from "./chunk-B-1Dlzi3.mjs";
2
+ import { o as CliError, t as fetchCatalogVersion } from "./chunk-BJFUtQhn.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, a as requestHashOf, bt as SLACK_BOT_SCOPES, 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 } from "./chunk-DidRk5le.mjs";
1
+ import { Q as ERRORS, a as requestHashOf, bt as SLACK_BOT_SCOPES, 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 } from "./chunk-B-1Dlzi3.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-Bwz_FohV.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-C8T8iXEN.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-BJFUtQhn.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-Bzr8W83d.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";
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-Bwz_FohV.mjs";
1
+ export { t as fetchCatalogVersion, n as fetchTokenStatus, r as requestOperation, i as requestSkillReload, a as requestTokenEnrollment } from "./chunk-BJFUtQhn.mjs";
package/dist/daemon.mjs CHANGED
@@ -1,15 +1,15 @@
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, St as VIAS, 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 SLACK_BOT_SCOPES, c as tokenRequestStatusSchema, d as buildCatalogSnapshot, dt as configBindings, f as roleCanUseOperation, ft as configSchema, gt as resolveWebOrigin, 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, xt as TASK_HOLDS, y as conversationRefSchema, yt as ITEM_KINDS, z as parseRingMarker } from "./chunk-DidRk5le.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, St as VIAS, 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 SLACK_BOT_SCOPES, c as tokenRequestStatusSchema, d as buildCatalogSnapshot, dt as configBindings, f as roleCanUseOperation, ft as configSchema, gt as resolveWebOrigin, 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, xt as TASK_HOLDS, y as conversationRefSchema, yt as ITEM_KINDS, z as parseRingMarker } from "./chunk-B-1Dlzi3.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";
5
5
  import { chmodSync, closeSync, existsSync, fchmodSync, fstatSync, fsyncSync, ftruncateSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
6
- import { homedir, hostname } from "node:os";
6
+ import { cpus, freemem, homedir, hostname, totalmem } from "node:os";
7
7
  import path, { basename, dirname, extname, isAbsolute, join, normalize, resolve } from "node:path";
8
8
  import { z } from "zod";
9
9
  import YAML from "yaml";
10
10
  import { spawn, spawnSync } from "node:child_process";
11
11
  import { parseEnv } from "node:util";
12
- import { lstat, readFile, readdir } from "node:fs/promises";
12
+ import { lstat, readFile, readdir, statfs } from "node:fs/promises";
13
13
  import Database from "better-sqlite3";
14
14
  import { Kysely, SqliteDialect, sql } from "kysely";
15
15
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -14185,6 +14185,113 @@ function blockRows(trx) {
14185
14185
  function turnRows(trx) {
14186
14186
  return trx.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").selectAll("turn").select(taskColumns).where("turn.role", "=", "operator");
14187
14187
  }
14188
+ // ../core/src/app/status-services.ts
14189
+ /** The daemon row is degraded after this long without a completed board tick. */
14190
+ const DAEMON_STALL_MS = 2 * BOARD_TICK_MS;
14191
+ /** Service of each source id prefix; sources with any other prefix get no services row. */
14192
+ const SOURCE_SERVICES = {
14193
+ github: "github",
14194
+ "github-issues": "github",
14195
+ spur: "spur",
14196
+ jira: "jira"
14197
+ };
14198
+ const STATE_RANK = {
14199
+ healthy: 0,
14200
+ degraded: 1,
14201
+ failing: 2
14202
+ };
14203
+ /** The latest or oldest of `values`, or null when any is null. */
14204
+ function pickTime(values, pick) {
14205
+ let chosen = null;
14206
+ for (const value of values) {
14207
+ if (value === null) return null;
14208
+ if (chosen === null || Date.parse(value) > Date.parse(chosen) === (pick === "latest")) chosen = value;
14209
+ }
14210
+ return chosen;
14211
+ }
14212
+ /** One source's health: failing when blind, degraded while not fully usable, else healthy. */
14213
+ function sourceHealth(source, config, now) {
14214
+ if (source.blindReason !== null) {
14215
+ const message = source.message === null ? "" : `: ${source.message}`;
14216
+ return {
14217
+ state: "failing",
14218
+ reason: `${source.source} blind (${source.blindReason})${message}`
14219
+ };
14220
+ }
14221
+ const degraded = (reason) => ({
14222
+ state: "degraded",
14223
+ reason
14224
+ });
14225
+ if (source.lastCompleteAt === null) return degraded(`${source.source} ${source.warmingUp ? "warming up" : "never completed"}`);
14226
+ if (source.stale) return degraded(`${source.source} stale`);
14227
+ if (source.warmingUp) return degraded(`${source.source} warming up`);
14228
+ const { budget } = source;
14229
+ 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}`);
14230
+ return {
14231
+ state: "healthy",
14232
+ reason: null
14233
+ };
14234
+ }
14235
+ /**
14236
+ * One health row per service: the daemon, each gateway (board-wide), then github, spur and jira
14237
+ * rolled up from the given sources only.
14238
+ */
14239
+ function services(input) {
14240
+ const { config, now, daemon } = input;
14241
+ const lastTick = daemon.lastDispatchAt ?? daemon.startedAt;
14242
+ const stalled = now - Date.parse(lastTick) > DAEMON_STALL_MS;
14243
+ const rows = [{
14244
+ service: "daemon",
14245
+ state: stalled ? "degraded" : "healthy",
14246
+ since: stalled ? null : daemon.startedAt,
14247
+ lastGoodAt: daemon.lastDispatchAt,
14248
+ reason: stalled ? `no board tick completed since ${lastTick}` : null
14249
+ }];
14250
+ for (const gateway of input.transport) {
14251
+ const ended = input.outageEnds.get(gateway.gateway);
14252
+ rows.push(gateway.state === "down" ? {
14253
+ service: gateway.gateway,
14254
+ state: "failing",
14255
+ since: gateway.since,
14256
+ lastGoodAt: null,
14257
+ reason: gateway.reason
14258
+ } : {
14259
+ service: gateway.gateway,
14260
+ state: "healthy",
14261
+ since: ended !== void 0 && Date.parse(ended) > Date.parse(daemon.startedAt) ? ended : daemon.startedAt,
14262
+ lastGoodAt: null,
14263
+ reason: null
14264
+ });
14265
+ }
14266
+ for (const service of [
14267
+ "github",
14268
+ "spur",
14269
+ "jira"
14270
+ ]) {
14271
+ const members = input.sources.filter((source) => SOURCE_SERVICES[source.source.split(":")[0] ?? ""] === service);
14272
+ if (members.length === 0) continue;
14273
+ const worst = members.map((source) => sourceHealth(source, config, now)).reduce((a, b) => STATE_RANK[b.state] > STATE_RANK[a.state] ? b : a);
14274
+ rows.push({
14275
+ service,
14276
+ state: worst.state,
14277
+ since: worst.state === "healthy" ? pickTime(members.map((source) => source.healthySince), "latest") : null,
14278
+ lastGoodAt: pickTime(members.map((source) => source.observedAt), "oldest"),
14279
+ reason: worst.reason
14280
+ });
14281
+ }
14282
+ return rows;
14283
+ }
14284
+ /** End of each gateway's last recorded outage: the clear time of its newest transport item. */
14285
+ async function readOutageEnds(db) {
14286
+ const items = await db.selectFrom("operator_item").select(["item_key", "cleared_at"]).where("item_key", "like", "transport:%").orderBy("raise_no").execute();
14287
+ const outageEnds = /* @__PURE__ */ new Map();
14288
+ for (const item of items) {
14289
+ const gateway = item.item_key.slice(10);
14290
+ if (item.cleared_at === null) outageEnds.delete(gateway);
14291
+ else outageEnds.set(gateway, item.cleared_at);
14292
+ }
14293
+ return outageEnds;
14294
+ }
14188
14295
  // ../core/src/app/status-views.ts
14189
14296
  /** Factual PR rollup; the caller owns snapshot freshness and all reads. */
14190
14297
  function summarizePr(fact, factAt, unconfirmed) {
@@ -14542,6 +14649,7 @@ async function getStatus(deps, options = {}) {
14542
14649
  resetAt: row.budget_reset_at
14543
14650
  } : null,
14544
14651
  stale: last === null || clock.now() - Date.parse(last) > config.thresholds.staleMultiplier * interval(config, source),
14652
+ healthySince: deps.healthySince?.get(source) ?? null,
14545
14653
  warmingUp: !completeSince.has(source)
14546
14654
  };
14547
14655
  });
@@ -14598,6 +14706,15 @@ async function getStatus(deps, options = {}) {
14598
14706
  warmingUp: sources.some((source) => source.warmingUp),
14599
14707
  spurUnavailable: spur?.blind_reason === null || spur === void 0 ? null : `Spur unavailable: ${spur.blind_message ?? spur.blind_reason}`,
14600
14708
  hostLoad: host?.value !== void 0 && host.value !== "null" ? "Host under load" : null,
14709
+ host: deps.host ?? null,
14710
+ services: services({
14711
+ config,
14712
+ now: clock.now(),
14713
+ daemon,
14714
+ transport,
14715
+ outageEnds: await readOutageEnds(store.db),
14716
+ sources
14717
+ }),
14601
14718
  transport,
14602
14719
  sources,
14603
14720
  tasks,
@@ -17519,7 +17636,9 @@ function createOperationRegistry(deps) {
17519
17636
  version: productVersion,
17520
17637
  startedAt,
17521
17638
  lastDispatchAt: lastDispatchAt()
17522
- }
17639
+ },
17640
+ healthySince: deps.healthySince,
17641
+ host: deps.hostMetrics?.()
17523
17642
  }, {
17524
17643
  project: input.project,
17525
17644
  visibleProjects: visibleProjects(config, actor),
@@ -18302,9 +18421,11 @@ async function recordUsage(trx, source, usage, now) {
18302
18421
  function createObservationCore(deps) {
18303
18422
  const { store, config, clock } = deps;
18304
18423
  const completeSince = /* @__PURE__ */ new Map();
18424
+ const healthySince = /* @__PURE__ */ new Map();
18305
18425
  const warnSkipped = warnSkippedOnce(deps.warn);
18306
18426
  return {
18307
18427
  completeSince,
18428
+ healthySince,
18308
18429
  warnSkipped,
18309
18430
  async context(source) {
18310
18431
  const state = await store.db.selectFrom("source_state").selectAll().where("source", "=", source).executeTakeFirst();
@@ -18538,10 +18659,12 @@ function createObservationCore(deps) {
18538
18659
  });
18539
18660
  });
18540
18661
  if (observation.effectiveComplete) completeSince.set(source, batch.observedAt);
18662
+ if (observation.state.blind !== void 0) healthySince.delete(source);
18663
+ else if (!healthySince.has(source)) healthySince.set(source, batch.observedAt);
18541
18664
  },
18542
- reportSourceState(source, state, usage) {
18665
+ async reportSourceState(source, state, usage) {
18543
18666
  const now = clock.now();
18544
- return scanTransaction(store, config, async (trx) => {
18667
+ await scanTransaction(store, config, async (trx) => {
18545
18668
  const wasBlind = await blindReason(trx, source);
18546
18669
  await sourceState(trx, source, state);
18547
18670
  await recordUsage(trx, source, usage, now);
@@ -18552,6 +18675,7 @@ function createObservationCore(deps) {
18552
18675
  });
18553
18676
  await reconcileItems(trx, config, now, completeSince.has("spur"), warnSkipped);
18554
18677
  });
18678
+ if (state.blind !== void 0) healthySince.delete(source);
18555
18679
  },
18556
18680
  notice(kind, value) {
18557
18681
  const at = new Date(clock.now()).toISOString();
@@ -22708,14 +22832,14 @@ function runSource(entry, options, runnerStartMs) {
22708
22832
  /** Drain synchronously on abort, before the adapter unwinds or stop waits for reports. */
22709
22833
  async function readSource(read, signal) {
22710
22834
  const takeUsage = adapter.takeUsage?.bind(adapter);
22711
- if (takeUsage === void 0) return untilAborted$1(read(), signal);
22835
+ if (takeUsage === void 0) return untilAborted$2(read(), signal);
22712
22836
  const onAbort = () => {
22713
22837
  const usage = takeUsage();
22714
22838
  if (usage !== void 0) report(usage, true);
22715
22839
  };
22716
22840
  signal.addEventListener("abort", onAbort, { once: true });
22717
22841
  try {
22718
- return await untilAborted$1(read(), signal);
22842
+ return await untilAborted$2(read(), signal);
22719
22843
  } finally {
22720
22844
  signal.removeEventListener("abort", onAbort);
22721
22845
  }
@@ -22899,7 +23023,7 @@ function runSource(entry, options, runnerStartMs) {
22899
23023
  let usage;
22900
23024
  let step = "context";
22901
23025
  try {
22902
- const received = await untilAborted$1(core.context(source), abort.signal);
23026
+ const received = await untilAborted$2(core.context(source), abort.signal);
22903
23027
  if (aborted() || received === void 0) return err(stoppedError);
22904
23028
  const own = ({ ref: held }) => held.number === ref.number && held.repo.toLowerCase() === ref.repo.toLowerCase();
22905
23029
  const feedbackCursors = received.feedbackCursors?.filter(own) ?? [];
@@ -23081,7 +23205,7 @@ function demandValue(batch, observedAt) {
23081
23205
  * for an adapter that ignores its signal. A late result or rejection is dropped. The abort
23082
23206
  * listener is removed once either side settles, so a retained signal holds nothing.
23083
23207
  */
23084
- function untilAborted$1(work, signal) {
23208
+ function untilAborted$2(work, signal) {
23085
23209
  let settle = () => void 0;
23086
23210
  const abortion = new Promise((resolve) => {
23087
23211
  settle = resolve;
@@ -24419,18 +24543,18 @@ function inInterval(ts, from, until) {
24419
24543
  const READ_WAIT_BUDGET_MS = 1e4;
24420
24544
  /** Least budget one retry costs, so a `Retry-After: 0` cannot retry forever. */
24421
24545
  const MIN_RETRY_CHARGE_MS = 1e3;
24422
- const ABORTED = Symbol("aborted");
24546
+ const ABORTED$1 = Symbol("aborted");
24423
24547
  /**
24424
24548
  * Settles with `promise`, or with `ABORTED` once `signal` aborts. The SDK call cannot be
24425
24549
  * cancelled, so a losing read is left to its own timeout and its outcome is dropped.
24426
24550
  */
24427
- function untilAborted(promise, signal) {
24551
+ function untilAborted$1(promise, signal) {
24428
24552
  if (signal === void 0) return promise;
24429
24553
  promise.catch(() => {});
24430
- if (signal.aborted) return Promise.resolve(ABORTED);
24554
+ if (signal.aborted) return Promise.resolve(ABORTED$1);
24431
24555
  const abort = Promise.withResolvers();
24432
24556
  const onAbort = () => {
24433
- abort.resolve(ABORTED);
24557
+ abort.resolve(ABORTED$1);
24434
24558
  };
24435
24559
  signal.addEventListener("abort", onAbort, { once: true });
24436
24560
  return Promise.race([promise, abort.promise]).finally(() => {
@@ -24445,9 +24569,9 @@ function untilAborted(promise, signal) {
24445
24569
  async function readThread(client, channel, threadTs, signal) {
24446
24570
  let budget = READ_WAIT_BUDGET_MS;
24447
24571
  for (;;) {
24448
- if (signal?.aborted === true) return ABORTED;
24572
+ if (signal?.aborted === true) return ABORTED$1;
24449
24573
  try {
24450
- return await untilAborted(readMessages(client, {
24574
+ return await untilAborted$1(readMessages(client, {
24451
24575
  channel,
24452
24576
  threadTs,
24453
24577
  signal
@@ -24476,8 +24600,8 @@ async function* recoverThreads(client, request, botIdentity, now, channels) {
24476
24600
  const from = request.since.getTime();
24477
24601
  if (!Number.isFinite(from) || from > until) return;
24478
24602
  const signal = request.signal;
24479
- const bot = await untilAborted(botIdentity(), signal);
24480
- if (bot === ABORTED) return;
24603
+ const bot = await untilAborted$1(botIdentity(), signal);
24604
+ if (bot === ABORTED$1) return;
24481
24605
  for (const conversation of request.conversations) {
24482
24606
  if (signal?.aborted === true) return;
24483
24607
  const addressed = parseRef(conversation.ref);
@@ -24496,7 +24620,7 @@ async function* recoverThreads(client, request, botIdentity, now, channels) {
24496
24620
  }
24497
24621
  throw error;
24498
24622
  }
24499
- if (history === ABORTED) return;
24623
+ if (history === ABORTED$1) return;
24500
24624
  const root = history.find((message) => messageTs(message) === addressed.threadTs);
24501
24625
  if (root === void 0) {
24502
24626
  yield gap(conversation.ref);
@@ -24844,6 +24968,136 @@ function createBoardModules(ctxFor, options = {}) {
24844
24968
  pollPr
24845
24969
  };
24846
24970
  }
24971
+ // ../daemon/src/host-metrics.ts
24972
+ /** Reads the host through `node:os` and `statfs(dataDir)`; `disk` rejects without `dataDir`. */
24973
+ function createHostProbe(dataDir) {
24974
+ return {
24975
+ cpuTimes() {
24976
+ let idle = 0;
24977
+ let total = 0;
24978
+ for (const { times } of cpus()) {
24979
+ idle += times.idle;
24980
+ total += times.user + times.nice + times.sys + times.idle + times.irq;
24981
+ }
24982
+ return {
24983
+ idle,
24984
+ total
24985
+ };
24986
+ },
24987
+ memory: () => ({
24988
+ totalBytes: totalmem(),
24989
+ availableBytes: freemem()
24990
+ }),
24991
+ async disk() {
24992
+ if (dataDir === void 0) throw new Error("No data directory to measure");
24993
+ const { blocks, bfree, bavail, bsize } = await statfs(dataDir);
24994
+ return {
24995
+ blocks,
24996
+ bfree,
24997
+ bavail,
24998
+ bsize
24999
+ };
25000
+ }
25001
+ };
25002
+ }
25003
+ const HOST_SAMPLE_MS = 3e4;
25004
+ const ABORTED = Symbol("aborted");
25005
+ /** One decimal, kept within 0..100. */
25006
+ function percent(value) {
25007
+ return Math.min(100, Math.max(0, Math.round(value * 10) / 10));
25008
+ }
25009
+ /**
25010
+ * Settles with the promise's outcome, or with `ABORTED` once `signal` aborts. It always handles
25011
+ * the promise, so an abandoned read that rejects later is no unhandled rejection.
25012
+ */
25013
+ function untilAborted(promise, signal) {
25014
+ return new Promise((resolve) => {
25015
+ const onAbort = () => {
25016
+ resolve(ABORTED);
25017
+ };
25018
+ signal.addEventListener("abort", onAbort, { once: true });
25019
+ if (signal.aborted) onAbort();
25020
+ promise.then((value) => {
25021
+ resolve({ value });
25022
+ }, (error) => {
25023
+ resolve({ error });
25024
+ }).finally(() => {
25025
+ signal.removeEventListener("abort", onAbort);
25026
+ });
25027
+ });
25028
+ }
25029
+ /**
25030
+ * Samples the host every `intervalMs` (first run in the background) and keeps the last sample;
25031
+ * `read` never samples. A metric whose read fails is null, with one warning per metric. Stop
25032
+ * aborts a pending disk read instead of waiting for it, and that run writes nothing.
25033
+ */
25034
+ function createHostSampler(options) {
25035
+ const { probe, clock, log, intervalMs = HOST_SAMPLE_MS } = options;
25036
+ let last = null;
25037
+ let previousCpu;
25038
+ const warned = /* @__PURE__ */ new Set();
25039
+ const failed = (metric, err) => {
25040
+ if (warned.has(metric)) return;
25041
+ warned.add(metric);
25042
+ log.warn({ err }, `host ${metric} unreadable`);
25043
+ };
25044
+ const attempt = (metric, read) => {
25045
+ try {
25046
+ return read();
25047
+ } catch (err) {
25048
+ failed(metric, err);
25049
+ return null;
25050
+ }
25051
+ };
25052
+ const sample = async (signal) => {
25053
+ if (signal.aborted) return;
25054
+ const sampledAt = new Date(clock.now()).toISOString();
25055
+ const cpu = attempt("cpu", () => probe.cpuTimes());
25056
+ const before = previousCpu;
25057
+ previousCpu = cpu ?? void 0;
25058
+ const cpuPercent = cpu === null || before === void 0 || cpu.total <= before.total ? null : percent(100 * (1 - (cpu.idle - before.idle) / (cpu.total - before.total)));
25059
+ const mem = attempt("memory", () => probe.memory());
25060
+ const read = await untilAborted((async () => probe.disk())(), signal);
25061
+ if (read === ABORTED) return;
25062
+ if ("error" in read) failed("disk", read.error);
25063
+ const fs = "value" in read ? read.value : null;
25064
+ const used = fs === null ? 0 : (fs.blocks - fs.bfree) * fs.bsize;
25065
+ const available = fs === null ? 0 : fs.bavail * fs.bsize;
25066
+ last = {
25067
+ sampledAt,
25068
+ cpuPercent,
25069
+ memory: mem === null ? null : {
25070
+ totalBytes: mem.totalBytes,
25071
+ availableBytes: mem.availableBytes,
25072
+ usedPercent: mem.totalBytes > 0 ? percent(100 * (mem.totalBytes - mem.availableBytes) / mem.totalBytes) : 0
25073
+ },
25074
+ disk: fs === null ? null : {
25075
+ totalBytes: fs.blocks * fs.bsize,
25076
+ availableBytes: available,
25077
+ usedPercent: used + available > 0 ? percent(100 * used / (used + available)) : 0
25078
+ }
25079
+ };
25080
+ };
25081
+ const own = new AbortController();
25082
+ const job = createJob({
25083
+ run: (signal) => sample(AbortSignal.any([signal, own.signal])),
25084
+ intervalMs,
25085
+ first: "background",
25086
+ onError: (err) => {
25087
+ log.error({ err }, "host sample failed");
25088
+ }
25089
+ });
25090
+ return {
25091
+ module: {
25092
+ start: (signal) => job.start(signal),
25093
+ async stop() {
25094
+ own.abort();
25095
+ await job.stop();
25096
+ }
25097
+ },
25098
+ read: () => last
25099
+ };
25100
+ }
24847
25101
  // ../daemon/src/spur-port.ts
24848
25102
  const SEND_TIMEOUT_MS = 8e3;
24849
25103
  const ERROR_TEXT_LIMIT = 200;
@@ -25745,12 +25999,20 @@ function createDaemonModules(ctxFor, ports = {}) {
25745
25999
  ctx.log.error({ err }, work === "connection" ? "slack connection event failed" : "slack envelope failed");
25746
26000
  }
25747
26001
  }));
26002
+ const hostCtx = ctxFor("host-metrics");
26003
+ const host = createHostSampler({
26004
+ probe: ports.hostProbe ?? createHostProbe(ports.dataDir),
26005
+ clock: hostCtx.clock,
26006
+ log: hostCtx.log
26007
+ });
25748
26008
  let webPort;
25749
26009
  let lastDispatchAt = null;
25750
26010
  const registry = createOperationRegistry({
25751
26011
  config: board.config,
25752
26012
  clock: board.clock,
25753
26013
  completeSince: core.completeSince,
26014
+ healthySince: core.healthySince,
26015
+ hostMetrics: () => host.read(),
25754
26016
  gateways: gateway === void 0 ? [] : [gateway.kind],
25755
26017
  reapplyInbound: () => inbound?.reapply,
25756
26018
  prPoller: () => boardModules.pollPr,
@@ -25767,29 +26029,37 @@ function createDaemonModules(ctxFor, ports = {}) {
25767
26029
  });
25768
26030
  const commands = ctxFor("commands");
25769
26031
  const tokenRequests = ctxFor("token-requests");
25770
- const entries = [{
25771
- name: "commands",
25772
- stopStage: "final",
25773
- module: createJob({
25774
- run: () => purgeExpiredCommands(commands.store, commands.clock, commands.config.commands.retentionDays),
25775
- intervalMs: DAY_MS,
25776
- first: "await",
25777
- onError: (err) => {
25778
- commands.log.error({ err }, "command purge failed");
25779
- }
25780
- })
25781
- }, {
25782
- name: "token-requests",
25783
- stopStage: "final",
25784
- module: createJob({
25785
- run: () => purgeEndedTokenRequests(tokenRequests.store, new Date(tokenRequests.clock.now())),
25786
- intervalMs: DAY_MS,
25787
- first: "background",
25788
- onError: (err) => {
25789
- tokenRequests.log.error({ err }, "token request purge failed");
25790
- }
25791
- })
25792
- }];
26032
+ const entries = [
26033
+ {
26034
+ name: "commands",
26035
+ stopStage: "final",
26036
+ module: createJob({
26037
+ run: () => purgeExpiredCommands(commands.store, commands.clock, commands.config.commands.retentionDays),
26038
+ intervalMs: DAY_MS,
26039
+ first: "await",
26040
+ onError: (err) => {
26041
+ commands.log.error({ err }, "command purge failed");
26042
+ }
26043
+ })
26044
+ },
26045
+ {
26046
+ name: "token-requests",
26047
+ stopStage: "final",
26048
+ module: createJob({
26049
+ run: () => purgeEndedTokenRequests(tokenRequests.store, new Date(tokenRequests.clock.now())),
26050
+ intervalMs: DAY_MS,
26051
+ first: "background",
26052
+ onError: (err) => {
26053
+ tokenRequests.log.error({ err }, "token request purge failed");
26054
+ }
26055
+ })
26056
+ },
26057
+ {
26058
+ name: "host-metrics",
26059
+ stopStage: "pollers",
26060
+ module: host.module
26061
+ }
26062
+ ];
25793
26063
  const boardModules = createBoardModules(ctxFor, {
25794
26064
  core,
25795
26065
  ...ports.startAdapters === void 0 ? {} : { startAdapters: ports.startAdapters },
@@ -25917,8 +26187,9 @@ function processPort() {
25917
26187
  async function main() {
25918
26188
  setInterval(() => void 0, KEEPALIVE_MS);
25919
26189
  const productVersion = publishedVersion();
26190
+ const paths = resolvePaths(process.env, homedir());
25920
26191
  await runDaemon({
25921
- paths: resolvePaths(process.env, homedir()),
26192
+ paths,
25922
26193
  acquireLock,
25923
26194
  loadConfig: (paths) => {
25924
26195
  const loaded = loadConfig(paths);
@@ -25928,6 +26199,7 @@ async function main() {
25928
26199
  openStore,
25929
26200
  modules: (ctxFor) => createDaemonModules(ctxFor, {
25930
26201
  productVersion,
26202
+ dataDir: dirname(paths.dbFile),
25931
26203
  systemd: {
25932
26204
  env: process.env,
25933
26205
  pid: process.pid