paperclip-github-plugin 0.15.1 → 0.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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) => entry.dedupeKey.endsWith(":result")).map((entry) => entry.dedupeKey.slice(0, -":result".length)));
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 = 4;
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;
@@ -1278,6 +1534,7 @@ var GITHUB_PULL_REQUEST_CI_CONTEXTS_QUERY = `
1278
1534
  query GitHubPullRequestCiContexts($owner: String!, $repo: String!, $pullRequestNumber: Int!, $after: String) {
1279
1535
  repository(owner: $owner, name: $repo) {
1280
1536
  pullRequest(number: $pullRequestNumber) {
1537
+ headRefOid
1281
1538
  mergeable
1282
1539
  mergeStateStatus
1283
1540
  reviewDecision
@@ -1344,6 +1601,7 @@ var GITHUB_REPOSITORY_OPEN_PULL_REQUEST_STATUSES_QUERY = `
1344
1601
  }
1345
1602
  nodes {
1346
1603
  number
1604
+ headRefOid
1347
1605
  mergeable
1348
1606
  mergeStateStatus
1349
1607
  reviewDecision
@@ -5071,6 +5329,8 @@ function normalizeImportRegistry(value) {
5071
5329
  const linkedPullRequestCommentCounts = normalizeGitHubPullRequestCommentCountRecords(
5072
5330
  record.linkedPullRequestCommentCounts
5073
5331
  );
5332
+ const remoteActionFingerprint = typeof record.remoteActionFingerprint === "string" && /^[a-f0-9]{64}$/.test(record.remoteActionFingerprint) ? record.remoteActionFingerprint : void 0;
5333
+ const pendingRemoteActionWake = normalizePendingRemoteActionWake(record.pendingRemoteActionWake);
5074
5334
  if (!mappingId || Number.isNaN(githubIssueId) || !paperclipIssueId || !importedAt) {
5075
5335
  return null;
5076
5336
  }
@@ -5085,10 +5345,66 @@ function normalizeImportRegistry(value) {
5085
5345
  ...companyId ? { companyId } : {},
5086
5346
  ...lastSeenCommentCount !== void 0 ? { lastSeenCommentCount } : {},
5087
5347
  ...lastSeenGitHubState ? { lastSeenGitHubState } : {},
5088
- ...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : {}
5348
+ ...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : {},
5349
+ ...remoteActionFingerprint ? { remoteActionFingerprint } : {},
5350
+ ...pendingRemoteActionWake ? { pendingRemoteActionWake } : {}
5089
5351
  };
5090
5352
  }).filter((entry) => entry !== null);
5091
5353
  }
5354
+ function normalizePendingRemoteActionWake(value) {
5355
+ if (!value || typeof value !== "object") return void 0;
5356
+ const record = value;
5357
+ const fingerprint = typeof record.fingerprint === "string" && /^[a-f0-9]{64}$/.test(record.fingerprint) ? record.fingerprint : void 0;
5358
+ const assigneeAgentId = normalizeOptionalString2(record.assigneeAgentId);
5359
+ const reason = normalizeOptionalString2(record.reason);
5360
+ const mutation = record.mutation === "import" ? "import" : "status_transition";
5361
+ const previousStatus = normalizePaperclipIssueStatus(record.previousStatus);
5362
+ const nextStatus = normalizePaperclipIssueStatus(record.nextStatus);
5363
+ if (!fingerprint || !assigneeAgentId || !reason) return void 0;
5364
+ return {
5365
+ fingerprint,
5366
+ assigneeAgentId,
5367
+ reason: reason.slice(0, 500),
5368
+ mutation,
5369
+ ...previousStatus ? { previousStatus } : {},
5370
+ ...nextStatus ? { nextStatus } : {}
5371
+ };
5372
+ }
5373
+ function normalizeRemoteActionRegistry(value) {
5374
+ if (!Array.isArray(value)) return [];
5375
+ const recordsByKey = /* @__PURE__ */ new Map();
5376
+ for (const entry of value) {
5377
+ if (!entry || typeof entry !== "object") continue;
5378
+ const record = entry;
5379
+ const key = normalizeOptionalString2(record.key);
5380
+ if (!key || key.length > 500) continue;
5381
+ const fingerprint = typeof record.fingerprint === "string" && /^[a-f0-9]{64}$/.test(record.fingerprint) ? record.fingerprint : void 0;
5382
+ const pendingWake = normalizePendingRemoteActionWake(record.pendingWake);
5383
+ const linkedPullRequestCommentCounts = normalizeGitHubPullRequestCommentCountRecords(
5384
+ record.linkedPullRequestCommentCounts
5385
+ );
5386
+ const previous = recordsByKey.get(key);
5387
+ recordsByKey.set(key, {
5388
+ key,
5389
+ ...fingerprint ? { fingerprint } : previous?.fingerprint ? { fingerprint: previous.fingerprint } : {},
5390
+ ...pendingWake ? { pendingWake } : previous?.pendingWake ? { pendingWake: previous.pendingWake } : {},
5391
+ ...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : previous?.linkedPullRequestCommentCounts ? { linkedPullRequestCommentCounts: previous.linkedPullRequestCommentCounts } : {}
5392
+ });
5393
+ }
5394
+ const records = [...recordsByKey.values()];
5395
+ const pendingRecords = records.filter((record) => record.pendingWake).sort((left, right) => left.key.localeCompare(right.key));
5396
+ if (pendingRecords.length > MAX_REMOTE_ACTION_REGISTRY_RECORDS) {
5397
+ throw new Error(
5398
+ `Remote action registry contains ${pendingRecords.length} pending wakes; maximum is ${MAX_REMOTE_ACTION_REGISTRY_RECORDS}`
5399
+ );
5400
+ }
5401
+ const retainedKeys = new Set(pendingRecords.map((record) => record.key));
5402
+ for (const record of records.sort((left, right) => left.key.localeCompare(right.key))) {
5403
+ if (retainedKeys.size >= MAX_REMOTE_ACTION_REGISTRY_RECORDS) break;
5404
+ retainedKeys.add(record.key);
5405
+ }
5406
+ return records.filter((record) => retainedKeys.has(record.key)).sort((left, right) => left.key.localeCompare(right.key));
5407
+ }
5092
5408
  function normalizeExternalGitHubLinkCompanyIndex(value) {
5093
5409
  const rawCompanyIds = Array.isArray(value) ? value : value && typeof value === "object" && Array.isArray(value.companyIds) ? value.companyIds : [];
5094
5410
  const companyIds = [
@@ -5990,7 +6306,7 @@ function isHealthyMaintainerWaitTransition(params) {
5990
6306
  return nextStatus === "in_review" && (currentStatus === "done" || currentStatus === "in_review") && isClearableMaintainerWaitExecutionState(syncContext.executionState);
5991
6307
  }
5992
6308
  function isClearableMaintainerWaitExecutionState(executionState) {
5993
- if (executionState === null) {
6309
+ if (executionState === null || executionState.status === "completed") {
5994
6310
  return true;
5995
6311
  }
5996
6312
  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 +6549,12 @@ function resolvePaperclipPullRequestIssueStatus(params) {
6233
6549
  });
6234
6550
  }
6235
6551
  function resolvePaperclipDirectPullRequestIssueStatus(params) {
6236
- const { currentStatus, pullRequests, hasExecutorHandoffTarget } = params;
6552
+ const { currentStatus, pullRequests, hasExecutorHandoffTarget, hasTrustedNewComment } = params;
6237
6553
  const openPullRequests = pullRequests.map((entry) => entry.pullRequest).filter((pullRequest) => Boolean(pullRequest));
6238
6554
  if (openPullRequests.length > 0) {
6555
+ if (hasTrustedNewComment) {
6556
+ return currentStatus === "backlog" ? "backlog" : hasExecutorHandoffTarget ? "in_progress" : "todo";
6557
+ }
6239
6558
  if (shouldPreserveBlockedExternalPullRequestWait({
6240
6559
  currentStatus,
6241
6560
  linkedPullRequests: openPullRequests
@@ -6457,6 +6776,7 @@ function tryBuildGitHubPullRequestStatusSnapshotFromBatchNode(node, repository)
6457
6776
  return {
6458
6777
  number: node.number,
6459
6778
  repositoryUrl: repository.url,
6779
+ ...typeof node.headRefOid === "string" && node.headRefOid.trim() ? { headSha: node.headRefOid.trim().toLowerCase() } : {},
6460
6780
  hasUnresolvedReviewThreads: reviewThreadSummary.unresolvedReviewThreads > 0,
6461
6781
  ciState,
6462
6782
  mergeability: normalizeGitHubPullRequestMergeability(node.mergeable),
@@ -6516,6 +6836,7 @@ async function getGitHubPullRequestCiState(octokit, repository, pullRequestNumbe
6516
6836
  }
6517
6837
  async function getGitHubPullRequestCiSnapshot(octokit, repository, pullRequestNumber) {
6518
6838
  const contexts = [];
6839
+ let headSha;
6519
6840
  let mergeability = "unknown";
6520
6841
  let mergeStateStatus = "unknown";
6521
6842
  let reviewDecision = "unknown";
@@ -6530,6 +6851,10 @@ async function getGitHubPullRequestCiSnapshot(octokit, repository, pullRequestNu
6530
6851
  mergeability = normalizeGitHubPullRequestMergeability(response.repository?.pullRequest?.mergeable);
6531
6852
  mergeStateStatus = normalizeGitHubPullRequestMergeStateStatus(response.repository?.pullRequest?.mergeStateStatus);
6532
6853
  reviewDecision = normalizeGitHubPullRequestReviewDecision(response.repository?.pullRequest?.reviewDecision);
6854
+ const responseHeadSha = response.repository?.pullRequest?.headRefOid;
6855
+ if (typeof responseHeadSha === "string" && responseHeadSha.trim()) {
6856
+ headSha = responseHeadSha.trim().toLowerCase();
6857
+ }
6533
6858
  const connection = response.repository?.pullRequest?.statusCheckRollup?.contexts;
6534
6859
  const nodes = connection?.nodes ?? [];
6535
6860
  for (const node of nodes) {
@@ -6554,6 +6879,7 @@ async function getGitHubPullRequestCiSnapshot(octokit, repository, pullRequestNu
6554
6879
  after = getPageCursor(connection?.pageInfo);
6555
6880
  } while (after);
6556
6881
  return {
6882
+ ...headSha ? { headSha } : {},
6557
6883
  ciState: classifyGitHubPullRequestCiState(contexts),
6558
6884
  mergeability,
6559
6885
  mergeStateStatus,
@@ -6603,6 +6929,7 @@ async function getGitHubPullRequestStatusSnapshot(octokit, repository, pullReque
6603
6929
  return cacheGitHubPullRequestStatusSnapshot(repository, {
6604
6930
  number: pullRequestNumber,
6605
6931
  repositoryUrl: repository.url,
6932
+ ..."headSha" in ciSnapshot && ciSnapshot.headSha ? { headSha: ciSnapshot.headSha } : {},
6606
6933
  hasUnresolvedReviewThreads: reviewThreadSummary.unresolvedReviewThreads > 0,
6607
6934
  ciState: ciSnapshot.ciState,
6608
6935
  mergeability: ciSnapshot.mergeability,
@@ -6940,7 +7267,7 @@ async function hasTrustedNewLinkedPullRequestComments(params) {
6940
7267
  octokit: params.octokit,
6941
7268
  repository: pullRequestRepository,
6942
7269
  comments: newTopLevelComments,
6943
- originalPosterLogin: params.githubIssue.authorLogin,
7270
+ originalPosterLogin: params.originalPosterLogin,
6944
7271
  maintainerCache: params.maintainerCache
6945
7272
  })) {
6946
7273
  return true;
@@ -6958,7 +7285,7 @@ async function hasTrustedNewLinkedPullRequestComments(params) {
6958
7285
  octokit: params.octokit,
6959
7286
  repository: pullRequestRepository,
6960
7287
  comments: newReviewComments,
6961
- originalPosterLogin: params.githubIssue.authorLogin,
7288
+ originalPosterLogin: params.originalPosterLogin,
6962
7289
  maintainerCache: params.maintainerCache
6963
7290
  })) {
6964
7291
  return true;
@@ -7137,7 +7464,7 @@ function normalizeGitHubPullRequestCommentCountRecords(value) {
7137
7464
  return repositoryComparison;
7138
7465
  }
7139
7466
  return left.number - right.number;
7140
- });
7467
+ }).slice(0, MAX_PULL_REQUEST_COMMENT_WATERMARKS);
7141
7468
  }
7142
7469
  function normalizeLinkedPullRequestReferences(values, fallbackRepositoryUrl) {
7143
7470
  const references = [];
@@ -8491,19 +8818,15 @@ async function wakePaperclipIssueAssignee(ctx, params) {
8491
8818
  await ctx.issues.requestWakeup(params.paperclipIssueId, params.companyId, {
8492
8819
  reason: params.reason,
8493
8820
  contextSource: `github-sync.${params.mutation}`,
8494
- ...params.mutation === "import" ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId].join(":") } : {}
8821
+ ...params.actionFingerprint ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId, params.actionFingerprint].join(":") } : params.mutation === "import" ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId].join(":") } : {}
8495
8822
  });
8496
8823
  return;
8497
8824
  } catch (error) {
8498
8825
  if (!params.paperclipApiBaseUrl) {
8499
- ctx.logger.warn("GitHub sync could not wake the assignee for a Paperclip issue through the SDK.", {
8500
- issueId: params.paperclipIssueId,
8501
- agentId: params.assigneeAgentId,
8502
- companyId: params.companyId,
8503
- mutation: params.mutation,
8504
- error: error instanceof Error ? error.message : String(error)
8505
- });
8506
- return;
8826
+ throw new Error(
8827
+ `GitHub sync could not wake the assignee for Paperclip issue ${params.paperclipIssueId} through the SDK: ${getErrorMessage(error)}`,
8828
+ { cause: error }
8829
+ );
8507
8830
  }
8508
8831
  ctx.logger.warn("GitHub sync could not wake the assignee through the SDK. Falling back to the local Paperclip API.", {
8509
8832
  issueId: params.paperclipIssueId,
@@ -8515,7 +8838,7 @@ async function wakePaperclipIssueAssignee(ctx, params) {
8515
8838
  }
8516
8839
  }
8517
8840
  if (!params.paperclipApiBaseUrl) {
8518
- return;
8841
+ throw new Error(`GitHub sync has no available wakeup transport for Paperclip issue ${params.paperclipIssueId}.`);
8519
8842
  }
8520
8843
  try {
8521
8844
  const response = await fetchPaperclipApi(
@@ -8530,6 +8853,7 @@ async function wakePaperclipIssueAssignee(ctx, params) {
8530
8853
  source: "assignment",
8531
8854
  triggerDetail: "system",
8532
8855
  reason: params.reason,
8856
+ ...params.actionFingerprint ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId, params.actionFingerprint].join(":") } : params.mutation === "import" ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId].join(":") } : {},
8533
8857
  payload: {
8534
8858
  issueId: params.paperclipIssueId,
8535
8859
  mutation: params.mutation,
@@ -8546,14 +8870,10 @@ async function wakePaperclipIssueAssignee(ctx, params) {
8546
8870
  throw new Error(`Wakeup request failed with status ${response.status}.`);
8547
8871
  }
8548
8872
  } catch (error) {
8549
- ctx.logger.warn("GitHub sync could not wake the assignee for a Paperclip issue.", {
8550
- issueId: params.paperclipIssueId,
8551
- agentId: params.assigneeAgentId,
8552
- companyId: params.companyId,
8553
- paperclipApiBaseUrl: params.paperclipApiBaseUrl,
8554
- mutation: params.mutation,
8555
- error: error instanceof Error ? error.message : String(error)
8556
- });
8873
+ throw new Error(
8874
+ `GitHub sync could not wake the assignee for Paperclip issue ${params.paperclipIssueId}: ${getErrorMessage(error)}`,
8875
+ { cause: error }
8876
+ );
8557
8877
  }
8558
8878
  }
8559
8879
  function parsePaperclipIssueDescription(value) {
@@ -9250,6 +9570,81 @@ function doIssueNumberListsMatch(left, right) {
9250
9570
  }
9251
9571
  return left.every((value, index) => value === right[index]);
9252
9572
  }
9573
+ function getEffectivePullRequestActionCondition(pullRequest) {
9574
+ if (pullRequest.mergeability === "conflicting" || pullRequest.mergeStateStatus === "dirty") return "conflict";
9575
+ if (pullRequest.ciState === "red") return "ci_failed";
9576
+ if (pullRequest.hasUnresolvedReviewThreads) return "review_actionable";
9577
+ if (pullRequest.ciState === "green" && pullRequest.mergeability === "mergeable") return "ready";
9578
+ return "waiting";
9579
+ }
9580
+ function getEffectivePullRequestActionPriority(condition) {
9581
+ switch (condition) {
9582
+ case "conflict":
9583
+ return 0;
9584
+ case "ci_failed":
9585
+ return 1;
9586
+ case "review_actionable":
9587
+ return 2;
9588
+ case "waiting":
9589
+ return 3;
9590
+ case "ready":
9591
+ return 4;
9592
+ }
9593
+ }
9594
+ function selectEffectivePullRequestFingerprintEntries(pullRequests) {
9595
+ const highestPriority = Math.min(...pullRequests.map(
9596
+ (pullRequest) => getEffectivePullRequestActionPriority(pullRequest.condition)
9597
+ ));
9598
+ return pullRequests.filter((pullRequest) => getEffectivePullRequestActionPriority(pullRequest.condition) === highestPriority).sort((left, right) => left.repositoryUrl.localeCompare(right.repositoryUrl) || left.number - right.number);
9599
+ }
9600
+ function buildRemoteActionFingerprint(snapshot) {
9601
+ const allPullRequests = snapshot.linkedPullRequests.map((pullRequest) => ({
9602
+ repositoryUrl: pullRequest.repositoryUrl.toLowerCase(),
9603
+ number: pullRequest.number,
9604
+ headSha: pullRequest.headSha ?? null,
9605
+ condition: getEffectivePullRequestActionCondition(pullRequest)
9606
+ }));
9607
+ const pullRequests = snapshot.state === "closed" || allPullRequests.length === 0 ? [] : selectEffectivePullRequestFingerprintEntries(allPullRequests);
9608
+ const reasonCode = snapshot.state === "closed" ? `issue_closed_${snapshot.stateReason ?? "completed"}` : pullRequests.length === 0 ? "issue_open" : `pr_${pullRequests[0]?.condition ?? "waiting"}`;
9609
+ return createHash("sha256").update(JSON.stringify({
9610
+ version: 3,
9611
+ issue: {
9612
+ state: snapshot.state,
9613
+ stateReason: snapshot.stateReason ?? null
9614
+ },
9615
+ pullRequests,
9616
+ reasonCode
9617
+ })).digest("hex");
9618
+ }
9619
+ function buildDirectPullRequestActionFingerprint(snapshots) {
9620
+ const openPullRequests = snapshots.filter((entry) => entry.lifecycleState === "open" && entry.pullRequest).map((entry) => ({
9621
+ repositoryUrl: entry.repository.url.toLowerCase(),
9622
+ number: entry.pullRequestLink.data.githubPullRequestNumber,
9623
+ headSha: entry.pullRequest?.headSha ?? null,
9624
+ condition: getEffectivePullRequestActionCondition(entry.pullRequest)
9625
+ }));
9626
+ const terminalOutcome = openPullRequests.length > 0 ? null : snapshots.some((entry) => entry.lifecycleState === "merged") ? "merged" : "closed";
9627
+ const pullRequests = openPullRequests.length > 0 ? selectEffectivePullRequestFingerprintEntries(openPullRequests) : [];
9628
+ return createHash("sha256").update(JSON.stringify({
9629
+ version: 3,
9630
+ terminalOutcome,
9631
+ pullRequests
9632
+ })).digest("hex");
9633
+ }
9634
+ function classifyIssueInteractionReason(value) {
9635
+ const reason = value.toLowerCase();
9636
+ if (reason.includes("new github comment")) return "trusted_comment";
9637
+ if (reason.includes("green ci") && reason.includes("review thread")) return "pr_ready";
9638
+ if (reason.includes("merge conflict")) return "pr_merge_conflict";
9639
+ if (reason.includes("failing ci")) return "pr_ci_failed";
9640
+ if (reason.includes("unfinished ci")) return "pr_ci_unfinished";
9641
+ if (reason.includes("unknown mergeability")) return "pr_mergeability_unknown";
9642
+ if (reason.includes("closed as completed")) return "issue_closed_completed";
9643
+ if (reason.includes("closed") && reason.includes("not planned")) return "issue_closed_not_planned";
9644
+ if (reason.includes("duplicate")) return "issue_closed_duplicate";
9645
+ if (reason.includes("open with no linked pull request")) return "issue_ready_for_triage";
9646
+ return "github_sync_status_decision";
9647
+ }
9253
9648
  async function updatePaperclipIssueState(ctx, params) {
9254
9649
  const {
9255
9650
  companyId,
@@ -9265,6 +9660,7 @@ async function updatePaperclipIssueState(ctx, params) {
9265
9660
  paperclipApiBaseUrl
9266
9661
  } = params;
9267
9662
  const trimmedTransitionComment = transitionComment.trim();
9663
+ const interactionOccurredAt = (/* @__PURE__ */ new Date()).toISOString();
9268
9664
  const statusWillChange = currentStatus !== nextStatus;
9269
9665
  let createdTransitionComment = null;
9270
9666
  let issueUpdated = false;
@@ -9291,120 +9687,172 @@ async function updatePaperclipIssueState(ctx, params) {
9291
9687
  issuePatch.assigneeAgentId = null;
9292
9688
  issuePatch.assigneeUserId = null;
9293
9689
  }
9294
- if (statusWillChange) {
9295
- if (!trimmedTransitionComment) {
9296
- throw new Error("GitHub Sync refused to update a Paperclip issue status without an explanatory transition comment.");
9297
- }
9298
- if (typeof ctx.issues.createComment !== "function") {
9299
- 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.");
9300
- }
9301
- createdTransitionComment = await ctx.issues.createComment(issueId, trimmedTransitionComment, companyId);
9690
+ if (statusWillChange && !trimmedTransitionComment) {
9691
+ throw new Error("GitHub Sync refused to update a Paperclip issue status without an explanatory transition comment.");
9302
9692
  }
9303
- if (paperclipApiBaseUrl) {
9304
- try {
9305
- const response = await fetchPaperclipApi(
9306
- getPaperclipIssueEndpoint(paperclipApiBaseUrl, issueId),
9307
- {
9308
- method: "PATCH",
9309
- headers: {
9310
- accept: "application/json",
9311
- "content-type": "application/json"
9693
+ if (statusWillChange && typeof ctx.issues.createComment !== "function") {
9694
+ 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.");
9695
+ }
9696
+ const reasonCode = classifyIssueInteractionReason(transitionCommentAnnotation?.reason ?? trimmedTransitionComment);
9697
+ const interactionDedupeBase = `sync:${issueId}:${interactionOccurredAt}:${currentStatus}:${nextStatus}`;
9698
+ await persistIssueInteractionEvent(ctx, {
9699
+ schemaVersion: 1,
9700
+ companyId,
9701
+ paperclipIssueId: issueId,
9702
+ occurredAt: interactionOccurredAt,
9703
+ category: "sync",
9704
+ action: "status_decision",
9705
+ source: "sync",
9706
+ ...transitionCommentAnnotation ? {
9707
+ remote: {
9708
+ repositoryUrl: transitionCommentAnnotation.repositoryUrl,
9709
+ kind: "issue",
9710
+ number: transitionCommentAnnotation.githubIssueNumber,
9711
+ url: transitionCommentAnnotation.githubIssueUrl
9712
+ }
9713
+ } : {},
9714
+ transition: { from: currentStatus, to: nextStatus, reasonCode },
9715
+ outcome: "observed",
9716
+ dedupeKey: `${interactionDedupeBase}:intent`
9717
+ });
9718
+ const persistSyncResult = (outcome) => persistIssueInteractionEvent(ctx, {
9719
+ schemaVersion: 1,
9720
+ companyId,
9721
+ paperclipIssueId: issueId,
9722
+ occurredAt: interactionOccurredAt,
9723
+ category: "sync",
9724
+ action: "status_decision",
9725
+ source: "sync",
9726
+ ...transitionCommentAnnotation ? {
9727
+ remote: {
9728
+ repositoryUrl: transitionCommentAnnotation.repositoryUrl,
9729
+ kind: "issue",
9730
+ number: transitionCommentAnnotation.githubIssueNumber,
9731
+ url: transitionCommentAnnotation.githubIssueUrl
9732
+ }
9733
+ } : {},
9734
+ transition: { from: currentStatus, to: nextStatus, reasonCode },
9735
+ outcome,
9736
+ dedupeKey: `${interactionDedupeBase}:result`
9737
+ });
9738
+ try {
9739
+ if (statusWillChange) {
9740
+ createdTransitionComment = await ctx.issues.createComment(issueId, trimmedTransitionComment, companyId);
9741
+ }
9742
+ if (paperclipApiBaseUrl) {
9743
+ try {
9744
+ const response = await fetchPaperclipApi(
9745
+ getPaperclipIssueEndpoint(paperclipApiBaseUrl, issueId),
9746
+ {
9747
+ method: "PATCH",
9748
+ headers: {
9749
+ accept: "application/json",
9750
+ "content-type": "application/json"
9751
+ },
9752
+ body: JSON.stringify(issuePatch)
9312
9753
  },
9313
- body: JSON.stringify(issuePatch)
9314
- },
9315
- {
9316
- companyId
9317
- }
9318
- );
9319
- const payloadResult = await readPaperclipApiJsonResponse(response, {
9320
- operationLabel: "issue update",
9321
- bodyRequired: false
9322
- });
9323
- if (!payloadResult.failure) {
9324
- issueUpdated = true;
9325
- if (issuePatch.executionState === null && ctx.issues && typeof ctx.issues.update === "function") {
9326
- try {
9327
- await ctx.issues.update(
9328
- issueId,
9329
- { executionState: null },
9330
- companyId
9331
- );
9332
- } catch (error) {
9333
- issueUpdated = false;
9334
- ctx.logger.warn("GitHub sync could not clear Paperclip issue execution state after the local API update. Falling back to direct issue mutation.", {
9335
- companyId,
9336
- issueId,
9337
- paperclipApiBaseUrl,
9338
- nextStatus,
9339
- error: getErrorMessage(error)
9340
- });
9754
+ {
9755
+ companyId
9756
+ }
9757
+ );
9758
+ const payloadResult = await readPaperclipApiJsonResponse(response, {
9759
+ operationLabel: "issue update",
9760
+ bodyRequired: false
9761
+ });
9762
+ if (!payloadResult.failure) {
9763
+ issueUpdated = true;
9764
+ if (issuePatch.executionState === null && ctx.issues && typeof ctx.issues.update === "function") {
9765
+ try {
9766
+ await ctx.issues.update(
9767
+ issueId,
9768
+ { executionState: null },
9769
+ companyId
9770
+ );
9771
+ } catch (error) {
9772
+ issueUpdated = false;
9773
+ ctx.logger.warn("GitHub sync could not clear Paperclip issue execution state after the local API update. Falling back to direct issue mutation.", {
9774
+ companyId,
9775
+ issueId,
9776
+ paperclipApiBaseUrl,
9777
+ nextStatus,
9778
+ error: getErrorMessage(error)
9779
+ });
9780
+ }
9341
9781
  }
9342
9782
  }
9343
- }
9344
- if (payloadResult.failure && (payloadResult.failure.status ?? response.status) !== 404 && (payloadResult.failure.status ?? response.status) !== 405) {
9783
+ if (payloadResult.failure && (payloadResult.failure.status ?? response.status) !== 404 && (payloadResult.failure.status ?? response.status) !== 405) {
9784
+ logPaperclipIssueStatusUpdateFailure(ctx, {
9785
+ companyId,
9786
+ issueId,
9787
+ paperclipApiBaseUrl,
9788
+ nextStatus,
9789
+ status: payloadResult.failure.status ?? response.status,
9790
+ errorMessage: payloadResult.failure.errorMessage
9791
+ });
9792
+ }
9793
+ } catch (error) {
9345
9794
  logPaperclipIssueStatusUpdateFailure(ctx, {
9346
9795
  companyId,
9347
9796
  issueId,
9348
9797
  paperclipApiBaseUrl,
9349
9798
  nextStatus,
9350
- status: payloadResult.failure.status ?? response.status,
9351
- errorMessage: payloadResult.failure.errorMessage
9799
+ errorMessage: getErrorMessage(error)
9352
9800
  });
9353
9801
  }
9354
- } catch (error) {
9355
- logPaperclipIssueStatusUpdateFailure(ctx, {
9356
- companyId,
9357
- issueId,
9358
- paperclipApiBaseUrl,
9359
- nextStatus,
9360
- errorMessage: getErrorMessage(error)
9361
- });
9362
9802
  }
9363
- }
9364
- if (!issueUpdated) {
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
- });
9379
- }
9380
- await ctx.issues.update(issueId, sdkIssuePatch, companyId);
9381
- }
9382
- if (createdTransitionComment) {
9383
- if (transitionCommentAnnotation) {
9384
- await upsertStatusTransitionCommentAnnotation(ctx, {
9385
- issueId,
9386
- commentId: createdTransitionComment.id,
9387
- annotation: {
9388
- ...transitionCommentAnnotation,
9803
+ if (!issueUpdated) {
9804
+ const preserveExistingUserAssigneeWithoutLocalApi = nextAssignee?.kind === "user" && !paperclipApiBaseUrl;
9805
+ const sdkIssuePatch = {
9806
+ ...issuePatch,
9807
+ ...syncExecutionStatePatch !== void 0 ? { executionState: syncExecutionStatePatch } : {}
9808
+ };
9809
+ if (preserveExistingUserAssigneeWithoutLocalApi) {
9810
+ delete sdkIssuePatch.assigneeAgentId;
9811
+ delete sdkIssuePatch.assigneeUserId;
9812
+ ctx.logger.warn("GitHub sync could not reassign a Paperclip issue to a user without the local Paperclip API. Preserving the existing assignee.", {
9389
9813
  companyId,
9390
- paperclipIssueId: issueId
9391
- }
9392
- });
9814
+ issueId,
9815
+ nextStatus,
9816
+ assigneeUserId: nextAssignee.id
9817
+ });
9818
+ }
9819
+ await ctx.issues.update(issueId, sdkIssuePatch, companyId);
9393
9820
  }
9394
- } else if (trimmedTransitionComment && typeof ctx.issues.createComment === "function") {
9395
- const createdComment = await ctx.issues.createComment(issueId, trimmedTransitionComment, companyId);
9396
- if (transitionCommentAnnotation) {
9397
- await upsertStatusTransitionCommentAnnotation(ctx, {
9398
- issueId,
9399
- commentId: createdComment.id,
9400
- annotation: {
9401
- ...transitionCommentAnnotation,
9402
- companyId,
9403
- paperclipIssueId: issueId
9404
- }
9405
- });
9821
+ if (createdTransitionComment) {
9822
+ if (transitionCommentAnnotation) {
9823
+ await upsertStatusTransitionCommentAnnotation(ctx, {
9824
+ issueId,
9825
+ commentId: createdTransitionComment.id,
9826
+ annotation: {
9827
+ ...transitionCommentAnnotation,
9828
+ companyId,
9829
+ paperclipIssueId: issueId
9830
+ }
9831
+ });
9832
+ }
9833
+ } else if (trimmedTransitionComment && typeof ctx.issues.createComment === "function") {
9834
+ const createdComment = await ctx.issues.createComment(issueId, trimmedTransitionComment, companyId);
9835
+ if (transitionCommentAnnotation) {
9836
+ await upsertStatusTransitionCommentAnnotation(ctx, {
9837
+ issueId,
9838
+ commentId: createdComment.id,
9839
+ annotation: {
9840
+ ...transitionCommentAnnotation,
9841
+ companyId,
9842
+ paperclipIssueId: issueId
9843
+ }
9844
+ });
9845
+ }
9846
+ }
9847
+ } catch (error) {
9848
+ try {
9849
+ await persistSyncResult("failed");
9850
+ } catch (ledgerError) {
9851
+ throw new AggregateError([error, ledgerError], "GitHub Sync mutation failed and its result event could not be persisted.");
9406
9852
  }
9853
+ throw error;
9407
9854
  }
9855
+ await persistSyncResult(statusWillChange ? "changed" : "noop");
9408
9856
  }
9409
9857
  function sortIssuesForImport(issues) {
9410
9858
  return [...issues].sort((left, right) => {
@@ -9950,7 +10398,7 @@ async function reconcileTransferredImportedIssues(ctx, params) {
9950
10398
  updatedDescriptionsCount
9951
10399
  };
9952
10400
  }
9953
- async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mapping, advancedSettings, allIssuesById, importedIssues, createdIssueIds, availableLabels, paperclipApiBaseUrl, linkedPullRequestsByIssueNumber, issueStatusSnapshotCache, pullRequestStatusCache, repositoryMaintainerCache, syncFailureContext, failures, assertNotCancelled, onGitHubIssueClosed, onProgress) {
10401
+ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mapping, advancedSettings, allIssuesById, importedIssues, createdIssueIds, availableLabels, paperclipApiBaseUrl, linkedPullRequestsByIssueNumber, issueStatusSnapshotCache, pullRequestStatusCache, repositoryMaintainerCache, syncFailureContext, failures, persistImportRegistry, assertNotCancelled, onGitHubIssueClosed, onProgress) {
9954
10402
  if (!mapping.companyId || !ctx.issues || typeof ctx.issues.get !== "function" || typeof ctx.issues.update !== "function") {
9955
10403
  return {
9956
10404
  updatedStatusesCount: 0,
@@ -10106,12 +10554,29 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10106
10554
  }
10107
10555
  const hasTrustedNewLinkedPullRequestComment = paperclipIssue.status === "backlog" || currentLinkedPullRequestCommentCounts.length === 0 ? false : await hasTrustedNewLinkedPullRequestComments({
10108
10556
  octokit,
10109
- githubIssue,
10557
+ originalPosterLogin: githubIssue.authorLogin,
10110
10558
  previousCommentCounts: importedIssue.linkedPullRequestCommentCounts,
10111
10559
  currentCommentCounts: currentLinkedPullRequestCommentCounts,
10112
10560
  maintainerCache: repositoryMaintainerCache
10113
10561
  });
10114
10562
  const hasTrustedNewComment = hasTrustedNewIssueComment || hasTrustedNewLinkedPullRequestComment;
10563
+ const remoteActionFingerprint = buildRemoteActionFingerprint(snapshot);
10564
+ if (importedIssue.pendingRemoteActionWake) {
10565
+ const pendingWake2 = importedIssue.pendingRemoteActionWake;
10566
+ await wakePaperclipIssueAssignee(ctx, {
10567
+ assigneeAgentId: pendingWake2.assigneeAgentId,
10568
+ paperclipIssueId: importedIssue.paperclipIssueId,
10569
+ companyId: mapping.companyId,
10570
+ paperclipApiBaseUrl,
10571
+ reason: pendingWake2.reason,
10572
+ mutation: pendingWake2.mutation,
10573
+ actionFingerprint: pendingWake2.fingerprint,
10574
+ previousStatus: pendingWake2.previousStatus,
10575
+ nextStatus: pendingWake2.nextStatus
10576
+ });
10577
+ delete importedIssue.pendingRemoteActionWake;
10578
+ await persistImportRegistry();
10579
+ }
10115
10580
  const wasImportedThisRun = createdIssueIds.has(importedIssue.githubIssueId);
10116
10581
  const maintainerAuthoredImportedIssue = wasImportedThisRun && advancedSettings.defaultStatus !== "todo" && snapshot.state === "open" && snapshot.linkedPullRequests.length === 0 ? await isMaintainerAuthoredGitHubIssue({
10117
10582
  octokit,
@@ -10136,6 +10601,9 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10136
10601
  if (paperclipIssue.status === "blocked" && nextStatus !== "blocked" && await hasUnresolvedPaperclipIssueBlocker(ctx, paperclipIssue, mapping.companyId)) {
10137
10602
  nextStatus = "blocked";
10138
10603
  }
10604
+ if (paperclipIssue.status !== nextStatus && !hasTrustedNewComment && importedIssue.remoteActionFingerprint === remoteActionFingerprint) {
10605
+ nextStatus = paperclipIssue.status;
10606
+ }
10139
10607
  const shouldPreserveMaintainerWaitRouting = isHealthyMaintainerWaitTransition({
10140
10608
  currentStatus: paperclipIssue.status,
10141
10609
  nextStatus,
@@ -10161,10 +10629,15 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10161
10629
  const nextAssigneeChanged = nextTransitionAssignee ? !doesPaperclipIssueAssigneeMatch(paperclipIssueSyncContext.assignee, nextTransitionAssignee.principal) : false;
10162
10630
  const shouldWakeImportedAssignee = wasImportedThisRun && nextStatus === "todo" && (paperclipIssue.status === nextStatus || shouldPreserveImportedTriageRouting) && paperclipIssueSyncContext.assignee?.kind === "agent";
10163
10631
  const shouldWakeTransitionAssignee = paperclipIssue.status !== nextStatus && nextTransitionAssignee?.principal.kind === "agent" && isActionablePaperclipIssueStatus(nextStatus) && (nextAssigneeChanged || paperclipIssue.status !== nextStatus);
10164
- importedIssue.githubIssueNumber = githubIssue.number;
10165
- importedIssue.lastSeenCommentCount = snapshot.commentCount;
10166
- importedIssue.lastSeenGitHubState = snapshot.state;
10167
- importedIssue.linkedPullRequestCommentCounts = currentLinkedPullRequestCommentCounts;
10632
+ const persistObservedRemoteState = async (pendingWake2) => {
10633
+ importedIssue.githubIssueNumber = githubIssue.number;
10634
+ importedIssue.lastSeenCommentCount = snapshot.commentCount;
10635
+ importedIssue.lastSeenGitHubState = snapshot.state;
10636
+ importedIssue.linkedPullRequestCommentCounts = currentLinkedPullRequestCommentCounts;
10637
+ importedIssue.remoteActionFingerprint = remoteActionFingerprint;
10638
+ if (pendingWake2) importedIssue.pendingRemoteActionWake = pendingWake2;
10639
+ await persistImportRegistry();
10640
+ };
10168
10641
  if (paperclipIssue.status === nextStatus) {
10169
10642
  if (shouldClearTransitionAssignee || shouldClearCompletedExecutionPolicy) {
10170
10643
  updateSyncFailureContext(syncFailureContext, {
@@ -10184,13 +10657,31 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10184
10657
  paperclipApiBaseUrl
10185
10658
  });
10186
10659
  }
10187
- if (shouldWakeImportedAssignee) {
10660
+ if (shouldWakeImportedAssignee && paperclipIssueSyncContext.assignee?.kind === "agent") {
10661
+ const pendingWake2 = {
10662
+ fingerprint: remoteActionFingerprint,
10663
+ assigneeAgentId: paperclipIssueSyncContext.assignee.id,
10664
+ reason: IMPORTED_ISSUE_WAKE_REASON,
10665
+ mutation: "import",
10666
+ nextStatus
10667
+ };
10668
+ await persistObservedRemoteState(pendingWake2);
10188
10669
  queuedIssueWakeups.push({
10189
- assigneeAgentId: paperclipIssueSyncContext.assignee?.kind === "agent" ? paperclipIssueSyncContext.assignee.id : null,
10670
+ assigneeAgentId: pendingWake2.assigneeAgentId,
10190
10671
  paperclipIssueId: importedIssue.paperclipIssueId,
10191
- reason: IMPORTED_ISSUE_WAKE_REASON,
10192
- mutation: "import"
10672
+ reason: pendingWake2.reason,
10673
+ mutation: "import",
10674
+ actionFingerprint: pendingWake2.fingerprint,
10675
+ nextStatus,
10676
+ onSuccess: async () => {
10677
+ if (importedIssue.pendingRemoteActionWake?.fingerprint === pendingWake2.fingerprint) {
10678
+ delete importedIssue.pendingRemoteActionWake;
10679
+ await persistImportRegistry();
10680
+ }
10681
+ }
10193
10682
  });
10683
+ } else {
10684
+ await persistObservedRemoteState();
10194
10685
  }
10195
10686
  continue;
10196
10687
  }
@@ -10220,23 +10711,38 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10220
10711
  transitionCommentAnnotation: transitionComment.annotation,
10221
10712
  paperclipApiBaseUrl
10222
10713
  });
10714
+ const pendingWake = shouldWakeImportedAssignee && paperclipIssueSyncContext.assignee?.kind === "agent" ? {
10715
+ fingerprint: remoteActionFingerprint,
10716
+ assigneeAgentId: paperclipIssueSyncContext.assignee.id,
10717
+ reason: IMPORTED_ISSUE_WAKE_REASON,
10718
+ mutation: "import",
10719
+ previousStatus: paperclipIssue.status,
10720
+ nextStatus
10721
+ } : shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? {
10722
+ fingerprint: remoteActionFingerprint,
10723
+ assigneeAgentId: nextTransitionAssignee.principal.id,
10724
+ reason: STATUS_TRANSITION_WAKE_REASON,
10725
+ mutation: "status_transition",
10726
+ previousStatus: paperclipIssue.status,
10727
+ nextStatus
10728
+ } : void 0;
10729
+ await persistObservedRemoteState(pendingWake);
10223
10730
  updatedStatusesCount += 1;
10224
- if (shouldWakeImportedAssignee) {
10731
+ if (pendingWake) {
10225
10732
  queuedIssueWakeups.push({
10226
- assigneeAgentId: paperclipIssueSyncContext.assignee?.kind === "agent" ? paperclipIssueSyncContext.assignee.id : null,
10733
+ assigneeAgentId: pendingWake.assigneeAgentId,
10227
10734
  paperclipIssueId: importedIssue.paperclipIssueId,
10228
- reason: IMPORTED_ISSUE_WAKE_REASON,
10229
- mutation: "import"
10230
- });
10231
- }
10232
- if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent") {
10233
- queuedIssueWakeups.push({
10234
- assigneeAgentId: nextTransitionAssignee.principal.id,
10235
- paperclipIssueId: importedIssue.paperclipIssueId,
10236
- reason: STATUS_TRANSITION_WAKE_REASON,
10237
- mutation: "status_transition",
10238
- previousStatus: paperclipIssue.status,
10239
- nextStatus
10735
+ reason: pendingWake.reason,
10736
+ mutation: pendingWake.mutation,
10737
+ actionFingerprint: pendingWake.fingerprint,
10738
+ previousStatus: pendingWake.previousStatus,
10739
+ nextStatus: pendingWake.nextStatus,
10740
+ onSuccess: async () => {
10741
+ if (importedIssue.pendingRemoteActionWake?.fingerprint === pendingWake.fingerprint) {
10742
+ delete importedIssue.pendingRemoteActionWake;
10743
+ await persistImportRegistry();
10744
+ }
10745
+ }
10240
10746
  });
10241
10747
  }
10242
10748
  } catch (error) {
@@ -10260,16 +10766,20 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10260
10766
  await mapWithConcurrency(
10261
10767
  queuedIssueWakeups,
10262
10768
  IMPORTED_ISSUE_WAKEUP_CONCURRENCY,
10263
- async (queuedWakeup) => wakePaperclipIssueAssignee(ctx, {
10264
- assigneeAgentId: queuedWakeup.assigneeAgentId,
10265
- paperclipIssueId: queuedWakeup.paperclipIssueId,
10266
- companyId: mapping.companyId,
10267
- paperclipApiBaseUrl,
10268
- reason: queuedWakeup.reason,
10269
- mutation: queuedWakeup.mutation,
10270
- previousStatus: queuedWakeup.previousStatus,
10271
- nextStatus: queuedWakeup.nextStatus
10272
- })
10769
+ async (queuedWakeup) => {
10770
+ await wakePaperclipIssueAssignee(ctx, {
10771
+ assigneeAgentId: queuedWakeup.assigneeAgentId,
10772
+ paperclipIssueId: queuedWakeup.paperclipIssueId,
10773
+ companyId: mapping.companyId,
10774
+ paperclipApiBaseUrl,
10775
+ reason: queuedWakeup.reason,
10776
+ mutation: queuedWakeup.mutation,
10777
+ actionFingerprint: queuedWakeup.actionFingerprint,
10778
+ previousStatus: queuedWakeup.previousStatus,
10779
+ nextStatus: queuedWakeup.nextStatus
10780
+ });
10781
+ await queuedWakeup.onSuccess?.();
10782
+ }
10273
10783
  );
10274
10784
  return {
10275
10785
  updatedStatusesCount,
@@ -10289,7 +10799,7 @@ function groupGitHubPullRequestLinksByPaperclipIssue(pullRequestLinks) {
10289
10799
  }
10290
10800
  return groups;
10291
10801
  }
10292
- async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mapping, advancedSettings, pullRequestLinks, paperclipApiBaseUrl, pullRequestStatusCache, syncFailureContext, failures, assertNotCancelled, onProgress) {
10802
+ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mapping, advancedSettings, pullRequestLinks, paperclipApiBaseUrl, pullRequestStatusCache, syncFailureContext, failures, remoteActionRegistry, persistRemoteActionRegistry, assertNotCancelled, onProgress) {
10293
10803
  if (!mapping.companyId || !ctx.issues || typeof ctx.issues.get !== "function" || typeof ctx.issues.update !== "function") {
10294
10804
  return {
10295
10805
  updatedStatusesCount: 0
@@ -10341,6 +10851,15 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10341
10851
  pullRequestState: livePullRequestLinkState
10342
10852
  });
10343
10853
  }
10854
+ const directPullRequestMetadata = {
10855
+ ...normalizeGitHubUsername(pullRequestResponse.data.user?.login) ? { authorLogin: normalizeGitHubUsername(pullRequestResponse.data.user?.login) } : {},
10856
+ commentCounts: {
10857
+ number: pullRequestLink.data.githubPullRequestNumber,
10858
+ repositoryUrl: pullRequestRepository.url,
10859
+ topLevelCommentCount: typeof pullRequestResponse.data.comments === "number" && pullRequestResponse.data.comments >= 0 ? Math.floor(pullRequestResponse.data.comments) : 0,
10860
+ reviewCommentCount: typeof pullRequestResponse.data.review_comments === "number" && pullRequestResponse.data.review_comments >= 0 ? Math.floor(pullRequestResponse.data.review_comments) : 0
10861
+ }
10862
+ };
10344
10863
  if (livePullRequestLifecycleState === "open") {
10345
10864
  const pullRequest = await getGitHubPullRequestStatusSnapshot(
10346
10865
  octokit,
@@ -10352,13 +10871,15 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10352
10871
  pullRequestLink,
10353
10872
  repository: pullRequestRepository,
10354
10873
  lifecycleState: "open",
10355
- pullRequest
10874
+ pullRequest,
10875
+ ...directPullRequestMetadata
10356
10876
  });
10357
10877
  } else {
10358
10878
  pullRequestSnapshots.push({
10359
10879
  pullRequestLink,
10360
10880
  repository: pullRequestRepository,
10361
- lifecycleState: livePullRequestLifecycleState
10881
+ lifecycleState: livePullRequestLifecycleState,
10882
+ ...directPullRequestMetadata
10362
10883
  });
10363
10884
  }
10364
10885
  } catch (error) {
@@ -10390,6 +10911,47 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10390
10911
  if (!paperclipIssue) {
10391
10912
  continue;
10392
10913
  }
10914
+ const remoteActionKey = `direct-pr:${mapping.companyId}:${paperclipIssueId}`;
10915
+ let remoteAction = remoteActionRegistry.find((entry) => entry.key === remoteActionKey);
10916
+ if (!remoteAction) {
10917
+ remoteAction = { key: remoteActionKey };
10918
+ remoteActionRegistry.push(remoteAction);
10919
+ }
10920
+ if (remoteAction.pendingWake) {
10921
+ const pendingWake2 = remoteAction.pendingWake;
10922
+ await wakePaperclipIssueAssignee(ctx, {
10923
+ assigneeAgentId: pendingWake2.assigneeAgentId,
10924
+ paperclipIssueId,
10925
+ companyId: mapping.companyId,
10926
+ paperclipApiBaseUrl,
10927
+ reason: pendingWake2.reason,
10928
+ mutation: pendingWake2.mutation,
10929
+ actionFingerprint: pendingWake2.fingerprint,
10930
+ previousStatus: pendingWake2.previousStatus,
10931
+ nextStatus: pendingWake2.nextStatus
10932
+ });
10933
+ delete remoteAction.pendingWake;
10934
+ await persistRemoteActionRegistry();
10935
+ }
10936
+ const currentCommentCounts = pullRequestSnapshots.map((snapshot) => snapshot.commentCounts).filter((counts) => Boolean(counts));
10937
+ let hasTrustedNewComment = false;
10938
+ if (paperclipIssue.status !== "backlog" && remoteAction.linkedPullRequestCommentCounts) {
10939
+ const maintainerCache = /* @__PURE__ */ new Map();
10940
+ for (const snapshot of pullRequestSnapshots) {
10941
+ if (!snapshot.commentCounts) continue;
10942
+ if (await hasTrustedNewLinkedPullRequestComments({
10943
+ octokit,
10944
+ originalPosterLogin: snapshot.authorLogin,
10945
+ previousCommentCounts: remoteAction.linkedPullRequestCommentCounts,
10946
+ currentCommentCounts: [snapshot.commentCounts],
10947
+ maintainerCache
10948
+ })) {
10949
+ hasTrustedNewComment = true;
10950
+ break;
10951
+ }
10952
+ }
10953
+ }
10954
+ const remoteActionFingerprint = buildDirectPullRequestActionFingerprint(pullRequestSnapshots);
10393
10955
  const paperclipIssueSyncContext = getPaperclipIssueSyncContext(paperclipIssue);
10394
10956
  const executorTransitionAssignee = resolvePaperclipIssueExecutorAssignee(
10395
10957
  paperclipIssueSyncContext,
@@ -10398,11 +10960,15 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10398
10960
  let nextStatus = resolvePaperclipDirectPullRequestIssueStatus({
10399
10961
  currentStatus: paperclipIssue.status,
10400
10962
  pullRequests: pullRequestSnapshots,
10401
- hasExecutorHandoffTarget: Boolean(executorTransitionAssignee)
10963
+ hasExecutorHandoffTarget: Boolean(executorTransitionAssignee),
10964
+ hasTrustedNewComment
10402
10965
  });
10403
10966
  if (paperclipIssue.status === "blocked" && nextStatus !== "blocked" && pullRequestSnapshots.some((entry) => entry.lifecycleState === "open") && await hasUnresolvedPaperclipIssueBlocker(ctx, paperclipIssue, mapping.companyId)) {
10404
10967
  nextStatus = "blocked";
10405
10968
  }
10969
+ if (paperclipIssue.status !== nextStatus && remoteAction.fingerprint === remoteActionFingerprint && !hasTrustedNewComment) {
10970
+ nextStatus = paperclipIssue.status;
10971
+ }
10406
10972
  const shouldPreserveMaintainerWaitRouting = isHealthyMaintainerWaitTransition({
10407
10973
  currentStatus: paperclipIssue.status,
10408
10974
  nextStatus,
@@ -10440,6 +11006,9 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10440
11006
  paperclipApiBaseUrl
10441
11007
  });
10442
11008
  }
11009
+ remoteAction.fingerprint = remoteActionFingerprint;
11010
+ remoteAction.linkedPullRequestCommentCounts = currentCommentCounts;
11011
+ await persistRemoteActionRegistry();
10443
11012
  continue;
10444
11013
  }
10445
11014
  const transitionComment = buildPaperclipPullRequestIssueStatusTransitionComment({
@@ -10452,6 +11021,11 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10452
11021
  repositoryUrl: primaryRepository?.url,
10453
11022
  githubIssueNumber: void 0
10454
11023
  });
11024
+ if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" && remoteActionRegistry.filter((record) => record.pendingWake).length >= MAX_REMOTE_ACTION_REGISTRY_RECORDS) {
11025
+ throw new Error(
11026
+ `Remote action registry pending-wake capacity ${MAX_REMOTE_ACTION_REGISTRY_RECORDS} reached; refusing an untracked status transition`
11027
+ );
11028
+ }
10455
11029
  await updatePaperclipIssueState(ctx, {
10456
11030
  companyId: mapping.companyId,
10457
11031
  issueId: paperclipIssueId,
@@ -10464,15 +11038,34 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10464
11038
  transitionComment,
10465
11039
  paperclipApiBaseUrl
10466
11040
  });
11041
+ const pendingWake = shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? {
11042
+ fingerprint: remoteActionFingerprint,
11043
+ assigneeAgentId: nextTransitionAssignee.principal.id,
11044
+ reason: STATUS_TRANSITION_WAKE_REASON,
11045
+ mutation: "status_transition",
11046
+ previousStatus: paperclipIssue.status,
11047
+ nextStatus
11048
+ } : void 0;
11049
+ remoteAction.fingerprint = remoteActionFingerprint;
11050
+ remoteAction.linkedPullRequestCommentCounts = currentCommentCounts;
11051
+ if (pendingWake) remoteAction.pendingWake = pendingWake;
11052
+ await persistRemoteActionRegistry();
10467
11053
  updatedStatusesCount += 1;
10468
- if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent") {
11054
+ if (pendingWake) {
10469
11055
  queuedIssueWakeups.push({
10470
- assigneeAgentId: nextTransitionAssignee.principal.id,
11056
+ assigneeAgentId: pendingWake.assigneeAgentId,
10471
11057
  paperclipIssueId,
10472
- reason: STATUS_TRANSITION_WAKE_REASON,
10473
- mutation: "status_transition",
10474
- previousStatus: paperclipIssue.status,
10475
- nextStatus
11058
+ reason: pendingWake.reason,
11059
+ mutation: pendingWake.mutation,
11060
+ actionFingerprint: pendingWake.fingerprint,
11061
+ previousStatus: pendingWake.previousStatus,
11062
+ nextStatus: pendingWake.nextStatus,
11063
+ onSuccess: async () => {
11064
+ if (remoteAction.pendingWake?.fingerprint === pendingWake.fingerprint) {
11065
+ delete remoteAction.pendingWake;
11066
+ await persistRemoteActionRegistry();
11067
+ }
11068
+ }
10476
11069
  });
10477
11070
  }
10478
11071
  } catch (error) {
@@ -10485,16 +11078,20 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10485
11078
  await mapWithConcurrency(
10486
11079
  queuedIssueWakeups,
10487
11080
  IMPORTED_ISSUE_WAKEUP_CONCURRENCY,
10488
- async (queuedWakeup) => wakePaperclipIssueAssignee(ctx, {
10489
- assigneeAgentId: queuedWakeup.assigneeAgentId,
10490
- paperclipIssueId: queuedWakeup.paperclipIssueId,
10491
- companyId: mapping.companyId,
10492
- paperclipApiBaseUrl,
10493
- reason: queuedWakeup.reason,
10494
- mutation: queuedWakeup.mutation,
10495
- previousStatus: queuedWakeup.previousStatus,
10496
- nextStatus: queuedWakeup.nextStatus
10497
- })
11081
+ async (queuedWakeup) => {
11082
+ await wakePaperclipIssueAssignee(ctx, {
11083
+ assigneeAgentId: queuedWakeup.assigneeAgentId,
11084
+ paperclipIssueId: queuedWakeup.paperclipIssueId,
11085
+ companyId: mapping.companyId,
11086
+ paperclipApiBaseUrl,
11087
+ reason: queuedWakeup.reason,
11088
+ mutation: queuedWakeup.mutation,
11089
+ actionFingerprint: queuedWakeup.actionFingerprint,
11090
+ previousStatus: queuedWakeup.previousStatus,
11091
+ nextStatus: queuedWakeup.nextStatus
11092
+ });
11093
+ await queuedWakeup.onSuccess?.();
11094
+ }
10498
11095
  );
10499
11096
  return {
10500
11097
  updatedStatusesCount
@@ -14075,6 +14672,12 @@ function mergeNamedValues(currentValues, params) {
14075
14672
  }
14076
14673
  return [...values.values()];
14077
14674
  }
14675
+ function sameNamedValues(left, right) {
14676
+ if (left.length !== right.length) return false;
14677
+ const normalizedLeft = left.map((value) => value.toLowerCase()).sort();
14678
+ const normalizedRight = right.map((value) => value.toLowerCase()).sort();
14679
+ return normalizedLeft.every((value, index) => value === normalizedRight[index]);
14680
+ }
14078
14681
  async function validateGithubToken(ctx, token) {
14079
14682
  const octokit = createGitHubOctokit(ctx, token.trim(), {
14080
14683
  logFailures: false,
@@ -14137,6 +14740,7 @@ async function performSync(ctx, trigger, options = {}) {
14137
14740
  const config = await getResolvedConfig(ctx);
14138
14741
  const settings = materializeScopedSettings(baseSettings, config, targetCompanyId);
14139
14742
  const importRegistry = normalizeImportRegistry(await ctx.state.get(IMPORT_REGISTRY_SCOPE));
14743
+ const remoteActionRegistry = normalizeRemoteActionRegistry(await ctx.state.get(REMOTE_ACTION_REGISTRY_SCOPE));
14140
14744
  let companyKpiState = normalizeCompanyKpiState(await ctx.state.get(COMPANY_KPI_SCOPE));
14141
14745
  let companyKpiStateDirty = false;
14142
14746
  const token = typeof options.resolvedToken === "string" ? options.resolvedToken : await resolveGithubToken(ctx, { companyId: targetCompanyId });
@@ -14146,6 +14750,10 @@ async function performSync(ctx, trigger, options = {}) {
14146
14750
  const externalLinkAuthMappings = buildExternalLinkAuthMappings(externalSyncWork);
14147
14751
  const externalLinkCount = externalSyncWork.issueLinks.length + externalSyncWork.pullRequestLinks.length;
14148
14752
  activePaperclipApiAuthTokensByCompanyId = null;
14753
+ activeGitHubPullRequestStatusSnapshotCache.clear();
14754
+ activeGitHubPullRequestStatusSnapshotPromiseCache.clear();
14755
+ activeGitHubPullRequestReviewThreadSummaryCache.clear();
14756
+ activeGitHubPullRequestReviewThreadSummaryPromiseCache.clear();
14149
14757
  const failureContext = {
14150
14758
  phase: "configuration"
14151
14759
  };
@@ -14686,6 +15294,7 @@ async function performSync(ctx, trigger, options = {}) {
14686
15294
  repositoryMaintainerCache,
14687
15295
  failureContext,
14688
15296
  recoverableFailures,
15297
+ async () => ctx.state.set(IMPORT_REGISTRY_SCOPE, nextRegistry),
14689
15298
  throwIfSyncCancelled,
14690
15299
  async (params) => {
14691
15300
  const recorded = recordCompanyActivityMetricEvent(companyKpiState, {
@@ -14725,6 +15334,12 @@ async function performSync(ctx, trigger, options = {}) {
14725
15334
  pullRequestStatusCache,
14726
15335
  failureContext,
14727
15336
  recoverableFailures,
15337
+ remoteActionRegistry,
15338
+ async () => {
15339
+ const compacted = normalizeRemoteActionRegistry(remoteActionRegistry);
15340
+ remoteActionRegistry.splice(0, remoteActionRegistry.length, ...compacted);
15341
+ await ctx.state.set(REMOTE_ACTION_REGISTRY_SCOPE, remoteActionRegistry);
15342
+ },
14728
15343
  throwIfSyncCancelled,
14729
15344
  async (progress) => {
14730
15345
  markTrackedPullRequestIssueProcessed(mapping, progress.pullRequestLink);
@@ -14804,7 +15419,10 @@ async function performSync(ctx, trigger, options = {}) {
14804
15419
  ...issueLink.data.paperclipProjectId ? { paperclipProjectId: issueLink.data.paperclipProjectId } : {},
14805
15420
  companyId
14806
15421
  };
14807
- const importedIssue = {
15422
+ const existingImportedIssue = nextRegistry.find(
15423
+ (entry) => entry.paperclipIssueId === issueLink.paperclipIssueId && entry.companyId === companyId && entry.repositoryUrl === repository.url
15424
+ );
15425
+ const importedIssue = existingImportedIssue ?? upsertImportedIssueRecord(nextRegistry, {
14808
15426
  mappingId: virtualMapping.id,
14809
15427
  githubIssueId: githubIssue.id,
14810
15428
  githubIssueNumber: githubIssue.number,
@@ -14816,7 +15434,10 @@ async function performSync(ctx, trigger, options = {}) {
14816
15434
  repositoryUrl: repository.url,
14817
15435
  ...issueLink.data.paperclipProjectId ? { paperclipProjectId: issueLink.data.paperclipProjectId } : {},
14818
15436
  companyId
14819
- };
15437
+ });
15438
+ if (!existingImportedIssue) {
15439
+ await ctx.state.set(IMPORT_REGISTRY_SCOPE, nextRegistry);
15440
+ }
14820
15441
  const synchronizationResult = await synchronizePaperclipIssueStatuses(
14821
15442
  ctx,
14822
15443
  octokit,
@@ -14834,6 +15455,7 @@ async function performSync(ctx, trigger, options = {}) {
14834
15455
  repositoryMaintainerCache,
14835
15456
  failureContext,
14836
15457
  recoverableFailures,
15458
+ async () => ctx.state.set(IMPORT_REGISTRY_SCOPE, nextRegistry),
14837
15459
  throwIfSyncCancelled,
14838
15460
  async (params) => {
14839
15461
  const recorded = recordCompanyActivityMetricEvent(companyKpiState, {
@@ -14914,6 +15536,12 @@ async function performSync(ctx, trigger, options = {}) {
14914
15536
  pullRequestStatusCache,
14915
15537
  failureContext,
14916
15538
  recoverableFailures,
15539
+ remoteActionRegistry,
15540
+ async () => {
15541
+ const compacted = normalizeRemoteActionRegistry(remoteActionRegistry);
15542
+ remoteActionRegistry.splice(0, remoteActionRegistry.length, ...compacted);
15543
+ await ctx.state.set(REMOTE_ACTION_REGISTRY_SCOPE, remoteActionRegistry);
15544
+ },
14917
15545
  throwIfSyncCancelled,
14918
15546
  async (progress) => {
14919
15547
  completedTrackedIssueCount += 1;
@@ -15132,6 +15760,240 @@ async function startSync(ctx, trigger, options = {}) {
15132
15760
  return getActiveOrCurrentSyncState(ctx);
15133
15761
  }
15134
15762
  }
15763
+ async function persistIssueInteractionEvent(ctx, event) {
15764
+ const sanitized = sanitizeIssueInteractionEvent(event);
15765
+ const contentAddress = createHash("sha256").update(JSON.stringify(sanitized)).digest("hex");
15766
+ await ctx.entities.upsert({
15767
+ entityType: ISSUE_INTERACTION_ENTITY_TYPE,
15768
+ scopeKind: "issue",
15769
+ scopeId: sanitized.paperclipIssueId,
15770
+ externalId: `event:${contentAddress}`,
15771
+ title: `${sanitized.source}: ${sanitized.action}`,
15772
+ status: sanitized.outcome,
15773
+ data: { ...sanitized }
15774
+ });
15775
+ }
15776
+ async function listIssueInteractionEvents(ctx, companyId, paperclipIssueId, range) {
15777
+ const byDedupeKey = /* @__PURE__ */ new Map();
15778
+ const conflictingKeys = /* @__PURE__ */ new Set();
15779
+ let malformedRows = 0;
15780
+ let scannedRows = 0;
15781
+ let scanTruncated = false;
15782
+ let ledgerStartedAt = null;
15783
+ const fromMs = Date.parse(range.from);
15784
+ const toMs = Date.parse(range.to);
15785
+ outer: for (let offset = 0; ; ) {
15786
+ const page = await ctx.entities.list({
15787
+ entityType: ISSUE_INTERACTION_ENTITY_TYPE,
15788
+ scopeKind: "issue",
15789
+ scopeId: paperclipIssueId,
15790
+ limit: 100,
15791
+ offset
15792
+ });
15793
+ for (const entry of page) {
15794
+ if (scannedRows >= ISSUE_INTERACTION_MAX_SCAN_ROWS) {
15795
+ scanTruncated = true;
15796
+ break outer;
15797
+ }
15798
+ scannedRows += 1;
15799
+ if (entry.scopeKind !== "issue" || entry.scopeId !== paperclipIssueId) continue;
15800
+ const raw = entry.data;
15801
+ if (raw?.companyId !== companyId || raw?.paperclipIssueId !== paperclipIssueId) continue;
15802
+ try {
15803
+ const event = sanitizeIssueInteractionEvent(raw);
15804
+ if (ledgerStartedAt === null || event.occurredAt < ledgerStartedAt) ledgerStartedAt = event.occurredAt;
15805
+ const serialized = JSON.stringify(event);
15806
+ const existing = byDedupeKey.get(event.dedupeKey);
15807
+ if (existing && existing.serialized !== serialized) conflictingKeys.add(event.dedupeKey);
15808
+ else if (!existing) byDedupeKey.set(event.dedupeKey, { event, serialized });
15809
+ } catch {
15810
+ malformedRows += 1;
15811
+ }
15812
+ }
15813
+ if (page.length < 100) break;
15814
+ offset += page.length;
15815
+ }
15816
+ const events = [...byDedupeKey.entries()].filter(([dedupeKey, { event }]) => {
15817
+ if (conflictingKeys.has(dedupeKey)) return false;
15818
+ const timestamp = Date.parse(event.occurredAt);
15819
+ return timestamp >= fromMs && timestamp < toMs;
15820
+ }).map(([, value]) => value.event);
15821
+ return {
15822
+ events,
15823
+ ledgerStartedAt,
15824
+ integrity: { malformedRows, conflictingKeys: conflictingKeys.size, scanTruncated, scannedRows }
15825
+ };
15826
+ }
15827
+ async function buildIssueInteractionSummaryForTool(ctx, input, runCtx) {
15828
+ const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
15829
+ if (!paperclipIssueId) throw new Error("paperclipIssueId is required.");
15830
+ const issue = await ctx.issues.get(paperclipIssueId, runCtx.companyId);
15831
+ if (!issue) throw new Error("Paperclip issue was not found in the authenticated company.");
15832
+ const range = parseIssueInteractionRange({ from: input.from, to: input.to });
15833
+ const ledger = await listIssueInteractionEvents(ctx, runCtx.companyId, paperclipIssueId, range);
15834
+ return buildIssueInteractionSummary({
15835
+ companyId: runCtx.companyId,
15836
+ paperclipIssueId,
15837
+ range,
15838
+ events: ledger.events,
15839
+ ledgerStartedAt: ledger.ledgerStartedAt,
15840
+ integrity: ledger.integrity
15841
+ });
15842
+ }
15843
+ function trackedMutationOutcome(result) {
15844
+ if (result.error) return "failed";
15845
+ const content = typeof result.content === "string" ? result.content.toLowerCase() : "";
15846
+ if (/\bno (?:github )?.*changes? (?:were )?requested\b/.test(content) || /\bwas already\b/.test(content) || /\bis already\b/.test(content)) {
15847
+ return "noop";
15848
+ }
15849
+ return "changed";
15850
+ }
15851
+ function resolveTrackedMutationRemoteFromInput(input) {
15852
+ const reference = normalizeOptionalToolString(input.reference);
15853
+ const issueReference = reference ? parseGitHubIssueHtmlUrl(reference) : void 0;
15854
+ const pullRequestReference = (reference ? parseGitHubPullRequestHtmlUrl(reference) : void 0) ?? parseGitHubPullRequestHtmlUrl(normalizeOptionalToolString(input.pullRequestUrl) ?? "");
15855
+ const explicitRepository = parseRepositoryReference(normalizeOptionalToolString(input.repository) ?? "");
15856
+ const explicitKind = normalizeIssueGitHubLinkKind(input.kind);
15857
+ const numericReference = normalizePositiveIntegerReference(input.reference);
15858
+ const explicitIssueNumber = normalizeToolPositiveInteger(input.issueNumber);
15859
+ const explicitPullRequestNumber = normalizeToolPositiveInteger(input.pullRequestNumber);
15860
+ let kind;
15861
+ let number;
15862
+ let repository = explicitRepository;
15863
+ if (explicitKind === "issue") {
15864
+ kind = "issue";
15865
+ number = issueReference?.issueNumber ?? numericReference ?? explicitIssueNumber;
15866
+ repository = parseRepositoryReference(issueReference?.repositoryUrl ?? "") ?? explicitRepository;
15867
+ } else if (explicitKind === "pull_request") {
15868
+ kind = "pull_request";
15869
+ number = pullRequestReference?.pullRequestNumber ?? explicitPullRequestNumber ?? numericReference;
15870
+ repository = parseRepositoryReference(pullRequestReference?.repositoryUrl ?? "") ?? explicitRepository;
15871
+ } else if (issueReference || explicitIssueNumber) {
15872
+ kind = "issue";
15873
+ number = issueReference?.issueNumber ?? explicitIssueNumber;
15874
+ repository = parseRepositoryReference(issueReference?.repositoryUrl ?? "") ?? explicitRepository;
15875
+ } else if (pullRequestReference || explicitPullRequestNumber) {
15876
+ kind = "pull_request";
15877
+ number = pullRequestReference?.pullRequestNumber ?? explicitPullRequestNumber;
15878
+ repository = parseRepositoryReference(pullRequestReference?.repositoryUrl ?? "") ?? explicitRepository;
15879
+ }
15880
+ if (!repository && !kind && !number) return void 0;
15881
+ return { repositoryUrl: repository?.url, kind, number };
15882
+ }
15883
+ var TRACKED_ISSUE_MUTATIONS = /* @__PURE__ */ new Set([
15884
+ "update_issue",
15885
+ "assign_to_current_user",
15886
+ "add_issue_comment"
15887
+ ]);
15888
+ var TRACKED_PULL_REQUEST_MUTATIONS = /* @__PURE__ */ new Set([
15889
+ "update_pull_request",
15890
+ "request_pull_request_reviewers",
15891
+ "add_pull_request_to_project",
15892
+ "upload_pull_request_asset"
15893
+ ]);
15894
+ async function resolveTrackedMutationRemote(ctx, action, input, runCtx) {
15895
+ const fallback = resolveTrackedMutationRemoteFromInput(input);
15896
+ try {
15897
+ if (TRACKED_ISSUE_MUTATIONS.has(action)) {
15898
+ const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
15899
+ return { repositoryUrl: target.repository.url, kind: "issue", number: target.issueNumber };
15900
+ }
15901
+ if (TRACKED_PULL_REQUEST_MUTATIONS.has(action)) {
15902
+ const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
15903
+ return { repositoryUrl: target.repository.url, kind: "pull_request", number: target.pullRequestNumber };
15904
+ }
15905
+ if (action === "create_pull_request") {
15906
+ const explicitRepository = parseRepositoryReference(normalizeOptionalToolString(input.repository) ?? "");
15907
+ const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
15908
+ const repository = explicitRepository ?? (paperclipIssueId ? (await resolveIssueGitHubLinkMapping(ctx, { companyId: runCtx.companyId, issueId: paperclipIssueId })).repository : void 0);
15909
+ if (repository) return { repositoryUrl: repository.url, kind: "pull_request" };
15910
+ }
15911
+ } catch {
15912
+ }
15913
+ return fallback;
15914
+ }
15915
+ function resolveTrackedMutationResultRemote(result, fallback) {
15916
+ const data = result.data && typeof result.data === "object" ? result.data : {};
15917
+ const pullRequest = data.pullRequest && typeof data.pullRequest === "object" ? data.pullRequest : {};
15918
+ const issue = data.issue && typeof data.issue === "object" ? data.issue : {};
15919
+ const repository = parseRepositoryReference(
15920
+ normalizeOptionalToolString(data.repository) ?? normalizeOptionalToolString(data.repositoryUrl) ?? fallback?.repositoryUrl ?? ""
15921
+ );
15922
+ const pullRequestNumber = normalizeToolPositiveInteger(data.pullRequestNumber) ?? normalizeToolPositiveInteger(data.githubPullRequestNumber) ?? normalizeToolPositiveInteger(pullRequest.number);
15923
+ const issueNumber = normalizeToolPositiveInteger(data.issueNumber) ?? normalizeToolPositiveInteger(data.githubIssueNumber) ?? normalizeToolPositiveInteger(issue.number);
15924
+ const kind = pullRequestNumber ? "pull_request" : issueNumber ? "issue" : fallback?.kind;
15925
+ const number = kind === "pull_request" ? pullRequestNumber ?? fallback?.number : kind === "issue" ? issueNumber ?? fallback?.number : fallback?.number;
15926
+ if (!repository && !kind && !number) return void 0;
15927
+ return { repositoryUrl: repository?.url, kind, number };
15928
+ }
15929
+ async function executeTrackedGitHubMutation(ctx, action, params, runCtx, fn) {
15930
+ return executeGitHubTool(async () => {
15931
+ const input = getToolInputRecord(params);
15932
+ const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
15933
+ if (paperclipIssueId && !await ctx.issues.get(paperclipIssueId, runCtx.companyId)) {
15934
+ throw new Error("Paperclip issue was not found in the authenticated company.");
15935
+ }
15936
+ const startedAt = /* @__PURE__ */ new Date();
15937
+ if (!paperclipIssueId) return fn();
15938
+ const runRecord = runCtx;
15939
+ const fingerprintInput = JSON.stringify(input, Object.keys(input).sort());
15940
+ const fingerprint = createHash("sha256").update(fingerprintInput).digest("hex").slice(0, 24);
15941
+ const runId = normalizeOptionalToolString(runRecord.runId);
15942
+ const remote = await resolveTrackedMutationRemote(ctx, action, input, runCtx);
15943
+ const attemptId = createHash("sha256").update([runId ?? "no-run-id", action, fingerprint, startedAt.toISOString(), randomUUID()].join("\n")).digest("hex");
15944
+ const dedupeBase = `agent_tool:${attemptId}`;
15945
+ await persistIssueInteractionEvent(ctx, {
15946
+ schemaVersion: 1,
15947
+ companyId: runCtx.companyId,
15948
+ paperclipIssueId,
15949
+ occurredAt: startedAt.toISOString(),
15950
+ category: action === "link_github_item" ? "paperclip_link" : action.includes("comment") || action.includes("reply") ? "comment" : "github_write",
15951
+ action,
15952
+ source: "agent_tool",
15953
+ actor: {
15954
+ agentId: normalizeOptionalToolString(runRecord.agentId),
15955
+ runId,
15956
+ llmModel: normalizeOptionalToolString(input.llmModel)
15957
+ },
15958
+ ...remote ? { remote } : {},
15959
+ outcome: "observed",
15960
+ durationMs: 0,
15961
+ dedupeKey: `${dedupeBase}:intent`
15962
+ });
15963
+ const result = await executeGitHubTool(fn);
15964
+ const resultRemote = resolveTrackedMutationResultRemote(result, remote);
15965
+ const durationMs = Math.max(0, Date.now() - startedAt.getTime());
15966
+ try {
15967
+ await persistIssueInteractionEvent(ctx, {
15968
+ schemaVersion: 1,
15969
+ companyId: runCtx.companyId,
15970
+ paperclipIssueId,
15971
+ occurredAt: startedAt.toISOString(),
15972
+ category: action === "link_github_item" ? "paperclip_link" : action.includes("comment") || action.includes("reply") ? "comment" : "github_write",
15973
+ action,
15974
+ source: "agent_tool",
15975
+ actor: {
15976
+ agentId: normalizeOptionalToolString(runRecord.agentId),
15977
+ runId,
15978
+ llmModel: normalizeOptionalToolString(input.llmModel)
15979
+ },
15980
+ ...resultRemote ? { remote: resultRemote } : {},
15981
+ outcome: trackedMutationOutcome(result),
15982
+ durationMs,
15983
+ dedupeKey: `${dedupeBase}:result`
15984
+ });
15985
+ } catch (persistenceError) {
15986
+ if (result.error) {
15987
+ throw new AggregateError(
15988
+ [new Error(result.error), persistenceError],
15989
+ `GitHub mutation failed (${result.error}) and its result could not be persisted: ${getErrorMessage(persistenceError)}`
15990
+ );
15991
+ }
15992
+ throw persistenceError;
15993
+ }
15994
+ return result;
15995
+ });
15996
+ }
15135
15997
  function resolveTrustedWorkspacePath(workspacePath, workspaceRelativePath) {
15136
15998
  if (!workspaceRelativePath) {
15137
15999
  return workspacePath;
@@ -15290,7 +16152,7 @@ function registerGitHubAgentTools(ctx) {
15290
16152
  ctx.tools.register(
15291
16153
  "update_issue",
15292
16154
  getGitHubAgentToolDeclaration("update_issue"),
15293
- async (params, runCtx) => executeGitHubTool(async () => {
16155
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "update_issue", params, runCtx, async () => {
15294
16156
  const input = getToolInputRecord(params);
15295
16157
  const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
15296
16158
  const octokit = await createAgentToolOctokit(runCtx, "update_issue", target.repository);
@@ -15320,7 +16182,9 @@ function registerGitHubAgentTools(ctx) {
15320
16182
  const body = Object.prototype.hasOwnProperty.call(input, "body") && typeof input.body === "string" ? appendOptionalAiAuthorshipFooter(input.body, "issue description", llmModel) : void 0;
15321
16183
  const state = input.state === "open" || input.state === "closed" ? input.state : void 0;
15322
16184
  const milestoneNumber = Object.prototype.hasOwnProperty.call(input, "milestoneNumber") ? input.milestoneNumber === null ? null : normalizeToolPositiveInteger(input.milestoneNumber) : void 0;
15323
- const hasChanges = title !== void 0 || body !== void 0 || state !== void 0 || Object.prototype.hasOwnProperty.call(input, "milestoneNumber") || normalizeToolStringArray(input.setLabels).length > 0 || normalizeToolStringArray(input.addLabels).length > 0 || normalizeToolStringArray(input.removeLabels).length > 0 || normalizeToolStringArray(input.setAssignees).length > 0 || normalizeToolStringArray(input.addAssignees).length > 0 || normalizeToolStringArray(input.removeAssignees).length > 0;
16185
+ const milestoneRequested = Object.prototype.hasOwnProperty.call(input, "milestoneNumber");
16186
+ const currentMilestoneNumber = currentIssue.milestone?.number ?? null;
16187
+ 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
16188
  const updatedResponse = hasChanges ? await octokit.rest.issues.update({
15325
16189
  owner: target.repository.owner,
15326
16190
  repo: target.repository.repo,
@@ -15328,7 +16192,7 @@ function registerGitHubAgentTools(ctx) {
15328
16192
  ...title !== void 0 ? { title } : {},
15329
16193
  ...body !== void 0 ? { body } : {},
15330
16194
  ...state ? { state } : {},
15331
- ...Object.prototype.hasOwnProperty.call(input, "milestoneNumber") ? { milestone: milestoneNumber } : {},
16195
+ ...milestoneRequested ? { milestone: milestoneNumber } : {},
15332
16196
  labels: nextLabels,
15333
16197
  assignees: nextAssignees,
15334
16198
  headers: {
@@ -15363,7 +16227,7 @@ function registerGitHubAgentTools(ctx) {
15363
16227
  ctx.tools.register(
15364
16228
  "assign_to_current_user",
15365
16229
  getGitHubAgentToolDeclaration("assign_to_current_user"),
15366
- async (params, runCtx) => executeGitHubTool(async () => {
16230
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "assign_to_current_user", params, runCtx, async () => {
15367
16231
  const input = getToolInputRecord(params);
15368
16232
  const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
15369
16233
  const octokit = await createAgentToolOctokit(runCtx, "assign_to_current_user", target.repository);
@@ -15423,7 +16287,7 @@ function registerGitHubAgentTools(ctx) {
15423
16287
  ctx.tools.register(
15424
16288
  "add_issue_comment",
15425
16289
  getGitHubAgentToolDeclaration("add_issue_comment"),
15426
- async (params, runCtx) => executeGitHubTool(async () => {
16290
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "add_issue_comment", params, runCtx, async () => {
15427
16291
  const input = getToolInputRecord(params);
15428
16292
  const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
15429
16293
  const octokit = await createAgentToolOctokit(runCtx, "add_issue_comment", target.repository);
@@ -15456,7 +16320,7 @@ function registerGitHubAgentTools(ctx) {
15456
16320
  ctx.tools.register(
15457
16321
  "create_pull_request",
15458
16322
  getGitHubAgentToolDeclaration("create_pull_request"),
15459
- async (params, runCtx) => executeGitHubTool(async () => {
16323
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "create_pull_request", params, runCtx, async () => {
15460
16324
  const input = getToolInputRecord(params);
15461
16325
  const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
15462
16326
  const explicitRepository = normalizeOptionalToolString(input.repository);
@@ -15673,7 +16537,7 @@ function registerGitHubAgentTools(ctx) {
15673
16537
  ctx.tools.register(
15674
16538
  "update_pull_request",
15675
16539
  getGitHubAgentToolDeclaration("update_pull_request"),
15676
- async (params, runCtx) => executeGitHubTool(async () => {
16540
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "update_pull_request", params, runCtx, async () => {
15677
16541
  const input = getToolInputRecord(params);
15678
16542
  const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
15679
16543
  const octokit = await createAgentToolOctokit(runCtx, "update_pull_request", target.repository);
@@ -15691,25 +16555,31 @@ function registerGitHubAgentTools(ctx) {
15691
16555
  const base = normalizeOptionalToolString(input.base);
15692
16556
  const state = input.state === "open" || input.state === "closed" ? input.state : void 0;
15693
16557
  const isDraft = typeof input.isDraft === "boolean" ? input.isDraft : void 0;
15694
- if (title !== void 0 || body !== void 0 || base !== void 0 || state !== void 0) {
16558
+ let changed = false;
16559
+ const update = {
16560
+ ...title !== void 0 && title !== currentResponse.data.title ? { title } : {},
16561
+ ...body !== void 0 && body !== (currentResponse.data.body ?? "") ? { body } : {},
16562
+ ...base !== void 0 && base !== currentResponse.data.base.ref ? { base } : {},
16563
+ ...state !== void 0 && state !== currentResponse.data.state ? { state } : {}
16564
+ };
16565
+ if (Object.keys(update).length > 0) {
15695
16566
  currentResponse = await octokit.rest.pulls.update({
15696
16567
  owner: target.repository.owner,
15697
16568
  repo: target.repository.repo,
15698
16569
  pull_number: target.pullRequestNumber,
15699
- ...title !== void 0 ? { title } : {},
15700
- ...body !== void 0 ? { body } : {},
15701
- ...base !== void 0 ? { base } : {},
15702
- ...state !== void 0 ? { state } : {},
16570
+ ...update,
15703
16571
  headers: {
15704
16572
  "X-GitHub-Api-Version": GITHUB_API_VERSION
15705
16573
  }
15706
16574
  });
16575
+ changed = true;
15707
16576
  }
15708
16577
  if (isDraft !== void 0 && currentResponse.data.draft !== isDraft) {
15709
16578
  if (!currentResponse.data.node_id) {
15710
16579
  throw new Error("GitHub did not return a pull request node id, so draft state cannot be updated.");
15711
16580
  }
15712
16581
  await updatePullRequestDraftState(octokit, currentResponse.data.node_id, isDraft);
16582
+ changed = true;
15713
16583
  currentResponse = await octokit.rest.pulls.get({
15714
16584
  owner: target.repository.owner,
15715
16585
  repo: target.repository.repo,
@@ -15720,7 +16590,7 @@ function registerGitHubAgentTools(ctx) {
15720
16590
  });
15721
16591
  }
15722
16592
  return buildToolSuccessResult(
15723
- `Updated pull request #${currentResponse.data.number} in ${formatRepositoryLabel(target.repository)}.`,
16593
+ 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
16594
  {
15725
16595
  repository: target.repository.url,
15726
16596
  pullRequest: {
@@ -15874,7 +16744,7 @@ function registerGitHubAgentTools(ctx) {
15874
16744
  ctx.tools.register(
15875
16745
  "reply_to_review_thread",
15876
16746
  getGitHubAgentToolDeclaration("reply_to_review_thread"),
15877
- async (params, runCtx) => executeGitHubTool(async () => {
16747
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "reply_to_review_thread", params, runCtx, async () => {
15878
16748
  const input = getToolInputRecord(params);
15879
16749
  const threadId = normalizeOptionalToolString(input.threadId);
15880
16750
  if (!threadId) {
@@ -15910,7 +16780,7 @@ function registerGitHubAgentTools(ctx) {
15910
16780
  ctx.tools.register(
15911
16781
  "resolve_review_thread",
15912
16782
  getGitHubAgentToolDeclaration("resolve_review_thread"),
15913
- async (params, runCtx) => executeGitHubTool(async () => {
16783
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "resolve_review_thread", params, runCtx, async () => {
15914
16784
  const input = getToolInputRecord(params);
15915
16785
  const threadId = normalizeOptionalToolString(input.threadId);
15916
16786
  if (!threadId) {
@@ -15941,7 +16811,7 @@ function registerGitHubAgentTools(ctx) {
15941
16811
  ctx.tools.register(
15942
16812
  "unresolve_review_thread",
15943
16813
  getGitHubAgentToolDeclaration("unresolve_review_thread"),
15944
- async (params, runCtx) => executeGitHubTool(async () => {
16814
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "unresolve_review_thread", params, runCtx, async () => {
15945
16815
  const input = getToolInputRecord(params);
15946
16816
  const threadId = normalizeOptionalToolString(input.threadId);
15947
16817
  if (!threadId) {
@@ -15972,7 +16842,7 @@ function registerGitHubAgentTools(ctx) {
15972
16842
  ctx.tools.register(
15973
16843
  "request_pull_request_reviewers",
15974
16844
  getGitHubAgentToolDeclaration("request_pull_request_reviewers"),
15975
- async (params, runCtx) => executeGitHubTool(async () => {
16845
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "request_pull_request_reviewers", params, runCtx, async () => {
15976
16846
  const input = getToolInputRecord(params);
15977
16847
  const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
15978
16848
  const userReviewers = normalizeToolStringArray(input.userReviewers);
@@ -16029,7 +16899,7 @@ function registerGitHubAgentTools(ctx) {
16029
16899
  ctx.tools.register(
16030
16900
  "add_pull_request_to_project",
16031
16901
  getGitHubAgentToolDeclaration("add_pull_request_to_project"),
16032
- async (params, runCtx) => executeGitHubTool(async () => {
16902
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "add_pull_request_to_project", params, runCtx, async () => {
16033
16903
  const input = getToolInputRecord(params);
16034
16904
  const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
16035
16905
  const octokit = await createAgentToolOctokit(runCtx, "add_pull_request_to_project", target.repository);
@@ -16090,7 +16960,7 @@ function registerGitHubAgentTools(ctx) {
16090
16960
  ctx.tools.register(
16091
16961
  "upload_pull_request_asset",
16092
16962
  getGitHubAgentToolDeclaration("upload_pull_request_asset"),
16093
- async (params, runCtx) => executeGitHubTool(async () => {
16963
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "upload_pull_request_asset", params, runCtx, async () => {
16094
16964
  const input = getToolInputRecord(params);
16095
16965
  const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
16096
16966
  const octokit = await createAgentToolOctokit(runCtx, "upload_pull_request_asset", target.repository);
@@ -16111,7 +16981,7 @@ function registerGitHubAgentTools(ctx) {
16111
16981
  ctx.tools.register(
16112
16982
  "link_github_item",
16113
16983
  getGitHubAgentToolDeclaration("link_github_item"),
16114
- async (params, runCtx) => executeGitHubTool(async () => {
16984
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "link_github_item", params, runCtx, async () => {
16115
16985
  const input = getToolInputRecord(params);
16116
16986
  const kind = normalizeIssueGitHubLinkKind(input.kind);
16117
16987
  if (!kind) {
@@ -16144,6 +17014,17 @@ function registerGitHubAgentTools(ctx) {
16144
17014
  );
16145
17015
  })
16146
17016
  );
17017
+ ctx.tools.register(
17018
+ "get_issue_interaction_summary",
17019
+ getGitHubAgentToolDeclaration("get_issue_interaction_summary"),
17020
+ async (params, runCtx) => executeGitHubTool(async () => {
17021
+ const summary = await buildIssueInteractionSummaryForTool(ctx, getToolInputRecord(params), runCtx);
17022
+ return buildToolSuccessResult(
17023
+ `Loaded ${summary.counts.events} captured interactions for Paperclip issue ${summary.paperclipIssueId}.`,
17024
+ { summary }
17025
+ );
17026
+ })
17027
+ );
16147
17028
  }
16148
17029
  function shouldStartWorkerHost(moduleUrl, entry = process.argv[1]) {
16149
17030
  if (typeof entry !== "string" || !entry.trim()) {
@@ -16157,16 +17038,24 @@ function shouldStartWorkerHost(moduleUrl, entry = process.argv[1]) {
16157
17038
  }
16158
17039
  }
16159
17040
  var __testing = {
17041
+ buildDirectPullRequestActionFingerprint,
17042
+ buildRemoteActionFingerprint,
16160
17043
  buildSyncFallbackExecutionStatePatch,
16161
17044
  createGitHubToolOctokit,
16162
17045
  formatPaperclipApiFetchErrorMessage,
16163
17046
  hasUnresolvedPaperclipIssueBlocker,
16164
17047
  isHealthyMaintainerWaitTransition,
17048
+ normalizeImportRegistry,
17049
+ normalizeRemoteActionRegistry,
17050
+ persistIssueInteractionEvent,
17051
+ trackedMutationOutcome,
16165
17052
  resolvePaperclipApiAuthTokens,
16166
17053
  resolveGithubToken,
16167
17054
  resolvePaperclipPullRequestIssueStatus,
16168
17055
  resolveSyncTransitionAssignee,
16169
17056
  resolveTrustedWorkspacePath,
17057
+ updatePaperclipIssueState,
17058
+ wakePaperclipIssueAssignee,
16170
17059
  setCreatePullRequestBranchPublisher(publisher) {
16171
17060
  createPullRequestBranchPublisher = publisher ?? publishLocalBranchForPullRequest;
16172
17061
  }