paperclip-github-plugin 0.15.1 → 0.15.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/README.md +19 -2
- package/dist/manifest.js +31 -4
- package/dist/worker.js +1222 -198
- package/package.json +2 -2
package/dist/worker.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// src/worker.ts
|
|
2
2
|
import { Buffer as Buffer2 } from "node:buffer";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
4
|
import { realpathSync } from "node:fs";
|
|
4
5
|
import { chmod, mkdir as mkdir2, readFile, writeFile } from "node:fs/promises";
|
|
5
6
|
import { homedir } from "node:os";
|
|
@@ -421,7 +422,8 @@ var GITHUB_AGENT_TOOLS = [
|
|
|
421
422
|
minLength: 1,
|
|
422
423
|
description: "Human-facing reply body without the AI footer. It must remain non-empty after trimming and removing any existing AI footer."
|
|
423
424
|
},
|
|
424
|
-
llmModel: llmModelProperty
|
|
425
|
+
llmModel: llmModelProperty,
|
|
426
|
+
paperclipIssueId: paperclipIssueIdProperty
|
|
425
427
|
}
|
|
426
428
|
}
|
|
427
429
|
},
|
|
@@ -437,7 +439,8 @@ var GITHUB_AGENT_TOOLS = [
|
|
|
437
439
|
threadId: {
|
|
438
440
|
type: "string",
|
|
439
441
|
description: "GitHub pull request review thread node id."
|
|
440
|
-
}
|
|
442
|
+
},
|
|
443
|
+
paperclipIssueId: paperclipIssueIdProperty
|
|
441
444
|
}
|
|
442
445
|
}
|
|
443
446
|
},
|
|
@@ -453,7 +456,8 @@ var GITHUB_AGENT_TOOLS = [
|
|
|
453
456
|
threadId: {
|
|
454
457
|
type: "string",
|
|
455
458
|
description: "GitHub pull request review thread node id."
|
|
456
|
-
}
|
|
459
|
+
},
|
|
460
|
+
paperclipIssueId: paperclipIssueIdProperty
|
|
457
461
|
}
|
|
458
462
|
}
|
|
459
463
|
},
|
|
@@ -645,6 +649,30 @@ var GITHUB_AGENT_TOOLS = [
|
|
|
645
649
|
}
|
|
646
650
|
}
|
|
647
651
|
}
|
|
652
|
+
},
|
|
653
|
+
{
|
|
654
|
+
name: "get_issue_interaction_summary",
|
|
655
|
+
displayName: "Get Issue Interaction Summary",
|
|
656
|
+
description: "Return a deterministic, sanitized interaction summary for one Paperclip issue over a maximum 30-day [from,to) UTC range.",
|
|
657
|
+
parametersSchema: {
|
|
658
|
+
type: "object",
|
|
659
|
+
additionalProperties: false,
|
|
660
|
+
required: ["paperclipIssueId"],
|
|
661
|
+
properties: {
|
|
662
|
+
paperclipIssueId: {
|
|
663
|
+
type: "string",
|
|
664
|
+
description: "Paperclip issue id in the authenticated tool run company."
|
|
665
|
+
},
|
|
666
|
+
from: {
|
|
667
|
+
type: "string",
|
|
668
|
+
description: "Optional inclusive ISO timestamp. Defaults to 30 days before to."
|
|
669
|
+
},
|
|
670
|
+
to: {
|
|
671
|
+
type: "string",
|
|
672
|
+
description: "Optional exclusive ISO timestamp. Defaults to the current time."
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
648
676
|
}
|
|
649
677
|
];
|
|
650
678
|
function getGitHubAgentToolDeclaration(name) {
|
|
@@ -997,6 +1025,228 @@ function parseRepositoryReference(repositoryInput) {
|
|
|
997
1025
|
}
|
|
998
1026
|
}
|
|
999
1027
|
|
|
1028
|
+
// src/issue-interactions.ts
|
|
1029
|
+
var ISSUE_INTERACTION_ENTITY_TYPE = "paperclip-github-plugin.issue-interaction-event";
|
|
1030
|
+
var ISSUE_INTERACTION_SCHEMA_VERSION = 1;
|
|
1031
|
+
var ISSUE_INTERACTION_MAX_WINDOW_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
1032
|
+
var ISSUE_INTERACTION_ACTIONS = /* @__PURE__ */ new Set([
|
|
1033
|
+
"status_decision",
|
|
1034
|
+
"add_issue_comment",
|
|
1035
|
+
"add_pull_request_to_project",
|
|
1036
|
+
"assign_to_current_user",
|
|
1037
|
+
"create_pull_request",
|
|
1038
|
+
"link_github_item",
|
|
1039
|
+
"reply_to_review_thread",
|
|
1040
|
+
"request_pull_request_reviewers",
|
|
1041
|
+
"resolve_review_thread",
|
|
1042
|
+
"unresolve_review_thread",
|
|
1043
|
+
"update_issue",
|
|
1044
|
+
"update_pull_request",
|
|
1045
|
+
"upload_pull_request_asset"
|
|
1046
|
+
]);
|
|
1047
|
+
var ISSUE_INTERACTION_CATEGORIES = /* @__PURE__ */ new Set(["sync", "github_write", "comment", "paperclip_link"]);
|
|
1048
|
+
var ISSUE_INTERACTION_REASON_CODES = /* @__PURE__ */ new Set([
|
|
1049
|
+
"trusted_comment",
|
|
1050
|
+
"pr_ready",
|
|
1051
|
+
"pr_merge_conflict",
|
|
1052
|
+
"pr_ci_failed",
|
|
1053
|
+
"pr_ci_unfinished",
|
|
1054
|
+
"pr_mergeability_unknown",
|
|
1055
|
+
"issue_closed_completed",
|
|
1056
|
+
"issue_closed_not_planned",
|
|
1057
|
+
"issue_closed_duplicate",
|
|
1058
|
+
"issue_ready_for_triage",
|
|
1059
|
+
"github_sync_status_decision"
|
|
1060
|
+
]);
|
|
1061
|
+
var ISSUE_INTERACTION_MAX_SCAN_ROWS = 5e3;
|
|
1062
|
+
var ISSUE_INTERACTION_MAX_REPEATED_ACTIONS = 10;
|
|
1063
|
+
var SOURCES = /* @__PURE__ */ new Set(["agent_tool", "sync", "api_route", "operator_action", "backfill"]);
|
|
1064
|
+
var OUTCOMES = /* @__PURE__ */ new Set(["observed", "changed", "noop", "failed"]);
|
|
1065
|
+
var SAFE_TOKEN = /^[a-zA-Z0-9_.:/#-]{1,256}$/;
|
|
1066
|
+
function safeHttpUrl(value) {
|
|
1067
|
+
if (typeof value !== "string" || value.length > 512) return void 0;
|
|
1068
|
+
try {
|
|
1069
|
+
const parsed = new URL(value);
|
|
1070
|
+
if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password) return void 0;
|
|
1071
|
+
parsed.search = "";
|
|
1072
|
+
parsed.hash = "";
|
|
1073
|
+
return parsed.href;
|
|
1074
|
+
} catch {
|
|
1075
|
+
return void 0;
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
function requiredString(value, label) {
|
|
1079
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
1080
|
+
throw new Error(`${label} is required.`);
|
|
1081
|
+
}
|
|
1082
|
+
return value.trim();
|
|
1083
|
+
}
|
|
1084
|
+
function safeOptionalString(value) {
|
|
1085
|
+
if (typeof value !== "string") return void 0;
|
|
1086
|
+
const trimmed = value.trim();
|
|
1087
|
+
return trimmed && SAFE_TOKEN.test(trimmed) ? trimmed : void 0;
|
|
1088
|
+
}
|
|
1089
|
+
function isoTimestamp(value, label) {
|
|
1090
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
1091
|
+
throw new Error(`${label} must be a valid ISO timestamp.`);
|
|
1092
|
+
}
|
|
1093
|
+
const parsed = Date.parse(value);
|
|
1094
|
+
if (!Number.isFinite(parsed)) {
|
|
1095
|
+
throw new Error(`${label} must be a valid ISO timestamp.`);
|
|
1096
|
+
}
|
|
1097
|
+
return new Date(parsed).toISOString();
|
|
1098
|
+
}
|
|
1099
|
+
function sanitizeIssueInteractionEvent(value) {
|
|
1100
|
+
const source = SOURCES.has(value.source) ? value.source : void 0;
|
|
1101
|
+
const outcome = OUTCOMES.has(value.outcome) ? value.outcome : void 0;
|
|
1102
|
+
const category = ISSUE_INTERACTION_CATEGORIES.has(value.category) ? value.category : void 0;
|
|
1103
|
+
const action = ISSUE_INTERACTION_ACTIONS.has(value.action) ? value.action : void 0;
|
|
1104
|
+
if (!source || !outcome || !category || !action) throw new Error("Interaction source, outcome, category, and action must be allowlisted.");
|
|
1105
|
+
const actor = value.actor ? {
|
|
1106
|
+
agentId: safeOptionalString(value.actor.agentId),
|
|
1107
|
+
runId: safeOptionalString(value.actor.runId),
|
|
1108
|
+
remoteLogin: safeOptionalString(value.actor.remoteLogin),
|
|
1109
|
+
llmModel: safeOptionalString(value.actor.llmModel)
|
|
1110
|
+
} : void 0;
|
|
1111
|
+
const remote = value.remote ? {
|
|
1112
|
+
repositoryUrl: safeHttpUrl(value.remote.repositoryUrl),
|
|
1113
|
+
kind: value.remote.kind === "issue" || value.remote.kind === "pull_request" ? value.remote.kind : void 0,
|
|
1114
|
+
number: Number.isSafeInteger(value.remote.number) && (value.remote.number ?? 0) > 0 ? value.remote.number : void 0,
|
|
1115
|
+
url: safeHttpUrl(value.remote.url),
|
|
1116
|
+
externalEventId: safeOptionalString(value.remote.externalEventId)
|
|
1117
|
+
} : void 0;
|
|
1118
|
+
const transition = value.transition ? {
|
|
1119
|
+
from: safeOptionalString(value.transition.from),
|
|
1120
|
+
to: safeOptionalString(value.transition.to),
|
|
1121
|
+
reasonCode: typeof value.transition.reasonCode === "string" && ISSUE_INTERACTION_REASON_CODES.has(value.transition.reasonCode) ? value.transition.reasonCode : void 0
|
|
1122
|
+
} : void 0;
|
|
1123
|
+
return {
|
|
1124
|
+
schemaVersion: ISSUE_INTERACTION_SCHEMA_VERSION,
|
|
1125
|
+
companyId: requiredString(value.companyId, "companyId"),
|
|
1126
|
+
paperclipIssueId: requiredString(value.paperclipIssueId, "paperclipIssueId"),
|
|
1127
|
+
occurredAt: isoTimestamp(value.occurredAt, "occurredAt"),
|
|
1128
|
+
category,
|
|
1129
|
+
action,
|
|
1130
|
+
source,
|
|
1131
|
+
...actor && Object.values(actor).some(Boolean) ? { actor } : {},
|
|
1132
|
+
...remote && Object.values(remote).some((entry) => entry !== void 0) ? { remote } : {},
|
|
1133
|
+
...transition && Object.values(transition).some(Boolean) ? { transition } : {},
|
|
1134
|
+
outcome,
|
|
1135
|
+
...Number.isFinite(value.durationMs) && (value.durationMs ?? -1) >= 0 ? { durationMs: Math.round(value.durationMs) } : {},
|
|
1136
|
+
dedupeKey: requiredString(value.dedupeKey, "dedupeKey").slice(0, 256)
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
function parseIssueInteractionRange(input, now = /* @__PURE__ */ new Date()) {
|
|
1140
|
+
const nowMs = now.getTime();
|
|
1141
|
+
const to = input.to === void 0 ? new Date(nowMs) : new Date(isoTimestamp(input.to, "to"));
|
|
1142
|
+
const from = input.from === void 0 ? new Date(to.getTime() - ISSUE_INTERACTION_MAX_WINDOW_MS) : new Date(isoTimestamp(input.from, "from"));
|
|
1143
|
+
if (from.getTime() >= to.getTime()) throw new Error("from must be before to.");
|
|
1144
|
+
if (to.getTime() > nowMs) throw new Error("to must not be in the future.");
|
|
1145
|
+
if (to.getTime() - from.getTime() > ISSUE_INTERACTION_MAX_WINDOW_MS) {
|
|
1146
|
+
throw new Error("Interaction summaries are limited to 30 days.");
|
|
1147
|
+
}
|
|
1148
|
+
return { from: from.toISOString(), to: to.toISOString() };
|
|
1149
|
+
}
|
|
1150
|
+
function buildIssueInteractionSummary(input) {
|
|
1151
|
+
if (input.events.length > ISSUE_INTERACTION_MAX_SCAN_ROWS) {
|
|
1152
|
+
throw new Error(`Interaction summary input exceeds ${ISSUE_INTERACTION_MAX_SCAN_ROWS} events.`);
|
|
1153
|
+
}
|
|
1154
|
+
const fromMs = Date.parse(input.range.from);
|
|
1155
|
+
const toMs = Date.parse(input.range.to);
|
|
1156
|
+
const sanitized = input.events.map(sanitizeIssueInteractionEvent);
|
|
1157
|
+
for (const entry of sanitized) {
|
|
1158
|
+
if (entry.companyId !== input.companyId || entry.paperclipIssueId !== input.paperclipIssueId) {
|
|
1159
|
+
throw new Error("Interaction event scope does not match the requested company and issue scope.");
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
const events = sanitized.filter((entry) => {
|
|
1163
|
+
const timestamp = Date.parse(entry.occurredAt);
|
|
1164
|
+
return timestamp >= fromMs && timestamp < toMs;
|
|
1165
|
+
}).sort((left, right) => left.occurredAt.localeCompare(right.occurredAt) || left.dedupeKey.localeCompare(right.dedupeKey));
|
|
1166
|
+
const resultDedupeBases = new Set(events.filter((entry) => /:result(?::(?:changed|noop|failed))?$/.test(entry.dedupeKey)).map((entry) => entry.dedupeKey.replace(/:result(?::(?:changed|noop|failed))?$/, "")));
|
|
1167
|
+
const uncertainAttempts = events.filter((entry) => entry.outcome === "observed" && entry.dedupeKey.endsWith(":intent") && !resultDedupeBases.has(entry.dedupeKey.slice(0, -":intent".length)));
|
|
1168
|
+
const runIds = new Set(events.map((entry) => entry.actor?.runId).filter((value) => Boolean(value)));
|
|
1169
|
+
const actionCounts = /* @__PURE__ */ new Map();
|
|
1170
|
+
for (const entry of events.filter((candidate) => candidate.source === "agent_tool" && candidate.outcome !== "observed")) {
|
|
1171
|
+
actionCounts.set(entry.action, (actionCounts.get(entry.action) ?? 0) + 1);
|
|
1172
|
+
}
|
|
1173
|
+
const transitions = events.filter((entry) => entry.outcome !== "observed" && entry.transition?.from && entry.transition?.to && entry.transition.from !== entry.transition.to).map((entry) => ({
|
|
1174
|
+
occurredAt: entry.occurredAt,
|
|
1175
|
+
from: entry.transition.from,
|
|
1176
|
+
to: entry.transition.to,
|
|
1177
|
+
...entry.transition.reasonCode ? { reasonCode: entry.transition.reasonCode } : {},
|
|
1178
|
+
outcome: entry.outcome
|
|
1179
|
+
}));
|
|
1180
|
+
let statusReversals = 0;
|
|
1181
|
+
for (let index = 1; index < transitions.length; index += 1) {
|
|
1182
|
+
const previous = transitions[index - 1];
|
|
1183
|
+
const current = transitions[index];
|
|
1184
|
+
if (previous.from === current.to && previous.to === current.from) statusReversals += 1;
|
|
1185
|
+
}
|
|
1186
|
+
const ledgerStartedAt = input.ledgerStartedAt ? isoTimestamp(input.ledgerStartedAt, "ledgerStartedAt") : sanitized.map((entry) => entry.occurredAt).sort()[0] ?? null;
|
|
1187
|
+
const ledgerWindowComplete = ledgerStartedAt !== null && Date.parse(ledgerStartedAt) <= fromMs;
|
|
1188
|
+
const integrity = {
|
|
1189
|
+
malformedRows: input.integrity?.malformedRows ?? 0,
|
|
1190
|
+
conflictingKeys: input.integrity?.conflictingKeys ?? 0,
|
|
1191
|
+
scanTruncated: input.integrity?.scanTruncated === true,
|
|
1192
|
+
scannedRows: input.integrity?.scannedRows ?? sanitized.length
|
|
1193
|
+
};
|
|
1194
|
+
const ledgerIntegrityComplete = integrity.malformedRows === 0 && integrity.conflictingKeys === 0 && !integrity.scanTruncated;
|
|
1195
|
+
const MAX_TRANSITIONS = 100;
|
|
1196
|
+
const visibleTransitions = transitions.slice(-MAX_TRANSITIONS);
|
|
1197
|
+
const repeatedActions = [...actionCounts.entries()].filter(([, count]) => count > 1).map(([action, count]) => ({ action, count })).sort((left, right) => right.count - left.count || left.action.localeCompare(right.action));
|
|
1198
|
+
const visibleRepeatedActions = repeatedActions.slice(0, ISSUE_INTERACTION_MAX_REPEATED_ACTIONS);
|
|
1199
|
+
return {
|
|
1200
|
+
schemaVersion: ISSUE_INTERACTION_SCHEMA_VERSION,
|
|
1201
|
+
companyId: input.companyId,
|
|
1202
|
+
paperclipIssueId: input.paperclipIssueId,
|
|
1203
|
+
range: input.range,
|
|
1204
|
+
coverage: {
|
|
1205
|
+
overallComplete: false,
|
|
1206
|
+
dimensions: {
|
|
1207
|
+
pluginLedger: {
|
|
1208
|
+
startedAt: ledgerStartedAt,
|
|
1209
|
+
complete: ledgerWindowComplete && ledgerIntegrityComplete,
|
|
1210
|
+
historicalBackfill: false,
|
|
1211
|
+
integrity
|
|
1212
|
+
},
|
|
1213
|
+
paperclipCore: { included: false, complete: false },
|
|
1214
|
+
externalGitHub: { included: false, complete: false }
|
|
1215
|
+
}
|
|
1216
|
+
},
|
|
1217
|
+
counts: {
|
|
1218
|
+
events: events.length,
|
|
1219
|
+
runs: runIds.size,
|
|
1220
|
+
comments: events.filter((entry) => entry.outcome !== "observed" && (entry.action.includes("comment") || entry.action.includes("reply"))).length,
|
|
1221
|
+
mutatingToolAttempts: events.filter((entry) => entry.source === "agent_tool" && entry.outcome !== "observed").length,
|
|
1222
|
+
remoteWrites: events.filter((entry) => entry.source === "agent_tool" && entry.category !== "paperclip_link" && entry.outcome === "changed").length,
|
|
1223
|
+
statusDecisions: events.filter((entry) => entry.action === "status_decision" && entry.outcome !== "observed").length,
|
|
1224
|
+
statusTransitions: transitions.length,
|
|
1225
|
+
failures: events.filter((entry) => entry.outcome === "failed").length,
|
|
1226
|
+
noops: events.filter((entry) => entry.outcome === "noop").length,
|
|
1227
|
+
uncertainAttempts: uncertainAttempts.length
|
|
1228
|
+
},
|
|
1229
|
+
transitions: visibleTransitions,
|
|
1230
|
+
truncation: {
|
|
1231
|
+
transitions: transitions.length > visibleTransitions.length,
|
|
1232
|
+
returnedTransitions: visibleTransitions.length,
|
|
1233
|
+
repeatedActions: repeatedActions.length > visibleRepeatedActions.length,
|
|
1234
|
+
returnedRepeatedActions: visibleRepeatedActions.length,
|
|
1235
|
+
ledgerScan: integrity.scanTruncated
|
|
1236
|
+
},
|
|
1237
|
+
signals: {
|
|
1238
|
+
repeatedActions: visibleRepeatedActions,
|
|
1239
|
+
statusReversals,
|
|
1240
|
+
failedActions: events.filter((entry) => entry.outcome === "failed").length,
|
|
1241
|
+
noopStatusDecisions: events.filter((entry) => entry.action === "status_decision" && entry.outcome === "noop").length
|
|
1242
|
+
},
|
|
1243
|
+
limitations: [
|
|
1244
|
+
"Only events captured after ledger instrumentation are included; no historical backfill is attempted.",
|
|
1245
|
+
"GitHub activity performed outside GitHub Sync is not included unless a captured plugin path records it."
|
|
1246
|
+
]
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1000
1250
|
// src/kpi-contract.ts
|
|
1001
1251
|
var GITHUB_SYNC_PLUGIN_ID = "paperclip-github-plugin";
|
|
1002
1252
|
var COMPANY_METRIC_API_ROUTE_KEY = "record-company-metric-event";
|
|
@@ -1053,6 +1303,10 @@ var IMPORT_REGISTRY_SCOPE = {
|
|
|
1053
1303
|
scopeKind: "instance",
|
|
1054
1304
|
stateKey: "paperclip-github-plugin-import-registry"
|
|
1055
1305
|
};
|
|
1306
|
+
var REMOTE_ACTION_REGISTRY_SCOPE = {
|
|
1307
|
+
scopeKind: "instance",
|
|
1308
|
+
stateKey: "paperclip-github-plugin-remote-action-registry"
|
|
1309
|
+
};
|
|
1056
1310
|
var COMPANY_KPI_SCOPE = {
|
|
1057
1311
|
scopeKind: "instance",
|
|
1058
1312
|
stateKey: "paperclip-github-plugin-company-kpis"
|
|
@@ -1085,7 +1339,9 @@ var INTERRUPTED_SYNC_ACTION = "Run GitHub sync again. If it stops on the same re
|
|
|
1085
1339
|
var SYNC_PROGRESS_PERSIST_INTERVAL_MS = 250;
|
|
1086
1340
|
var MAX_SYNC_FAILURE_LOG_ENTRIES = 25;
|
|
1087
1341
|
var GITHUB_SECONDARY_RATE_LIMIT_FALLBACK_MS = 6e4;
|
|
1088
|
-
var IMPORTED_ISSUE_WAKEUP_CONCURRENCY =
|
|
1342
|
+
var IMPORTED_ISSUE_WAKEUP_CONCURRENCY = 1;
|
|
1343
|
+
var MAX_REMOTE_ACTION_REGISTRY_RECORDS = 256;
|
|
1344
|
+
var MAX_PULL_REQUEST_COMMENT_WATERMARKS = 128;
|
|
1089
1345
|
var COMPANY_KPI_CHART_WINDOW_DAYS = 14;
|
|
1090
1346
|
var COMPANY_KPI_COMPARISON_WINDOW_DAYS = 30;
|
|
1091
1347
|
var MAX_COMPANY_BACKLOG_SNAPSHOTS = 180;
|
|
@@ -1218,6 +1474,11 @@ var SyncCancellationError = class extends Error {
|
|
|
1218
1474
|
this.requestedAt = requestedAt;
|
|
1219
1475
|
}
|
|
1220
1476
|
};
|
|
1477
|
+
function canonicalizeGitHubPullRequestCommentCounts(records) {
|
|
1478
|
+
return [...records].sort(
|
|
1479
|
+
(left, right) => left.repositoryUrl.localeCompare(right.repositoryUrl) || left.number - right.number
|
|
1480
|
+
);
|
|
1481
|
+
}
|
|
1221
1482
|
var SUCCESSFUL_CHECK_RUN_CONCLUSIONS = /* @__PURE__ */ new Set(["SUCCESS", "NEUTRAL", "SKIPPED"]);
|
|
1222
1483
|
var FAILED_CHECK_RUN_CONCLUSIONS = /* @__PURE__ */ new Set([
|
|
1223
1484
|
"ACTION_REQUIRED",
|
|
@@ -1278,6 +1539,7 @@ var GITHUB_PULL_REQUEST_CI_CONTEXTS_QUERY = `
|
|
|
1278
1539
|
query GitHubPullRequestCiContexts($owner: String!, $repo: String!, $pullRequestNumber: Int!, $after: String) {
|
|
1279
1540
|
repository(owner: $owner, name: $repo) {
|
|
1280
1541
|
pullRequest(number: $pullRequestNumber) {
|
|
1542
|
+
headRefOid
|
|
1281
1543
|
mergeable
|
|
1282
1544
|
mergeStateStatus
|
|
1283
1545
|
reviewDecision
|
|
@@ -1344,6 +1606,7 @@ var GITHUB_REPOSITORY_OPEN_PULL_REQUEST_STATUSES_QUERY = `
|
|
|
1344
1606
|
}
|
|
1345
1607
|
nodes {
|
|
1346
1608
|
number
|
|
1609
|
+
headRefOid
|
|
1347
1610
|
mergeable
|
|
1348
1611
|
mergeStateStatus
|
|
1349
1612
|
reviewDecision
|
|
@@ -5071,6 +5334,8 @@ function normalizeImportRegistry(value) {
|
|
|
5071
5334
|
const linkedPullRequestCommentCounts = normalizeGitHubPullRequestCommentCountRecords(
|
|
5072
5335
|
record.linkedPullRequestCommentCounts
|
|
5073
5336
|
);
|
|
5337
|
+
const remoteActionFingerprint = typeof record.remoteActionFingerprint === "string" && /^[a-f0-9]{64}$/.test(record.remoteActionFingerprint) ? record.remoteActionFingerprint : void 0;
|
|
5338
|
+
const pendingRemoteActionWake = normalizePendingRemoteActionWake(record.pendingRemoteActionWake);
|
|
5074
5339
|
if (!mappingId || Number.isNaN(githubIssueId) || !paperclipIssueId || !importedAt) {
|
|
5075
5340
|
return null;
|
|
5076
5341
|
}
|
|
@@ -5085,10 +5350,66 @@ function normalizeImportRegistry(value) {
|
|
|
5085
5350
|
...companyId ? { companyId } : {},
|
|
5086
5351
|
...lastSeenCommentCount !== void 0 ? { lastSeenCommentCount } : {},
|
|
5087
5352
|
...lastSeenGitHubState ? { lastSeenGitHubState } : {},
|
|
5088
|
-
...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : {}
|
|
5353
|
+
...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : {},
|
|
5354
|
+
...remoteActionFingerprint ? { remoteActionFingerprint } : {},
|
|
5355
|
+
...pendingRemoteActionWake ? { pendingRemoteActionWake } : {}
|
|
5089
5356
|
};
|
|
5090
5357
|
}).filter((entry) => entry !== null);
|
|
5091
5358
|
}
|
|
5359
|
+
function normalizePendingRemoteActionWake(value) {
|
|
5360
|
+
if (!value || typeof value !== "object") return void 0;
|
|
5361
|
+
const record = value;
|
|
5362
|
+
const fingerprint = typeof record.fingerprint === "string" && /^[a-f0-9]{64}$/.test(record.fingerprint) ? record.fingerprint : void 0;
|
|
5363
|
+
const assigneeAgentId = normalizeOptionalString2(record.assigneeAgentId);
|
|
5364
|
+
const reason = normalizeOptionalString2(record.reason);
|
|
5365
|
+
const mutation = record.mutation === "import" ? "import" : "status_transition";
|
|
5366
|
+
const previousStatus = normalizePaperclipIssueStatus(record.previousStatus);
|
|
5367
|
+
const nextStatus = normalizePaperclipIssueStatus(record.nextStatus);
|
|
5368
|
+
if (!fingerprint || !assigneeAgentId || !reason) return void 0;
|
|
5369
|
+
return {
|
|
5370
|
+
fingerprint,
|
|
5371
|
+
assigneeAgentId,
|
|
5372
|
+
reason: reason.slice(0, 500),
|
|
5373
|
+
mutation,
|
|
5374
|
+
...previousStatus ? { previousStatus } : {},
|
|
5375
|
+
...nextStatus ? { nextStatus } : {}
|
|
5376
|
+
};
|
|
5377
|
+
}
|
|
5378
|
+
function normalizeRemoteActionRegistry(value) {
|
|
5379
|
+
if (!Array.isArray(value)) return [];
|
|
5380
|
+
const recordsByKey = /* @__PURE__ */ new Map();
|
|
5381
|
+
for (const entry of value) {
|
|
5382
|
+
if (!entry || typeof entry !== "object") continue;
|
|
5383
|
+
const record = entry;
|
|
5384
|
+
const key = normalizeOptionalString2(record.key);
|
|
5385
|
+
if (!key || key.length > 500) continue;
|
|
5386
|
+
const fingerprint = typeof record.fingerprint === "string" && /^[a-f0-9]{64}$/.test(record.fingerprint) ? record.fingerprint : void 0;
|
|
5387
|
+
const pendingWake = normalizePendingRemoteActionWake(record.pendingWake);
|
|
5388
|
+
const linkedPullRequestCommentCounts = normalizeGitHubPullRequestCommentCountRecords(
|
|
5389
|
+
record.linkedPullRequestCommentCounts
|
|
5390
|
+
);
|
|
5391
|
+
const previous = recordsByKey.get(key);
|
|
5392
|
+
recordsByKey.set(key, {
|
|
5393
|
+
key,
|
|
5394
|
+
...fingerprint ? { fingerprint } : previous?.fingerprint ? { fingerprint: previous.fingerprint } : {},
|
|
5395
|
+
...pendingWake ? { pendingWake } : previous?.pendingWake ? { pendingWake: previous.pendingWake } : {},
|
|
5396
|
+
...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : previous?.linkedPullRequestCommentCounts ? { linkedPullRequestCommentCounts: previous.linkedPullRequestCommentCounts } : {}
|
|
5397
|
+
});
|
|
5398
|
+
}
|
|
5399
|
+
const records = [...recordsByKey.values()];
|
|
5400
|
+
const pendingRecords = records.filter((record) => record.pendingWake).sort((left, right) => left.key.localeCompare(right.key));
|
|
5401
|
+
if (pendingRecords.length > MAX_REMOTE_ACTION_REGISTRY_RECORDS) {
|
|
5402
|
+
throw new Error(
|
|
5403
|
+
`Remote action registry contains ${pendingRecords.length} pending wakes; maximum is ${MAX_REMOTE_ACTION_REGISTRY_RECORDS}`
|
|
5404
|
+
);
|
|
5405
|
+
}
|
|
5406
|
+
const retainedKeys = new Set(pendingRecords.map((record) => record.key));
|
|
5407
|
+
for (const record of records.sort((left, right) => left.key.localeCompare(right.key))) {
|
|
5408
|
+
if (retainedKeys.size >= MAX_REMOTE_ACTION_REGISTRY_RECORDS) break;
|
|
5409
|
+
retainedKeys.add(record.key);
|
|
5410
|
+
}
|
|
5411
|
+
return records.filter((record) => retainedKeys.has(record.key)).sort((left, right) => left.key.localeCompare(right.key));
|
|
5412
|
+
}
|
|
5092
5413
|
function normalizeExternalGitHubLinkCompanyIndex(value) {
|
|
5093
5414
|
const rawCompanyIds = Array.isArray(value) ? value : value && typeof value === "object" && Array.isArray(value.companyIds) ? value.companyIds : [];
|
|
5094
5415
|
const companyIds = [
|
|
@@ -5990,7 +6311,7 @@ function isHealthyMaintainerWaitTransition(params) {
|
|
|
5990
6311
|
return nextStatus === "in_review" && (currentStatus === "done" || currentStatus === "in_review") && isClearableMaintainerWaitExecutionState(syncContext.executionState);
|
|
5991
6312
|
}
|
|
5992
6313
|
function isClearableMaintainerWaitExecutionState(executionState) {
|
|
5993
|
-
if (executionState === null) {
|
|
6314
|
+
if (executionState === null || executionState.status === "completed") {
|
|
5994
6315
|
return true;
|
|
5995
6316
|
}
|
|
5996
6317
|
if (executionState.currentParticipant !== null || executionState.returnAssignee !== null || executionState.currentStageId !== null || executionState.currentStageIndex !== null || executionState.currentStageType !== null || executionState.completedStageIds.length > 0 || executionState.lastDecisionId || executionState.lastDecisionOutcome) {
|
|
@@ -6233,9 +6554,12 @@ function resolvePaperclipPullRequestIssueStatus(params) {
|
|
|
6233
6554
|
});
|
|
6234
6555
|
}
|
|
6235
6556
|
function resolvePaperclipDirectPullRequestIssueStatus(params) {
|
|
6236
|
-
const { currentStatus, pullRequests, hasExecutorHandoffTarget } = params;
|
|
6557
|
+
const { currentStatus, pullRequests, hasExecutorHandoffTarget, hasTrustedNewComment } = params;
|
|
6237
6558
|
const openPullRequests = pullRequests.map((entry) => entry.pullRequest).filter((pullRequest) => Boolean(pullRequest));
|
|
6238
6559
|
if (openPullRequests.length > 0) {
|
|
6560
|
+
if (hasTrustedNewComment) {
|
|
6561
|
+
return currentStatus === "backlog" ? "backlog" : hasExecutorHandoffTarget ? "in_progress" : "todo";
|
|
6562
|
+
}
|
|
6239
6563
|
if (shouldPreserveBlockedExternalPullRequestWait({
|
|
6240
6564
|
currentStatus,
|
|
6241
6565
|
linkedPullRequests: openPullRequests
|
|
@@ -6457,6 +6781,7 @@ function tryBuildGitHubPullRequestStatusSnapshotFromBatchNode(node, repository)
|
|
|
6457
6781
|
return {
|
|
6458
6782
|
number: node.number,
|
|
6459
6783
|
repositoryUrl: repository.url,
|
|
6784
|
+
...typeof node.headRefOid === "string" && node.headRefOid.trim() ? { headSha: node.headRefOid.trim().toLowerCase() } : {},
|
|
6460
6785
|
hasUnresolvedReviewThreads: reviewThreadSummary.unresolvedReviewThreads > 0,
|
|
6461
6786
|
ciState,
|
|
6462
6787
|
mergeability: normalizeGitHubPullRequestMergeability(node.mergeable),
|
|
@@ -6516,6 +6841,7 @@ async function getGitHubPullRequestCiState(octokit, repository, pullRequestNumbe
|
|
|
6516
6841
|
}
|
|
6517
6842
|
async function getGitHubPullRequestCiSnapshot(octokit, repository, pullRequestNumber) {
|
|
6518
6843
|
const contexts = [];
|
|
6844
|
+
let headSha;
|
|
6519
6845
|
let mergeability = "unknown";
|
|
6520
6846
|
let mergeStateStatus = "unknown";
|
|
6521
6847
|
let reviewDecision = "unknown";
|
|
@@ -6530,6 +6856,10 @@ async function getGitHubPullRequestCiSnapshot(octokit, repository, pullRequestNu
|
|
|
6530
6856
|
mergeability = normalizeGitHubPullRequestMergeability(response.repository?.pullRequest?.mergeable);
|
|
6531
6857
|
mergeStateStatus = normalizeGitHubPullRequestMergeStateStatus(response.repository?.pullRequest?.mergeStateStatus);
|
|
6532
6858
|
reviewDecision = normalizeGitHubPullRequestReviewDecision(response.repository?.pullRequest?.reviewDecision);
|
|
6859
|
+
const responseHeadSha = response.repository?.pullRequest?.headRefOid;
|
|
6860
|
+
if (typeof responseHeadSha === "string" && responseHeadSha.trim()) {
|
|
6861
|
+
headSha = responseHeadSha.trim().toLowerCase();
|
|
6862
|
+
}
|
|
6533
6863
|
const connection = response.repository?.pullRequest?.statusCheckRollup?.contexts;
|
|
6534
6864
|
const nodes = connection?.nodes ?? [];
|
|
6535
6865
|
for (const node of nodes) {
|
|
@@ -6554,6 +6884,7 @@ async function getGitHubPullRequestCiSnapshot(octokit, repository, pullRequestNu
|
|
|
6554
6884
|
after = getPageCursor(connection?.pageInfo);
|
|
6555
6885
|
} while (after);
|
|
6556
6886
|
return {
|
|
6887
|
+
...headSha ? { headSha } : {},
|
|
6557
6888
|
ciState: classifyGitHubPullRequestCiState(contexts),
|
|
6558
6889
|
mergeability,
|
|
6559
6890
|
mergeStateStatus,
|
|
@@ -6603,6 +6934,7 @@ async function getGitHubPullRequestStatusSnapshot(octokit, repository, pullReque
|
|
|
6603
6934
|
return cacheGitHubPullRequestStatusSnapshot(repository, {
|
|
6604
6935
|
number: pullRequestNumber,
|
|
6605
6936
|
repositoryUrl: repository.url,
|
|
6937
|
+
..."headSha" in ciSnapshot && ciSnapshot.headSha ? { headSha: ciSnapshot.headSha } : {},
|
|
6606
6938
|
hasUnresolvedReviewThreads: reviewThreadSummary.unresolvedReviewThreads > 0,
|
|
6607
6939
|
ciState: ciSnapshot.ciState,
|
|
6608
6940
|
mergeability: ciSnapshot.mergeability,
|
|
@@ -6940,7 +7272,7 @@ async function hasTrustedNewLinkedPullRequestComments(params) {
|
|
|
6940
7272
|
octokit: params.octokit,
|
|
6941
7273
|
repository: pullRequestRepository,
|
|
6942
7274
|
comments: newTopLevelComments,
|
|
6943
|
-
originalPosterLogin: params.
|
|
7275
|
+
originalPosterLogin: params.originalPosterLogin,
|
|
6944
7276
|
maintainerCache: params.maintainerCache
|
|
6945
7277
|
})) {
|
|
6946
7278
|
return true;
|
|
@@ -6958,7 +7290,7 @@ async function hasTrustedNewLinkedPullRequestComments(params) {
|
|
|
6958
7290
|
octokit: params.octokit,
|
|
6959
7291
|
repository: pullRequestRepository,
|
|
6960
7292
|
comments: newReviewComments,
|
|
6961
|
-
originalPosterLogin: params.
|
|
7293
|
+
originalPosterLogin: params.originalPosterLogin,
|
|
6962
7294
|
maintainerCache: params.maintainerCache
|
|
6963
7295
|
})) {
|
|
6964
7296
|
return true;
|
|
@@ -7137,7 +7469,7 @@ function normalizeGitHubPullRequestCommentCountRecords(value) {
|
|
|
7137
7469
|
return repositoryComparison;
|
|
7138
7470
|
}
|
|
7139
7471
|
return left.number - right.number;
|
|
7140
|
-
});
|
|
7472
|
+
}).slice(0, MAX_PULL_REQUEST_COMMENT_WATERMARKS);
|
|
7141
7473
|
}
|
|
7142
7474
|
function normalizeLinkedPullRequestReferences(values, fallbackRepositoryUrl) {
|
|
7143
7475
|
const references = [];
|
|
@@ -8491,19 +8823,15 @@ async function wakePaperclipIssueAssignee(ctx, params) {
|
|
|
8491
8823
|
await ctx.issues.requestWakeup(params.paperclipIssueId, params.companyId, {
|
|
8492
8824
|
reason: params.reason,
|
|
8493
8825
|
contextSource: `github-sync.${params.mutation}`,
|
|
8494
|
-
...params.mutation === "import" ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId].join(":") } : {}
|
|
8826
|
+
...params.actionFingerprint ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId, params.actionFingerprint].join(":") } : params.mutation === "import" ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId].join(":") } : {}
|
|
8495
8827
|
});
|
|
8496
8828
|
return;
|
|
8497
8829
|
} catch (error) {
|
|
8498
8830
|
if (!params.paperclipApiBaseUrl) {
|
|
8499
|
-
|
|
8500
|
-
|
|
8501
|
-
|
|
8502
|
-
|
|
8503
|
-
mutation: params.mutation,
|
|
8504
|
-
error: error instanceof Error ? error.message : String(error)
|
|
8505
|
-
});
|
|
8506
|
-
return;
|
|
8831
|
+
throw new Error(
|
|
8832
|
+
`GitHub sync could not wake the assignee for Paperclip issue ${params.paperclipIssueId} through the SDK: ${getErrorMessage(error)}`,
|
|
8833
|
+
{ cause: error }
|
|
8834
|
+
);
|
|
8507
8835
|
}
|
|
8508
8836
|
ctx.logger.warn("GitHub sync could not wake the assignee through the SDK. Falling back to the local Paperclip API.", {
|
|
8509
8837
|
issueId: params.paperclipIssueId,
|
|
@@ -8515,7 +8843,7 @@ async function wakePaperclipIssueAssignee(ctx, params) {
|
|
|
8515
8843
|
}
|
|
8516
8844
|
}
|
|
8517
8845
|
if (!params.paperclipApiBaseUrl) {
|
|
8518
|
-
|
|
8846
|
+
throw new Error(`GitHub sync has no available wakeup transport for Paperclip issue ${params.paperclipIssueId}.`);
|
|
8519
8847
|
}
|
|
8520
8848
|
try {
|
|
8521
8849
|
const response = await fetchPaperclipApi(
|
|
@@ -8530,6 +8858,7 @@ async function wakePaperclipIssueAssignee(ctx, params) {
|
|
|
8530
8858
|
source: "assignment",
|
|
8531
8859
|
triggerDetail: "system",
|
|
8532
8860
|
reason: params.reason,
|
|
8861
|
+
...params.actionFingerprint ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId, params.actionFingerprint].join(":") } : params.mutation === "import" ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId].join(":") } : {},
|
|
8533
8862
|
payload: {
|
|
8534
8863
|
issueId: params.paperclipIssueId,
|
|
8535
8864
|
mutation: params.mutation,
|
|
@@ -8546,14 +8875,10 @@ async function wakePaperclipIssueAssignee(ctx, params) {
|
|
|
8546
8875
|
throw new Error(`Wakeup request failed with status ${response.status}.`);
|
|
8547
8876
|
}
|
|
8548
8877
|
} catch (error) {
|
|
8549
|
-
|
|
8550
|
-
|
|
8551
|
-
|
|
8552
|
-
|
|
8553
|
-
paperclipApiBaseUrl: params.paperclipApiBaseUrl,
|
|
8554
|
-
mutation: params.mutation,
|
|
8555
|
-
error: error instanceof Error ? error.message : String(error)
|
|
8556
|
-
});
|
|
8878
|
+
throw new Error(
|
|
8879
|
+
`GitHub sync could not wake the assignee for Paperclip issue ${params.paperclipIssueId}: ${getErrorMessage(error)}`,
|
|
8880
|
+
{ cause: error }
|
|
8881
|
+
);
|
|
8557
8882
|
}
|
|
8558
8883
|
}
|
|
8559
8884
|
function parsePaperclipIssueDescription(value) {
|
|
@@ -9250,6 +9575,81 @@ function doIssueNumberListsMatch(left, right) {
|
|
|
9250
9575
|
}
|
|
9251
9576
|
return left.every((value, index) => value === right[index]);
|
|
9252
9577
|
}
|
|
9578
|
+
function getEffectivePullRequestActionCondition(pullRequest) {
|
|
9579
|
+
if (pullRequest.mergeability === "conflicting" || pullRequest.mergeStateStatus === "dirty") return "conflict";
|
|
9580
|
+
if (pullRequest.ciState === "red") return "ci_failed";
|
|
9581
|
+
if (pullRequest.hasUnresolvedReviewThreads) return "review_actionable";
|
|
9582
|
+
if (pullRequest.ciState === "green" && pullRequest.mergeability === "mergeable") return "ready";
|
|
9583
|
+
return "waiting";
|
|
9584
|
+
}
|
|
9585
|
+
function getEffectivePullRequestActionPriority(condition) {
|
|
9586
|
+
switch (condition) {
|
|
9587
|
+
case "conflict":
|
|
9588
|
+
return 0;
|
|
9589
|
+
case "ci_failed":
|
|
9590
|
+
return 1;
|
|
9591
|
+
case "review_actionable":
|
|
9592
|
+
return 2;
|
|
9593
|
+
case "waiting":
|
|
9594
|
+
return 3;
|
|
9595
|
+
case "ready":
|
|
9596
|
+
return 4;
|
|
9597
|
+
}
|
|
9598
|
+
}
|
|
9599
|
+
function selectEffectivePullRequestFingerprintEntries(pullRequests) {
|
|
9600
|
+
const highestPriority = Math.min(...pullRequests.map(
|
|
9601
|
+
(pullRequest) => getEffectivePullRequestActionPriority(pullRequest.condition)
|
|
9602
|
+
));
|
|
9603
|
+
return pullRequests.filter((pullRequest) => getEffectivePullRequestActionPriority(pullRequest.condition) === highestPriority).sort((left, right) => left.repositoryUrl.localeCompare(right.repositoryUrl) || left.number - right.number);
|
|
9604
|
+
}
|
|
9605
|
+
function buildRemoteActionFingerprint(snapshot) {
|
|
9606
|
+
const allPullRequests = snapshot.linkedPullRequests.map((pullRequest) => ({
|
|
9607
|
+
repositoryUrl: pullRequest.repositoryUrl.toLowerCase(),
|
|
9608
|
+
number: pullRequest.number,
|
|
9609
|
+
headSha: pullRequest.headSha ?? null,
|
|
9610
|
+
condition: getEffectivePullRequestActionCondition(pullRequest)
|
|
9611
|
+
}));
|
|
9612
|
+
const pullRequests = snapshot.state === "closed" || allPullRequests.length === 0 ? [] : selectEffectivePullRequestFingerprintEntries(allPullRequests);
|
|
9613
|
+
const reasonCode = snapshot.state === "closed" ? `issue_closed_${snapshot.stateReason ?? "completed"}` : pullRequests.length === 0 ? "issue_open" : `pr_${pullRequests[0]?.condition ?? "waiting"}`;
|
|
9614
|
+
return createHash("sha256").update(JSON.stringify({
|
|
9615
|
+
version: 3,
|
|
9616
|
+
issue: {
|
|
9617
|
+
state: snapshot.state,
|
|
9618
|
+
stateReason: snapshot.stateReason ?? null
|
|
9619
|
+
},
|
|
9620
|
+
pullRequests,
|
|
9621
|
+
reasonCode
|
|
9622
|
+
})).digest("hex");
|
|
9623
|
+
}
|
|
9624
|
+
function buildDirectPullRequestActionFingerprint(snapshots) {
|
|
9625
|
+
const openPullRequests = snapshots.filter((entry) => entry.lifecycleState === "open" && entry.pullRequest).map((entry) => ({
|
|
9626
|
+
repositoryUrl: entry.repository.url.toLowerCase(),
|
|
9627
|
+
number: entry.pullRequestLink.data.githubPullRequestNumber,
|
|
9628
|
+
headSha: entry.pullRequest?.headSha ?? null,
|
|
9629
|
+
condition: getEffectivePullRequestActionCondition(entry.pullRequest)
|
|
9630
|
+
}));
|
|
9631
|
+
const terminalOutcome = openPullRequests.length > 0 ? null : snapshots.some((entry) => entry.lifecycleState === "merged") ? "merged" : "closed";
|
|
9632
|
+
const pullRequests = openPullRequests.length > 0 ? selectEffectivePullRequestFingerprintEntries(openPullRequests) : [];
|
|
9633
|
+
return createHash("sha256").update(JSON.stringify({
|
|
9634
|
+
version: 3,
|
|
9635
|
+
terminalOutcome,
|
|
9636
|
+
pullRequests
|
|
9637
|
+
})).digest("hex");
|
|
9638
|
+
}
|
|
9639
|
+
function classifyIssueInteractionReason(value) {
|
|
9640
|
+
const reason = value.toLowerCase();
|
|
9641
|
+
if (reason.includes("new github comment")) return "trusted_comment";
|
|
9642
|
+
if (reason.includes("green ci") && reason.includes("review thread")) return "pr_ready";
|
|
9643
|
+
if (reason.includes("merge conflict")) return "pr_merge_conflict";
|
|
9644
|
+
if (reason.includes("failing ci")) return "pr_ci_failed";
|
|
9645
|
+
if (reason.includes("unfinished ci")) return "pr_ci_unfinished";
|
|
9646
|
+
if (reason.includes("unknown mergeability")) return "pr_mergeability_unknown";
|
|
9647
|
+
if (reason.includes("closed as completed")) return "issue_closed_completed";
|
|
9648
|
+
if (reason.includes("closed") && reason.includes("not planned")) return "issue_closed_not_planned";
|
|
9649
|
+
if (reason.includes("duplicate")) return "issue_closed_duplicate";
|
|
9650
|
+
if (reason.includes("open with no linked pull request")) return "issue_ready_for_triage";
|
|
9651
|
+
return "github_sync_status_decision";
|
|
9652
|
+
}
|
|
9253
9653
|
async function updatePaperclipIssueState(ctx, params) {
|
|
9254
9654
|
const {
|
|
9255
9655
|
companyId,
|
|
@@ -9262,11 +9662,14 @@ async function updatePaperclipIssueState(ctx, params) {
|
|
|
9262
9662
|
clearExecutionPolicy,
|
|
9263
9663
|
transitionComment,
|
|
9264
9664
|
transitionCommentAnnotation,
|
|
9665
|
+
actionFingerprint,
|
|
9265
9666
|
paperclipApiBaseUrl
|
|
9266
9667
|
} = params;
|
|
9267
9668
|
const trimmedTransitionComment = transitionComment.trim();
|
|
9669
|
+
let interactionOccurredAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
9268
9670
|
const statusWillChange = currentStatus !== nextStatus;
|
|
9269
9671
|
let createdTransitionComment = null;
|
|
9672
|
+
let transitionCommentComplete = false;
|
|
9270
9673
|
let issueUpdated = false;
|
|
9271
9674
|
const syncExecutionStatePatch = buildSyncFallbackExecutionStatePatch({
|
|
9272
9675
|
currentStatus,
|
|
@@ -9291,120 +9694,283 @@ async function updatePaperclipIssueState(ctx, params) {
|
|
|
9291
9694
|
issuePatch.assigneeAgentId = null;
|
|
9292
9695
|
issuePatch.assigneeUserId = null;
|
|
9293
9696
|
}
|
|
9294
|
-
if (statusWillChange) {
|
|
9295
|
-
|
|
9296
|
-
|
|
9297
|
-
|
|
9298
|
-
|
|
9299
|
-
|
|
9697
|
+
if (statusWillChange && !trimmedTransitionComment) {
|
|
9698
|
+
throw new Error("GitHub Sync refused to update a Paperclip issue status without an explanatory transition comment.");
|
|
9699
|
+
}
|
|
9700
|
+
if (statusWillChange && typeof ctx.issues.createComment !== "function") {
|
|
9701
|
+
throw new Error("This Paperclip runtime does not expose issue comment creation, so GitHub Sync refused to update a Paperclip issue status without an explanatory comment.");
|
|
9702
|
+
}
|
|
9703
|
+
const reasonCode = classifyIssueInteractionReason(transitionCommentAnnotation?.reason ?? trimmedTransitionComment);
|
|
9704
|
+
const interactionDedupeBase = actionFingerprint ? `sync:${createHash("sha256").update(JSON.stringify({
|
|
9705
|
+
companyId,
|
|
9706
|
+
issueId,
|
|
9707
|
+
mutation: "status_transition",
|
|
9708
|
+
actionFingerprint,
|
|
9709
|
+
currentStatus,
|
|
9710
|
+
nextStatus
|
|
9711
|
+
})).digest("hex")}` : `sync:${issueId}:${interactionOccurredAt}:${currentStatus}:${nextStatus}`;
|
|
9712
|
+
let existingInteractionEvents = [];
|
|
9713
|
+
if (actionFingerprint) {
|
|
9714
|
+
const ledger = await listIssueInteractionEvents(ctx, companyId, issueId, {
|
|
9715
|
+
from: "1970-01-01T00:00:00.000Z",
|
|
9716
|
+
to: "9999-12-31T23:59:59.999Z"
|
|
9717
|
+
});
|
|
9718
|
+
if (ledger.integrity.malformedRows > 0 || ledger.integrity.conflictingKeys > 0 || ledger.integrity.scanTruncated) {
|
|
9719
|
+
throw new Error("GitHub Sync refused a status transition because its issue interaction ledger is incomplete or conflicting.");
|
|
9300
9720
|
}
|
|
9301
|
-
|
|
9721
|
+
existingInteractionEvents = ledger.events;
|
|
9722
|
+
const existingIntent = existingInteractionEvents.find((event) => event.dedupeKey === `${interactionDedupeBase}:intent`);
|
|
9723
|
+
if (existingIntent) interactionOccurredAt = existingIntent.occurredAt;
|
|
9302
9724
|
}
|
|
9303
|
-
|
|
9304
|
-
|
|
9305
|
-
|
|
9306
|
-
|
|
9307
|
-
|
|
9308
|
-
|
|
9309
|
-
|
|
9310
|
-
|
|
9311
|
-
|
|
9312
|
-
|
|
9313
|
-
|
|
9314
|
-
|
|
9315
|
-
|
|
9316
|
-
|
|
9317
|
-
|
|
9318
|
-
|
|
9319
|
-
|
|
9320
|
-
|
|
9321
|
-
|
|
9322
|
-
|
|
9323
|
-
|
|
9324
|
-
|
|
9325
|
-
|
|
9326
|
-
|
|
9327
|
-
|
|
9725
|
+
await persistIssueInteractionEvent(ctx, {
|
|
9726
|
+
schemaVersion: 1,
|
|
9727
|
+
companyId,
|
|
9728
|
+
paperclipIssueId: issueId,
|
|
9729
|
+
occurredAt: interactionOccurredAt,
|
|
9730
|
+
category: "sync",
|
|
9731
|
+
action: "status_decision",
|
|
9732
|
+
source: "sync",
|
|
9733
|
+
...transitionCommentAnnotation ? {
|
|
9734
|
+
remote: {
|
|
9735
|
+
repositoryUrl: transitionCommentAnnotation.repositoryUrl,
|
|
9736
|
+
kind: "issue",
|
|
9737
|
+
number: transitionCommentAnnotation.githubIssueNumber,
|
|
9738
|
+
url: transitionCommentAnnotation.githubIssueUrl
|
|
9739
|
+
}
|
|
9740
|
+
} : {},
|
|
9741
|
+
transition: { from: currentStatus, to: nextStatus, reasonCode },
|
|
9742
|
+
outcome: "observed",
|
|
9743
|
+
dedupeKey: `${interactionDedupeBase}:intent`
|
|
9744
|
+
});
|
|
9745
|
+
const persistSyncResult = (outcome) => persistIssueInteractionEvent(ctx, {
|
|
9746
|
+
schemaVersion: 1,
|
|
9747
|
+
companyId,
|
|
9748
|
+
paperclipIssueId: issueId,
|
|
9749
|
+
occurredAt: interactionOccurredAt,
|
|
9750
|
+
category: "sync",
|
|
9751
|
+
action: "status_decision",
|
|
9752
|
+
source: "sync",
|
|
9753
|
+
...transitionCommentAnnotation ? {
|
|
9754
|
+
remote: {
|
|
9755
|
+
repositoryUrl: transitionCommentAnnotation.repositoryUrl,
|
|
9756
|
+
kind: "issue",
|
|
9757
|
+
number: transitionCommentAnnotation.githubIssueNumber,
|
|
9758
|
+
url: transitionCommentAnnotation.githubIssueUrl
|
|
9759
|
+
}
|
|
9760
|
+
} : {},
|
|
9761
|
+
transition: { from: currentStatus, to: nextStatus, reasonCode },
|
|
9762
|
+
outcome,
|
|
9763
|
+
dedupeKey: `${interactionDedupeBase}:result:${outcome}`
|
|
9764
|
+
});
|
|
9765
|
+
const persistMutationPhase = (outcome) => persistIssueInteractionEvent(ctx, {
|
|
9766
|
+
schemaVersion: 1,
|
|
9767
|
+
companyId,
|
|
9768
|
+
paperclipIssueId: issueId,
|
|
9769
|
+
occurredAt: interactionOccurredAt,
|
|
9770
|
+
category: "sync",
|
|
9771
|
+
action: "update_issue",
|
|
9772
|
+
source: "sync",
|
|
9773
|
+
...transitionCommentAnnotation ? {
|
|
9774
|
+
remote: {
|
|
9775
|
+
repositoryUrl: transitionCommentAnnotation.repositoryUrl,
|
|
9776
|
+
kind: "issue",
|
|
9777
|
+
number: transitionCommentAnnotation.githubIssueNumber,
|
|
9778
|
+
url: transitionCommentAnnotation.githubIssueUrl
|
|
9779
|
+
}
|
|
9780
|
+
} : {},
|
|
9781
|
+
outcome,
|
|
9782
|
+
dedupeKey: `${interactionDedupeBase}:mutation:${outcome === "observed" ? "intent" : `result:${outcome}`}`
|
|
9783
|
+
});
|
|
9784
|
+
const priorMutationIntent = existingInteractionEvents.find((event) => event.dedupeKey === `${interactionDedupeBase}:mutation:intent`);
|
|
9785
|
+
const priorMutationChanged = existingInteractionEvents.find((event) => event.dedupeKey === `${interactionDedupeBase}:mutation:result:changed`);
|
|
9786
|
+
const priorMutationFailed = existingInteractionEvents.find((event) => event.dedupeKey === `${interactionDedupeBase}:mutation:result:failed`);
|
|
9787
|
+
let mutationAttemptStarted = false;
|
|
9788
|
+
let mutationReturned = false;
|
|
9789
|
+
let mutationComplete = Boolean(priorMutationChanged);
|
|
9790
|
+
try {
|
|
9791
|
+
if (statusWillChange) {
|
|
9792
|
+
const commentIntentKey = `${interactionDedupeBase}:comment:intent`;
|
|
9793
|
+
const commentChangedKey = `${interactionDedupeBase}:comment:result:changed`;
|
|
9794
|
+
const priorCommentIntent = existingInteractionEvents.find((event) => event.dedupeKey === commentIntentKey);
|
|
9795
|
+
const priorCommentChanged = existingInteractionEvents.find((event) => event.dedupeKey === commentChangedKey);
|
|
9796
|
+
if (priorCommentChanged) {
|
|
9797
|
+
transitionCommentComplete = true;
|
|
9798
|
+
} else if (priorCommentIntent) {
|
|
9799
|
+
throw new Error("GitHub Sync refused to repeat an uncertain transition comment; reconcile the durable interaction intent before retrying.");
|
|
9800
|
+
} else {
|
|
9801
|
+
const commentEventBase = {
|
|
9802
|
+
schemaVersion: 1,
|
|
9803
|
+
companyId,
|
|
9804
|
+
paperclipIssueId: issueId,
|
|
9805
|
+
occurredAt: interactionOccurredAt,
|
|
9806
|
+
category: "comment",
|
|
9807
|
+
action: "add_issue_comment",
|
|
9808
|
+
source: "sync",
|
|
9809
|
+
...transitionCommentAnnotation ? {
|
|
9810
|
+
remote: {
|
|
9811
|
+
repositoryUrl: transitionCommentAnnotation.repositoryUrl,
|
|
9812
|
+
kind: "issue",
|
|
9813
|
+
number: transitionCommentAnnotation.githubIssueNumber,
|
|
9814
|
+
url: transitionCommentAnnotation.githubIssueUrl
|
|
9815
|
+
}
|
|
9816
|
+
} : {}
|
|
9817
|
+
};
|
|
9818
|
+
await persistIssueInteractionEvent(ctx, {
|
|
9819
|
+
...commentEventBase,
|
|
9820
|
+
outcome: "observed",
|
|
9821
|
+
dedupeKey: commentIntentKey
|
|
9822
|
+
});
|
|
9823
|
+
try {
|
|
9824
|
+
createdTransitionComment = await ctx.issues.createComment(issueId, trimmedTransitionComment, companyId);
|
|
9825
|
+
if (transitionCommentAnnotation) {
|
|
9826
|
+
await upsertStatusTransitionCommentAnnotation(ctx, {
|
|
9328
9827
|
issueId,
|
|
9329
|
-
|
|
9828
|
+
commentId: createdTransitionComment.id,
|
|
9829
|
+
annotation: {
|
|
9830
|
+
...transitionCommentAnnotation,
|
|
9831
|
+
companyId,
|
|
9832
|
+
paperclipIssueId: issueId
|
|
9833
|
+
}
|
|
9834
|
+
});
|
|
9835
|
+
}
|
|
9836
|
+
await persistIssueInteractionEvent(ctx, {
|
|
9837
|
+
...commentEventBase,
|
|
9838
|
+
outcome: "changed",
|
|
9839
|
+
dedupeKey: commentChangedKey
|
|
9840
|
+
});
|
|
9841
|
+
transitionCommentComplete = true;
|
|
9842
|
+
} catch (error) {
|
|
9843
|
+
await persistIssueInteractionEvent(ctx, {
|
|
9844
|
+
...commentEventBase,
|
|
9845
|
+
outcome: "failed",
|
|
9846
|
+
dedupeKey: `${interactionDedupeBase}:comment:result:failed`
|
|
9847
|
+
});
|
|
9848
|
+
throw error;
|
|
9849
|
+
}
|
|
9850
|
+
}
|
|
9851
|
+
}
|
|
9852
|
+
if (!mutationComplete) {
|
|
9853
|
+
if (priorMutationIntent && !priorMutationFailed) {
|
|
9854
|
+
throw new Error("GitHub Sync refused to repeat an uncertain issue mutation; reconcile the durable mutation intent before retrying.");
|
|
9855
|
+
}
|
|
9856
|
+
await persistMutationPhase("observed");
|
|
9857
|
+
mutationAttemptStarted = true;
|
|
9858
|
+
if (paperclipApiBaseUrl) {
|
|
9859
|
+
try {
|
|
9860
|
+
const response = await fetchPaperclipApi(
|
|
9861
|
+
getPaperclipIssueEndpoint(paperclipApiBaseUrl, issueId),
|
|
9862
|
+
{
|
|
9863
|
+
method: "PATCH",
|
|
9864
|
+
headers: {
|
|
9865
|
+
accept: "application/json",
|
|
9866
|
+
"content-type": "application/json"
|
|
9867
|
+
},
|
|
9868
|
+
body: JSON.stringify(issuePatch)
|
|
9869
|
+
},
|
|
9870
|
+
{
|
|
9330
9871
|
companyId
|
|
9331
|
-
|
|
9332
|
-
|
|
9333
|
-
|
|
9334
|
-
|
|
9872
|
+
}
|
|
9873
|
+
);
|
|
9874
|
+
const payloadResult = await readPaperclipApiJsonResponse(response, {
|
|
9875
|
+
operationLabel: "issue update",
|
|
9876
|
+
bodyRequired: false
|
|
9877
|
+
});
|
|
9878
|
+
if (!payloadResult.failure) {
|
|
9879
|
+
issueUpdated = true;
|
|
9880
|
+
if (issuePatch.executionState === null && ctx.issues && typeof ctx.issues.update === "function") {
|
|
9881
|
+
try {
|
|
9882
|
+
await ctx.issues.update(
|
|
9883
|
+
issueId,
|
|
9884
|
+
{ executionState: null },
|
|
9885
|
+
companyId
|
|
9886
|
+
);
|
|
9887
|
+
} catch (error) {
|
|
9888
|
+
issueUpdated = false;
|
|
9889
|
+
ctx.logger.warn("GitHub sync could not clear Paperclip issue execution state after the local API update. Falling back to direct issue mutation.", {
|
|
9890
|
+
companyId,
|
|
9891
|
+
issueId,
|
|
9892
|
+
paperclipApiBaseUrl,
|
|
9893
|
+
nextStatus,
|
|
9894
|
+
error: getErrorMessage(error)
|
|
9895
|
+
});
|
|
9896
|
+
}
|
|
9897
|
+
}
|
|
9898
|
+
}
|
|
9899
|
+
if (payloadResult.failure && (payloadResult.failure.status ?? response.status) !== 404 && (payloadResult.failure.status ?? response.status) !== 405) {
|
|
9900
|
+
logPaperclipIssueStatusUpdateFailure(ctx, {
|
|
9335
9901
|
companyId,
|
|
9336
9902
|
issueId,
|
|
9337
9903
|
paperclipApiBaseUrl,
|
|
9338
9904
|
nextStatus,
|
|
9339
|
-
|
|
9905
|
+
status: payloadResult.failure.status ?? response.status,
|
|
9906
|
+
errorMessage: payloadResult.failure.errorMessage
|
|
9340
9907
|
});
|
|
9341
9908
|
}
|
|
9909
|
+
} catch (error) {
|
|
9910
|
+
logPaperclipIssueStatusUpdateFailure(ctx, {
|
|
9911
|
+
companyId,
|
|
9912
|
+
issueId,
|
|
9913
|
+
paperclipApiBaseUrl,
|
|
9914
|
+
nextStatus,
|
|
9915
|
+
errorMessage: getErrorMessage(error)
|
|
9916
|
+
});
|
|
9342
9917
|
}
|
|
9343
9918
|
}
|
|
9344
|
-
if (
|
|
9345
|
-
|
|
9346
|
-
|
|
9919
|
+
if (!issueUpdated) {
|
|
9920
|
+
const preserveExistingUserAssigneeWithoutLocalApi = nextAssignee?.kind === "user" && !paperclipApiBaseUrl;
|
|
9921
|
+
const sdkIssuePatch = {
|
|
9922
|
+
...issuePatch,
|
|
9923
|
+
...syncExecutionStatePatch !== void 0 ? { executionState: syncExecutionStatePatch } : {}
|
|
9924
|
+
};
|
|
9925
|
+
if (preserveExistingUserAssigneeWithoutLocalApi) {
|
|
9926
|
+
delete sdkIssuePatch.assigneeAgentId;
|
|
9927
|
+
delete sdkIssuePatch.assigneeUserId;
|
|
9928
|
+
ctx.logger.warn("GitHub sync could not reassign a Paperclip issue to a user without the local Paperclip API. Preserving the existing assignee.", {
|
|
9929
|
+
companyId,
|
|
9930
|
+
issueId,
|
|
9931
|
+
nextStatus,
|
|
9932
|
+
assigneeUserId: nextAssignee.id
|
|
9933
|
+
});
|
|
9934
|
+
}
|
|
9935
|
+
await ctx.issues.update(issueId, sdkIssuePatch, companyId);
|
|
9936
|
+
}
|
|
9937
|
+
mutationReturned = true;
|
|
9938
|
+
await persistMutationPhase("changed");
|
|
9939
|
+
mutationComplete = true;
|
|
9940
|
+
}
|
|
9941
|
+
if (!statusWillChange && trimmedTransitionComment && typeof ctx.issues.createComment === "function") {
|
|
9942
|
+
const createdComment = await ctx.issues.createComment(issueId, trimmedTransitionComment, companyId);
|
|
9943
|
+
if (transitionCommentAnnotation) {
|
|
9944
|
+
await upsertStatusTransitionCommentAnnotation(ctx, {
|
|
9347
9945
|
issueId,
|
|
9348
|
-
|
|
9349
|
-
|
|
9350
|
-
|
|
9351
|
-
|
|
9946
|
+
commentId: createdComment.id,
|
|
9947
|
+
annotation: {
|
|
9948
|
+
...transitionCommentAnnotation,
|
|
9949
|
+
companyId,
|
|
9950
|
+
paperclipIssueId: issueId
|
|
9951
|
+
}
|
|
9352
9952
|
});
|
|
9353
9953
|
}
|
|
9354
|
-
} catch (error) {
|
|
9355
|
-
logPaperclipIssueStatusUpdateFailure(ctx, {
|
|
9356
|
-
companyId,
|
|
9357
|
-
issueId,
|
|
9358
|
-
paperclipApiBaseUrl,
|
|
9359
|
-
nextStatus,
|
|
9360
|
-
errorMessage: getErrorMessage(error)
|
|
9361
|
-
});
|
|
9362
9954
|
}
|
|
9363
|
-
|
|
9364
|
-
|
|
9365
|
-
const preserveExistingUserAssigneeWithoutLocalApi = nextAssignee?.kind === "user" && !paperclipApiBaseUrl;
|
|
9366
|
-
const sdkIssuePatch = {
|
|
9367
|
-
...issuePatch,
|
|
9368
|
-
...syncExecutionStatePatch !== void 0 ? { executionState: syncExecutionStatePatch } : {}
|
|
9369
|
-
};
|
|
9370
|
-
if (preserveExistingUserAssigneeWithoutLocalApi) {
|
|
9371
|
-
delete sdkIssuePatch.assigneeAgentId;
|
|
9372
|
-
delete sdkIssuePatch.assigneeUserId;
|
|
9373
|
-
ctx.logger.warn("GitHub sync could not reassign a Paperclip issue to a user without the local Paperclip API. Preserving the existing assignee.", {
|
|
9374
|
-
companyId,
|
|
9375
|
-
issueId,
|
|
9376
|
-
nextStatus,
|
|
9377
|
-
assigneeUserId: nextAssignee.id
|
|
9378
|
-
});
|
|
9955
|
+
if (statusWillChange && !transitionCommentComplete) {
|
|
9956
|
+
throw new Error("GitHub Sync refused to complete a status transition without a durable transition comment result.");
|
|
9379
9957
|
}
|
|
9380
|
-
|
|
9381
|
-
|
|
9382
|
-
|
|
9383
|
-
|
|
9384
|
-
|
|
9385
|
-
|
|
9386
|
-
|
|
9387
|
-
annotation: {
|
|
9388
|
-
...transitionCommentAnnotation,
|
|
9389
|
-
companyId,
|
|
9390
|
-
paperclipIssueId: issueId
|
|
9391
|
-
}
|
|
9392
|
-
});
|
|
9958
|
+
} catch (error) {
|
|
9959
|
+
if (mutationAttemptStarted && !mutationReturned) {
|
|
9960
|
+
try {
|
|
9961
|
+
await persistMutationPhase("failed");
|
|
9962
|
+
} catch (mutationLedgerError) {
|
|
9963
|
+
throw new AggregateError([error, mutationLedgerError], "GitHub Sync issue mutation failed and its mutation result could not be persisted.");
|
|
9964
|
+
}
|
|
9393
9965
|
}
|
|
9394
|
-
|
|
9395
|
-
|
|
9396
|
-
|
|
9397
|
-
|
|
9398
|
-
issueId,
|
|
9399
|
-
commentId: createdComment.id,
|
|
9400
|
-
annotation: {
|
|
9401
|
-
...transitionCommentAnnotation,
|
|
9402
|
-
companyId,
|
|
9403
|
-
paperclipIssueId: issueId
|
|
9404
|
-
}
|
|
9405
|
-
});
|
|
9966
|
+
try {
|
|
9967
|
+
await persistSyncResult("failed");
|
|
9968
|
+
} catch (ledgerError) {
|
|
9969
|
+
throw new AggregateError([error, ledgerError], "GitHub Sync mutation failed and its result event could not be persisted.");
|
|
9406
9970
|
}
|
|
9971
|
+
throw error;
|
|
9407
9972
|
}
|
|
9973
|
+
await persistSyncResult(statusWillChange ? "changed" : "noop");
|
|
9408
9974
|
}
|
|
9409
9975
|
function sortIssuesForImport(issues) {
|
|
9410
9976
|
return [...issues].sort((left, right) => {
|
|
@@ -9853,6 +10419,7 @@ async function cancelUnmappedTransferredGitHubIssue(ctx, params) {
|
|
|
9853
10419
|
nextStatus,
|
|
9854
10420
|
transferredRepository: params.transferredRepository
|
|
9855
10421
|
}),
|
|
10422
|
+
actionFingerprint: `transferred-unmapped:${params.transferredRepository.url}`,
|
|
9856
10423
|
paperclipApiBaseUrl: params.paperclipApiBaseUrl
|
|
9857
10424
|
});
|
|
9858
10425
|
return {
|
|
@@ -9950,7 +10517,7 @@ async function reconcileTransferredImportedIssues(ctx, params) {
|
|
|
9950
10517
|
updatedDescriptionsCount
|
|
9951
10518
|
};
|
|
9952
10519
|
}
|
|
9953
|
-
async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mapping, advancedSettings, allIssuesById, importedIssues, createdIssueIds, availableLabels, paperclipApiBaseUrl, linkedPullRequestsByIssueNumber, issueStatusSnapshotCache, pullRequestStatusCache, repositoryMaintainerCache, syncFailureContext, failures, assertNotCancelled, onGitHubIssueClosed, onProgress) {
|
|
10520
|
+
async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mapping, advancedSettings, allIssuesById, importedIssues, createdIssueIds, availableLabels, paperclipApiBaseUrl, linkedPullRequestsByIssueNumber, issueStatusSnapshotCache, pullRequestStatusCache, repositoryMaintainerCache, syncFailureContext, failures, persistImportRegistry, assertNotCancelled, onGitHubIssueClosed, onProgress) {
|
|
9954
10521
|
if (!mapping.companyId || !ctx.issues || typeof ctx.issues.get !== "function" || typeof ctx.issues.update !== "function") {
|
|
9955
10522
|
return {
|
|
9956
10523
|
updatedStatusesCount: 0,
|
|
@@ -10106,12 +10673,36 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
|
|
|
10106
10673
|
}
|
|
10107
10674
|
const hasTrustedNewLinkedPullRequestComment = paperclipIssue.status === "backlog" || currentLinkedPullRequestCommentCounts.length === 0 ? false : await hasTrustedNewLinkedPullRequestComments({
|
|
10108
10675
|
octokit,
|
|
10109
|
-
githubIssue,
|
|
10676
|
+
originalPosterLogin: githubIssue.authorLogin,
|
|
10110
10677
|
previousCommentCounts: importedIssue.linkedPullRequestCommentCounts,
|
|
10111
10678
|
currentCommentCounts: currentLinkedPullRequestCommentCounts,
|
|
10112
10679
|
maintainerCache: repositoryMaintainerCache
|
|
10113
10680
|
});
|
|
10114
10681
|
const hasTrustedNewComment = hasTrustedNewIssueComment || hasTrustedNewLinkedPullRequestComment;
|
|
10682
|
+
const remoteActionFingerprint = buildRemoteActionFingerprint(snapshot);
|
|
10683
|
+
const actionJournalFingerprint = createHash("sha256").update(JSON.stringify({
|
|
10684
|
+
remoteActionFingerprint,
|
|
10685
|
+
issueCommentCount: snapshot.commentCount,
|
|
10686
|
+
linkedPullRequestCommentCounts: canonicalizeGitHubPullRequestCommentCounts(
|
|
10687
|
+
currentLinkedPullRequestCommentCounts
|
|
10688
|
+
)
|
|
10689
|
+
})).digest("hex");
|
|
10690
|
+
if (importedIssue.pendingRemoteActionWake) {
|
|
10691
|
+
const pendingWake2 = importedIssue.pendingRemoteActionWake;
|
|
10692
|
+
await wakePaperclipIssueAssignee(ctx, {
|
|
10693
|
+
assigneeAgentId: pendingWake2.assigneeAgentId,
|
|
10694
|
+
paperclipIssueId: importedIssue.paperclipIssueId,
|
|
10695
|
+
companyId: mapping.companyId,
|
|
10696
|
+
paperclipApiBaseUrl,
|
|
10697
|
+
reason: pendingWake2.reason,
|
|
10698
|
+
mutation: pendingWake2.mutation,
|
|
10699
|
+
actionFingerprint: pendingWake2.fingerprint,
|
|
10700
|
+
previousStatus: pendingWake2.previousStatus,
|
|
10701
|
+
nextStatus: pendingWake2.nextStatus
|
|
10702
|
+
});
|
|
10703
|
+
delete importedIssue.pendingRemoteActionWake;
|
|
10704
|
+
await persistImportRegistry();
|
|
10705
|
+
}
|
|
10115
10706
|
const wasImportedThisRun = createdIssueIds.has(importedIssue.githubIssueId);
|
|
10116
10707
|
const maintainerAuthoredImportedIssue = wasImportedThisRun && advancedSettings.defaultStatus !== "todo" && snapshot.state === "open" && snapshot.linkedPullRequests.length === 0 ? await isMaintainerAuthoredGitHubIssue({
|
|
10117
10708
|
octokit,
|
|
@@ -10136,6 +10727,9 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
|
|
|
10136
10727
|
if (paperclipIssue.status === "blocked" && nextStatus !== "blocked" && await hasUnresolvedPaperclipIssueBlocker(ctx, paperclipIssue, mapping.companyId)) {
|
|
10137
10728
|
nextStatus = "blocked";
|
|
10138
10729
|
}
|
|
10730
|
+
if (paperclipIssue.status !== nextStatus && !hasTrustedNewComment && importedIssue.remoteActionFingerprint === remoteActionFingerprint) {
|
|
10731
|
+
nextStatus = paperclipIssue.status;
|
|
10732
|
+
}
|
|
10139
10733
|
const shouldPreserveMaintainerWaitRouting = isHealthyMaintainerWaitTransition({
|
|
10140
10734
|
currentStatus: paperclipIssue.status,
|
|
10141
10735
|
nextStatus,
|
|
@@ -10161,10 +10755,15 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
|
|
|
10161
10755
|
const nextAssigneeChanged = nextTransitionAssignee ? !doesPaperclipIssueAssigneeMatch(paperclipIssueSyncContext.assignee, nextTransitionAssignee.principal) : false;
|
|
10162
10756
|
const shouldWakeImportedAssignee = wasImportedThisRun && nextStatus === "todo" && (paperclipIssue.status === nextStatus || shouldPreserveImportedTriageRouting) && paperclipIssueSyncContext.assignee?.kind === "agent";
|
|
10163
10757
|
const shouldWakeTransitionAssignee = paperclipIssue.status !== nextStatus && nextTransitionAssignee?.principal.kind === "agent" && isActionablePaperclipIssueStatus(nextStatus) && (nextAssigneeChanged || paperclipIssue.status !== nextStatus);
|
|
10164
|
-
|
|
10165
|
-
|
|
10166
|
-
|
|
10167
|
-
|
|
10758
|
+
const persistObservedRemoteState = async (pendingWake2) => {
|
|
10759
|
+
importedIssue.githubIssueNumber = githubIssue.number;
|
|
10760
|
+
importedIssue.lastSeenCommentCount = snapshot.commentCount;
|
|
10761
|
+
importedIssue.lastSeenGitHubState = snapshot.state;
|
|
10762
|
+
importedIssue.linkedPullRequestCommentCounts = currentLinkedPullRequestCommentCounts;
|
|
10763
|
+
importedIssue.remoteActionFingerprint = remoteActionFingerprint;
|
|
10764
|
+
if (pendingWake2) importedIssue.pendingRemoteActionWake = pendingWake2;
|
|
10765
|
+
await persistImportRegistry();
|
|
10766
|
+
};
|
|
10168
10767
|
if (paperclipIssue.status === nextStatus) {
|
|
10169
10768
|
if (shouldClearTransitionAssignee || shouldClearCompletedExecutionPolicy) {
|
|
10170
10769
|
updateSyncFailureContext(syncFailureContext, {
|
|
@@ -10181,16 +10780,35 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
|
|
|
10181
10780
|
...shouldClearTransitionAssignee ? { clearAssignee: true } : {},
|
|
10182
10781
|
...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
|
|
10183
10782
|
transitionComment: "",
|
|
10783
|
+
actionFingerprint: actionJournalFingerprint,
|
|
10184
10784
|
paperclipApiBaseUrl
|
|
10185
10785
|
});
|
|
10186
10786
|
}
|
|
10187
|
-
if (shouldWakeImportedAssignee) {
|
|
10787
|
+
if (shouldWakeImportedAssignee && paperclipIssueSyncContext.assignee?.kind === "agent") {
|
|
10788
|
+
const pendingWake2 = {
|
|
10789
|
+
fingerprint: remoteActionFingerprint,
|
|
10790
|
+
assigneeAgentId: paperclipIssueSyncContext.assignee.id,
|
|
10791
|
+
reason: IMPORTED_ISSUE_WAKE_REASON,
|
|
10792
|
+
mutation: "import",
|
|
10793
|
+
nextStatus
|
|
10794
|
+
};
|
|
10795
|
+
await persistObservedRemoteState(pendingWake2);
|
|
10188
10796
|
queuedIssueWakeups.push({
|
|
10189
|
-
assigneeAgentId:
|
|
10797
|
+
assigneeAgentId: pendingWake2.assigneeAgentId,
|
|
10190
10798
|
paperclipIssueId: importedIssue.paperclipIssueId,
|
|
10191
|
-
reason:
|
|
10192
|
-
mutation: "import"
|
|
10799
|
+
reason: pendingWake2.reason,
|
|
10800
|
+
mutation: "import",
|
|
10801
|
+
actionFingerprint: pendingWake2.fingerprint,
|
|
10802
|
+
nextStatus,
|
|
10803
|
+
onSuccess: async () => {
|
|
10804
|
+
if (importedIssue.pendingRemoteActionWake?.fingerprint === pendingWake2.fingerprint) {
|
|
10805
|
+
delete importedIssue.pendingRemoteActionWake;
|
|
10806
|
+
await persistImportRegistry();
|
|
10807
|
+
}
|
|
10808
|
+
}
|
|
10193
10809
|
});
|
|
10810
|
+
} else {
|
|
10811
|
+
await persistObservedRemoteState();
|
|
10194
10812
|
}
|
|
10195
10813
|
continue;
|
|
10196
10814
|
}
|
|
@@ -10218,25 +10836,41 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
|
|
|
10218
10836
|
...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
|
|
10219
10837
|
transitionComment: transitionComment.body,
|
|
10220
10838
|
transitionCommentAnnotation: transitionComment.annotation,
|
|
10839
|
+
actionFingerprint: actionJournalFingerprint,
|
|
10221
10840
|
paperclipApiBaseUrl
|
|
10222
10841
|
});
|
|
10842
|
+
const pendingWake = shouldWakeImportedAssignee && paperclipIssueSyncContext.assignee?.kind === "agent" ? {
|
|
10843
|
+
fingerprint: remoteActionFingerprint,
|
|
10844
|
+
assigneeAgentId: paperclipIssueSyncContext.assignee.id,
|
|
10845
|
+
reason: IMPORTED_ISSUE_WAKE_REASON,
|
|
10846
|
+
mutation: "import",
|
|
10847
|
+
previousStatus: paperclipIssue.status,
|
|
10848
|
+
nextStatus
|
|
10849
|
+
} : shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? {
|
|
10850
|
+
fingerprint: remoteActionFingerprint,
|
|
10851
|
+
assigneeAgentId: nextTransitionAssignee.principal.id,
|
|
10852
|
+
reason: STATUS_TRANSITION_WAKE_REASON,
|
|
10853
|
+
mutation: "status_transition",
|
|
10854
|
+
previousStatus: paperclipIssue.status,
|
|
10855
|
+
nextStatus
|
|
10856
|
+
} : void 0;
|
|
10857
|
+
await persistObservedRemoteState(pendingWake);
|
|
10223
10858
|
updatedStatusesCount += 1;
|
|
10224
|
-
if (
|
|
10225
|
-
queuedIssueWakeups.push({
|
|
10226
|
-
assigneeAgentId: paperclipIssueSyncContext.assignee?.kind === "agent" ? paperclipIssueSyncContext.assignee.id : null,
|
|
10227
|
-
paperclipIssueId: importedIssue.paperclipIssueId,
|
|
10228
|
-
reason: IMPORTED_ISSUE_WAKE_REASON,
|
|
10229
|
-
mutation: "import"
|
|
10230
|
-
});
|
|
10231
|
-
}
|
|
10232
|
-
if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent") {
|
|
10859
|
+
if (pendingWake) {
|
|
10233
10860
|
queuedIssueWakeups.push({
|
|
10234
|
-
assigneeAgentId:
|
|
10861
|
+
assigneeAgentId: pendingWake.assigneeAgentId,
|
|
10235
10862
|
paperclipIssueId: importedIssue.paperclipIssueId,
|
|
10236
|
-
reason:
|
|
10237
|
-
mutation:
|
|
10238
|
-
|
|
10239
|
-
|
|
10863
|
+
reason: pendingWake.reason,
|
|
10864
|
+
mutation: pendingWake.mutation,
|
|
10865
|
+
actionFingerprint: pendingWake.fingerprint,
|
|
10866
|
+
previousStatus: pendingWake.previousStatus,
|
|
10867
|
+
nextStatus: pendingWake.nextStatus,
|
|
10868
|
+
onSuccess: async () => {
|
|
10869
|
+
if (importedIssue.pendingRemoteActionWake?.fingerprint === pendingWake.fingerprint) {
|
|
10870
|
+
delete importedIssue.pendingRemoteActionWake;
|
|
10871
|
+
await persistImportRegistry();
|
|
10872
|
+
}
|
|
10873
|
+
}
|
|
10240
10874
|
});
|
|
10241
10875
|
}
|
|
10242
10876
|
} catch (error) {
|
|
@@ -10260,16 +10894,20 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
|
|
|
10260
10894
|
await mapWithConcurrency(
|
|
10261
10895
|
queuedIssueWakeups,
|
|
10262
10896
|
IMPORTED_ISSUE_WAKEUP_CONCURRENCY,
|
|
10263
|
-
async (queuedWakeup) =>
|
|
10264
|
-
|
|
10265
|
-
|
|
10266
|
-
|
|
10267
|
-
|
|
10268
|
-
|
|
10269
|
-
|
|
10270
|
-
|
|
10271
|
-
|
|
10272
|
-
|
|
10897
|
+
async (queuedWakeup) => {
|
|
10898
|
+
await wakePaperclipIssueAssignee(ctx, {
|
|
10899
|
+
assigneeAgentId: queuedWakeup.assigneeAgentId,
|
|
10900
|
+
paperclipIssueId: queuedWakeup.paperclipIssueId,
|
|
10901
|
+
companyId: mapping.companyId,
|
|
10902
|
+
paperclipApiBaseUrl,
|
|
10903
|
+
reason: queuedWakeup.reason,
|
|
10904
|
+
mutation: queuedWakeup.mutation,
|
|
10905
|
+
actionFingerprint: queuedWakeup.actionFingerprint,
|
|
10906
|
+
previousStatus: queuedWakeup.previousStatus,
|
|
10907
|
+
nextStatus: queuedWakeup.nextStatus
|
|
10908
|
+
});
|
|
10909
|
+
await queuedWakeup.onSuccess?.();
|
|
10910
|
+
}
|
|
10273
10911
|
);
|
|
10274
10912
|
return {
|
|
10275
10913
|
updatedStatusesCount,
|
|
@@ -10289,7 +10927,7 @@ function groupGitHubPullRequestLinksByPaperclipIssue(pullRequestLinks) {
|
|
|
10289
10927
|
}
|
|
10290
10928
|
return groups;
|
|
10291
10929
|
}
|
|
10292
|
-
async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mapping, advancedSettings, pullRequestLinks, paperclipApiBaseUrl, pullRequestStatusCache, syncFailureContext, failures, assertNotCancelled, onProgress) {
|
|
10930
|
+
async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mapping, advancedSettings, pullRequestLinks, paperclipApiBaseUrl, pullRequestStatusCache, syncFailureContext, failures, remoteActionRegistry, persistRemoteActionRegistry, assertNotCancelled, onProgress) {
|
|
10293
10931
|
if (!mapping.companyId || !ctx.issues || typeof ctx.issues.get !== "function" || typeof ctx.issues.update !== "function") {
|
|
10294
10932
|
return {
|
|
10295
10933
|
updatedStatusesCount: 0
|
|
@@ -10341,6 +10979,15 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
|
|
|
10341
10979
|
pullRequestState: livePullRequestLinkState
|
|
10342
10980
|
});
|
|
10343
10981
|
}
|
|
10982
|
+
const directPullRequestMetadata = {
|
|
10983
|
+
...normalizeGitHubUsername(pullRequestResponse.data.user?.login) ? { authorLogin: normalizeGitHubUsername(pullRequestResponse.data.user?.login) } : {},
|
|
10984
|
+
commentCounts: {
|
|
10985
|
+
number: pullRequestLink.data.githubPullRequestNumber,
|
|
10986
|
+
repositoryUrl: pullRequestRepository.url,
|
|
10987
|
+
topLevelCommentCount: typeof pullRequestResponse.data.comments === "number" && pullRequestResponse.data.comments >= 0 ? Math.floor(pullRequestResponse.data.comments) : 0,
|
|
10988
|
+
reviewCommentCount: typeof pullRequestResponse.data.review_comments === "number" && pullRequestResponse.data.review_comments >= 0 ? Math.floor(pullRequestResponse.data.review_comments) : 0
|
|
10989
|
+
}
|
|
10990
|
+
};
|
|
10344
10991
|
if (livePullRequestLifecycleState === "open") {
|
|
10345
10992
|
const pullRequest = await getGitHubPullRequestStatusSnapshot(
|
|
10346
10993
|
octokit,
|
|
@@ -10352,13 +10999,15 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
|
|
|
10352
10999
|
pullRequestLink,
|
|
10353
11000
|
repository: pullRequestRepository,
|
|
10354
11001
|
lifecycleState: "open",
|
|
10355
|
-
pullRequest
|
|
11002
|
+
pullRequest,
|
|
11003
|
+
...directPullRequestMetadata
|
|
10356
11004
|
});
|
|
10357
11005
|
} else {
|
|
10358
11006
|
pullRequestSnapshots.push({
|
|
10359
11007
|
pullRequestLink,
|
|
10360
11008
|
repository: pullRequestRepository,
|
|
10361
|
-
lifecycleState: livePullRequestLifecycleState
|
|
11009
|
+
lifecycleState: livePullRequestLifecycleState,
|
|
11010
|
+
...directPullRequestMetadata
|
|
10362
11011
|
});
|
|
10363
11012
|
}
|
|
10364
11013
|
} catch (error) {
|
|
@@ -10390,6 +11039,51 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
|
|
|
10390
11039
|
if (!paperclipIssue) {
|
|
10391
11040
|
continue;
|
|
10392
11041
|
}
|
|
11042
|
+
const remoteActionKey = `direct-pr:${mapping.companyId}:${paperclipIssueId}`;
|
|
11043
|
+
let remoteAction = remoteActionRegistry.find((entry) => entry.key === remoteActionKey);
|
|
11044
|
+
if (!remoteAction) {
|
|
11045
|
+
remoteAction = { key: remoteActionKey };
|
|
11046
|
+
remoteActionRegistry.push(remoteAction);
|
|
11047
|
+
}
|
|
11048
|
+
if (remoteAction.pendingWake) {
|
|
11049
|
+
const pendingWake2 = remoteAction.pendingWake;
|
|
11050
|
+
await wakePaperclipIssueAssignee(ctx, {
|
|
11051
|
+
assigneeAgentId: pendingWake2.assigneeAgentId,
|
|
11052
|
+
paperclipIssueId,
|
|
11053
|
+
companyId: mapping.companyId,
|
|
11054
|
+
paperclipApiBaseUrl,
|
|
11055
|
+
reason: pendingWake2.reason,
|
|
11056
|
+
mutation: pendingWake2.mutation,
|
|
11057
|
+
actionFingerprint: pendingWake2.fingerprint,
|
|
11058
|
+
previousStatus: pendingWake2.previousStatus,
|
|
11059
|
+
nextStatus: pendingWake2.nextStatus
|
|
11060
|
+
});
|
|
11061
|
+
delete remoteAction.pendingWake;
|
|
11062
|
+
await persistRemoteActionRegistry();
|
|
11063
|
+
}
|
|
11064
|
+
const currentCommentCounts = pullRequestSnapshots.map((snapshot) => snapshot.commentCounts).filter((counts) => Boolean(counts));
|
|
11065
|
+
let hasTrustedNewComment = false;
|
|
11066
|
+
if (paperclipIssue.status !== "backlog" && remoteAction.linkedPullRequestCommentCounts) {
|
|
11067
|
+
const maintainerCache = /* @__PURE__ */ new Map();
|
|
11068
|
+
for (const snapshot of pullRequestSnapshots) {
|
|
11069
|
+
if (!snapshot.commentCounts) continue;
|
|
11070
|
+
if (await hasTrustedNewLinkedPullRequestComments({
|
|
11071
|
+
octokit,
|
|
11072
|
+
originalPosterLogin: snapshot.authorLogin,
|
|
11073
|
+
previousCommentCounts: remoteAction.linkedPullRequestCommentCounts,
|
|
11074
|
+
currentCommentCounts: [snapshot.commentCounts],
|
|
11075
|
+
maintainerCache
|
|
11076
|
+
})) {
|
|
11077
|
+
hasTrustedNewComment = true;
|
|
11078
|
+
break;
|
|
11079
|
+
}
|
|
11080
|
+
}
|
|
11081
|
+
}
|
|
11082
|
+
const remoteActionFingerprint = buildDirectPullRequestActionFingerprint(pullRequestSnapshots);
|
|
11083
|
+
const actionJournalFingerprint = createHash("sha256").update(JSON.stringify({
|
|
11084
|
+
remoteActionFingerprint,
|
|
11085
|
+
commentCounts: canonicalizeGitHubPullRequestCommentCounts(currentCommentCounts)
|
|
11086
|
+
})).digest("hex");
|
|
10393
11087
|
const paperclipIssueSyncContext = getPaperclipIssueSyncContext(paperclipIssue);
|
|
10394
11088
|
const executorTransitionAssignee = resolvePaperclipIssueExecutorAssignee(
|
|
10395
11089
|
paperclipIssueSyncContext,
|
|
@@ -10398,11 +11092,15 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
|
|
|
10398
11092
|
let nextStatus = resolvePaperclipDirectPullRequestIssueStatus({
|
|
10399
11093
|
currentStatus: paperclipIssue.status,
|
|
10400
11094
|
pullRequests: pullRequestSnapshots,
|
|
10401
|
-
hasExecutorHandoffTarget: Boolean(executorTransitionAssignee)
|
|
11095
|
+
hasExecutorHandoffTarget: Boolean(executorTransitionAssignee),
|
|
11096
|
+
hasTrustedNewComment
|
|
10402
11097
|
});
|
|
10403
11098
|
if (paperclipIssue.status === "blocked" && nextStatus !== "blocked" && pullRequestSnapshots.some((entry) => entry.lifecycleState === "open") && await hasUnresolvedPaperclipIssueBlocker(ctx, paperclipIssue, mapping.companyId)) {
|
|
10404
11099
|
nextStatus = "blocked";
|
|
10405
11100
|
}
|
|
11101
|
+
if (paperclipIssue.status !== nextStatus && remoteAction.fingerprint === remoteActionFingerprint && !hasTrustedNewComment) {
|
|
11102
|
+
nextStatus = paperclipIssue.status;
|
|
11103
|
+
}
|
|
10406
11104
|
const shouldPreserveMaintainerWaitRouting = isHealthyMaintainerWaitTransition({
|
|
10407
11105
|
currentStatus: paperclipIssue.status,
|
|
10408
11106
|
nextStatus,
|
|
@@ -10437,9 +11135,13 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
|
|
|
10437
11135
|
...shouldClearTransitionAssignee ? { clearAssignee: true } : {},
|
|
10438
11136
|
...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
|
|
10439
11137
|
transitionComment: "",
|
|
11138
|
+
actionFingerprint: actionJournalFingerprint,
|
|
10440
11139
|
paperclipApiBaseUrl
|
|
10441
11140
|
});
|
|
10442
11141
|
}
|
|
11142
|
+
remoteAction.fingerprint = remoteActionFingerprint;
|
|
11143
|
+
remoteAction.linkedPullRequestCommentCounts = currentCommentCounts;
|
|
11144
|
+
await persistRemoteActionRegistry();
|
|
10443
11145
|
continue;
|
|
10444
11146
|
}
|
|
10445
11147
|
const transitionComment = buildPaperclipPullRequestIssueStatusTransitionComment({
|
|
@@ -10452,6 +11154,11 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
|
|
|
10452
11154
|
repositoryUrl: primaryRepository?.url,
|
|
10453
11155
|
githubIssueNumber: void 0
|
|
10454
11156
|
});
|
|
11157
|
+
if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" && remoteActionRegistry.filter((record) => record.pendingWake).length >= MAX_REMOTE_ACTION_REGISTRY_RECORDS) {
|
|
11158
|
+
throw new Error(
|
|
11159
|
+
`Remote action registry pending-wake capacity ${MAX_REMOTE_ACTION_REGISTRY_RECORDS} reached; refusing an untracked status transition`
|
|
11160
|
+
);
|
|
11161
|
+
}
|
|
10455
11162
|
await updatePaperclipIssueState(ctx, {
|
|
10456
11163
|
companyId: mapping.companyId,
|
|
10457
11164
|
issueId: paperclipIssueId,
|
|
@@ -10462,17 +11169,37 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
|
|
|
10462
11169
|
...shouldClearTransitionAssignee ? { clearAssignee: true } : {},
|
|
10463
11170
|
...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
|
|
10464
11171
|
transitionComment,
|
|
11172
|
+
actionFingerprint: actionJournalFingerprint,
|
|
10465
11173
|
paperclipApiBaseUrl
|
|
10466
11174
|
});
|
|
11175
|
+
const pendingWake = shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? {
|
|
11176
|
+
fingerprint: remoteActionFingerprint,
|
|
11177
|
+
assigneeAgentId: nextTransitionAssignee.principal.id,
|
|
11178
|
+
reason: STATUS_TRANSITION_WAKE_REASON,
|
|
11179
|
+
mutation: "status_transition",
|
|
11180
|
+
previousStatus: paperclipIssue.status,
|
|
11181
|
+
nextStatus
|
|
11182
|
+
} : void 0;
|
|
11183
|
+
remoteAction.fingerprint = remoteActionFingerprint;
|
|
11184
|
+
remoteAction.linkedPullRequestCommentCounts = currentCommentCounts;
|
|
11185
|
+
if (pendingWake) remoteAction.pendingWake = pendingWake;
|
|
11186
|
+
await persistRemoteActionRegistry();
|
|
10467
11187
|
updatedStatusesCount += 1;
|
|
10468
|
-
if (
|
|
11188
|
+
if (pendingWake) {
|
|
10469
11189
|
queuedIssueWakeups.push({
|
|
10470
|
-
assigneeAgentId:
|
|
11190
|
+
assigneeAgentId: pendingWake.assigneeAgentId,
|
|
10471
11191
|
paperclipIssueId,
|
|
10472
|
-
reason:
|
|
10473
|
-
mutation:
|
|
10474
|
-
|
|
10475
|
-
|
|
11192
|
+
reason: pendingWake.reason,
|
|
11193
|
+
mutation: pendingWake.mutation,
|
|
11194
|
+
actionFingerprint: pendingWake.fingerprint,
|
|
11195
|
+
previousStatus: pendingWake.previousStatus,
|
|
11196
|
+
nextStatus: pendingWake.nextStatus,
|
|
11197
|
+
onSuccess: async () => {
|
|
11198
|
+
if (remoteAction.pendingWake?.fingerprint === pendingWake.fingerprint) {
|
|
11199
|
+
delete remoteAction.pendingWake;
|
|
11200
|
+
await persistRemoteActionRegistry();
|
|
11201
|
+
}
|
|
11202
|
+
}
|
|
10476
11203
|
});
|
|
10477
11204
|
}
|
|
10478
11205
|
} catch (error) {
|
|
@@ -10485,16 +11212,20 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
|
|
|
10485
11212
|
await mapWithConcurrency(
|
|
10486
11213
|
queuedIssueWakeups,
|
|
10487
11214
|
IMPORTED_ISSUE_WAKEUP_CONCURRENCY,
|
|
10488
|
-
async (queuedWakeup) =>
|
|
10489
|
-
|
|
10490
|
-
|
|
10491
|
-
|
|
10492
|
-
|
|
10493
|
-
|
|
10494
|
-
|
|
10495
|
-
|
|
10496
|
-
|
|
10497
|
-
|
|
11215
|
+
async (queuedWakeup) => {
|
|
11216
|
+
await wakePaperclipIssueAssignee(ctx, {
|
|
11217
|
+
assigneeAgentId: queuedWakeup.assigneeAgentId,
|
|
11218
|
+
paperclipIssueId: queuedWakeup.paperclipIssueId,
|
|
11219
|
+
companyId: mapping.companyId,
|
|
11220
|
+
paperclipApiBaseUrl,
|
|
11221
|
+
reason: queuedWakeup.reason,
|
|
11222
|
+
mutation: queuedWakeup.mutation,
|
|
11223
|
+
actionFingerprint: queuedWakeup.actionFingerprint,
|
|
11224
|
+
previousStatus: queuedWakeup.previousStatus,
|
|
11225
|
+
nextStatus: queuedWakeup.nextStatus
|
|
11226
|
+
});
|
|
11227
|
+
await queuedWakeup.onSuccess?.();
|
|
11228
|
+
}
|
|
10498
11229
|
);
|
|
10499
11230
|
return {
|
|
10500
11231
|
updatedStatusesCount
|
|
@@ -14075,6 +14806,12 @@ function mergeNamedValues(currentValues, params) {
|
|
|
14075
14806
|
}
|
|
14076
14807
|
return [...values.values()];
|
|
14077
14808
|
}
|
|
14809
|
+
function sameNamedValues(left, right) {
|
|
14810
|
+
if (left.length !== right.length) return false;
|
|
14811
|
+
const normalizedLeft = left.map((value) => value.toLowerCase()).sort();
|
|
14812
|
+
const normalizedRight = right.map((value) => value.toLowerCase()).sort();
|
|
14813
|
+
return normalizedLeft.every((value, index) => value === normalizedRight[index]);
|
|
14814
|
+
}
|
|
14078
14815
|
async function validateGithubToken(ctx, token) {
|
|
14079
14816
|
const octokit = createGitHubOctokit(ctx, token.trim(), {
|
|
14080
14817
|
logFailures: false,
|
|
@@ -14137,6 +14874,7 @@ async function performSync(ctx, trigger, options = {}) {
|
|
|
14137
14874
|
const config = await getResolvedConfig(ctx);
|
|
14138
14875
|
const settings = materializeScopedSettings(baseSettings, config, targetCompanyId);
|
|
14139
14876
|
const importRegistry = normalizeImportRegistry(await ctx.state.get(IMPORT_REGISTRY_SCOPE));
|
|
14877
|
+
const remoteActionRegistry = normalizeRemoteActionRegistry(await ctx.state.get(REMOTE_ACTION_REGISTRY_SCOPE));
|
|
14140
14878
|
let companyKpiState = normalizeCompanyKpiState(await ctx.state.get(COMPANY_KPI_SCOPE));
|
|
14141
14879
|
let companyKpiStateDirty = false;
|
|
14142
14880
|
const token = typeof options.resolvedToken === "string" ? options.resolvedToken : await resolveGithubToken(ctx, { companyId: targetCompanyId });
|
|
@@ -14146,6 +14884,10 @@ async function performSync(ctx, trigger, options = {}) {
|
|
|
14146
14884
|
const externalLinkAuthMappings = buildExternalLinkAuthMappings(externalSyncWork);
|
|
14147
14885
|
const externalLinkCount = externalSyncWork.issueLinks.length + externalSyncWork.pullRequestLinks.length;
|
|
14148
14886
|
activePaperclipApiAuthTokensByCompanyId = null;
|
|
14887
|
+
activeGitHubPullRequestStatusSnapshotCache.clear();
|
|
14888
|
+
activeGitHubPullRequestStatusSnapshotPromiseCache.clear();
|
|
14889
|
+
activeGitHubPullRequestReviewThreadSummaryCache.clear();
|
|
14890
|
+
activeGitHubPullRequestReviewThreadSummaryPromiseCache.clear();
|
|
14149
14891
|
const failureContext = {
|
|
14150
14892
|
phase: "configuration"
|
|
14151
14893
|
};
|
|
@@ -14686,6 +15428,7 @@ async function performSync(ctx, trigger, options = {}) {
|
|
|
14686
15428
|
repositoryMaintainerCache,
|
|
14687
15429
|
failureContext,
|
|
14688
15430
|
recoverableFailures,
|
|
15431
|
+
async () => ctx.state.set(IMPORT_REGISTRY_SCOPE, nextRegistry),
|
|
14689
15432
|
throwIfSyncCancelled,
|
|
14690
15433
|
async (params) => {
|
|
14691
15434
|
const recorded = recordCompanyActivityMetricEvent(companyKpiState, {
|
|
@@ -14725,6 +15468,12 @@ async function performSync(ctx, trigger, options = {}) {
|
|
|
14725
15468
|
pullRequestStatusCache,
|
|
14726
15469
|
failureContext,
|
|
14727
15470
|
recoverableFailures,
|
|
15471
|
+
remoteActionRegistry,
|
|
15472
|
+
async () => {
|
|
15473
|
+
const compacted = normalizeRemoteActionRegistry(remoteActionRegistry);
|
|
15474
|
+
remoteActionRegistry.splice(0, remoteActionRegistry.length, ...compacted);
|
|
15475
|
+
await ctx.state.set(REMOTE_ACTION_REGISTRY_SCOPE, remoteActionRegistry);
|
|
15476
|
+
},
|
|
14728
15477
|
throwIfSyncCancelled,
|
|
14729
15478
|
async (progress) => {
|
|
14730
15479
|
markTrackedPullRequestIssueProcessed(mapping, progress.pullRequestLink);
|
|
@@ -14804,7 +15553,10 @@ async function performSync(ctx, trigger, options = {}) {
|
|
|
14804
15553
|
...issueLink.data.paperclipProjectId ? { paperclipProjectId: issueLink.data.paperclipProjectId } : {},
|
|
14805
15554
|
companyId
|
|
14806
15555
|
};
|
|
14807
|
-
const
|
|
15556
|
+
const existingImportedIssue = nextRegistry.find(
|
|
15557
|
+
(entry) => entry.paperclipIssueId === issueLink.paperclipIssueId && entry.companyId === companyId && entry.repositoryUrl === repository.url
|
|
15558
|
+
);
|
|
15559
|
+
const importedIssue = existingImportedIssue ?? upsertImportedIssueRecord(nextRegistry, {
|
|
14808
15560
|
mappingId: virtualMapping.id,
|
|
14809
15561
|
githubIssueId: githubIssue.id,
|
|
14810
15562
|
githubIssueNumber: githubIssue.number,
|
|
@@ -14816,7 +15568,10 @@ async function performSync(ctx, trigger, options = {}) {
|
|
|
14816
15568
|
repositoryUrl: repository.url,
|
|
14817
15569
|
...issueLink.data.paperclipProjectId ? { paperclipProjectId: issueLink.data.paperclipProjectId } : {},
|
|
14818
15570
|
companyId
|
|
14819
|
-
};
|
|
15571
|
+
});
|
|
15572
|
+
if (!existingImportedIssue) {
|
|
15573
|
+
await ctx.state.set(IMPORT_REGISTRY_SCOPE, nextRegistry);
|
|
15574
|
+
}
|
|
14820
15575
|
const synchronizationResult = await synchronizePaperclipIssueStatuses(
|
|
14821
15576
|
ctx,
|
|
14822
15577
|
octokit,
|
|
@@ -14834,6 +15589,7 @@ async function performSync(ctx, trigger, options = {}) {
|
|
|
14834
15589
|
repositoryMaintainerCache,
|
|
14835
15590
|
failureContext,
|
|
14836
15591
|
recoverableFailures,
|
|
15592
|
+
async () => ctx.state.set(IMPORT_REGISTRY_SCOPE, nextRegistry),
|
|
14837
15593
|
throwIfSyncCancelled,
|
|
14838
15594
|
async (params) => {
|
|
14839
15595
|
const recorded = recordCompanyActivityMetricEvent(companyKpiState, {
|
|
@@ -14914,6 +15670,12 @@ async function performSync(ctx, trigger, options = {}) {
|
|
|
14914
15670
|
pullRequestStatusCache,
|
|
14915
15671
|
failureContext,
|
|
14916
15672
|
recoverableFailures,
|
|
15673
|
+
remoteActionRegistry,
|
|
15674
|
+
async () => {
|
|
15675
|
+
const compacted = normalizeRemoteActionRegistry(remoteActionRegistry);
|
|
15676
|
+
remoteActionRegistry.splice(0, remoteActionRegistry.length, ...compacted);
|
|
15677
|
+
await ctx.state.set(REMOTE_ACTION_REGISTRY_SCOPE, remoteActionRegistry);
|
|
15678
|
+
},
|
|
14917
15679
|
throwIfSyncCancelled,
|
|
14918
15680
|
async (progress) => {
|
|
14919
15681
|
completedTrackedIssueCount += 1;
|
|
@@ -15132,6 +15894,240 @@ async function startSync(ctx, trigger, options = {}) {
|
|
|
15132
15894
|
return getActiveOrCurrentSyncState(ctx);
|
|
15133
15895
|
}
|
|
15134
15896
|
}
|
|
15897
|
+
async function persistIssueInteractionEvent(ctx, event) {
|
|
15898
|
+
const sanitized = sanitizeIssueInteractionEvent(event);
|
|
15899
|
+
const contentAddress = createHash("sha256").update(JSON.stringify(sanitized)).digest("hex");
|
|
15900
|
+
await ctx.entities.upsert({
|
|
15901
|
+
entityType: ISSUE_INTERACTION_ENTITY_TYPE,
|
|
15902
|
+
scopeKind: "issue",
|
|
15903
|
+
scopeId: sanitized.paperclipIssueId,
|
|
15904
|
+
externalId: `event:${contentAddress}`,
|
|
15905
|
+
title: `${sanitized.source}: ${sanitized.action}`,
|
|
15906
|
+
status: sanitized.outcome,
|
|
15907
|
+
data: { ...sanitized }
|
|
15908
|
+
});
|
|
15909
|
+
}
|
|
15910
|
+
async function listIssueInteractionEvents(ctx, companyId, paperclipIssueId, range) {
|
|
15911
|
+
const byDedupeKey = /* @__PURE__ */ new Map();
|
|
15912
|
+
const conflictingKeys = /* @__PURE__ */ new Set();
|
|
15913
|
+
let malformedRows = 0;
|
|
15914
|
+
let scannedRows = 0;
|
|
15915
|
+
let scanTruncated = false;
|
|
15916
|
+
let ledgerStartedAt = null;
|
|
15917
|
+
const fromMs = Date.parse(range.from);
|
|
15918
|
+
const toMs = Date.parse(range.to);
|
|
15919
|
+
outer: for (let offset = 0; ; ) {
|
|
15920
|
+
const page = await ctx.entities.list({
|
|
15921
|
+
entityType: ISSUE_INTERACTION_ENTITY_TYPE,
|
|
15922
|
+
scopeKind: "issue",
|
|
15923
|
+
scopeId: paperclipIssueId,
|
|
15924
|
+
limit: 100,
|
|
15925
|
+
offset
|
|
15926
|
+
});
|
|
15927
|
+
for (const entry of page) {
|
|
15928
|
+
if (scannedRows >= ISSUE_INTERACTION_MAX_SCAN_ROWS) {
|
|
15929
|
+
scanTruncated = true;
|
|
15930
|
+
break outer;
|
|
15931
|
+
}
|
|
15932
|
+
scannedRows += 1;
|
|
15933
|
+
if (entry.scopeKind !== "issue" || entry.scopeId !== paperclipIssueId) continue;
|
|
15934
|
+
const raw = entry.data;
|
|
15935
|
+
if (raw?.companyId !== companyId || raw?.paperclipIssueId !== paperclipIssueId) continue;
|
|
15936
|
+
try {
|
|
15937
|
+
const event = sanitizeIssueInteractionEvent(raw);
|
|
15938
|
+
if (ledgerStartedAt === null || event.occurredAt < ledgerStartedAt) ledgerStartedAt = event.occurredAt;
|
|
15939
|
+
const serialized = JSON.stringify(event);
|
|
15940
|
+
const existing = byDedupeKey.get(event.dedupeKey);
|
|
15941
|
+
if (existing && existing.serialized !== serialized) conflictingKeys.add(event.dedupeKey);
|
|
15942
|
+
else if (!existing) byDedupeKey.set(event.dedupeKey, { event, serialized });
|
|
15943
|
+
} catch {
|
|
15944
|
+
malformedRows += 1;
|
|
15945
|
+
}
|
|
15946
|
+
}
|
|
15947
|
+
if (page.length < 100) break;
|
|
15948
|
+
offset += page.length;
|
|
15949
|
+
}
|
|
15950
|
+
const events = [...byDedupeKey.entries()].filter(([dedupeKey, { event }]) => {
|
|
15951
|
+
if (conflictingKeys.has(dedupeKey)) return false;
|
|
15952
|
+
const timestamp = Date.parse(event.occurredAt);
|
|
15953
|
+
return timestamp >= fromMs && timestamp < toMs;
|
|
15954
|
+
}).map(([, value]) => value.event);
|
|
15955
|
+
return {
|
|
15956
|
+
events,
|
|
15957
|
+
ledgerStartedAt,
|
|
15958
|
+
integrity: { malformedRows, conflictingKeys: conflictingKeys.size, scanTruncated, scannedRows }
|
|
15959
|
+
};
|
|
15960
|
+
}
|
|
15961
|
+
async function buildIssueInteractionSummaryForTool(ctx, input, runCtx) {
|
|
15962
|
+
const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
|
|
15963
|
+
if (!paperclipIssueId) throw new Error("paperclipIssueId is required.");
|
|
15964
|
+
const issue = await ctx.issues.get(paperclipIssueId, runCtx.companyId);
|
|
15965
|
+
if (!issue) throw new Error("Paperclip issue was not found in the authenticated company.");
|
|
15966
|
+
const range = parseIssueInteractionRange({ from: input.from, to: input.to });
|
|
15967
|
+
const ledger = await listIssueInteractionEvents(ctx, runCtx.companyId, paperclipIssueId, range);
|
|
15968
|
+
return buildIssueInteractionSummary({
|
|
15969
|
+
companyId: runCtx.companyId,
|
|
15970
|
+
paperclipIssueId,
|
|
15971
|
+
range,
|
|
15972
|
+
events: ledger.events,
|
|
15973
|
+
ledgerStartedAt: ledger.ledgerStartedAt,
|
|
15974
|
+
integrity: ledger.integrity
|
|
15975
|
+
});
|
|
15976
|
+
}
|
|
15977
|
+
function trackedMutationOutcome(result) {
|
|
15978
|
+
if (result.error) return "failed";
|
|
15979
|
+
const content = typeof result.content === "string" ? result.content.toLowerCase() : "";
|
|
15980
|
+
if (/\bno (?:github )?.*changes? (?:were )?requested\b/.test(content) || /\bwas already\b/.test(content) || /\bis already\b/.test(content)) {
|
|
15981
|
+
return "noop";
|
|
15982
|
+
}
|
|
15983
|
+
return "changed";
|
|
15984
|
+
}
|
|
15985
|
+
function resolveTrackedMutationRemoteFromInput(input) {
|
|
15986
|
+
const reference = normalizeOptionalToolString(input.reference);
|
|
15987
|
+
const issueReference = reference ? parseGitHubIssueHtmlUrl(reference) : void 0;
|
|
15988
|
+
const pullRequestReference = (reference ? parseGitHubPullRequestHtmlUrl(reference) : void 0) ?? parseGitHubPullRequestHtmlUrl(normalizeOptionalToolString(input.pullRequestUrl) ?? "");
|
|
15989
|
+
const explicitRepository = parseRepositoryReference(normalizeOptionalToolString(input.repository) ?? "");
|
|
15990
|
+
const explicitKind = normalizeIssueGitHubLinkKind(input.kind);
|
|
15991
|
+
const numericReference = normalizePositiveIntegerReference(input.reference);
|
|
15992
|
+
const explicitIssueNumber = normalizeToolPositiveInteger(input.issueNumber);
|
|
15993
|
+
const explicitPullRequestNumber = normalizeToolPositiveInteger(input.pullRequestNumber);
|
|
15994
|
+
let kind;
|
|
15995
|
+
let number;
|
|
15996
|
+
let repository = explicitRepository;
|
|
15997
|
+
if (explicitKind === "issue") {
|
|
15998
|
+
kind = "issue";
|
|
15999
|
+
number = issueReference?.issueNumber ?? numericReference ?? explicitIssueNumber;
|
|
16000
|
+
repository = parseRepositoryReference(issueReference?.repositoryUrl ?? "") ?? explicitRepository;
|
|
16001
|
+
} else if (explicitKind === "pull_request") {
|
|
16002
|
+
kind = "pull_request";
|
|
16003
|
+
number = pullRequestReference?.pullRequestNumber ?? explicitPullRequestNumber ?? numericReference;
|
|
16004
|
+
repository = parseRepositoryReference(pullRequestReference?.repositoryUrl ?? "") ?? explicitRepository;
|
|
16005
|
+
} else if (issueReference || explicitIssueNumber) {
|
|
16006
|
+
kind = "issue";
|
|
16007
|
+
number = issueReference?.issueNumber ?? explicitIssueNumber;
|
|
16008
|
+
repository = parseRepositoryReference(issueReference?.repositoryUrl ?? "") ?? explicitRepository;
|
|
16009
|
+
} else if (pullRequestReference || explicitPullRequestNumber) {
|
|
16010
|
+
kind = "pull_request";
|
|
16011
|
+
number = pullRequestReference?.pullRequestNumber ?? explicitPullRequestNumber;
|
|
16012
|
+
repository = parseRepositoryReference(pullRequestReference?.repositoryUrl ?? "") ?? explicitRepository;
|
|
16013
|
+
}
|
|
16014
|
+
if (!repository && !kind && !number) return void 0;
|
|
16015
|
+
return { repositoryUrl: repository?.url, kind, number };
|
|
16016
|
+
}
|
|
16017
|
+
var TRACKED_ISSUE_MUTATIONS = /* @__PURE__ */ new Set([
|
|
16018
|
+
"update_issue",
|
|
16019
|
+
"assign_to_current_user",
|
|
16020
|
+
"add_issue_comment"
|
|
16021
|
+
]);
|
|
16022
|
+
var TRACKED_PULL_REQUEST_MUTATIONS = /* @__PURE__ */ new Set([
|
|
16023
|
+
"update_pull_request",
|
|
16024
|
+
"request_pull_request_reviewers",
|
|
16025
|
+
"add_pull_request_to_project",
|
|
16026
|
+
"upload_pull_request_asset"
|
|
16027
|
+
]);
|
|
16028
|
+
async function resolveTrackedMutationRemote(ctx, action, input, runCtx) {
|
|
16029
|
+
const fallback = resolveTrackedMutationRemoteFromInput(input);
|
|
16030
|
+
try {
|
|
16031
|
+
if (TRACKED_ISSUE_MUTATIONS.has(action)) {
|
|
16032
|
+
const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
|
|
16033
|
+
return { repositoryUrl: target.repository.url, kind: "issue", number: target.issueNumber };
|
|
16034
|
+
}
|
|
16035
|
+
if (TRACKED_PULL_REQUEST_MUTATIONS.has(action)) {
|
|
16036
|
+
const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
|
|
16037
|
+
return { repositoryUrl: target.repository.url, kind: "pull_request", number: target.pullRequestNumber };
|
|
16038
|
+
}
|
|
16039
|
+
if (action === "create_pull_request") {
|
|
16040
|
+
const explicitRepository = parseRepositoryReference(normalizeOptionalToolString(input.repository) ?? "");
|
|
16041
|
+
const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
|
|
16042
|
+
const repository = explicitRepository ?? (paperclipIssueId ? (await resolveIssueGitHubLinkMapping(ctx, { companyId: runCtx.companyId, issueId: paperclipIssueId })).repository : void 0);
|
|
16043
|
+
if (repository) return { repositoryUrl: repository.url, kind: "pull_request" };
|
|
16044
|
+
}
|
|
16045
|
+
} catch {
|
|
16046
|
+
}
|
|
16047
|
+
return fallback;
|
|
16048
|
+
}
|
|
16049
|
+
function resolveTrackedMutationResultRemote(result, fallback) {
|
|
16050
|
+
const data = result.data && typeof result.data === "object" ? result.data : {};
|
|
16051
|
+
const pullRequest = data.pullRequest && typeof data.pullRequest === "object" ? data.pullRequest : {};
|
|
16052
|
+
const issue = data.issue && typeof data.issue === "object" ? data.issue : {};
|
|
16053
|
+
const repository = parseRepositoryReference(
|
|
16054
|
+
normalizeOptionalToolString(data.repository) ?? normalizeOptionalToolString(data.repositoryUrl) ?? fallback?.repositoryUrl ?? ""
|
|
16055
|
+
);
|
|
16056
|
+
const pullRequestNumber = normalizeToolPositiveInteger(data.pullRequestNumber) ?? normalizeToolPositiveInteger(data.githubPullRequestNumber) ?? normalizeToolPositiveInteger(pullRequest.number);
|
|
16057
|
+
const issueNumber = normalizeToolPositiveInteger(data.issueNumber) ?? normalizeToolPositiveInteger(data.githubIssueNumber) ?? normalizeToolPositiveInteger(issue.number);
|
|
16058
|
+
const kind = pullRequestNumber ? "pull_request" : issueNumber ? "issue" : fallback?.kind;
|
|
16059
|
+
const number = kind === "pull_request" ? pullRequestNumber ?? fallback?.number : kind === "issue" ? issueNumber ?? fallback?.number : fallback?.number;
|
|
16060
|
+
if (!repository && !kind && !number) return void 0;
|
|
16061
|
+
return { repositoryUrl: repository?.url, kind, number };
|
|
16062
|
+
}
|
|
16063
|
+
async function executeTrackedGitHubMutation(ctx, action, params, runCtx, fn) {
|
|
16064
|
+
return executeGitHubTool(async () => {
|
|
16065
|
+
const input = getToolInputRecord(params);
|
|
16066
|
+
const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
|
|
16067
|
+
if (paperclipIssueId && !await ctx.issues.get(paperclipIssueId, runCtx.companyId)) {
|
|
16068
|
+
throw new Error("Paperclip issue was not found in the authenticated company.");
|
|
16069
|
+
}
|
|
16070
|
+
const startedAt = /* @__PURE__ */ new Date();
|
|
16071
|
+
if (!paperclipIssueId) return fn();
|
|
16072
|
+
const runRecord = runCtx;
|
|
16073
|
+
const fingerprintInput = JSON.stringify(input, Object.keys(input).sort());
|
|
16074
|
+
const fingerprint = createHash("sha256").update(fingerprintInput).digest("hex").slice(0, 24);
|
|
16075
|
+
const runId = normalizeOptionalToolString(runRecord.runId);
|
|
16076
|
+
const remote = await resolveTrackedMutationRemote(ctx, action, input, runCtx);
|
|
16077
|
+
const attemptId = createHash("sha256").update([runId ?? "no-run-id", action, fingerprint, startedAt.toISOString(), randomUUID()].join("\n")).digest("hex");
|
|
16078
|
+
const dedupeBase = `agent_tool:${attemptId}`;
|
|
16079
|
+
await persistIssueInteractionEvent(ctx, {
|
|
16080
|
+
schemaVersion: 1,
|
|
16081
|
+
companyId: runCtx.companyId,
|
|
16082
|
+
paperclipIssueId,
|
|
16083
|
+
occurredAt: startedAt.toISOString(),
|
|
16084
|
+
category: action === "link_github_item" ? "paperclip_link" : action.includes("comment") || action.includes("reply") ? "comment" : "github_write",
|
|
16085
|
+
action,
|
|
16086
|
+
source: "agent_tool",
|
|
16087
|
+
actor: {
|
|
16088
|
+
agentId: normalizeOptionalToolString(runRecord.agentId),
|
|
16089
|
+
runId,
|
|
16090
|
+
llmModel: normalizeOptionalToolString(input.llmModel)
|
|
16091
|
+
},
|
|
16092
|
+
...remote ? { remote } : {},
|
|
16093
|
+
outcome: "observed",
|
|
16094
|
+
durationMs: 0,
|
|
16095
|
+
dedupeKey: `${dedupeBase}:intent`
|
|
16096
|
+
});
|
|
16097
|
+
const result = await executeGitHubTool(fn);
|
|
16098
|
+
const resultRemote = resolveTrackedMutationResultRemote(result, remote);
|
|
16099
|
+
const durationMs = Math.max(0, Date.now() - startedAt.getTime());
|
|
16100
|
+
try {
|
|
16101
|
+
await persistIssueInteractionEvent(ctx, {
|
|
16102
|
+
schemaVersion: 1,
|
|
16103
|
+
companyId: runCtx.companyId,
|
|
16104
|
+
paperclipIssueId,
|
|
16105
|
+
occurredAt: startedAt.toISOString(),
|
|
16106
|
+
category: action === "link_github_item" ? "paperclip_link" : action.includes("comment") || action.includes("reply") ? "comment" : "github_write",
|
|
16107
|
+
action,
|
|
16108
|
+
source: "agent_tool",
|
|
16109
|
+
actor: {
|
|
16110
|
+
agentId: normalizeOptionalToolString(runRecord.agentId),
|
|
16111
|
+
runId,
|
|
16112
|
+
llmModel: normalizeOptionalToolString(input.llmModel)
|
|
16113
|
+
},
|
|
16114
|
+
...resultRemote ? { remote: resultRemote } : {},
|
|
16115
|
+
outcome: trackedMutationOutcome(result),
|
|
16116
|
+
durationMs,
|
|
16117
|
+
dedupeKey: `${dedupeBase}:result`
|
|
16118
|
+
});
|
|
16119
|
+
} catch (persistenceError) {
|
|
16120
|
+
if (result.error) {
|
|
16121
|
+
throw new AggregateError(
|
|
16122
|
+
[new Error(result.error), persistenceError],
|
|
16123
|
+
`GitHub mutation failed (${result.error}) and its result could not be persisted: ${getErrorMessage(persistenceError)}`
|
|
16124
|
+
);
|
|
16125
|
+
}
|
|
16126
|
+
throw persistenceError;
|
|
16127
|
+
}
|
|
16128
|
+
return result;
|
|
16129
|
+
});
|
|
16130
|
+
}
|
|
15135
16131
|
function resolveTrustedWorkspacePath(workspacePath, workspaceRelativePath) {
|
|
15136
16132
|
if (!workspaceRelativePath) {
|
|
15137
16133
|
return workspacePath;
|
|
@@ -15290,7 +16286,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15290
16286
|
ctx.tools.register(
|
|
15291
16287
|
"update_issue",
|
|
15292
16288
|
getGitHubAgentToolDeclaration("update_issue"),
|
|
15293
|
-
async (params, runCtx) =>
|
|
16289
|
+
async (params, runCtx) => executeTrackedGitHubMutation(ctx, "update_issue", params, runCtx, async () => {
|
|
15294
16290
|
const input = getToolInputRecord(params);
|
|
15295
16291
|
const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
|
|
15296
16292
|
const octokit = await createAgentToolOctokit(runCtx, "update_issue", target.repository);
|
|
@@ -15320,7 +16316,9 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15320
16316
|
const body = Object.prototype.hasOwnProperty.call(input, "body") && typeof input.body === "string" ? appendOptionalAiAuthorshipFooter(input.body, "issue description", llmModel) : void 0;
|
|
15321
16317
|
const state = input.state === "open" || input.state === "closed" ? input.state : void 0;
|
|
15322
16318
|
const milestoneNumber = Object.prototype.hasOwnProperty.call(input, "milestoneNumber") ? input.milestoneNumber === null ? null : normalizeToolPositiveInteger(input.milestoneNumber) : void 0;
|
|
15323
|
-
const
|
|
16319
|
+
const milestoneRequested = Object.prototype.hasOwnProperty.call(input, "milestoneNumber");
|
|
16320
|
+
const currentMilestoneNumber = currentIssue.milestone?.number ?? null;
|
|
16321
|
+
const hasChanges = title !== void 0 && title !== currentIssue.title || body !== void 0 && body !== (currentIssue.body ?? "") || state !== void 0 && state !== currentIssue.state || milestoneRequested && milestoneNumber !== currentMilestoneNumber || !sameNamedValues(nextLabels, currentLabels) || !sameNamedValues(nextAssignees, currentAssignees);
|
|
15324
16322
|
const updatedResponse = hasChanges ? await octokit.rest.issues.update({
|
|
15325
16323
|
owner: target.repository.owner,
|
|
15326
16324
|
repo: target.repository.repo,
|
|
@@ -15328,7 +16326,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15328
16326
|
...title !== void 0 ? { title } : {},
|
|
15329
16327
|
...body !== void 0 ? { body } : {},
|
|
15330
16328
|
...state ? { state } : {},
|
|
15331
|
-
...
|
|
16329
|
+
...milestoneRequested ? { milestone: milestoneNumber } : {},
|
|
15332
16330
|
labels: nextLabels,
|
|
15333
16331
|
assignees: nextAssignees,
|
|
15334
16332
|
headers: {
|
|
@@ -15363,7 +16361,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15363
16361
|
ctx.tools.register(
|
|
15364
16362
|
"assign_to_current_user",
|
|
15365
16363
|
getGitHubAgentToolDeclaration("assign_to_current_user"),
|
|
15366
|
-
async (params, runCtx) =>
|
|
16364
|
+
async (params, runCtx) => executeTrackedGitHubMutation(ctx, "assign_to_current_user", params, runCtx, async () => {
|
|
15367
16365
|
const input = getToolInputRecord(params);
|
|
15368
16366
|
const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
|
|
15369
16367
|
const octokit = await createAgentToolOctokit(runCtx, "assign_to_current_user", target.repository);
|
|
@@ -15423,7 +16421,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15423
16421
|
ctx.tools.register(
|
|
15424
16422
|
"add_issue_comment",
|
|
15425
16423
|
getGitHubAgentToolDeclaration("add_issue_comment"),
|
|
15426
|
-
async (params, runCtx) =>
|
|
16424
|
+
async (params, runCtx) => executeTrackedGitHubMutation(ctx, "add_issue_comment", params, runCtx, async () => {
|
|
15427
16425
|
const input = getToolInputRecord(params);
|
|
15428
16426
|
const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
|
|
15429
16427
|
const octokit = await createAgentToolOctokit(runCtx, "add_issue_comment", target.repository);
|
|
@@ -15456,7 +16454,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15456
16454
|
ctx.tools.register(
|
|
15457
16455
|
"create_pull_request",
|
|
15458
16456
|
getGitHubAgentToolDeclaration("create_pull_request"),
|
|
15459
|
-
async (params, runCtx) =>
|
|
16457
|
+
async (params, runCtx) => executeTrackedGitHubMutation(ctx, "create_pull_request", params, runCtx, async () => {
|
|
15460
16458
|
const input = getToolInputRecord(params);
|
|
15461
16459
|
const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
|
|
15462
16460
|
const explicitRepository = normalizeOptionalToolString(input.repository);
|
|
@@ -15673,7 +16671,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15673
16671
|
ctx.tools.register(
|
|
15674
16672
|
"update_pull_request",
|
|
15675
16673
|
getGitHubAgentToolDeclaration("update_pull_request"),
|
|
15676
|
-
async (params, runCtx) =>
|
|
16674
|
+
async (params, runCtx) => executeTrackedGitHubMutation(ctx, "update_pull_request", params, runCtx, async () => {
|
|
15677
16675
|
const input = getToolInputRecord(params);
|
|
15678
16676
|
const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
|
|
15679
16677
|
const octokit = await createAgentToolOctokit(runCtx, "update_pull_request", target.repository);
|
|
@@ -15691,25 +16689,31 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15691
16689
|
const base = normalizeOptionalToolString(input.base);
|
|
15692
16690
|
const state = input.state === "open" || input.state === "closed" ? input.state : void 0;
|
|
15693
16691
|
const isDraft = typeof input.isDraft === "boolean" ? input.isDraft : void 0;
|
|
15694
|
-
|
|
16692
|
+
let changed = false;
|
|
16693
|
+
const update = {
|
|
16694
|
+
...title !== void 0 && title !== currentResponse.data.title ? { title } : {},
|
|
16695
|
+
...body !== void 0 && body !== (currentResponse.data.body ?? "") ? { body } : {},
|
|
16696
|
+
...base !== void 0 && base !== currentResponse.data.base.ref ? { base } : {},
|
|
16697
|
+
...state !== void 0 && state !== currentResponse.data.state ? { state } : {}
|
|
16698
|
+
};
|
|
16699
|
+
if (Object.keys(update).length > 0) {
|
|
15695
16700
|
currentResponse = await octokit.rest.pulls.update({
|
|
15696
16701
|
owner: target.repository.owner,
|
|
15697
16702
|
repo: target.repository.repo,
|
|
15698
16703
|
pull_number: target.pullRequestNumber,
|
|
15699
|
-
...
|
|
15700
|
-
...body !== void 0 ? { body } : {},
|
|
15701
|
-
...base !== void 0 ? { base } : {},
|
|
15702
|
-
...state !== void 0 ? { state } : {},
|
|
16704
|
+
...update,
|
|
15703
16705
|
headers: {
|
|
15704
16706
|
"X-GitHub-Api-Version": GITHUB_API_VERSION
|
|
15705
16707
|
}
|
|
15706
16708
|
});
|
|
16709
|
+
changed = true;
|
|
15707
16710
|
}
|
|
15708
16711
|
if (isDraft !== void 0 && currentResponse.data.draft !== isDraft) {
|
|
15709
16712
|
if (!currentResponse.data.node_id) {
|
|
15710
16713
|
throw new Error("GitHub did not return a pull request node id, so draft state cannot be updated.");
|
|
15711
16714
|
}
|
|
15712
16715
|
await updatePullRequestDraftState(octokit, currentResponse.data.node_id, isDraft);
|
|
16716
|
+
changed = true;
|
|
15713
16717
|
currentResponse = await octokit.rest.pulls.get({
|
|
15714
16718
|
owner: target.repository.owner,
|
|
15715
16719
|
repo: target.repository.repo,
|
|
@@ -15720,7 +16724,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15720
16724
|
});
|
|
15721
16725
|
}
|
|
15722
16726
|
return buildToolSuccessResult(
|
|
15723
|
-
`Updated pull request #${currentResponse.data.number} in ${formatRepositoryLabel(target.repository)}.`,
|
|
16727
|
+
changed ? `Updated pull request #${currentResponse.data.number} in ${formatRepositoryLabel(target.repository)}.` : `No GitHub pull request changes were requested for #${currentResponse.data.number} in ${formatRepositoryLabel(target.repository)}.`,
|
|
15724
16728
|
{
|
|
15725
16729
|
repository: target.repository.url,
|
|
15726
16730
|
pullRequest: {
|
|
@@ -15874,7 +16878,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15874
16878
|
ctx.tools.register(
|
|
15875
16879
|
"reply_to_review_thread",
|
|
15876
16880
|
getGitHubAgentToolDeclaration("reply_to_review_thread"),
|
|
15877
|
-
async (params, runCtx) =>
|
|
16881
|
+
async (params, runCtx) => executeTrackedGitHubMutation(ctx, "reply_to_review_thread", params, runCtx, async () => {
|
|
15878
16882
|
const input = getToolInputRecord(params);
|
|
15879
16883
|
const threadId = normalizeOptionalToolString(input.threadId);
|
|
15880
16884
|
if (!threadId) {
|
|
@@ -15910,7 +16914,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15910
16914
|
ctx.tools.register(
|
|
15911
16915
|
"resolve_review_thread",
|
|
15912
16916
|
getGitHubAgentToolDeclaration("resolve_review_thread"),
|
|
15913
|
-
async (params, runCtx) =>
|
|
16917
|
+
async (params, runCtx) => executeTrackedGitHubMutation(ctx, "resolve_review_thread", params, runCtx, async () => {
|
|
15914
16918
|
const input = getToolInputRecord(params);
|
|
15915
16919
|
const threadId = normalizeOptionalToolString(input.threadId);
|
|
15916
16920
|
if (!threadId) {
|
|
@@ -15941,7 +16945,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15941
16945
|
ctx.tools.register(
|
|
15942
16946
|
"unresolve_review_thread",
|
|
15943
16947
|
getGitHubAgentToolDeclaration("unresolve_review_thread"),
|
|
15944
|
-
async (params, runCtx) =>
|
|
16948
|
+
async (params, runCtx) => executeTrackedGitHubMutation(ctx, "unresolve_review_thread", params, runCtx, async () => {
|
|
15945
16949
|
const input = getToolInputRecord(params);
|
|
15946
16950
|
const threadId = normalizeOptionalToolString(input.threadId);
|
|
15947
16951
|
if (!threadId) {
|
|
@@ -15972,7 +16976,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
15972
16976
|
ctx.tools.register(
|
|
15973
16977
|
"request_pull_request_reviewers",
|
|
15974
16978
|
getGitHubAgentToolDeclaration("request_pull_request_reviewers"),
|
|
15975
|
-
async (params, runCtx) =>
|
|
16979
|
+
async (params, runCtx) => executeTrackedGitHubMutation(ctx, "request_pull_request_reviewers", params, runCtx, async () => {
|
|
15976
16980
|
const input = getToolInputRecord(params);
|
|
15977
16981
|
const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
|
|
15978
16982
|
const userReviewers = normalizeToolStringArray(input.userReviewers);
|
|
@@ -16029,7 +17033,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
16029
17033
|
ctx.tools.register(
|
|
16030
17034
|
"add_pull_request_to_project",
|
|
16031
17035
|
getGitHubAgentToolDeclaration("add_pull_request_to_project"),
|
|
16032
|
-
async (params, runCtx) =>
|
|
17036
|
+
async (params, runCtx) => executeTrackedGitHubMutation(ctx, "add_pull_request_to_project", params, runCtx, async () => {
|
|
16033
17037
|
const input = getToolInputRecord(params);
|
|
16034
17038
|
const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
|
|
16035
17039
|
const octokit = await createAgentToolOctokit(runCtx, "add_pull_request_to_project", target.repository);
|
|
@@ -16090,7 +17094,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
16090
17094
|
ctx.tools.register(
|
|
16091
17095
|
"upload_pull_request_asset",
|
|
16092
17096
|
getGitHubAgentToolDeclaration("upload_pull_request_asset"),
|
|
16093
|
-
async (params, runCtx) =>
|
|
17097
|
+
async (params, runCtx) => executeTrackedGitHubMutation(ctx, "upload_pull_request_asset", params, runCtx, async () => {
|
|
16094
17098
|
const input = getToolInputRecord(params);
|
|
16095
17099
|
const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
|
|
16096
17100
|
const octokit = await createAgentToolOctokit(runCtx, "upload_pull_request_asset", target.repository);
|
|
@@ -16111,7 +17115,7 @@ function registerGitHubAgentTools(ctx) {
|
|
|
16111
17115
|
ctx.tools.register(
|
|
16112
17116
|
"link_github_item",
|
|
16113
17117
|
getGitHubAgentToolDeclaration("link_github_item"),
|
|
16114
|
-
async (params, runCtx) =>
|
|
17118
|
+
async (params, runCtx) => executeTrackedGitHubMutation(ctx, "link_github_item", params, runCtx, async () => {
|
|
16115
17119
|
const input = getToolInputRecord(params);
|
|
16116
17120
|
const kind = normalizeIssueGitHubLinkKind(input.kind);
|
|
16117
17121
|
if (!kind) {
|
|
@@ -16144,6 +17148,17 @@ function registerGitHubAgentTools(ctx) {
|
|
|
16144
17148
|
);
|
|
16145
17149
|
})
|
|
16146
17150
|
);
|
|
17151
|
+
ctx.tools.register(
|
|
17152
|
+
"get_issue_interaction_summary",
|
|
17153
|
+
getGitHubAgentToolDeclaration("get_issue_interaction_summary"),
|
|
17154
|
+
async (params, runCtx) => executeGitHubTool(async () => {
|
|
17155
|
+
const summary = await buildIssueInteractionSummaryForTool(ctx, getToolInputRecord(params), runCtx);
|
|
17156
|
+
return buildToolSuccessResult(
|
|
17157
|
+
`Loaded ${summary.counts.events} captured interactions for Paperclip issue ${summary.paperclipIssueId}.`,
|
|
17158
|
+
{ summary }
|
|
17159
|
+
);
|
|
17160
|
+
})
|
|
17161
|
+
);
|
|
16147
17162
|
}
|
|
16148
17163
|
function shouldStartWorkerHost(moduleUrl, entry = process.argv[1]) {
|
|
16149
17164
|
if (typeof entry !== "string" || !entry.trim()) {
|
|
@@ -16157,16 +17172,25 @@ function shouldStartWorkerHost(moduleUrl, entry = process.argv[1]) {
|
|
|
16157
17172
|
}
|
|
16158
17173
|
}
|
|
16159
17174
|
var __testing = {
|
|
17175
|
+
buildDirectPullRequestActionFingerprint,
|
|
17176
|
+
buildRemoteActionFingerprint,
|
|
17177
|
+
canonicalizeGitHubPullRequestCommentCounts,
|
|
16160
17178
|
buildSyncFallbackExecutionStatePatch,
|
|
16161
17179
|
createGitHubToolOctokit,
|
|
16162
17180
|
formatPaperclipApiFetchErrorMessage,
|
|
16163
17181
|
hasUnresolvedPaperclipIssueBlocker,
|
|
16164
17182
|
isHealthyMaintainerWaitTransition,
|
|
17183
|
+
normalizeImportRegistry,
|
|
17184
|
+
normalizeRemoteActionRegistry,
|
|
17185
|
+
persistIssueInteractionEvent,
|
|
17186
|
+
trackedMutationOutcome,
|
|
16165
17187
|
resolvePaperclipApiAuthTokens,
|
|
16166
17188
|
resolveGithubToken,
|
|
16167
17189
|
resolvePaperclipPullRequestIssueStatus,
|
|
16168
17190
|
resolveSyncTransitionAssignee,
|
|
16169
17191
|
resolveTrustedWorkspacePath,
|
|
17192
|
+
updatePaperclipIssueState,
|
|
17193
|
+
wakePaperclipIssueAssignee,
|
|
16170
17194
|
setCreatePullRequestBranchPublisher(publisher) {
|
|
16171
17195
|
createPullRequestBranchPublisher = publisher ?? publishLocalBranchForPullRequest;
|
|
16172
17196
|
}
|