paperclip-github-plugin 0.15.7 → 0.16.1

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
@@ -25,6 +25,10 @@ var paperclipIssueIdProperty = {
25
25
  type: "string",
26
26
  description: "Paperclip issue id used to infer the linked GitHub issue and repository when available."
27
27
  };
28
+ var followThroughAssigneeAgentIdProperty = {
29
+ type: ["string", "null"],
30
+ description: "Optional durable Paperclip agent owner for actionable follow-through on this linked pull request. The agent must belong to the authenticated company. Pass null to clear an existing owner."
31
+ };
28
32
  var issueNumberProperty = {
29
33
  type: "integer",
30
34
  minimum: 1,
@@ -160,7 +164,7 @@ var GITHUB_AGENT_TOOLS = [
160
164
  {
161
165
  name: "update_issue",
162
166
  displayName: "Update Issue",
163
- description: "Update GitHub issue fields such as title, body, state, labels, assignees, or milestone. When a non-empty body is provided, the plugin appends an AI-authorship footer and includes llmModel when supplied.",
167
+ description: "Update GitHub issue fields such as title, body, state, closure reason, labels, assignees, or milestone. When a non-empty body is provided, the plugin appends an AI-authorship footer and includes llmModel when supplied.",
164
168
  parametersSchema: {
165
169
  type: "object",
166
170
  additionalProperties: false,
@@ -181,6 +185,16 @@ var GITHUB_AGENT_TOOLS = [
181
185
  type: "string",
182
186
  enum: ["open", "closed"]
183
187
  },
188
+ stateReason: {
189
+ type: "string",
190
+ enum: ["completed", "not_planned", "duplicate", "reopened"],
191
+ description: "Native GitHub state reason. Use completed, not_planned, or duplicate with state=closed; use reopened with state=open."
192
+ },
193
+ duplicateIssueNumber: {
194
+ type: "integer",
195
+ minimum: 1,
196
+ description: "Canonical issue number in the same repository. Required only when stateReason=duplicate."
197
+ },
184
198
  setLabels: {
185
199
  type: "array",
186
200
  items: {
@@ -283,6 +297,7 @@ var GITHUB_AGENT_TOOLS = [
283
297
  type: "string",
284
298
  description: "Paperclip issue id used to resolve the trusted execution workspace and durable pull-request link."
285
299
  },
300
+ followThroughAssigneeAgentId: followThroughAssigneeAgentIdProperty,
286
301
  head: {
287
302
  type: "string",
288
303
  description: "Plain local branch name to publish. Owner-qualified branches and arbitrary refspecs are rejected."
@@ -646,7 +661,8 @@ var GITHUB_AGENT_TOOLS = [
646
661
  pullRequestUrl: {
647
662
  type: "string",
648
663
  description: "Full GitHub pull request URL."
649
- }
664
+ },
665
+ followThroughAssigneeAgentId: followThroughAssigneeAgentIdProperty
650
666
  }
651
667
  }
652
668
  },
@@ -1399,6 +1415,24 @@ var PULL_REQUEST_ASSET_EXTENSION_BY_MIME_TYPE = {
1399
1415
  "application/octet-stream": "bin"
1400
1416
  };
1401
1417
  var pluginRuntimeContext = null;
1418
+ function isPendingWakeApplied(pendingWake, status, assignee) {
1419
+ return (!pendingWake.nextStatus || pendingWake.nextStatus === status) && assignee?.kind === "agent" && assignee.id === pendingWake.assigneeAgentId;
1420
+ }
1421
+ function reuseOrCreatePendingWake(existing, next, createFingerprint) {
1422
+ if (existing && existing.assigneeAgentId === next.assigneeAgentId && existing.mutation === next.mutation && existing.nextStatus === next.nextStatus) {
1423
+ return existing;
1424
+ }
1425
+ return { fingerprint: createFingerprint(), ...next };
1426
+ }
1427
+ function canReservePendingWake(registry, currentRecord) {
1428
+ return Boolean(currentRecord.pendingWake) || registry.filter((record) => record.pendingWake).length < MAX_REMOTE_ACTION_REGISTRY_RECORDS;
1429
+ }
1430
+ function createRemoteActionWakeFingerprint(remoteActionFingerprint) {
1431
+ return createHash("sha256").update(JSON.stringify({
1432
+ remoteActionFingerprint,
1433
+ wakeEpisodeId: randomUUID()
1434
+ })).digest("hex");
1435
+ }
1402
1436
  function normalizeCompanyId(value) {
1403
1437
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
1404
1438
  }
@@ -1552,11 +1586,29 @@ var GITHUB_PULL_REQUEST_CI_CONTEXTS_QUERY = `
1552
1586
  nodes {
1553
1587
  __typename
1554
1588
  ... on CheckRun {
1589
+ name
1555
1590
  status
1556
1591
  conclusion
1592
+ startedAt
1593
+ completedAt
1594
+ checkSuite {
1595
+ createdAt
1596
+ app {
1597
+ id
1598
+ slug
1599
+ }
1600
+ workflowRun {
1601
+ workflow {
1602
+ id
1603
+ }
1604
+ }
1605
+ }
1557
1606
  }
1558
1607
  ... on StatusContext {
1608
+ context
1559
1609
  state
1610
+ createdAt
1611
+ updatedAt
1560
1612
  }
1561
1613
  }
1562
1614
  }
@@ -1628,11 +1680,29 @@ var GITHUB_REPOSITORY_OPEN_PULL_REQUEST_STATUSES_QUERY = `
1628
1680
  nodes {
1629
1681
  __typename
1630
1682
  ... on CheckRun {
1683
+ name
1631
1684
  status
1632
1685
  conclusion
1686
+ startedAt
1687
+ completedAt
1688
+ checkSuite {
1689
+ createdAt
1690
+ app {
1691
+ id
1692
+ slug
1693
+ }
1694
+ workflowRun {
1695
+ workflow {
1696
+ id
1697
+ }
1698
+ }
1699
+ }
1633
1700
  }
1634
1701
  ... on StatusContext {
1702
+ context
1635
1703
  state
1704
+ createdAt
1705
+ updatedAt
1636
1706
  }
1637
1707
  }
1638
1708
  }
@@ -1722,11 +1792,29 @@ var GITHUB_PROJECT_PULL_REQUEST_INSIGHT_FIELDS = `
1722
1792
  nodes {
1723
1793
  __typename
1724
1794
  ... on CheckRun {
1795
+ name
1725
1796
  status
1726
1797
  conclusion
1798
+ startedAt
1799
+ completedAt
1800
+ checkSuite {
1801
+ createdAt
1802
+ app {
1803
+ id
1804
+ slug
1805
+ }
1806
+ workflowRun {
1807
+ workflow {
1808
+ id
1809
+ }
1810
+ }
1811
+ }
1727
1812
  }
1728
1813
  ... on StatusContext {
1814
+ context
1729
1815
  state
1816
+ createdAt
1817
+ updatedAt
1730
1818
  }
1731
1819
  }
1732
1820
  }
@@ -1776,11 +1864,29 @@ var GITHUB_PROJECT_PULL_REQUEST_METRICS_FIELDS = `
1776
1864
  nodes {
1777
1865
  __typename
1778
1866
  ... on CheckRun {
1867
+ name
1779
1868
  status
1780
1869
  conclusion
1870
+ startedAt
1871
+ completedAt
1872
+ checkSuite {
1873
+ createdAt
1874
+ app {
1875
+ id
1876
+ slug
1877
+ }
1878
+ workflowRun {
1879
+ workflow {
1880
+ id
1881
+ }
1882
+ }
1883
+ }
1781
1884
  }
1782
1885
  ... on StatusContext {
1886
+ context
1783
1887
  state
1888
+ createdAt
1889
+ updatedAt
1784
1890
  }
1785
1891
  }
1786
1892
  }
@@ -5310,6 +5416,21 @@ function recordCompanyActivityMetricEvent(state, params) {
5310
5416
  ...eventKey ? { eventKey } : {}
5311
5417
  };
5312
5418
  }
5419
+ function normalizeSelectedPullRequestGate(value) {
5420
+ if (!value || typeof value !== "object") return void 0;
5421
+ const record = value;
5422
+ const repositoryUrl = normalizeOptionalString2(record.repositoryUrl);
5423
+ const number = typeof record.number === "number" && Number.isInteger(record.number) && record.number > 0 ? record.number : void 0;
5424
+ if (!repositoryUrl || !number) return void 0;
5425
+ try {
5426
+ return {
5427
+ repositoryUrl: getNormalizedMappingRepositoryUrl({ repositoryUrl }).toLowerCase(),
5428
+ number
5429
+ };
5430
+ } catch {
5431
+ return void 0;
5432
+ }
5433
+ }
5313
5434
  function normalizeImportRegistry(value) {
5314
5435
  if (!Array.isArray(value)) {
5315
5436
  return [];
@@ -5335,7 +5456,9 @@ function normalizeImportRegistry(value) {
5335
5456
  record.linkedPullRequestCommentCounts
5336
5457
  );
5337
5458
  const remoteActionFingerprint = typeof record.remoteActionFingerprint === "string" && /^[a-f0-9]{64}$/.test(record.remoteActionFingerprint) ? record.remoteActionFingerprint : void 0;
5459
+ const selectedPullRequestGate = normalizeSelectedPullRequestGate(record.selectedPullRequestGate);
5338
5460
  const pendingRemoteActionWake = normalizePendingRemoteActionWake(record.pendingRemoteActionWake);
5461
+ const activationPending = record.activationPending === true;
5339
5462
  if (!mappingId || Number.isNaN(githubIssueId) || !paperclipIssueId || !importedAt) {
5340
5463
  return null;
5341
5464
  }
@@ -5352,7 +5475,9 @@ function normalizeImportRegistry(value) {
5352
5475
  ...lastSeenGitHubState ? { lastSeenGitHubState } : {},
5353
5476
  ...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : {},
5354
5477
  ...remoteActionFingerprint ? { remoteActionFingerprint } : {},
5355
- ...pendingRemoteActionWake ? { pendingRemoteActionWake } : {}
5478
+ ...selectedPullRequestGate ? { selectedPullRequestGate } : {},
5479
+ ...pendingRemoteActionWake ? { pendingRemoteActionWake } : {},
5480
+ ...activationPending ? { activationPending: true } : {}
5356
5481
  };
5357
5482
  }).filter((entry) => entry !== null);
5358
5483
  }
@@ -5388,12 +5513,14 @@ function normalizeRemoteActionRegistry(value) {
5388
5513
  const linkedPullRequestCommentCounts = normalizeGitHubPullRequestCommentCountRecords(
5389
5514
  record.linkedPullRequestCommentCounts
5390
5515
  );
5516
+ const selectedPullRequestGate = normalizeSelectedPullRequestGate(record.selectedPullRequestGate);
5391
5517
  const previous = recordsByKey.get(key);
5392
5518
  recordsByKey.set(key, {
5393
5519
  key,
5394
5520
  ...fingerprint ? { fingerprint } : previous?.fingerprint ? { fingerprint: previous.fingerprint } : {},
5395
5521
  ...pendingWake ? { pendingWake } : previous?.pendingWake ? { pendingWake: previous.pendingWake } : {},
5396
- ...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : previous?.linkedPullRequestCommentCounts ? { linkedPullRequestCommentCounts: previous.linkedPullRequestCommentCounts } : {}
5522
+ ...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : previous?.linkedPullRequestCommentCounts ? { linkedPullRequestCommentCounts: previous.linkedPullRequestCommentCounts } : {},
5523
+ ...selectedPullRequestGate ? { selectedPullRequestGate } : previous?.selectedPullRequestGate ? { selectedPullRequestGate: previous.selectedPullRequestGate } : {}
5397
5524
  });
5398
5525
  }
5399
5526
  const records = [...recordsByKey.values()];
@@ -5502,7 +5629,7 @@ function buildTrackedPullRequestIssueProgressKey(mapping, record) {
5502
5629
  repositoryUrl: record.data.repositoryUrl
5503
5630
  })}`;
5504
5631
  }
5505
- function buildImportedIssueRecord(mapping, issue, paperclipIssueId, importedAt) {
5632
+ function buildImportedIssueRecord(mapping, issue, paperclipIssueId, importedAt, activationPending = false) {
5506
5633
  return {
5507
5634
  mappingId: mapping.id,
5508
5635
  githubIssueId: issue.id,
@@ -5514,7 +5641,8 @@ function buildImportedIssueRecord(mapping, issue, paperclipIssueId, importedAt)
5514
5641
  linkedPullRequestCommentCounts: [],
5515
5642
  repositoryUrl: getNormalizedMappingRepositoryUrl(mapping),
5516
5643
  paperclipProjectId: mapping.paperclipProjectId,
5517
- companyId: mapping.companyId
5644
+ companyId: mapping.companyId,
5645
+ ...activationPending ? { activationPending: true } : {}
5518
5646
  };
5519
5647
  }
5520
5648
  function refreshImportedIssueRecordForMapping(record, mapping, issue) {
@@ -5912,12 +6040,45 @@ function sliceProjectPullRequestNumbers(pullRequestNumbers, pageIndex, pageSize
5912
6040
  hasPreviousPage: normalizedPageIndex > 0
5913
6041
  };
5914
6042
  }
6043
+ function getGitHubCiContextAttemptTimestamp(context) {
6044
+ const value = context.type === "checkRun" ? context.startedAt ?? context.createdAt : context.updatedAt ?? context.createdAt;
6045
+ if (!value) {
6046
+ return void 0;
6047
+ }
6048
+ const timestamp = Date.parse(value);
6049
+ return Number.isFinite(timestamp) ? timestamp : void 0;
6050
+ }
6051
+ function getEffectiveGitHubCiContexts(contexts) {
6052
+ const ungroupedContexts = [];
6053
+ const latestContexts = /* @__PURE__ */ new Map();
6054
+ for (const context of contexts) {
6055
+ const timestamp = getGitHubCiContextAttemptTimestamp(context);
6056
+ if (!context.identity || timestamp === void 0) {
6057
+ ungroupedContexts.push(context);
6058
+ continue;
6059
+ }
6060
+ const existing = latestContexts.get(context.identity);
6061
+ if (!existing) {
6062
+ latestContexts.set(context.identity, { contexts: [context], timestamp });
6063
+ continue;
6064
+ }
6065
+ if (timestamp > existing.timestamp) {
6066
+ latestContexts.set(context.identity, { contexts: [context], timestamp });
6067
+ continue;
6068
+ }
6069
+ if (timestamp === existing.timestamp) {
6070
+ existing.contexts.push(context);
6071
+ }
6072
+ }
6073
+ return [...ungroupedContexts, ...[...latestContexts.values()].flatMap(({ contexts: latest }) => latest)];
6074
+ }
5915
6075
  function classifyGitHubPullRequestCiState(contexts) {
5916
- if (contexts.length === 0) {
6076
+ const effectiveContexts = getEffectiveGitHubCiContexts(contexts);
6077
+ if (effectiveContexts.length === 0) {
5917
6078
  return "unfinished";
5918
6079
  }
5919
6080
  let hasPendingContext = false;
5920
- for (const context of contexts) {
6081
+ for (const context of effectiveContexts) {
5921
6082
  if (context.type === "statusContext") {
5922
6083
  const state = context.state?.toUpperCase();
5923
6084
  if (!state) {
@@ -5968,6 +6129,119 @@ function resolvePaperclipStatusFromLinkedPullRequests(linkedPullRequests, option
5968
6129
  }
5969
6130
  return "in_progress";
5970
6131
  }
6132
+ function getEffectiveDirectPullRequestGatePriority(condition) {
6133
+ switch (condition) {
6134
+ case "conflict":
6135
+ return 0;
6136
+ case "ci_failed":
6137
+ return 1;
6138
+ case "review_actionable":
6139
+ return 2;
6140
+ case "action_required":
6141
+ return 3;
6142
+ case "trusted_comment":
6143
+ return 4;
6144
+ case "waiting":
6145
+ return 5;
6146
+ case "ready":
6147
+ return 6;
6148
+ }
6149
+ }
6150
+ function getEffectiveDirectPullRequestGateCondition(pullRequest, hasTrustedPullRequestComment) {
6151
+ const baseCondition = getEffectivePullRequestActionCondition(pullRequest);
6152
+ const remoteCondition = baseCondition === "conflict" || baseCondition === "ci_failed" || baseCondition === "review_actionable" ? baseCondition : isGitHubPullRequestActionRequiredForSync(pullRequest) ? "action_required" : baseCondition;
6153
+ return {
6154
+ condition: hasTrustedPullRequestComment && (remoteCondition === "ready" || remoteCondition === "waiting") ? "trusted_comment" : remoteCondition,
6155
+ remoteCondition
6156
+ };
6157
+ }
6158
+ function selectHighestPriorityEffectivePullRequestGate(gates, preferredGate) {
6159
+ const preferredGateKey = preferredGate ? buildGitHubPullRequestReferenceKey(preferredGate) : void 0;
6160
+ return [...gates].sort(
6161
+ (left, right) => getEffectiveDirectPullRequestGatePriority(left.condition) - getEffectiveDirectPullRequestGatePriority(right.condition) || Number(buildGitHubPullRequestReferenceKey(right) === preferredGateKey) - Number(buildGitHubPullRequestReferenceKey(left) === preferredGateKey) || left.repositoryUrl.localeCompare(right.repositoryUrl) || left.number - right.number
6162
+ )[0];
6163
+ }
6164
+ function buildTrustedCommentKindsByPullRequest(trustedCommentSources) {
6165
+ const kindsByPullRequest = /* @__PURE__ */ new Map();
6166
+ for (const source of trustedCommentSources) {
6167
+ const key = buildGitHubPullRequestReferenceKey(source);
6168
+ const kinds = kindsByPullRequest.get(key) ?? /* @__PURE__ */ new Set();
6169
+ kinds.add(source.kind);
6170
+ kindsByPullRequest.set(key, kinds);
6171
+ }
6172
+ return new Map([...kindsByPullRequest].map(([key, kinds]) => [key, [...kinds].sort()]));
6173
+ }
6174
+ function selectEffectiveDirectPullRequestGate(pullRequests, trustedCommentSources, preferredGate) {
6175
+ const trustedCommentKindsByPullRequest = buildTrustedCommentKindsByPullRequest(trustedCommentSources);
6176
+ return selectHighestPriorityEffectivePullRequestGate(pullRequests.filter(
6177
+ (entry) => entry.lifecycleState === "open" && Boolean(entry.pullRequest)
6178
+ ).map((entry) => {
6179
+ const repositoryUrl = getNormalizedMappingRepositoryUrl({ repositoryUrl: entry.repository.url }).toLowerCase();
6180
+ const number = entry.pullRequestLink.data.githubPullRequestNumber;
6181
+ const trustedCommentKinds = trustedCommentKindsByPullRequest.get(
6182
+ buildGitHubPullRequestReferenceKey({ repositoryUrl, number })
6183
+ ) ?? [];
6184
+ const { condition, remoteCondition } = getEffectiveDirectPullRequestGateCondition(
6185
+ entry.pullRequest,
6186
+ trustedCommentKinds.length > 0
6187
+ );
6188
+ return {
6189
+ repositoryUrl,
6190
+ number,
6191
+ headSha: entry.pullRequest.headSha ?? null,
6192
+ condition,
6193
+ remoteCondition,
6194
+ trustedCommentKinds,
6195
+ ownerCandidate: entry.pullRequestLink.data.followThroughAssigneeAgentId,
6196
+ pullRequest: entry.pullRequest
6197
+ };
6198
+ }), preferredGate);
6199
+ }
6200
+ function selectEffectiveIssueLinkedPullRequestGate(pullRequests, trustedCommentSources, hasTrustedIssueComment, pullRequestLinks = [], preferredGate) {
6201
+ const trustedCommentKindsByPullRequest = buildTrustedCommentKindsByPullRequest(trustedCommentSources);
6202
+ const ownerByPullRequest = new Map(pullRequestLinks.map((link) => [
6203
+ buildGitHubPullRequestReferenceKey({
6204
+ repositoryUrl: link.data.repositoryUrl,
6205
+ number: link.data.githubPullRequestNumber
6206
+ }),
6207
+ link.data.followThroughAssigneeAgentId
6208
+ ]));
6209
+ return selectHighestPriorityEffectivePullRequestGate(pullRequests.map((pullRequest) => {
6210
+ const repositoryUrl = getNormalizedMappingRepositoryUrl({ repositoryUrl: pullRequest.repositoryUrl }).toLowerCase();
6211
+ const number = pullRequest.number;
6212
+ const key = buildGitHubPullRequestReferenceKey({ repositoryUrl, number });
6213
+ const trustedCommentKinds = trustedCommentKindsByPullRequest.get(key) ?? [];
6214
+ const { condition, remoteCondition } = getEffectiveDirectPullRequestGateCondition(
6215
+ pullRequest,
6216
+ hasTrustedIssueComment || trustedCommentKinds.length > 0
6217
+ );
6218
+ return {
6219
+ repositoryUrl,
6220
+ number,
6221
+ headSha: pullRequest.headSha ?? null,
6222
+ condition,
6223
+ remoteCondition,
6224
+ trustedCommentKinds,
6225
+ ownerCandidate: ownerByPullRequest.get(key),
6226
+ pullRequest
6227
+ };
6228
+ }), preferredGate);
6229
+ }
6230
+ function selectEffectiveIssueLinkedPullRequestAction(pullRequests, trustedCommentSources, hasTrustedIssueComment) {
6231
+ return selectEffectiveIssueLinkedPullRequestGate(
6232
+ pullRequests,
6233
+ trustedCommentSources,
6234
+ hasTrustedIssueComment
6235
+ )?.pullRequest;
6236
+ }
6237
+ function isActionableDirectPullRequestGate(gate) {
6238
+ return Boolean(gate && gate.condition !== "ready" && gate.condition !== "waiting");
6239
+ }
6240
+ async function resolveValidFollowThroughAssigneeAgentId(ctx, companyId, candidate) {
6241
+ if (!candidate) return void 0;
6242
+ const agent = await ctx.agents.get(candidate, companyId);
6243
+ return agent?.companyId === companyId ? candidate : void 0;
6244
+ }
5971
6245
  function formatPaperclipIssueStatus(status) {
5972
6246
  switch (status) {
5973
6247
  case "backlog":
@@ -6274,14 +6548,20 @@ function resolvePaperclipIssueReviewAssignee(syncContext, advancedSettings) {
6274
6548
  }
6275
6549
  return null;
6276
6550
  }
6277
- function resolvePaperclipIssueExecutorAssignee(syncContext, advancedSettings) {
6551
+ function resolvePaperclipIssueExecutorAssignee(syncContext, advancedSettings, followThroughAssigneeAgentId) {
6278
6552
  const returnAssignee = syncContext.executionState?.returnAssignee;
6279
- if (returnAssignee) {
6553
+ if (returnAssignee && (syncContext.executionState?.status === "pending" || syncContext.executionState?.status === "changes_requested")) {
6280
6554
  return {
6281
6555
  principal: returnAssignee,
6282
6556
  role: "executor"
6283
6557
  };
6284
6558
  }
6559
+ if (followThroughAssigneeAgentId) {
6560
+ return {
6561
+ principal: { kind: "agent", id: followThroughAssigneeAgentId },
6562
+ role: "executor"
6563
+ };
6564
+ }
6285
6565
  const executorOverride = getConfiguredAdvancedAssigneePrincipal(advancedSettings, "executor");
6286
6566
  if (executorOverride) {
6287
6567
  return {
@@ -6299,7 +6579,7 @@ function resolvePaperclipIssueExecutorAssignee(syncContext, advancedSettings) {
6299
6579
  return null;
6300
6580
  }
6301
6581
  function resolveSyncTransitionAssignee(params) {
6302
- const { currentStatus, nextStatus, syncContext, advancedSettings } = params;
6582
+ const { currentStatus, nextStatus, syncContext, advancedSettings, followThroughAssigneeAgentId } = params;
6303
6583
  if (isHealthyMaintainerWaitTransition({ currentStatus, nextStatus, syncContext })) {
6304
6584
  return null;
6305
6585
  }
@@ -6307,7 +6587,11 @@ function resolveSyncTransitionAssignee(params) {
6307
6587
  return resolvePaperclipIssueReviewAssignee(syncContext, advancedSettings);
6308
6588
  }
6309
6589
  if (nextStatus === "todo" || nextStatus === "in_progress") {
6310
- return resolvePaperclipIssueExecutorAssignee(syncContext, advancedSettings);
6590
+ return resolvePaperclipIssueExecutorAssignee(
6591
+ syncContext,
6592
+ advancedSettings,
6593
+ followThroughAssigneeAgentId
6594
+ );
6311
6595
  }
6312
6596
  return null;
6313
6597
  }
@@ -6507,6 +6791,7 @@ function resolvePaperclipIssueStatus(params) {
6507
6791
  const {
6508
6792
  currentStatus,
6509
6793
  snapshot,
6794
+ effectiveGate,
6510
6795
  hasTrustedNewComment,
6511
6796
  wasImportedThisRun,
6512
6797
  defaultImportedStatus,
@@ -6519,16 +6804,28 @@ function resolvePaperclipIssueStatus(params) {
6519
6804
  if (currentStatus === "backlog" && !wasImportedThisRun) {
6520
6805
  return "backlog";
6521
6806
  }
6522
- if (hasTrustedNewComment) {
6807
+ if (hasTrustedNewComment && snapshot.linkedPullRequests.length === 0) {
6523
6808
  return hasExecutorHandoffTarget ? "in_progress" : "todo";
6524
6809
  }
6525
- if (snapshot.linkedPullRequests.length > 0) {
6526
- if (shouldPreserveBlockedExternalPullRequestWait({
6527
- currentStatus,
6528
- linkedPullRequests: snapshot.linkedPullRequests
6529
- })) {
6530
- return "blocked";
6810
+ if (effectiveGate) {
6811
+ if (effectiveGate.condition === "trusted_comment") {
6812
+ return hasExecutorHandoffTarget ? "in_progress" : "todo";
6813
+ }
6814
+ if (isActionableDirectPullRequestGate(effectiveGate)) {
6815
+ if (shouldPreserveBlockedExternalPullRequestWait({
6816
+ currentStatus,
6817
+ linkedPullRequests: [effectiveGate.pullRequest]
6818
+ })) {
6819
+ return "blocked";
6820
+ }
6821
+ return hasExecutorHandoffTarget ? "in_progress" : "todo";
6822
+ }
6823
+ if (effectiveGate.condition === "waiting") {
6824
+ return (currentStatus === "done" || currentStatus === "in_review") && isGitHubPullRequestTransientUnknownMergeabilityWait(effectiveGate.pullRequest) ? "in_review" : "in_progress";
6531
6825
  }
6826
+ return "in_review";
6827
+ }
6828
+ if (snapshot.linkedPullRequests.length > 0) {
6532
6829
  return resolvePaperclipStatusFromLinkedPullRequests(snapshot.linkedPullRequests, {
6533
6830
  preferInProgress: hasExecutorHandoffTarget,
6534
6831
  preserveTransientUnknownMergeabilityWait: currentStatus === "done" || currentStatus === "in_review"
@@ -6556,22 +6853,24 @@ function resolvePaperclipPullRequestIssueStatus(params) {
6556
6853
  });
6557
6854
  }
6558
6855
  function resolvePaperclipDirectPullRequestIssueStatus(params) {
6559
- const { currentStatus, pullRequests, hasExecutorHandoffTarget, hasTrustedNewComment } = params;
6560
- const openPullRequests = pullRequests.map((entry) => entry.pullRequest).filter((pullRequest) => Boolean(pullRequest));
6561
- if (openPullRequests.length > 0) {
6562
- if (hasTrustedNewComment) {
6856
+ const { currentStatus, pullRequests, effectiveGate, hasExecutorHandoffTarget } = params;
6857
+ if (effectiveGate) {
6858
+ if (effectiveGate.condition === "trusted_comment") {
6563
6859
  return currentStatus === "backlog" ? "backlog" : hasExecutorHandoffTarget ? "in_progress" : "todo";
6564
6860
  }
6565
- if (shouldPreserveBlockedExternalPullRequestWait({
6566
- currentStatus,
6567
- linkedPullRequests: openPullRequests
6568
- })) {
6569
- return "blocked";
6861
+ if (isActionableDirectPullRequestGate(effectiveGate)) {
6862
+ if (shouldPreserveBlockedExternalPullRequestWait({
6863
+ currentStatus,
6864
+ linkedPullRequests: [effectiveGate.pullRequest]
6865
+ })) {
6866
+ return "blocked";
6867
+ }
6868
+ return hasExecutorHandoffTarget ? "in_progress" : "todo";
6570
6869
  }
6571
- return resolvePaperclipStatusFromLinkedPullRequests(openPullRequests, {
6572
- preferInProgress: hasExecutorHandoffTarget,
6573
- preserveTransientUnknownMergeabilityWait: currentStatus === "done" || currentStatus === "in_review"
6574
- });
6870
+ if (effectiveGate.condition === "waiting") {
6871
+ return (currentStatus === "done" || currentStatus === "in_review") && isGitHubPullRequestTransientUnknownMergeabilityWait(effectiveGate.pullRequest) ? "in_review" : "in_progress";
6872
+ }
6873
+ return "in_review";
6575
6874
  }
6576
6875
  return pullRequests.some((entry) => entry.lifecycleState === "merged") ? "done" : "cancelled";
6577
6876
  }
@@ -6661,17 +6960,32 @@ function extractGitHubCiContextRecords(nodes) {
6661
6960
  continue;
6662
6961
  }
6663
6962
  if (node.__typename === "CheckRun") {
6963
+ const app = node.checkSuite?.app;
6964
+ const appId = typeof app?.id === "string" && app.id.trim() ? app.id.trim() : void 0;
6965
+ const appSlug = typeof app?.slug === "string" && app.slug.trim() ? app.slug.trim() : void 0;
6966
+ const producerIdentity = appId ? `app:${appId}` : appSlug ? `appSlug:${appSlug}` : void 0;
6967
+ const workflowId = node.checkSuite?.workflowRun?.workflow?.id?.trim();
6664
6968
  contexts.push({
6665
6969
  type: "checkRun",
6970
+ // A rendered check name is stable only within its producer and workflow.
6971
+ // If GitHub omits workflow provenance, retain the context instead of
6972
+ // accidentally hiding a distinct required check with the same name.
6973
+ ...typeof node.name === "string" && node.name.trim() && producerIdentity && workflowId ? { identity: `checkRun:${producerIdentity}:${workflowId}:${node.name.trim()}` } : {},
6666
6974
  status: node.status ?? void 0,
6667
- conclusion: node.conclusion ?? void 0
6975
+ conclusion: node.conclusion ?? void 0,
6976
+ startedAt: node.startedAt ?? void 0,
6977
+ completedAt: node.completedAt ?? void 0,
6978
+ createdAt: node.checkSuite?.createdAt ?? void 0
6668
6979
  });
6669
6980
  continue;
6670
6981
  }
6671
6982
  if (node.__typename === "StatusContext") {
6672
6983
  contexts.push({
6673
6984
  type: "statusContext",
6674
- state: node.state ?? void 0
6985
+ ...typeof node.context === "string" && node.context.trim() ? { identity: `statusContext:${node.context.trim()}` } : {},
6986
+ state: node.state ?? void 0,
6987
+ createdAt: node.createdAt ?? void 0,
6988
+ updatedAt: node.updatedAt ?? void 0
6675
6989
  });
6676
6990
  }
6677
6991
  }
@@ -6863,26 +7177,7 @@ async function getGitHubPullRequestCiSnapshot(octokit, repository, pullRequestNu
6863
7177
  headSha = responseHeadSha.trim().toLowerCase();
6864
7178
  }
6865
7179
  const connection = response.repository?.pullRequest?.statusCheckRollup?.contexts;
6866
- const nodes = connection?.nodes ?? [];
6867
- for (const node of nodes) {
6868
- if (!node?.__typename) {
6869
- continue;
6870
- }
6871
- if (node.__typename === "CheckRun") {
6872
- contexts.push({
6873
- type: "checkRun",
6874
- status: node.status ?? void 0,
6875
- conclusion: node.conclusion ?? void 0
6876
- });
6877
- continue;
6878
- }
6879
- if (node.__typename === "StatusContext") {
6880
- contexts.push({
6881
- type: "statusContext",
6882
- state: node.state ?? void 0
6883
- });
6884
- }
6885
- }
7180
+ contexts.push(...extractGitHubCiContextRecords(connection?.nodes ?? []));
6886
7181
  after = getPageCursor(connection?.pageInfo);
6887
7182
  } while (after);
6888
7183
  return {
@@ -7249,10 +7544,11 @@ async function listGitHubPullRequestCommentCountRecords(octokit, linkedPullReque
7249
7544
  }
7250
7545
  return normalizeGitHubPullRequestCommentCountRecords(commentCounts);
7251
7546
  }
7252
- async function hasTrustedNewLinkedPullRequestComments(params) {
7547
+ async function listTrustedNewLinkedPullRequestCommentSources(params) {
7253
7548
  if ((params.currentCommentCounts?.length ?? 0) === 0 || (params.previousCommentCounts?.length ?? 0) === 0) {
7254
- return false;
7549
+ return [];
7255
7550
  }
7551
+ const sources = [];
7256
7552
  const previousCommentCountsByKey = new Map(
7257
7553
  (params.previousCommentCounts ?? []).map((record) => [buildGitHubPullRequestReferenceKey(record), record])
7258
7554
  );
@@ -7262,6 +7558,7 @@ async function hasTrustedNewLinkedPullRequestComments(params) {
7262
7558
  continue;
7263
7559
  }
7264
7560
  const pullRequestRepository = requireRepositoryReference(currentCommentCount.repositoryUrl);
7561
+ const repositoryUrl = getNormalizedMappingRepositoryUrl({ repositoryUrl: currentCommentCount.repositoryUrl });
7265
7562
  if (currentCommentCount.topLevelCommentCount > previousCommentCount.topLevelCommentCount) {
7266
7563
  const newTopLevelComments = await listNewGitHubIssueCommentsSinceCount(
7267
7564
  params.octokit,
@@ -7277,7 +7574,7 @@ async function hasTrustedNewLinkedPullRequestComments(params) {
7277
7574
  originalPosterLogin: params.originalPosterLogin,
7278
7575
  maintainerCache: params.maintainerCache
7279
7576
  })) {
7280
- return true;
7577
+ sources.push({ repositoryUrl, number: currentCommentCount.number, kind: "top_level" });
7281
7578
  }
7282
7579
  }
7283
7580
  if (currentCommentCount.reviewCommentCount > previousCommentCount.reviewCommentCount) {
@@ -7295,11 +7592,13 @@ async function hasTrustedNewLinkedPullRequestComments(params) {
7295
7592
  originalPosterLogin: params.originalPosterLogin,
7296
7593
  maintainerCache: params.maintainerCache
7297
7594
  })) {
7298
- return true;
7595
+ sources.push({ repositoryUrl, number: currentCommentCount.number, kind: "review" });
7299
7596
  }
7300
7597
  }
7301
7598
  }
7302
- return false;
7599
+ return sources.sort(
7600
+ (left, right) => buildGitHubPullRequestReferenceKey(left).localeCompare(buildGitHubPullRequestReferenceKey(right)) || left.kind.localeCompare(right.kind)
7601
+ );
7303
7602
  }
7304
7603
  async function isMaintainerAuthoredGitHubIssue(params) {
7305
7604
  const authorLogin = normalizeGitHubUserLogin(params.githubIssue.authorLogin);
@@ -7612,7 +7911,8 @@ async function listImportedPaperclipIssuesForMapping(ctx, mapping) {
7612
7911
  if (issue.projectId !== mapping.paperclipProjectId) {
7613
7912
  continue;
7614
7913
  }
7615
- const githubIssueUrl = extractImportedGitHubIssueUrlFromDescription(issue.description);
7914
+ const originLink = resolvePaperclipIssueOriginGitHubIssueLink(issue, mapping.companyId);
7915
+ const githubIssueUrl = originLink?.repositoryUrl === normalizedRepositoryUrl ? originLink.githubIssueUrl : extractImportedGitHubIssueUrlFromDescription(issue.description);
7616
7916
  if (!githubIssueUrl) {
7617
7917
  continue;
7618
7918
  }
@@ -7809,6 +8109,8 @@ function normalizeGitHubPullRequestLinkEntityData(value) {
7809
8109
  const githubPullRequestUrl = typeof record.githubPullRequestUrl === "string" && record.githubPullRequestUrl.trim() ? record.githubPullRequestUrl.trim() : void 0;
7810
8110
  const githubPullRequestState = record.githubPullRequestState === "closed" ? "closed" : record.githubPullRequestState === "open" ? "open" : void 0;
7811
8111
  const title = typeof record.title === "string" && record.title.trim() ? record.title.trim() : void 0;
8112
+ const followThroughAssigneeAgentId = normalizeOptionalString2(record.followThroughAssigneeAgentId);
8113
+ const followThroughAssigneeUpdatedAt = normalizeOptionalString2(record.followThroughAssigneeUpdatedAt);
7812
8114
  const syncedAt = typeof record.syncedAt === "string" && record.syncedAt.trim() ? record.syncedAt.trim() : void 0;
7813
8115
  if (!repositoryUrl || githubPullRequestNumber === void 0 || !githubPullRequestUrl || !githubPullRequestState || !syncedAt) {
7814
8116
  return null;
@@ -7821,6 +8123,8 @@ function normalizeGitHubPullRequestLinkEntityData(value) {
7821
8123
  githubPullRequestUrl,
7822
8124
  githubPullRequestState,
7823
8125
  ...title ? { title } : {},
8126
+ ...followThroughAssigneeAgentId ? { followThroughAssigneeAgentId } : {},
8127
+ ...followThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt } : {},
7824
8128
  syncedAt
7825
8129
  };
7826
8130
  }
@@ -7975,7 +8279,7 @@ function doesGitHubPullRequestLinkRecordMatchTarget(record, target) {
7975
8279
  case "project":
7976
8280
  return (!record.data.companyId || record.data.companyId === target.companyId) && (!record.data.paperclipProjectId || record.data.paperclipProjectId === target.projectId);
7977
8281
  case "issue":
7978
- return Boolean(target.issueId && record.paperclipIssueId === target.issueId);
8282
+ return Boolean(target.issueId && record.paperclipIssueId === target.issueId) && (!record.data.companyId || record.data.companyId === target.companyId);
7979
8283
  default:
7980
8284
  return true;
7981
8285
  }
@@ -8216,28 +8520,86 @@ async function upsertGitHubIssueLinkRecord(ctx, target, issueId, githubIssue, li
8216
8520
  data: record.data
8217
8521
  });
8218
8522
  }
8523
+ var pullRequestLinkMutationTails = /* @__PURE__ */ new Map();
8524
+ async function withPullRequestLinkMutationLock(key, mutation) {
8525
+ const previousTail = pullRequestLinkMutationTails.get(key) ?? Promise.resolve();
8526
+ let release;
8527
+ const currentMutation = new Promise((resolve3) => {
8528
+ release = resolve3;
8529
+ });
8530
+ const currentTail = previousTail.catch(() => void 0).then(() => currentMutation);
8531
+ pullRequestLinkMutationTails.set(key, currentTail);
8532
+ await previousTail.catch(() => void 0);
8533
+ try {
8534
+ return await mutation();
8535
+ } finally {
8536
+ release();
8537
+ if (pullRequestLinkMutationTails.get(key) === currentTail) {
8538
+ pullRequestLinkMutationTails.delete(key);
8539
+ }
8540
+ }
8541
+ }
8219
8542
  async function upsertGitHubPullRequestLinkRecord(ctx, params) {
8220
- await ctx.entities.upsert({
8221
- entityType: PULL_REQUEST_LINK_ENTITY_TYPE,
8222
- scopeKind: "issue",
8223
- scopeId: params.issueId,
8224
- externalId: params.pullRequestUrl,
8225
- title: `GitHub pull request #${params.pullRequestNumber}`,
8226
- status: params.pullRequestState,
8227
- data: {
8543
+ const repositoryUrl = getNormalizedMappingRepositoryUrl({ repositoryUrl: params.repositoryUrl });
8544
+ const referenceKey = buildGitHubPullRequestReferenceKey({
8545
+ repositoryUrl,
8546
+ number: params.pullRequestNumber
8547
+ });
8548
+ const mutationKey = `${params.companyId}:${params.issueId}:${referenceKey}`;
8549
+ return withPullRequestLinkMutationLock(mutationKey, async () => {
8550
+ const findMatchingRecord = (records) => records.find(
8551
+ (record) => buildGitHubPullRequestReferenceKey({
8552
+ repositoryUrl: record.data.repositoryUrl,
8553
+ number: record.data.githubPullRequestNumber
8554
+ }) === referenceKey
8555
+ );
8556
+ const exactExternalIdMatch = findMatchingRecord(await listGitHubPullRequestLinkRecords(ctx, {
8557
+ paperclipIssueId: params.issueId,
8558
+ externalId: params.pullRequestUrl
8559
+ }));
8560
+ const existing = exactExternalIdMatch ?? findMatchingRecord(await listGitHubPullRequestLinkRecords(ctx, {
8561
+ paperclipIssueId: params.issueId
8562
+ }));
8563
+ const previousOwner = existing?.data.followThroughAssigneeAgentId;
8564
+ const nextOwner = params.followThroughAssigneeAgentId === void 0 ? previousOwner : params.followThroughAssigneeAgentId ?? void 0;
8565
+ const ownerChanged = params.followThroughAssigneeAgentId !== void 0 && previousOwner !== nextOwner;
8566
+ const data = {
8228
8567
  companyId: params.companyId,
8229
8568
  ...params.projectId ? { paperclipProjectId: params.projectId } : {},
8230
- repositoryUrl: getNormalizedMappingRepositoryUrl({
8231
- repositoryUrl: params.repositoryUrl
8232
- }),
8569
+ repositoryUrl,
8233
8570
  githubPullRequestNumber: params.pullRequestNumber,
8234
8571
  githubPullRequestUrl: params.pullRequestUrl,
8235
8572
  githubPullRequestState: params.pullRequestState,
8236
8573
  title: params.pullRequestTitle,
8574
+ ...nextOwner ? { followThroughAssigneeAgentId: nextOwner } : {},
8575
+ ...ownerChanged ? { followThroughAssigneeUpdatedAt: (/* @__PURE__ */ new Date()).toISOString() } : existing?.data.followThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt: existing.data.followThroughAssigneeUpdatedAt } : {},
8237
8576
  syncedAt: (/* @__PURE__ */ new Date()).toISOString()
8238
- }
8577
+ };
8578
+ await ctx.entities.upsert({
8579
+ entityType: PULL_REQUEST_LINK_ENTITY_TYPE,
8580
+ scopeKind: "issue",
8581
+ scopeId: params.issueId,
8582
+ externalId: existing?.externalId ?? params.pullRequestUrl,
8583
+ title: `GitHub pull request #${params.pullRequestNumber}`,
8584
+ status: params.pullRequestState,
8585
+ data
8586
+ });
8587
+ return data;
8239
8588
  });
8240
8589
  }
8590
+ async function validateFollowThroughAssigneeAgentId(ctx, companyId, value) {
8591
+ if (value === void 0) return void 0;
8592
+ if (value === null) return null;
8593
+ const agentId = normalizeOptionalString2(value);
8594
+ if (!agentId) {
8595
+ throw new Error("followThroughAssigneeAgentId must be a Paperclip agent id or null.");
8596
+ }
8597
+ const agent = await ctx.agents.get(agentId, companyId);
8598
+ if (!agent || agent.companyId !== companyId) {
8599
+ throw new Error("followThroughAssigneeAgentId must identify an agent in the same Paperclip company.");
8600
+ }
8601
+ return agentId;
8602
+ }
8241
8603
  function normalizeIssueGitHubLinkKind(value) {
8242
8604
  if (value === "issue" || value === "github_issue") {
8243
8605
  return "issue";
@@ -8514,6 +8876,11 @@ async function linkPaperclipIssueToGitHubPullRequest(ctx, params) {
8514
8876
  repositoryUrl: reference.repositoryUrl,
8515
8877
  allowUnmapped: params.allowUnmapped
8516
8878
  });
8879
+ const followThroughAssigneeAgentId = await validateFollowThroughAssigneeAgentId(
8880
+ ctx,
8881
+ companyId,
8882
+ params.followThroughAssigneeAgentId
8883
+ );
8517
8884
  const octokit = await createGitHubToolOctokit(ctx, companyId);
8518
8885
  const response = await octokit.rest.pulls.get({
8519
8886
  owner: scope.repository.owner,
@@ -8528,7 +8895,7 @@ async function linkPaperclipIssueToGitHubPullRequest(ctx, params) {
8528
8895
  state: response.data.state,
8529
8896
  merged: response.data.merged
8530
8897
  });
8531
- await upsertGitHubPullRequestLinkRecord(ctx, {
8898
+ const storedLink = await upsertGitHubPullRequestLinkRecord(ctx, {
8532
8899
  companyId,
8533
8900
  projectId: scope.mapping?.paperclipProjectId ?? scope.projectId,
8534
8901
  issueId,
@@ -8536,7 +8903,8 @@ async function linkPaperclipIssueToGitHubPullRequest(ctx, params) {
8536
8903
  pullRequestNumber: reference.pullRequestNumber,
8537
8904
  pullRequestUrl,
8538
8905
  pullRequestTitle: response.data.title || `Pull request #${reference.pullRequestNumber}`,
8539
- pullRequestState
8906
+ pullRequestState,
8907
+ followThroughAssigneeAgentId
8540
8908
  });
8541
8909
  await rememberExternalGitHubLinkCompany(ctx, companyId);
8542
8910
  const projectIdForCacheInvalidation = scope.mapping?.paperclipProjectId ?? scope.projectId;
@@ -8553,7 +8921,9 @@ async function linkPaperclipIssueToGitHubPullRequest(ctx, params) {
8553
8921
  repositoryUrl: scope.repository.url,
8554
8922
  githubPullRequestNumber: reference.pullRequestNumber,
8555
8923
  githubPullRequestUrl: pullRequestUrl,
8556
- githubPullRequestState: pullRequestState
8924
+ githubPullRequestState: pullRequestState,
8925
+ ...storedLink.followThroughAssigneeAgentId ? { followThroughAssigneeAgentId: storedLink.followThroughAssigneeAgentId } : {},
8926
+ ...storedLink.followThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt: storedLink.followThroughAssigneeUpdatedAt } : {}
8557
8927
  };
8558
8928
  }
8559
8929
  function invalidateGitHubLinkCachesForTarget(params) {
@@ -8818,16 +9188,16 @@ async function detectPaperclipBoardAccessRequirement(paperclipApiBaseUrl) {
8818
9188
  }
8819
9189
  async function wakePaperclipIssueAssignee(ctx, params) {
8820
9190
  if (!params.assigneeAgentId) {
8821
- return;
9191
+ return false;
8822
9192
  }
8823
9193
  if (ctx.issues && typeof ctx.issues.requestWakeup === "function" && params.companyId) {
8824
9194
  try {
8825
- await ctx.issues.requestWakeup(params.paperclipIssueId, params.companyId, {
9195
+ const result = await ctx.issues.requestWakeup(params.paperclipIssueId, params.companyId, {
8826
9196
  reason: params.reason,
8827
9197
  contextSource: `github-sync.${params.mutation}`,
8828
9198
  ...params.actionFingerprint ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId, params.actionFingerprint].join(":") } : params.mutation === "import" ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId].join(":") } : {}
8829
9199
  });
8830
- return;
9200
+ return result?.queued !== false;
8831
9201
  } catch (error) {
8832
9202
  if (!params.paperclipApiBaseUrl) {
8833
9203
  throw new Error(
@@ -8876,6 +9246,7 @@ async function wakePaperclipIssueAssignee(ctx, params) {
8876
9246
  if (!response.ok) {
8877
9247
  throw new Error(`Wakeup request failed with status ${response.status}.`);
8878
9248
  }
9249
+ return true;
8879
9250
  } catch (error) {
8880
9251
  throw new Error(
8881
9252
  `GitHub sync could not wake the assignee for Paperclip issue ${params.paperclipIssueId}: ${getErrorMessage(error)}`,
@@ -9584,58 +9955,36 @@ function getEffectivePullRequestActionCondition(pullRequest) {
9584
9955
  if (pullRequest.ciState === "green" && pullRequest.mergeability === "mergeable") return "ready";
9585
9956
  return "waiting";
9586
9957
  }
9587
- function getEffectivePullRequestActionPriority(condition) {
9588
- switch (condition) {
9589
- case "conflict":
9590
- return 0;
9591
- case "ci_failed":
9592
- return 1;
9593
- case "review_actionable":
9594
- return 2;
9595
- case "waiting":
9596
- return 3;
9597
- case "ready":
9598
- return 4;
9599
- }
9600
- }
9601
- function selectEffectivePullRequestFingerprintEntries(pullRequests) {
9602
- const highestPriority = Math.min(...pullRequests.map(
9603
- (pullRequest) => getEffectivePullRequestActionPriority(pullRequest.condition)
9604
- ));
9605
- return pullRequests.filter((pullRequest) => getEffectivePullRequestActionPriority(pullRequest.condition) === highestPriority).sort((left, right) => left.repositoryUrl.localeCompare(right.repositoryUrl) || left.number - right.number);
9606
- }
9607
- function buildRemoteActionFingerprint(snapshot) {
9608
- const allPullRequests = snapshot.linkedPullRequests.map((pullRequest) => ({
9609
- repositoryUrl: pullRequest.repositoryUrl.toLowerCase(),
9610
- number: pullRequest.number,
9611
- headSha: pullRequest.headSha ?? null,
9612
- condition: getEffectivePullRequestActionCondition(pullRequest)
9613
- }));
9614
- const pullRequests = snapshot.state === "closed" || allPullRequests.length === 0 ? [] : selectEffectivePullRequestFingerprintEntries(allPullRequests);
9615
- const reasonCode = snapshot.state === "closed" ? `issue_closed_${snapshot.stateReason ?? "completed"}` : pullRequests.length === 0 ? "issue_open" : `pr_${pullRequests[0]?.condition ?? "waiting"}`;
9958
+ function buildRemoteActionFingerprint(snapshot, effectiveGate = snapshot.state === "closed" ? void 0 : selectEffectiveIssueLinkedPullRequestGate(snapshot.linkedPullRequests, [], false)) {
9959
+ const gate = snapshot.state === "closed" || !effectiveGate ? null : {
9960
+ repositoryUrl: effectiveGate.repositoryUrl,
9961
+ number: effectiveGate.number,
9962
+ headSha: effectiveGate.headSha,
9963
+ condition: effectiveGate.remoteCondition
9964
+ };
9965
+ const reasonCode = snapshot.state === "closed" ? `issue_closed_${snapshot.stateReason ?? "completed"}` : gate ? `pr_${gate.condition}` : "issue_open";
9616
9966
  return createHash("sha256").update(JSON.stringify({
9617
- version: 3,
9967
+ version: 4,
9618
9968
  issue: {
9619
9969
  state: snapshot.state,
9620
9970
  stateReason: snapshot.stateReason ?? null
9621
9971
  },
9622
- pullRequests,
9972
+ gate,
9623
9973
  reasonCode
9624
9974
  })).digest("hex");
9625
9975
  }
9626
- function buildDirectPullRequestActionFingerprint(snapshots) {
9627
- const openPullRequests = snapshots.filter((entry) => entry.lifecycleState === "open" && entry.pullRequest).map((entry) => ({
9628
- repositoryUrl: entry.repository.url.toLowerCase(),
9629
- number: entry.pullRequestLink.data.githubPullRequestNumber,
9630
- headSha: entry.pullRequest?.headSha ?? null,
9631
- condition: getEffectivePullRequestActionCondition(entry.pullRequest)
9632
- }));
9633
- const terminalOutcome = openPullRequests.length > 0 ? null : snapshots.some((entry) => entry.lifecycleState === "merged") ? "merged" : "closed";
9634
- const pullRequests = openPullRequests.length > 0 ? selectEffectivePullRequestFingerprintEntries(openPullRequests) : [];
9976
+ function buildDirectPullRequestActionFingerprint(snapshots, effectiveGate) {
9977
+ const terminalOutcome = effectiveGate ? null : snapshots.some((entry) => entry.lifecycleState === "merged") ? "merged" : "closed";
9978
+ const gate = effectiveGate ? {
9979
+ repositoryUrl: effectiveGate.repositoryUrl,
9980
+ number: effectiveGate.number,
9981
+ headSha: effectiveGate.headSha,
9982
+ condition: effectiveGate.remoteCondition
9983
+ } : null;
9635
9984
  return createHash("sha256").update(JSON.stringify({
9636
- version: 3,
9985
+ version: 4,
9637
9986
  terminalOutcome,
9638
- pullRequests
9987
+ gate
9639
9988
  })).digest("hex");
9640
9989
  }
9641
9990
  function classifyIssueInteractionReason(value) {
@@ -9728,7 +10077,7 @@ async function updatePaperclipIssueState(ctx, params) {
9728
10077
  issuePatch
9729
10078
  });
9730
10079
  const reasonCode = classifyIssueInteractionReason(transitionCommentAnnotation?.reason ?? trimmedTransitionComment);
9731
- const interactionDedupeBase = actionFingerprint ? `sync:${createHash("sha256").update(JSON.stringify({
10080
+ const interactionFamilyBase = actionFingerprint ? `sync:${createHash("sha256").update(JSON.stringify({
9732
10081
  companyId,
9733
10082
  issueId,
9734
10083
  mutation: "status_transition",
@@ -9737,14 +10086,14 @@ async function updatePaperclipIssueState(ctx, params) {
9737
10086
  nextStatus,
9738
10087
  currentIssueState: syncContext,
9739
10088
  issuePatch
9740
- })).digest("hex")}` : `sync:${issueId}:${interactionOccurredAt}:${currentStatus}:${nextStatus}`;
10089
+ })).digest("hex")}` : void 0;
9741
10090
  const mutationFamilyBase = actionFingerprint ? `sync:${createHash("sha256").update(JSON.stringify({
9742
10091
  companyId,
9743
10092
  issueId,
9744
10093
  mutation: "status_transition",
9745
10094
  actionFingerprint,
9746
10095
  nextStatus
9747
- })).digest("hex")}` : interactionDedupeBase;
10096
+ })).digest("hex")}` : `sync:${issueId}:${interactionOccurredAt}:${currentStatus}:${nextStatus}`;
9748
10097
  const hasAssigneePatch = Object.prototype.hasOwnProperty.call(issuePatch, "assigneeAgentId") || Object.prototype.hasOwnProperty.call(issuePatch, "assigneeUserId");
9749
10098
  const mutationExpectedState = {
9750
10099
  status: issuePatch.status ?? liveCurrentStatus,
@@ -9763,9 +10112,10 @@ async function updatePaperclipIssueState(ctx, params) {
9763
10112
  };
9764
10113
  const mutationExpectedStateFingerprint = createHash("sha256").update(JSON.stringify(mutationExpectedState)).digest("hex").slice(0, 32);
9765
10114
  const liveMutationStateFingerprint = createHash("sha256").update(JSON.stringify(liveMutationState)).digest("hex").slice(0, 32);
9766
- const mutationPatchBase = `${mutationFamilyBase}:patch:${createHash("sha256").update(JSON.stringify(issuePatch)).digest("hex").slice(0, 32)}:applied:${mutationExpectedStateFingerprint}`;
9767
10115
  let existingInteractionEvents = [];
9768
- if (actionFingerprint) {
10116
+ let interactionDedupeBase = mutationFamilyBase;
10117
+ let reconciliationAttemptId;
10118
+ if (actionFingerprint && interactionFamilyBase) {
9769
10119
  const ledger = await listIssueInteractionEvents(ctx, companyId, issueId, {
9770
10120
  from: "1970-01-01T00:00:00.000Z",
9771
10121
  to: "9999-12-31T23:59:59.999Z"
@@ -9774,17 +10124,30 @@ async function updatePaperclipIssueState(ctx, params) {
9774
10124
  throw new Error("GitHub Sync refused a status transition because its issue interaction ledger is incomplete or conflicting.");
9775
10125
  }
9776
10126
  existingInteractionEvents = ledger.events;
9777
- const existingIntent = existingInteractionEvents.find((event) => event.dedupeKey === `${interactionDedupeBase}:intent`);
9778
- if (existingIntent) interactionOccurredAt = existingIntent.occurredAt;
10127
+ const attemptPrefix = `${interactionFamilyBase}:attempt:`;
10128
+ const latestOpenAttemptIntent = existingInteractionEvents.filter((event) => {
10129
+ if (!event.dedupeKey.startsWith(attemptPrefix)) return false;
10130
+ const suffix = event.dedupeKey.slice(attemptPrefix.length);
10131
+ return /^[^:]+:intent$/.test(suffix);
10132
+ }).sort(
10133
+ (left, right) => right.occurredAt.localeCompare(left.occurredAt) || right.dedupeKey.localeCompare(left.dedupeKey)
10134
+ ).find((intent) => {
10135
+ const attemptBase = intent.dedupeKey.slice(0, -":intent".length);
10136
+ return !existingInteractionEvents.some(
10137
+ (event) => event.dedupeKey.startsWith(`${attemptBase}:result:`) && !event.dedupeKey.endsWith(":result:failed")
10138
+ );
10139
+ });
10140
+ if (latestOpenAttemptIntent) {
10141
+ interactionDedupeBase = latestOpenAttemptIntent.dedupeKey.slice(0, -":intent".length);
10142
+ reconciliationAttemptId = interactionDedupeBase.slice(attemptPrefix.length);
10143
+ interactionOccurredAt = latestOpenAttemptIntent.occurredAt;
10144
+ } else {
10145
+ reconciliationAttemptId = randomUUID();
10146
+ interactionDedupeBase = `${attemptPrefix}${reconciliationAttemptId}`;
10147
+ }
9779
10148
  }
9780
- const completedMutationForPatch = existingInteractionEvents.some(
9781
- (event) => event.dedupeKey.startsWith(`${mutationPatchBase}:`) && event.dedupeKey.endsWith(":mutation:result:changed")
9782
- );
9783
- const mutationDedupeBase = !issuePatchAlreadyApplied && completedMutationForPatch ? `${mutationPatchBase}:drift:${createHash("sha256").update(JSON.stringify({
9784
- currentStatus: liveCurrentStatus,
9785
- currentIssueState: liveSyncContext,
9786
- issuePatch
9787
- })).digest("hex").slice(0, 32)}` : mutationPatchBase;
10149
+ const mutationPatchBase = `${mutationFamilyBase}${reconciliationAttemptId ? `:attempt:${reconciliationAttemptId}` : ""}:patch:${createHash("sha256").update(JSON.stringify(issuePatch)).digest("hex").slice(0, 32)}:applied:${mutationExpectedStateFingerprint}`;
10150
+ const mutationDedupeBase = mutationPatchBase;
9788
10151
  await persistIssueInteractionEvent(ctx, {
9789
10152
  schemaVersion: 1,
9790
10153
  companyId,
@@ -9866,11 +10229,15 @@ async function updatePaperclipIssueState(ctx, params) {
9866
10229
  if (statusWillChange) {
9867
10230
  const commentIntentKey = `${interactionDedupeBase}:comment:intent`;
9868
10231
  const commentChangedKey = `${interactionDedupeBase}:comment:result:changed`;
10232
+ const commentFailedBeforeReturnKey = `${interactionDedupeBase}:comment:result:failed-before-return`;
9869
10233
  const priorCommentIntent = existingInteractionEvents.find((event) => event.dedupeKey === commentIntentKey);
9870
10234
  const priorCommentChanged = existingInteractionEvents.find((event) => event.dedupeKey === commentChangedKey);
10235
+ const priorCommentFailedBeforeReturn = existingInteractionEvents.find(
10236
+ (event) => event.dedupeKey === commentFailedBeforeReturnKey
10237
+ );
9871
10238
  if (priorCommentChanged) {
9872
10239
  transitionCommentComplete = true;
9873
- } else if (priorCommentIntent) {
10240
+ } else if (priorCommentIntent && !priorCommentFailedBeforeReturn) {
9874
10241
  throw new Error("GitHub Sync refused to repeat an uncertain transition comment; reconcile the durable interaction intent before retrying.");
9875
10242
  } else {
9876
10243
  const commentEventBase = {
@@ -9895,8 +10262,10 @@ async function updatePaperclipIssueState(ctx, params) {
9895
10262
  outcome: "observed",
9896
10263
  dedupeKey: commentIntentKey
9897
10264
  });
10265
+ let commentReturned = false;
9898
10266
  try {
9899
10267
  createdTransitionComment = await ctx.issues.createComment(issueId, trimmedTransitionComment, companyId);
10268
+ commentReturned = true;
9900
10269
  if (transitionCommentAnnotation) {
9901
10270
  await upsertStatusTransitionCommentAnnotation(ctx, {
9902
10271
  issueId,
@@ -9918,7 +10287,7 @@ async function updatePaperclipIssueState(ctx, params) {
9918
10287
  await persistIssueInteractionEvent(ctx, {
9919
10288
  ...commentEventBase,
9920
10289
  outcome: "failed",
9921
- dedupeKey: `${interactionDedupeBase}:comment:result:failed`
10290
+ dedupeKey: commentReturned ? `${interactionDedupeBase}:comment:result:failed-after-return` : commentFailedBeforeReturnKey
9922
10291
  });
9923
10292
  throw error;
9924
10293
  }
@@ -10124,51 +10493,6 @@ function shouldIgnoreGitHubIssue(issue, advancedSettings) {
10124
10493
  (ignoredUsername) => buildGitHubUsernameAliases(ignoredUsername).some((alias) => issueAuthorAliases.has(alias))
10125
10494
  );
10126
10495
  }
10127
- async function assignImportedPaperclipIssueToUser(ctx, params) {
10128
- if (!params.paperclipApiBaseUrl) {
10129
- ctx.logger.warn("GitHub sync could not assign a newly imported Paperclip issue to a user without the local Paperclip API. Preserving the imported issue assignment.", {
10130
- companyId: params.companyId,
10131
- issueId: params.issueId,
10132
- assigneeUserId: params.assigneeUserId
10133
- });
10134
- return;
10135
- }
10136
- try {
10137
- const response = await fetchPaperclipApi(
10138
- getPaperclipIssueEndpoint(params.paperclipApiBaseUrl, params.issueId),
10139
- {
10140
- method: "PATCH",
10141
- headers: {
10142
- accept: "application/json",
10143
- "content-type": "application/json"
10144
- },
10145
- body: JSON.stringify({
10146
- assigneeAgentId: null,
10147
- assigneeUserId: params.assigneeUserId
10148
- })
10149
- },
10150
- {
10151
- companyId: params.companyId
10152
- }
10153
- );
10154
- const payloadResult = await readPaperclipApiJsonResponse(response, {
10155
- operationLabel: "issue update",
10156
- bodyRequired: false
10157
- });
10158
- if (!payloadResult.failure) {
10159
- return;
10160
- }
10161
- throw new Error(payloadResult.failure.errorMessage ?? `Issue update failed with status ${payloadResult.failure.status ?? response.status}.`);
10162
- } catch (error) {
10163
- ctx.logger.warn("GitHub sync could not assign a newly imported Paperclip issue to a Paperclip user.", {
10164
- companyId: params.companyId,
10165
- issueId: params.issueId,
10166
- assigneeUserId: params.assigneeUserId,
10167
- paperclipApiBaseUrl: params.paperclipApiBaseUrl,
10168
- error: getErrorMessage(error)
10169
- });
10170
- }
10171
- }
10172
10496
  async function ensurePaperclipIssueStandardWorkMode(ctx, issue, companyId) {
10173
10497
  if (!("workMode" in issue) || issue.workMode === "standard") {
10174
10498
  return issue;
@@ -10185,7 +10509,6 @@ async function createPaperclipIssue(ctx, mapping, advancedSettings, issue, avail
10185
10509
  }
10186
10510
  const title = issue.title;
10187
10511
  const description = buildPaperclipIssueDescription(issue);
10188
- const defaultAssignee = getConfiguredAdvancedAssigneePrincipal(advancedSettings, "default");
10189
10512
  const createdIssue = await ensurePaperclipIssueStandardWorkMode(
10190
10513
  ctx,
10191
10514
  await ctx.issues.create({
@@ -10193,24 +10516,15 @@ async function createPaperclipIssue(ctx, mapping, advancedSettings, issue, avail
10193
10516
  projectId: mapping.paperclipProjectId,
10194
10517
  title,
10195
10518
  ...description ? { description } : {},
10196
- status: advancedSettings.defaultStatus,
10519
+ status: "backlog",
10197
10520
  originKind: GITHUB_ISSUE_ORIGIN_KIND,
10198
- originId: normalizeGitHubIssueHtmlUrl(issue.htmlUrl) ?? issue.htmlUrl,
10199
- ...defaultAssignee?.kind === "agent" ? { assigneeAgentId: defaultAssignee.id } : defaultAssignee?.kind === "user" ? { assigneeUserId: defaultAssignee.id } : {}
10521
+ originId: normalizeGitHubIssueHtmlUrl(issue.htmlUrl) ?? issue.htmlUrl
10200
10522
  }),
10201
10523
  mapping.companyId
10202
10524
  );
10203
10525
  const ensuredCreatedIssueId = createdIssue.id;
10204
10526
  const normalizedCreatedIssueDescription = createdIssue.description ?? void 0;
10205
10527
  const createPath = "sdk";
10206
- if (defaultAssignee?.kind === "user") {
10207
- await assignImportedPaperclipIssueToUser(ctx, {
10208
- companyId: mapping.companyId,
10209
- issueId: ensuredCreatedIssueId,
10210
- assigneeUserId: defaultAssignee.id,
10211
- paperclipApiBaseUrl
10212
- });
10213
- }
10214
10528
  if (normalizeIssueDescriptionValue(normalizedCreatedIssueDescription) !== description) {
10215
10529
  logIssueDescriptionDiagnostic(
10216
10530
  ctx,
@@ -10302,7 +10616,8 @@ async function ensurePaperclipIssueImported(ctx, mapping, advancedSettings, issu
10302
10616
  mapping,
10303
10617
  issue,
10304
10618
  existingImportedPaperclipIssue.id,
10305
- coerceDate(existingImportedPaperclipIssue.createdAt ?? /* @__PURE__ */ new Date()).toISOString()
10619
+ coerceDate(existingImportedPaperclipIssue.createdAt ?? /* @__PURE__ */ new Date()).toISOString(),
10620
+ true
10306
10621
  )
10307
10622
  );
10308
10623
  importRegistryByIssueId.set(issue.id, repairedRecord);
@@ -10321,7 +10636,7 @@ async function ensurePaperclipIssueImported(ctx, mapping, advancedSettings, issu
10321
10636
  );
10322
10637
  const registryRecord = upsertImportedIssueRecord(
10323
10638
  nextRegistry,
10324
- buildImportedIssueRecord(mapping, issue, createdIssue.id, (/* @__PURE__ */ new Date()).toISOString())
10639
+ buildImportedIssueRecord(mapping, issue, createdIssue.id, (/* @__PURE__ */ new Date()).toISOString(), true)
10325
10640
  );
10326
10641
  importRegistryByIssueId.set(issue.id, registryRecord);
10327
10642
  ensuredPaperclipIssueIds.set(issue.id, createdIssue.id);
@@ -10746,15 +11061,35 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10746
11061
  }
10747
11062
  }
10748
11063
  }
10749
- const hasTrustedNewLinkedPullRequestComment = paperclipIssue.status === "backlog" || currentLinkedPullRequestCommentCounts.length === 0 ? false : await hasTrustedNewLinkedPullRequestComments({
11064
+ const trustedNewLinkedPullRequestCommentSources = paperclipIssue.status === "backlog" || currentLinkedPullRequestCommentCounts.length === 0 ? [] : await listTrustedNewLinkedPullRequestCommentSources({
10750
11065
  octokit,
10751
11066
  originalPosterLogin: githubIssue.authorLogin,
10752
11067
  previousCommentCounts: importedIssue.linkedPullRequestCommentCounts,
10753
11068
  currentCommentCounts: currentLinkedPullRequestCommentCounts,
10754
11069
  maintainerCache: repositoryMaintainerCache
10755
11070
  });
11071
+ const hasTrustedNewLinkedPullRequestComment = trustedNewLinkedPullRequestCommentSources.length > 0;
10756
11072
  const hasTrustedNewComment = hasTrustedNewIssueComment || hasTrustedNewLinkedPullRequestComment;
10757
- const remoteActionFingerprint = buildRemoteActionFingerprint(snapshot);
11073
+ const issueLinkedPullRequestLinks = snapshot.linkedPullRequests.length === 0 ? [] : await listGitHubPullRequestLinkRecords(ctx, {
11074
+ paperclipIssueId: importedIssue.paperclipIssueId
11075
+ });
11076
+ const effectiveGate = selectEffectiveIssueLinkedPullRequestGate(
11077
+ snapshot.linkedPullRequests,
11078
+ trustedNewLinkedPullRequestCommentSources,
11079
+ hasTrustedNewIssueComment,
11080
+ issueLinkedPullRequestLinks,
11081
+ importedIssue.selectedPullRequestGate
11082
+ );
11083
+ const followThroughAssigneeAgentId = await resolveValidFollowThroughAssigneeAgentId(
11084
+ ctx,
11085
+ mapping.companyId,
11086
+ effectiveGate?.ownerCandidate
11087
+ );
11088
+ const transitionFollowThroughAssigneeAgentId = isActionableDirectPullRequestGate(effectiveGate) ? followThroughAssigneeAgentId : void 0;
11089
+ const remoteActionFingerprint = createHash("sha256").update(JSON.stringify({
11090
+ issue: buildRemoteActionFingerprint(snapshot, effectiveGate),
11091
+ followThroughAssigneeAgentId
11092
+ })).digest("hex");
10758
11093
  const actionJournalFingerprint = createHash("sha256").update(JSON.stringify({
10759
11094
  remoteActionFingerprint,
10760
11095
  issueCommentCount: snapshot.commentCount,
@@ -10762,9 +11097,14 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10762
11097
  currentLinkedPullRequestCommentCounts
10763
11098
  )
10764
11099
  })).digest("hex");
10765
- if (importedIssue.pendingRemoteActionWake) {
11100
+ const createWakeFingerprint = () => createRemoteActionWakeFingerprint(remoteActionFingerprint);
11101
+ if (importedIssue.pendingRemoteActionWake && isPendingWakeApplied(
11102
+ importedIssue.pendingRemoteActionWake,
11103
+ paperclipIssue.status,
11104
+ getPaperclipIssueSyncContext(paperclipIssue).assignee
11105
+ )) {
10766
11106
  const pendingWake2 = importedIssue.pendingRemoteActionWake;
10767
- await wakePaperclipIssueAssignee(ctx, {
11107
+ const admitted = await wakePaperclipIssueAssignee(ctx, {
10768
11108
  assigneeAgentId: pendingWake2.assigneeAgentId,
10769
11109
  paperclipIssueId: importedIssue.paperclipIssueId,
10770
11110
  companyId: mapping.companyId,
@@ -10775,11 +11115,15 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10775
11115
  previousStatus: pendingWake2.previousStatus,
10776
11116
  nextStatus: pendingWake2.nextStatus
10777
11117
  });
10778
- delete importedIssue.pendingRemoteActionWake;
10779
- await persistImportRegistry();
11118
+ if (admitted) {
11119
+ delete importedIssue.pendingRemoteActionWake;
11120
+ delete importedIssue.activationPending;
11121
+ await persistImportRegistry();
11122
+ }
10780
11123
  }
10781
11124
  const wasImportedThisRun = createdIssueIds.has(importedIssue.githubIssueId);
10782
- const maintainerAuthoredImportedIssue = wasImportedThisRun && advancedSettings.defaultStatus !== "todo" && snapshot.state === "open" && snapshot.linkedPullRequests.length === 0 ? await isMaintainerAuthoredGitHubIssue({
11125
+ const isPendingInitialActivation = wasImportedThisRun || importedIssue.activationPending === true;
11126
+ const maintainerAuthoredImportedIssue = isPendingInitialActivation && advancedSettings.defaultStatus !== "todo" && snapshot.state === "open" && snapshot.linkedPullRequests.length === 0 ? await isMaintainerAuthoredGitHubIssue({
10783
11127
  octokit,
10784
11128
  repository,
10785
11129
  githubIssue,
@@ -10788,13 +11132,15 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10788
11132
  const paperclipIssueSyncContext = getPaperclipIssueSyncContext(paperclipIssue);
10789
11133
  const executorTransitionAssignee = resolvePaperclipIssueExecutorAssignee(
10790
11134
  paperclipIssueSyncContext,
10791
- advancedSettings
11135
+ advancedSettings,
11136
+ transitionFollowThroughAssigneeAgentId
10792
11137
  );
10793
11138
  let nextStatus = resolvePaperclipIssueStatus({
10794
11139
  currentStatus: paperclipIssue.status,
10795
11140
  snapshot,
11141
+ effectiveGate,
10796
11142
  hasTrustedNewComment,
10797
- wasImportedThisRun,
11143
+ wasImportedThisRun: isPendingInitialActivation,
10798
11144
  defaultImportedStatus: advancedSettings.defaultStatus,
10799
11145
  maintainerAuthoredImportedIssue,
10800
11146
  hasExecutorHandoffTarget: Boolean(executorTransitionAssignee)
@@ -10802,41 +11148,57 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10802
11148
  if (paperclipIssue.status === "blocked" && nextStatus !== "blocked" && await hasUnresolvedPaperclipIssueBlocker(ctx, paperclipIssue, mapping.companyId)) {
10803
11149
  nextStatus = "blocked";
10804
11150
  }
10805
- if (paperclipIssue.status !== nextStatus && !hasTrustedNewComment && importedIssue.remoteActionFingerprint === remoteActionFingerprint) {
10806
- nextStatus = paperclipIssue.status;
10807
- }
10808
11151
  const shouldPreserveMaintainerWaitRouting = isHealthyMaintainerWaitTransition({
10809
11152
  currentStatus: paperclipIssue.status,
10810
11153
  nextStatus,
10811
11154
  syncContext: paperclipIssueSyncContext
10812
11155
  });
10813
11156
  const shouldClearCompletedExecutionPolicy = nextStatus === "done" || nextStatus === "cancelled";
10814
- const shouldPreserveImportedTriageRouting = shouldPreserveImportedTriageAssignee({
11157
+ const shouldPreserveImportedTriageRouting = Boolean(paperclipIssueSyncContext.assignee) && shouldPreserveImportedTriageAssignee({
10815
11158
  currentStatus: paperclipIssue.status,
10816
11159
  nextStatus,
10817
- wasImportedThisRun,
11160
+ wasImportedThisRun: isPendingInitialActivation,
10818
11161
  maintainerAuthoredImportedIssue
10819
11162
  });
10820
- const nextTransitionAssignee = shouldPreserveImportedTriageRouting ? null : resolveSyncTransitionAssignee({
11163
+ const configuredDefaultAssignee = getConfiguredAdvancedAssigneePrincipal(advancedSettings, "default");
11164
+ const nextTransitionAssignee = isPendingInitialActivation && configuredDefaultAssignee ? { principal: configuredDefaultAssignee, role: "executor" } : shouldPreserveImportedTriageRouting ? null : resolveSyncTransitionAssignee({
10821
11165
  currentStatus: paperclipIssue.status,
10822
11166
  nextStatus,
10823
11167
  syncContext: paperclipIssueSyncContext,
10824
- advancedSettings
11168
+ advancedSettings,
11169
+ followThroughAssigneeAgentId: transitionFollowThroughAssigneeAgentId
10825
11170
  });
10826
11171
  const shouldClearTransitionAssignee = nextStatus === "in_review" && (nextTransitionAssignee === null || shouldPreserveMaintainerWaitRouting);
10827
11172
  const nextAssigneeChanged = nextTransitionAssignee ? !doesPaperclipIssueAssigneeMatch(paperclipIssueSyncContext.assignee, nextTransitionAssignee.principal) : false;
10828
- const shouldWakeImportedAssignee = wasImportedThisRun && nextStatus === "todo" && (paperclipIssue.status === nextStatus || shouldPreserveImportedTriageRouting) && paperclipIssueSyncContext.assignee?.kind === "agent";
10829
- const shouldWakeTransitionAssignee = paperclipIssue.status !== nextStatus && nextTransitionAssignee?.principal.kind === "agent" && isActionablePaperclipIssueStatus(nextStatus) && (nextAssigneeChanged || paperclipIssue.status !== nextStatus);
11173
+ const importedActivationAssignee = paperclipIssueSyncContext.assignee?.kind === "agent" ? paperclipIssueSyncContext.assignee : nextTransitionAssignee?.principal.kind === "agent" ? nextTransitionAssignee.principal : void 0;
11174
+ const shouldWakeImportedAssignee = isPendingInitialActivation && nextStatus === "todo" && Boolean(importedActivationAssignee);
11175
+ const shouldWakeTransitionAssignee = nextTransitionAssignee?.principal.kind === "agent" && isActionablePaperclipIssueStatus(nextStatus) && (nextAssigneeChanged || paperclipIssue.status !== nextStatus);
10830
11176
  const persistObservedRemoteState = async (pendingWake2) => {
10831
11177
  importedIssue.githubIssueNumber = githubIssue.number;
10832
11178
  importedIssue.lastSeenCommentCount = snapshot.commentCount;
10833
11179
  importedIssue.lastSeenGitHubState = snapshot.state;
10834
11180
  importedIssue.linkedPullRequestCommentCounts = currentLinkedPullRequestCommentCounts;
10835
11181
  importedIssue.remoteActionFingerprint = remoteActionFingerprint;
11182
+ importedIssue.selectedPullRequestGate = effectiveGate ? { repositoryUrl: effectiveGate.repositoryUrl, number: effectiveGate.number } : void 0;
10836
11183
  if (pendingWake2) importedIssue.pendingRemoteActionWake = pendingWake2;
11184
+ else delete importedIssue.activationPending;
10837
11185
  await persistImportRegistry();
10838
11186
  };
10839
11187
  if (paperclipIssue.status === nextStatus) {
11188
+ const pendingWake2 = shouldWakeImportedAssignee && importedActivationAssignee ? reuseOrCreatePendingWake(importedIssue.pendingRemoteActionWake, {
11189
+ assigneeAgentId: importedActivationAssignee.id,
11190
+ reason: IMPORTED_ISSUE_WAKE_REASON,
11191
+ mutation: "import",
11192
+ nextStatus
11193
+ }, createWakeFingerprint) : shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? reuseOrCreatePendingWake(importedIssue.pendingRemoteActionWake, {
11194
+ assigneeAgentId: nextTransitionAssignee.principal.id,
11195
+ reason: STATUS_TRANSITION_WAKE_REASON,
11196
+ mutation: "status_transition",
11197
+ previousStatus: paperclipIssue.status,
11198
+ nextStatus
11199
+ }, createWakeFingerprint) : void 0;
11200
+ if (pendingWake2) importedIssue.pendingRemoteActionWake = pendingWake2;
11201
+ if (pendingWake2 || isPendingInitialActivation) await persistImportRegistry();
10840
11202
  updateSyncFailureContext(syncFailureContext, {
10841
11203
  phase: "updating_paperclip_status",
10842
11204
  repositoryUrl: repository.url,
@@ -10848,31 +11210,27 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10848
11210
  currentStatus: paperclipIssue.status,
10849
11211
  syncContext: paperclipIssueSyncContext,
10850
11212
  nextStatus,
11213
+ ...nextAssigneeChanged && nextTransitionAssignee ? { nextAssignee: nextTransitionAssignee.principal } : {},
10851
11214
  ...shouldClearTransitionAssignee ? { clearAssignee: true } : {},
10852
11215
  ...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
10853
11216
  transitionComment: "",
10854
11217
  actionFingerprint: actionJournalFingerprint,
10855
11218
  paperclipApiBaseUrl
10856
11219
  });
10857
- if (shouldWakeImportedAssignee && paperclipIssueSyncContext.assignee?.kind === "agent") {
10858
- const pendingWake2 = {
10859
- fingerprint: remoteActionFingerprint,
10860
- assigneeAgentId: paperclipIssueSyncContext.assignee.id,
10861
- reason: IMPORTED_ISSUE_WAKE_REASON,
10862
- mutation: "import",
10863
- nextStatus
10864
- };
11220
+ if (pendingWake2) {
10865
11221
  await persistObservedRemoteState(pendingWake2);
10866
11222
  queuedIssueWakeups.push({
10867
11223
  assigneeAgentId: pendingWake2.assigneeAgentId,
10868
11224
  paperclipIssueId: importedIssue.paperclipIssueId,
10869
11225
  reason: pendingWake2.reason,
10870
- mutation: "import",
11226
+ mutation: pendingWake2.mutation,
10871
11227
  actionFingerprint: pendingWake2.fingerprint,
11228
+ previousStatus: pendingWake2.previousStatus,
10872
11229
  nextStatus,
10873
11230
  onSuccess: async () => {
10874
11231
  if (importedIssue.pendingRemoteActionWake?.fingerprint === pendingWake2.fingerprint) {
10875
11232
  delete importedIssue.pendingRemoteActionWake;
11233
+ delete importedIssue.activationPending;
10876
11234
  await persistImportRegistry();
10877
11235
  }
10878
11236
  }
@@ -10895,6 +11253,21 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10895
11253
  repositoryUrl: repository.url,
10896
11254
  githubIssueNumber: githubIssue.number
10897
11255
  });
11256
+ const pendingWake = shouldWakeImportedAssignee && importedActivationAssignee ? reuseOrCreatePendingWake(importedIssue.pendingRemoteActionWake, {
11257
+ assigneeAgentId: importedActivationAssignee.id,
11258
+ reason: IMPORTED_ISSUE_WAKE_REASON,
11259
+ mutation: "import",
11260
+ previousStatus: paperclipIssue.status,
11261
+ nextStatus
11262
+ }, createWakeFingerprint) : shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? reuseOrCreatePendingWake(importedIssue.pendingRemoteActionWake, {
11263
+ assigneeAgentId: nextTransitionAssignee.principal.id,
11264
+ reason: STATUS_TRANSITION_WAKE_REASON,
11265
+ mutation: "status_transition",
11266
+ previousStatus: paperclipIssue.status,
11267
+ nextStatus
11268
+ }, createWakeFingerprint) : void 0;
11269
+ if (pendingWake) importedIssue.pendingRemoteActionWake = pendingWake;
11270
+ if (pendingWake || isPendingInitialActivation) await persistImportRegistry();
10898
11271
  await updatePaperclipIssueState(ctx, {
10899
11272
  companyId: mapping.companyId,
10900
11273
  issueId: importedIssue.paperclipIssueId,
@@ -10909,21 +11282,6 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10909
11282
  actionFingerprint: actionJournalFingerprint,
10910
11283
  paperclipApiBaseUrl
10911
11284
  });
10912
- const pendingWake = shouldWakeImportedAssignee && paperclipIssueSyncContext.assignee?.kind === "agent" ? {
10913
- fingerprint: remoteActionFingerprint,
10914
- assigneeAgentId: paperclipIssueSyncContext.assignee.id,
10915
- reason: IMPORTED_ISSUE_WAKE_REASON,
10916
- mutation: "import",
10917
- previousStatus: paperclipIssue.status,
10918
- nextStatus
10919
- } : shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? {
10920
- fingerprint: remoteActionFingerprint,
10921
- assigneeAgentId: nextTransitionAssignee.principal.id,
10922
- reason: STATUS_TRANSITION_WAKE_REASON,
10923
- mutation: "status_transition",
10924
- previousStatus: paperclipIssue.status,
10925
- nextStatus
10926
- } : void 0;
10927
11285
  await persistObservedRemoteState(pendingWake);
10928
11286
  updatedStatusesCount += 1;
10929
11287
  if (pendingWake) {
@@ -10938,6 +11296,7 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10938
11296
  onSuccess: async () => {
10939
11297
  if (importedIssue.pendingRemoteActionWake?.fingerprint === pendingWake.fingerprint) {
10940
11298
  delete importedIssue.pendingRemoteActionWake;
11299
+ delete importedIssue.activationPending;
10941
11300
  await persistImportRegistry();
10942
11301
  }
10943
11302
  }
@@ -10965,7 +11324,7 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10965
11324
  queuedIssueWakeups,
10966
11325
  IMPORTED_ISSUE_WAKEUP_CONCURRENCY,
10967
11326
  async (queuedWakeup) => {
10968
- await wakePaperclipIssueAssignee(ctx, {
11327
+ const admitted = await wakePaperclipIssueAssignee(ctx, {
10969
11328
  assigneeAgentId: queuedWakeup.assigneeAgentId,
10970
11329
  paperclipIssueId: queuedWakeup.paperclipIssueId,
10971
11330
  companyId: mapping.companyId,
@@ -10976,7 +11335,7 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10976
11335
  previousStatus: queuedWakeup.previousStatus,
10977
11336
  nextStatus: queuedWakeup.nextStatus
10978
11337
  });
10979
- await queuedWakeup.onSuccess?.();
11338
+ if (admitted) await queuedWakeup.onSuccess?.();
10980
11339
  }
10981
11340
  );
10982
11341
  return {
@@ -11115,9 +11474,13 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11115
11474
  remoteAction = { key: remoteActionKey };
11116
11475
  remoteActionRegistry.push(remoteAction);
11117
11476
  }
11118
- if (remoteAction.pendingWake) {
11477
+ if (remoteAction.pendingWake && isPendingWakeApplied(
11478
+ remoteAction.pendingWake,
11479
+ paperclipIssue.status,
11480
+ getPaperclipIssueSyncContext(paperclipIssue).assignee
11481
+ )) {
11119
11482
  const pendingWake2 = remoteAction.pendingWake;
11120
- await wakePaperclipIssueAssignee(ctx, {
11483
+ const admitted = await wakePaperclipIssueAssignee(ctx, {
11121
11484
  assigneeAgentId: pendingWake2.assigneeAgentId,
11122
11485
  paperclipIssueId,
11123
11486
  companyId: mapping.companyId,
@@ -11128,49 +11491,62 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11128
11491
  previousStatus: pendingWake2.previousStatus,
11129
11492
  nextStatus: pendingWake2.nextStatus
11130
11493
  });
11131
- delete remoteAction.pendingWake;
11132
- await persistRemoteActionRegistry();
11494
+ if (admitted) {
11495
+ delete remoteAction.pendingWake;
11496
+ await persistRemoteActionRegistry();
11497
+ }
11133
11498
  }
11134
11499
  const currentCommentCounts = pullRequestSnapshots.map((snapshot) => snapshot.commentCounts).filter((counts) => Boolean(counts));
11135
- let hasTrustedNewComment = false;
11500
+ const trustedCommentSources = [];
11136
11501
  if (paperclipIssue.status !== "backlog" && remoteAction.linkedPullRequestCommentCounts) {
11137
11502
  const maintainerCache = /* @__PURE__ */ new Map();
11138
11503
  for (const snapshot of pullRequestSnapshots) {
11139
11504
  if (!snapshot.commentCounts) continue;
11140
- if (await hasTrustedNewLinkedPullRequestComments({
11505
+ trustedCommentSources.push(...await listTrustedNewLinkedPullRequestCommentSources({
11141
11506
  octokit,
11142
11507
  originalPosterLogin: snapshot.authorLogin,
11143
11508
  previousCommentCounts: remoteAction.linkedPullRequestCommentCounts,
11144
11509
  currentCommentCounts: [snapshot.commentCounts],
11145
11510
  maintainerCache
11146
- })) {
11147
- hasTrustedNewComment = true;
11148
- break;
11149
- }
11511
+ }));
11150
11512
  }
11151
11513
  }
11152
- const remoteActionFingerprint = buildDirectPullRequestActionFingerprint(pullRequestSnapshots);
11514
+ const effectiveGate = selectEffectiveDirectPullRequestGate(
11515
+ pullRequestSnapshots,
11516
+ trustedCommentSources,
11517
+ remoteAction.selectedPullRequestGate
11518
+ );
11519
+ const hasTrustedNewComment = Boolean(effectiveGate?.trustedCommentKinds.length);
11520
+ const followThroughAssigneeAgentId = await resolveValidFollowThroughAssigneeAgentId(
11521
+ ctx,
11522
+ mapping.companyId,
11523
+ effectiveGate?.ownerCandidate
11524
+ );
11525
+ const transitionFollowThroughAssigneeAgentId = isActionableDirectPullRequestGate(effectiveGate) ? followThroughAssigneeAgentId : void 0;
11526
+ const remoteActionFingerprint = createHash("sha256").update(JSON.stringify({
11527
+ pullRequest: buildDirectPullRequestActionFingerprint(pullRequestSnapshots, effectiveGate),
11528
+ followThroughAssigneeAgentId
11529
+ })).digest("hex");
11153
11530
  const actionJournalFingerprint = createHash("sha256").update(JSON.stringify({
11154
11531
  remoteActionFingerprint,
11155
11532
  commentCounts: canonicalizeGitHubPullRequestCommentCounts(currentCommentCounts)
11156
11533
  })).digest("hex");
11534
+ const createWakeFingerprint = () => createRemoteActionWakeFingerprint(remoteActionFingerprint);
11157
11535
  const paperclipIssueSyncContext = getPaperclipIssueSyncContext(paperclipIssue);
11158
11536
  const executorTransitionAssignee = resolvePaperclipIssueExecutorAssignee(
11159
11537
  paperclipIssueSyncContext,
11160
- advancedSettings
11538
+ advancedSettings,
11539
+ transitionFollowThroughAssigneeAgentId
11161
11540
  );
11162
11541
  let nextStatus = resolvePaperclipDirectPullRequestIssueStatus({
11163
11542
  currentStatus: paperclipIssue.status,
11164
11543
  pullRequests: pullRequestSnapshots,
11165
- hasExecutorHandoffTarget: Boolean(executorTransitionAssignee),
11166
- hasTrustedNewComment
11544
+ effectiveGate,
11545
+ hasExecutorHandoffTarget: Boolean(executorTransitionAssignee)
11167
11546
  });
11168
11547
  if (paperclipIssue.status === "blocked" && nextStatus !== "blocked" && pullRequestSnapshots.some((entry) => entry.lifecycleState === "open") && await hasUnresolvedPaperclipIssueBlocker(ctx, paperclipIssue, mapping.companyId)) {
11169
11548
  nextStatus = "blocked";
11170
11549
  }
11171
- if (paperclipIssue.status !== nextStatus && remoteAction.fingerprint === remoteActionFingerprint && !hasTrustedNewComment) {
11172
- nextStatus = paperclipIssue.status;
11173
- }
11174
11550
  const shouldPreserveMaintainerWaitRouting = isHealthyMaintainerWaitTransition({
11175
11551
  currentStatus: paperclipIssue.status,
11176
11552
  nextStatus,
@@ -11181,13 +11557,31 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11181
11557
  currentStatus: paperclipIssue.status,
11182
11558
  nextStatus,
11183
11559
  syncContext: paperclipIssueSyncContext,
11184
- advancedSettings
11560
+ advancedSettings,
11561
+ followThroughAssigneeAgentId: transitionFollowThroughAssigneeAgentId
11185
11562
  });
11186
11563
  const shouldClearTransitionAssignee = nextStatus === "in_review" && (nextTransitionAssignee === null || shouldPreserveMaintainerWaitRouting);
11187
11564
  const nextAssigneeChanged = nextTransitionAssignee ? !doesPaperclipIssueAssigneeMatch(paperclipIssueSyncContext.assignee, nextTransitionAssignee.principal) : false;
11188
- const shouldWakeTransitionAssignee = paperclipIssue.status !== nextStatus && nextTransitionAssignee?.principal.kind === "agent" && isActionablePaperclipIssueStatus(nextStatus) && (nextAssigneeChanged || paperclipIssue.status !== nextStatus);
11565
+ const shouldWakeTransitionAssignee = nextTransitionAssignee?.principal.kind === "agent" && isActionablePaperclipIssueStatus(nextStatus) && (nextAssigneeChanged || paperclipIssue.status !== nextStatus);
11189
11566
  if (paperclipIssue.status === nextStatus) {
11190
- if (shouldClearTransitionAssignee || shouldClearCompletedExecutionPolicy) {
11567
+ if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" && !canReservePendingWake(remoteActionRegistry, remoteAction)) {
11568
+ throw new Error(
11569
+ `Remote action registry pending-wake capacity ${MAX_REMOTE_ACTION_REGISTRY_RECORDS} reached; refusing an untracked assignment update`
11570
+ );
11571
+ }
11572
+ const pendingWake2 = shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? reuseOrCreatePendingWake(remoteAction.pendingWake, {
11573
+ assigneeAgentId: nextTransitionAssignee.principal.id,
11574
+ reason: STATUS_TRANSITION_WAKE_REASON,
11575
+ mutation: "status_transition",
11576
+ previousStatus: paperclipIssue.status,
11577
+ nextStatus
11578
+ }, createWakeFingerprint) : void 0;
11579
+ if (pendingWake2) {
11580
+ remoteAction.pendingWake = pendingWake2;
11581
+ await persistRemoteActionRegistry();
11582
+ remoteAction = remoteActionRegistry.find((record) => record.key === remoteActionKey) ?? remoteAction;
11583
+ }
11584
+ if (shouldClearTransitionAssignee || shouldClearCompletedExecutionPolicy || nextAssigneeChanged) {
11191
11585
  updateSyncFailureContext(syncFailureContext, {
11192
11586
  phase: "updating_paperclip_status",
11193
11587
  repositoryUrl: primaryRepository?.url,
@@ -11199,6 +11593,7 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11199
11593
  currentStatus: paperclipIssue.status,
11200
11594
  syncContext: paperclipIssueSyncContext,
11201
11595
  nextStatus,
11596
+ ...nextAssigneeChanged && nextTransitionAssignee ? { nextAssignee: nextTransitionAssignee.principal } : {},
11202
11597
  ...shouldClearTransitionAssignee ? { clearAssignee: true } : {},
11203
11598
  ...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
11204
11599
  transitionComment: "",
@@ -11208,7 +11603,27 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11208
11603
  }
11209
11604
  remoteAction.fingerprint = remoteActionFingerprint;
11210
11605
  remoteAction.linkedPullRequestCommentCounts = currentCommentCounts;
11606
+ remoteAction.selectedPullRequestGate = effectiveGate ? { repositoryUrl: effectiveGate.repositoryUrl, number: effectiveGate.number } : void 0;
11607
+ if (pendingWake2) remoteAction.pendingWake = pendingWake2;
11211
11608
  await persistRemoteActionRegistry();
11609
+ if (pendingWake2) {
11610
+ queuedIssueWakeups.push({
11611
+ assigneeAgentId: pendingWake2.assigneeAgentId,
11612
+ paperclipIssueId,
11613
+ reason: pendingWake2.reason,
11614
+ mutation: "status_transition",
11615
+ actionFingerprint: pendingWake2.fingerprint,
11616
+ previousStatus: pendingWake2.previousStatus,
11617
+ nextStatus: pendingWake2.nextStatus,
11618
+ onSuccess: async () => {
11619
+ const persistedRemoteAction = remoteActionRegistry.find((record) => record.key === remoteActionKey);
11620
+ if (persistedRemoteAction?.pendingWake?.fingerprint === pendingWake2.fingerprint) {
11621
+ delete persistedRemoteAction.pendingWake;
11622
+ await persistRemoteActionRegistry();
11623
+ }
11624
+ }
11625
+ });
11626
+ }
11212
11627
  continue;
11213
11628
  }
11214
11629
  const transitionComment = buildPaperclipPullRequestIssueStatusTransitionComment({
@@ -11221,11 +11636,23 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11221
11636
  repositoryUrl: primaryRepository?.url,
11222
11637
  githubIssueNumber: void 0
11223
11638
  });
11224
- if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" && remoteActionRegistry.filter((record) => record.pendingWake).length >= MAX_REMOTE_ACTION_REGISTRY_RECORDS) {
11639
+ if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" && !canReservePendingWake(remoteActionRegistry, remoteAction)) {
11225
11640
  throw new Error(
11226
11641
  `Remote action registry pending-wake capacity ${MAX_REMOTE_ACTION_REGISTRY_RECORDS} reached; refusing an untracked status transition`
11227
11642
  );
11228
11643
  }
11644
+ const pendingWake = shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? reuseOrCreatePendingWake(remoteAction.pendingWake, {
11645
+ assigneeAgentId: nextTransitionAssignee.principal.id,
11646
+ reason: STATUS_TRANSITION_WAKE_REASON,
11647
+ mutation: "status_transition",
11648
+ previousStatus: paperclipIssue.status,
11649
+ nextStatus
11650
+ }, createWakeFingerprint) : void 0;
11651
+ if (pendingWake) {
11652
+ remoteAction.pendingWake = pendingWake;
11653
+ await persistRemoteActionRegistry();
11654
+ remoteAction = remoteActionRegistry.find((record) => record.key === remoteActionKey) ?? remoteAction;
11655
+ }
11229
11656
  await updatePaperclipIssueState(ctx, {
11230
11657
  companyId: mapping.companyId,
11231
11658
  issueId: paperclipIssueId,
@@ -11239,16 +11666,9 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11239
11666
  actionFingerprint: actionJournalFingerprint,
11240
11667
  paperclipApiBaseUrl
11241
11668
  });
11242
- const pendingWake = shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? {
11243
- fingerprint: remoteActionFingerprint,
11244
- assigneeAgentId: nextTransitionAssignee.principal.id,
11245
- reason: STATUS_TRANSITION_WAKE_REASON,
11246
- mutation: "status_transition",
11247
- previousStatus: paperclipIssue.status,
11248
- nextStatus
11249
- } : void 0;
11250
11669
  remoteAction.fingerprint = remoteActionFingerprint;
11251
11670
  remoteAction.linkedPullRequestCommentCounts = currentCommentCounts;
11671
+ remoteAction.selectedPullRequestGate = effectiveGate ? { repositoryUrl: effectiveGate.repositoryUrl, number: effectiveGate.number } : void 0;
11252
11672
  if (pendingWake) remoteAction.pendingWake = pendingWake;
11253
11673
  await persistRemoteActionRegistry();
11254
11674
  updatedStatusesCount += 1;
@@ -11262,8 +11682,9 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11262
11682
  previousStatus: pendingWake.previousStatus,
11263
11683
  nextStatus: pendingWake.nextStatus,
11264
11684
  onSuccess: async () => {
11265
- if (remoteAction.pendingWake?.fingerprint === pendingWake.fingerprint) {
11266
- delete remoteAction.pendingWake;
11685
+ const persistedRemoteAction = remoteActionRegistry.find((record) => record.key === remoteActionKey);
11686
+ if (persistedRemoteAction?.pendingWake?.fingerprint === pendingWake.fingerprint) {
11687
+ delete persistedRemoteAction.pendingWake;
11267
11688
  await persistRemoteActionRegistry();
11268
11689
  }
11269
11690
  }
@@ -11280,7 +11701,7 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11280
11701
  queuedIssueWakeups,
11281
11702
  IMPORTED_ISSUE_WAKEUP_CONCURRENCY,
11282
11703
  async (queuedWakeup) => {
11283
- await wakePaperclipIssueAssignee(ctx, {
11704
+ const admitted = await wakePaperclipIssueAssignee(ctx, {
11284
11705
  assigneeAgentId: queuedWakeup.assigneeAgentId,
11285
11706
  paperclipIssueId: queuedWakeup.paperclipIssueId,
11286
11707
  companyId: mapping.companyId,
@@ -11291,7 +11712,7 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11291
11712
  previousStatus: queuedWakeup.previousStatus,
11292
11713
  nextStatus: queuedWakeup.nextStatus
11293
11714
  });
11294
- await queuedWakeup.onSuccess?.();
11715
+ if (admitted) await queuedWakeup.onSuccess?.();
11295
11716
  }
11296
11717
  );
11297
11718
  return {
@@ -11828,19 +12249,24 @@ async function handleCompanyMetricApiRoute(ctx, input) {
11828
12249
  let linkedRepository = null;
11829
12250
  let linkedPullRequestNumber;
11830
12251
  let linkedPullRequestUrl;
12252
+ let linkedFollowThroughAssigneeAgentId;
12253
+ let linkedFollowThroughAssigneeUpdatedAt;
11831
12254
  if (paperclipIssueId) {
11832
12255
  const linkResult = await linkPaperclipIssueToGitHubPullRequest(ctx, {
11833
12256
  companyId,
11834
12257
  issueId: paperclipIssueId,
11835
12258
  repositoryUrl: repository?.url,
11836
12259
  pullRequestNumber,
11837
- pullRequestUrl
12260
+ pullRequestUrl,
12261
+ followThroughAssigneeAgentId: payload.followThroughAssigneeAgentId
11838
12262
  });
11839
12263
  linkedPaperclipIssueId = typeof linkResult.paperclipIssueId === "string" ? linkResult.paperclipIssueId : paperclipIssueId;
11840
12264
  const resultRepositoryUrl = normalizeOptionalString2(linkResult.repositoryUrl);
11841
12265
  linkedRepository = resultRepositoryUrl ? parseRepositoryReference(resultRepositoryUrl) : null;
11842
12266
  linkedPullRequestNumber = normalizeToolPositiveInteger(linkResult.githubPullRequestNumber);
11843
12267
  linkedPullRequestUrl = normalizeGitHubPullRequestHtmlUrl(normalizeOptionalString2(linkResult.githubPullRequestUrl));
12268
+ linkedFollowThroughAssigneeAgentId = normalizeOptionalString2(linkResult.followThroughAssigneeAgentId);
12269
+ linkedFollowThroughAssigneeUpdatedAt = normalizeOptionalString2(linkResult.followThroughAssigneeUpdatedAt);
11844
12270
  }
11845
12271
  const metricRepositoryUrl = repository?.url ?? linkedRepository?.url;
11846
12272
  const metricPullRequestNumber = pullRequestNumber ?? linkedPullRequestNumber;
@@ -11894,7 +12320,9 @@ async function handleCompanyMetricApiRoute(ctx, input) {
11894
12320
  recorded: recordedMetric.recorded,
11895
12321
  companyId,
11896
12322
  metric: "pull_request_created",
11897
- ...linkedPaperclipIssueId ? { paperclipIssueId: linkedPaperclipIssueId } : {}
12323
+ ...linkedPaperclipIssueId ? { paperclipIssueId: linkedPaperclipIssueId } : {},
12324
+ ...linkedFollowThroughAssigneeAgentId ? { followThroughAssigneeAgentId: linkedFollowThroughAssigneeAgentId } : {},
12325
+ ...linkedFollowThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt: linkedFollowThroughAssigneeUpdatedAt } : {}
11898
12326
  }
11899
12327
  };
11900
12328
  }
@@ -14261,6 +14689,11 @@ async function createProjectPullRequestPaperclipIssue(ctx, input) {
14261
14689
  throw new Error("This Paperclip runtime does not expose plugin issue creation yet.");
14262
14690
  }
14263
14691
  const scope = await requireProjectPullRequestScope(ctx, input);
14692
+ const followThroughAssigneeAgentId = await validateFollowThroughAssigneeAgentId(
14693
+ ctx,
14694
+ scope.companyId,
14695
+ input.followThroughAssigneeAgentId
14696
+ );
14264
14697
  const octokit = await createGitHubToolOctokit(ctx, scope.companyId);
14265
14698
  const pullRequestResponse = await octokit.rest.pulls.get({
14266
14699
  owner: scope.repository.owner,
@@ -14272,59 +14705,111 @@ async function createProjectPullRequestPaperclipIssue(ctx, input) {
14272
14705
  });
14273
14706
  const pullRequest = pullRequestResponse.data;
14274
14707
  const pullRequestUrl = pullRequest.html_url;
14275
- const existingLinks = await listGitHubPullRequestLinkRecords(ctx, {
14276
- externalId: pullRequestUrl
14708
+ const pullRequestState = getPullRequestApiState({
14709
+ state: pullRequest.state,
14710
+ merged: pullRequest.merged
14711
+ }) === "open" ? "open" : "closed";
14712
+ const pullRequestReferenceKey = buildGitHubPullRequestReferenceKey({
14713
+ repositoryUrl: scope.repository.url,
14714
+ number: pullRequestNumber
14277
14715
  });
14278
- const existingLink = existingLinks.find(
14279
- (record) => record.data.githubPullRequestNumber === pullRequestNumber && record.data.repositoryUrl === scope.repository.url && (!record.data.companyId || record.data.companyId === scope.companyId) && (!record.data.paperclipProjectId || record.data.paperclipProjectId === scope.projectId)
14280
- );
14281
- const existingIssue = existingLink ? await ctx.issues.get(existingLink.paperclipIssueId, scope.companyId) : null;
14282
- if (existingLink && existingIssue) {
14283
- return {
14284
- paperclipIssueId: existingIssue.id,
14285
- ...existingIssue.identifier ? { paperclipIssueKey: existingIssue.identifier } : {},
14286
- alreadyLinked: true
14716
+ const creationLockKey = `hosted-create:${scope.companyId}:${scope.projectId}:${pullRequestReferenceKey}`;
14717
+ return withPullRequestLinkMutationLock(creationLockKey, async () => {
14718
+ const sortMatchingLinks = (records) => records.filter(
14719
+ (record) => record.data.githubPullRequestNumber === pullRequestNumber && buildGitHubPullRequestReferenceKey({
14720
+ repositoryUrl: record.data.repositoryUrl,
14721
+ number: record.data.githubPullRequestNumber
14722
+ }) === pullRequestReferenceKey
14723
+ ).sort(
14724
+ (left, right) => left.paperclipIssueId.localeCompare(right.paperclipIssueId) || (left.externalId ?? "").localeCompare(right.externalId ?? "")
14725
+ );
14726
+ const findReusableLinkedIssue = async (records) => {
14727
+ for (const link of sortMatchingLinks(records)) {
14728
+ const issue = await ctx.issues.get(link.paperclipIssueId, scope.companyId);
14729
+ if (issue?.companyId === scope.companyId && issue.projectId === scope.projectId) {
14730
+ return { link, issue };
14731
+ }
14732
+ }
14733
+ return null;
14287
14734
  };
14288
- }
14289
- const requestedTitle = typeof input.title === "string" && input.title.trim() ? input.title.trim() : pullRequest.title.trim();
14290
- const createdIssue = await ensurePaperclipIssueStandardWorkMode(
14291
- ctx,
14292
- await ctx.issues.create({
14293
- companyId: scope.companyId,
14294
- projectId: scope.projectId,
14295
- title: requestedTitle,
14296
- status: "todo",
14297
- originKind: GITHUB_PULL_REQUEST_ORIGIN_KIND,
14298
- originId: pullRequestUrl,
14299
- description: buildPaperclipIssueDescriptionFromPullRequest({
14300
- repository: scope.repository,
14735
+ const exactLinks = await listGitHubPullRequestLinkRecords(ctx, {
14736
+ externalId: pullRequestUrl
14737
+ });
14738
+ const linkedMatch = await findReusableLinkedIssue(exactLinks) ?? await findReusableLinkedIssue(await listGitHubPullRequestLinkRecords(ctx));
14739
+ const existingLink = linkedMatch?.link ?? null;
14740
+ const existingIssue = linkedMatch?.issue ?? null;
14741
+ const recoveredOriginIssue = existingIssue ? null : (await listPaperclipIssuesForProject(ctx, scope.companyId, scope.projectId)).find((issue) => {
14742
+ const originLink = resolvePaperclipIssueOriginGitHubPullRequestLink(issue);
14743
+ if (!originLink) {
14744
+ return false;
14745
+ }
14746
+ return buildGitHubPullRequestReferenceKey({
14747
+ repositoryUrl: originLink.repositoryUrl,
14748
+ number: originLink.githubPullRequestNumber
14749
+ }) === pullRequestReferenceKey;
14750
+ }) ?? null;
14751
+ const reusableIssue = existingIssue ?? recoveredOriginIssue;
14752
+ if (reusableIssue) {
14753
+ const persistedLink2 = await upsertGitHubPullRequestLinkRecord(ctx, {
14754
+ companyId: scope.companyId,
14755
+ projectId: scope.projectId,
14756
+ issueId: reusableIssue.id,
14757
+ repositoryUrl: scope.repository.url,
14301
14758
  pullRequestNumber,
14302
14759
  pullRequestUrl,
14303
- body: pullRequest.body
14304
- })
14305
- }),
14306
- scope.companyId
14307
- );
14308
- const resolvedIssue = await ctx.issues.get(createdIssue.id, scope.companyId) ?? createdIssue;
14309
- await upsertGitHubPullRequestLinkRecord(ctx, {
14310
- companyId: scope.companyId,
14311
- projectId: scope.projectId,
14312
- issueId: resolvedIssue.id,
14313
- repositoryUrl: scope.repository.url,
14314
- pullRequestNumber,
14315
- pullRequestUrl,
14316
- pullRequestTitle: pullRequest.title,
14317
- pullRequestState: getPullRequestApiState({
14318
- state: pullRequest.state,
14319
- merged: pullRequest.merged
14320
- }) === "open" ? "open" : "closed"
14760
+ pullRequestTitle: pullRequest.title,
14761
+ pullRequestState,
14762
+ followThroughAssigneeAgentId
14763
+ });
14764
+ invalidateProjectPullRequestCaches(scope);
14765
+ return {
14766
+ paperclipIssueId: reusableIssue.id,
14767
+ ...reusableIssue.identifier ? { paperclipIssueKey: reusableIssue.identifier } : {},
14768
+ ...persistedLink2.followThroughAssigneeAgentId ? { followThroughAssigneeAgentId: persistedLink2.followThroughAssigneeAgentId } : {},
14769
+ ...persistedLink2.followThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt: persistedLink2.followThroughAssigneeUpdatedAt } : {},
14770
+ alreadyLinked: Boolean(existingLink && existingIssue)
14771
+ };
14772
+ }
14773
+ const requestedTitle = typeof input.title === "string" && input.title.trim() ? input.title.trim() : pullRequest.title.trim();
14774
+ const createdIssue = await ensurePaperclipIssueStandardWorkMode(
14775
+ ctx,
14776
+ await ctx.issues.create({
14777
+ companyId: scope.companyId,
14778
+ projectId: scope.projectId,
14779
+ title: requestedTitle,
14780
+ status: "todo",
14781
+ originKind: GITHUB_PULL_REQUEST_ORIGIN_KIND,
14782
+ originId: pullRequestUrl,
14783
+ description: buildPaperclipIssueDescriptionFromPullRequest({
14784
+ repository: scope.repository,
14785
+ pullRequestNumber,
14786
+ pullRequestUrl,
14787
+ body: pullRequest.body
14788
+ })
14789
+ }),
14790
+ scope.companyId
14791
+ );
14792
+ const resolvedIssue = await ctx.issues.get(createdIssue.id, scope.companyId) ?? createdIssue;
14793
+ const persistedLink = await upsertGitHubPullRequestLinkRecord(ctx, {
14794
+ companyId: scope.companyId,
14795
+ projectId: scope.projectId,
14796
+ issueId: resolvedIssue.id,
14797
+ repositoryUrl: scope.repository.url,
14798
+ pullRequestNumber,
14799
+ pullRequestUrl,
14800
+ pullRequestTitle: pullRequest.title,
14801
+ pullRequestState,
14802
+ followThroughAssigneeAgentId
14803
+ });
14804
+ invalidateProjectPullRequestCaches(scope);
14805
+ return {
14806
+ paperclipIssueId: resolvedIssue.id,
14807
+ ...resolvedIssue.identifier ? { paperclipIssueKey: resolvedIssue.identifier } : {},
14808
+ ...persistedLink.followThroughAssigneeAgentId ? { followThroughAssigneeAgentId: persistedLink.followThroughAssigneeAgentId } : {},
14809
+ ...persistedLink.followThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt: persistedLink.followThroughAssigneeUpdatedAt } : {},
14810
+ alreadyLinked: false
14811
+ };
14321
14812
  });
14322
- invalidateProjectPullRequestCaches(scope);
14323
- return {
14324
- paperclipIssueId: resolvedIssue.id,
14325
- ...resolvedIssue.identifier ? { paperclipIssueKey: resolvedIssue.identifier } : {},
14326
- alreadyLinked: false
14327
- };
14328
14813
  }
14329
14814
  async function refreshProjectPullRequests(ctx, input) {
14330
14815
  const scope = await requireProjectPullRequestScope(ctx, input);
@@ -16355,7 +16840,33 @@ function registerGitHubAgentTools(ctx) {
16355
16840
  getGitHubAgentToolDeclaration("update_issue"),
16356
16841
  async (params, runCtx) => executeTrackedGitHubMutation(ctx, "update_issue", params, runCtx, async () => {
16357
16842
  const input = getToolInputRecord(params);
16843
+ const state = input.state === "open" || input.state === "closed" ? input.state : void 0;
16844
+ const stateReason = input.stateReason === "completed" || input.stateReason === "not_planned" || input.stateReason === "duplicate" || input.stateReason === "reopened" ? input.stateReason : void 0;
16845
+ const stateReasonRequested = Object.prototype.hasOwnProperty.call(input, "stateReason");
16846
+ const duplicateIssueNumberRequested = Object.prototype.hasOwnProperty.call(input, "duplicateIssueNumber");
16847
+ const duplicateIssueNumber = duplicateIssueNumberRequested ? normalizeToolPositiveInteger(input.duplicateIssueNumber) : void 0;
16848
+ if (stateReasonRequested && !stateReason) {
16849
+ throw new Error("stateReason must be completed, not_planned, duplicate, or reopened.");
16850
+ }
16851
+ if (stateReason && !state) {
16852
+ throw new Error("stateReason requires state.");
16853
+ }
16854
+ if (stateReason === "reopened" && state !== "open") {
16855
+ throw new Error("stateReason reopened requires state=open.");
16856
+ }
16857
+ if (stateReason && stateReason !== "reopened" && state !== "closed") {
16858
+ throw new Error(`stateReason ${stateReason} requires state=closed.`);
16859
+ }
16860
+ if (stateReason === "duplicate" && duplicateIssueNumber === void 0) {
16861
+ throw new Error("stateReason duplicate requires duplicateIssueNumber.");
16862
+ }
16863
+ if (duplicateIssueNumberRequested && stateReason !== "duplicate") {
16864
+ throw new Error("duplicateIssueNumber requires stateReason=duplicate.");
16865
+ }
16358
16866
  const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
16867
+ if (duplicateIssueNumber === target.issueNumber) {
16868
+ throw new Error("An issue cannot be marked as a duplicate of itself.");
16869
+ }
16359
16870
  const octokit = await createAgentToolOctokit(runCtx, "update_issue", target.repository);
16360
16871
  const currentResponse = await octokit.rest.issues.get({
16361
16872
  owner: target.repository.owner,
@@ -16381,11 +16892,30 @@ function registerGitHubAgentTools(ctx) {
16381
16892
  const title = Object.prototype.hasOwnProperty.call(input, "title") && typeof input.title === "string" ? input.title : void 0;
16382
16893
  const llmModel = normalizeOptionalToolString(input.llmModel);
16383
16894
  const body = Object.prototype.hasOwnProperty.call(input, "body") && typeof input.body === "string" ? appendOptionalAiAuthorshipFooter(input.body, "issue description", llmModel) : void 0;
16384
- const state = input.state === "open" || input.state === "closed" ? input.state : void 0;
16385
16895
  const milestoneNumber = Object.prototype.hasOwnProperty.call(input, "milestoneNumber") ? input.milestoneNumber === null ? null : normalizeToolPositiveInteger(input.milestoneNumber) : void 0;
16386
16896
  const milestoneRequested = Object.prototype.hasOwnProperty.call(input, "milestoneNumber");
16387
16897
  const currentMilestoneNumber = currentIssue.milestone?.number ?? null;
16898
+ const currentStateReason = normalizeGitHubIssueStateReason(currentIssue.state_reason);
16899
+ if (stateReason && state === currentIssue.state && state === "closed" && stateReason !== currentStateReason) {
16900
+ throw new Error(
16901
+ `GitHub only applies stateReason when state changes; reopen issue #${target.issueNumber} before closing it as ${stateReason}.`
16902
+ );
16903
+ }
16904
+ if (stateReason === "duplicate" && state === currentIssue.state && currentStateReason === "duplicate") {
16905
+ throw new Error(
16906
+ `GitHub does not expose the current canonical duplicate target; reopen issue #${target.issueNumber} before marking it as a duplicate again.`
16907
+ );
16908
+ }
16909
+ const effectiveStateReason = state === currentIssue.state ? currentStateReason : stateReason;
16388
16910
  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);
16911
+ const duplicateIssueId = hasChanges && stateReason === "duplicate" && duplicateIssueNumber !== void 0 ? (await octokit.rest.issues.get({
16912
+ owner: target.repository.owner,
16913
+ repo: target.repository.repo,
16914
+ issue_number: duplicateIssueNumber,
16915
+ headers: {
16916
+ "X-GitHub-Api-Version": GITHUB_API_VERSION
16917
+ }
16918
+ })).data.id : void 0;
16389
16919
  const updatedResponse = hasChanges ? await octokit.rest.issues.update({
16390
16920
  owner: target.repository.owner,
16391
16921
  repo: target.repository.repo,
@@ -16393,6 +16923,8 @@ function registerGitHubAgentTools(ctx) {
16393
16923
  ...title !== void 0 ? { title } : {},
16394
16924
  ...body !== void 0 ? { body } : {},
16395
16925
  ...state ? { state } : {},
16926
+ ...stateReason ? { state_reason: stateReason } : {},
16927
+ ...duplicateIssueId !== void 0 ? { duplicate_issue_id: duplicateIssueId } : {},
16396
16928
  ...milestoneRequested ? { milestone: milestoneNumber } : {},
16397
16929
  labels: nextLabels,
16398
16930
  assignees: nextAssignees,
@@ -16411,7 +16943,7 @@ function registerGitHubAgentTools(ctx) {
16411
16943
  body: updatedIssue.body,
16412
16944
  url: updatedIssue.htmlUrl,
16413
16945
  state: updatedIssue.state,
16414
- stateReason: updatedIssue.stateReason,
16946
+ stateReason: updatedIssue.stateReason ?? effectiveStateReason,
16415
16947
  labels: normalizeGitHubIssueLabels(updatedResponse.data.labels),
16416
16948
  assignees: (updatedResponse.data.assignees ?? []).map((assignee) => assignee?.login ?? "").filter(Boolean),
16417
16949
  milestone: updatedResponse.data.milestone ? {
@@ -16537,6 +17069,11 @@ function registerGitHubAgentTools(ctx) {
16537
17069
  if (!issue) {
16538
17070
  throw new Error("Paperclip issue was not found.");
16539
17071
  }
17072
+ const followThroughAssigneeAgentId = await validateFollowThroughAssigneeAgentId(
17073
+ ctx,
17074
+ runCtx.companyId,
17075
+ input.followThroughAssigneeAgentId
17076
+ );
16540
17077
  const issueProjectId = normalizeOptionalToolString(issue.projectId);
16541
17078
  if (!issueProjectId || issueProjectId !== runCtx.projectId) {
16542
17079
  throw new Error("The selected Paperclip issue does not belong to the current tool run project.");
@@ -16630,9 +17167,11 @@ function registerGitHubAgentTools(ctx) {
16630
17167
  }
16631
17168
  pullRequestData = existingPullRequest;
16632
17169
  }
17170
+ let persistedFollowThroughAssigneeAgentId = followThroughAssigneeAgentId ?? void 0;
17171
+ let persistedFollowThroughAssigneeUpdatedAt;
16633
17172
  if (paperclipIssueId) {
16634
17173
  const pullRequestUrl = normalizeGitHubPullRequestHtmlUrl(pullRequestData.html_url) ?? `${repository.url}/pull/${pullRequestData.number}`;
16635
- await upsertGitHubPullRequestLinkRecord(ctx, {
17174
+ const persistedLink = await upsertGitHubPullRequestLinkRecord(ctx, {
16636
17175
  companyId: runCtx.companyId,
16637
17176
  projectId: issueProjectId,
16638
17177
  issueId: paperclipIssueId,
@@ -16643,8 +17182,11 @@ function registerGitHubAgentTools(ctx) {
16643
17182
  pullRequestState: getGitHubPullRequestStateForLink({
16644
17183
  state: pullRequestData.state,
16645
17184
  merged: false
16646
- })
17185
+ }),
17186
+ followThroughAssigneeAgentId
16647
17187
  });
17188
+ persistedFollowThroughAssigneeAgentId = persistedLink.followThroughAssigneeAgentId;
17189
+ persistedFollowThroughAssigneeUpdatedAt = persistedLink.followThroughAssigneeUpdatedAt;
16648
17190
  invalidateProjectPullRequestCaches({
16649
17191
  companyId: runCtx.companyId,
16650
17192
  projectId: issueProjectId,
@@ -16673,6 +17215,10 @@ function registerGitHubAgentTools(ctx) {
16673
17215
  commitSha: publishedBranch.commitSha,
16674
17216
  remoteRef: publishedBranch.remoteRef
16675
17217
  },
17218
+ ...persistedFollowThroughAssigneeAgentId ? {
17219
+ followThroughAssigneeAgentId: persistedFollowThroughAssigneeAgentId,
17220
+ ...persistedFollowThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt: persistedFollowThroughAssigneeUpdatedAt } : {}
17221
+ } : {},
16676
17222
  pullRequest: {
16677
17223
  number: pullRequestData.number,
16678
17224
  title: pullRequestData.title,
@@ -17206,7 +17752,8 @@ function registerGitHubAgentTools(ctx) {
17206
17752
  repositoryUrl: normalizeOptionalToolString(input.repository),
17207
17753
  pullRequestNumber: input.pullRequestNumber,
17208
17754
  pullRequestUrl: input.pullRequestUrl,
17209
- allowUnmapped: true
17755
+ allowUnmapped: true,
17756
+ followThroughAssigneeAgentId: input.followThroughAssigneeAgentId
17210
17757
  });
17211
17758
  const itemLabel = kind === "issue" ? `issue #${normalizeToolPositiveInteger(linkResult.githubIssueNumber) ?? ""}`.trim() : `pull request #${normalizeToolPositiveInteger(linkResult.githubPullRequestNumber) ?? ""}`.trim();
17212
17759
  return buildToolSuccessResult(
@@ -17241,6 +17788,7 @@ function shouldStartWorkerHost(moduleUrl, entry = process.argv[1]) {
17241
17788
  var __testing = {
17242
17789
  buildDirectPullRequestActionFingerprint,
17243
17790
  buildRemoteActionFingerprint,
17791
+ canReservePendingWake,
17244
17792
  canonicalizeGitHubPullRequestCommentCounts,
17245
17793
  buildSyncFallbackExecutionStatePatch,
17246
17794
  createGitHubToolOctokit,
@@ -17248,17 +17796,24 @@ var __testing = {
17248
17796
  hasUnresolvedPaperclipIssueBlocker,
17249
17797
  isHealthyMaintainerWaitTransition,
17250
17798
  isPaperclipIssuePatchApplied,
17799
+ listTrustedNewLinkedPullRequestCommentSources,
17251
17800
  normalizePaperclipIssueAssigneePrincipal,
17252
17801
  normalizeImportRegistry,
17253
17802
  normalizeRemoteActionRegistry,
17254
17803
  persistIssueInteractionEvent,
17255
17804
  trackedMutationOutcome,
17805
+ selectHighestPriorityEffectivePullRequestGate,
17806
+ selectEffectiveDirectPullRequestGate,
17807
+ selectEffectiveIssueLinkedPullRequestAction,
17808
+ selectEffectiveIssueLinkedPullRequestGate,
17256
17809
  resolvePaperclipApiAuthTokens,
17257
17810
  resolveGithubToken,
17811
+ resolvePaperclipIssueStatus,
17258
17812
  resolvePaperclipPullRequestIssueStatus,
17259
17813
  resolveSyncTransitionAssignee,
17260
17814
  resolveTrustedWorkspacePath,
17261
17815
  updatePaperclipIssueState,
17816
+ upsertGitHubPullRequestLinkRecord,
17262
17817
  wakePaperclipIssueAssignee,
17263
17818
  setCreatePullRequestBranchPublisher(publisher) {
17264
17819
  createPullRequestBranchPublisher = publisher ?? publishLocalBranchForPullRequest;
@@ -17380,7 +17935,8 @@ var plugin = definePlugin({
17380
17935
  repositoryUrl: normalizeOptionalString2(record.repository),
17381
17936
  pullRequestNumber: record.pullRequestNumber,
17382
17937
  pullRequestUrl: record.pullRequestUrl,
17383
- requireUnlinked: true
17938
+ requireUnlinked: true,
17939
+ followThroughAssigneeAgentId: record.followThroughAssigneeAgentId
17384
17940
  });
17385
17941
  });
17386
17942
  ctx.actions.register("issue.unlinkGitHubItem", async (input, actionContext) => {