paperclip-github-plugin 0.15.0 → 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,9 +1,10 @@
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";
6
- import { dirname, join as join2, resolve as resolve2 } from "node:path";
7
+ import { dirname, isAbsolute as isAbsolute2, join as join2, relative, resolve as resolve2 } from "node:path";
7
8
  import { fileURLToPath } from "node:url";
8
9
  import { Octokit } from "@octokit/rest";
9
10
  import {
@@ -272,7 +273,11 @@ var GITHUB_AGENT_TOOLS = [
272
273
  properties: {
273
274
  repository: {
274
275
  type: "string",
275
- description: "Target GitHub repository as owner/repo or https://github.com/owner/repo. It may be outside Paperclip repository mappings, but it must match the issue execution workspace. Omit only when the issue project has exactly one mapped repository."
276
+ description: "Target GitHub repository as owner/repo or https://github.com/owner/repo. It may be outside Paperclip repository mappings. Omit only when the issue project has exactly one mapped repository."
277
+ },
278
+ workspaceRelativePath: {
279
+ type: "string",
280
+ description: "Optional path to the local Git checkout, relative to the trusted issue execution workspace. Use this when a general-purpose workspace contains the target repository in a subdirectory."
276
281
  },
277
282
  paperclipIssueId: {
278
283
  type: "string",
@@ -417,7 +422,8 @@ var GITHUB_AGENT_TOOLS = [
417
422
  minLength: 1,
418
423
  description: "Human-facing reply body without the AI footer. It must remain non-empty after trimming and removing any existing AI footer."
419
424
  },
420
- llmModel: llmModelProperty
425
+ llmModel: llmModelProperty,
426
+ paperclipIssueId: paperclipIssueIdProperty
421
427
  }
422
428
  }
423
429
  },
@@ -433,7 +439,8 @@ var GITHUB_AGENT_TOOLS = [
433
439
  threadId: {
434
440
  type: "string",
435
441
  description: "GitHub pull request review thread node id."
436
- }
442
+ },
443
+ paperclipIssueId: paperclipIssueIdProperty
437
444
  }
438
445
  }
439
446
  },
@@ -449,7 +456,8 @@ var GITHUB_AGENT_TOOLS = [
449
456
  threadId: {
450
457
  type: "string",
451
458
  description: "GitHub pull request review thread node id."
452
- }
459
+ },
460
+ paperclipIssueId: paperclipIssueIdProperty
453
461
  }
454
462
  }
455
463
  },
@@ -641,6 +649,30 @@ var GITHUB_AGENT_TOOLS = [
641
649
  }
642
650
  }
643
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
+ }
644
676
  }
645
677
  ];
646
678
  function getGitHubAgentToolDeclaration(name) {
@@ -993,6 +1025,228 @@ function parseRepositoryReference(repositoryInput) {
993
1025
  }
994
1026
  }
995
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
+
996
1250
  // src/kpi-contract.ts
997
1251
  var GITHUB_SYNC_PLUGIN_ID = "paperclip-github-plugin";
998
1252
  var COMPANY_METRIC_API_ROUTE_KEY = "record-company-metric-event";
@@ -1049,6 +1303,10 @@ var IMPORT_REGISTRY_SCOPE = {
1049
1303
  scopeKind: "instance",
1050
1304
  stateKey: "paperclip-github-plugin-import-registry"
1051
1305
  };
1306
+ var REMOTE_ACTION_REGISTRY_SCOPE = {
1307
+ scopeKind: "instance",
1308
+ stateKey: "paperclip-github-plugin-remote-action-registry"
1309
+ };
1052
1310
  var COMPANY_KPI_SCOPE = {
1053
1311
  scopeKind: "instance",
1054
1312
  stateKey: "paperclip-github-plugin-company-kpis"
@@ -1081,7 +1339,9 @@ var INTERRUPTED_SYNC_ACTION = "Run GitHub sync again. If it stops on the same re
1081
1339
  var SYNC_PROGRESS_PERSIST_INTERVAL_MS = 250;
1082
1340
  var MAX_SYNC_FAILURE_LOG_ENTRIES = 25;
1083
1341
  var GITHUB_SECONDARY_RATE_LIMIT_FALLBACK_MS = 6e4;
1084
- 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;
1085
1345
  var COMPANY_KPI_CHART_WINDOW_DAYS = 14;
1086
1346
  var COMPANY_KPI_COMPARISON_WINDOW_DAYS = 30;
1087
1347
  var MAX_COMPANY_BACKLOG_SNAPSHOTS = 180;
@@ -1274,6 +1534,7 @@ var GITHUB_PULL_REQUEST_CI_CONTEXTS_QUERY = `
1274
1534
  query GitHubPullRequestCiContexts($owner: String!, $repo: String!, $pullRequestNumber: Int!, $after: String) {
1275
1535
  repository(owner: $owner, name: $repo) {
1276
1536
  pullRequest(number: $pullRequestNumber) {
1537
+ headRefOid
1277
1538
  mergeable
1278
1539
  mergeStateStatus
1279
1540
  reviewDecision
@@ -1340,6 +1601,7 @@ var GITHUB_REPOSITORY_OPEN_PULL_REQUEST_STATUSES_QUERY = `
1340
1601
  }
1341
1602
  nodes {
1342
1603
  number
1604
+ headRefOid
1343
1605
  mergeable
1344
1606
  mergeStateStatus
1345
1607
  reviewDecision
@@ -5067,6 +5329,8 @@ function normalizeImportRegistry(value) {
5067
5329
  const linkedPullRequestCommentCounts = normalizeGitHubPullRequestCommentCountRecords(
5068
5330
  record.linkedPullRequestCommentCounts
5069
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);
5070
5334
  if (!mappingId || Number.isNaN(githubIssueId) || !paperclipIssueId || !importedAt) {
5071
5335
  return null;
5072
5336
  }
@@ -5081,10 +5345,66 @@ function normalizeImportRegistry(value) {
5081
5345
  ...companyId ? { companyId } : {},
5082
5346
  ...lastSeenCommentCount !== void 0 ? { lastSeenCommentCount } : {},
5083
5347
  ...lastSeenGitHubState ? { lastSeenGitHubState } : {},
5084
- ...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : {}
5348
+ ...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : {},
5349
+ ...remoteActionFingerprint ? { remoteActionFingerprint } : {},
5350
+ ...pendingRemoteActionWake ? { pendingRemoteActionWake } : {}
5085
5351
  };
5086
5352
  }).filter((entry) => entry !== null);
5087
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
+ }
5088
5408
  function normalizeExternalGitHubLinkCompanyIndex(value) {
5089
5409
  const rawCompanyIds = Array.isArray(value) ? value : value && typeof value === "object" && Array.isArray(value.companyIds) ? value.companyIds : [];
5090
5410
  const companyIds = [
@@ -5986,7 +6306,7 @@ function isHealthyMaintainerWaitTransition(params) {
5986
6306
  return nextStatus === "in_review" && (currentStatus === "done" || currentStatus === "in_review") && isClearableMaintainerWaitExecutionState(syncContext.executionState);
5987
6307
  }
5988
6308
  function isClearableMaintainerWaitExecutionState(executionState) {
5989
- if (executionState === null) {
6309
+ if (executionState === null || executionState.status === "completed") {
5990
6310
  return true;
5991
6311
  }
5992
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) {
@@ -6229,9 +6549,12 @@ function resolvePaperclipPullRequestIssueStatus(params) {
6229
6549
  });
6230
6550
  }
6231
6551
  function resolvePaperclipDirectPullRequestIssueStatus(params) {
6232
- const { currentStatus, pullRequests, hasExecutorHandoffTarget } = params;
6552
+ const { currentStatus, pullRequests, hasExecutorHandoffTarget, hasTrustedNewComment } = params;
6233
6553
  const openPullRequests = pullRequests.map((entry) => entry.pullRequest).filter((pullRequest) => Boolean(pullRequest));
6234
6554
  if (openPullRequests.length > 0) {
6555
+ if (hasTrustedNewComment) {
6556
+ return currentStatus === "backlog" ? "backlog" : hasExecutorHandoffTarget ? "in_progress" : "todo";
6557
+ }
6235
6558
  if (shouldPreserveBlockedExternalPullRequestWait({
6236
6559
  currentStatus,
6237
6560
  linkedPullRequests: openPullRequests
@@ -6453,6 +6776,7 @@ function tryBuildGitHubPullRequestStatusSnapshotFromBatchNode(node, repository)
6453
6776
  return {
6454
6777
  number: node.number,
6455
6778
  repositoryUrl: repository.url,
6779
+ ...typeof node.headRefOid === "string" && node.headRefOid.trim() ? { headSha: node.headRefOid.trim().toLowerCase() } : {},
6456
6780
  hasUnresolvedReviewThreads: reviewThreadSummary.unresolvedReviewThreads > 0,
6457
6781
  ciState,
6458
6782
  mergeability: normalizeGitHubPullRequestMergeability(node.mergeable),
@@ -6512,6 +6836,7 @@ async function getGitHubPullRequestCiState(octokit, repository, pullRequestNumbe
6512
6836
  }
6513
6837
  async function getGitHubPullRequestCiSnapshot(octokit, repository, pullRequestNumber) {
6514
6838
  const contexts = [];
6839
+ let headSha;
6515
6840
  let mergeability = "unknown";
6516
6841
  let mergeStateStatus = "unknown";
6517
6842
  let reviewDecision = "unknown";
@@ -6526,6 +6851,10 @@ async function getGitHubPullRequestCiSnapshot(octokit, repository, pullRequestNu
6526
6851
  mergeability = normalizeGitHubPullRequestMergeability(response.repository?.pullRequest?.mergeable);
6527
6852
  mergeStateStatus = normalizeGitHubPullRequestMergeStateStatus(response.repository?.pullRequest?.mergeStateStatus);
6528
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
+ }
6529
6858
  const connection = response.repository?.pullRequest?.statusCheckRollup?.contexts;
6530
6859
  const nodes = connection?.nodes ?? [];
6531
6860
  for (const node of nodes) {
@@ -6550,6 +6879,7 @@ async function getGitHubPullRequestCiSnapshot(octokit, repository, pullRequestNu
6550
6879
  after = getPageCursor(connection?.pageInfo);
6551
6880
  } while (after);
6552
6881
  return {
6882
+ ...headSha ? { headSha } : {},
6553
6883
  ciState: classifyGitHubPullRequestCiState(contexts),
6554
6884
  mergeability,
6555
6885
  mergeStateStatus,
@@ -6599,6 +6929,7 @@ async function getGitHubPullRequestStatusSnapshot(octokit, repository, pullReque
6599
6929
  return cacheGitHubPullRequestStatusSnapshot(repository, {
6600
6930
  number: pullRequestNumber,
6601
6931
  repositoryUrl: repository.url,
6932
+ ..."headSha" in ciSnapshot && ciSnapshot.headSha ? { headSha: ciSnapshot.headSha } : {},
6602
6933
  hasUnresolvedReviewThreads: reviewThreadSummary.unresolvedReviewThreads > 0,
6603
6934
  ciState: ciSnapshot.ciState,
6604
6935
  mergeability: ciSnapshot.mergeability,
@@ -6936,7 +7267,7 @@ async function hasTrustedNewLinkedPullRequestComments(params) {
6936
7267
  octokit: params.octokit,
6937
7268
  repository: pullRequestRepository,
6938
7269
  comments: newTopLevelComments,
6939
- originalPosterLogin: params.githubIssue.authorLogin,
7270
+ originalPosterLogin: params.originalPosterLogin,
6940
7271
  maintainerCache: params.maintainerCache
6941
7272
  })) {
6942
7273
  return true;
@@ -6954,7 +7285,7 @@ async function hasTrustedNewLinkedPullRequestComments(params) {
6954
7285
  octokit: params.octokit,
6955
7286
  repository: pullRequestRepository,
6956
7287
  comments: newReviewComments,
6957
- originalPosterLogin: params.githubIssue.authorLogin,
7288
+ originalPosterLogin: params.originalPosterLogin,
6958
7289
  maintainerCache: params.maintainerCache
6959
7290
  })) {
6960
7291
  return true;
@@ -7133,7 +7464,7 @@ function normalizeGitHubPullRequestCommentCountRecords(value) {
7133
7464
  return repositoryComparison;
7134
7465
  }
7135
7466
  return left.number - right.number;
7136
- });
7467
+ }).slice(0, MAX_PULL_REQUEST_COMMENT_WATERMARKS);
7137
7468
  }
7138
7469
  function normalizeLinkedPullRequestReferences(values, fallbackRepositoryUrl) {
7139
7470
  const references = [];
@@ -8487,19 +8818,15 @@ async function wakePaperclipIssueAssignee(ctx, params) {
8487
8818
  await ctx.issues.requestWakeup(params.paperclipIssueId, params.companyId, {
8488
8819
  reason: params.reason,
8489
8820
  contextSource: `github-sync.${params.mutation}`,
8490
- ...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(":") } : {}
8491
8822
  });
8492
8823
  return;
8493
8824
  } catch (error) {
8494
8825
  if (!params.paperclipApiBaseUrl) {
8495
- ctx.logger.warn("GitHub sync could not wake the assignee for a Paperclip issue through the SDK.", {
8496
- issueId: params.paperclipIssueId,
8497
- agentId: params.assigneeAgentId,
8498
- companyId: params.companyId,
8499
- mutation: params.mutation,
8500
- error: error instanceof Error ? error.message : String(error)
8501
- });
8502
- 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
+ );
8503
8830
  }
8504
8831
  ctx.logger.warn("GitHub sync could not wake the assignee through the SDK. Falling back to the local Paperclip API.", {
8505
8832
  issueId: params.paperclipIssueId,
@@ -8511,7 +8838,7 @@ async function wakePaperclipIssueAssignee(ctx, params) {
8511
8838
  }
8512
8839
  }
8513
8840
  if (!params.paperclipApiBaseUrl) {
8514
- return;
8841
+ throw new Error(`GitHub sync has no available wakeup transport for Paperclip issue ${params.paperclipIssueId}.`);
8515
8842
  }
8516
8843
  try {
8517
8844
  const response = await fetchPaperclipApi(
@@ -8526,6 +8853,7 @@ async function wakePaperclipIssueAssignee(ctx, params) {
8526
8853
  source: "assignment",
8527
8854
  triggerDetail: "system",
8528
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(":") } : {},
8529
8857
  payload: {
8530
8858
  issueId: params.paperclipIssueId,
8531
8859
  mutation: params.mutation,
@@ -8542,14 +8870,10 @@ async function wakePaperclipIssueAssignee(ctx, params) {
8542
8870
  throw new Error(`Wakeup request failed with status ${response.status}.`);
8543
8871
  }
8544
8872
  } catch (error) {
8545
- ctx.logger.warn("GitHub sync could not wake the assignee for a Paperclip issue.", {
8546
- issueId: params.paperclipIssueId,
8547
- agentId: params.assigneeAgentId,
8548
- companyId: params.companyId,
8549
- paperclipApiBaseUrl: params.paperclipApiBaseUrl,
8550
- mutation: params.mutation,
8551
- error: error instanceof Error ? error.message : String(error)
8552
- });
8873
+ throw new Error(
8874
+ `GitHub sync could not wake the assignee for Paperclip issue ${params.paperclipIssueId}: ${getErrorMessage(error)}`,
8875
+ { cause: error }
8876
+ );
8553
8877
  }
8554
8878
  }
8555
8879
  function parsePaperclipIssueDescription(value) {
@@ -9246,6 +9570,81 @@ function doIssueNumberListsMatch(left, right) {
9246
9570
  }
9247
9571
  return left.every((value, index) => value === right[index]);
9248
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
+ }
9249
9648
  async function updatePaperclipIssueState(ctx, params) {
9250
9649
  const {
9251
9650
  companyId,
@@ -9261,6 +9660,7 @@ async function updatePaperclipIssueState(ctx, params) {
9261
9660
  paperclipApiBaseUrl
9262
9661
  } = params;
9263
9662
  const trimmedTransitionComment = transitionComment.trim();
9663
+ const interactionOccurredAt = (/* @__PURE__ */ new Date()).toISOString();
9264
9664
  const statusWillChange = currentStatus !== nextStatus;
9265
9665
  let createdTransitionComment = null;
9266
9666
  let issueUpdated = false;
@@ -9287,120 +9687,172 @@ async function updatePaperclipIssueState(ctx, params) {
9287
9687
  issuePatch.assigneeAgentId = null;
9288
9688
  issuePatch.assigneeUserId = null;
9289
9689
  }
9290
- if (statusWillChange) {
9291
- if (!trimmedTransitionComment) {
9292
- throw new Error("GitHub Sync refused to update a Paperclip issue status without an explanatory transition comment.");
9293
- }
9294
- if (typeof ctx.issues.createComment !== "function") {
9295
- 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.");
9296
- }
9297
- 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.");
9298
9692
  }
9299
- if (paperclipApiBaseUrl) {
9300
- try {
9301
- const response = await fetchPaperclipApi(
9302
- getPaperclipIssueEndpoint(paperclipApiBaseUrl, issueId),
9303
- {
9304
- method: "PATCH",
9305
- headers: {
9306
- accept: "application/json",
9307
- "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)
9308
9753
  },
9309
- body: JSON.stringify(issuePatch)
9310
- },
9311
- {
9312
- companyId
9313
- }
9314
- );
9315
- const payloadResult = await readPaperclipApiJsonResponse(response, {
9316
- operationLabel: "issue update",
9317
- bodyRequired: false
9318
- });
9319
- if (!payloadResult.failure) {
9320
- issueUpdated = true;
9321
- if (issuePatch.executionState === null && ctx.issues && typeof ctx.issues.update === "function") {
9322
- try {
9323
- await ctx.issues.update(
9324
- issueId,
9325
- { executionState: null },
9326
- companyId
9327
- );
9328
- } catch (error) {
9329
- issueUpdated = false;
9330
- ctx.logger.warn("GitHub sync could not clear Paperclip issue execution state after the local API update. Falling back to direct issue mutation.", {
9331
- companyId,
9332
- issueId,
9333
- paperclipApiBaseUrl,
9334
- nextStatus,
9335
- error: getErrorMessage(error)
9336
- });
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
+ }
9337
9781
  }
9338
9782
  }
9339
- }
9340
- 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) {
9341
9794
  logPaperclipIssueStatusUpdateFailure(ctx, {
9342
9795
  companyId,
9343
9796
  issueId,
9344
9797
  paperclipApiBaseUrl,
9345
9798
  nextStatus,
9346
- status: payloadResult.failure.status ?? response.status,
9347
- errorMessage: payloadResult.failure.errorMessage
9799
+ errorMessage: getErrorMessage(error)
9348
9800
  });
9349
9801
  }
9350
- } catch (error) {
9351
- logPaperclipIssueStatusUpdateFailure(ctx, {
9352
- companyId,
9353
- issueId,
9354
- paperclipApiBaseUrl,
9355
- nextStatus,
9356
- errorMessage: getErrorMessage(error)
9357
- });
9358
- }
9359
- }
9360
- if (!issueUpdated) {
9361
- const preserveExistingUserAssigneeWithoutLocalApi = nextAssignee?.kind === "user" && !paperclipApiBaseUrl;
9362
- const sdkIssuePatch = {
9363
- ...issuePatch,
9364
- ...syncExecutionStatePatch !== void 0 ? { executionState: syncExecutionStatePatch } : {}
9365
- };
9366
- if (preserveExistingUserAssigneeWithoutLocalApi) {
9367
- delete sdkIssuePatch.assigneeAgentId;
9368
- delete sdkIssuePatch.assigneeUserId;
9369
- ctx.logger.warn("GitHub sync could not reassign a Paperclip issue to a user without the local Paperclip API. Preserving the existing assignee.", {
9370
- companyId,
9371
- issueId,
9372
- nextStatus,
9373
- assigneeUserId: nextAssignee.id
9374
- });
9375
9802
  }
9376
- await ctx.issues.update(issueId, sdkIssuePatch, companyId);
9377
- }
9378
- if (createdTransitionComment) {
9379
- if (transitionCommentAnnotation) {
9380
- await upsertStatusTransitionCommentAnnotation(ctx, {
9381
- issueId,
9382
- commentId: createdTransitionComment.id,
9383
- annotation: {
9384
- ...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.", {
9385
9813
  companyId,
9386
- paperclipIssueId: issueId
9387
- }
9388
- });
9814
+ issueId,
9815
+ nextStatus,
9816
+ assigneeUserId: nextAssignee.id
9817
+ });
9818
+ }
9819
+ await ctx.issues.update(issueId, sdkIssuePatch, companyId);
9389
9820
  }
9390
- } else if (trimmedTransitionComment && typeof ctx.issues.createComment === "function") {
9391
- const createdComment = await ctx.issues.createComment(issueId, trimmedTransitionComment, companyId);
9392
- if (transitionCommentAnnotation) {
9393
- await upsertStatusTransitionCommentAnnotation(ctx, {
9394
- issueId,
9395
- commentId: createdComment.id,
9396
- annotation: {
9397
- ...transitionCommentAnnotation,
9398
- companyId,
9399
- paperclipIssueId: issueId
9400
- }
9401
- });
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.");
9402
9852
  }
9853
+ throw error;
9403
9854
  }
9855
+ await persistSyncResult(statusWillChange ? "changed" : "noop");
9404
9856
  }
9405
9857
  function sortIssuesForImport(issues) {
9406
9858
  return [...issues].sort((left, right) => {
@@ -9946,7 +10398,7 @@ async function reconcileTransferredImportedIssues(ctx, params) {
9946
10398
  updatedDescriptionsCount
9947
10399
  };
9948
10400
  }
9949
- 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) {
9950
10402
  if (!mapping.companyId || !ctx.issues || typeof ctx.issues.get !== "function" || typeof ctx.issues.update !== "function") {
9951
10403
  return {
9952
10404
  updatedStatusesCount: 0,
@@ -10102,12 +10554,29 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10102
10554
  }
10103
10555
  const hasTrustedNewLinkedPullRequestComment = paperclipIssue.status === "backlog" || currentLinkedPullRequestCommentCounts.length === 0 ? false : await hasTrustedNewLinkedPullRequestComments({
10104
10556
  octokit,
10105
- githubIssue,
10557
+ originalPosterLogin: githubIssue.authorLogin,
10106
10558
  previousCommentCounts: importedIssue.linkedPullRequestCommentCounts,
10107
10559
  currentCommentCounts: currentLinkedPullRequestCommentCounts,
10108
10560
  maintainerCache: repositoryMaintainerCache
10109
10561
  });
10110
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
+ }
10111
10580
  const wasImportedThisRun = createdIssueIds.has(importedIssue.githubIssueId);
10112
10581
  const maintainerAuthoredImportedIssue = wasImportedThisRun && advancedSettings.defaultStatus !== "todo" && snapshot.state === "open" && snapshot.linkedPullRequests.length === 0 ? await isMaintainerAuthoredGitHubIssue({
10113
10582
  octokit,
@@ -10132,6 +10601,9 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10132
10601
  if (paperclipIssue.status === "blocked" && nextStatus !== "blocked" && await hasUnresolvedPaperclipIssueBlocker(ctx, paperclipIssue, mapping.companyId)) {
10133
10602
  nextStatus = "blocked";
10134
10603
  }
10604
+ if (paperclipIssue.status !== nextStatus && !hasTrustedNewComment && importedIssue.remoteActionFingerprint === remoteActionFingerprint) {
10605
+ nextStatus = paperclipIssue.status;
10606
+ }
10135
10607
  const shouldPreserveMaintainerWaitRouting = isHealthyMaintainerWaitTransition({
10136
10608
  currentStatus: paperclipIssue.status,
10137
10609
  nextStatus,
@@ -10157,10 +10629,15 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10157
10629
  const nextAssigneeChanged = nextTransitionAssignee ? !doesPaperclipIssueAssigneeMatch(paperclipIssueSyncContext.assignee, nextTransitionAssignee.principal) : false;
10158
10630
  const shouldWakeImportedAssignee = wasImportedThisRun && nextStatus === "todo" && (paperclipIssue.status === nextStatus || shouldPreserveImportedTriageRouting) && paperclipIssueSyncContext.assignee?.kind === "agent";
10159
10631
  const shouldWakeTransitionAssignee = paperclipIssue.status !== nextStatus && nextTransitionAssignee?.principal.kind === "agent" && isActionablePaperclipIssueStatus(nextStatus) && (nextAssigneeChanged || paperclipIssue.status !== nextStatus);
10160
- importedIssue.githubIssueNumber = githubIssue.number;
10161
- importedIssue.lastSeenCommentCount = snapshot.commentCount;
10162
- importedIssue.lastSeenGitHubState = snapshot.state;
10163
- 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
+ };
10164
10641
  if (paperclipIssue.status === nextStatus) {
10165
10642
  if (shouldClearTransitionAssignee || shouldClearCompletedExecutionPolicy) {
10166
10643
  updateSyncFailureContext(syncFailureContext, {
@@ -10180,13 +10657,31 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10180
10657
  paperclipApiBaseUrl
10181
10658
  });
10182
10659
  }
10183
- 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);
10184
10669
  queuedIssueWakeups.push({
10185
- assigneeAgentId: paperclipIssueSyncContext.assignee?.kind === "agent" ? paperclipIssueSyncContext.assignee.id : null,
10670
+ assigneeAgentId: pendingWake2.assigneeAgentId,
10186
10671
  paperclipIssueId: importedIssue.paperclipIssueId,
10187
- reason: IMPORTED_ISSUE_WAKE_REASON,
10188
- 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
+ }
10189
10682
  });
10683
+ } else {
10684
+ await persistObservedRemoteState();
10190
10685
  }
10191
10686
  continue;
10192
10687
  }
@@ -10216,23 +10711,38 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10216
10711
  transitionCommentAnnotation: transitionComment.annotation,
10217
10712
  paperclipApiBaseUrl
10218
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);
10219
10730
  updatedStatusesCount += 1;
10220
- if (shouldWakeImportedAssignee) {
10731
+ if (pendingWake) {
10221
10732
  queuedIssueWakeups.push({
10222
- assigneeAgentId: paperclipIssueSyncContext.assignee?.kind === "agent" ? paperclipIssueSyncContext.assignee.id : null,
10733
+ assigneeAgentId: pendingWake.assigneeAgentId,
10223
10734
  paperclipIssueId: importedIssue.paperclipIssueId,
10224
- reason: IMPORTED_ISSUE_WAKE_REASON,
10225
- mutation: "import"
10226
- });
10227
- }
10228
- if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent") {
10229
- queuedIssueWakeups.push({
10230
- assigneeAgentId: nextTransitionAssignee.principal.id,
10231
- paperclipIssueId: importedIssue.paperclipIssueId,
10232
- reason: STATUS_TRANSITION_WAKE_REASON,
10233
- mutation: "status_transition",
10234
- previousStatus: paperclipIssue.status,
10235
- 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
+ }
10236
10746
  });
10237
10747
  }
10238
10748
  } catch (error) {
@@ -10256,16 +10766,20 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10256
10766
  await mapWithConcurrency(
10257
10767
  queuedIssueWakeups,
10258
10768
  IMPORTED_ISSUE_WAKEUP_CONCURRENCY,
10259
- async (queuedWakeup) => wakePaperclipIssueAssignee(ctx, {
10260
- assigneeAgentId: queuedWakeup.assigneeAgentId,
10261
- paperclipIssueId: queuedWakeup.paperclipIssueId,
10262
- companyId: mapping.companyId,
10263
- paperclipApiBaseUrl,
10264
- reason: queuedWakeup.reason,
10265
- mutation: queuedWakeup.mutation,
10266
- previousStatus: queuedWakeup.previousStatus,
10267
- nextStatus: queuedWakeup.nextStatus
10268
- })
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
+ }
10269
10783
  );
10270
10784
  return {
10271
10785
  updatedStatusesCount,
@@ -10285,7 +10799,7 @@ function groupGitHubPullRequestLinksByPaperclipIssue(pullRequestLinks) {
10285
10799
  }
10286
10800
  return groups;
10287
10801
  }
10288
- 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) {
10289
10803
  if (!mapping.companyId || !ctx.issues || typeof ctx.issues.get !== "function" || typeof ctx.issues.update !== "function") {
10290
10804
  return {
10291
10805
  updatedStatusesCount: 0
@@ -10337,6 +10851,15 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10337
10851
  pullRequestState: livePullRequestLinkState
10338
10852
  });
10339
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
+ };
10340
10863
  if (livePullRequestLifecycleState === "open") {
10341
10864
  const pullRequest = await getGitHubPullRequestStatusSnapshot(
10342
10865
  octokit,
@@ -10348,13 +10871,15 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10348
10871
  pullRequestLink,
10349
10872
  repository: pullRequestRepository,
10350
10873
  lifecycleState: "open",
10351
- pullRequest
10874
+ pullRequest,
10875
+ ...directPullRequestMetadata
10352
10876
  });
10353
10877
  } else {
10354
10878
  pullRequestSnapshots.push({
10355
10879
  pullRequestLink,
10356
10880
  repository: pullRequestRepository,
10357
- lifecycleState: livePullRequestLifecycleState
10881
+ lifecycleState: livePullRequestLifecycleState,
10882
+ ...directPullRequestMetadata
10358
10883
  });
10359
10884
  }
10360
10885
  } catch (error) {
@@ -10386,6 +10911,47 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10386
10911
  if (!paperclipIssue) {
10387
10912
  continue;
10388
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);
10389
10955
  const paperclipIssueSyncContext = getPaperclipIssueSyncContext(paperclipIssue);
10390
10956
  const executorTransitionAssignee = resolvePaperclipIssueExecutorAssignee(
10391
10957
  paperclipIssueSyncContext,
@@ -10394,11 +10960,15 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10394
10960
  let nextStatus = resolvePaperclipDirectPullRequestIssueStatus({
10395
10961
  currentStatus: paperclipIssue.status,
10396
10962
  pullRequests: pullRequestSnapshots,
10397
- hasExecutorHandoffTarget: Boolean(executorTransitionAssignee)
10963
+ hasExecutorHandoffTarget: Boolean(executorTransitionAssignee),
10964
+ hasTrustedNewComment
10398
10965
  });
10399
10966
  if (paperclipIssue.status === "blocked" && nextStatus !== "blocked" && pullRequestSnapshots.some((entry) => entry.lifecycleState === "open") && await hasUnresolvedPaperclipIssueBlocker(ctx, paperclipIssue, mapping.companyId)) {
10400
10967
  nextStatus = "blocked";
10401
10968
  }
10969
+ if (paperclipIssue.status !== nextStatus && remoteAction.fingerprint === remoteActionFingerprint && !hasTrustedNewComment) {
10970
+ nextStatus = paperclipIssue.status;
10971
+ }
10402
10972
  const shouldPreserveMaintainerWaitRouting = isHealthyMaintainerWaitTransition({
10403
10973
  currentStatus: paperclipIssue.status,
10404
10974
  nextStatus,
@@ -10436,6 +11006,9 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10436
11006
  paperclipApiBaseUrl
10437
11007
  });
10438
11008
  }
11009
+ remoteAction.fingerprint = remoteActionFingerprint;
11010
+ remoteAction.linkedPullRequestCommentCounts = currentCommentCounts;
11011
+ await persistRemoteActionRegistry();
10439
11012
  continue;
10440
11013
  }
10441
11014
  const transitionComment = buildPaperclipPullRequestIssueStatusTransitionComment({
@@ -10448,6 +11021,11 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10448
11021
  repositoryUrl: primaryRepository?.url,
10449
11022
  githubIssueNumber: void 0
10450
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
+ }
10451
11029
  await updatePaperclipIssueState(ctx, {
10452
11030
  companyId: mapping.companyId,
10453
11031
  issueId: paperclipIssueId,
@@ -10460,15 +11038,34 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10460
11038
  transitionComment,
10461
11039
  paperclipApiBaseUrl
10462
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();
10463
11053
  updatedStatusesCount += 1;
10464
- if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent") {
11054
+ if (pendingWake) {
10465
11055
  queuedIssueWakeups.push({
10466
- assigneeAgentId: nextTransitionAssignee.principal.id,
11056
+ assigneeAgentId: pendingWake.assigneeAgentId,
10467
11057
  paperclipIssueId,
10468
- reason: STATUS_TRANSITION_WAKE_REASON,
10469
- mutation: "status_transition",
10470
- previousStatus: paperclipIssue.status,
10471
- 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
+ }
10472
11069
  });
10473
11070
  }
10474
11071
  } catch (error) {
@@ -10481,16 +11078,20 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10481
11078
  await mapWithConcurrency(
10482
11079
  queuedIssueWakeups,
10483
11080
  IMPORTED_ISSUE_WAKEUP_CONCURRENCY,
10484
- async (queuedWakeup) => wakePaperclipIssueAssignee(ctx, {
10485
- assigneeAgentId: queuedWakeup.assigneeAgentId,
10486
- paperclipIssueId: queuedWakeup.paperclipIssueId,
10487
- companyId: mapping.companyId,
10488
- paperclipApiBaseUrl,
10489
- reason: queuedWakeup.reason,
10490
- mutation: queuedWakeup.mutation,
10491
- previousStatus: queuedWakeup.previousStatus,
10492
- nextStatus: queuedWakeup.nextStatus
10493
- })
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
+ }
10494
11095
  );
10495
11096
  return {
10496
11097
  updatedStatusesCount
@@ -14071,6 +14672,12 @@ function mergeNamedValues(currentValues, params) {
14071
14672
  }
14072
14673
  return [...values.values()];
14073
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
+ }
14074
14681
  async function validateGithubToken(ctx, token) {
14075
14682
  const octokit = createGitHubOctokit(ctx, token.trim(), {
14076
14683
  logFailures: false,
@@ -14133,6 +14740,7 @@ async function performSync(ctx, trigger, options = {}) {
14133
14740
  const config = await getResolvedConfig(ctx);
14134
14741
  const settings = materializeScopedSettings(baseSettings, config, targetCompanyId);
14135
14742
  const importRegistry = normalizeImportRegistry(await ctx.state.get(IMPORT_REGISTRY_SCOPE));
14743
+ const remoteActionRegistry = normalizeRemoteActionRegistry(await ctx.state.get(REMOTE_ACTION_REGISTRY_SCOPE));
14136
14744
  let companyKpiState = normalizeCompanyKpiState(await ctx.state.get(COMPANY_KPI_SCOPE));
14137
14745
  let companyKpiStateDirty = false;
14138
14746
  const token = typeof options.resolvedToken === "string" ? options.resolvedToken : await resolveGithubToken(ctx, { companyId: targetCompanyId });
@@ -14142,6 +14750,10 @@ async function performSync(ctx, trigger, options = {}) {
14142
14750
  const externalLinkAuthMappings = buildExternalLinkAuthMappings(externalSyncWork);
14143
14751
  const externalLinkCount = externalSyncWork.issueLinks.length + externalSyncWork.pullRequestLinks.length;
14144
14752
  activePaperclipApiAuthTokensByCompanyId = null;
14753
+ activeGitHubPullRequestStatusSnapshotCache.clear();
14754
+ activeGitHubPullRequestStatusSnapshotPromiseCache.clear();
14755
+ activeGitHubPullRequestReviewThreadSummaryCache.clear();
14756
+ activeGitHubPullRequestReviewThreadSummaryPromiseCache.clear();
14145
14757
  const failureContext = {
14146
14758
  phase: "configuration"
14147
14759
  };
@@ -14682,6 +15294,7 @@ async function performSync(ctx, trigger, options = {}) {
14682
15294
  repositoryMaintainerCache,
14683
15295
  failureContext,
14684
15296
  recoverableFailures,
15297
+ async () => ctx.state.set(IMPORT_REGISTRY_SCOPE, nextRegistry),
14685
15298
  throwIfSyncCancelled,
14686
15299
  async (params) => {
14687
15300
  const recorded = recordCompanyActivityMetricEvent(companyKpiState, {
@@ -14721,6 +15334,12 @@ async function performSync(ctx, trigger, options = {}) {
14721
15334
  pullRequestStatusCache,
14722
15335
  failureContext,
14723
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
+ },
14724
15343
  throwIfSyncCancelled,
14725
15344
  async (progress) => {
14726
15345
  markTrackedPullRequestIssueProcessed(mapping, progress.pullRequestLink);
@@ -14800,7 +15419,10 @@ async function performSync(ctx, trigger, options = {}) {
14800
15419
  ...issueLink.data.paperclipProjectId ? { paperclipProjectId: issueLink.data.paperclipProjectId } : {},
14801
15420
  companyId
14802
15421
  };
14803
- 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, {
14804
15426
  mappingId: virtualMapping.id,
14805
15427
  githubIssueId: githubIssue.id,
14806
15428
  githubIssueNumber: githubIssue.number,
@@ -14812,7 +15434,10 @@ async function performSync(ctx, trigger, options = {}) {
14812
15434
  repositoryUrl: repository.url,
14813
15435
  ...issueLink.data.paperclipProjectId ? { paperclipProjectId: issueLink.data.paperclipProjectId } : {},
14814
15436
  companyId
14815
- };
15437
+ });
15438
+ if (!existingImportedIssue) {
15439
+ await ctx.state.set(IMPORT_REGISTRY_SCOPE, nextRegistry);
15440
+ }
14816
15441
  const synchronizationResult = await synchronizePaperclipIssueStatuses(
14817
15442
  ctx,
14818
15443
  octokit,
@@ -14830,6 +15455,7 @@ async function performSync(ctx, trigger, options = {}) {
14830
15455
  repositoryMaintainerCache,
14831
15456
  failureContext,
14832
15457
  recoverableFailures,
15458
+ async () => ctx.state.set(IMPORT_REGISTRY_SCOPE, nextRegistry),
14833
15459
  throwIfSyncCancelled,
14834
15460
  async (params) => {
14835
15461
  const recorded = recordCompanyActivityMetricEvent(companyKpiState, {
@@ -14910,6 +15536,12 @@ async function performSync(ctx, trigger, options = {}) {
14910
15536
  pullRequestStatusCache,
14911
15537
  failureContext,
14912
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
+ },
14913
15545
  throwIfSyncCancelled,
14914
15546
  async (progress) => {
14915
15547
  completedTrackedIssueCount += 1;
@@ -15128,6 +15760,255 @@ async function startSync(ctx, trigger, options = {}) {
15128
15760
  return getActiveOrCurrentSyncState(ctx);
15129
15761
  }
15130
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
+ }
15997
+ function resolveTrustedWorkspacePath(workspacePath, workspaceRelativePath) {
15998
+ if (!workspaceRelativePath) {
15999
+ return workspacePath;
16000
+ }
16001
+ const trustedRoot = realpathSync(workspacePath);
16002
+ if (isAbsolute2(workspaceRelativePath)) {
16003
+ throw new Error("workspaceRelativePath must be relative to the trusted execution workspace.");
16004
+ }
16005
+ const candidate = realpathSync(resolve2(trustedRoot, workspaceRelativePath));
16006
+ const relativeCandidate = relative(trustedRoot, candidate);
16007
+ if (relativeCandidate === ".." || relativeCandidate.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute2(relativeCandidate)) {
16008
+ throw new Error("workspaceRelativePath must stay inside the trusted execution workspace.");
16009
+ }
16010
+ return candidate;
16011
+ }
15131
16012
  function registerGitHubAgentTools(ctx) {
15132
16013
  async function createAgentToolOctokit(runCtx, toolName, repository) {
15133
16014
  return createGitHubToolOctokit(ctx, runCtx.companyId, {
@@ -15271,7 +16152,7 @@ function registerGitHubAgentTools(ctx) {
15271
16152
  ctx.tools.register(
15272
16153
  "update_issue",
15273
16154
  getGitHubAgentToolDeclaration("update_issue"),
15274
- async (params, runCtx) => executeGitHubTool(async () => {
16155
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "update_issue", params, runCtx, async () => {
15275
16156
  const input = getToolInputRecord(params);
15276
16157
  const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
15277
16158
  const octokit = await createAgentToolOctokit(runCtx, "update_issue", target.repository);
@@ -15301,7 +16182,9 @@ function registerGitHubAgentTools(ctx) {
15301
16182
  const body = Object.prototype.hasOwnProperty.call(input, "body") && typeof input.body === "string" ? appendOptionalAiAuthorshipFooter(input.body, "issue description", llmModel) : void 0;
15302
16183
  const state = input.state === "open" || input.state === "closed" ? input.state : void 0;
15303
16184
  const milestoneNumber = Object.prototype.hasOwnProperty.call(input, "milestoneNumber") ? input.milestoneNumber === null ? null : normalizeToolPositiveInteger(input.milestoneNumber) : void 0;
15304
- 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);
15305
16188
  const updatedResponse = hasChanges ? await octokit.rest.issues.update({
15306
16189
  owner: target.repository.owner,
15307
16190
  repo: target.repository.repo,
@@ -15309,7 +16192,7 @@ function registerGitHubAgentTools(ctx) {
15309
16192
  ...title !== void 0 ? { title } : {},
15310
16193
  ...body !== void 0 ? { body } : {},
15311
16194
  ...state ? { state } : {},
15312
- ...Object.prototype.hasOwnProperty.call(input, "milestoneNumber") ? { milestone: milestoneNumber } : {},
16195
+ ...milestoneRequested ? { milestone: milestoneNumber } : {},
15313
16196
  labels: nextLabels,
15314
16197
  assignees: nextAssignees,
15315
16198
  headers: {
@@ -15344,7 +16227,7 @@ function registerGitHubAgentTools(ctx) {
15344
16227
  ctx.tools.register(
15345
16228
  "assign_to_current_user",
15346
16229
  getGitHubAgentToolDeclaration("assign_to_current_user"),
15347
- async (params, runCtx) => executeGitHubTool(async () => {
16230
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "assign_to_current_user", params, runCtx, async () => {
15348
16231
  const input = getToolInputRecord(params);
15349
16232
  const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
15350
16233
  const octokit = await createAgentToolOctokit(runCtx, "assign_to_current_user", target.repository);
@@ -15404,7 +16287,7 @@ function registerGitHubAgentTools(ctx) {
15404
16287
  ctx.tools.register(
15405
16288
  "add_issue_comment",
15406
16289
  getGitHubAgentToolDeclaration("add_issue_comment"),
15407
- async (params, runCtx) => executeGitHubTool(async () => {
16290
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "add_issue_comment", params, runCtx, async () => {
15408
16291
  const input = getToolInputRecord(params);
15409
16292
  const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
15410
16293
  const octokit = await createAgentToolOctokit(runCtx, "add_issue_comment", target.repository);
@@ -15437,10 +16320,11 @@ function registerGitHubAgentTools(ctx) {
15437
16320
  ctx.tools.register(
15438
16321
  "create_pull_request",
15439
16322
  getGitHubAgentToolDeclaration("create_pull_request"),
15440
- async (params, runCtx) => executeGitHubTool(async () => {
16323
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "create_pull_request", params, runCtx, async () => {
15441
16324
  const input = getToolInputRecord(params);
15442
16325
  const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
15443
16326
  const explicitRepository = normalizeOptionalToolString(input.repository);
16327
+ const workspaceRelativePath = normalizeOptionalToolString(input.workspaceRelativePath);
15444
16328
  const head = normalizeOptionalToolString(input.head);
15445
16329
  const headCommitSha = normalizeOptionalToolString(input.headCommitSha);
15446
16330
  const base = normalizeOptionalToolString(input.base);
@@ -15477,7 +16361,7 @@ function registerGitHubAgentTools(ctx) {
15477
16361
  if (!workspacePath) {
15478
16362
  throw new Error("The selected Paperclip issue execution workspace is not locally realized.");
15479
16363
  }
15480
- const workspaceRepository = workspace.repoUrl ? parseRepositoryReference(workspace.repoUrl) : null;
16364
+ const publicationWorkspacePath = resolveTrustedWorkspacePath(workspacePath, workspaceRelativePath);
15481
16365
  const repository = explicitRepository ? parseRepositoryReference(explicitRepository) : (await resolveIssueGitHubLinkMapping(ctx, {
15482
16366
  companyId: runCtx.companyId,
15483
16367
  issueId: paperclipIssueId
@@ -15485,15 +16369,12 @@ function registerGitHubAgentTools(ctx) {
15485
16369
  if (!repository) {
15486
16370
  throw new Error(`Invalid GitHub repository: ${explicitRepository}. Use owner/repo or https://github.com/owner/repo.`);
15487
16371
  }
15488
- if (!workspaceRepository || !areRepositoriesEqual(workspaceRepository, repository)) {
15489
- throw new Error("The execution workspace repository does not match the selected GitHub repository.");
15490
- }
15491
16372
  const githubToken = (await resolveGithubToken(ctx, { companyId: runCtx.companyId })).trim();
15492
16373
  if (!githubToken) {
15493
16374
  throw new Error(MISSING_GITHUB_TOKEN_SYNC_MESSAGE);
15494
16375
  }
15495
16376
  const publishedBranch = await createPullRequestBranchPublisher({
15496
- workspacePath,
16377
+ workspacePath: publicationWorkspacePath,
15497
16378
  repositoryUrl: repository.url,
15498
16379
  branchName: head,
15499
16380
  expectedCommitSha: headCommitSha,
@@ -15656,7 +16537,7 @@ function registerGitHubAgentTools(ctx) {
15656
16537
  ctx.tools.register(
15657
16538
  "update_pull_request",
15658
16539
  getGitHubAgentToolDeclaration("update_pull_request"),
15659
- async (params, runCtx) => executeGitHubTool(async () => {
16540
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "update_pull_request", params, runCtx, async () => {
15660
16541
  const input = getToolInputRecord(params);
15661
16542
  const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
15662
16543
  const octokit = await createAgentToolOctokit(runCtx, "update_pull_request", target.repository);
@@ -15674,25 +16555,31 @@ function registerGitHubAgentTools(ctx) {
15674
16555
  const base = normalizeOptionalToolString(input.base);
15675
16556
  const state = input.state === "open" || input.state === "closed" ? input.state : void 0;
15676
16557
  const isDraft = typeof input.isDraft === "boolean" ? input.isDraft : void 0;
15677
- 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) {
15678
16566
  currentResponse = await octokit.rest.pulls.update({
15679
16567
  owner: target.repository.owner,
15680
16568
  repo: target.repository.repo,
15681
16569
  pull_number: target.pullRequestNumber,
15682
- ...title !== void 0 ? { title } : {},
15683
- ...body !== void 0 ? { body } : {},
15684
- ...base !== void 0 ? { base } : {},
15685
- ...state !== void 0 ? { state } : {},
16570
+ ...update,
15686
16571
  headers: {
15687
16572
  "X-GitHub-Api-Version": GITHUB_API_VERSION
15688
16573
  }
15689
16574
  });
16575
+ changed = true;
15690
16576
  }
15691
16577
  if (isDraft !== void 0 && currentResponse.data.draft !== isDraft) {
15692
16578
  if (!currentResponse.data.node_id) {
15693
16579
  throw new Error("GitHub did not return a pull request node id, so draft state cannot be updated.");
15694
16580
  }
15695
16581
  await updatePullRequestDraftState(octokit, currentResponse.data.node_id, isDraft);
16582
+ changed = true;
15696
16583
  currentResponse = await octokit.rest.pulls.get({
15697
16584
  owner: target.repository.owner,
15698
16585
  repo: target.repository.repo,
@@ -15703,7 +16590,7 @@ function registerGitHubAgentTools(ctx) {
15703
16590
  });
15704
16591
  }
15705
16592
  return buildToolSuccessResult(
15706
- `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)}.`,
15707
16594
  {
15708
16595
  repository: target.repository.url,
15709
16596
  pullRequest: {
@@ -15857,7 +16744,7 @@ function registerGitHubAgentTools(ctx) {
15857
16744
  ctx.tools.register(
15858
16745
  "reply_to_review_thread",
15859
16746
  getGitHubAgentToolDeclaration("reply_to_review_thread"),
15860
- async (params, runCtx) => executeGitHubTool(async () => {
16747
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "reply_to_review_thread", params, runCtx, async () => {
15861
16748
  const input = getToolInputRecord(params);
15862
16749
  const threadId = normalizeOptionalToolString(input.threadId);
15863
16750
  if (!threadId) {
@@ -15893,7 +16780,7 @@ function registerGitHubAgentTools(ctx) {
15893
16780
  ctx.tools.register(
15894
16781
  "resolve_review_thread",
15895
16782
  getGitHubAgentToolDeclaration("resolve_review_thread"),
15896
- async (params, runCtx) => executeGitHubTool(async () => {
16783
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "resolve_review_thread", params, runCtx, async () => {
15897
16784
  const input = getToolInputRecord(params);
15898
16785
  const threadId = normalizeOptionalToolString(input.threadId);
15899
16786
  if (!threadId) {
@@ -15924,7 +16811,7 @@ function registerGitHubAgentTools(ctx) {
15924
16811
  ctx.tools.register(
15925
16812
  "unresolve_review_thread",
15926
16813
  getGitHubAgentToolDeclaration("unresolve_review_thread"),
15927
- async (params, runCtx) => executeGitHubTool(async () => {
16814
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "unresolve_review_thread", params, runCtx, async () => {
15928
16815
  const input = getToolInputRecord(params);
15929
16816
  const threadId = normalizeOptionalToolString(input.threadId);
15930
16817
  if (!threadId) {
@@ -15955,7 +16842,7 @@ function registerGitHubAgentTools(ctx) {
15955
16842
  ctx.tools.register(
15956
16843
  "request_pull_request_reviewers",
15957
16844
  getGitHubAgentToolDeclaration("request_pull_request_reviewers"),
15958
- async (params, runCtx) => executeGitHubTool(async () => {
16845
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "request_pull_request_reviewers", params, runCtx, async () => {
15959
16846
  const input = getToolInputRecord(params);
15960
16847
  const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
15961
16848
  const userReviewers = normalizeToolStringArray(input.userReviewers);
@@ -16012,7 +16899,7 @@ function registerGitHubAgentTools(ctx) {
16012
16899
  ctx.tools.register(
16013
16900
  "add_pull_request_to_project",
16014
16901
  getGitHubAgentToolDeclaration("add_pull_request_to_project"),
16015
- async (params, runCtx) => executeGitHubTool(async () => {
16902
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "add_pull_request_to_project", params, runCtx, async () => {
16016
16903
  const input = getToolInputRecord(params);
16017
16904
  const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
16018
16905
  const octokit = await createAgentToolOctokit(runCtx, "add_pull_request_to_project", target.repository);
@@ -16073,7 +16960,7 @@ function registerGitHubAgentTools(ctx) {
16073
16960
  ctx.tools.register(
16074
16961
  "upload_pull_request_asset",
16075
16962
  getGitHubAgentToolDeclaration("upload_pull_request_asset"),
16076
- async (params, runCtx) => executeGitHubTool(async () => {
16963
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "upload_pull_request_asset", params, runCtx, async () => {
16077
16964
  const input = getToolInputRecord(params);
16078
16965
  const target = await resolveGitHubPullRequestToolTarget(ctx, runCtx, input);
16079
16966
  const octokit = await createAgentToolOctokit(runCtx, "upload_pull_request_asset", target.repository);
@@ -16094,7 +16981,7 @@ function registerGitHubAgentTools(ctx) {
16094
16981
  ctx.tools.register(
16095
16982
  "link_github_item",
16096
16983
  getGitHubAgentToolDeclaration("link_github_item"),
16097
- async (params, runCtx) => executeGitHubTool(async () => {
16984
+ async (params, runCtx) => executeTrackedGitHubMutation(ctx, "link_github_item", params, runCtx, async () => {
16098
16985
  const input = getToolInputRecord(params);
16099
16986
  const kind = normalizeIssueGitHubLinkKind(input.kind);
16100
16987
  if (!kind) {
@@ -16127,6 +17014,17 @@ function registerGitHubAgentTools(ctx) {
16127
17014
  );
16128
17015
  })
16129
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
+ );
16130
17028
  }
16131
17029
  function shouldStartWorkerHost(moduleUrl, entry = process.argv[1]) {
16132
17030
  if (typeof entry !== "string" || !entry.trim()) {
@@ -16140,15 +17038,24 @@ function shouldStartWorkerHost(moduleUrl, entry = process.argv[1]) {
16140
17038
  }
16141
17039
  }
16142
17040
  var __testing = {
17041
+ buildDirectPullRequestActionFingerprint,
17042
+ buildRemoteActionFingerprint,
16143
17043
  buildSyncFallbackExecutionStatePatch,
16144
17044
  createGitHubToolOctokit,
16145
17045
  formatPaperclipApiFetchErrorMessage,
16146
17046
  hasUnresolvedPaperclipIssueBlocker,
16147
17047
  isHealthyMaintainerWaitTransition,
17048
+ normalizeImportRegistry,
17049
+ normalizeRemoteActionRegistry,
17050
+ persistIssueInteractionEvent,
17051
+ trackedMutationOutcome,
16148
17052
  resolvePaperclipApiAuthTokens,
16149
17053
  resolveGithubToken,
16150
17054
  resolvePaperclipPullRequestIssueStatus,
16151
17055
  resolveSyncTransitionAssignee,
17056
+ resolveTrustedWorkspacePath,
17057
+ updatePaperclipIssueState,
17058
+ wakePaperclipIssueAssignee,
16152
17059
  setCreatePullRequestBranchPublisher(publisher) {
16153
17060
  createPullRequestBranchPublisher = publisher ?? publishLocalBranchForPullRequest;
16154
17061
  }