spur-board 0.59.1 → 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 +453 -78
- 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
- package/skills/spur-board/references/how-board-works.md +3 -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";
|
|
@@ -433,9 +433,15 @@ function priorAddressees(original, current, type, hasCurator) {
|
|
|
433
433
|
}
|
|
434
434
|
return path;
|
|
435
435
|
}
|
|
436
|
-
|
|
436
|
+
/** Skips each step the escalating actor's own project holds, up to the operator. */
|
|
437
|
+
function escalateBlock(block, hasCurator = false, heldByActor = () => false) {
|
|
437
438
|
requireOpen(block);
|
|
438
|
-
|
|
439
|
+
let addressee = nextAddressee(block.addressee, block.type, hasCurator);
|
|
440
|
+
while (heldByActor(addressee)) {
|
|
441
|
+
const next = nextAddressee(addressee, block.type, hasCurator);
|
|
442
|
+
if (next === addressee) break;
|
|
443
|
+
addressee = next;
|
|
444
|
+
}
|
|
439
445
|
return {
|
|
440
446
|
addressee,
|
|
441
447
|
changed: block.addressee !== addressee
|
|
@@ -8437,7 +8443,7 @@ function createQuery(deps) {
|
|
|
8437
8443
|
const parsed = entry.input.safeParse(input);
|
|
8438
8444
|
if (!parsed.success) throw new CommandError(errorCodeOf(parsed.error), "Fix the operation input.");
|
|
8439
8445
|
const parsedInput = parsed.data;
|
|
8440
|
-
const
|
|
8446
|
+
const read = (prepare) => store.transaction(async (trx) => {
|
|
8441
8447
|
const targets = await query.resolveTargets(trx, parsedInput, actor);
|
|
8442
8448
|
for (const target of targets.length === 0 ? [{ kind: "missing" }] : targets) {
|
|
8443
8449
|
const decision = authorize(entry.grants, actor, {
|
|
@@ -8461,12 +8467,20 @@ function createQuery(deps) {
|
|
|
8461
8467
|
}
|
|
8462
8468
|
if (targets.some((target) => target.kind === "missing")) throw new CommandError("not_found", "Check the target ID.");
|
|
8463
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" };
|
|
8464
8471
|
const value = await query.run(trx, parsedInput, actor);
|
|
8465
8472
|
return {
|
|
8466
8473
|
status: "done",
|
|
8467
8474
|
value: entry.output.parse(value)
|
|
8468
8475
|
};
|
|
8469
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");
|
|
8470
8484
|
if (result.status === "denied") throw new CommandError("forbidden", result.hint);
|
|
8471
8485
|
return result.value;
|
|
8472
8486
|
};
|
|
@@ -11522,6 +11536,20 @@ function holdsBlock(config, actor, target) {
|
|
|
11522
11536
|
target
|
|
11523
11537
|
}).status === "allowed";
|
|
11524
11538
|
}
|
|
11539
|
+
/** `target` with its block moved to `role`, to ask who would hold it there. */
|
|
11540
|
+
function atAddressee(target, role) {
|
|
11541
|
+
if (target.kind !== "found" || target.value.block === null) return target;
|
|
11542
|
+
return {
|
|
11543
|
+
kind: "found",
|
|
11544
|
+
value: {
|
|
11545
|
+
...target.value,
|
|
11546
|
+
block: {
|
|
11547
|
+
...target.value.block,
|
|
11548
|
+
addressee_role: role
|
|
11549
|
+
}
|
|
11550
|
+
}
|
|
11551
|
+
};
|
|
11552
|
+
}
|
|
11525
11553
|
function wroteBlock(config, actor, target) {
|
|
11526
11554
|
return authorize([{ grant: "block-author" }], actor, {
|
|
11527
11555
|
config,
|
|
@@ -11840,17 +11868,8 @@ function createBlockMutations(config) {
|
|
|
11840
11868
|
const { task } = subject;
|
|
11841
11869
|
if (task === null) return [target];
|
|
11842
11870
|
const priors = priorAddressees(await routeBlock(trx, task, block, config), block.addressee_role, block.type, curatorProject(config, task.project) !== null);
|
|
11843
|
-
for (const
|
|
11844
|
-
const prior =
|
|
11845
|
-
kind: "found",
|
|
11846
|
-
value: {
|
|
11847
|
-
...target.value,
|
|
11848
|
-
block: {
|
|
11849
|
-
...target.value.block,
|
|
11850
|
-
addressee_role
|
|
11851
|
-
}
|
|
11852
|
-
}
|
|
11853
|
-
};
|
|
11871
|
+
for (const role of priors) {
|
|
11872
|
+
const prior = atAddressee(target, role);
|
|
11854
11873
|
if (holdsBlock(config, actor, prior)) return [prior];
|
|
11855
11874
|
}
|
|
11856
11875
|
return [target];
|
|
@@ -11861,13 +11880,13 @@ function createBlockMutations(config) {
|
|
|
11861
11880
|
const { task } = subject;
|
|
11862
11881
|
if (task !== null) active(task);
|
|
11863
11882
|
const hasCurator = curatorProject(config, subject.project) !== null;
|
|
11864
|
-
const
|
|
11883
|
+
const target = await subjectTarget(trx, subject, block);
|
|
11884
|
+
const next = rule(() => escalateBlock(current$1(block), hasCurator, (role) => holdsBlock(config, ctx.actor, atAddressee(target, role))));
|
|
11865
11885
|
const unchanged = async () => {
|
|
11866
11886
|
if (input.note !== void 0) await addComment(trx, subject, block, input.note, ctx, block.addressee_role, config, { ringsAuthor: false });
|
|
11867
11887
|
return { block: blockView(block, subject) };
|
|
11868
11888
|
};
|
|
11869
11889
|
if (!next.changed || task === null) return unchanged();
|
|
11870
|
-
const target = await subjectTarget(trx, subject, block);
|
|
11871
11890
|
if (!holdsBlock(config, ctx.actor, target)) return unchanged();
|
|
11872
11891
|
const updated = await moveBlockToAddressee(trx, {
|
|
11873
11892
|
task,
|
|
@@ -12095,6 +12114,112 @@ function createBlockMutations(config) {
|
|
|
12095
12114
|
};
|
|
12096
12115
|
}
|
|
12097
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
|
|
12098
12223
|
//#region ../core/src/app/archive.ts
|
|
12099
12224
|
/**
|
|
12100
12225
|
* Takes a task off the board in the caller's transaction: closes its open blocks with outcome
|
|
@@ -12200,6 +12325,7 @@ function createMembershipMutations(config) {
|
|
|
12200
12325
|
if (task.membership === "archived") await emit(trx, "task_added", project.id, task.id, ctx.at, { column: task.column }, "operator");
|
|
12201
12326
|
task = await trx.selectFrom("task").selectAll().where("id", "=", task.id).executeTakeFirstOrThrow();
|
|
12202
12327
|
}
|
|
12328
|
+
await reconcileTaskPrs(trx, config, task.id, ctx.at);
|
|
12203
12329
|
return { task: taskView(task) };
|
|
12204
12330
|
}
|
|
12205
12331
|
},
|
|
@@ -13083,6 +13209,37 @@ function createItemMutations(deps) {
|
|
|
13083
13209
|
};
|
|
13084
13210
|
}
|
|
13085
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
|
|
13086
13243
|
//#region ../core/src/app/links.ts
|
|
13087
13244
|
function prIdentity(url) {
|
|
13088
13245
|
const parsed = new URL(url);
|
|
@@ -13276,12 +13433,24 @@ async function run(trx, input, ctx, config, remove) {
|
|
|
13276
13433
|
target
|
|
13277
13434
|
};
|
|
13278
13435
|
}
|
|
13279
|
-
function createLinkMutations(config) {
|
|
13436
|
+
function createLinkMutations(config, deps = {}) {
|
|
13280
13437
|
const resolveTargets = (trx, input) => taskTarget(trx, canonicalKey(config, input.task).key);
|
|
13281
13438
|
return {
|
|
13282
13439
|
add: {
|
|
13283
13440
|
id: "link.add",
|
|
13284
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
|
+
},
|
|
13285
13454
|
run: (trx, input, ctx) => run(trx, input, ctx, config, false)
|
|
13286
13455
|
},
|
|
13287
13456
|
remove: {
|
|
@@ -13481,6 +13650,9 @@ async function getStatus(deps, options = {}) {
|
|
|
13481
13650
|
});
|
|
13482
13651
|
const sourceRows = await store.db.selectFrom("source_state").selectAll().execute();
|
|
13483
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);
|
|
13484
13656
|
const sourceById = new Map(sourceRows.map((row) => [row.source, row]));
|
|
13485
13657
|
const sources = [...required].map((source) => {
|
|
13486
13658
|
const row = sourceById.get(source);
|
|
@@ -13488,6 +13660,7 @@ async function getStatus(deps, options = {}) {
|
|
|
13488
13660
|
const blindReason = row?.blind_reason === "auth" || row?.blind_reason === "config" || row?.blind_reason === "stale" ? row.blind_reason : null;
|
|
13489
13661
|
return {
|
|
13490
13662
|
source,
|
|
13663
|
+
...source.startsWith("github:") ? { pointsLastHour: points.get(source) ?? 0 } : {},
|
|
13491
13664
|
observedAt: row?.observed_at ?? null,
|
|
13492
13665
|
lastCompleteAt: last,
|
|
13493
13666
|
blindReason,
|
|
@@ -15399,6 +15572,16 @@ function createTaskQueries(deps) {
|
|
|
15399
15572
|
const get = {
|
|
15400
15573
|
id: "task.get",
|
|
15401
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
|
+
},
|
|
15402
15585
|
async run(trx, input) {
|
|
15403
15586
|
const task = await taskByKey(trx, taskKey(input.task));
|
|
15404
15587
|
const [blocks, comments, links] = await Promise.all([
|
|
@@ -15863,11 +16046,12 @@ function createOperationRegistry(deps) {
|
|
|
15863
16046
|
const { config, clock, completeSince, gateways } = deps;
|
|
15864
16047
|
const items = createItemMutations(deps);
|
|
15865
16048
|
const membership = createMembershipMutations(config);
|
|
15866
|
-
const links = createLinkMutations(config);
|
|
16049
|
+
const links = createLinkMutations(config, { prPoller: deps.prPoller });
|
|
15867
16050
|
const blocks = createBlockMutations(config);
|
|
15868
16051
|
const taskQueries = createTaskQueries({
|
|
15869
16052
|
config,
|
|
15870
|
-
completeSince
|
|
16053
|
+
completeSince,
|
|
16054
|
+
prPoller: deps.prPoller
|
|
15871
16055
|
});
|
|
15872
16056
|
const turns = createTurnMutations({
|
|
15873
16057
|
config,
|
|
@@ -16157,10 +16341,6 @@ async function setReopenFloor(trx, taskId, at) {
|
|
|
16157
16341
|
* `updatedAt`, never earlier than the merge, so a later edit makes the merge count. Then the reopen hides this link only: another link
|
|
16158
16342
|
* of the task that already counts, such as a follow-up merged after the reopen, keeps counting.
|
|
16159
16343
|
*/
|
|
16160
|
-
/** The PR was merged before `reopenedAt`; a tie counts the merge. */
|
|
16161
|
-
function mergedBefore(fact, reopenedAt) {
|
|
16162
|
-
return fact.state === "merged" && reopenedAt !== null && Date.parse(fact.mergedAt ?? fact.updatedAt) < Date.parse(reopenedAt);
|
|
16163
|
-
}
|
|
16164
16344
|
async function applyPendingReopen(trx, fact, at) {
|
|
16165
16345
|
if (fact.state === "open") return;
|
|
16166
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();
|
|
@@ -16195,6 +16375,8 @@ async function ticket(trx, config, fact, at, source) {
|
|
|
16195
16375
|
if (project === void 0) throw new Error("Ticket from an unconfigured tracker");
|
|
16196
16376
|
let task = await trx.selectFrom("task").selectAll().where("project", "=", project.id).where("tracker_kind", "=", project.tracker.type).where("tracker_id", "=", fact.id).executeTakeFirst();
|
|
16197
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;
|
|
16198
16380
|
if (task !== void 0 && pending !== void 0 && pending.id !== task.id) {
|
|
16199
16381
|
const oldKey = task.key;
|
|
16200
16382
|
await trx.updateTable("task").set({ key: `__transfer__${String(task.id)}` }).where("id", "=", task.id).execute();
|
|
@@ -16282,10 +16464,19 @@ async function ticket(trx, config, fact, at, source) {
|
|
|
16282
16464
|
if (task.membership === "out_of_filter") await emit(trx, "flag_cleared", project.id, task.id, at, { flag: "out_of_filter" });
|
|
16283
16465
|
else await emit(trx, "task_added", project.id, task.id, at, { column: task.column });
|
|
16284
16466
|
}
|
|
16467
|
+
if (previousKey !== fact.key || previousMembership === "archived") await reconcileTaskPrs(trx, config, task.id, at);
|
|
16285
16468
|
}
|
|
16286
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();
|
|
16287
16475
|
const old = await trx.selectFrom("pr_snapshot").selectAll().where(sql`lower(repo) = ${fact.repo.toLowerCase()}`).where("number", "=", fact.number).executeTakeFirst();
|
|
16288
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);
|
|
16289
16480
|
const changed = previous === null || JSON.stringify(previous) !== JSON.stringify(fact);
|
|
16290
16481
|
await trx.insertInto("pr_snapshot").values({
|
|
16291
16482
|
repo: old?.repo ?? fact.repo,
|
|
@@ -16298,8 +16489,10 @@ async function pr(trx, config, fact, at, source) {
|
|
|
16298
16489
|
merge_state: fact.mergeState,
|
|
16299
16490
|
detail: toJson(prFactsSchema, fact),
|
|
16300
16491
|
source,
|
|
16301
|
-
observed_at: at
|
|
16492
|
+
observed_at: at,
|
|
16493
|
+
closed_recheck_at: recheckAt
|
|
16302
16494
|
}).onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet({
|
|
16495
|
+
closed_recheck_at: recheckAt,
|
|
16303
16496
|
head_sha: fact.headSha,
|
|
16304
16497
|
head_branch: fact.headBranch,
|
|
16305
16498
|
state: fact.state,
|
|
@@ -16321,33 +16514,7 @@ async function pr(trx, config, fact, at, source) {
|
|
|
16321
16514
|
for (const key of fact.ticketKeys) {
|
|
16322
16515
|
const task = await trx.selectFrom("task").selectAll().where("project", "=", project.id).where("key", "=", key).executeTakeFirst();
|
|
16323
16516
|
if (task === void 0 || task.membership === "archived") continue;
|
|
16324
|
-
|
|
16325
|
-
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();
|
|
16326
|
-
const state = fact.state !== "open" || active === void 0 ? "active" : "conflict";
|
|
16327
|
-
await trx.insertInto("link").values({
|
|
16328
|
-
task_id: task.id,
|
|
16329
|
-
entity: "pr",
|
|
16330
|
-
repo: fact.repo,
|
|
16331
|
-
number: fact.number,
|
|
16332
|
-
pr_state: state,
|
|
16333
|
-
session_id: null,
|
|
16334
|
-
role: null,
|
|
16335
|
-
source: "branch",
|
|
16336
|
-
banned: 0,
|
|
16337
|
-
created_at: at,
|
|
16338
|
-
ticket_key: null,
|
|
16339
|
-
pr_open: fact.state === "open" ? 1 : 0,
|
|
16340
|
-
reopen_hidden_at: mergedBefore(fact, task.reopened_at) ? at : null
|
|
16341
|
-
}).execute();
|
|
16342
|
-
await emit(trx, "link_added", task.project, task.id, at, {
|
|
16343
|
-
entity: "pr",
|
|
16344
|
-
repo: fact.repo,
|
|
16345
|
-
pr: fact.number,
|
|
16346
|
-
state,
|
|
16347
|
-
source: "branch",
|
|
16348
|
-
facts: fact
|
|
16349
|
-
});
|
|
16350
|
-
}
|
|
16517
|
+
await linkPrToTask(trx, task, fact, at);
|
|
16351
16518
|
}
|
|
16352
16519
|
const linkedPrs = await trx.selectFrom("link").select([
|
|
16353
16520
|
"id",
|
|
@@ -16618,6 +16785,16 @@ async function holdContinuation(trx, source, item) {
|
|
|
16618
16785
|
...held
|
|
16619
16786
|
}).onConflict((oc) => oc.columns(["source", "ref_key"]).doUpdateSet(held)).execute();
|
|
16620
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
|
+
}
|
|
16621
16798
|
/** Core's adapter-facing port. Every accepted batch and its source state share one transaction. */
|
|
16622
16799
|
function createObservationCore(deps) {
|
|
16623
16800
|
const { store, config, clock } = deps;
|
|
@@ -16645,7 +16822,41 @@ function createObservationCore(deps) {
|
|
|
16645
16822
|
key: task.key
|
|
16646
16823
|
}] : [];
|
|
16647
16824
|
}) : [];
|
|
16648
|
-
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)));
|
|
16649
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 ? [] : [{
|
|
16650
16861
|
kind: "session",
|
|
16651
16862
|
id: link.session_id
|
|
@@ -16659,9 +16870,11 @@ function createObservationCore(deps) {
|
|
|
16659
16870
|
})));
|
|
16660
16871
|
}
|
|
16661
16872
|
const misses = await store.db.selectFrom("source_miss").selectAll().where("source", "=", source).execute();
|
|
16662
|
-
const feedbackCursors = await pollFeedbackCursors(store.db, config,
|
|
16663
|
-
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);
|
|
16664
16875
|
return {
|
|
16876
|
+
terminalPrs,
|
|
16877
|
+
prRechecks,
|
|
16665
16878
|
observe: {
|
|
16666
16879
|
prs: requested,
|
|
16667
16880
|
tickets,
|
|
@@ -16685,6 +16898,26 @@ function createObservationCore(deps) {
|
|
|
16685
16898
|
await scanTransaction(store, config, async (trx) => {
|
|
16686
16899
|
const wasBlind = await blindReason(trx, source);
|
|
16687
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
|
+
}
|
|
16688
16921
|
for (const outcome of observation.outcomes) {
|
|
16689
16922
|
const answer = batch.entities.find((entity) => refKey(entity.ref) === refKey(outcome.ref));
|
|
16690
16923
|
await trx.insertInto("source_miss").values({
|
|
@@ -16800,11 +17033,12 @@ function createObservationCore(deps) {
|
|
|
16800
17033
|
});
|
|
16801
17034
|
if (observation.effectiveComplete) completeSince.set(source, batch.observedAt);
|
|
16802
17035
|
},
|
|
16803
|
-
reportSourceState(source, state) {
|
|
17036
|
+
reportSourceState(source, state, usage) {
|
|
16804
17037
|
const now = clock.now();
|
|
16805
17038
|
return scanTransaction(store, config, async (trx) => {
|
|
16806
17039
|
const wasBlind = await blindReason(trx, source);
|
|
16807
17040
|
await sourceState(trx, source, state);
|
|
17041
|
+
await recordUsage(trx, source, usage, now);
|
|
16808
17042
|
if (wasBlind !== null && state.blind === void 0) await dispatchSource(trx, source, {
|
|
16809
17043
|
config,
|
|
16810
17044
|
at: new Date(now),
|
|
@@ -18291,18 +18525,21 @@ function aliases(numbers, fields) {
|
|
|
18291
18525
|
}
|
|
18292
18526
|
const discoveryStates = (bootstrap) => bootstrap ? "OPEN" : "OPEN, MERGED, CLOSED";
|
|
18293
18527
|
function discoveryQuery(bootstrap = false) {
|
|
18294
|
-
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")} }`;
|
|
18295
18532
|
}
|
|
18296
18533
|
function indexQuery(numbers) {
|
|
18297
|
-
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)} }`;
|
|
18298
18535
|
}
|
|
18299
18536
|
function detailQuery(numbers, closing = false) {
|
|
18300
|
-
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))} }`;
|
|
18301
18538
|
}
|
|
18302
18539
|
function pageQuery(connection, bootstrap = false) {
|
|
18303
|
-
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} } } } }`;
|
|
18304
|
-
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} } } }`;
|
|
18305
|
-
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 } }`} } } }`;
|
|
18306
18543
|
}
|
|
18307
18544
|
/**
|
|
18308
18545
|
* The failure that GraphQL `errors` mean for the whole request, in rule order: a rate limit is
|
|
@@ -18322,6 +18559,12 @@ function checkAccessDenied(errors) {
|
|
|
18322
18559
|
return errors.some((error) => error.type === "FORBIDDEN" && error.path?.includes("statusCheckRollup") === true && error.path.includes("contexts"));
|
|
18323
18560
|
}
|
|
18324
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
|
+
}
|
|
18325
18568
|
token;
|
|
18326
18569
|
now;
|
|
18327
18570
|
fetcher;
|
|
@@ -18367,6 +18610,8 @@ var GithubClient = class {
|
|
|
18367
18610
|
body
|
|
18368
18611
|
};
|
|
18369
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;
|
|
18370
18615
|
const wire = parseWire(graphEnvelopeWire, body, MALFORMED$3);
|
|
18371
18616
|
const errors = wire.errors ?? [];
|
|
18372
18617
|
const failure = graphqlFailure(errors, query, response.headers, this.now());
|
|
@@ -18384,6 +18629,7 @@ var GithubClient = class {
|
|
|
18384
18629
|
const timestamp$1 = z.string().min(1).refine((value) => !Number.isNaN(Date.parse(value)));
|
|
18385
18630
|
const discoveryNodeWire = z.object({
|
|
18386
18631
|
number: z.int().positive(),
|
|
18632
|
+
state: z.string().optional(),
|
|
18387
18633
|
updatedAt: timestamp$1,
|
|
18388
18634
|
author: z.object({ login: z.string() }).nullable()
|
|
18389
18635
|
});
|
|
@@ -18400,16 +18646,19 @@ function latestUpdatedAt(nodes, previous) {
|
|
|
18400
18646
|
function discover(nodes, previous, login) {
|
|
18401
18647
|
let high = previous;
|
|
18402
18648
|
const numbers = /* @__PURE__ */ new Set();
|
|
18649
|
+
const states = /* @__PURE__ */ new Map();
|
|
18403
18650
|
for (const node of nodes) {
|
|
18404
18651
|
const updated = sourceCursorSchema.parse(node.updatedAt);
|
|
18405
18652
|
const updatedMs = Date.parse(updated);
|
|
18406
18653
|
if (high === void 0 || updatedMs > Date.parse(high)) high = updated;
|
|
18407
18654
|
if (previous !== void 0 && updatedMs < Date.parse(previous)) continue;
|
|
18655
|
+
states.set(node.number, node.state);
|
|
18408
18656
|
if (node.author?.login.toLowerCase() !== login.toLowerCase()) continue;
|
|
18409
18657
|
numbers.add(node.number);
|
|
18410
18658
|
}
|
|
18411
18659
|
return {
|
|
18412
18660
|
numbers: [...numbers],
|
|
18661
|
+
states,
|
|
18413
18662
|
...high === void 0 ? {} : { cursor: high }
|
|
18414
18663
|
};
|
|
18415
18664
|
}
|
|
@@ -18891,13 +19140,30 @@ function githubSources(config, options) {
|
|
|
18891
19140
|
const client = new GithubClient(options.token, options.now, options.fetch);
|
|
18892
19141
|
const keys = projectKeyRule(project.tracker, project.link, repo);
|
|
18893
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
|
+
}
|
|
18894
19159
|
sources.push({
|
|
18895
19160
|
repo,
|
|
18896
19161
|
reserveRemaining: config.github.reserveRemaining,
|
|
18897
19162
|
adapter: {
|
|
18898
19163
|
id,
|
|
18899
19164
|
intervalMs: config.adapters.github.intervalMs,
|
|
18900
|
-
|
|
19165
|
+
takeUsage: () => client.takeUsage(),
|
|
19166
|
+
poll: (ctx) => withUsage(ctx.signal, () => pollRepository({
|
|
18901
19167
|
id,
|
|
18902
19168
|
repo,
|
|
18903
19169
|
login: project.operatorGithubLogin,
|
|
@@ -18907,8 +19173,8 @@ function githubSources(config, options) {
|
|
|
18907
19173
|
ctx,
|
|
18908
19174
|
reserveRemaining: config.github.reserveRemaining,
|
|
18909
19175
|
cache
|
|
18910
|
-
}),
|
|
18911
|
-
pollPr: (ref, ctx) => pollOnePr({
|
|
19176
|
+
})),
|
|
19177
|
+
pollPr: (ref, ctx) => withUsage(ctx.signal, () => pollOnePr({
|
|
18912
19178
|
id,
|
|
18913
19179
|
repo,
|
|
18914
19180
|
keys,
|
|
@@ -18917,7 +19183,7 @@ function githubSources(config, options) {
|
|
|
18917
19183
|
ref,
|
|
18918
19184
|
ctx,
|
|
18919
19185
|
cache
|
|
18920
|
-
})
|
|
19186
|
+
}))
|
|
18921
19187
|
}
|
|
18922
19188
|
});
|
|
18923
19189
|
}
|
|
@@ -19342,6 +19608,43 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
|
|
|
19342
19608
|
const discovery = await readDiscovery(request, acc, ctx, login);
|
|
19343
19609
|
if (!discovery.ok) acc.complete = false;
|
|
19344
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);
|
|
19345
19648
|
const numbers = [...byNumber.keys(), ...found.numbers.filter((number) => !byNumber.has(number) && cache.has(number))];
|
|
19346
19649
|
const fresh = found.numbers.filter((number) => !byNumber.has(number) && !cache.has(number));
|
|
19347
19650
|
for (const number of cache.keys()) if (!byNumber.has(number) && discovery.ok && !found.numbers.includes(number)) cache.delete(number);
|
|
@@ -19424,6 +19727,16 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
|
|
|
19424
19727
|
if (ctx.signal.aborted) throw new AdapterError("transient", "GitHub poll aborted");
|
|
19425
19728
|
if (requests.firstError !== void 0 && requests.succeeded === 0) throw requests.firstError;
|
|
19426
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];
|
|
19427
19740
|
const nextCursor = bootstrap ? discovery.bootstrapCursor : found.cursor;
|
|
19428
19741
|
return {
|
|
19429
19742
|
source: id,
|
|
@@ -19431,6 +19744,7 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
|
|
|
19431
19744
|
complete: acc.complete,
|
|
19432
19745
|
items: acc.items,
|
|
19433
19746
|
entities: acc.entities,
|
|
19747
|
+
...prProbes.length === 0 ? {} : { prProbes },
|
|
19434
19748
|
...discovery.ok && discoveredOk ? nextCursor === void 0 ? {} : { cursor: nextCursor } : ctx.cursor === void 0 ? {} : { cursor: ctx.cursor },
|
|
19435
19749
|
...acc.budget === void 0 ? {} : { budget: acc.budget }
|
|
19436
19750
|
};
|
|
@@ -20177,6 +20491,24 @@ function applyEntityOutcomes(input) {
|
|
|
20177
20491
|
}
|
|
20178
20492
|
//#endregion
|
|
20179
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
|
+
}
|
|
20180
20512
|
/** The setTimeout limit: a longer delay would otherwise fire after 1 ms. */
|
|
20181
20513
|
const MAX_TIMER_MS = 2147483647;
|
|
20182
20514
|
/** Waits before the second and third attempt of an on-demand poll after a transient failure. */
|
|
@@ -20261,14 +20593,18 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20261
20593
|
};
|
|
20262
20594
|
}
|
|
20263
20595
|
/** Appends the current state to the serial report chain; resolves when its step is done. */
|
|
20264
|
-
|
|
20265
|
-
|
|
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;
|
|
20266
20600
|
reports = reports.then(async () => {
|
|
20267
20601
|
const next = state();
|
|
20268
20602
|
const json = JSON.stringify(next);
|
|
20269
|
-
if (json === lastReported) return;
|
|
20603
|
+
if (json === lastReported && pendingPoints === void 0) return;
|
|
20604
|
+
const points = pendingPoints;
|
|
20270
20605
|
try {
|
|
20271
|
-
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;
|
|
20272
20608
|
lastReported = json;
|
|
20273
20609
|
} catch (error) {
|
|
20274
20610
|
fail("report", error);
|
|
@@ -20276,6 +20612,21 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20276
20612
|
});
|
|
20277
20613
|
return reports;
|
|
20278
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
|
+
}
|
|
20279
20630
|
function armDeadline() {
|
|
20280
20631
|
clearTimeout(deadlineTimer);
|
|
20281
20632
|
deadlineTimer = void 0;
|
|
@@ -20315,6 +20666,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20315
20666
|
controller = abort;
|
|
20316
20667
|
const startMs = now();
|
|
20317
20668
|
let outcome;
|
|
20669
|
+
let usage;
|
|
20318
20670
|
let step = "context";
|
|
20319
20671
|
try {
|
|
20320
20672
|
const received = await core.context(source);
|
|
@@ -20333,17 +20685,18 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20333
20685
|
}
|
|
20334
20686
|
const requested = [...context.observe.prs, ...context.observe.tickets];
|
|
20335
20687
|
step = "poll";
|
|
20336
|
-
const batch = await
|
|
20688
|
+
const batch = await readSource(() => adapter.poll({
|
|
20337
20689
|
...context,
|
|
20338
20690
|
signal: abort.signal
|
|
20339
20691
|
}), abort.signal);
|
|
20340
20692
|
if (aborted()) return;
|
|
20693
|
+
usage = batch?.usage;
|
|
20341
20694
|
step = "batch";
|
|
20342
20695
|
const parsed = batchSchema.safeParse({
|
|
20343
20696
|
...batch,
|
|
20344
20697
|
observedAt: iso$1(startMs)
|
|
20345
20698
|
});
|
|
20346
|
-
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;
|
|
20347
20700
|
if (!parsed.success || invalid !== void 0) {
|
|
20348
20701
|
const error = new AdapterError("transient", `Invalid batch: ${invalid ?? "fails the batch schema"}`);
|
|
20349
20702
|
fail("batch", error, parsed.error?.issues.map((issue) => ({
|
|
@@ -20377,6 +20730,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20377
20730
|
state: proposedState,
|
|
20378
20731
|
outcomes: outcomes.outcomes
|
|
20379
20732
|
});
|
|
20733
|
+
usage = void 0;
|
|
20380
20734
|
counts = outcomes.counts;
|
|
20381
20735
|
gone = outcomes.gone;
|
|
20382
20736
|
lastCompleteMs = proposedLastCompleteMs;
|
|
@@ -20394,6 +20748,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20394
20748
|
}
|
|
20395
20749
|
} catch (error) {
|
|
20396
20750
|
if (aborted()) return;
|
|
20751
|
+
if (error instanceof AdapterError && error.usage !== void 0) usage = error.usage;
|
|
20397
20752
|
fail(step, error);
|
|
20398
20753
|
if (error instanceof AdapterError && (error.kind === "auth" || error.kind === "config")) errorBlind = {
|
|
20399
20754
|
reason: error.kind,
|
|
@@ -20418,7 +20773,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20418
20773
|
failures = delay.failures;
|
|
20419
20774
|
throttledUntilMs = outcome.kind === "failed" ? throttledRetryAt(outcome.error) : void 0;
|
|
20420
20775
|
if (!options.oneShot) armDeadline();
|
|
20421
|
-
await report();
|
|
20776
|
+
await report(usage);
|
|
20422
20777
|
if (!options.oneShot) schedule(delay.delayMs);
|
|
20423
20778
|
return outcome;
|
|
20424
20779
|
}
|
|
@@ -20436,7 +20791,8 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20436
20791
|
reason: blind.reason,
|
|
20437
20792
|
message: blind.message
|
|
20438
20793
|
});
|
|
20439
|
-
|
|
20794
|
+
const pollOne = adapter.pollPr?.bind(adapter);
|
|
20795
|
+
if (pollOne === void 0) return err({
|
|
20440
20796
|
kind: "unsupported",
|
|
20441
20797
|
message: "The source does not poll one PR on demand"
|
|
20442
20798
|
});
|
|
@@ -20447,6 +20803,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20447
20803
|
message: "The source is throttled until retryAt"
|
|
20448
20804
|
});
|
|
20449
20805
|
const aborted = () => abort.signal.aborted;
|
|
20806
|
+
let usage;
|
|
20450
20807
|
let step = "context";
|
|
20451
20808
|
try {
|
|
20452
20809
|
const received = await untilAborted$1(core.context(source), abort.signal);
|
|
@@ -20455,12 +20812,13 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20455
20812
|
const feedbackCursors = received.feedbackCursors?.filter(own) ?? [];
|
|
20456
20813
|
const continuations = received.continuations?.filter(own) ?? [];
|
|
20457
20814
|
step = "poll";
|
|
20458
|
-
const batch = await
|
|
20815
|
+
const batch = await readSource(() => pollOne(ref, {
|
|
20459
20816
|
signal: abort.signal,
|
|
20460
20817
|
...feedbackCursors.length === 0 ? {} : { feedbackCursors },
|
|
20461
20818
|
...continuations.length === 0 ? {} : { continuations }
|
|
20462
20819
|
}), abort.signal);
|
|
20463
20820
|
if (aborted()) return err(stoppedError);
|
|
20821
|
+
usage = batch?.usage;
|
|
20464
20822
|
step = "batch";
|
|
20465
20823
|
const observedAt = iso$1(startMs);
|
|
20466
20824
|
const parsed = batchSchema.safeParse({
|
|
@@ -20472,7 +20830,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20472
20830
|
prs: [ref],
|
|
20473
20831
|
tickets: [],
|
|
20474
20832
|
sessions: []
|
|
20475
|
-
}, 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;
|
|
20476
20834
|
if (!parsed.success || invalid !== void 0 || value === void 0) {
|
|
20477
20835
|
const error = new AdapterError("transient", `Invalid batch: ${invalid ?? "fails the batch schema"}`);
|
|
20478
20836
|
fail("batch", error, parsed.error?.issues.map((issue) => ({
|
|
@@ -20480,6 +20838,7 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20480
20838
|
code: issue.code,
|
|
20481
20839
|
message: issue.message
|
|
20482
20840
|
})));
|
|
20841
|
+
await report(usage);
|
|
20483
20842
|
return err({
|
|
20484
20843
|
kind: "failed",
|
|
20485
20844
|
adapterKind: "transient",
|
|
@@ -20491,22 +20850,38 @@ function runSource(entry, options, runnerStartMs) {
|
|
|
20491
20850
|
if (!live()) return;
|
|
20492
20851
|
if (stopping) return err(stoppedError);
|
|
20493
20852
|
observing();
|
|
20494
|
-
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
|
+
};
|
|
20495
20860
|
await core.observe(source, {
|
|
20496
20861
|
batch: parsed.data,
|
|
20497
20862
|
effectiveComplete: false,
|
|
20498
20863
|
state: committed,
|
|
20499
20864
|
outcomes: []
|
|
20500
20865
|
});
|
|
20866
|
+
usage = void 0;
|
|
20867
|
+
counts = recoveredCounts;
|
|
20868
|
+
gone = recoveredGone;
|
|
20501
20869
|
lastReported = JSON.stringify(committed);
|
|
20502
20870
|
return ok(value);
|
|
20503
20871
|
});
|
|
20504
20872
|
reports = accepted.then(noop, noop);
|
|
20505
|
-
|
|
20873
|
+
const result = await accepted;
|
|
20874
|
+
if (usage !== void 0) {
|
|
20875
|
+
await report(usage, true);
|
|
20876
|
+
usage = void 0;
|
|
20877
|
+
}
|
|
20878
|
+
return result;
|
|
20506
20879
|
} catch (error) {
|
|
20507
20880
|
if (aborted()) return err(stoppedError);
|
|
20881
|
+
if (error instanceof AdapterError && error.usage !== void 0) usage = error.usage;
|
|
20508
20882
|
fail(step, error);
|
|
20509
20883
|
if (step === "poll" && error instanceof AdapterError && error.kind === "transient") retryable();
|
|
20884
|
+
await report(usage);
|
|
20510
20885
|
const retryAt = throttledRetryAt(error);
|
|
20511
20886
|
return err({
|
|
20512
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.
|
|
@@ -100,7 +100,9 @@ the curator's own question goes to the operator. A column explicitly assigned to
|
|
|
100
100
|
A `code` block goes to the worker to repair. A `dependency` or `external` block
|
|
101
101
|
stays with its author's role to track the dependency or outside event. Questions
|
|
102
102
|
can escalate from column orchestrator to curator to operator; other blocks
|
|
103
|
-
escalate straight to the operator.
|
|
103
|
+
escalate straight to the operator. Escalation skips a step your own project also
|
|
104
|
+
holds: a curator that also orchestrates the column escalates its column's
|
|
105
|
+
question straight to the operator. Use keyed `board escalate <block>`
|
|
104
106
|
when the current addressee cannot resolve it.
|
|
105
107
|
|
|
106
108
|
The routing configuration is `projects[].columns[].orchestrator`,
|