spur-board 0.65.0 → 0.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import { ct as configSchema, d as buildCatalogSnapshot, lt as plainHttpAllowed, p as OPERATIONS } from "./chunk-BdO94P44.mjs";
2
- import { o as CliError, t as fetchCatalogVersion } from "./chunk-BJMN8jrU.mjs";
1
+ import { ct as configSchema, d as buildCatalogSnapshot, lt as plainHttpAllowed, p as OPERATIONS } from "./chunk-D4cCKVAP.mjs";
2
+ import { o as CliError, t as fetchCatalogVersion } from "./chunk-DawDZw1u.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";
@@ -306,7 +306,7 @@ const columnConfig = z.strictObject({
306
306
  id: z.enum(COLUMN_IDS, { error: (issue) => typeof issue.input === "string" ? `Unknown column ${JSON.stringify(issue.input)}: custom columns arrive with custom matchers and are not supported yet. Built-in columns: ${COLUMN_IDS.join(", ")}` : void 0 }).describe("The built-in column this entry configures."),
307
307
  enabled: z.boolean().default(true).describe("false skips the column: tasks move past it and its exit condition is not checked. todo, dev and done cannot be disabled."),
308
308
  orchestrator: nonEmpty.default("none").describe("Who takes the column's turns. none: the task's live worker session, else the operator. operator: the operator, who also gets the questions asked in the column. Otherwise the name of a spurProjects entry with role orchestrator or curator whose sessions orchestrate the column and get the questions others ask in it."),
309
- cycleLimit: z.int().min(1).default(DEFAULT_CYCLE_LIMIT).describe("How many times a task may return to Dev from this column before the board stops it for the operator. Returns by the column executor, changes requested and external comments count; a conflict, red CI and a draft do not."),
309
+ cycleLimit: z.int().min(1).default(DEFAULT_CYCLE_LIMIT).describe("How many times a task may return to Dev from this column before the board stops it for the operator. Returns by the column executor and for external comments count, a changes-requested review included (it is an external comment, not a separate return); a conflict, red CI and a draft do not."),
310
310
  courseCheck: z.int().min(0).default(DEFAULT_COURSE_CHECK).describe("How many returns to Dev from this column, counted as for cycleLimit, before the board holds the task and asks courseCheckTo (by default the curator, or the operator when the project has no curator) to check its course. The answer resets the count and reaches the worker as a task comment. 0 turns the check off; cycleLimit is checked first."),
311
311
  courseCheckTo: nonEmpty.optional().describe("Who answers this column's course check: operator, the curator's name, or the name of a column orchestrator. Without it, the curator, or the operator when the project has no curator. When the addressee has no live session the question moves to the operator; a conductor that is rung and does not answer keeps it, and the operator gets an item.")
312
312
  });
@@ -358,7 +358,7 @@ const projectSchema = z.strictObject({
358
358
  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."),
359
359
  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.")
360
360
  }).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."),
361
- 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."),
361
+ 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. Comments, reviews and approvals by this login or by a bot (GitHub App) are not external: they never return a task to Dev, approve External Review or block its approval. Every other account is external, the repo owner's and the human operator's included."),
362
362
  spurProjects: z.array(spurProject).superRefine((items, ctx) => {
363
363
  rejectDuplicates(items, "name", "spur project name", ctx);
364
364
  let curator;
@@ -549,6 +549,7 @@ const configSchema = z.strictObject({
549
549
  }).prefault({}),
550
550
  github: z.strictObject({ reserveRemaining: z.int().min(0).default(1e3).describe("GitHub API requests to leave unused in each quota window.") }).prefault({}),
551
551
  health: z.strictObject({
552
+ turnStallAfterMs: durationMs(6e5, "How long an unhealthy open-turn executor waits before a curator or operator block"),
552
553
  errorAfterMs: durationMs(9e4, "How long a session stays in error before it is flagged"),
553
554
  needsInputAfterMs: durationMs(12e4, "How long a session waits for input before it is flagged"),
554
555
  idleInDevAfterMs: durationMs(18e5, "How long a worker session without an open PR, or the executor of a taken turn, waits at its prompt before it is flagged"),
@@ -1,4 +1,4 @@
1
- import { $ as errorContextSchema, Z as ERRORS, c as tokenRequestStatusSchema, et as errorEnvelopeSchema, g as renderJsonError, nt as successEnvelopeSchema, o as tokenRequestResultSchema } from "./chunk-BdO94P44.mjs";
1
+ import { $ as errorContextSchema, Z as ERRORS, c as tokenRequestStatusSchema, et as errorEnvelopeSchema, g as renderJsonError, nt as successEnvelopeSchema, o as tokenRequestResultSchema } from "./chunk-D4cCKVAP.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
package/dist/cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { K as actorIdSchema, Z as ERRORS, a as requestHashOf, ct as configSchema, f as roleCanUseOperation, nt as successEnvelopeSchema, p as OPERATIONS, pt as SLACK_BOT_SCOPES, r as remoteDoctorReportSchema, u as SYSTEMD_SERVICE_SETTINGS, ut as requiredSecretKeys } from "./chunk-BdO94P44.mjs";
1
+ import { K as actorIdSchema, Z as ERRORS, a as requestHashOf, ct as configSchema, f as roleCanUseOperation, nt as successEnvelopeSchema, p as OPERATIONS, pt as SLACK_BOT_SCOPES, r as remoteDoctorReportSchema, u as SYSTEMD_SERVICE_SETTINGS, ut as requiredSecretKeys } from "./chunk-D4cCKVAP.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-BJMN8jrU.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-CNZV8Ua0.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-DawDZw1u.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-BywmJyLe.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,2 +1,2 @@
1
- import { a as requestTokenEnrollment, i as requestSkillReload, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./chunk-BJMN8jrU.mjs";
1
+ import { a as requestTokenEnrollment, i as requestSkillReload, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./chunk-DawDZw1u.mjs";
2
2
  export { fetchCatalogVersion, fetchTokenStatus, requestOperation, requestSkillReload, requestTokenEnrollment };
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as sessionTransitionSchema, B as prRefSchema, C as userIdSchema, D as batchSchema, E as AdapterError, F as SESSION_HEALTH_STATES, G as REF_NUMBER, H as sessionFactsSchema, I as SESSION_STATUSES, J as errorCodeOf, K as actorIdSchema, L as isExternalAuthor, M as trackerSourceId, N as PR_STATES, O as entityRefSchema, P as REVIEW_STATES, Q as err, R as parseRingMarker, S as messageRefSchema, T as eventPayloadSchemas, U as ticketFactsSchema, V as ringMarker, W as JIRA_PROJECT_KEY, X as parseRef$1, Y as parseActorId, Z as ERRORS, a as requestHashOf, b as inboundEventSchema, c as tokenRequestStatusSchema, ct as configSchema, d as buildCatalogSnapshot, dt as COLUMN_IDS, f as roleCanUseOperation, ft as DISPATCHER_MODES, h as renderHttpProblem, i as TOKEN_REQUEST_LIMITS, it as DEFAULT_LINK, j as sourceCursorSchema, k as prSourceId, l as BOARD_TICK_MS, lt as plainHttpAllowed, m as turnHandedSchema, mt as TASK_HOLDS, n as doctorReportSchema, nt as successEnvelopeSchema, o as tokenRequestResultSchema, ot as DEFAULT_SLACK_COMMAND, p as OPERATIONS, pt as SLACK_BOT_SCOPES, q as encodeActorId, s as tokenRequestSchema, st as RESERVED_PROJECT, t as assertNever, tt as ok, ut as requiredSecretKeys, v as SPACE_IDS, w as EVENT_KINDS, x as interactionRefSchema, y as conversationRefSchema, z as prFactsSchema } from "./chunk-BdO94P44.mjs";
1
+ import { A as sessionTransitionSchema, B as prRefSchema, C as userIdSchema, D as batchSchema, E as AdapterError, F as SESSION_HEALTH_STATES, G as REF_NUMBER, H as sessionFactsSchema, I as SESSION_STATUSES, J as errorCodeOf, K as actorIdSchema, L as isExternalAuthor, M as trackerSourceId, N as PR_STATES, O as entityRefSchema, P as REVIEW_STATES, Q as err, R as parseRingMarker, S as messageRefSchema, T as eventPayloadSchemas, U as ticketFactsSchema, V as ringMarker, W as JIRA_PROJECT_KEY, X as parseRef$1, Y as parseActorId, Z as ERRORS, a as requestHashOf, b as inboundEventSchema, c as tokenRequestStatusSchema, ct as configSchema, d as buildCatalogSnapshot, dt as COLUMN_IDS, f as roleCanUseOperation, ft as DISPATCHER_MODES, h as renderHttpProblem, i as TOKEN_REQUEST_LIMITS, it as DEFAULT_LINK, j as sourceCursorSchema, k as prSourceId, l as BOARD_TICK_MS, lt as plainHttpAllowed, m as turnHandedSchema, mt as TASK_HOLDS, n as doctorReportSchema, nt as successEnvelopeSchema, o as tokenRequestResultSchema, ot as DEFAULT_SLACK_COMMAND, p as OPERATIONS, pt as SLACK_BOT_SCOPES, q as encodeActorId, s as tokenRequestSchema, st as RESERVED_PROJECT, t as assertNever, tt as ok, ut as requiredSecretKeys, v as SPACE_IDS, w as EVENT_KINDS, x as interactionRefSchema, y as conversationRefSchema, z as prFactsSchema } from "./chunk-D4cCKVAP.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";
@@ -14751,6 +14751,17 @@ function prsPolledSince(task, since) {
14751
14751
  //#endregion
14752
14752
  //#region ../core/src/app/fromYou.ts
14753
14753
  const episodeSchema = z.object({ startedAt: z.number() }).nullable();
14754
+ const stallEpisodeSchema = z.object({
14755
+ session: z.string().nullable(),
14756
+ health: z.string().nullable(),
14757
+ since: z.string().nullable(),
14758
+ revision: z.int().min(1)
14759
+ });
14760
+ const stallObservationSchema = z.object({
14761
+ blind: z.boolean(),
14762
+ observedAt: z.string().nullable(),
14763
+ resumedAt: z.number().nullable()
14764
+ });
14754
14765
  const ENDED_WORKER_LABELS = {
14755
14766
  worker_completed: "worker ended (completed), no PR",
14756
14767
  worker_killed: "worker ended (killed), no PR",
@@ -14785,7 +14796,7 @@ async function conversationWaiting(trx, config, block, subject) {
14785
14796
  };
14786
14797
  }
14787
14798
  /** Reconciles every item in the caller's observation or tick transaction. */
14788
- async function reconcileItems(trx, config, now, spurComplete, warnSkipped) {
14799
+ async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurContinuityStartAt) {
14789
14800
  const candidates = [];
14790
14801
  const sources = await trx.selectFrom("source_state").selectAll().execute();
14791
14802
  const sourceById = new Map(sources.map((state) => [state.source, state]));
@@ -15018,6 +15029,120 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped) {
15018
15029
  revision: "closed"
15019
15030
  });
15020
15031
  }
15032
+ const observationRow = await trx.selectFrom("meta").select("value").where("key", "=", "turn_stall_observation").executeTakeFirst();
15033
+ const previousObservation = observationRow === void 0 ? {
15034
+ blind: false,
15035
+ observedAt: null,
15036
+ resumedAt: null
15037
+ } : parseJson(stallObservationSchema, observationRow.value);
15038
+ const spurExpired = spur?.last_complete_at != null && now > Date.parse(spur.last_complete_at) + config.adapters.spur.intervalMs * config.thresholds.staleMultiplier;
15039
+ const observation = spurBlind || !spurComplete || spurExpired ? {
15040
+ ...previousObservation,
15041
+ blind: true,
15042
+ observedAt: spurComplete ? spur?.observed_at ?? null : null
15043
+ } : spurContinuityStartAt !== void 0 ? {
15044
+ blind: false,
15045
+ observedAt: spur?.observed_at ?? null,
15046
+ resumedAt: spurContinuityStartAt
15047
+ } : previousObservation.blind && spur?.observed_at != null && spur.observed_at !== previousObservation.observedAt ? {
15048
+ blind: false,
15049
+ observedAt: spur.observed_at,
15050
+ resumedAt: Date.parse(spur.observed_at)
15051
+ } : previousObservation;
15052
+ if (JSON.stringify(observation) !== JSON.stringify(previousObservation)) await trx.insertInto("meta").values({
15053
+ key: "turn_stall_observation",
15054
+ value: toJson(stallObservationSchema, observation)
15055
+ }).onConflict((oc) => oc.column("key").doUpdateSet({ value: toJson(stallObservationSchema, observation) })).execute();
15056
+ const stallBlind = observation.blind;
15057
+ const stallExecutors = /* @__PURE__ */ new Map();
15058
+ const stalled = /* @__PURE__ */ new Set();
15059
+ const stallHeld = /* @__PURE__ */ new Set();
15060
+ const turns = await trx.selectFrom("turn").selectAll().where("closed_at", "is", null).execute();
15061
+ for (const turn of turns) {
15062
+ const task = taskById.get(turn.task_id);
15063
+ if (task === void 0 || turn.role === "operator") continue;
15064
+ const holder = turn.acked_by === null ? null : parseActorId(turn.acked_by);
15065
+ let executor = holder?.actor === "agent" ? await trx.selectFrom("session_snapshot").selectAll().where("id", "=", holder.actorRef.session).executeTakeFirst() : turn.acked_at === null ? await selectNotificationRecipient(trx, {
15066
+ task_id: task.id,
15067
+ role: turn.role,
15068
+ author_session: null
15069
+ }, config) : void 0;
15070
+ if (executor === void 0 && turn.acked_at === null) {
15071
+ const target = config.projects.find((entry) => entry.id === task.project)?.columns.find((entry) => entry.id === turn.column)?.orchestrator;
15072
+ const stopped = await trx.selectFrom("session_snapshot").selectAll().where("state", "=", "stopped").where("ended_at", "is", null).where("absent_since", "is", null).orderBy("first_seen", "desc").orderBy("id").execute();
15073
+ for (const row of stopped) if (await trx.selectFrom("link").select("id").where("task_id", "=", task.id).where("session_id", "=", row.id).where("role", "=", turn.role === "worker" ? "worker" : "orchestrator").where("banned", "=", 0).executeTakeFirst() !== void 0 || turn.role !== "worker" && row.spur_project === target) {
15074
+ executor = row;
15075
+ break;
15076
+ }
15077
+ }
15078
+ if (executor === void 0 || executor.ended_at !== null || executor.absent_since !== null) {
15079
+ await observeTurnEpisode(trx, turn.id, null);
15080
+ continue;
15081
+ }
15082
+ if (turn.role === "worker") {
15083
+ if (await trx.selectFrom("link").select("id").where("task_id", "=", task.id).where("session_id", "=", executor.id).where("banned", "=", 1).executeTakeFirst() !== void 0) {
15084
+ await observeTurnEpisode(trx, turn.id, null);
15085
+ continue;
15086
+ }
15087
+ }
15088
+ const parsed = sessionFactsSchema.safeParse(JSON.parse(executor.detail));
15089
+ if (!parsed.success) {
15090
+ await observeTurnEpisode(trx, turn.id, null);
15091
+ continue;
15092
+ }
15093
+ const fact = parsed.data;
15094
+ if (holder?.actor === "agent" && holder.actorRef.project !== fact.spurProject) {
15095
+ await observeTurnEpisode(trx, turn.id, null);
15096
+ continue;
15097
+ }
15098
+ const episode = await observeTurnEpisode(trx, turn.id, fact);
15099
+ const episodeSince = episode.since ?? fact.healthSince;
15100
+ if (![
15101
+ "needs_input",
15102
+ "error",
15103
+ "rate_limited",
15104
+ "stopped"
15105
+ ].includes(fact.health)) continue;
15106
+ const healthStart = Math.max(Date.parse(turn.created_at), Date.parse(episodeSince));
15107
+ if (!Number.isFinite(healthStart)) continue;
15108
+ stalled.add(`${String(task.id)}:${fact.id}`);
15109
+ const key = `turn-stall:${String(turn.id)}:${fact.id}:${fact.health}:${episodeSince}:${String(episode.revision)}`;
15110
+ stallHeld.add(key);
15111
+ const previous = await trx.selectFrom("operator_item").select([
15112
+ "text",
15113
+ "cleared_at",
15114
+ "block_id"
15115
+ ]).where("item_key", "=", key).orderBy("id", "desc").executeTakeFirst();
15116
+ const activeBlock = previous?.cleared_at === null ? blocks.find((block) => block.id === previous.block_id) : void 0;
15117
+ if (activeBlock?.addressee_role === "curator" && (await curatorSession(trx, config, task.project))?.id === fact.id) await moveBlockToAddressee(trx, {
15118
+ task,
15119
+ block: activeBlock,
15120
+ to: "operator",
15121
+ reason: "The selected curator is the stalled executor.",
15122
+ ctx: {
15123
+ actor: "system",
15124
+ at: new Date(now).toISOString()
15125
+ },
15126
+ config
15127
+ });
15128
+ const since = previous?.cleared_at === null ? healthStart : Math.max(healthStart, observation.resumedAt ?? healthStart);
15129
+ if (stallBlind || now - since < config.health.turnStallAfterMs) continue;
15130
+ stallExecutors.set(key, fact.id);
15131
+ const questions = blocks.filter((block) => {
15132
+ const author = parseActorId(block.author);
15133
+ return block.task_id === task.id && author?.actor === "agent" && author.actorRef.project === fact.spurProject && author.actorRef.session === fact.id;
15134
+ }).map((block) => `B${String(block.id)}`);
15135
+ const quota = fact.health === "rate_limited" ? `; quota name unavailable; reset ${fact.rateLimitResetAt ?? "unknown"}` : "";
15136
+ candidates.push({
15137
+ key,
15138
+ kind: "anomaly",
15139
+ taskId: task.id,
15140
+ summary: previous?.text ?? `${task.key}: turn T${String(turn.id)} executor ${fact.id} remains ${fact.health} since ${episodeSince}; turn-relative elapsed ${String(now - since)} ms${since > healthStart ? `; continuous observation since ${new Date(since).toISOString()}` : ""}${quota}${questions.length === 0 ? "" : `; open executor questions: ${questions.join(", ")}`}`,
15141
+ factAt: episodeSince,
15142
+ source: "spur",
15143
+ priority: 4
15144
+ });
15145
+ }
15021
15146
  const previousEpisode = await trx.selectFrom("meta").select("value").where("key", "=", "host_load_episode").executeTakeFirst();
15022
15147
  const health = evaluateSessionHealth({
15023
15148
  sessions: subjects,
@@ -15038,6 +15163,11 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped) {
15038
15163
  const task = taskById.get(Number(flag.taskId));
15039
15164
  if (task === void 0) continue;
15040
15165
  const fact = subjects.find((subject) => subject.taskId === flag.taskId && subject.id === flag.sessionId);
15166
+ if ([
15167
+ "stuck_worker",
15168
+ "stuck_orchestrator",
15169
+ "needs_input"
15170
+ ].includes(flag.kind) && stalled.has(`${flag.taskId}:${flag.sessionId}`)) continue;
15041
15171
  const endedLabel = ENDED_WORKER_LABELS[flag.kind];
15042
15172
  const asking = flag.kind === "needs_input" && fact !== void 0 && blocks.some((block) => {
15043
15173
  const author = parseActorId(block.author);
@@ -15080,15 +15210,16 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped) {
15080
15210
  const seen = /* @__PURE__ */ new Set([...ordered.map((item) => item.key), ...heldKeys]);
15081
15211
  for (const flag of health.held) {
15082
15212
  const task = taskById.get(Number(flag.taskId));
15083
- if (task !== void 0) seen.add(healthKey(task.id, flag));
15213
+ if (task !== void 0 && !stalled.has(`${flag.taskId}:${flag.sessionId}`)) seen.add(healthKey(task.id, flag));
15084
15214
  }
15085
15215
  const existing = await trx.selectFrom("operator_item").selectAll().where("kind", "in", RECONCILED_KINDS).where("cleared_at", "is", null).execute();
15086
- const stillInError = new Set(health.hostLoad === null ? [] : subjects.filter((subject) => subject.endedAt === null && subject.health === "error" && subject.role !== "other").map((subject) => healthKey(Number(subject.taskId), {
15216
+ const stillInError = new Set(health.hostLoad === null ? [] : subjects.filter((subject) => subject.endedAt === null && subject.health === "error" && subject.role !== "other" && !stalled.has(`${subject.taskId}:${subject.id}`)).map((subject) => healthKey(Number(subject.taskId), {
15087
15217
  taskId: subject.taskId,
15088
15218
  sessionId: subject.id,
15089
15219
  kind: subject.role === "worker" ? "stuck_worker" : "stuck_orchestrator"
15090
15220
  })));
15091
15221
  const spurHeld = spurBlind ? await blindHeldKeys(trx, subjects) : /* @__PURE__ */ new Set();
15222
+ if (stallBlind) for (const key of stallHeld) spurHeld.add(key);
15092
15223
  for (const item of existing) {
15093
15224
  if (item.kind !== "anomaly") continue;
15094
15225
  if (item.source === "spur" && spurHeld.has(item.item_key) || stillInError.has(item.item_key)) seen.add(item.item_key);
@@ -15122,7 +15253,7 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped) {
15122
15253
  source: candidate.source,
15123
15254
  priority: candidate.priority
15124
15255
  };
15125
- if (ITEM_POLICY[candidate.kind].block && task !== null && task !== void 0) await raiseAnomaly(trx, config, task, input);
15256
+ if (ITEM_POLICY[candidate.kind].block && task !== null && task !== void 0) await raiseAnomaly(trx, config, task, input, stallExecutors.get(candidate.key));
15126
15257
  else await raiseItem(trx, {
15127
15258
  ...input,
15128
15259
  taskId: candidate.taskId,
@@ -15148,15 +15279,17 @@ function prCompleteAt(project, sourceById) {
15148
15279
  * Raises a ledger item with the operator block it stands for. An active item of the key is
15149
15280
  * returned as it is, so a repeated raise opens no second block.
15150
15281
  */
15151
- async function raiseAnomaly(trx, config, task, input) {
15282
+ async function raiseAnomaly(trx, config, task, input, executorId) {
15152
15283
  const active = await trx.selectFrom("operator_item").selectAll().where("item_key", "=", input.itemKey).where("cleared_at", "is", null).executeTakeFirst();
15153
15284
  if (active !== void 0) return active;
15154
15285
  const prefix = `${task.key}: `;
15286
+ const toCurator = input.itemKey.startsWith("turn-stall:") && curatorProject(config, task.project) !== null && (await curatorSession(trx, config, task.project))?.id !== executorId;
15155
15287
  const block = await openSystemBlock(trx, {
15156
15288
  task,
15157
15289
  reason: input.text.startsWith(prefix) ? input.text.slice(prefix.length) : input.text,
15158
15290
  at: input.at.toISOString(),
15159
- config
15291
+ config,
15292
+ ...toCurator ? { addressee: "curator" } : {}
15160
15293
  });
15161
15294
  return raiseItem(trx, {
15162
15295
  ...input,
@@ -15204,6 +15337,24 @@ async function blindHeldKeys(trx, subjects) {
15204
15337
  for (const { turn } of await quietTurns(trx)) held.add(`stuck-turn:${String(turn.id)}`);
15205
15338
  return held;
15206
15339
  }
15340
+ /** A producer's local healthSince can restart without a new current observed health state. */
15341
+ async function observeTurnEpisode(trx, turnId, fact) {
15342
+ const key = `turn_stall_episode:${String(turnId)}`;
15343
+ const row = await trx.selectFrom("meta").select("value").where("key", "=", key).executeTakeFirst();
15344
+ const previous = row === void 0 ? void 0 : parseJson(stallEpisodeSchema, row.value);
15345
+ if (previous !== void 0 && previous.session === (fact?.id ?? null) && previous.health === (fact?.health ?? null)) return previous;
15346
+ const episode = {
15347
+ session: fact?.id ?? null,
15348
+ health: fact?.health ?? null,
15349
+ since: fact?.healthSince ?? null,
15350
+ revision: (previous?.revision ?? 0) + 1
15351
+ };
15352
+ await trx.insertInto("meta").values({
15353
+ key,
15354
+ value: toJson(stallEpisodeSchema, episode)
15355
+ }).onConflict((oc) => oc.column("key").doUpdateSet({ value: toJson(stallEpisodeSchema, episode) })).execute();
15356
+ return episode;
15357
+ }
15207
15358
  function healthKey(taskId, flag) {
15208
15359
  return `health:${String(taskId)}:${flag.sessionId}:${flag.kind}`;
15209
15360
  }
@@ -17536,6 +17687,8 @@ function createObservationCore(deps) {
17536
17687
  const now = clock.now();
17537
17688
  await scanTransaction(store, config, async (trx) => {
17538
17689
  const wasBlind = await blindReason(trx, source);
17690
+ const previousSpur = source === "spur" ? await trx.selectFrom("source_state").select("last_complete_at").where("source", "=", source).executeTakeFirst() : void 0;
17691
+ const spurGap = previousSpur?.last_complete_at != null && Date.parse(batch.observedAt) > Date.parse(previousSpur.last_complete_at) + config.adapters.spur.intervalMs * config.thresholds.staleMultiplier;
17539
17692
  await sourceState(trx, source, observation.state, batch.observedAt, batch.cursor);
17540
17693
  await recordUsage(trx, source, batch.usage, now);
17541
17694
  for (const probe of batch.prProbes ?? []) {
@@ -17662,7 +17815,7 @@ function createObservationCore(deps) {
17662
17815
  if (observation.effectiveComplete && !completeSince.has(source) || recovered) await dispatchSource(trx, source, dispatchContext);
17663
17816
  await dispatchMergedTickets(trx, source, dispatchContext);
17664
17817
  await dispatchJournaled(trx, dispatchContext);
17665
- await reconcileItems(trx, config, now, currentComplete.has("spur"), warnSkipped);
17818
+ await reconcileItems(trx, config, now, currentComplete.has("spur"), warnSkipped, source === "spur" && observation.effectiveComplete && (!completeSince.has("spur") || spurGap) ? Date.parse(batch.observedAt) : void 0);
17666
17819
  if (deps.productVersion !== void 0) await enqueueLiveAfterFirstPoll(trx, {
17667
17820
  config,
17668
17821
  productVersion: deps.productVersion,
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { Z as ERRORS, _ as renderMcpError, p as OPERATIONS } from "./chunk-BdO94P44.mjs";
2
- import { o as CliError, r as requestOperation } from "./chunk-BJMN8jrU.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-CNZV8Ua0.mjs";
1
+ import { Z as ERRORS, _ as renderMcpError, p as OPERATIONS } from "./chunk-D4cCKVAP.mjs";
2
+ import { o as CliError, r as requestOperation } from "./chunk-DawDZw1u.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-BywmJyLe.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.65.0",
3
+ "version": "0.67.0",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"
@@ -23,13 +23,12 @@ after checking an uncertain outcome.
23
23
  ## Turns
24
24
 
25
25
  Ack T<number> first with keyed
26
- `board inbox ack <entries>`; only its acking session may submit or return. New heads
27
- close turns outside Dev; taken Dev turns survive pushes.
26
+ `board inbox ack <entries>`; only its acking session may submit or return.
28
27
  On `turn_closed`, act only on a turn `board inbox` lists. Shadow mode opens no turn:
29
28
  `board submit <task> <sha>`.
30
29
 
31
- - Dev worker: ack, push, then keyed `board submit <turn> <sha>`; use a fresh PR head. Answer each external comment the turn hands you with a new head or a reasoned reply.
32
- Re-request review only from reviewers whose threads this push closed.
30
+ - Dev worker: ack, then keyed `board submit <turn> <sha>` for the PR head. Answer each external comment the turn hands you with a new head or a reasoned reply; a reply alone submits the same head.
31
+ Re-request review only from reviewers whose threads your push closed.
33
32
  If returns repeat the same mechanism, fix the class once; one table test for variants;
34
33
  edges with no user-visible effect under PR Risk; still fix P0/P1 and user-visible findings.
35
34
  - Column orchestrator: ack, then keyed `board submit <turn> <sha>` for the reviewed head, or
@@ -1,21 +1,18 @@
1
1
  # How the Board works
2
2
 
3
- `board task <task> --why`: gates, holds, waits, turn and moves.
4
-
5
3
  ## Columns and executors
6
4
 
7
5
  `todo`, `ready-for-dev`, `dev`, `review`, `product-review`,
8
6
  `external-review`, `qa`, `ready-to-merge`, `done`.
9
- `projects[].columns[].enabled` false or omitted optional columns skip gates;
7
+ `projects[].columns[].enabled`: disabled/omitted optional columns skip gates;
10
8
  To Do, Dev, Done stay enabled.
11
9
 
12
10
  Each column has one executor: `projects[].columns[].orchestrator`:
13
11
  `none` (live worker, else operator), `operator`, or project with role
14
- `orchestrator` or `curator`. The worker owns the code and branch; others
15
- submit inspected heads or return findings; never push.
12
+ `orchestrator` or `curator`. The worker owns the code and branch; others inspect/return, never push.
16
13
 
17
14
  `projects[].spurProjects[].role` accepts `worker`, `operator`, `curator` and
18
- `orchestrator`. Curators guide; orchestrators execute columns, never as workers.
15
+ `orchestrator`. Curators guide; orchestrators execute.
19
16
 
20
17
  ## Gates and placement
21
18
 
@@ -27,62 +24,75 @@ Moves, turns and course checks need `projects[].dispatcher.mode: on`;
27
24
  default is `shadow`: proposed placement only; no turns, doorbells or blocks.
28
25
 
29
26
  Gates are cumulative: each column checks its enabled gate and those to its left. At a turn boundary, failed gates return to the leftmost failing
30
- column. Taken turns hold until submit, return or new head. Pending CI, unknown
27
+ column. Pending CI, unknown
31
28
  mergeability and incomplete comment history are waits. Downstream handoff waits
32
- for settled prerequisites; Dev can receive a repair turn for red CI, drafts,
33
- conflicts or unhandled external comments.
29
+ for settled prerequisites; Dev can receive a repair turn.
34
30
 
35
31
  Dev needs an open non-draft PR, passing checks, no conflict, handled external
36
32
  feedback, comment history and current-head submit. Feedback excludes
37
33
  bots, approvals and `projects[].operatorGithubLogin` (agents' account), so worker
38
34
  thread replies never count; others' posts do.
35
+ The repo owner's and the human operator's own accounts count too, unless one is
36
+ that login: a PR comment is a change request; talk to agents in Slack
37
+ (`@shortName`) or the Board. A review-thread reply is a new review. An approval
38
+ hides its inline comments; thread resolution and the head a comment was left on
39
+ change nothing. Bots (GitHub Apps) neither return a task, approve it nor block
40
+ an approval. Handled means handed by ID to a Dev turn, not answered; in shadow
41
+ mode, a later submit in Dev or an executor `none` column handles it.
39
42
  A status comment whose last line is a hidden `board-reviewer-progress` or
40
- `board-reviewer-unavailable` marker is not external feedback. No required checks: count non-skipped checks. `projects[].reposWithoutCi` waives absent checks
43
+ `board-reviewer-unavailable` marker is not external feedback. No required checks: non-skipped count. `projects[].reposWithoutCi` waives absent checks
41
44
  for listed repos; never failed/skipped required ones.
42
45
 
43
46
  Review and Product Review need current-head internal review marks, separate from
44
47
  External Review's external approval. QA: current-head submit; Ready to Merge awaits merge. Executor `none` may reuse same-head submits from other worker columns. Fixed gate rules have no configuration switch
45
- except enabled columns and no-CI.
48
+ except enabled/no-CI.
46
49
 
47
50
  Review/Product Review mark lasts across visits on the current head. A visit
48
51
  submission belongs to one column visit; moving left clears it and those to the right. New heads invalidate internal Review and Product Review marks,
49
52
  even old heads.
50
53
 
51
- Anomalies: PR closed without merge with no open PR, or closed
52
- ticket with live work and no merged PR. `board status` lists them; they may surface
53
- as operator block threads.
54
+ PR closed without merge with no open PR, or closed
55
+ ticket with live work and no merged PR. `board status` lists them as operator block threads.
54
56
 
55
57
  ## Turns and delivery
56
58
 
57
- A turn `T<number>`: a visit. Keyed `board inbox ack <entries>`.
59
+ A turn `T<number>`: keyed `board inbox ack <entries>`.
58
60
  Only the acknowledging session may submit or return: keyed
59
61
  `board submit <turn> <sha>` accepts the head; keyed
60
62
  `board return <turn> <reason>` sends findings to Dev. In
61
63
  shadow mode, use keyed `board submit <task> <sha>`.
62
64
  Unseen heads answer `pending`: that submit is final; do not resubmit or raise a
63
- block. Confirms or returns the turn
64
- (`projects[].dispatcher.submitConfirmMs`).
65
+ block. Confirm timeout: `projects[].dispatcher.submitConfirmMs`.
65
66
 
66
67
  A new head closes taken turns outside Dev; taken Dev turns survive pushes.
67
- Untaken turns: CI, draft, conflict or external-comment returns.
68
+ Right of Dev, red CI, a draft, a conflict or an external comment returns the
69
+ task to Dev at once, unless a turn is taken; then after its submit or return.
70
+ The Dev turn hands the comments, beside a return's `code` block.
68
71
  Operator turns: 1 inbox item + Slack thread until exit.
69
72
 
70
73
  Closed turns receive no further Board sends; Obsolete queued rings are dropped;
71
74
  a message already accepted by Spur cannot be retracted. Check `board inbox` and
72
75
  act only on a current turn; reread after `turn_closed`.
73
76
 
77
+ Open-turn executors in `needs_input`, `error`, `rate_limited` or `stopped` raise
78
+ one question after `health.turnStallAfterMs` (default 600000 ms): curator unless self, else
79
+ operator. Time starts at the later turn/state start; taking never resets it.
80
+ One frozen explanation/dismissal per turn/session/state episode. Recovery,
81
+ replacement, removal, archive or turn closure withdraws it. Blind Spur opens none,
82
+ holds existing; gaps restart timing for new questions.
83
+
74
84
  ## Doorbells
75
85
 
76
86
  A turn opened for you by your own confirmed submit or return is first rung only after `doorbells.firstRetryMs`; a turn opened for you any other way rings at once.
77
87
 
78
88
  A doorbell expects action: read `board inbox` for the turn, addressed
79
89
  block, answer or follow-up. Ordinary task comments do not ring; nor does a block
80
- tracked by its author role ring itself. Rings differ from moves.
90
+ tracked by its author role ring itself.
81
91
 
82
- Unacked series repeat, up to three delivered rings;
92
+ Repeat up to three delivered rings;
83
93
  acknowledgement stops them. Removal notices and quiet-turn reminders ring once.
84
94
  Busy recipients defer delivery; pending delivery or earlier rings in the Spur
85
- queue defer repeats. Queued rings can exhaust their waiting window.
95
+ queue defer repeats. Queues can exhaust their waiting window.
86
96
 
87
97
  Most notices await recipients; taskless worker, orchestrator and operator-agent
88
98
  answers end without a live asking session. Curator and course-check orchestrator
@@ -94,18 +104,17 @@ curator questions move to operator.
94
104
 
95
105
  `projects[].columns[].courseCheck` defaults to 3 counted returns to Dev;
96
106
  `courseCheck: 0` disables it. `projects[].columns[].cycleLimit` defaults to 10 and
97
- takes priority. Executor returns, changes requested and external comments count;
98
- CI failures, conflicts and drafts alone do not count, nor reopened tickets or
99
- mode switches.
107
+ takes priority. Executor returns and external comments (a changes-requested
108
+ review is one) count; CI failures, conflicts and drafts alone do not count, nor
109
+ reopened tickets or mode switches.
100
110
 
101
- Checks hold for input.
102
111
  If returns keep hitting the same mechanism, fix the bug class once; cover its variants with one table test. Put remaining edges with no user-visible effect under Risk in the PR description. Still fix P0/P1 and user-visible findings in this PR.
103
112
  `projects[].columns[].courseCheckTo`: `operator`, curator or column orchestrator.
104
113
  Default: curator (`projects[].spurProjects[].role`), else operator. An answer
105
114
  resets the course count and reaches the worker as a task comment. Only the
106
115
  operator can resolve the separate cycle limit and reset its count. With no live
107
116
  session it falls back to the operator; a live conductor that does not
108
- answer keeps the question, with intervention item.
117
+ answer keeps the question.
109
118
 
110
119
  ## Blocks and escalation
111
120
 
@@ -123,13 +132,13 @@ Taskless: all roles, operator only:
123
132
  Project `needs_input` blocks get Slack threads except operator-agent asks;
124
133
  operator: `board inbox`, keyed `board answer`. Answers reach a current curator session; other roles use the asking session.
125
134
 
126
- Routing: `projects[].columns[].orchestrator`, `projects[].spurProjects[].role`,
127
- `operator.slack` (Slack user ID). Roles follow session.
135
+ `projects[].columns[].orchestrator`, `projects[].spurProjects[].role`,
136
+ `operator.slack`.
128
137
 
129
138
  ## Slack now
130
139
 
131
140
  `slack.channels.feed`: curator answers and operator items,
132
- except items elsewhere/delivery problems.
141
+ except elsewhere/delivery problems.
133
142
  `slack.channels.orchestrators`: block threads addressed to the operator by
134
143
  others. Answer in the existing block thread.
135
144
 
@@ -144,13 +153,12 @@ Middle mentions or Slack `<@U…>` address nobody; unknown names cause no lookup
144
153
  error. The operator checks short-name collisions with workspace names.
145
154
  A task key after the prefix attaches it.
146
155
 
147
- Given block ID, read `board inbox`, reply with
148
- `board answer`. Each operator thread message rings again; `close` or ✅ in the
156
+ Read `board inbox`; reply with `board answer`. Each operator thread message rings again; `close` or ✅ in the
149
157
  thread closes it. Replies use `projects[].spurProjects[].displayName` and `icon`,
150
- else project name/role icon (`board` for operator). No session:
158
+ else project/role icon. No session:
151
159
  `board status` lists it as waiting.
152
160
 
153
161
  ## Done follows the ticket
154
162
 
155
- One linked PR merging does not by itself finish the task. Done per ticket: `projects[].tracker.doneStatuses` for Jira; for GitHub, the Issue must be
163
+ One linked PR merging does not by itself finish the task. Done: `projects[].tracker.doneStatuses` for Jira; for GitHub, the Issue must be
156
164
  closed. If open after merge, link another PR.