spur-board 0.15.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { H as requiredSecretKeys, N as ERRORS, U as SLACK_BOT_SCOPES, V as configSchema, c as roleCanUseOperation, l as OPERATIONS, n as SYSTEMD_SERVICE_SETTINGS } from "./src-eVAzSAsk.mjs";
2
- import { a as errorExitCode, i as CliError, n as requestOperation, o as renderCliError, r as requestTokenEnrollment, s as escapeTerminalControls } from "./client-FoFGbc11.mjs";
3
- import { a as memoryVerdictCache, c as loadEnrollmentConfig, i as fileVerdictCache, l as readConfiguredPort, n as cliPackageVersion, o as configFile, s as loadClientConfig, t as checkCatalog, u as resolveDaemonAddress } from "./config-6Nm4MFGe.mjs";
1
+ import { G as SLACK_BOT_SCOPES, P as ERRORS, U as configSchema, W as requiredSecretKeys, l as roleCanUseOperation, r as SYSTEMD_SERVICE_SETTINGS, u as OPERATIONS } from "./src-ep5scuVt.mjs";
2
+ import { a as errorExitCode, i as CliError, n as requestOperation, o as renderCliError, r as requestTokenEnrollment, s as escapeTerminalControls } from "./client-CwKmG23X.mjs";
3
+ import { a as memoryVerdictCache, c as loadEnrollmentConfig, i as fileVerdictCache, l as readConfiguredPort, n as cliPackageVersion, o as configFile, s as loadClientConfig, t as checkCatalog, u as resolveDaemonAddress } from "./config-CXDupHSC.mjs";
4
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
5
5
  import { chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
6
  import { homedir, hostname, userInfo } from "node:os";
@@ -1,4 +1,4 @@
1
- import { F as errorEnvelopeSchema, I as successEnvelopeSchema, N as ERRORS, P as errorContextSchema, d as renderJsonError } from "./src-eVAzSAsk.mjs";
1
+ import { F as errorContextSchema, I as errorEnvelopeSchema, L as successEnvelopeSchema, P as ERRORS, f as renderJsonError } from "./src-ep5scuVt.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
package/dist/client.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as requestOperation, r as requestTokenEnrollment, t as fetchCatalogVersion } from "./client-FoFGbc11.mjs";
1
+ import { n as requestOperation, r as requestTokenEnrollment, t as fetchCatalogVersion } from "./client-CwKmG23X.mjs";
2
2
  export { fetchCatalogVersion, requestOperation, requestTokenEnrollment };
@@ -1,5 +1,5 @@
1
- import { L as DEFAULT_HTTP_PORT, V as configSchema, l as OPERATIONS, s as buildCatalogSnapshot } from "./src-eVAzSAsk.mjs";
2
- import { i as CliError, t as fetchCatalogVersion } from "./client-FoFGbc11.mjs";
1
+ import { R as DEFAULT_HTTP_PORT, U as configSchema, c as buildCatalogSnapshot, u as OPERATIONS } from "./src-ep5scuVt.mjs";
2
+ import { i as CliError, t as fetchCatalogVersion } from "./client-CwKmG23X.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/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as parseActorId, B as RESERVED_PROJECT, C as prFactsSchema, D as actorIdSchema, E as ticketFactsSchema, H as requiredSecretKeys, I as successEnvelopeSchema, M as taskKeySchema, N as ERRORS, O as encodeActorId, S as SESSION_STATUSES, T as sessionFactsSchema, U as SLACK_BOT_SCOPES, V as configSchema, _ as messageRefSchema, a as entityRefSchema, b as eventPayloadSchemas, c as roleCanUseOperation, g as interactionRefSchema, h as inboundEventSchema, i as batchSchema, j as parseRef$1, k as errorCodeOf, l as OPERATIONS, m as conversationRefSchema, o as sourceCursorSchema, p as SPACE_IDS, r as AdapterError, s as buildCatalogSnapshot, t as BOARD_TICK_MS, u as renderHttpProblem, v as userIdSchema, w as prRefSchema, x as SESSION_HEALTH_STATES, y as EVENT_KINDS, z as DEFAULT_SLACK_COMMAND } from "./src-eVAzSAsk.mjs";
1
+ import { A as errorCodeOf, C as SESSION_STATUSES, D as ticketFactsSchema, E as sessionFactsSchema, G as SLACK_BOT_SCOPES, H as RESERVED_PROJECT, L as successEnvelopeSchema, M as parseRef$1, N as taskKeySchema, O as actorIdSchema, P as ERRORS, S as SESSION_HEALTH_STATES, T as prRefSchema, U as configSchema, V as DEFAULT_SLACK_COMMAND, W as requiredSecretKeys, _ as interactionRefSchema, a as batchSchema, b as EVENT_KINDS, c as buildCatalogSnapshot, d as renderHttpProblem, g as inboundEventSchema, h as conversationRefSchema, i as AdapterError, j as parseActorId, k as encodeActorId, l as roleCanUseOperation, m as SPACE_IDS, n as BOARD_TICK_MS, o as entityRefSchema, s as sourceCursorSchema, t as assertNever, u as OPERATIONS, v as messageRefSchema, w as prFactsSchema, x as eventPayloadSchemas, y as userIdSchema, z as DEFAULT_LINK } from "./src-ep5scuVt.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { closeSync, existsSync, fstatSync, ftruncateSync, mkdirSync, openSync, readFileSync, readdirSync, writeSync } from "node:fs";
@@ -8778,13 +8778,25 @@ async function journalToken(trx, kind, name, at) {
8778
8778
  request_id: null
8779
8779
  }).execute();
8780
8780
  }
8781
+ /** Lapse one pending request: journal it once and clear its approval item. */
8782
+ async function expireToken(trx, row, at) {
8783
+ await trx.updateTable("operator_token").set({
8784
+ status: "expired",
8785
+ decided_at: at.toISOString()
8786
+ }).where("id", "=", row.id).execute();
8787
+ await journalToken(trx, "token_expired", row.name, at);
8788
+ await clearItem(trx, row.item_id, at);
8789
+ }
8781
8790
  /** Register a hash and its approval item together. The raw file secret never reaches this app. */
8782
8791
  async function requestToken(store, input, at) {
8783
8792
  if (!/^[0-9a-f]{64}$/.test(input.hash) || input.name.trim() === "" || input.folder.trim() === "") throw new CommandError("usage", "Provide a name, folder and SHA-256 token hash.");
8784
8793
  const expiresAt = new Date(at.getTime() + REQUEST_LIFETIME_MS).toISOString();
8785
8794
  return scanTransaction(store, async (trx) => {
8786
- if (await trx.selectFrom("operator_token").select("id").where("name", "=", input.name).executeTakeFirst() !== void 0) throw new CommandError("usage", "Choose a new token name.");
8795
+ const existing = await trx.selectFrom("operator_token").selectAll().where("name", "=", input.name).executeTakeFirst();
8796
+ const status = existing === void 0 ? void 0 : effectiveStatus(existing, at);
8797
+ if (status === "pending" || status === "approved" || status === "revoked") throw new CommandError("usage", `Token name ${input.name} is taken; choose another name (see \`board token list\`).`);
8787
8798
  if ((await trx.selectFrom("operator_token").select("id").where("status", "=", "pending").where("expires_at", ">", at.toISOString()).limit(MAX_PENDING_REQUESTS).execute()).length >= MAX_PENDING_REQUESTS) throw new CommandError("usage", "Too many token requests are awaiting approval.");
8799
+ if (existing?.status === "pending") await expireToken(trx, existing, at);
8788
8800
  const item = await raiseItem(trx, {
8789
8801
  itemKey: `token:${input.name}`,
8790
8802
  kind: "token_request",
@@ -8794,8 +8806,7 @@ async function requestToken(store, input, at) {
8794
8806
  blockId: null,
8795
8807
  at
8796
8808
  });
8797
- await trx.insertInto("operator_token").values({
8798
- name: input.name,
8809
+ const values = {
8799
8810
  hash: input.hash,
8800
8811
  folder: input.folder,
8801
8812
  host: input.host,
@@ -8804,7 +8815,12 @@ async function requestToken(store, input, at) {
8804
8815
  expires_at: expiresAt,
8805
8816
  decided_at: null,
8806
8817
  item_id: item.id
8818
+ };
8819
+ if (existing === void 0) await trx.insertInto("operator_token").values({
8820
+ name: input.name,
8821
+ ...values
8807
8822
  }).execute();
8823
+ else await trx.updateTable("operator_token").set(values).where("id", "=", existing.id).execute();
8808
8824
  await journalToken(trx, "token_requested", input.name, at);
8809
8825
  return {
8810
8826
  name: input.name,
@@ -8819,14 +8835,7 @@ async function decideTokenInTransaction(trx, itemId, decision, at) {
8819
8835
  if (row === void 0) throw new CommandError("not_found", "Token request was not found.");
8820
8836
  const status = effectiveStatus(row, at);
8821
8837
  if (status !== "pending") {
8822
- if (status === "expired" && row.status === "pending") {
8823
- await trx.updateTable("operator_token").set({
8824
- status: "expired",
8825
- decided_at: at.toISOString()
8826
- }).where("id", "=", row.id).execute();
8827
- await journalToken(trx, "token_expired", row.name, at);
8828
- await clearItem(trx, row.item_id, at);
8829
- }
8838
+ if (status === "expired" && row.status === "pending") await expireToken(trx, row, at);
8830
8839
  return {
8831
8840
  name: row.name,
8832
8841
  status
@@ -8854,14 +8863,7 @@ async function expirePendingTokens(store, at) {
8854
8863
  "name",
8855
8864
  "item_id"
8856
8865
  ]).where("status", "=", "pending").where("expires_at", "<=", expiresAt).execute();
8857
- for (const row of rows) {
8858
- await trx.updateTable("operator_token").set({
8859
- status: "expired",
8860
- decided_at: expiresAt
8861
- }).where("id", "=", row.id).execute();
8862
- await journalToken(trx, "token_expired", row.name, at);
8863
- await clearItem(trx, row.item_id, at);
8864
- }
8866
+ for (const row of rows) await expireToken(trx, row, at);
8865
8867
  return rows.length;
8866
8868
  });
8867
8869
  }
@@ -10766,6 +10768,8 @@ function taskState(ticket, prs, sessions) {
10766
10768
  function issuesRepo(project) {
10767
10769
  return project?.tracker.type === "github-issues" ? project.tracker.repo.toLowerCase() : null;
10768
10770
  }
10771
+ /** Unlinked PRs and sessions finished longer ago than this are counted, not listed. */
10772
+ const UNLINKED_WINDOW_MS = 10080 * 60 * 1e3;
10769
10773
  function interval(config, source) {
10770
10774
  if (source === "spur") return config.adapters.spur.intervalMs;
10771
10775
  if (source.startsWith("jira:")) return config.adapters.jira.intervalMs;
@@ -10827,6 +10831,7 @@ async function getStatus(deps, options = {}) {
10827
10831
  } : {}
10828
10832
  });
10829
10833
  }
10834
+ const pastWindow = (at) => clock.now() - Date.parse(at) > UNLINKED_WINDOW_MS;
10830
10835
  const allPrs = await store.db.selectFrom("pr_snapshot").selectAll().execute();
10831
10836
  const allSessions = await store.db.selectFrom("session_snapshot").selectAll().execute();
10832
10837
  const allLinks = await store.db.selectFrom("link").selectAll().where("banned", "=", 0).execute();
@@ -10840,8 +10845,12 @@ async function getStatus(deps, options = {}) {
10840
10845
  if (facts.ticketKeys.length === 0) return "no key in branch or title by the link rules";
10841
10846
  return facts.ticketKeys.some((key) => rows.some((task) => task.project === project.id && task.key === key)) ? void 0 : `no task on the board for ${facts.ticketKeys.join(", ")}`;
10842
10847
  };
10843
- const unlinkedPrs = allPrs.filter((pr) => projects.some((project) => project.repos.some((repo) => repo.toLowerCase() === pr.repo.toLowerCase())) && !allLinks.some((link) => link.entity === "pr" && link.repo?.toLowerCase() === pr.repo.toLowerCase() && link.number === pr.number)).map((pr) => {
10844
- const facts = parseJson(prFactsSchema, pr.detail);
10848
+ const prRows = allPrs.filter((pr) => projects.some((project) => project.repos.some((repo) => repo.toLowerCase() === pr.repo.toLowerCase())) && !allLinks.some((link) => link.entity === "pr" && link.repo?.toLowerCase() === pr.repo.toLowerCase() && link.number === pr.number)).map((pr) => ({
10849
+ pr,
10850
+ facts: parseJson(prFactsSchema, pr.detail)
10851
+ }));
10852
+ const hiddenPr = (facts) => facts.state !== "open" && pastWindow(facts.updatedAt);
10853
+ const unlinkedPrs = prRows.filter(({ facts }) => !hiddenPr(facts)).map(({ pr, facts }) => {
10845
10854
  const reason = unlinkedReason(pr.source, facts);
10846
10855
  const why = reason === void 0 ? {} : { reason };
10847
10856
  if (detail) return {
@@ -10859,7 +10868,12 @@ async function getStatus(deps, options = {}) {
10859
10868
  ...why
10860
10869
  };
10861
10870
  });
10862
- const unlinkedSessions = allSessions.filter((session) => projects.some((project) => project.spurProjects.some((spur) => spur.name === session.spur_project)) && !allLinks.some((link) => link.entity === "session" && link.session_id === session.id)).map((session) => {
10871
+ const sessionRows = allSessions.filter((session) => projects.some((project) => project.spurProjects.some((spur) => spur.name === session.spur_project)) && !allLinks.some((link) => link.entity === "session" && link.session_id === session.id));
10872
+ /** Ended, or omitted by complete Spur polls, for longer than the window. */
10873
+ const hiddenSession = (session) => {
10874
+ return (session.ended_at !== null || session.state === "completed" || session.state === "killed" || session.absent_since !== null) && pastWindow(session.ended_at ?? session.absent_since ?? session.last_seen);
10875
+ };
10876
+ const unlinkedSessions = sessionRows.filter((session) => !hiddenSession(session)).map((session) => {
10863
10877
  const facts = parseJson(sessionFactsSchema, session.detail);
10864
10878
  if (detail) return sessionView(facts);
10865
10879
  const { id, spurProject, branch, lifecycle, health } = facts;
@@ -10935,7 +10949,9 @@ async function getStatus(deps, options = {}) {
10935
10949
  sources,
10936
10950
  tasks,
10937
10951
  unlinkedPrs,
10938
- unlinkedSessions
10952
+ unlinkedSessions,
10953
+ hiddenUnlinkedPrs: prRows.length - unlinkedPrs.length,
10954
+ hiddenUnlinkedSessions: sessionRows.length - unlinkedSessions.length
10939
10955
  };
10940
10956
  }
10941
10957
  //#endregion
@@ -11853,7 +11869,8 @@ async function session(trx, config, fact, at, source, ambiguousBranches) {
11853
11869
  end_reason: fact.endReason,
11854
11870
  detail: toJson(sessionFactsSchema, fact),
11855
11871
  source,
11856
- observed_at: at
11872
+ observed_at: at,
11873
+ absent_since: null
11857
11874
  }).onConflict((oc) => oc.column("id").doUpdateSet({
11858
11875
  branch: fact.branch,
11859
11876
  pr: fact.pr === null ? null : `${fact.pr.repo}#${String(fact.pr.number)}`,
@@ -11864,7 +11881,8 @@ async function session(trx, config, fact, at, source, ambiguousBranches) {
11864
11881
  end_reason: fact.endReason,
11865
11882
  detail: toJson(sessionFactsSchema, fact),
11866
11883
  source,
11867
- observed_at: at
11884
+ observed_at: at,
11885
+ absent_since: null
11868
11886
  })).execute();
11869
11887
  let key;
11870
11888
  let role;
@@ -12044,6 +12062,7 @@ function createObservationCore(deps) {
12044
12062
  await emit(trx, "session_facts_changed", task.project, task.id, batch.observedAt, { facts: ended });
12045
12063
  }
12046
12064
  }
12065
+ if (observation.effectiveComplete) await trx.updateTable("session_snapshot").set({ absent_since: batch.observedAt }).where("source", "=", source).where("absent_since", "is", null).where("last_seen", "<", batch.observedAt).execute();
12047
12066
  if (observation.effectiveComplete) {
12048
12067
  const project = config.projects.find((entry) => trackerSource(entry) === source);
12049
12068
  if (project !== void 0) {
@@ -12280,7 +12299,7 @@ function commandReply(id, value, input) {
12280
12299
  line(`Board status: ${String(status.tasks.length)} tasks, ${String(status.items.length)} items needing attention.`),
12281
12300
  ...status.tasks.map((task) => line(`${task.key}: ${task.column} (${task.membership})`)),
12282
12301
  ...status.items.map((item) => line(`${item.key}: ${item.summary}`)),
12283
- line(`Unlinked: ${String(status.unlinkedPrs.length)} pull requests, ${String(status.unlinkedSessions.length)} sessions.`),
12302
+ line(`Unlinked: ${String(status.unlinkedPrs.length)} pull requests, ${String(status.unlinkedSessions.length)} sessions${status.hiddenUnlinkedPrs + status.hiddenUnlinkedSessions === 0 ? "" : `; ${String(status.hiddenUnlinkedPrs)} pull requests and ${String(status.hiddenUnlinkedSessions)} sessions finished over 7 days ago are hidden`}.`),
12284
12303
  ...status.sources.map((source) => line(`${source.source}: ${source.blindReason !== null ? `blind (${source.blindReason})` : source.warmingUp ? "warming up" : source.stale ? "stale" : "current"}`)),
12285
12304
  ...status.warmingUp ? [line("Sources are warming up.")] : [],
12286
12305
  ...status.spurUnavailable === null ? [] : [line(status.spurUnavailable)],
@@ -13555,6 +13574,36 @@ function issuesRule(repo, link) {
13555
13574
  title: new RegExp(link.titlePattern)
13556
13575
  };
13557
13576
  }
13577
+ function jiraRule(prefixes, link) {
13578
+ const sources = link.sources.length === DEFAULT_LINK.sources.length && link.sources.every((source, i) => source === DEFAULT_LINK.sources[i]);
13579
+ const branch = link.branchPattern === DEFAULT_LINK.branchPattern;
13580
+ const title = link.titlePattern === DEFAULT_LINK.titlePattern;
13581
+ if (sources && branch && title) return {
13582
+ type: "prefixes",
13583
+ prefixes
13584
+ };
13585
+ return {
13586
+ type: "jira",
13587
+ prefixes,
13588
+ sources: link.sources.filter((source) => source !== "closing"),
13589
+ branch: branch ? void 0 : new RegExp(link.branchPattern),
13590
+ title: title ? void 0 : new RegExp(link.titlePattern)
13591
+ };
13592
+ }
13593
+ /**
13594
+ * The key rule of `repo` in a project: the github-issues tracker repo reads issue numbers by
13595
+ * `link`, its other repos link nothing, and a Jira project's repos read `projectKeys` keys.
13596
+ */
13597
+ function projectKeyRule(tracker, link, repo) {
13598
+ switch (tracker.type) {
13599
+ case "github-issues": return tracker.repo.toLowerCase() === repo.toLowerCase() ? issuesRule(tracker.repo, link) : {
13600
+ type: "prefixes",
13601
+ prefixes: []
13602
+ };
13603
+ case "jira": return jiraRule(tracker.projectKeys, link);
13604
+ default: return assertNever(tracker);
13605
+ }
13606
+ }
13558
13607
  /** Drops denied (null) nodes and nodes without a repository. */
13559
13608
  function closingRefs(wire) {
13560
13609
  return (wire?.nodes ?? []).flatMap((node) => node?.repository ? [{
@@ -13624,9 +13673,12 @@ function latestReviews(nodes) {
13624
13673
  return [...latest.values()].sort((a, b) => a.reviewer.localeCompare(b.reviewer));
13625
13674
  }
13626
13675
  function ticketKeys(title, branch, prefixes) {
13676
+ return scanKeys(`${title} ${branch}`, prefixes);
13677
+ }
13678
+ function scanKeys(text, prefixes) {
13627
13679
  const keys = /* @__PURE__ */ new Set();
13628
13680
  const allowed = new Set(prefixes);
13629
- for (const match of `${title} ${branch}`.matchAll(/(?<![A-Za-z0-9_])([A-Z][A-Z0-9_]*)-([1-9][0-9]*)(?![A-Za-z0-9_])/gi)) {
13681
+ for (const match of text.matchAll(/(?<![A-Za-z0-9_])([A-Z][A-Z0-9_]*)-([1-9][0-9]*)(?![A-Za-z0-9_])/gi)) {
13630
13682
  const prefix = match[1]?.toUpperCase();
13631
13683
  const number = match[2];
13632
13684
  if (prefix !== void 0 && number !== void 0 && allowed.has(prefix)) keys.add(`${prefix}-${number}`);
@@ -13654,6 +13706,32 @@ function issueKeys(title, branch, refs, rule) {
13654
13706
  }
13655
13707
  return [];
13656
13708
  }
13709
+ const JIRA_KEY = /^([A-Z][A-Z0-9_]*)-[1-9][0-9]*$/;
13710
+ function matchedKey(text, pattern, prefixes) {
13711
+ if (text.length > MAX_MATCHED_LENGTH) return [];
13712
+ const key = pattern.exec(text)?.[1]?.toUpperCase();
13713
+ if (key === void 0) return [];
13714
+ const prefix = JIRA_KEY.exec(key)?.[1];
13715
+ return prefix !== void 0 && prefixes.includes(prefix) ? [key] : [];
13716
+ }
13717
+ function jiraKeys(title, branch, rule) {
13718
+ for (const source of rule.sources) {
13719
+ const text = source === "branch" ? branch : title;
13720
+ const pattern = rule[source];
13721
+ const keys = pattern === void 0 ? scanKeys(text, rule.prefixes) : matchedKey(text, pattern, rule.prefixes);
13722
+ if (keys.length > 0) return keys;
13723
+ }
13724
+ return [];
13725
+ }
13726
+ /** The task keys `rule` reads from a PR's title, head branch and closing references. */
13727
+ function prKeys(rule, title, branch, refs) {
13728
+ switch (rule.type) {
13729
+ case "prefixes": return ticketKeys(title, branch, rule.prefixes);
13730
+ case "issues": return issueKeys(title, branch, refs, rule);
13731
+ case "jira": return jiraKeys(title, branch, rule);
13732
+ default: return assertNever(rule);
13733
+ }
13734
+ }
13657
13735
  function normalizePr(repo, value, rule) {
13658
13736
  const wire = parseWire(prWire, value, "Malformed GitHub PR response");
13659
13737
  const checks = latestChecks(wire.statusCheckRollup?.contexts.nodes ?? []);
@@ -13690,7 +13768,7 @@ function normalizePr(repo, value, rule) {
13690
13768
  reviewer: node.requestedReviewer.login ?? node.requestedReviewer.name,
13691
13769
  asCodeOwner: node.asCodeOwner
13692
13770
  })),
13693
- ticketKeys: rule.type === "prefixes" ? ticketKeys(title, headBranch, rule.prefixes) : issueKeys(title, headBranch, closingRefs(wire.closingIssuesReferences), rule),
13771
+ ticketKeys: prKeys(rule, title, headBranch, closingRefs(wire.closingIssuesReferences)),
13694
13772
  updatedAt: wire.updatedAt
13695
13773
  };
13696
13774
  const parsed = prFactsSchema.safeParse(facts);
@@ -13718,12 +13796,6 @@ function sourceId(project, repo) {
13718
13796
  function githubSources(config, options) {
13719
13797
  const sources = [];
13720
13798
  for (const project of config.projects) {
13721
- const tracker = project.tracker;
13722
- const issues = tracker.type === "github-issues" ? issuesRule(tracker.repo, project.link) : void 0;
13723
- const prefixes = {
13724
- type: "prefixes",
13725
- prefixes: tracker.type === "jira" ? tracker.projectKeys : []
13726
- };
13727
13799
  const seen = /* @__PURE__ */ new Set();
13728
13800
  for (const repo of project.repos) {
13729
13801
  const normalized = repo.toLowerCase();
@@ -13731,7 +13803,7 @@ function githubSources(config, options) {
13731
13803
  seen.add(normalized);
13732
13804
  const id = sourceId(project.id, repo);
13733
13805
  const client = new GithubClient(options.token, options.fetch);
13734
- const keys = issues?.repo.toLowerCase() === normalized ? issues : prefixes;
13806
+ const keys = projectKeyRule(project.tracker, project.link, repo);
13735
13807
  sources.push({
13736
13808
  repo,
13737
13809
  reserveRemaining: config.github.reserveRemaining,
@@ -15070,25 +15142,26 @@ function sampleQuery(closing) {
15070
15142
  }
15071
15143
  /**
15072
15144
  * Matches up to 10 of the operator's most recently updated open or merged PRs in `repo` (among
15073
- * the last 50) against `link`. A denied closing reference is dropped, as the poller does; any
15074
- * other GraphQL error rejects with a transient `AdapterError`.
15145
+ * the last 50) against the key rule `tracker` and `link` give that repo. A denied closing
15146
+ * reference is dropped, as the poller does; any other GraphQL error rejects with a transient
15147
+ * `AdapterError`.
15075
15148
  */
15076
- async function sampleLinkRules({ repo, login, link }, { token, fetch: fetcher, signal }) {
15149
+ async function sampleLinkRules({ repo, login, tracker, link }, { token, fetch: fetcher, signal }) {
15077
15150
  const [owner, name] = repo.split("/");
15078
15151
  if (!owner || !name) throw new AdapterError("config", "Invalid repository");
15079
- const closing = link.sources.includes("closing");
15152
+ const rule = projectKeyRule(tracker, link, repo);
15153
+ const closing = rule.type === "issues" && rule.sources.includes("closing");
15080
15154
  const response = await new GithubClient(token, fetcher).query(sampleQuery(closing), {
15081
15155
  owner,
15082
15156
  repo: name
15083
15157
  }, signal);
15084
15158
  if (response.errors.some((error) => !deniedReference(error))) throw new AdapterError("transient", "GitHub link sample failed");
15085
15159
  const root = parseWire(sampleRootWire, response.data["repository"], MALFORMED, ["data", "repository"]);
15086
- const rule = issuesRule(repo, link);
15087
15160
  const operator = login.toLowerCase();
15088
15161
  const sampled = root.pullRequests.nodes.filter((pr) => pr.author?.login?.toLowerCase() === operator).slice(0, SAMPLED);
15089
15162
  return {
15090
15163
  sampled: sampled.length,
15091
- unmatched: sampled.filter((pr) => issueKeys(pr.title, pr.headRefName, closingRefs(pr.closingIssuesReferences), rule).length === 0).map((pr) => ({
15164
+ unmatched: sampled.filter((pr) => prKeys(rule, pr.title, pr.headRefName, closingRefs(pr.closingIssuesReferences)).length === 0).map((pr) => ({
15092
15165
  number: pr.number,
15093
15166
  branch: pr.headRefName
15094
15167
  }))
@@ -16409,6 +16482,7 @@ function sampleProject(ctx, fetcher, token, project, repo) {
16409
16482
  return deadlineCall(ctx, "doctor.link_rules", "GitHub link sample failed", (signal) => sampleLinkRules({
16410
16483
  repo,
16411
16484
  login: project.operatorGithubLogin,
16485
+ tracker: project.tracker,
16412
16486
  link: project.link
16413
16487
  }, {
16414
16488
  token,
@@ -16420,8 +16494,11 @@ function sampleLinks(ctx, fetcher, token) {
16420
16494
  const projects = ctx.config.projects.flatMap((project) => project.tracker.type === "github-issues" ? [{
16421
16495
  project,
16422
16496
  repo: project.tracker.repo
16423
- }] : []);
16424
- if (projects.length === 0 || token === void 0) return null;
16497
+ }] : project.repos.map((repo) => ({
16498
+ project,
16499
+ repo
16500
+ })));
16501
+ if (token === void 0) return null;
16425
16502
  return Promise.all(projects.map(async ({ project, repo }) => {
16426
16503
  const polled = project.repos.some((entry) => entry.toLowerCase() === repo.toLowerCase());
16427
16504
  return polled ? {
@@ -16476,14 +16553,8 @@ function fitFix(segments, tail, fallback) {
16476
16553
  }
16477
16554
  return fallback;
16478
16555
  }
16479
- function linkRulesCheck(outcomes, configured) {
16556
+ function linkRulesCheck(outcomes) {
16480
16557
  const id = "link.rules";
16481
- if (!configured) return {
16482
- id,
16483
- status: "pass",
16484
- blocking: false,
16485
- fix: null
16486
- };
16487
16558
  if (outcomes === null) return warning(id, LINK_RULES_TOKEN_FIX);
16488
16559
  const segments = outcomes.map(linkSegment);
16489
16560
  const problems = segments.filter((segment) => segment.problem);
@@ -16588,7 +16659,7 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch) {
16588
16659
  return null;
16589
16660
  }))).find((failure) => failure !== null) ?? null;
16590
16661
  checks.push(check("github.credentials", githubFailure === null, githubFailure ?? GITHUB_FIX));
16591
- checks.push(linkRulesCheck(await linkSamples, config.projects.some((project) => project.tracker.type === "github-issues")));
16662
+ checks.push(linkRulesCheck(await linkSamples));
16592
16663
  const probe = spurSendRequest(config.adapters.spur.baseUrl, SPUR_PROBE_SESSION, "spur-board doctor probe");
16593
16664
  const [spur, spurSend] = await Promise.all([request(ctx, fetcher, "spur", new URL("sessions", `${config.adapters.spur.baseUrl.replace(/\/$/, "")}/`)), request(ctx, fetcher, "spur.send", probe.url, probe.init)]);
16594
16665
  checks.push(check("spur.api", spur?.ok === true, "Start or correct the configured Spur API."));
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { N as ERRORS, f as renderMcpError, l as OPERATIONS } from "./src-eVAzSAsk.mjs";
2
- import { i as CliError, n as requestOperation } from "./client-FoFGbc11.mjs";
3
- import { a as memoryVerdictCache, r as compareCatalogs, s as loadClientConfig, t as checkCatalog } from "./config-6Nm4MFGe.mjs";
1
+ import { P as ERRORS, p as renderMcpError, u as OPERATIONS } from "./src-ep5scuVt.mjs";
2
+ import { i as CliError, n as requestOperation } from "./client-CwKmG23X.mjs";
3
+ import { a as memoryVerdictCache, r as compareCatalogs, s as loadClientConfig, t as checkCatalog } from "./config-CXDupHSC.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";
@@ -0,0 +1,2 @@
1
+ -- When a complete Spur poll first omitted the session; NULL while it is still observed.
2
+ ALTER TABLE session_snapshot ADD COLUMN absent_since TEXT;
@@ -173,6 +173,15 @@ const LINK_SOURCES = [
173
173
  "branch",
174
174
  "title"
175
175
  ];
176
+ /**
177
+ * The `projects[].link` defaults. A Jira project whose `link` field equals its default here
178
+ * treats it as unset and finds every `tracker.projectKeys` key in that text instead.
179
+ */
180
+ const DEFAULT_LINK = {
181
+ sources: LINK_SOURCES,
182
+ branchPattern: "^[A-Za-z]+-([1-9][0-9]*)",
183
+ titlePattern: "^[a-z]+(?:\\([^)]*\\))?!?: #([1-9][0-9]*)"
184
+ };
176
185
  /** A `link` pattern: compiles, starts with `^` and has exactly one capture group. */
177
186
  function linkPattern(fallback, description) {
178
187
  return nonEmpty.superRefine((pattern, ctx) => {
@@ -246,10 +255,10 @@ const projectSchema = z.strictObject({
246
255
  message: `Duplicate link source: ${JSON.stringify(source)}`
247
256
  });
248
257
  });
249
- }).default([...LINK_SOURCES]).describe("Where a PR in tracker.repo names its issue, in priority order; the first source that yields an issue number wins. closing: issues in tracker.repo the PR closes (Closes #12 in the body, or linked in the sidebar), for PRs to the default branch only. branch: branchPattern on the head branch. title: titlePattern on the PR title."),
250
- branchPattern: linkPattern("^[A-Za-z]+-([1-9][0-9]*)", "Regular expression that starts with ^ and whose one capture group reads the issue number from a PR head branch, such as <agent>-<number>-<slug>. Branches longer than 255 characters are not matched."),
251
- titlePattern: linkPattern("^[a-z]+(?:\\([^)]*\\))?!?: #([1-9][0-9]*)", "Regular expression that starts with ^ and whose one capture group reads the issue number from a PR title, such as fix(core): #12 summary. Titles longer than 255 characters are not matched.")
252
- }).prefault({}).describe("How a github-issues project links a PR in tracker.repo to its issue. A Jira project ignores it and links by tracker.projectKeys. Set the sources and patterns to the branch and PR title naming rules of tracker.repo. The board does not enforce those rules; the repo enforces them through its CI title check and its agents' skills. board doctor compares these rules with recent PRs by operatorGithubLogin."),
258
+ }).default([...DEFAULT_LINK.sources]).describe("Where a PR names its task, in priority order; the first source that yields an issue number wins (for a Jira project, an issue key). closing: issues in tracker.repo the PR closes (Closes #12 in the body, or linked in the sidebar), for PRs to the default branch only; a Jira project skips it. branch: branchPattern on the head branch. title: titlePattern on the PR title."),
259
+ branchPattern: linkPattern(DEFAULT_LINK.branchPattern, "Regular expression that starts with ^ and whose one capture group reads the issue number from a PR head branch, such as <agent>-<number>-<slug>. Branches longer than 255 characters are not matched. For a Jira project the capture group reads the issue key, such as PROJ-12, which must use one of tracker.projectKeys in any letter case; left at the default, a Jira project finds every such key in the PR head branch."),
260
+ titlePattern: linkPattern(DEFAULT_LINK.titlePattern, "Regular expression that starts with ^ and whose one capture group reads the issue number from a PR title, such as fix(core): #12 summary. Titles longer than 255 characters are not matched. For a Jira project the capture group reads the issue key, such as PROJ-12, which must use one of tracker.projectKeys in any letter case; left at the default, a Jira project finds every such key in the PR title.")
261
+ }).prefault({}).describe("How a project links a PR to its task. A github-issues project reads an issue number from PRs in tracker.repo; a Jira project reads an issue key with one of tracker.projectKeys from PRs in repos. Left at the defaults, a Jira project links every tracker.projectKeys key (such as PROJ-12, any letter case) in the PR title or head branch. Set the sources and patterns to the branch and PR title naming rules of the repos. The board does not enforce those rules; the repo enforces them through its CI title check and its agents' skills. board doctor compares these rules with recent PRs by operatorGithubLogin."),
253
262
  operatorGithubLogin: z.string().regex(/^[A-Za-z0-9-]{1,39}$/, "Expected a GitHub login").describe("The GitHub account agents open PRs under. PR discovery in repos keeps only PRs whose author is this login. It is not necessarily the maintainer's own account: when agents push as one account and a maintainer approves as another, set the agents' account, or no PR is discovered."),
254
263
  spurProjects: z.array(spurProject).superRefine((items, ctx) => {
255
264
  rejectDuplicates(items, "name", "spur project name", ctx);
@@ -1740,8 +1749,10 @@ const OPERATIONS = [
1740
1749
  }).describe("Transport health of one gateway.")).describe("Transport health of each chat gateway."),
1741
1750
  sources: z.array(sourceViewSchema).describe("Freshness and availability of each source."),
1742
1751
  tasks: z.array(statusTaskSchema).describe("Tasks on the board with state and counts; facts and links with detail."),
1743
- unlinkedPrs: z.array(statusUnlinkedPrSchema).describe("Observed pull requests without a task link."),
1744
- unlinkedSessions: z.array(statusUnlinkedSessionSchema).describe("Observed sessions without a task link.")
1752
+ unlinkedPrs: z.array(statusUnlinkedPrSchema).describe("Observed pull requests without a task link; merged or closed ones with no change for over 7 days are left out."),
1753
+ unlinkedSessions: z.array(statusUnlinkedSessionSchema).describe("Observed sessions without a task link; ones ended, or gone from Spur's session list, for over 7 days are left out."),
1754
+ hiddenUnlinkedPrs: z.int().min(0).describe("Unlinked pull requests not listed: merged or closed, with no change for over 7 days. Counted within the requested projects; detail does not list them."),
1755
+ hiddenUnlinkedSessions: z.int().min(0).describe("Unlinked sessions not listed: ended, or gone from Spur's session list, for over 7 days. Counted within the requested projects; detail does not list them.")
1745
1756
  }),
1746
1757
  grants: operatorOrProjectAgent,
1747
1758
  errors: ["not_found"],
@@ -1771,7 +1782,9 @@ const OPERATIONS = [
1771
1782
  openBlocks: 0
1772
1783
  }],
1773
1784
  unlinkedPrs: [],
1774
- unlinkedSessions: []
1785
+ unlinkedSessions: [],
1786
+ hiddenUnlinkedPrs: 0,
1787
+ hiddenUnlinkedSessions: 0
1775
1788
  }
1776
1789
  }, {
1777
1790
  summary: "Show the board with full facts and links",
@@ -1795,7 +1808,9 @@ const OPERATIONS = [
1795
1808
  links: []
1796
1809
  }],
1797
1810
  unlinkedPrs: [],
1798
- unlinkedSessions: []
1811
+ unlinkedSessions: [],
1812
+ hiddenUnlinkedPrs: 0,
1813
+ hiddenUnlinkedSessions: 0
1799
1814
  }
1800
1815
  }]
1801
1816
  }),
@@ -2846,4 +2861,10 @@ const SYSTEMD_SERVICE_SETTINGS = [
2846
2861
  "TimeoutStopSec=15s"
2847
2862
  ];
2848
2863
  //#endregion
2849
- export { parseActorId as A, RESERVED_PROJECT as B, prFactsSchema as C, actorIdSchema as D, ticketFactsSchema as E, errorEnvelopeSchema as F, requiredSecretKeys as H, successEnvelopeSchema as I, DEFAULT_HTTP_PORT as L, taskKeySchema as M, ERRORS as N, encodeActorId as O, errorContextSchema as P, DEFAULT_SLACK_APP_NAME as R, SESSION_STATUSES as S, sessionFactsSchema as T, SLACK_BOT_SCOPES as U, configSchema as V, messageRefSchema as _, entityRefSchema as a, eventPayloadSchemas as b, roleCanUseOperation as c, renderJsonError as d, renderMcpError as f, interactionRefSchema as g, inboundEventSchema as h, batchSchema as i, parseRef as j, errorCodeOf as k, OPERATIONS as l, conversationRefSchema as m, SYSTEMD_SERVICE_SETTINGS as n, sourceCursorSchema as o, SPACE_IDS as p, AdapterError as r, buildCatalogSnapshot as s, BOARD_TICK_MS as t, renderHttpProblem as u, userIdSchema as v, prRefSchema as w, SESSION_HEALTH_STATES as x, EVENT_KINDS as y, DEFAULT_SLACK_COMMAND as z };
2864
+ //#region ../contracts/src/index.ts
2865
+ /** Exhaustiveness check: call it in the `default` branch of a switch over a union. */
2866
+ function assertNever(value) {
2867
+ throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
2868
+ }
2869
+ //#endregion
2870
+ export { errorCodeOf as A, DEFAULT_SLACK_APP_NAME as B, SESSION_STATUSES as C, ticketFactsSchema as D, sessionFactsSchema as E, errorContextSchema as F, SLACK_BOT_SCOPES as G, RESERVED_PROJECT as H, errorEnvelopeSchema as I, successEnvelopeSchema as L, parseRef as M, taskKeySchema as N, actorIdSchema as O, ERRORS as P, DEFAULT_HTTP_PORT as R, SESSION_HEALTH_STATES as S, prRefSchema as T, configSchema as U, DEFAULT_SLACK_COMMAND as V, requiredSecretKeys as W, interactionRefSchema as _, batchSchema as a, EVENT_KINDS as b, buildCatalogSnapshot as c, renderHttpProblem as d, renderJsonError as f, inboundEventSchema as g, conversationRefSchema as h, AdapterError as i, parseActorId as j, encodeActorId as k, roleCanUseOperation as l, SPACE_IDS as m, BOARD_TICK_MS as n, entityRefSchema as o, renderMcpError as p, SYSTEMD_SERVICE_SETTINGS as r, sourceCursorSchema as s, assertNever as t, OPERATIONS as u, messageRefSchema as v, prFactsSchema as w, eventPayloadSchemas as x, userIdSchema as y, DEFAULT_LINK as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.15.2",
3
+ "version": "0.16.0",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"