spur-board 0.159.0 → 0.160.1

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.
@@ -195,7 +195,7 @@ const SUBMISSION_BASES = [
195
195
  * when the task moved on (it also covers returns and mode switches recorded by older versions),
196
196
  * `corrected` by the operator's column correction, `rerouted` to another executor,
197
197
  * `mode_changed` by a dispatcher mode switch, `archived` with the task. `moved` also closes a
198
- * Done wrap-up turn whose holder session ended.
198
+ * Done wrap-up turn whose holder session ended, or an untaken one with no recipient left.
199
199
  */
200
200
  const TURN_OUTCOMES = [
201
201
  "submitted",
@@ -3313,11 +3313,20 @@ const statusUnlinkedPrSchema = prFactsSchema.partial({
3313
3313
  const statusUnlinkedSessionSchema = statusSessionFactsSchema.partial({
3314
3314
  pr: true,
3315
3315
  links: true,
3316
+ lifecycle: true,
3317
+ health: true,
3316
3318
  healthSince: true,
3317
3319
  lastActivityAt: true,
3318
3320
  endedAt: true,
3319
3321
  endReason: true
3320
- }).describe("A session without a task link; fields beyond its identity need detail.");
3322
+ }).extend({
3323
+ state: z.enum([
3324
+ "live",
3325
+ "ended",
3326
+ "absent"
3327
+ ]).describe("live while listed by Spur; ended once it ended, vanished, or Spur lists it completed, killed or errored; absent once a complete Spur poll left it out of the list."),
3328
+ since: z.iso.datetime().nullable().describe("When the session ended or left the list, ISO 8601 UTC; null while live.")
3329
+ }).describe("A session without a task link. Compact rows carry id, spurProject, branch, state and since, plus lifecycle and health while live. Detail rows add the other session facts; ended and absent rows keep a completed, killed or errored lifecycle but leave out health, healthSince and rateLimitResetAt.");
3321
3330
  const statusItemSchema = itemViewSchema.extend({
3322
3331
  key: z.string().min(1).describe("Stable key of this actionable item."),
3323
3332
  unconfirmed: z.boolean().describe("Whether a supporting fact is stale or its source is blind."),
@@ -3736,7 +3745,7 @@ const statusOutputSchema = z.strictObject({
3736
3745
  openBlocks: z.int().min(0).describe("Open project-level blocks, without a task.")
3737
3746
  }).describe("Open project-level blocks of one project.")).describe("Open project-level blocks of each requested project."),
3738
3747
  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."),
3739
- 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."),
3748
+ unlinkedSessions: z.array(statusUnlinkedSessionSchema).describe("Observed sessions without a task link, each with its state (live, ended or absent) and since when; ones ended, or gone from Spur's session list, for over 7 days are left out, but not an errored session Spur still lists."),
3740
3749
  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."),
3741
3750
  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."),
3742
3751
  bindings: statusBindingsSchema,
@@ -1,5 +1,5 @@
1
- import { At as plainHttpAllowed, Dt as configSchema, f as buildCatalogSnapshot, m as OPERATIONS } from "./chunk-BUxxW9le.mjs";
2
- import { o as CliError, t as fetchCatalogVersion } from "./chunk-f54aP3OF.mjs";
1
+ import { At as plainHttpAllowed, Dt as configSchema, f as buildCatalogSnapshot, m as OPERATIONS } from "./chunk-C4g6_v8X.mjs";
2
+ import { o as CliError, t as fetchCatalogVersion } from "./chunk-DrCDq9Bd.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";
@@ -1,4 +1,4 @@
1
- import { dt as ERRORS, gt as successEnvelopeSchema, l as tokenRequestStatusSchema, mt as errorEnvelopeSchema, pt as errorContextSchema, s as tokenRequestResultSchema, y as renderJsonError } from "./chunk-BUxxW9le.mjs";
1
+ import { dt as ERRORS, gt as successEnvelopeSchema, l as tokenRequestStatusSchema, mt as errorEnvelopeSchema, pt as errorContextSchema, s as tokenRequestResultSchema, y as renderJsonError } from "./chunk-C4g6_v8X.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 { Bt as SLACK_BOT_SCOPES, D as skillReloadFileSchema, Dt as configSchema, Mt as requiredSecretKeys, Nt as resolveWebOrigin, d as SYSTEMD_SERVICE_SETTINGS, dt as ERRORS, gt as successEnvelopeSchema, i as remoteDoctorReportSchema, k as sortSkillFiles, m as OPERATIONS, o as requestHashOf, ot as actorIdSchema, p as roleCanUseOperation, xt as DEFAULT_STAND_PORT_RANGE } from "./chunk-BUxxW9le.mjs";
1
+ import { Bt as SLACK_BOT_SCOPES, D as skillReloadFileSchema, Dt as configSchema, Mt as requiredSecretKeys, Nt as resolveWebOrigin, d as SYSTEMD_SERVICE_SETTINGS, dt as ERRORS, gt as successEnvelopeSchema, i as remoteDoctorReportSchema, k as sortSkillFiles, m as OPERATIONS, o as requestHashOf, ot as actorIdSchema, p as roleCanUseOperation, xt as DEFAULT_STAND_PORT_RANGE } from "./chunk-C4g6_v8X.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-f54aP3OF.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-BVb6nX0w.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-DrCDq9Bd.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-De2rPW0w.mjs";
5
5
  import { createHash, randomBytes, randomUUID } from "node:crypto";
6
6
  import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
7
7
  import { homedir, hostname, tmpdir, userInfo } from "node:os";
package/dist/client.mjs CHANGED
@@ -1 +1 @@
1
- export { t as fetchCatalogVersion, n as fetchTokenStatus, r as requestOperation, i as requestSkillReload, a as requestTokenEnrollment } from "./chunk-f54aP3OF.mjs";
1
+ export { t as fetchCatalogVersion, n as fetchTokenStatus, r as requestOperation, i as requestSkillReload, a as requestTokenEnrollment } from "./chunk-DrCDq9Bd.mjs";
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as prRefSchema, A as EVENT_KINDS, At as plainHttpAllowed, B as prSourceId, Bt as SLACK_BOT_SCOPES, C as inboundEventSchema, Ct as approvalRuleOf, Dt as configSchema, E as userIdSchema, Et as configBindings, F as MIRROR_FAILURE_CODES, Ft as COLUMNS, G as REVIEW_DECISIONS, H as sourceCursorSchema, Ht as TODO_GROUP_COLUMN_IDS, I as batchSchema, It as COLUMN_GROUPS, J as SESSION_STATUSES, K as REVIEW_STATES, L as defaultBranchFactSchema, Lt as COLUMN_IDS, M as eventPayloadSchemas, Mt as requiredSecretKeys, N as AdapterError, Nt as resolveWebOrigin, O as skillReloadFilesSchema, Ot as defaultAddressee, P as MIRROR_FAILURES, Pt as BLOCK_TYPES, Q as prFactsSchema, R as entityRefSchema, Rt as DISPATCHER_MODES, S as conversationRefSchema, St as RESERVED_PROJECT, T as messageRefSchema, Tt as columnTurnTimings, U as trackerSourceId, Ut as VIAS, V as sessionTransitionSchema, Vt as TASK_HOLDS, W as PR_STATES, Wt as isTodoGroupColumn, X as parseRingMarker, Y as isExternalAuthor, Z as prApprovalPairSchema, _ as turnHandedSchema, a as TOKEN_REQUEST_LIMITS, at as REF_NUMBER, bt as DEFAULT_SLACK_COMMAND, c as tokenRequestSchema, ct as errorCodeOf, dt as ERRORS, et as prReviewRuleSchema, f as buildCatalogSnapshot, ft as err, g as inboxNoSessionSchema, gt as successEnvelopeSchema, h as defaultBranchViewSchema, ht as ok, it as JIRA_PROJECT_KEY, j as GATE_REASONS, jt as readyMirrorOf, k as sortSkillFiles, kt as externalQuietAfterMs, l as tokenRequestStatusSchema, lt as parseActorId, m as OPERATIONS, n as SPUR_MIN_VERSION, nt as sessionFactsSchema, o as requestHashOf, ot as actorIdSchema, p as roleCanUseOperation, q as SESSION_HEALTH_STATES, r as doctorReportSchema, rt as ticketFactsSchema, s as tokenRequestResultSchema, st as encodeActorId, t as assertNever, tt as ringMarker, u as BOARD_TICK_MS, ut as parseRef$1, v as renderHttpProblem, vt as DEFAULT_LINK, w as interactionRefSchema, wt as boardWideSpurProject, x as SPACE_IDS, z as mirrorSourceId, zt as ITEM_KINDS } from "./chunk-BUxxW9le.mjs";
1
+ import { $ as prRefSchema, A as EVENT_KINDS, At as plainHttpAllowed, B as prSourceId, Bt as SLACK_BOT_SCOPES, C as inboundEventSchema, Ct as approvalRuleOf, Dt as configSchema, E as userIdSchema, Et as configBindings, F as MIRROR_FAILURE_CODES, Ft as COLUMNS, G as REVIEW_DECISIONS, H as sourceCursorSchema, Ht as TODO_GROUP_COLUMN_IDS, I as batchSchema, It as COLUMN_GROUPS, J as SESSION_STATUSES, K as REVIEW_STATES, L as defaultBranchFactSchema, Lt as COLUMN_IDS, M as eventPayloadSchemas, Mt as requiredSecretKeys, N as AdapterError, Nt as resolveWebOrigin, O as skillReloadFilesSchema, Ot as defaultAddressee, P as MIRROR_FAILURES, Pt as BLOCK_TYPES, Q as prFactsSchema, R as entityRefSchema, Rt as DISPATCHER_MODES, S as conversationRefSchema, St as RESERVED_PROJECT, T as messageRefSchema, Tt as columnTurnTimings, U as trackerSourceId, Ut as VIAS, V as sessionTransitionSchema, Vt as TASK_HOLDS, W as PR_STATES, Wt as isTodoGroupColumn, X as parseRingMarker, Y as isExternalAuthor, Z as prApprovalPairSchema, _ as turnHandedSchema, a as TOKEN_REQUEST_LIMITS, at as REF_NUMBER, bt as DEFAULT_SLACK_COMMAND, c as tokenRequestSchema, ct as errorCodeOf, dt as ERRORS, et as prReviewRuleSchema, f as buildCatalogSnapshot, ft as err, g as inboxNoSessionSchema, gt as successEnvelopeSchema, h as defaultBranchViewSchema, ht as ok, it as JIRA_PROJECT_KEY, j as GATE_REASONS, jt as readyMirrorOf, k as sortSkillFiles, kt as externalQuietAfterMs, l as tokenRequestStatusSchema, lt as parseActorId, m as OPERATIONS, n as SPUR_MIN_VERSION, nt as sessionFactsSchema, o as requestHashOf, ot as actorIdSchema, p as roleCanUseOperation, q as SESSION_HEALTH_STATES, r as doctorReportSchema, rt as ticketFactsSchema, s as tokenRequestResultSchema, st as encodeActorId, t as assertNever, tt as ringMarker, u as BOARD_TICK_MS, ut as parseRef$1, v as renderHttpProblem, vt as DEFAULT_LINK, w as interactionRefSchema, wt as boardWideSpurProject, x as SPACE_IDS, z as mirrorSourceId, zt as ITEM_KINDS } from "./chunk-C4g6_v8X.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";
@@ -14537,6 +14537,82 @@ function sessionView(fact) {
14537
14537
  }))
14538
14538
  };
14539
14539
  }
14540
+ /** Lifecycles after which Spur's session is over, even while Spur still lists it. */
14541
+ const TERMINAL_LIFECYCLES = [
14542
+ "completed",
14543
+ "killed",
14544
+ "errored"
14545
+ ];
14546
+ /**
14547
+ * Whether an unlinked session is live, ended or gone from Spur's list, and since when. Ended wins
14548
+ * over absent; a session ended at the earlier of its finish and end times, and a listed completed,
14549
+ * killed or errored session ended when it finished.
14550
+ */
14551
+ function unlinkedSessionState(session) {
14552
+ if (session.ended_at !== null) return {
14553
+ state: "ended",
14554
+ since: earliestTime([session.finished_at, session.ended_at]) ?? session.ended_at
14555
+ };
14556
+ if (TERMINAL_LIFECYCLES.includes(session.state)) return {
14557
+ state: "ended",
14558
+ since: session.finished_at ?? session.last_seen
14559
+ };
14560
+ if (session.absent_since !== null) return {
14561
+ state: "absent",
14562
+ since: session.absent_since
14563
+ };
14564
+ return {
14565
+ state: "live",
14566
+ since: null
14567
+ };
14568
+ }
14569
+ /**
14570
+ * An unlinked session row: ended and absent ones leave out health and their last live lifecycle;
14571
+ * in detail they keep a terminal lifecycle, which tells completion from kill or error.
14572
+ */
14573
+ function unlinkedSessionView(session, facts, detail) {
14574
+ const shown = unlinkedSessionState(session);
14575
+ const live = shown.state === "live";
14576
+ if (detail) {
14577
+ const view = sessionView(facts);
14578
+ if (live) return {
14579
+ ...view,
14580
+ ...shown
14581
+ };
14582
+ const { id, spurProject, branch, pr, links, lastActivityAt } = view;
14583
+ const rings = view.queuedRings === void 0 ? {} : { queuedRings: view.queuedRings };
14584
+ const terminal = TERMINAL_LIFECYCLES.includes(session.state) ? { lifecycle: view.lifecycle } : {};
14585
+ const finished = session.state === "completed" || session.state === "killed";
14586
+ const { endedAt, endReason } = view.endReason === null && finished ? {
14587
+ endedAt: shown.since,
14588
+ endReason: session.state === "completed" ? "complete" : "kill"
14589
+ } : view;
14590
+ return {
14591
+ id,
14592
+ spurProject,
14593
+ branch,
14594
+ pr,
14595
+ links,
14596
+ ...terminal,
14597
+ lastActivityAt,
14598
+ endedAt,
14599
+ endReason,
14600
+ ...rings,
14601
+ ...shown
14602
+ };
14603
+ }
14604
+ const { id, spurProject, branch, lifecycle, health } = facts;
14605
+ return {
14606
+ id,
14607
+ spurProject,
14608
+ branch,
14609
+ ...shown,
14610
+ ...live ? {
14611
+ lifecycle,
14612
+ health
14613
+ } : {}
14614
+ };
14615
+ }
14540
14616
  /** Order group visits in their own slots, preserving non-group relative ordering. */
14541
14617
  function orderTodoGroupRows(rows, entries, projects) {
14542
14618
  const columnEntries = new Map(entries.map((entry) => [entry.task_id, entry.at]));
@@ -15543,13 +15619,18 @@ async function turnsWithoutSession(trx, config, now, taskById) {
15543
15619
  /**
15544
15620
  * Reconciles every item in the caller's observation or tick transaction. It first closes each
15545
15621
  * Done wrap-up turn whose holder session ended (`closeEndedDoneTurns`), so no stall item is
15546
- * raised for it.
15622
+ * raised for it, and, while Spur is current, each untaken one left with no recipient
15623
+ * (`closeUnaddressedDoneTurns`).
15547
15624
  */
15548
15625
  async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurContinuityStartAt) {
15549
- await closeEndedDoneTurns(trx, new Date(now));
15550
- const candidates = [];
15551
15626
  const sources = await trx.selectFrom("source_state").selectAll().execute();
15552
15627
  const sourceById = new Map(sources.map((state) => [state.source, state]));
15628
+ const spur = sourceById.get("spur");
15629
+ const spurBlind = spur !== void 0 && spur.blind_reason !== null;
15630
+ const spurExpired = spur?.last_complete_at != null && now > Date.parse(spur.last_complete_at) + config.adapters.spur.intervalMs * config.thresholds.staleMultiplier;
15631
+ await closeEndedDoneTurns(trx, new Date(now));
15632
+ if (!(spurBlind || !spurComplete || spurExpired)) await closeUnaddressedDoneTurns(trx, config, new Date(now));
15633
+ const candidates = [];
15553
15634
  for (const source of sources) {
15554
15635
  if (source.blind_reason === null) continue;
15555
15636
  if (source.blind_reason === "stale" && source.source !== "spur") continue;
@@ -15670,8 +15751,6 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurC
15670
15751
  source: null,
15671
15752
  priority: ITEM_POLICY.post_failed.priority
15672
15753
  });
15673
- const spur = sourceById.get("spur");
15674
- const spurBlind = spur !== void 0 && spur.blind_reason !== null;
15675
15754
  const subjects = (await trx.selectFrom("link").innerJoin("session_snapshot", "session_snapshot.id", "link.session_id").select([
15676
15755
  "link.task_id",
15677
15756
  "link.role",
@@ -15849,7 +15928,6 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurC
15849
15928
  observedAt: null,
15850
15929
  resumedAt: null
15851
15930
  } : parseJson(stallObservationSchema, observationRow.value);
15852
- const spurExpired = spur?.last_complete_at != null && now > Date.parse(spur.last_complete_at) + config.adapters.spur.intervalMs * config.thresholds.staleMultiplier;
15853
15931
  const observation = spurBlind || !spurComplete || spurExpired ? {
15854
15932
  ...previousObservation,
15855
15933
  blind: true,
@@ -15883,11 +15961,7 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurC
15883
15961
  }, config) : void 0;
15884
15962
  if (executor === void 0 && turn.acked_at === null) {
15885
15963
  const target = config.projects.find((entry) => entry.id === task.project)?.columns.find((entry) => entry.id === turn.column)?.orchestrator;
15886
- 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();
15887
- 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) {
15888
- executor = row;
15889
- break;
15890
- }
15964
+ executor = await stoppedExecutor(trx, task.id, turn.role, target);
15891
15965
  }
15892
15966
  if (executor === void 0 || executor.ended_at !== null || executor.absent_since !== null) {
15893
15967
  await observeTurnEpisode(trx, turn.id, null);
@@ -15992,8 +16066,24 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurC
15992
16066
  }).onConflict((oc) => oc.column("key").doUpdateSet({ value: toJson(episodeSchema, health.episode) })).execute();
15993
16067
  const resting = await restingHolders(trx, config, now);
15994
16068
  const restingIdle = (flag) => flag.kind === "worker_idle" && resting.has(`${flag.taskId}:${flag.sessionId}`);
16069
+ const turnTasks = new Set(turns.map((turn) => turn.task_id));
16070
+ const latestDoneTurns = new Map((await trx.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").select([
16071
+ "turn.task_id",
16072
+ "turn.acked_at",
16073
+ "turn.role",
16074
+ "turn.closed_reason"
16075
+ ]).where("turn.column", "=", "done").where("task.column", "=", "done").whereRef("turn.epoch", "=", "task.column_epoch").orderBy("turn.id").execute()).map((turn) => [turn.task_id, turn]));
16076
+ const unaddressedDone = new Set([...latestDoneTurns.values()].filter((turn) => turn.closed_reason === "moved" && turn.acked_at === null && turn.role === "worker").map((turn) => turn.task_id));
16077
+ const addressed = /* @__PURE__ */ new Set();
16078
+ for (const taskId of unaddressedDone) {
16079
+ if (!taskById.has(taskId) || turnTasks.has(taskId)) continue;
16080
+ const session = await stoppedExecutor(trx, taskId, "worker", void 0);
16081
+ if (session !== void 0) addressed.add(`${String(taskId)}:${session.id}`);
16082
+ }
16083
+ const stoppedInDone = new Set(subjects.filter((subject) => subject.role === "worker" && subject.lifecycle === "stopped" && subject.endedAt === null && addressed.has(`${subject.taskId}:${subject.id}`)).map((subject) => `${subject.taskId}:${subject.id}`));
16084
+ const stoppedRetained = (flag) => ["stuck_worker", "needs_input"].includes(flag.kind) && stoppedInDone.has(`${flag.taskId}:${flag.sessionId}`);
15995
16085
  for (const flag of health.flags) {
15996
- if (endedHolders.has(`${flag.taskId}:${flag.sessionId}`) || restingIdle(flag)) continue;
16086
+ if (endedHolders.has(`${flag.taskId}:${flag.sessionId}`) || restingIdle(flag) || stoppedRetained(flag)) continue;
15997
16087
  const task = taskById.get(Number(flag.taskId));
15998
16088
  if (task === void 0) continue;
15999
16089
  const fact = subjects.find((subject) => subject.taskId === flag.taskId && subject.id === flag.sessionId);
@@ -16054,12 +16144,12 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped, spurC
16054
16144
  const ordered = orderItems(candidates);
16055
16145
  const seen = /* @__PURE__ */ new Set([...ordered.map((item) => item.key), ...heldKeys]);
16056
16146
  for (const flag of health.held) {
16057
- if (endedHolders.has(`${flag.taskId}:${flag.sessionId}`) || restingIdle(flag)) continue;
16147
+ if (endedHolders.has(`${flag.taskId}:${flag.sessionId}`) || restingIdle(flag) || stoppedRetained(flag)) continue;
16058
16148
  const task = taskById.get(Number(flag.taskId));
16059
16149
  if (task !== void 0 && !stalled.has(`${flag.taskId}:${flag.sessionId}`)) seen.add(healthKey(task.id, flag));
16060
16150
  }
16061
16151
  const existing = await trx.selectFrom("operator_item").selectAll().where("kind", "in", RECONCILED_KINDS).where("cleared_at", "is", null).execute();
16062
- 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), {
16152
+ 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}`) && !stoppedInDone.has(`${subject.taskId}:${subject.id}`)).map((subject) => healthKey(Number(subject.taskId), {
16063
16153
  taskId: subject.taskId,
16064
16154
  sessionId: subject.id,
16065
16155
  kind: subject.role === "worker" ? "stuck_worker" : "stuck_orchestrator"
@@ -16200,6 +16290,26 @@ async function closeEndedDoneTurns(trx, at) {
16200
16290
  for (const item of items) await clearReconciled(trx, item, at, reason);
16201
16291
  }
16202
16292
  }
16293
+ /**
16294
+ * Closes, as `moved`, each untaken worker-role Done wrap-up turn of an unarchived Done task when
16295
+ * no recipient is left: no live worker session is linked to the task and Done has no
16296
+ * orchestrator. The caller runs it only while Spur is current, so a missed session end does not
16297
+ * close a turn a live worker still holds.
16298
+ */
16299
+ async function closeUnaddressedDoneTurns(trx, config, at) {
16300
+ const turns = await trx.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").select(["turn.task_id", "task.project"]).where("turn.closed_at", "is", null).where("turn.acked_at", "is", null).where("turn.role", "=", "worker").where("turn.column", "=", "done").where("task.column", "=", "done").where("task.membership", "!=", "archived").orderBy("turn.id").execute();
16301
+ for (const turn of turns) {
16302
+ const project = config.projects.find((candidate) => candidate.id === turn.project);
16303
+ if (project === void 0) continue;
16304
+ if ((project.columns.find((column) => column.id === "done")?.orchestrator ?? "none") !== "none") continue;
16305
+ if (await linkedSession(trx, turn.task_id, "worker") !== void 0) continue;
16306
+ await closeTurns(trx, {
16307
+ taskId: turn.task_id,
16308
+ reason: "moved",
16309
+ at
16310
+ });
16311
+ }
16312
+ }
16203
16313
  /** Raise ended-holder attention from ownership, independent of links, PRs and source freshness. */
16204
16314
  async function endedTurnItems(trx, tasks, candidates, at, spurConfirmedAt) {
16205
16315
  const holders = /* @__PURE__ */ new Set();
@@ -16280,6 +16390,20 @@ async function observeTurnEpisode(trx, turnId, fact) {
16280
16390
  }).onConflict((oc) => oc.column("key").doUpdateSet({ value: toJson(stallEpisodeSchema, episode) })).execute();
16281
16391
  return episode;
16282
16392
  }
16393
+ /**
16394
+ * The stopped session an untaken turn of `role` with no live recipient is diagnosed against: the
16395
+ * newest stopped, present session linked to the task in that role, or for a column orchestrator
16396
+ * turn one of the column's orchestrator project `target`. It runs on every reconcile, so each
16397
+ * query is scoped to the task's links or to that project.
16398
+ */
16399
+ async function stoppedExecutor(trx, taskId, role, target) {
16400
+ const newestStopped = trx.selectFrom("session_snapshot").selectAll("session_snapshot").where("session_snapshot.state", "=", "stopped").where("session_snapshot.ended_at", "is", null).where("session_snapshot.absent_since", "is", null).orderBy("session_snapshot.first_seen", "desc").orderBy("session_snapshot.id").limit(1);
16401
+ const linked = await newestStopped.innerJoin("link", "link.session_id", "session_snapshot.id").where("link.task_id", "=", taskId).where("link.entity", "=", "session").where("link.role", "=", role === "worker" ? "worker" : "orchestrator").where("link.banned", "=", 0).executeTakeFirst();
16402
+ if (role === "worker" || target === void 0) return linked;
16403
+ const inProject = await newestStopped.where("session_snapshot.spur_project", "=", target).executeTakeFirst();
16404
+ if (linked === void 0 || inProject === void 0) return linked ?? inProject;
16405
+ return inProject.first_seen > linked.first_seen || inProject.first_seen === linked.first_seen && inProject.id < linked.id ? inProject : linked;
16406
+ }
16283
16407
  function healthKey(taskId, flag) {
16284
16408
  return `health:${String(taskId)}:${flag.sessionId}:${flag.kind}`;
16285
16409
  }
@@ -18729,18 +18853,7 @@ async function getStatus(deps, options = {}) {
18729
18853
  const hiddenSession = (session) => {
18730
18854
  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);
18731
18855
  };
18732
- const unlinkedSessions = sessionRows.filter((session) => !hiddenSession(session)).map((session) => {
18733
- const facts = parseJson(sessionFactsSchema, session.detail);
18734
- if (detail) return sessionView(facts);
18735
- const { id, spurProject, branch, lifecycle, health } = facts;
18736
- return {
18737
- id,
18738
- spurProject,
18739
- branch,
18740
- lifecycle,
18741
- health
18742
- };
18743
- });
18856
+ const unlinkedSessions = sessionRows.filter((session) => !hiddenSession(session)).map((session) => unlinkedSessionView(session, parseJson(sessionFactsSchema, session.detail), detail));
18744
18857
  const sourceIds = (scope, mirrors) => /* @__PURE__ */ new Set(["spur", ...scope.flatMap((project) => {
18745
18858
  const mirror = mirrors ? mirrorSourceId(project) : void 0;
18746
18859
  return [
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { b as renderMcpError, dt as ERRORS, m as OPERATIONS } from "./chunk-BUxxW9le.mjs";
2
- import { o as CliError, r as requestOperation } from "./chunk-f54aP3OF.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-BVb6nX0w.mjs";
1
+ import { b as renderMcpError, dt as ERRORS, m as OPERATIONS } from "./chunk-C4g6_v8X.mjs";
2
+ import { o as CliError, r as requestOperation } from "./chunk-DrCDq9Bd.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-De2rPW0w.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";