spur-board 0.59.2 → 0.59.3
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/{chunk-DjdHFn4C.mjs → chunk-BLpo-8dp.mjs} +2 -2
- package/dist/{chunk-ZywNbxbW.mjs → chunk-CLjE9L59.mjs} +26 -8
- package/dist/{chunk-BY5dr3F6.mjs → chunk-DQwj2UTj.mjs} +1 -1
- package/dist/cli.mjs +3 -3
- package/dist/client.mjs +1 -1
- package/dist/daemon.mjs +427 -63
- package/dist/mcp.mjs +3 -3
- package/dist/migrations/0019_pr_polling.sql +9 -0
- package/package.json +1 -1
- package/skills/spur-board/references/commands.md +4 -4
- package/skills/spur-board/references/errors.md +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { _ as buildCatalogSnapshot, ct as plainHttpAllowed, st as configSchema, y as OPERATIONS } from "./chunk-
|
|
2
|
-
import { o as CliError, t as fetchCatalogVersion } from "./chunk-
|
|
1
|
+
import { _ as buildCatalogSnapshot, ct as plainHttpAllowed, st as configSchema, y as OPERATIONS } from "./chunk-CLjE9L59.mjs";
|
|
2
|
+
import { o as CliError, t as fetchCatalogVersion } from "./chunk-DQwj2UTj.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";
|
|
@@ -802,9 +802,9 @@ const ERRORS = {
|
|
|
802
802
|
github_unavailable: spec("github_unavailable", {
|
|
803
803
|
status: 503,
|
|
804
804
|
exit: EXIT_CODES.notApplied,
|
|
805
|
-
message: "GitHub did not confirm
|
|
806
|
-
hint: "Wait until GitHub answers, then
|
|
807
|
-
recovery: retry("Wait until GitHub answers, then
|
|
805
|
+
message: "GitHub did not confirm current pull request facts.",
|
|
806
|
+
hint: "Wait until GitHub answers, then retry the operation.",
|
|
807
|
+
recovery: retry("Wait until GitHub answers, then retry the operation.", "After GitHub is reachable; wait briefly between retries.")
|
|
808
808
|
}),
|
|
809
809
|
version_mismatch: spec("version_mismatch", {
|
|
810
810
|
status: 409,
|
|
@@ -2052,6 +2052,7 @@ const statusItemSchema = itemViewSchema.extend({
|
|
|
2052
2052
|
factAt: z.iso.datetime().nullable().describe("Time of the supporting fact, when known.")
|
|
2053
2053
|
}).describe("An actionable item with its freshness mark.");
|
|
2054
2054
|
const sourceViewSchema = z.strictObject({
|
|
2055
|
+
pointsLastHour: z.int().nonnegative().optional().describe("Reported source points consumed during the preceding hour."),
|
|
2055
2056
|
source: z.string().min(1).describe("Adapter source identifier."),
|
|
2056
2057
|
observedAt: z.iso.datetime().nullable().describe("Time of the latest observation, if any."),
|
|
2057
2058
|
lastCompleteAt: z.iso.datetime().nullable().describe("Time of the latest complete observation."),
|
|
@@ -2427,13 +2428,14 @@ const OPERATIONS = [
|
|
|
2427
2428
|
defineOperation({
|
|
2428
2429
|
id: "task.get",
|
|
2429
2430
|
kind: "query",
|
|
2430
|
-
description: "Show a task
|
|
2431
|
+
description: "Show a task; refresh reads GitHub PRs.",
|
|
2431
2432
|
mcp: {
|
|
2432
|
-
whenToUse: "Inspect
|
|
2433
|
+
whenToUse: "Inspect a task; detail adds closed turns.",
|
|
2433
2434
|
whenNotToUse: "Use task_history for past events."
|
|
2434
2435
|
},
|
|
2435
2436
|
input: z.strictObject({
|
|
2436
2437
|
task: taskKeyInputSchema,
|
|
2438
|
+
refresh: z.boolean().optional().describe("Read every linked pull request from GitHub before showing the task; unavailable reads fail visibly."),
|
|
2437
2439
|
detail: z.boolean().optional().describe("Also list the last 5 closed turns, newest first; absent means none."),
|
|
2438
2440
|
why: z.boolean().optional().describe("Explain why the task is in its column: gates, holds, the open turn and the last moves; absent means no explanation.")
|
|
2439
2441
|
}),
|
|
@@ -2447,7 +2449,11 @@ const OPERATIONS = [
|
|
|
2447
2449
|
why: taskWhySchema.optional().describe("Present only with why.")
|
|
2448
2450
|
}),
|
|
2449
2451
|
grants: operatorOrProjectAgent,
|
|
2450
|
-
errors: [
|
|
2452
|
+
errors: [
|
|
2453
|
+
"wrong_id_kind",
|
|
2454
|
+
"not_found",
|
|
2455
|
+
"github_unavailable"
|
|
2456
|
+
],
|
|
2451
2457
|
cli: {
|
|
2452
2458
|
command: "task",
|
|
2453
2459
|
args: ["task"]
|
|
@@ -2886,7 +2892,7 @@ const OPERATIONS = [
|
|
|
2886
2892
|
defineOperation({
|
|
2887
2893
|
id: "link.add",
|
|
2888
2894
|
kind: "mutation",
|
|
2889
|
-
description: "Manually link a pull request, session, or additional ticket to a task.",
|
|
2895
|
+
description: "Manually link a pull request, session, or additional ticket to a task. Pull request links first read current facts from GitHub.",
|
|
2890
2896
|
mcp: {
|
|
2891
2897
|
whenToUse: "Attach a pull request, session, or additional ticket.",
|
|
2892
2898
|
whenNotToUse: "Use link_remove to detach one."
|
|
@@ -2898,7 +2904,8 @@ const OPERATIONS = [
|
|
|
2898
2904
|
"wrong_id_kind",
|
|
2899
2905
|
"not_found",
|
|
2900
2906
|
"task_archived",
|
|
2901
|
-
"link_conflict"
|
|
2907
|
+
"link_conflict",
|
|
2908
|
+
"github_unavailable"
|
|
2902
2909
|
],
|
|
2903
2910
|
cli: {
|
|
2904
2911
|
command: "link",
|
|
@@ -3802,6 +3809,16 @@ const batchSchema = z.strictObject({
|
|
|
3802
3809
|
ref: entityRefSchema.describe("The requested entity."),
|
|
3803
3810
|
status: z.enum(ENTITY_STATUSES).describe("What the source answered for it.")
|
|
3804
3811
|
})).describe("One entry per entity core asked for (A4)."),
|
|
3812
|
+
prProbes: z.array(z.strictObject({
|
|
3813
|
+
ref: prRefSchema.extend({ kind: z.literal("pr").describe("A pull request.") }).describe("The rechecked PR."),
|
|
3814
|
+
status: z.enum([
|
|
3815
|
+
"closed",
|
|
3816
|
+
"refreshed",
|
|
3817
|
+
"not_found",
|
|
3818
|
+
"no_access"
|
|
3819
|
+
]).describe("Unchanged closed state, full refresh, or failed lookup.")
|
|
3820
|
+
})).optional().describe("State-only PR rechecks, separate from normal entity coverage."),
|
|
3821
|
+
usage: z.strictObject({ points: z.int().nonnegative().describe("Reported points consumed.") }).optional().describe("Reported source points consumed by this attempt."),
|
|
3805
3822
|
budget: z.strictObject({
|
|
3806
3823
|
remaining: z.int().min(0).describe("Requests or points the source still allows."),
|
|
3807
3824
|
resetAt: z.iso.datetime().describe("When the source restores the full budget.")
|
|
@@ -3859,6 +3876,7 @@ function trackerSourceId(project) {
|
|
|
3859
3876
|
var AdapterError = class extends Error {
|
|
3860
3877
|
kind;
|
|
3861
3878
|
retryAt;
|
|
3879
|
+
usage;
|
|
3862
3880
|
constructor(kind, message, options = {}) {
|
|
3863
3881
|
super(message, "cause" in options ? { cause: options.cause } : void 0);
|
|
3864
3882
|
this.name = "AdapterError";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as errorEnvelopeSchema, Q as errorContextSchema, S as renderJsonError, X as ERRORS, c as tokenRequestStatusSchema, o as tokenRequestResultSchema, tt as successEnvelopeSchema } from "./chunk-
|
|
1
|
+
import { $ as errorEnvelopeSchema, Q as errorContextSchema, S as renderJsonError, X as ERRORS, c as tokenRequestStatusSchema, o as tokenRequestResultSchema, tt as successEnvelopeSchema } from "./chunk-CLjE9L59.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 { G as actorIdSchema, X as ERRORS, a as requestHashOf, ft as SLACK_BOT_SCOPES, lt as requiredSecretKeys, r as remoteDoctorReportSchema, st as configSchema, tt as successEnvelopeSchema, u as SYSTEMD_SERVICE_SETTINGS, v as roleCanUseOperation, y as OPERATIONS } from "./chunk-
|
|
1
|
+
import { G as actorIdSchema, X as ERRORS, a as requestHashOf, ft as SLACK_BOT_SCOPES, lt as requiredSecretKeys, r as remoteDoctorReportSchema, st as configSchema, tt as successEnvelopeSchema, u as SYSTEMD_SERVICE_SETTINGS, v as roleCanUseOperation, y as OPERATIONS } from "./chunk-CLjE9L59.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-
|
|
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-
|
|
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-DQwj2UTj.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-BLpo-8dp.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-
|
|
1
|
+
import { a as requestTokenEnrollment, i as requestSkillReload, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./chunk-DQwj2UTj.mjs";
|
|
2
2
|
export { fetchCatalogVersion, fetchTokenStatus, requestOperation, requestSkillReload, requestTokenEnrollment };
|
package/dist/daemon.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as EVENT_KINDS, B as ringMarker, D as interactionRefSchema, E as inboundEventSchema, F as SESSION_STATUSES, G as actorIdSchema, H as ticketFactsSchema, I as isExternalAuthor, J as parseActorId, K as encodeActorId, L as parseRingMarker, M as PR_STATES, N as REVIEW_STATES, O as messageRefSchema, P as SESSION_HEALTH_STATES, R as prFactsSchema, T as conversationRefSchema, U as JIRA_PROJECT_KEY, V as sessionFactsSchema, W as REF_NUMBER, X as ERRORS, Y as parseRef$1, Z as err, _ as buildCatalogSnapshot, a as requestHashOf, at as DEFAULT_SLACK_COMMAND, b as turnHandedSchema, c as tokenRequestStatusSchema, ct as plainHttpAllowed, d as AdapterError, dt as DISPATCHER_MODES, et as ok, f as batchSchema, ft as SLACK_BOT_SCOPES, g as trackerSourceId, h as sourceCursorSchema, i as TOKEN_REQUEST_LIMITS, j as eventPayloadSchemas, k as userIdSchema, l as BOARD_TICK_MS, lt as requiredSecretKeys, m as prSourceId, n as doctorReportSchema, o as tokenRequestResultSchema, ot as RESERVED_PROJECT, p as entityRefSchema, pt as TASK_HOLDS, q as errorCodeOf, rt as DEFAULT_LINK, s as tokenRequestSchema, st as configSchema, t as assertNever, tt as successEnvelopeSchema, ut as COLUMN_IDS, v as roleCanUseOperation, w as SPACE_IDS, x as renderHttpProblem, y as OPERATIONS, z as prRefSchema } from "./chunk-
|
|
1
|
+
import { A as EVENT_KINDS, B as ringMarker, D as interactionRefSchema, E as inboundEventSchema, F as SESSION_STATUSES, G as actorIdSchema, H as ticketFactsSchema, I as isExternalAuthor, J as parseActorId, K as encodeActorId, L as parseRingMarker, M as PR_STATES, N as REVIEW_STATES, O as messageRefSchema, P as SESSION_HEALTH_STATES, R as prFactsSchema, T as conversationRefSchema, U as JIRA_PROJECT_KEY, V as sessionFactsSchema, W as REF_NUMBER, X as ERRORS, Y as parseRef$1, Z as err, _ as buildCatalogSnapshot, a as requestHashOf, at as DEFAULT_SLACK_COMMAND, b as turnHandedSchema, c as tokenRequestStatusSchema, ct as plainHttpAllowed, d as AdapterError, dt as DISPATCHER_MODES, et as ok, f as batchSchema, ft as SLACK_BOT_SCOPES, g as trackerSourceId, h as sourceCursorSchema, i as TOKEN_REQUEST_LIMITS, j as eventPayloadSchemas, k as userIdSchema, l as BOARD_TICK_MS, lt as requiredSecretKeys, m as prSourceId, n as doctorReportSchema, o as tokenRequestResultSchema, ot as RESERVED_PROJECT, p as entityRefSchema, pt as TASK_HOLDS, q as errorCodeOf, rt as DEFAULT_LINK, s as tokenRequestSchema, st as configSchema, t as assertNever, tt as successEnvelopeSchema, ut as COLUMN_IDS, v as roleCanUseOperation, w as SPACE_IDS, x as renderHttpProblem, y as OPERATIONS, z as prRefSchema } from "./chunk-CLjE9L59.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";
|
|
@@ -8443,7 +8443,7 @@ function createQuery(deps) {
|
|
|
8443
8443
|
const parsed = entry.input.safeParse(input);
|
|
8444
8444
|
if (!parsed.success) throw new CommandError(errorCodeOf(parsed.error), "Fix the operation input.");
|
|
8445
8445
|
const parsedInput = parsed.data;
|
|
8446
|
-
const
|
|
8446
|
+
const read = (prepare) => store.transaction(async (trx) => {
|
|
8447
8447
|
const targets = await query.resolveTargets(trx, parsedInput, actor);
|
|
8448
8448
|
for (const target of targets.length === 0 ? [{ kind: "missing" }] : targets) {
|
|
8449
8449
|
const decision = authorize(entry.grants, actor, {
|
|
@@ -8467,12 +8467,20 @@ function createQuery(deps) {
|
|
|
8467
8467
|
}
|
|
8468
8468
|
if (targets.some((target) => target.kind === "missing")) throw new CommandError("not_found", "Check the target ID.");
|
|
8469
8469
|
if (targets.length === 0 && entry.grants !== "any" && entry.id !== "token.list") throw new CommandError("not_found", "Resolve an authorization target before reading.");
|
|
8470
|
+
if (prepare) return { status: "prepared" };
|
|
8470
8471
|
const value = await query.run(trx, parsedInput, actor);
|
|
8471
8472
|
return {
|
|
8472
8473
|
status: "done",
|
|
8473
8474
|
value: entry.output.parse(value)
|
|
8474
8475
|
};
|
|
8475
8476
|
});
|
|
8477
|
+
if (query.prepare !== void 0) {
|
|
8478
|
+
const preflight = await read(true);
|
|
8479
|
+
if (preflight.status === "denied") throw new CommandError("forbidden", preflight.hint);
|
|
8480
|
+
await query.prepare(store.db, parsedInput, actor);
|
|
8481
|
+
}
|
|
8482
|
+
const result = await read(false);
|
|
8483
|
+
if (result.status === "prepared") throw new Error("Query result was not read");
|
|
8476
8484
|
if (result.status === "denied") throw new CommandError("forbidden", result.hint);
|
|
8477
8485
|
return result.value;
|
|
8478
8486
|
};
|
|
@@ -12106,6 +12114,112 @@ function createBlockMutations(config) {
|
|
|
12106
12114
|
};
|
|
12107
12115
|
}
|
|
12108
12116
|
//#endregion
|
|
12117
|
+
//#region ../core/src/app/pr-associations.ts
|
|
12118
|
+
const prPollingSchema = z.strictObject({
|
|
12119
|
+
state: z.enum(["merged", "closed"]),
|
|
12120
|
+
headSha: prFactsSchema.shape.headSha,
|
|
12121
|
+
recheckAt: z.iso.datetime().nullable(),
|
|
12122
|
+
ticketKeys: prFactsSchema.shape.ticketKeys.optional()
|
|
12123
|
+
});
|
|
12124
|
+
const prPollingKey = (source, ref) => `pr-poll:${source}:pr:${ref.repo.toLowerCase()}#${String(ref.number)}`;
|
|
12125
|
+
function readPrPolling(value) {
|
|
12126
|
+
if (value === void 0) return;
|
|
12127
|
+
try {
|
|
12128
|
+
const parsed = prPollingSchema.safeParse(JSON.parse(value));
|
|
12129
|
+
return parsed.success ? parsed.data : void 0;
|
|
12130
|
+
} catch {
|
|
12131
|
+
return;
|
|
12132
|
+
}
|
|
12133
|
+
}
|
|
12134
|
+
async function savePrPolling(trx, source, fact, recheckAt, preserve = false) {
|
|
12135
|
+
const key = prPollingKey(source, {
|
|
12136
|
+
kind: "pr",
|
|
12137
|
+
repo: fact.repo,
|
|
12138
|
+
number: fact.number
|
|
12139
|
+
});
|
|
12140
|
+
if (fact.state !== "merged" && fact.state !== "closed") {
|
|
12141
|
+
await trx.deleteFrom("meta").where("key", "=", key).execute();
|
|
12142
|
+
return;
|
|
12143
|
+
}
|
|
12144
|
+
if (preserve) {
|
|
12145
|
+
const previous = readPrPolling((await trx.selectFrom("meta").select("value").where("key", "=", key).executeTakeFirst())?.value);
|
|
12146
|
+
if (previous !== void 0) {
|
|
12147
|
+
if (previous.ticketKeys === void 0 && previous.state === fact.state && previous.headSha === fact.headSha && fact.ticketKeys !== void 0) await trx.updateTable("meta").set({ value: toJson(prPollingSchema, {
|
|
12148
|
+
...previous,
|
|
12149
|
+
ticketKeys: fact.ticketKeys
|
|
12150
|
+
}) }).where("key", "=", key).execute();
|
|
12151
|
+
return;
|
|
12152
|
+
}
|
|
12153
|
+
}
|
|
12154
|
+
const value = toJson(prPollingSchema, {
|
|
12155
|
+
state: fact.state,
|
|
12156
|
+
headSha: fact.headSha,
|
|
12157
|
+
recheckAt,
|
|
12158
|
+
ticketKeys: fact.ticketKeys
|
|
12159
|
+
});
|
|
12160
|
+
await trx.insertInto("meta").values({
|
|
12161
|
+
key,
|
|
12162
|
+
value
|
|
12163
|
+
}).onConflict((oc) => preserve ? oc.column("key").doNothing() : oc.column("key").doUpdateSet({ value })).execute();
|
|
12164
|
+
}
|
|
12165
|
+
/** The PR was merged before the reopen; a tie counts the merge. */
|
|
12166
|
+
function mergedBefore(fact, reopenedAt) {
|
|
12167
|
+
return fact.state === "merged" && reopenedAt !== null && Date.parse(fact.mergedAt ?? fact.updatedAt) < Date.parse(reopenedAt);
|
|
12168
|
+
}
|
|
12169
|
+
async function linkPrToTask(trx, task, fact, at) {
|
|
12170
|
+
if (await trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("entity", "=", "pr").where(sql`lower(repo) = ${fact.repo.toLowerCase()}`).where("number", "=", fact.number).executeTakeFirst() === void 0) {
|
|
12171
|
+
const active = await trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("entity", "=", "pr").where("pr_state", "=", "active").where("banned", "=", 0).where("pr_open", "=", 1).executeTakeFirst();
|
|
12172
|
+
const state = fact.state !== "open" || active === void 0 ? "active" : "conflict";
|
|
12173
|
+
await trx.insertInto("link").values({
|
|
12174
|
+
task_id: task.id,
|
|
12175
|
+
entity: "pr",
|
|
12176
|
+
repo: fact.repo,
|
|
12177
|
+
number: fact.number,
|
|
12178
|
+
pr_state: state,
|
|
12179
|
+
session_id: null,
|
|
12180
|
+
role: null,
|
|
12181
|
+
source: "branch",
|
|
12182
|
+
banned: 0,
|
|
12183
|
+
created_at: at,
|
|
12184
|
+
ticket_key: null,
|
|
12185
|
+
pr_open: fact.state === "open" ? 1 : 0,
|
|
12186
|
+
reopen_hidden_at: mergedBefore(fact, task.reopened_at) ? at : null
|
|
12187
|
+
}).execute();
|
|
12188
|
+
await emit(trx, "link_added", task.project, task.id, at, {
|
|
12189
|
+
entity: "pr",
|
|
12190
|
+
repo: fact.repo,
|
|
12191
|
+
pr: fact.number,
|
|
12192
|
+
state,
|
|
12193
|
+
source: "branch",
|
|
12194
|
+
facts: fact
|
|
12195
|
+
});
|
|
12196
|
+
}
|
|
12197
|
+
}
|
|
12198
|
+
/** Reuse locally observed source associations when a task arrives after its PR. */
|
|
12199
|
+
async function reconcileTaskPrs(trx, config, taskId, at) {
|
|
12200
|
+
const task = await trx.selectFrom("task").selectAll().where("id", "=", taskId).executeTakeFirstOrThrow();
|
|
12201
|
+
if (task.membership === "archived" || task.manual_exclude === 1) return;
|
|
12202
|
+
const project = config.projects.find((entry) => entry.id === task.project);
|
|
12203
|
+
if (project === void 0) return;
|
|
12204
|
+
const snapshots = await trx.selectFrom("pr_snapshot").selectAll().execute();
|
|
12205
|
+
for (const row of snapshots) {
|
|
12206
|
+
const repo = project.repos.find((repo) => repo.toLowerCase() === row.repo.toLowerCase());
|
|
12207
|
+
if (repo === void 0) continue;
|
|
12208
|
+
const fact = parseJson(prFactsSchema, row.detail);
|
|
12209
|
+
const source = prSourceId(project.id, repo);
|
|
12210
|
+
const processed = readPrPolling((await trx.selectFrom("meta").select("value").where("key", "=", prPollingKey(source, {
|
|
12211
|
+
kind: "pr",
|
|
12212
|
+
repo: row.repo,
|
|
12213
|
+
number: row.number
|
|
12214
|
+
})).executeTakeFirst())?.value);
|
|
12215
|
+
const keys = row.source === source ? fact.ticketKeys : processed?.state === fact.state && processed.headSha === fact.headSha ? processed.ticketKeys : void 0;
|
|
12216
|
+
if (keys?.includes(task.key)) await linkPrToTask(trx, task, {
|
|
12217
|
+
...fact,
|
|
12218
|
+
ticketKeys: keys
|
|
12219
|
+
}, at);
|
|
12220
|
+
}
|
|
12221
|
+
}
|
|
12222
|
+
//#endregion
|
|
12109
12223
|
//#region ../core/src/app/archive.ts
|
|
12110
12224
|
/**
|
|
12111
12225
|
* Takes a task off the board in the caller's transaction: closes its open blocks with outcome
|
|
@@ -12211,6 +12325,7 @@ function createMembershipMutations(config) {
|
|
|
12211
12325
|
if (task.membership === "archived") await emit(trx, "task_added", project.id, task.id, ctx.at, { column: task.column }, "operator");
|
|
12212
12326
|
task = await trx.selectFrom("task").selectAll().where("id", "=", task.id).executeTakeFirstOrThrow();
|
|
12213
12327
|
}
|
|
12328
|
+
await reconcileTaskPrs(trx, config, task.id, ctx.at);
|
|
12214
12329
|
return { task: taskView(task) };
|
|
12215
12330
|
}
|
|
12216
12331
|
},
|
|
@@ -13094,6 +13209,37 @@ function createItemMutations(deps) {
|
|
|
13094
13209
|
};
|
|
13095
13210
|
}
|
|
13096
13211
|
//#endregion
|
|
13212
|
+
//#region ../core/src/app/pr-refresh.ts
|
|
13213
|
+
/** Shared by explicit task reads and manual PR links; one deadline covers every distinct PR. */
|
|
13214
|
+
async function refreshPrs(config, projectId, refs, poll) {
|
|
13215
|
+
if (refs.length === 0) return;
|
|
13216
|
+
if (poll === void 0) throw new CommandError("github_unavailable", "Wait until the GitHub source is running, then retry.");
|
|
13217
|
+
const project = config.projects.find((entry) => entry.id === projectId);
|
|
13218
|
+
const unique = new Map(refs.map((ref) => [`${ref.repo.toLowerCase()}#${String(ref.number)}`, ref]));
|
|
13219
|
+
const deadline = Date.now() + 1e4;
|
|
13220
|
+
for (const ref of unique.values()) {
|
|
13221
|
+
if (!project?.repos.some((repo) => repo.toLowerCase() === ref.repo.toLowerCase())) throw new CommandError("github_unavailable", "Configure a GitHub source for the repository, then retry.");
|
|
13222
|
+
const timeoutMs = deadline - Date.now();
|
|
13223
|
+
if (timeoutMs <= 0) throw new CommandError("github_unavailable", "GitHub refresh timed out; retry the operation.");
|
|
13224
|
+
let timer;
|
|
13225
|
+
try {
|
|
13226
|
+
const result = await Promise.race([poll(prSourceId(projectId, ref.repo), ref, { timeoutMs }), new Promise((_resolve, reject) => {
|
|
13227
|
+
timer = setTimeout(() => {
|
|
13228
|
+
reject(new CommandError("github_unavailable", "GitHub refresh timed out; retry the operation."));
|
|
13229
|
+
}, timeoutMs);
|
|
13230
|
+
})]);
|
|
13231
|
+
if (!result.ok || result.value.status !== "ok") throw new CommandError("github_unavailable", "GitHub did not return current pull request facts; retry the operation.");
|
|
13232
|
+
} catch (error) {
|
|
13233
|
+
if (error instanceof CommandError) throw error;
|
|
13234
|
+
const failure = new CommandError("github_unavailable", "GitHub refresh failed; retry the operation.");
|
|
13235
|
+
failure.cause = error;
|
|
13236
|
+
throw failure;
|
|
13237
|
+
} finally {
|
|
13238
|
+
clearTimeout(timer);
|
|
13239
|
+
}
|
|
13240
|
+
}
|
|
13241
|
+
}
|
|
13242
|
+
//#endregion
|
|
13097
13243
|
//#region ../core/src/app/links.ts
|
|
13098
13244
|
function prIdentity(url) {
|
|
13099
13245
|
const parsed = new URL(url);
|
|
@@ -13287,12 +13433,24 @@ async function run(trx, input, ctx, config, remove) {
|
|
|
13287
13433
|
target
|
|
13288
13434
|
};
|
|
13289
13435
|
}
|
|
13290
|
-
function createLinkMutations(config) {
|
|
13436
|
+
function createLinkMutations(config, deps = {}) {
|
|
13291
13437
|
const resolveTargets = (trx, input) => taskTarget(trx, canonicalKey(config, input.task).key);
|
|
13292
13438
|
return {
|
|
13293
13439
|
add: {
|
|
13294
13440
|
id: "link.add",
|
|
13295
13441
|
resolveTargets,
|
|
13442
|
+
async prepare(db, input) {
|
|
13443
|
+
if (input.mode !== "pr") return;
|
|
13444
|
+
const key = canonicalKey(config, input.task).key;
|
|
13445
|
+
const task = await db.selectFrom("task").selectAll().where("key", "=", key).executeTakeFirst();
|
|
13446
|
+
if (task === void 0) throw new CommandError("not_found", "Check the task key.");
|
|
13447
|
+
if (task.membership === "archived") throw new CommandError("task_archived", "Task is archived.");
|
|
13448
|
+
const pr = prIdentity(input.pr);
|
|
13449
|
+
await refreshPrs(config, task.project, [{
|
|
13450
|
+
kind: "pr",
|
|
13451
|
+
...pr
|
|
13452
|
+
}], deps.prPoller?.());
|
|
13453
|
+
},
|
|
13296
13454
|
run: (trx, input, ctx) => run(trx, input, ctx, config, false)
|
|
13297
13455
|
},
|
|
13298
13456
|
remove: {
|
|
@@ -13492,6 +13650,9 @@ async function getStatus(deps, options = {}) {
|
|
|
13492
13650
|
});
|
|
13493
13651
|
const sourceRows = await store.db.selectFrom("source_state").selectAll().execute();
|
|
13494
13652
|
const required = /* @__PURE__ */ new Set(["spur", ...projects.flatMap((project) => [trackerSourceId(project), ...project.repos.map((repo) => prSourceId(project.id, repo))])]);
|
|
13653
|
+
const costs = await store.db.selectFrom("source_cost").select(["source", "points"]).where("at", ">", (/* @__PURE__ */ new Date(clock.now() - 36e5)).toISOString()).where("at", "<=", new Date(clock.now()).toISOString()).execute();
|
|
13654
|
+
const points = /* @__PURE__ */ new Map();
|
|
13655
|
+
for (const cost of costs) points.set(cost.source, (points.get(cost.source) ?? 0) + cost.points);
|
|
13495
13656
|
const sourceById = new Map(sourceRows.map((row) => [row.source, row]));
|
|
13496
13657
|
const sources = [...required].map((source) => {
|
|
13497
13658
|
const row = sourceById.get(source);
|
|
@@ -13499,6 +13660,7 @@ async function getStatus(deps, options = {}) {
|
|
|
13499
13660
|
const blindReason = row?.blind_reason === "auth" || row?.blind_reason === "config" || row?.blind_reason === "stale" ? row.blind_reason : null;
|
|
13500
13661
|
return {
|
|
13501
13662
|
source,
|
|
13663
|
+
...source.startsWith("github:") ? { pointsLastHour: points.get(source) ?? 0 } : {},
|
|
13502
13664
|
observedAt: row?.observed_at ?? null,
|
|
13503
13665
|
lastCompleteAt: last,
|
|
13504
13666
|
blindReason,
|
|
@@ -15410,6 +15572,16 @@ function createTaskQueries(deps) {
|
|
|
15410
15572
|
const get = {
|
|
15411
15573
|
id: "task.get",
|
|
15412
15574
|
resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
|
|
15575
|
+
async prepare(db, input) {
|
|
15576
|
+
if (input.refresh !== true) return;
|
|
15577
|
+
const task = await taskByKey(db, taskKey(input.task));
|
|
15578
|
+
const links = await db.selectFrom("link").select(["repo", "number"]).where("task_id", "=", task.id).where("entity", "=", "pr").where("banned", "=", 0).execute();
|
|
15579
|
+
await refreshPrs(config, task.project, links.flatMap((link) => link.repo === null || link.number === null ? [] : [{
|
|
15580
|
+
kind: "pr",
|
|
15581
|
+
repo: link.repo,
|
|
15582
|
+
number: link.number
|
|
15583
|
+
}]), deps.prPoller?.());
|
|
15584
|
+
},
|
|
15413
15585
|
async run(trx, input) {
|
|
15414
15586
|
const task = await taskByKey(trx, taskKey(input.task));
|
|
15415
15587
|
const [blocks, comments, links] = await Promise.all([
|
|
@@ -15874,11 +16046,12 @@ function createOperationRegistry(deps) {
|
|
|
15874
16046
|
const { config, clock, completeSince, gateways } = deps;
|
|
15875
16047
|
const items = createItemMutations(deps);
|
|
15876
16048
|
const membership = createMembershipMutations(config);
|
|
15877
|
-
const links = createLinkMutations(config);
|
|
16049
|
+
const links = createLinkMutations(config, { prPoller: deps.prPoller });
|
|
15878
16050
|
const blocks = createBlockMutations(config);
|
|
15879
16051
|
const taskQueries = createTaskQueries({
|
|
15880
16052
|
config,
|
|
15881
|
-
completeSince
|
|
16053
|
+
completeSince,
|
|
16054
|
+
prPoller: deps.prPoller
|
|
15882
16055
|
});
|
|
15883
16056
|
const turns = createTurnMutations({
|
|
15884
16057
|
config,
|
|
@@ -16168,10 +16341,6 @@ async function setReopenFloor(trx, taskId, at) {
|
|
|
16168
16341
|
* `updatedAt`, never earlier than the merge, so a later edit makes the merge count. Then the reopen hides this link only: another link
|
|
16169
16342
|
* of the task that already counts, such as a follow-up merged after the reopen, keeps counting.
|
|
16170
16343
|
*/
|
|
16171
|
-
/** The PR was merged before `reopenedAt`; a tie counts the merge. */
|
|
16172
|
-
function mergedBefore(fact, reopenedAt) {
|
|
16173
|
-
return fact.state === "merged" && reopenedAt !== null && Date.parse(fact.mergedAt ?? fact.updatedAt) < Date.parse(reopenedAt);
|
|
16174
|
-
}
|
|
16175
16344
|
async function applyPendingReopen(trx, fact, at) {
|
|
16176
16345
|
if (fact.state === "open") return;
|
|
16177
16346
|
const pending = await trx.selectFrom("link").select(["id", "reopen_pending_at"]).where("entity", "=", "pr").where(sql`lower(repo) = ${fact.repo.toLowerCase()}`).where("number", "=", fact.number).where("reopen_pending_at", "is not", null).execute();
|
|
@@ -16206,6 +16375,8 @@ async function ticket(trx, config, fact, at, source) {
|
|
|
16206
16375
|
if (project === void 0) throw new Error("Ticket from an unconfigured tracker");
|
|
16207
16376
|
let task = await trx.selectFrom("task").selectAll().where("project", "=", project.id).where("tracker_kind", "=", project.tracker.type).where("tracker_id", "=", fact.id).executeTakeFirst();
|
|
16208
16377
|
const pending = await trx.selectFrom("task").selectAll().where("project", "=", project.id).where("key", "=", fact.key).executeTakeFirst();
|
|
16378
|
+
const previousKey = task?.key ?? pending?.key;
|
|
16379
|
+
const previousMembership = task?.membership ?? pending?.membership;
|
|
16209
16380
|
if (task !== void 0 && pending !== void 0 && pending.id !== task.id) {
|
|
16210
16381
|
const oldKey = task.key;
|
|
16211
16382
|
await trx.updateTable("task").set({ key: `__transfer__${String(task.id)}` }).where("id", "=", task.id).execute();
|
|
@@ -16293,10 +16464,19 @@ async function ticket(trx, config, fact, at, source) {
|
|
|
16293
16464
|
if (task.membership === "out_of_filter") await emit(trx, "flag_cleared", project.id, task.id, at, { flag: "out_of_filter" });
|
|
16294
16465
|
else await emit(trx, "task_added", project.id, task.id, at, { column: task.column });
|
|
16295
16466
|
}
|
|
16467
|
+
if (previousKey !== fact.key || previousMembership === "archived") await reconcileTaskPrs(trx, config, task.id, at);
|
|
16296
16468
|
}
|
|
16297
16469
|
async function pr(trx, config, fact, at, source) {
|
|
16470
|
+
await trx.deleteFrom("source_miss").where("source", "=", source).where("ref_key", "=", refKey({
|
|
16471
|
+
kind: "pr",
|
|
16472
|
+
repo: fact.repo,
|
|
16473
|
+
number: fact.number
|
|
16474
|
+
})).execute();
|
|
16298
16475
|
const old = await trx.selectFrom("pr_snapshot").selectAll().where(sql`lower(repo) = ${fact.repo.toLowerCase()}`).where("number", "=", fact.number).executeTakeFirst();
|
|
16299
16476
|
const previous = old === void 0 ? null : parseJson(prFactsSchema, old.detail);
|
|
16477
|
+
const recheckAt = fact.state === "closed" ? new Date(Date.parse(at) + 360 * 6e4).toISOString() : null;
|
|
16478
|
+
if (old !== void 0 && previous !== null && old.source !== source) await savePrPolling(trx, old.source, previous, old.closed_recheck_at, true);
|
|
16479
|
+
await savePrPolling(trx, source, fact, recheckAt);
|
|
16300
16480
|
const changed = previous === null || JSON.stringify(previous) !== JSON.stringify(fact);
|
|
16301
16481
|
await trx.insertInto("pr_snapshot").values({
|
|
16302
16482
|
repo: old?.repo ?? fact.repo,
|
|
@@ -16309,8 +16489,10 @@ async function pr(trx, config, fact, at, source) {
|
|
|
16309
16489
|
merge_state: fact.mergeState,
|
|
16310
16490
|
detail: toJson(prFactsSchema, fact),
|
|
16311
16491
|
source,
|
|
16312
|
-
observed_at: at
|
|
16492
|
+
observed_at: at,
|
|
16493
|
+
closed_recheck_at: recheckAt
|
|
16313
16494
|
}).onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet({
|
|
16495
|
+
closed_recheck_at: recheckAt,
|
|
16314
16496
|
head_sha: fact.headSha,
|
|
16315
16497
|
head_branch: fact.headBranch,
|
|
16316
16498
|
state: fact.state,
|
|
@@ -16332,33 +16514,7 @@ async function pr(trx, config, fact, at, source) {
|
|
|
16332
16514
|
for (const key of fact.ticketKeys) {
|
|
16333
16515
|
const task = await trx.selectFrom("task").selectAll().where("project", "=", project.id).where("key", "=", key).executeTakeFirst();
|
|
16334
16516
|
if (task === void 0 || task.membership === "archived") continue;
|
|
16335
|
-
|
|
16336
|
-
const active = await trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("entity", "=", "pr").where("pr_state", "=", "active").where("banned", "=", 0).where("pr_open", "=", 1).executeTakeFirst();
|
|
16337
|
-
const state = fact.state !== "open" || active === void 0 ? "active" : "conflict";
|
|
16338
|
-
await trx.insertInto("link").values({
|
|
16339
|
-
task_id: task.id,
|
|
16340
|
-
entity: "pr",
|
|
16341
|
-
repo: fact.repo,
|
|
16342
|
-
number: fact.number,
|
|
16343
|
-
pr_state: state,
|
|
16344
|
-
session_id: null,
|
|
16345
|
-
role: null,
|
|
16346
|
-
source: "branch",
|
|
16347
|
-
banned: 0,
|
|
16348
|
-
created_at: at,
|
|
16349
|
-
ticket_key: null,
|
|
16350
|
-
pr_open: fact.state === "open" ? 1 : 0,
|
|
16351
|
-
reopen_hidden_at: mergedBefore(fact, task.reopened_at) ? at : null
|
|
16352
|
-
}).execute();
|
|
16353
|
-
await emit(trx, "link_added", task.project, task.id, at, {
|
|
16354
|
-
entity: "pr",
|
|
16355
|
-
repo: fact.repo,
|
|
16356
|
-
pr: fact.number,
|
|
16357
|
-
state,
|
|
16358
|
-
source: "branch",
|
|
16359
|
-
facts: fact
|
|
16360
|
-
});
|
|
16361
|
-
}
|
|
16517
|
+
await linkPrToTask(trx, task, fact, at);
|
|
16362
16518
|
}
|
|
16363
16519
|
const linkedPrs = await trx.selectFrom("link").select([
|
|
16364
16520
|
"id",
|
|
@@ -16629,6 +16785,16 @@ async function holdContinuation(trx, source, item) {
|
|
|
16629
16785
|
...held
|
|
16630
16786
|
}).onConflict((oc) => oc.columns(["source", "ref_key"]).doUpdateSet(held)).execute();
|
|
16631
16787
|
}
|
|
16788
|
+
/** Reported cost only; shared remaining-budget changes do not measure consumption. */
|
|
16789
|
+
async function recordUsage(trx, source, usage, now) {
|
|
16790
|
+
if (usage === void 0) return;
|
|
16791
|
+
await trx.deleteFrom("source_cost").where("at", "<=", (/* @__PURE__ */ new Date(now - 36e5)).toISOString()).execute();
|
|
16792
|
+
await trx.insertInto("source_cost").values({
|
|
16793
|
+
source,
|
|
16794
|
+
at: new Date(now).toISOString(),
|
|
16795
|
+
points: usage.points
|
|
16796
|
+
}).execute();
|
|
16797
|
+
}
|
|
16632
16798
|
/** Core's adapter-facing port. Every accepted batch and its source state share one transaction. */
|
|
16633
16799
|
function createObservationCore(deps) {
|
|
16634
16800
|
const { store, config, clock } = deps;
|
|
@@ -16656,7 +16822,41 @@ function createObservationCore(deps) {
|
|
|
16656
16822
|
key: task.key
|
|
16657
16823
|
}] : [];
|
|
16658
16824
|
}) : [];
|
|
16659
|
-
const
|
|
16825
|
+
const linked = await linkedPrs(store.db, source);
|
|
16826
|
+
const snapshots = source.startsWith("github:") ? await store.db.selectFrom("pr_snapshot").selectAll().where(sql`lower(repo) = ${source.slice(source.lastIndexOf(":") + 1).toLowerCase()}`).execute() : [];
|
|
16827
|
+
const pollingRows = source.startsWith("github:") ? await store.db.selectFrom("meta").select(["key", "value"]).where("key", "like", `pr-poll:${source}:%`).execute() : [];
|
|
16828
|
+
const polling = new Map(pollingRows.map((row) => [row.key, row.value]));
|
|
16829
|
+
const linkedKeys = new Set(linked.map(refKey));
|
|
16830
|
+
const terminalPrs = [];
|
|
16831
|
+
const prRechecks = [];
|
|
16832
|
+
for (const row of snapshots) {
|
|
16833
|
+
let value;
|
|
16834
|
+
try {
|
|
16835
|
+
value = JSON.parse(row.detail);
|
|
16836
|
+
} catch {
|
|
16837
|
+
continue;
|
|
16838
|
+
}
|
|
16839
|
+
const parsed = prFactsSchema.safeParse(value);
|
|
16840
|
+
if (!parsed.success || parsed.data.state !== "merged" && parsed.data.state !== "closed") continue;
|
|
16841
|
+
const ref = {
|
|
16842
|
+
kind: "pr",
|
|
16843
|
+
repo: row.repo,
|
|
16844
|
+
number: row.number
|
|
16845
|
+
};
|
|
16846
|
+
const processed = row.source === source ? {
|
|
16847
|
+
state: parsed.data.state,
|
|
16848
|
+
headSha: parsed.data.headSha,
|
|
16849
|
+
recheckAt: row.closed_recheck_at
|
|
16850
|
+
} : readPrPolling(polling.get(prPollingKey(source, ref)));
|
|
16851
|
+
if (processed === void 0 || processed.state !== parsed.data.state || processed.headSha.toLowerCase() !== parsed.data.headSha.toLowerCase()) continue;
|
|
16852
|
+
terminalPrs.push({
|
|
16853
|
+
ref,
|
|
16854
|
+
state: parsed.data.state === "merged" ? "merged" : "closed"
|
|
16855
|
+
});
|
|
16856
|
+
if (parsed.data.state === "closed" && linkedKeys.has(refKey(ref)) && (processed.recheckAt === null || Date.parse(processed.recheckAt) <= clock.now())) prRechecks.push(ref);
|
|
16857
|
+
}
|
|
16858
|
+
const terminal = new Set(terminalPrs.map(({ ref }) => refKey(ref)));
|
|
16859
|
+
const requested = linked.filter((ref) => !terminal.has(refKey(ref)));
|
|
16660
16860
|
const sessions = source === "spur" ? (await store.db.selectFrom("link").innerJoin("session_snapshot", "session_snapshot.id", "link.session_id").select("link.session_id").where("link.entity", "=", "session").where("session_snapshot.ended_at", "is", null).execute()).flatMap((link) => link.session_id === null ? [] : [{
|
|
16661
16861
|
kind: "session",
|
|
16662
16862
|
id: link.session_id
|
|
@@ -16670,9 +16870,11 @@ function createObservationCore(deps) {
|
|
|
16670
16870
|
})));
|
|
16671
16871
|
}
|
|
16672
16872
|
const misses = await store.db.selectFrom("source_miss").selectAll().where("source", "=", source).execute();
|
|
16673
|
-
const feedbackCursors = await pollFeedbackCursors(store.db, config,
|
|
16674
|
-
const continuations = await heldContinuations(store.db, source,
|
|
16873
|
+
const feedbackCursors = await pollFeedbackCursors(store.db, config, linked);
|
|
16874
|
+
const continuations = await heldContinuations(store.db, source, linked);
|
|
16675
16875
|
return {
|
|
16876
|
+
terminalPrs,
|
|
16877
|
+
prRechecks,
|
|
16676
16878
|
observe: {
|
|
16677
16879
|
prs: requested,
|
|
16678
16880
|
tickets,
|
|
@@ -16696,6 +16898,26 @@ function createObservationCore(deps) {
|
|
|
16696
16898
|
await scanTransaction(store, config, async (trx) => {
|
|
16697
16899
|
const wasBlind = await blindReason(trx, source);
|
|
16698
16900
|
await sourceState(trx, source, observation.state, batch.observedAt, batch.cursor);
|
|
16901
|
+
await recordUsage(trx, source, batch.usage, now);
|
|
16902
|
+
for (const probe of batch.prProbes ?? []) {
|
|
16903
|
+
if (probe.status !== "closed") continue;
|
|
16904
|
+
const recheckAt = new Date(Date.parse(batch.observedAt) + 360 * 6e4).toISOString();
|
|
16905
|
+
const row = await trx.selectFrom("pr_snapshot").selectAll().where(sql`lower(repo) = ${probe.ref.repo.toLowerCase()}`).where("number", "=", probe.ref.number).where("state", "=", "closed").executeTakeFirst();
|
|
16906
|
+
if (row === void 0) continue;
|
|
16907
|
+
const saved = await trx.selectFrom("meta").select("value").where("key", "=", prPollingKey(source, probe.ref)).executeTakeFirst();
|
|
16908
|
+
const processed = row.source === source ? {
|
|
16909
|
+
...parseJson(prFactsSchema, row.detail),
|
|
16910
|
+
state: "closed"
|
|
16911
|
+
} : readPrPolling(saved?.value);
|
|
16912
|
+
if (processed !== void 0) await savePrPolling(trx, source, {
|
|
16913
|
+
repo: probe.ref.repo,
|
|
16914
|
+
number: probe.ref.number,
|
|
16915
|
+
state: processed.state,
|
|
16916
|
+
headSha: processed.headSha,
|
|
16917
|
+
...processed.ticketKeys === void 0 ? {} : { ticketKeys: processed.ticketKeys }
|
|
16918
|
+
}, recheckAt);
|
|
16919
|
+
await trx.updateTable("pr_snapshot").set({ closed_recheck_at: recheckAt }).where("source", "=", source).where(sql`lower(repo) = ${probe.ref.repo.toLowerCase()}`).where("number", "=", probe.ref.number).where("state", "=", "closed").execute();
|
|
16920
|
+
}
|
|
16699
16921
|
for (const outcome of observation.outcomes) {
|
|
16700
16922
|
const answer = batch.entities.find((entity) => refKey(entity.ref) === refKey(outcome.ref));
|
|
16701
16923
|
await trx.insertInto("source_miss").values({
|
|
@@ -16811,11 +17033,12 @@ function createObservationCore(deps) {
|
|
|
16811
17033
|
});
|
|
16812
17034
|
if (observation.effectiveComplete) completeSince.set(source, batch.observedAt);
|
|
16813
17035
|
},
|
|
16814
|
-
reportSourceState(source, state) {
|
|
17036
|
+
reportSourceState(source, state, usage) {
|
|
16815
17037
|
const now = clock.now();
|
|
16816
17038
|
return scanTransaction(store, config, async (trx) => {
|
|
16817
17039
|
const wasBlind = await blindReason(trx, source);
|
|
16818
17040
|
await sourceState(trx, source, state);
|
|
17041
|
+
await recordUsage(trx, source, usage, now);
|
|
16819
17042
|
if (wasBlind !== null && state.blind === void 0) await dispatchSource(trx, source, {
|
|
16820
17043
|
config,
|
|
16821
17044
|
at: new Date(now),
|
|
@@ -18302,18 +18525,21 @@ function aliases(numbers, fields) {
|
|
|
18302
18525
|
}
|
|
18303
18526
|
const discoveryStates = (bootstrap) => bootstrap ? "OPEN" : "OPEN, MERGED, CLOSED";
|
|
18304
18527
|
function discoveryQuery(bootstrap = false) {
|
|
18305
|
-
return `query PrBatch($owner: String!, $repo: String!) { rateLimit { remaining resetAt } repository(owner: $owner, name: $repo) { pullRequests(first: 100, states: [${discoveryStates(bootstrap)}], orderBy: {field: UPDATED_AT, direction: DESC}) { ${DISCOVERY_FIELDS} }${bootstrap ? " mergedBaseline: pullRequests(first: 1, states: [MERGED, CLOSED], orderBy: {field: UPDATED_AT, direction: DESC}) { nodes { updatedAt } }" : ""} } }`;
|
|
18528
|
+
return `query PrBatch($owner: String!, $repo: String!) { rateLimit { cost remaining resetAt } repository(owner: $owner, name: $repo) { pullRequests(first: 100, states: [${discoveryStates(bootstrap)}], orderBy: {field: UPDATED_AT, direction: DESC}) { ${DISCOVERY_FIELDS} }${bootstrap ? " mergedBaseline: pullRequests(first: 1, states: [MERGED, CLOSED], orderBy: {field: UPDATED_AT, direction: DESC}) { nodes { updatedAt } }" : ""} } }`;
|
|
18529
|
+
}
|
|
18530
|
+
function stateQuery(numbers) {
|
|
18531
|
+
return `query PrStates($owner: String!, $repo: String!) { rateLimit { cost remaining resetAt } ${aliases(numbers, () => "number state")} }`;
|
|
18306
18532
|
}
|
|
18307
18533
|
function indexQuery(numbers) {
|
|
18308
|
-
return `query PrIndex($owner: String!, $repo: String!) { rateLimit { remaining resetAt } ${aliases(numbers, () => INDEX_FIELDS)} }`;
|
|
18534
|
+
return `query PrIndex($owner: String!, $repo: String!) { rateLimit { cost remaining resetAt } ${aliases(numbers, () => INDEX_FIELDS)} }`;
|
|
18309
18535
|
}
|
|
18310
18536
|
function detailQuery(numbers, closing = false) {
|
|
18311
|
-
return `query PrDetails($owner: String!, $repo: String!) { rateLimit { remaining resetAt } ${aliases(numbers, (number) => prFields(number, closing))} }`;
|
|
18537
|
+
return `query PrDetails($owner: String!, $repo: String!) { rateLimit { cost remaining resetAt } ${aliases(numbers, (number) => prFields(number, closing))} }`;
|
|
18312
18538
|
}
|
|
18313
18539
|
function pageQuery(connection, bootstrap = false) {
|
|
18314
|
-
if (connection === "comments") return `query PrPage($owner: String!, $repo: String!, $number: Int!, $before: String!) { rateLimit { remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { comments(last: 100, before: $before) { ${COMMENT_FIELDS} } } } }`;
|
|
18315
|
-
if (connection === "pullRequests") return `query DiscoveryPage($owner: String!, $repo: String!, $after: String!) { rateLimit { remaining resetAt } repository(owner: $owner, name: $repo) { pullRequests(first: 100, after: $after, states: [${discoveryStates(bootstrap)}], orderBy: {field: UPDATED_AT, direction: DESC}) { ${DISCOVERY_FIELDS} } } }`;
|
|
18316
|
-
return `query PrPage($owner: String!, $repo: String!, $number: Int!, $after: String!) { rateLimit { remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { ${connection === "closingIssuesReferences" ? `closingIssuesReferences(first: 100, after: $after) { ${CLOSING_FIELDS} }` : connection === "contexts" ? `statusCheckRollup { contexts(first: 100, after: $after) { nodes { ... on CheckRun { __typename name status conclusion startedAt completedAt checkSuite { createdAt } isRequired(pullRequestNumber: $number) } ... on StatusContext { __typename context state createdAt isRequired(pullRequestNumber: $number) } } pageInfo { hasNextPage endCursor } } }` : `${connection}(first: 100, after: $after) { nodes { ${connection === "reviews" ? REVIEW_FIELDS : connection === "reviewThreads" ? "isResolved" : REVIEWER_FIELDS} } pageInfo { hasNextPage endCursor } }`} } } }`;
|
|
18540
|
+
if (connection === "comments") return `query PrPage($owner: String!, $repo: String!, $number: Int!, $before: String!) { rateLimit { cost remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { comments(last: 100, before: $before) { ${COMMENT_FIELDS} } } } }`;
|
|
18541
|
+
if (connection === "pullRequests") return `query DiscoveryPage($owner: String!, $repo: String!, $after: String!) { rateLimit { cost remaining resetAt } repository(owner: $owner, name: $repo) { pullRequests(first: 100, after: $after, states: [${discoveryStates(bootstrap)}], orderBy: {field: UPDATED_AT, direction: DESC}) { ${DISCOVERY_FIELDS} } } }`;
|
|
18542
|
+
return `query PrPage($owner: String!, $repo: String!, $number: Int!, $after: String!) { rateLimit { cost remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { ${connection === "closingIssuesReferences" ? `closingIssuesReferences(first: 100, after: $after) { ${CLOSING_FIELDS} }` : connection === "contexts" ? `statusCheckRollup { contexts(first: 100, after: $after) { nodes { ... on CheckRun { __typename name status conclusion startedAt completedAt checkSuite { createdAt } isRequired(pullRequestNumber: $number) } ... on StatusContext { __typename context state createdAt isRequired(pullRequestNumber: $number) } } pageInfo { hasNextPage endCursor } } }` : `${connection}(first: 100, after: $after) { nodes { ${connection === "reviews" ? REVIEW_FIELDS : connection === "reviewThreads" ? "isResolved" : REVIEWER_FIELDS} } pageInfo { hasNextPage endCursor } }`} } } }`;
|
|
18317
18543
|
}
|
|
18318
18544
|
/**
|
|
18319
18545
|
* The failure that GraphQL `errors` mean for the whole request, in rule order: a rate limit is
|
|
@@ -18333,6 +18559,12 @@ function checkAccessDenied(errors) {
|
|
|
18333
18559
|
return errors.some((error) => error.type === "FORBIDDEN" && error.path?.includes("statusCheckRollup") === true && error.path.includes("contexts"));
|
|
18334
18560
|
}
|
|
18335
18561
|
var GithubClient = class {
|
|
18562
|
+
points;
|
|
18563
|
+
takeUsage() {
|
|
18564
|
+
const points = this.points;
|
|
18565
|
+
this.points = void 0;
|
|
18566
|
+
return points === void 0 ? void 0 : { points };
|
|
18567
|
+
}
|
|
18336
18568
|
token;
|
|
18337
18569
|
now;
|
|
18338
18570
|
fetcher;
|
|
@@ -18378,6 +18610,8 @@ var GithubClient = class {
|
|
|
18378
18610
|
body
|
|
18379
18611
|
};
|
|
18380
18612
|
});
|
|
18613
|
+
const cost = z.object({ data: z.object({ rateLimit: z.object({ cost: z.int().nonnegative() }) }) }).safeParse(body);
|
|
18614
|
+
if (cost.success) this.points = (this.points ?? 0) + cost.data.data.rateLimit.cost;
|
|
18381
18615
|
const wire = parseWire(graphEnvelopeWire, body, MALFORMED$3);
|
|
18382
18616
|
const errors = wire.errors ?? [];
|
|
18383
18617
|
const failure = graphqlFailure(errors, query, response.headers, this.now());
|
|
@@ -18395,6 +18629,7 @@ var GithubClient = class {
|
|
|
18395
18629
|
const timestamp$1 = z.string().min(1).refine((value) => !Number.isNaN(Date.parse(value)));
|
|
18396
18630
|
const discoveryNodeWire = z.object({
|
|
18397
18631
|
number: z.int().positive(),
|
|
18632
|
+
state: z.string().optional(),
|
|
18398
18633
|
updatedAt: timestamp$1,
|
|
18399
18634
|
author: z.object({ login: z.string() }).nullable()
|
|
18400
18635
|
});
|
|
@@ -18411,16 +18646,19 @@ function latestUpdatedAt(nodes, previous) {
|
|
|
18411
18646
|
function discover(nodes, previous, login) {
|
|
18412
18647
|
let high = previous;
|
|
18413
18648
|
const numbers = /* @__PURE__ */ new Set();
|
|
18649
|
+
const states = /* @__PURE__ */ new Map();
|
|
18414
18650
|
for (const node of nodes) {
|
|
18415
18651
|
const updated = sourceCursorSchema.parse(node.updatedAt);
|
|
18416
18652
|
const updatedMs = Date.parse(updated);
|
|
18417
18653
|
if (high === void 0 || updatedMs > Date.parse(high)) high = updated;
|
|
18418
18654
|
if (previous !== void 0 && updatedMs < Date.parse(previous)) continue;
|
|
18655
|
+
states.set(node.number, node.state);
|
|
18419
18656
|
if (node.author?.login.toLowerCase() !== login.toLowerCase()) continue;
|
|
18420
18657
|
numbers.add(node.number);
|
|
18421
18658
|
}
|
|
18422
18659
|
return {
|
|
18423
18660
|
numbers: [...numbers],
|
|
18661
|
+
states,
|
|
18424
18662
|
...high === void 0 ? {} : { cursor: high }
|
|
18425
18663
|
};
|
|
18426
18664
|
}
|
|
@@ -18902,13 +19140,30 @@ function githubSources(config, options) {
|
|
|
18902
19140
|
const client = new GithubClient(options.token, options.now, options.fetch);
|
|
18903
19141
|
const keys = projectKeyRule(project.tracker, project.link, repo);
|
|
18904
19142
|
const cache = /* @__PURE__ */ new Map();
|
|
19143
|
+
async function withUsage(signal, read) {
|
|
19144
|
+
try {
|
|
19145
|
+
const batch = await read();
|
|
19146
|
+
const usage = client.takeUsage();
|
|
19147
|
+
return {
|
|
19148
|
+
...batch,
|
|
19149
|
+
...usage === void 0 ? {} : { usage }
|
|
19150
|
+
};
|
|
19151
|
+
} catch (cause) {
|
|
19152
|
+
const usage = client.takeUsage();
|
|
19153
|
+
if (signal.aborted || usage === void 0) throw cause;
|
|
19154
|
+
const error = cause instanceof AdapterError ? cause : new AdapterError("transient", "GitHub poll failed", { cause });
|
|
19155
|
+
error.usage = usage;
|
|
19156
|
+
throw error;
|
|
19157
|
+
}
|
|
19158
|
+
}
|
|
18905
19159
|
sources.push({
|
|
18906
19160
|
repo,
|
|
18907
19161
|
reserveRemaining: config.github.reserveRemaining,
|
|
18908
19162
|
adapter: {
|
|
18909
19163
|
id,
|
|
18910
19164
|
intervalMs: config.adapters.github.intervalMs,
|
|
18911
|
-
|
|
19165
|
+
takeUsage: () => client.takeUsage(),
|
|
19166
|
+
poll: (ctx) => withUsage(ctx.signal, () => pollRepository({
|
|
18912
19167
|
id,
|
|
18913
19168
|
repo,
|
|
18914
19169
|
login: project.operatorGithubLogin,
|
|
@@ -18918,8 +19173,8 @@ function githubSources(config, options) {
|
|
|
18918
19173
|
ctx,
|
|
18919
19174
|
reserveRemaining: config.github.reserveRemaining,
|
|
18920
19175
|
cache
|
|
18921
|
-
}),
|
|
18922
|
-
pollPr: (ref, ctx) => pollOnePr({
|
|
19176
|
+
})),
|
|
19177
|
+
pollPr: (ref, ctx) => withUsage(ctx.signal, () => pollOnePr({
|
|
18923
19178
|
id,
|
|
18924
19179
|
repo,
|
|
18925
19180
|
keys,
|
|
@@ -18928,7 +19183,7 @@ function githubSources(config, options) {
|
|
|
18928
19183
|
ref,
|
|
18929
19184
|
ctx,
|
|
18930
19185
|
cache
|
|
18931
|
-
})
|
|
19186
|
+
}))
|
|
18932
19187
|
}
|
|
18933
19188
|
});
|
|
18934
19189
|
}
|
|
@@ -19353,6 +19608,43 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
|
|
|
19353
19608
|
const discovery = await readDiscovery(request, acc, ctx, login);
|
|
19354
19609
|
if (!discovery.ok) acc.complete = false;
|
|
19355
19610
|
const { found } = discovery;
|
|
19611
|
+
const terminal = new Map((ctx.terminalPrs ?? []).filter(({ ref }) => ref.repo.toLowerCase() === repo.toLowerCase()).map((entry) => [entry.ref.number, entry]));
|
|
19612
|
+
const probes = [];
|
|
19613
|
+
const fullProbe = /* @__PURE__ */ new Set();
|
|
19614
|
+
const due = (ctx.prRechecks ?? []).filter((ref) => ref.repo.toLowerCase() === repo.toLowerCase());
|
|
19615
|
+
for (const [number, entry] of terminal) if (entry.state === "closed" && ["OPEN", "MERGED"].includes(found.states.get(number) ?? "")) fullProbe.add(number);
|
|
19616
|
+
const stateWire = z.object({ pullRequest: z.object({
|
|
19617
|
+
number: z.int().positive(),
|
|
19618
|
+
state: z.string()
|
|
19619
|
+
}).nullable() }).nullable();
|
|
19620
|
+
for (const chunk of chunks(due.filter((ref) => !fullProbe.has(ref.number)).map((ref) => ref.number), INDEX_CHUNK)) for (const segment of await sendChunk(request, chunk, stateQuery)) {
|
|
19621
|
+
const { response, numbers: sent } = segment;
|
|
19622
|
+
if (response !== void 0) acc.budget = response.budget;
|
|
19623
|
+
for (const [i, number] of sent.entries()) {
|
|
19624
|
+
const ref = due.find((ref) => ref.number === number);
|
|
19625
|
+
if (ref === void 0) continue;
|
|
19626
|
+
const errors = response === void 0 ? [] : scoped(response.errors, `pr${String(i)}`);
|
|
19627
|
+
const parsed = response === void 0 ? void 0 : stateWire.safeParse(response.data[`pr${String(i)}`]);
|
|
19628
|
+
if (response === void 0 || unscoped(response.errors, aliasesOf(sent)) || errors.length > 0 || !parsed?.success || parsed.data?.pullRequest == null || parsed.data.pullRequest.number !== number) {
|
|
19629
|
+
const missing = errors.some((error) => error.type === "NOT_FOUND");
|
|
19630
|
+
probes.push({
|
|
19631
|
+
ref,
|
|
19632
|
+
status: missing ? "not_found" : "no_access"
|
|
19633
|
+
});
|
|
19634
|
+
acc.complete = false;
|
|
19635
|
+
} else if (parsed.data.pullRequest.state === "CLOSED") probes.push({
|
|
19636
|
+
ref,
|
|
19637
|
+
status: "closed"
|
|
19638
|
+
});
|
|
19639
|
+
else fullProbe.add(number);
|
|
19640
|
+
}
|
|
19641
|
+
}
|
|
19642
|
+
found.numbers = found.numbers.filter((number) => !terminal.has(number));
|
|
19643
|
+
for (const number of fullProbe) {
|
|
19644
|
+
cache.delete(number);
|
|
19645
|
+
if (!found.numbers.includes(number)) found.numbers.push(number);
|
|
19646
|
+
}
|
|
19647
|
+
for (const number of terminal.keys()) cache.delete(number);
|
|
19356
19648
|
const numbers = [...byNumber.keys(), ...found.numbers.filter((number) => !byNumber.has(number) && cache.has(number))];
|
|
19357
19649
|
const fresh = found.numbers.filter((number) => !byNumber.has(number) && !cache.has(number));
|
|
19358
19650
|
for (const number of cache.keys()) if (!byNumber.has(number) && discovery.ok && !found.numbers.includes(number)) cache.delete(number);
|
|
@@ -19435,6 +19727,16 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
|
|
|
19435
19727
|
if (ctx.signal.aborted) throw new AdapterError("transient", "GitHub poll aborted");
|
|
19436
19728
|
if (requests.firstError !== void 0 && requests.succeeded === 0) throw requests.firstError;
|
|
19437
19729
|
rethrowLoneParseFailure(acc);
|
|
19730
|
+
const fullReadProbes = [...fullProbe].map((number) => ({
|
|
19731
|
+
ref: terminal.get(number)?.ref ?? {
|
|
19732
|
+
kind: "pr",
|
|
19733
|
+
repo,
|
|
19734
|
+
number
|
|
19735
|
+
},
|
|
19736
|
+
status: acc.items.some((item) => item.kind === "pr" && item.facts.number === number) ? "refreshed" : "no_access"
|
|
19737
|
+
}));
|
|
19738
|
+
if (fullReadProbes.some((probe) => probe.status === "no_access")) acc.complete = false;
|
|
19739
|
+
const prProbes = [...probes, ...fullReadProbes];
|
|
19438
19740
|
const nextCursor = bootstrap ? discovery.bootstrapCursor : found.cursor;
|
|
19439
19741
|
return {
|
|
19440
19742
|
source: id,
|
|
@@ -19442,6 +19744,7 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
|
|
|
19442
19744
|
complete: acc.complete,
|
|
19443
19745
|
items: acc.items,
|
|
19444
19746
|
entities: acc.entities,
|
|
19747
|
+
...prProbes.length === 0 ? {} : { prProbes },
|
|
19445
19748
|
...discovery.ok && discoveredOk ? nextCursor === void 0 ? {} : { cursor: nextCursor } : ctx.cursor === void 0 ? {} : { cursor: ctx.cursor },
|
|
19446
19749
|
...acc.budget === void 0 ? {} : { budget: acc.budget }
|
|
19447
19750
|
};
|
|
@@ -20188,6 +20491,24 @@ function applyEntityOutcomes(input) {
|
|
|
20188
20491
|
}
|
|
20189
20492
|
//#endregion
|
|
20190
20493
|
//#region ../adapters/src/runner/runner.ts
|
|
20494
|
+
function answersProbes(context, batch) {
|
|
20495
|
+
const probes = batch.prProbes ?? [];
|
|
20496
|
+
const key = (ref) => `${ref.repo.toLowerCase()}#${String(ref.number)}`;
|
|
20497
|
+
const allowed = new Set([...context.prRechecks ?? [], ...(context.terminalPrs ?? []).filter((entry) => entry.state === "closed").map((entry) => entry.ref)].map(key));
|
|
20498
|
+
const seen = /* @__PURE__ */ new Set();
|
|
20499
|
+
for (const probe of probes) {
|
|
20500
|
+
const identity = key(probe.ref);
|
|
20501
|
+
if (!allowed.has(identity) || seen.has(identity)) return false;
|
|
20502
|
+
seen.add(identity);
|
|
20503
|
+
const item = batch.items.some((item) => item.kind === "pr" && key({
|
|
20504
|
+
kind: "pr",
|
|
20505
|
+
repo: item.facts.repo,
|
|
20506
|
+
number: item.facts.number
|
|
20507
|
+
}) === identity);
|
|
20508
|
+
if (probe.status === "refreshed" !== item) return false;
|
|
20509
|
+
}
|
|
20510
|
+
return (context.prRechecks ?? []).every((ref) => seen.has(key(ref)));
|
|
20511
|
+
}
|
|
20191
20512
|
/** The setTimeout limit: a longer delay would otherwise fire after 1 ms. */
|
|
20192
20513
|
const MAX_TIMER_MS = 2147483647;
|
|
20193
20514
|
/** Waits before the second and third attempt of an on-demand poll after a transient failure. */
|
|
@@ -20272,14 +20593,18 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20272
20593
|
};
|
|
20273
20594
|
}
|
|
20274
20595
|
/** Appends the current state to the serial report chain; resolves when its step is done. */
|
|
20275
|
-
|
|
20276
|
-
|
|
20596
|
+
let pendingPoints;
|
|
20597
|
+
function report(usage, allowStopped = false) {
|
|
20598
|
+
if (usage !== void 0) pendingPoints = (pendingPoints ?? 0) + usage.points;
|
|
20599
|
+
if (stopping && !allowStopped) return reports;
|
|
20277
20600
|
reports = reports.then(async () => {
|
|
20278
20601
|
const next = state();
|
|
20279
20602
|
const json = JSON.stringify(next);
|
|
20280
|
-
if (json === lastReported) return;
|
|
20603
|
+
if (json === lastReported && pendingPoints === void 0) return;
|
|
20604
|
+
const points = pendingPoints;
|
|
20281
20605
|
try {
|
|
20282
|
-
await core.reportSourceState(source, next);
|
|
20606
|
+
await core.reportSourceState(source, next, points === void 0 ? void 0 : { points });
|
|
20607
|
+
if (points !== void 0) pendingPoints = pendingPoints === points ? void 0 : (pendingPoints ?? 0) - points;
|
|
20283
20608
|
lastReported = json;
|
|
20284
20609
|
} catch (error) {
|
|
20285
20610
|
fail("report", error);
|
|
@@ -20287,6 +20612,21 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20287
20612
|
});
|
|
20288
20613
|
return reports;
|
|
20289
20614
|
}
|
|
20615
|
+
/** Drain synchronously on abort, before the adapter unwinds or stop waits for reports. */
|
|
20616
|
+
async function readSource(read, signal) {
|
|
20617
|
+
const takeUsage = adapter.takeUsage?.bind(adapter);
|
|
20618
|
+
if (takeUsage === void 0) return untilAborted$1(read(), signal);
|
|
20619
|
+
const onAbort = () => {
|
|
20620
|
+
const usage = takeUsage();
|
|
20621
|
+
if (usage !== void 0) report(usage, true);
|
|
20622
|
+
};
|
|
20623
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
20624
|
+
try {
|
|
20625
|
+
return await untilAborted$1(read(), signal);
|
|
20626
|
+
} finally {
|
|
20627
|
+
signal.removeEventListener("abort", onAbort);
|
|
20628
|
+
}
|
|
20629
|
+
}
|
|
20290
20630
|
function armDeadline() {
|
|
20291
20631
|
clearTimeout(deadlineTimer);
|
|
20292
20632
|
deadlineTimer = void 0;
|
|
@@ -20326,6 +20666,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20326
20666
|
controller = abort;
|
|
20327
20667
|
const startMs = now();
|
|
20328
20668
|
let outcome;
|
|
20669
|
+
let usage;
|
|
20329
20670
|
let step = "context";
|
|
20330
20671
|
try {
|
|
20331
20672
|
const received = await core.context(source);
|
|
@@ -20344,17 +20685,18 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20344
20685
|
}
|
|
20345
20686
|
const requested = [...context.observe.prs, ...context.observe.tickets];
|
|
20346
20687
|
step = "poll";
|
|
20347
|
-
const batch = await
|
|
20688
|
+
const batch = await readSource(() => adapter.poll({
|
|
20348
20689
|
...context,
|
|
20349
20690
|
signal: abort.signal
|
|
20350
20691
|
}), abort.signal);
|
|
20351
20692
|
if (aborted()) return;
|
|
20693
|
+
usage = batch?.usage;
|
|
20352
20694
|
step = "batch";
|
|
20353
20695
|
const parsed = batchSchema.safeParse({
|
|
20354
20696
|
...batch,
|
|
20355
20697
|
observedAt: iso$1(startMs)
|
|
20356
20698
|
});
|
|
20357
|
-
const invalid = !parsed.success ? void 0 : parsed.data.source !== source ? "names another source" : !answersRequest(context.observe, parsed.data.entities) ? "does not answer the request" : void 0;
|
|
20699
|
+
const invalid = !parsed.success ? void 0 : parsed.data.source !== source ? "names another source" : !answersProbes(context, parsed.data) ? "does not answer state probes" : !answersRequest(context.observe, parsed.data.entities) ? "does not answer the request" : void 0;
|
|
20358
20700
|
if (!parsed.success || invalid !== void 0) {
|
|
20359
20701
|
const error = new AdapterError("transient", `Invalid batch: ${invalid ?? "fails the batch schema"}`);
|
|
20360
20702
|
fail("batch", error, parsed.error?.issues.map((issue) => ({
|
|
@@ -20388,6 +20730,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20388
20730
|
state: proposedState,
|
|
20389
20731
|
outcomes: outcomes.outcomes
|
|
20390
20732
|
});
|
|
20733
|
+
usage = void 0;
|
|
20391
20734
|
counts = outcomes.counts;
|
|
20392
20735
|
gone = outcomes.gone;
|
|
20393
20736
|
lastCompleteMs = proposedLastCompleteMs;
|
|
@@ -20405,6 +20748,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20405
20748
|
}
|
|
20406
20749
|
} catch (error) {
|
|
20407
20750
|
if (aborted()) return;
|
|
20751
|
+
if (error instanceof AdapterError && error.usage !== void 0) usage = error.usage;
|
|
20408
20752
|
fail(step, error);
|
|
20409
20753
|
if (error instanceof AdapterError && (error.kind === "auth" || error.kind === "config")) errorBlind = {
|
|
20410
20754
|
reason: error.kind,
|
|
@@ -20429,7 +20773,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20429
20773
|
failures = delay.failures;
|
|
20430
20774
|
throttledUntilMs = outcome.kind === "failed" ? throttledRetryAt(outcome.error) : void 0;
|
|
20431
20775
|
if (!options.oneShot) armDeadline();
|
|
20432
|
-
await report();
|
|
20776
|
+
await report(usage);
|
|
20433
20777
|
if (!options.oneShot) schedule(delay.delayMs);
|
|
20434
20778
|
return outcome;
|
|
20435
20779
|
}
|
|
@@ -20447,7 +20791,8 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20447
20791
|
reason: blind.reason,
|
|
20448
20792
|
message: blind.message
|
|
20449
20793
|
});
|
|
20450
|
-
|
|
20794
|
+
const pollOne = adapter.pollPr?.bind(adapter);
|
|
20795
|
+
if (pollOne === void 0) return err({
|
|
20451
20796
|
kind: "unsupported",
|
|
20452
20797
|
message: "The source does not poll one PR on demand"
|
|
20453
20798
|
});
|
|
@@ -20458,6 +20803,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20458
20803
|
message: "The source is throttled until retryAt"
|
|
20459
20804
|
});
|
|
20460
20805
|
const aborted = () => abort.signal.aborted;
|
|
20806
|
+
let usage;
|
|
20461
20807
|
let step = "context";
|
|
20462
20808
|
try {
|
|
20463
20809
|
const received = await untilAborted$1(core.context(source), abort.signal);
|
|
@@ -20466,12 +20812,13 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20466
20812
|
const feedbackCursors = received.feedbackCursors?.filter(own) ?? [];
|
|
20467
20813
|
const continuations = received.continuations?.filter(own) ?? [];
|
|
20468
20814
|
step = "poll";
|
|
20469
|
-
const batch = await
|
|
20815
|
+
const batch = await readSource(() => pollOne(ref, {
|
|
20470
20816
|
signal: abort.signal,
|
|
20471
20817
|
...feedbackCursors.length === 0 ? {} : { feedbackCursors },
|
|
20472
20818
|
...continuations.length === 0 ? {} : { continuations }
|
|
20473
20819
|
}), abort.signal);
|
|
20474
20820
|
if (aborted()) return err(stoppedError);
|
|
20821
|
+
usage = batch?.usage;
|
|
20475
20822
|
step = "batch";
|
|
20476
20823
|
const observedAt = iso$1(startMs);
|
|
20477
20824
|
const parsed = batchSchema.safeParse({
|
|
@@ -20483,7 +20830,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20483
20830
|
prs: [ref],
|
|
20484
20831
|
tickets: [],
|
|
20485
20832
|
sessions: []
|
|
20486
|
-
}, parsed.data.entities) ? "does not answer the request" : parsed.data.complete ? "is marked complete" : parsed.data.cursor !== void 0 ? "carries a cursor" : parsed.data.items.some((item) => item.kind === "pr" && item.continuation !== void 0) ? "carries a continuation" : value === void 0 ? "carries another item" : void 0;
|
|
20833
|
+
}, parsed.data.entities) ? "does not answer the request" : (parsed.data.prProbes?.length ?? 0) > 0 ? "carries state probes" : parsed.data.complete ? "is marked complete" : parsed.data.cursor !== void 0 ? "carries a cursor" : parsed.data.items.some((item) => item.kind === "pr" && item.continuation !== void 0) ? "carries a continuation" : value === void 0 ? "carries another item" : void 0;
|
|
20487
20834
|
if (!parsed.success || invalid !== void 0 || value === void 0) {
|
|
20488
20835
|
const error = new AdapterError("transient", `Invalid batch: ${invalid ?? "fails the batch schema"}`);
|
|
20489
20836
|
fail("batch", error, parsed.error?.issues.map((issue) => ({
|
|
@@ -20491,6 +20838,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20491
20838
|
code: issue.code,
|
|
20492
20839
|
message: issue.message
|
|
20493
20840
|
})));
|
|
20841
|
+
await report(usage);
|
|
20494
20842
|
return err({
|
|
20495
20843
|
kind: "failed",
|
|
20496
20844
|
adapterKind: "transient",
|
|
@@ -20502,22 +20850,38 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20502
20850
|
if (!live()) return;
|
|
20503
20851
|
if (stopping) return err(stoppedError);
|
|
20504
20852
|
observing();
|
|
20505
|
-
const
|
|
20853
|
+
const recoveredKey = value.status === "ok" ? entityKey(ref).toLowerCase() : void 0;
|
|
20854
|
+
const recoveredCounts = recoveredKey === void 0 ? counts : new Map([...counts].filter(([key]) => key.toLowerCase() !== recoveredKey));
|
|
20855
|
+
const recoveredGone = recoveredKey === void 0 ? gone : gone.filter((known) => entityKey(known).toLowerCase() !== recoveredKey);
|
|
20856
|
+
const committed = {
|
|
20857
|
+
...state(),
|
|
20858
|
+
gone: recoveredGone
|
|
20859
|
+
};
|
|
20506
20860
|
await core.observe(source, {
|
|
20507
20861
|
batch: parsed.data,
|
|
20508
20862
|
effectiveComplete: false,
|
|
20509
20863
|
state: committed,
|
|
20510
20864
|
outcomes: []
|
|
20511
20865
|
});
|
|
20866
|
+
usage = void 0;
|
|
20867
|
+
counts = recoveredCounts;
|
|
20868
|
+
gone = recoveredGone;
|
|
20512
20869
|
lastReported = JSON.stringify(committed);
|
|
20513
20870
|
return ok(value);
|
|
20514
20871
|
});
|
|
20515
20872
|
reports = accepted.then(noop, noop);
|
|
20516
|
-
|
|
20873
|
+
const result = await accepted;
|
|
20874
|
+
if (usage !== void 0) {
|
|
20875
|
+
await report(usage, true);
|
|
20876
|
+
usage = void 0;
|
|
20877
|
+
}
|
|
20878
|
+
return result;
|
|
20517
20879
|
} catch (error) {
|
|
20518
20880
|
if (aborted()) return err(stoppedError);
|
|
20881
|
+
if (error instanceof AdapterError && error.usage !== void 0) usage = error.usage;
|
|
20519
20882
|
fail(step, error);
|
|
20520
20883
|
if (step === "poll" && error instanceof AdapterError && error.kind === "transient") retryable();
|
|
20884
|
+
await report(usage);
|
|
20521
20885
|
const retryAt = throttledRetryAt(error);
|
|
20522
20886
|
return err({
|
|
20523
20887
|
kind: "failed",
|
package/dist/mcp.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { C as renderMcpError, X as ERRORS, y as OPERATIONS } from "./chunk-
|
|
2
|
-
import { o as CliError, r as requestOperation } from "./chunk-
|
|
3
|
-
import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-
|
|
1
|
+
import { C as renderMcpError, X as ERRORS, y as OPERATIONS } from "./chunk-CLjE9L59.mjs";
|
|
2
|
+
import { o as CliError, r as requestOperation } from "./chunk-DQwj2UTj.mjs";
|
|
3
|
+
import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-BLpo-8dp.mjs";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
import { readFileSync } from "node:fs";
|
|
6
6
|
import { z } from "zod";
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
-- A separate deadline keeps cache replay from extending a closed PR's quiet period.
|
|
2
|
+
ALTER TABLE pr_snapshot ADD COLUMN closed_recheck_at TEXT;
|
|
3
|
+
CREATE TABLE source_cost (
|
|
4
|
+
id INTEGER PRIMARY KEY,
|
|
5
|
+
source TEXT NOT NULL,
|
|
6
|
+
at TEXT NOT NULL,
|
|
7
|
+
points INTEGER NOT NULL CHECK (points >= 0)
|
|
8
|
+
) STRICT;
|
|
9
|
+
CREATE INDEX source_cost_source_at ON source_cost (source, at);
|
package/package.json
CHANGED
|
@@ -14,13 +14,13 @@ Other errors: `not_found`.
|
|
|
14
14
|
|
|
15
15
|
### `board task`
|
|
16
16
|
|
|
17
|
-
Purpose: Show a task
|
|
17
|
+
Purpose: Show a task; refresh reads GitHub PRs.
|
|
18
18
|
Arguments: `<task>`.
|
|
19
|
-
Flags: `--detail`, `--why`, `--json`.
|
|
20
|
-
Use when: Inspect
|
|
19
|
+
Flags: `--refresh`, `--detail`, `--why`, `--json`.
|
|
20
|
+
Use when: Inspect a task; detail adds closed turns.
|
|
21
21
|
Avoid when: Use `board task history <task>` for past events.
|
|
22
22
|
Example: `board task PROJ-123` — Show one task.
|
|
23
|
-
Other errors: `wrong_id_kind`, `not_found`.
|
|
23
|
+
Other errors: `wrong_id_kind`, `not_found`, `github_unavailable`.
|
|
24
24
|
|
|
25
25
|
### `board task history`
|
|
26
26
|
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
|
|
14
14
|
- `not_found`: Check the ID with `board status` or `board task <KEY>`.
|
|
15
15
|
- `wrong_id_kind`: Pass the ID kind the operation expects, e.g. B<n> for a block or a task key for a task.
|
|
16
|
+
- `github_unavailable`: Wait until GitHub answers, then retry the operation.
|
|
16
17
|
- `stale_comment_revision`: Read the latest comment revision, then acknowledge that revision.
|
|
17
18
|
- `idempotency_key_mismatch`: Use a new key for a new command, or repeat the earlier input with the same key.
|
|
18
19
|
- `task_archived`: Ask an operator to add the task to the board again if work continues.
|
|
@@ -21,5 +22,4 @@
|
|
|
21
22
|
- `turn_closed`: Read your open turns with `board inbox` and act only on a turn listed there.
|
|
22
23
|
- `not_turn_taker`: Take the turn with `board inbox ack` first; only the session that took it can submit or return it.
|
|
23
24
|
- `head_mismatch`: Push the commit to the task's pull request branch and submit its head; if the task has none, ask the operator to link the pull request with `board link` first.
|
|
24
|
-
- `github_unavailable`: Wait until GitHub answers, then submit again.
|
|
25
25
|
- `return_not_allowed`: In Dev, ask with `board ask` instead.
|