paperclip-github-plugin 0.15.6 → 0.16.0

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
  }
@@ -5310,6 +5344,21 @@ function recordCompanyActivityMetricEvent(state, params) {
5310
5344
  ...eventKey ? { eventKey } : {}
5311
5345
  };
5312
5346
  }
5347
+ function normalizeSelectedPullRequestGate(value) {
5348
+ if (!value || typeof value !== "object") return void 0;
5349
+ const record = value;
5350
+ const repositoryUrl = normalizeOptionalString2(record.repositoryUrl);
5351
+ const number = typeof record.number === "number" && Number.isInteger(record.number) && record.number > 0 ? record.number : void 0;
5352
+ if (!repositoryUrl || !number) return void 0;
5353
+ try {
5354
+ return {
5355
+ repositoryUrl: getNormalizedMappingRepositoryUrl({ repositoryUrl }).toLowerCase(),
5356
+ number
5357
+ };
5358
+ } catch {
5359
+ return void 0;
5360
+ }
5361
+ }
5313
5362
  function normalizeImportRegistry(value) {
5314
5363
  if (!Array.isArray(value)) {
5315
5364
  return [];
@@ -5335,7 +5384,9 @@ function normalizeImportRegistry(value) {
5335
5384
  record.linkedPullRequestCommentCounts
5336
5385
  );
5337
5386
  const remoteActionFingerprint = typeof record.remoteActionFingerprint === "string" && /^[a-f0-9]{64}$/.test(record.remoteActionFingerprint) ? record.remoteActionFingerprint : void 0;
5387
+ const selectedPullRequestGate = normalizeSelectedPullRequestGate(record.selectedPullRequestGate);
5338
5388
  const pendingRemoteActionWake = normalizePendingRemoteActionWake(record.pendingRemoteActionWake);
5389
+ const activationPending = record.activationPending === true;
5339
5390
  if (!mappingId || Number.isNaN(githubIssueId) || !paperclipIssueId || !importedAt) {
5340
5391
  return null;
5341
5392
  }
@@ -5352,7 +5403,9 @@ function normalizeImportRegistry(value) {
5352
5403
  ...lastSeenGitHubState ? { lastSeenGitHubState } : {},
5353
5404
  ...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : {},
5354
5405
  ...remoteActionFingerprint ? { remoteActionFingerprint } : {},
5355
- ...pendingRemoteActionWake ? { pendingRemoteActionWake } : {}
5406
+ ...selectedPullRequestGate ? { selectedPullRequestGate } : {},
5407
+ ...pendingRemoteActionWake ? { pendingRemoteActionWake } : {},
5408
+ ...activationPending ? { activationPending: true } : {}
5356
5409
  };
5357
5410
  }).filter((entry) => entry !== null);
5358
5411
  }
@@ -5388,12 +5441,14 @@ function normalizeRemoteActionRegistry(value) {
5388
5441
  const linkedPullRequestCommentCounts = normalizeGitHubPullRequestCommentCountRecords(
5389
5442
  record.linkedPullRequestCommentCounts
5390
5443
  );
5444
+ const selectedPullRequestGate = normalizeSelectedPullRequestGate(record.selectedPullRequestGate);
5391
5445
  const previous = recordsByKey.get(key);
5392
5446
  recordsByKey.set(key, {
5393
5447
  key,
5394
5448
  ...fingerprint ? { fingerprint } : previous?.fingerprint ? { fingerprint: previous.fingerprint } : {},
5395
5449
  ...pendingWake ? { pendingWake } : previous?.pendingWake ? { pendingWake: previous.pendingWake } : {},
5396
- ...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : previous?.linkedPullRequestCommentCounts ? { linkedPullRequestCommentCounts: previous.linkedPullRequestCommentCounts } : {}
5450
+ ...linkedPullRequestCommentCounts.length > 0 ? { linkedPullRequestCommentCounts } : previous?.linkedPullRequestCommentCounts ? { linkedPullRequestCommentCounts: previous.linkedPullRequestCommentCounts } : {},
5451
+ ...selectedPullRequestGate ? { selectedPullRequestGate } : previous?.selectedPullRequestGate ? { selectedPullRequestGate: previous.selectedPullRequestGate } : {}
5397
5452
  });
5398
5453
  }
5399
5454
  const records = [...recordsByKey.values()];
@@ -5502,7 +5557,7 @@ function buildTrackedPullRequestIssueProgressKey(mapping, record) {
5502
5557
  repositoryUrl: record.data.repositoryUrl
5503
5558
  })}`;
5504
5559
  }
5505
- function buildImportedIssueRecord(mapping, issue, paperclipIssueId, importedAt) {
5560
+ function buildImportedIssueRecord(mapping, issue, paperclipIssueId, importedAt, activationPending = false) {
5506
5561
  return {
5507
5562
  mappingId: mapping.id,
5508
5563
  githubIssueId: issue.id,
@@ -5514,7 +5569,8 @@ function buildImportedIssueRecord(mapping, issue, paperclipIssueId, importedAt)
5514
5569
  linkedPullRequestCommentCounts: [],
5515
5570
  repositoryUrl: getNormalizedMappingRepositoryUrl(mapping),
5516
5571
  paperclipProjectId: mapping.paperclipProjectId,
5517
- companyId: mapping.companyId
5572
+ companyId: mapping.companyId,
5573
+ ...activationPending ? { activationPending: true } : {}
5518
5574
  };
5519
5575
  }
5520
5576
  function refreshImportedIssueRecordForMapping(record, mapping, issue) {
@@ -5968,6 +6024,119 @@ function resolvePaperclipStatusFromLinkedPullRequests(linkedPullRequests, option
5968
6024
  }
5969
6025
  return "in_progress";
5970
6026
  }
6027
+ function getEffectiveDirectPullRequestGatePriority(condition) {
6028
+ switch (condition) {
6029
+ case "conflict":
6030
+ return 0;
6031
+ case "ci_failed":
6032
+ return 1;
6033
+ case "review_actionable":
6034
+ return 2;
6035
+ case "action_required":
6036
+ return 3;
6037
+ case "trusted_comment":
6038
+ return 4;
6039
+ case "waiting":
6040
+ return 5;
6041
+ case "ready":
6042
+ return 6;
6043
+ }
6044
+ }
6045
+ function getEffectiveDirectPullRequestGateCondition(pullRequest, hasTrustedPullRequestComment) {
6046
+ const baseCondition = getEffectivePullRequestActionCondition(pullRequest);
6047
+ const remoteCondition = baseCondition === "conflict" || baseCondition === "ci_failed" || baseCondition === "review_actionable" ? baseCondition : isGitHubPullRequestActionRequiredForSync(pullRequest) ? "action_required" : baseCondition;
6048
+ return {
6049
+ condition: hasTrustedPullRequestComment && (remoteCondition === "ready" || remoteCondition === "waiting") ? "trusted_comment" : remoteCondition,
6050
+ remoteCondition
6051
+ };
6052
+ }
6053
+ function selectHighestPriorityEffectivePullRequestGate(gates, preferredGate) {
6054
+ const preferredGateKey = preferredGate ? buildGitHubPullRequestReferenceKey(preferredGate) : void 0;
6055
+ return [...gates].sort(
6056
+ (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
6057
+ )[0];
6058
+ }
6059
+ function buildTrustedCommentKindsByPullRequest(trustedCommentSources) {
6060
+ const kindsByPullRequest = /* @__PURE__ */ new Map();
6061
+ for (const source of trustedCommentSources) {
6062
+ const key = buildGitHubPullRequestReferenceKey(source);
6063
+ const kinds = kindsByPullRequest.get(key) ?? /* @__PURE__ */ new Set();
6064
+ kinds.add(source.kind);
6065
+ kindsByPullRequest.set(key, kinds);
6066
+ }
6067
+ return new Map([...kindsByPullRequest].map(([key, kinds]) => [key, [...kinds].sort()]));
6068
+ }
6069
+ function selectEffectiveDirectPullRequestGate(pullRequests, trustedCommentSources, preferredGate) {
6070
+ const trustedCommentKindsByPullRequest = buildTrustedCommentKindsByPullRequest(trustedCommentSources);
6071
+ return selectHighestPriorityEffectivePullRequestGate(pullRequests.filter(
6072
+ (entry) => entry.lifecycleState === "open" && Boolean(entry.pullRequest)
6073
+ ).map((entry) => {
6074
+ const repositoryUrl = getNormalizedMappingRepositoryUrl({ repositoryUrl: entry.repository.url }).toLowerCase();
6075
+ const number = entry.pullRequestLink.data.githubPullRequestNumber;
6076
+ const trustedCommentKinds = trustedCommentKindsByPullRequest.get(
6077
+ buildGitHubPullRequestReferenceKey({ repositoryUrl, number })
6078
+ ) ?? [];
6079
+ const { condition, remoteCondition } = getEffectiveDirectPullRequestGateCondition(
6080
+ entry.pullRequest,
6081
+ trustedCommentKinds.length > 0
6082
+ );
6083
+ return {
6084
+ repositoryUrl,
6085
+ number,
6086
+ headSha: entry.pullRequest.headSha ?? null,
6087
+ condition,
6088
+ remoteCondition,
6089
+ trustedCommentKinds,
6090
+ ownerCandidate: entry.pullRequestLink.data.followThroughAssigneeAgentId,
6091
+ pullRequest: entry.pullRequest
6092
+ };
6093
+ }), preferredGate);
6094
+ }
6095
+ function selectEffectiveIssueLinkedPullRequestGate(pullRequests, trustedCommentSources, hasTrustedIssueComment, pullRequestLinks = [], preferredGate) {
6096
+ const trustedCommentKindsByPullRequest = buildTrustedCommentKindsByPullRequest(trustedCommentSources);
6097
+ const ownerByPullRequest = new Map(pullRequestLinks.map((link) => [
6098
+ buildGitHubPullRequestReferenceKey({
6099
+ repositoryUrl: link.data.repositoryUrl,
6100
+ number: link.data.githubPullRequestNumber
6101
+ }),
6102
+ link.data.followThroughAssigneeAgentId
6103
+ ]));
6104
+ return selectHighestPriorityEffectivePullRequestGate(pullRequests.map((pullRequest) => {
6105
+ const repositoryUrl = getNormalizedMappingRepositoryUrl({ repositoryUrl: pullRequest.repositoryUrl }).toLowerCase();
6106
+ const number = pullRequest.number;
6107
+ const key = buildGitHubPullRequestReferenceKey({ repositoryUrl, number });
6108
+ const trustedCommentKinds = trustedCommentKindsByPullRequest.get(key) ?? [];
6109
+ const { condition, remoteCondition } = getEffectiveDirectPullRequestGateCondition(
6110
+ pullRequest,
6111
+ hasTrustedIssueComment || trustedCommentKinds.length > 0
6112
+ );
6113
+ return {
6114
+ repositoryUrl,
6115
+ number,
6116
+ headSha: pullRequest.headSha ?? null,
6117
+ condition,
6118
+ remoteCondition,
6119
+ trustedCommentKinds,
6120
+ ownerCandidate: ownerByPullRequest.get(key),
6121
+ pullRequest
6122
+ };
6123
+ }), preferredGate);
6124
+ }
6125
+ function selectEffectiveIssueLinkedPullRequestAction(pullRequests, trustedCommentSources, hasTrustedIssueComment) {
6126
+ return selectEffectiveIssueLinkedPullRequestGate(
6127
+ pullRequests,
6128
+ trustedCommentSources,
6129
+ hasTrustedIssueComment
6130
+ )?.pullRequest;
6131
+ }
6132
+ function isActionableDirectPullRequestGate(gate) {
6133
+ return Boolean(gate && gate.condition !== "ready" && gate.condition !== "waiting");
6134
+ }
6135
+ async function resolveValidFollowThroughAssigneeAgentId(ctx, companyId, candidate) {
6136
+ if (!candidate) return void 0;
6137
+ const agent = await ctx.agents.get(candidate, companyId);
6138
+ return agent?.companyId === companyId ? candidate : void 0;
6139
+ }
5971
6140
  function formatPaperclipIssueStatus(status) {
5972
6141
  switch (status) {
5973
6142
  case "backlog":
@@ -6274,14 +6443,20 @@ function resolvePaperclipIssueReviewAssignee(syncContext, advancedSettings) {
6274
6443
  }
6275
6444
  return null;
6276
6445
  }
6277
- function resolvePaperclipIssueExecutorAssignee(syncContext, advancedSettings) {
6446
+ function resolvePaperclipIssueExecutorAssignee(syncContext, advancedSettings, followThroughAssigneeAgentId) {
6278
6447
  const returnAssignee = syncContext.executionState?.returnAssignee;
6279
- if (returnAssignee) {
6448
+ if (returnAssignee && (syncContext.executionState?.status === "pending" || syncContext.executionState?.status === "changes_requested")) {
6280
6449
  return {
6281
6450
  principal: returnAssignee,
6282
6451
  role: "executor"
6283
6452
  };
6284
6453
  }
6454
+ if (followThroughAssigneeAgentId) {
6455
+ return {
6456
+ principal: { kind: "agent", id: followThroughAssigneeAgentId },
6457
+ role: "executor"
6458
+ };
6459
+ }
6285
6460
  const executorOverride = getConfiguredAdvancedAssigneePrincipal(advancedSettings, "executor");
6286
6461
  if (executorOverride) {
6287
6462
  return {
@@ -6299,7 +6474,7 @@ function resolvePaperclipIssueExecutorAssignee(syncContext, advancedSettings) {
6299
6474
  return null;
6300
6475
  }
6301
6476
  function resolveSyncTransitionAssignee(params) {
6302
- const { currentStatus, nextStatus, syncContext, advancedSettings } = params;
6477
+ const { currentStatus, nextStatus, syncContext, advancedSettings, followThroughAssigneeAgentId } = params;
6303
6478
  if (isHealthyMaintainerWaitTransition({ currentStatus, nextStatus, syncContext })) {
6304
6479
  return null;
6305
6480
  }
@@ -6307,7 +6482,11 @@ function resolveSyncTransitionAssignee(params) {
6307
6482
  return resolvePaperclipIssueReviewAssignee(syncContext, advancedSettings);
6308
6483
  }
6309
6484
  if (nextStatus === "todo" || nextStatus === "in_progress") {
6310
- return resolvePaperclipIssueExecutorAssignee(syncContext, advancedSettings);
6485
+ return resolvePaperclipIssueExecutorAssignee(
6486
+ syncContext,
6487
+ advancedSettings,
6488
+ followThroughAssigneeAgentId
6489
+ );
6311
6490
  }
6312
6491
  return null;
6313
6492
  }
@@ -6507,6 +6686,7 @@ function resolvePaperclipIssueStatus(params) {
6507
6686
  const {
6508
6687
  currentStatus,
6509
6688
  snapshot,
6689
+ effectiveGate,
6510
6690
  hasTrustedNewComment,
6511
6691
  wasImportedThisRun,
6512
6692
  defaultImportedStatus,
@@ -6519,16 +6699,28 @@ function resolvePaperclipIssueStatus(params) {
6519
6699
  if (currentStatus === "backlog" && !wasImportedThisRun) {
6520
6700
  return "backlog";
6521
6701
  }
6522
- if (hasTrustedNewComment) {
6702
+ if (hasTrustedNewComment && snapshot.linkedPullRequests.length === 0) {
6523
6703
  return hasExecutorHandoffTarget ? "in_progress" : "todo";
6524
6704
  }
6525
- if (snapshot.linkedPullRequests.length > 0) {
6526
- if (shouldPreserveBlockedExternalPullRequestWait({
6527
- currentStatus,
6528
- linkedPullRequests: snapshot.linkedPullRequests
6529
- })) {
6530
- return "blocked";
6705
+ if (effectiveGate) {
6706
+ if (effectiveGate.condition === "trusted_comment") {
6707
+ return hasExecutorHandoffTarget ? "in_progress" : "todo";
6531
6708
  }
6709
+ if (isActionableDirectPullRequestGate(effectiveGate)) {
6710
+ if (shouldPreserveBlockedExternalPullRequestWait({
6711
+ currentStatus,
6712
+ linkedPullRequests: [effectiveGate.pullRequest]
6713
+ })) {
6714
+ return "blocked";
6715
+ }
6716
+ return hasExecutorHandoffTarget ? "in_progress" : "todo";
6717
+ }
6718
+ if (effectiveGate.condition === "waiting") {
6719
+ return (currentStatus === "done" || currentStatus === "in_review") && isGitHubPullRequestTransientUnknownMergeabilityWait(effectiveGate.pullRequest) ? "in_review" : "in_progress";
6720
+ }
6721
+ return "in_review";
6722
+ }
6723
+ if (snapshot.linkedPullRequests.length > 0) {
6532
6724
  return resolvePaperclipStatusFromLinkedPullRequests(snapshot.linkedPullRequests, {
6533
6725
  preferInProgress: hasExecutorHandoffTarget,
6534
6726
  preserveTransientUnknownMergeabilityWait: currentStatus === "done" || currentStatus === "in_review"
@@ -6556,22 +6748,24 @@ function resolvePaperclipPullRequestIssueStatus(params) {
6556
6748
  });
6557
6749
  }
6558
6750
  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) {
6751
+ const { currentStatus, pullRequests, effectiveGate, hasExecutorHandoffTarget } = params;
6752
+ if (effectiveGate) {
6753
+ if (effectiveGate.condition === "trusted_comment") {
6563
6754
  return currentStatus === "backlog" ? "backlog" : hasExecutorHandoffTarget ? "in_progress" : "todo";
6564
6755
  }
6565
- if (shouldPreserveBlockedExternalPullRequestWait({
6566
- currentStatus,
6567
- linkedPullRequests: openPullRequests
6568
- })) {
6569
- return "blocked";
6756
+ if (isActionableDirectPullRequestGate(effectiveGate)) {
6757
+ if (shouldPreserveBlockedExternalPullRequestWait({
6758
+ currentStatus,
6759
+ linkedPullRequests: [effectiveGate.pullRequest]
6760
+ })) {
6761
+ return "blocked";
6762
+ }
6763
+ return hasExecutorHandoffTarget ? "in_progress" : "todo";
6570
6764
  }
6571
- return resolvePaperclipStatusFromLinkedPullRequests(openPullRequests, {
6572
- preferInProgress: hasExecutorHandoffTarget,
6573
- preserveTransientUnknownMergeabilityWait: currentStatus === "done" || currentStatus === "in_review"
6574
- });
6765
+ if (effectiveGate.condition === "waiting") {
6766
+ return (currentStatus === "done" || currentStatus === "in_review") && isGitHubPullRequestTransientUnknownMergeabilityWait(effectiveGate.pullRequest) ? "in_review" : "in_progress";
6767
+ }
6768
+ return "in_review";
6575
6769
  }
6576
6770
  return pullRequests.some((entry) => entry.lifecycleState === "merged") ? "done" : "cancelled";
6577
6771
  }
@@ -7249,10 +7443,11 @@ async function listGitHubPullRequestCommentCountRecords(octokit, linkedPullReque
7249
7443
  }
7250
7444
  return normalizeGitHubPullRequestCommentCountRecords(commentCounts);
7251
7445
  }
7252
- async function hasTrustedNewLinkedPullRequestComments(params) {
7446
+ async function listTrustedNewLinkedPullRequestCommentSources(params) {
7253
7447
  if ((params.currentCommentCounts?.length ?? 0) === 0 || (params.previousCommentCounts?.length ?? 0) === 0) {
7254
- return false;
7448
+ return [];
7255
7449
  }
7450
+ const sources = [];
7256
7451
  const previousCommentCountsByKey = new Map(
7257
7452
  (params.previousCommentCounts ?? []).map((record) => [buildGitHubPullRequestReferenceKey(record), record])
7258
7453
  );
@@ -7262,6 +7457,7 @@ async function hasTrustedNewLinkedPullRequestComments(params) {
7262
7457
  continue;
7263
7458
  }
7264
7459
  const pullRequestRepository = requireRepositoryReference(currentCommentCount.repositoryUrl);
7460
+ const repositoryUrl = getNormalizedMappingRepositoryUrl({ repositoryUrl: currentCommentCount.repositoryUrl });
7265
7461
  if (currentCommentCount.topLevelCommentCount > previousCommentCount.topLevelCommentCount) {
7266
7462
  const newTopLevelComments = await listNewGitHubIssueCommentsSinceCount(
7267
7463
  params.octokit,
@@ -7277,7 +7473,7 @@ async function hasTrustedNewLinkedPullRequestComments(params) {
7277
7473
  originalPosterLogin: params.originalPosterLogin,
7278
7474
  maintainerCache: params.maintainerCache
7279
7475
  })) {
7280
- return true;
7476
+ sources.push({ repositoryUrl, number: currentCommentCount.number, kind: "top_level" });
7281
7477
  }
7282
7478
  }
7283
7479
  if (currentCommentCount.reviewCommentCount > previousCommentCount.reviewCommentCount) {
@@ -7295,11 +7491,13 @@ async function hasTrustedNewLinkedPullRequestComments(params) {
7295
7491
  originalPosterLogin: params.originalPosterLogin,
7296
7492
  maintainerCache: params.maintainerCache
7297
7493
  })) {
7298
- return true;
7494
+ sources.push({ repositoryUrl, number: currentCommentCount.number, kind: "review" });
7299
7495
  }
7300
7496
  }
7301
7497
  }
7302
- return false;
7498
+ return sources.sort(
7499
+ (left, right) => buildGitHubPullRequestReferenceKey(left).localeCompare(buildGitHubPullRequestReferenceKey(right)) || left.kind.localeCompare(right.kind)
7500
+ );
7303
7501
  }
7304
7502
  async function isMaintainerAuthoredGitHubIssue(params) {
7305
7503
  const authorLogin = normalizeGitHubUserLogin(params.githubIssue.authorLogin);
@@ -7612,7 +7810,8 @@ async function listImportedPaperclipIssuesForMapping(ctx, mapping) {
7612
7810
  if (issue.projectId !== mapping.paperclipProjectId) {
7613
7811
  continue;
7614
7812
  }
7615
- const githubIssueUrl = extractImportedGitHubIssueUrlFromDescription(issue.description);
7813
+ const originLink = resolvePaperclipIssueOriginGitHubIssueLink(issue, mapping.companyId);
7814
+ const githubIssueUrl = originLink?.repositoryUrl === normalizedRepositoryUrl ? originLink.githubIssueUrl : extractImportedGitHubIssueUrlFromDescription(issue.description);
7616
7815
  if (!githubIssueUrl) {
7617
7816
  continue;
7618
7817
  }
@@ -7809,6 +8008,8 @@ function normalizeGitHubPullRequestLinkEntityData(value) {
7809
8008
  const githubPullRequestUrl = typeof record.githubPullRequestUrl === "string" && record.githubPullRequestUrl.trim() ? record.githubPullRequestUrl.trim() : void 0;
7810
8009
  const githubPullRequestState = record.githubPullRequestState === "closed" ? "closed" : record.githubPullRequestState === "open" ? "open" : void 0;
7811
8010
  const title = typeof record.title === "string" && record.title.trim() ? record.title.trim() : void 0;
8011
+ const followThroughAssigneeAgentId = normalizeOptionalString2(record.followThroughAssigneeAgentId);
8012
+ const followThroughAssigneeUpdatedAt = normalizeOptionalString2(record.followThroughAssigneeUpdatedAt);
7812
8013
  const syncedAt = typeof record.syncedAt === "string" && record.syncedAt.trim() ? record.syncedAt.trim() : void 0;
7813
8014
  if (!repositoryUrl || githubPullRequestNumber === void 0 || !githubPullRequestUrl || !githubPullRequestState || !syncedAt) {
7814
8015
  return null;
@@ -7821,6 +8022,8 @@ function normalizeGitHubPullRequestLinkEntityData(value) {
7821
8022
  githubPullRequestUrl,
7822
8023
  githubPullRequestState,
7823
8024
  ...title ? { title } : {},
8025
+ ...followThroughAssigneeAgentId ? { followThroughAssigneeAgentId } : {},
8026
+ ...followThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt } : {},
7824
8027
  syncedAt
7825
8028
  };
7826
8029
  }
@@ -7975,7 +8178,7 @@ function doesGitHubPullRequestLinkRecordMatchTarget(record, target) {
7975
8178
  case "project":
7976
8179
  return (!record.data.companyId || record.data.companyId === target.companyId) && (!record.data.paperclipProjectId || record.data.paperclipProjectId === target.projectId);
7977
8180
  case "issue":
7978
- return Boolean(target.issueId && record.paperclipIssueId === target.issueId);
8181
+ return Boolean(target.issueId && record.paperclipIssueId === target.issueId) && (!record.data.companyId || record.data.companyId === target.companyId);
7979
8182
  default:
7980
8183
  return true;
7981
8184
  }
@@ -8216,28 +8419,86 @@ async function upsertGitHubIssueLinkRecord(ctx, target, issueId, githubIssue, li
8216
8419
  data: record.data
8217
8420
  });
8218
8421
  }
8422
+ var pullRequestLinkMutationTails = /* @__PURE__ */ new Map();
8423
+ async function withPullRequestLinkMutationLock(key, mutation) {
8424
+ const previousTail = pullRequestLinkMutationTails.get(key) ?? Promise.resolve();
8425
+ let release;
8426
+ const currentMutation = new Promise((resolve3) => {
8427
+ release = resolve3;
8428
+ });
8429
+ const currentTail = previousTail.catch(() => void 0).then(() => currentMutation);
8430
+ pullRequestLinkMutationTails.set(key, currentTail);
8431
+ await previousTail.catch(() => void 0);
8432
+ try {
8433
+ return await mutation();
8434
+ } finally {
8435
+ release();
8436
+ if (pullRequestLinkMutationTails.get(key) === currentTail) {
8437
+ pullRequestLinkMutationTails.delete(key);
8438
+ }
8439
+ }
8440
+ }
8219
8441
  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: {
8442
+ const repositoryUrl = getNormalizedMappingRepositoryUrl({ repositoryUrl: params.repositoryUrl });
8443
+ const referenceKey = buildGitHubPullRequestReferenceKey({
8444
+ repositoryUrl,
8445
+ number: params.pullRequestNumber
8446
+ });
8447
+ const mutationKey = `${params.companyId}:${params.issueId}:${referenceKey}`;
8448
+ return withPullRequestLinkMutationLock(mutationKey, async () => {
8449
+ const findMatchingRecord = (records) => records.find(
8450
+ (record) => buildGitHubPullRequestReferenceKey({
8451
+ repositoryUrl: record.data.repositoryUrl,
8452
+ number: record.data.githubPullRequestNumber
8453
+ }) === referenceKey
8454
+ );
8455
+ const exactExternalIdMatch = findMatchingRecord(await listGitHubPullRequestLinkRecords(ctx, {
8456
+ paperclipIssueId: params.issueId,
8457
+ externalId: params.pullRequestUrl
8458
+ }));
8459
+ const existing = exactExternalIdMatch ?? findMatchingRecord(await listGitHubPullRequestLinkRecords(ctx, {
8460
+ paperclipIssueId: params.issueId
8461
+ }));
8462
+ const previousOwner = existing?.data.followThroughAssigneeAgentId;
8463
+ const nextOwner = params.followThroughAssigneeAgentId === void 0 ? previousOwner : params.followThroughAssigneeAgentId ?? void 0;
8464
+ const ownerChanged = params.followThroughAssigneeAgentId !== void 0 && previousOwner !== nextOwner;
8465
+ const data = {
8228
8466
  companyId: params.companyId,
8229
8467
  ...params.projectId ? { paperclipProjectId: params.projectId } : {},
8230
- repositoryUrl: getNormalizedMappingRepositoryUrl({
8231
- repositoryUrl: params.repositoryUrl
8232
- }),
8468
+ repositoryUrl,
8233
8469
  githubPullRequestNumber: params.pullRequestNumber,
8234
8470
  githubPullRequestUrl: params.pullRequestUrl,
8235
8471
  githubPullRequestState: params.pullRequestState,
8236
8472
  title: params.pullRequestTitle,
8473
+ ...nextOwner ? { followThroughAssigneeAgentId: nextOwner } : {},
8474
+ ...ownerChanged ? { followThroughAssigneeUpdatedAt: (/* @__PURE__ */ new Date()).toISOString() } : existing?.data.followThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt: existing.data.followThroughAssigneeUpdatedAt } : {},
8237
8475
  syncedAt: (/* @__PURE__ */ new Date()).toISOString()
8238
- }
8476
+ };
8477
+ await ctx.entities.upsert({
8478
+ entityType: PULL_REQUEST_LINK_ENTITY_TYPE,
8479
+ scopeKind: "issue",
8480
+ scopeId: params.issueId,
8481
+ externalId: existing?.externalId ?? params.pullRequestUrl,
8482
+ title: `GitHub pull request #${params.pullRequestNumber}`,
8483
+ status: params.pullRequestState,
8484
+ data
8485
+ });
8486
+ return data;
8239
8487
  });
8240
8488
  }
8489
+ async function validateFollowThroughAssigneeAgentId(ctx, companyId, value) {
8490
+ if (value === void 0) return void 0;
8491
+ if (value === null) return null;
8492
+ const agentId = normalizeOptionalString2(value);
8493
+ if (!agentId) {
8494
+ throw new Error("followThroughAssigneeAgentId must be a Paperclip agent id or null.");
8495
+ }
8496
+ const agent = await ctx.agents.get(agentId, companyId);
8497
+ if (!agent || agent.companyId !== companyId) {
8498
+ throw new Error("followThroughAssigneeAgentId must identify an agent in the same Paperclip company.");
8499
+ }
8500
+ return agentId;
8501
+ }
8241
8502
  function normalizeIssueGitHubLinkKind(value) {
8242
8503
  if (value === "issue" || value === "github_issue") {
8243
8504
  return "issue";
@@ -8514,6 +8775,11 @@ async function linkPaperclipIssueToGitHubPullRequest(ctx, params) {
8514
8775
  repositoryUrl: reference.repositoryUrl,
8515
8776
  allowUnmapped: params.allowUnmapped
8516
8777
  });
8778
+ const followThroughAssigneeAgentId = await validateFollowThroughAssigneeAgentId(
8779
+ ctx,
8780
+ companyId,
8781
+ params.followThroughAssigneeAgentId
8782
+ );
8517
8783
  const octokit = await createGitHubToolOctokit(ctx, companyId);
8518
8784
  const response = await octokit.rest.pulls.get({
8519
8785
  owner: scope.repository.owner,
@@ -8528,7 +8794,7 @@ async function linkPaperclipIssueToGitHubPullRequest(ctx, params) {
8528
8794
  state: response.data.state,
8529
8795
  merged: response.data.merged
8530
8796
  });
8531
- await upsertGitHubPullRequestLinkRecord(ctx, {
8797
+ const storedLink = await upsertGitHubPullRequestLinkRecord(ctx, {
8532
8798
  companyId,
8533
8799
  projectId: scope.mapping?.paperclipProjectId ?? scope.projectId,
8534
8800
  issueId,
@@ -8536,7 +8802,8 @@ async function linkPaperclipIssueToGitHubPullRequest(ctx, params) {
8536
8802
  pullRequestNumber: reference.pullRequestNumber,
8537
8803
  pullRequestUrl,
8538
8804
  pullRequestTitle: response.data.title || `Pull request #${reference.pullRequestNumber}`,
8539
- pullRequestState
8805
+ pullRequestState,
8806
+ followThroughAssigneeAgentId
8540
8807
  });
8541
8808
  await rememberExternalGitHubLinkCompany(ctx, companyId);
8542
8809
  const projectIdForCacheInvalidation = scope.mapping?.paperclipProjectId ?? scope.projectId;
@@ -8553,7 +8820,9 @@ async function linkPaperclipIssueToGitHubPullRequest(ctx, params) {
8553
8820
  repositoryUrl: scope.repository.url,
8554
8821
  githubPullRequestNumber: reference.pullRequestNumber,
8555
8822
  githubPullRequestUrl: pullRequestUrl,
8556
- githubPullRequestState: pullRequestState
8823
+ githubPullRequestState: pullRequestState,
8824
+ ...storedLink.followThroughAssigneeAgentId ? { followThroughAssigneeAgentId: storedLink.followThroughAssigneeAgentId } : {},
8825
+ ...storedLink.followThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt: storedLink.followThroughAssigneeUpdatedAt } : {}
8557
8826
  };
8558
8827
  }
8559
8828
  function invalidateGitHubLinkCachesForTarget(params) {
@@ -8818,16 +9087,16 @@ async function detectPaperclipBoardAccessRequirement(paperclipApiBaseUrl) {
8818
9087
  }
8819
9088
  async function wakePaperclipIssueAssignee(ctx, params) {
8820
9089
  if (!params.assigneeAgentId) {
8821
- return;
9090
+ return false;
8822
9091
  }
8823
9092
  if (ctx.issues && typeof ctx.issues.requestWakeup === "function" && params.companyId) {
8824
9093
  try {
8825
- await ctx.issues.requestWakeup(params.paperclipIssueId, params.companyId, {
9094
+ const result = await ctx.issues.requestWakeup(params.paperclipIssueId, params.companyId, {
8826
9095
  reason: params.reason,
8827
9096
  contextSource: `github-sync.${params.mutation}`,
8828
9097
  ...params.actionFingerprint ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId, params.actionFingerprint].join(":") } : params.mutation === "import" ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId].join(":") } : {}
8829
9098
  });
8830
- return;
9099
+ return result?.queued !== false;
8831
9100
  } catch (error) {
8832
9101
  if (!params.paperclipApiBaseUrl) {
8833
9102
  throw new Error(
@@ -8876,6 +9145,7 @@ async function wakePaperclipIssueAssignee(ctx, params) {
8876
9145
  if (!response.ok) {
8877
9146
  throw new Error(`Wakeup request failed with status ${response.status}.`);
8878
9147
  }
9148
+ return true;
8879
9149
  } catch (error) {
8880
9150
  throw new Error(
8881
9151
  `GitHub sync could not wake the assignee for Paperclip issue ${params.paperclipIssueId}: ${getErrorMessage(error)}`,
@@ -9584,58 +9854,36 @@ function getEffectivePullRequestActionCondition(pullRequest) {
9584
9854
  if (pullRequest.ciState === "green" && pullRequest.mergeability === "mergeable") return "ready";
9585
9855
  return "waiting";
9586
9856
  }
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"}`;
9857
+ function buildRemoteActionFingerprint(snapshot, effectiveGate = snapshot.state === "closed" ? void 0 : selectEffectiveIssueLinkedPullRequestGate(snapshot.linkedPullRequests, [], false)) {
9858
+ const gate = snapshot.state === "closed" || !effectiveGate ? null : {
9859
+ repositoryUrl: effectiveGate.repositoryUrl,
9860
+ number: effectiveGate.number,
9861
+ headSha: effectiveGate.headSha,
9862
+ condition: effectiveGate.remoteCondition
9863
+ };
9864
+ const reasonCode = snapshot.state === "closed" ? `issue_closed_${snapshot.stateReason ?? "completed"}` : gate ? `pr_${gate.condition}` : "issue_open";
9616
9865
  return createHash("sha256").update(JSON.stringify({
9617
- version: 3,
9866
+ version: 4,
9618
9867
  issue: {
9619
9868
  state: snapshot.state,
9620
9869
  stateReason: snapshot.stateReason ?? null
9621
9870
  },
9622
- pullRequests,
9871
+ gate,
9623
9872
  reasonCode
9624
9873
  })).digest("hex");
9625
9874
  }
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) : [];
9875
+ function buildDirectPullRequestActionFingerprint(snapshots, effectiveGate) {
9876
+ const terminalOutcome = effectiveGate ? null : snapshots.some((entry) => entry.lifecycleState === "merged") ? "merged" : "closed";
9877
+ const gate = effectiveGate ? {
9878
+ repositoryUrl: effectiveGate.repositoryUrl,
9879
+ number: effectiveGate.number,
9880
+ headSha: effectiveGate.headSha,
9881
+ condition: effectiveGate.remoteCondition
9882
+ } : null;
9635
9883
  return createHash("sha256").update(JSON.stringify({
9636
- version: 3,
9884
+ version: 4,
9637
9885
  terminalOutcome,
9638
- pullRequests
9886
+ gate
9639
9887
  })).digest("hex");
9640
9888
  }
9641
9889
  function classifyIssueInteractionReason(value) {
@@ -9728,7 +9976,7 @@ async function updatePaperclipIssueState(ctx, params) {
9728
9976
  issuePatch
9729
9977
  });
9730
9978
  const reasonCode = classifyIssueInteractionReason(transitionCommentAnnotation?.reason ?? trimmedTransitionComment);
9731
- const interactionDedupeBase = actionFingerprint ? `sync:${createHash("sha256").update(JSON.stringify({
9979
+ const interactionFamilyBase = actionFingerprint ? `sync:${createHash("sha256").update(JSON.stringify({
9732
9980
  companyId,
9733
9981
  issueId,
9734
9982
  mutation: "status_transition",
@@ -9737,14 +9985,14 @@ async function updatePaperclipIssueState(ctx, params) {
9737
9985
  nextStatus,
9738
9986
  currentIssueState: syncContext,
9739
9987
  issuePatch
9740
- })).digest("hex")}` : `sync:${issueId}:${interactionOccurredAt}:${currentStatus}:${nextStatus}`;
9988
+ })).digest("hex")}` : void 0;
9741
9989
  const mutationFamilyBase = actionFingerprint ? `sync:${createHash("sha256").update(JSON.stringify({
9742
9990
  companyId,
9743
9991
  issueId,
9744
9992
  mutation: "status_transition",
9745
9993
  actionFingerprint,
9746
9994
  nextStatus
9747
- })).digest("hex")}` : interactionDedupeBase;
9995
+ })).digest("hex")}` : `sync:${issueId}:${interactionOccurredAt}:${currentStatus}:${nextStatus}`;
9748
9996
  const hasAssigneePatch = Object.prototype.hasOwnProperty.call(issuePatch, "assigneeAgentId") || Object.prototype.hasOwnProperty.call(issuePatch, "assigneeUserId");
9749
9997
  const mutationExpectedState = {
9750
9998
  status: issuePatch.status ?? liveCurrentStatus,
@@ -9763,9 +10011,10 @@ async function updatePaperclipIssueState(ctx, params) {
9763
10011
  };
9764
10012
  const mutationExpectedStateFingerprint = createHash("sha256").update(JSON.stringify(mutationExpectedState)).digest("hex").slice(0, 32);
9765
10013
  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
10014
  let existingInteractionEvents = [];
9768
- if (actionFingerprint) {
10015
+ let interactionDedupeBase = mutationFamilyBase;
10016
+ let reconciliationAttemptId;
10017
+ if (actionFingerprint && interactionFamilyBase) {
9769
10018
  const ledger = await listIssueInteractionEvents(ctx, companyId, issueId, {
9770
10019
  from: "1970-01-01T00:00:00.000Z",
9771
10020
  to: "9999-12-31T23:59:59.999Z"
@@ -9774,17 +10023,30 @@ async function updatePaperclipIssueState(ctx, params) {
9774
10023
  throw new Error("GitHub Sync refused a status transition because its issue interaction ledger is incomplete or conflicting.");
9775
10024
  }
9776
10025
  existingInteractionEvents = ledger.events;
9777
- const existingIntent = existingInteractionEvents.find((event) => event.dedupeKey === `${interactionDedupeBase}:intent`);
9778
- if (existingIntent) interactionOccurredAt = existingIntent.occurredAt;
10026
+ const attemptPrefix = `${interactionFamilyBase}:attempt:`;
10027
+ const latestOpenAttemptIntent = existingInteractionEvents.filter((event) => {
10028
+ if (!event.dedupeKey.startsWith(attemptPrefix)) return false;
10029
+ const suffix = event.dedupeKey.slice(attemptPrefix.length);
10030
+ return /^[^:]+:intent$/.test(suffix);
10031
+ }).sort(
10032
+ (left, right) => right.occurredAt.localeCompare(left.occurredAt) || right.dedupeKey.localeCompare(left.dedupeKey)
10033
+ ).find((intent) => {
10034
+ const attemptBase = intent.dedupeKey.slice(0, -":intent".length);
10035
+ return !existingInteractionEvents.some(
10036
+ (event) => event.dedupeKey.startsWith(`${attemptBase}:result:`) && !event.dedupeKey.endsWith(":result:failed")
10037
+ );
10038
+ });
10039
+ if (latestOpenAttemptIntent) {
10040
+ interactionDedupeBase = latestOpenAttemptIntent.dedupeKey.slice(0, -":intent".length);
10041
+ reconciliationAttemptId = interactionDedupeBase.slice(attemptPrefix.length);
10042
+ interactionOccurredAt = latestOpenAttemptIntent.occurredAt;
10043
+ } else {
10044
+ reconciliationAttemptId = randomUUID();
10045
+ interactionDedupeBase = `${attemptPrefix}${reconciliationAttemptId}`;
10046
+ }
9779
10047
  }
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;
10048
+ const mutationPatchBase = `${mutationFamilyBase}${reconciliationAttemptId ? `:attempt:${reconciliationAttemptId}` : ""}:patch:${createHash("sha256").update(JSON.stringify(issuePatch)).digest("hex").slice(0, 32)}:applied:${mutationExpectedStateFingerprint}`;
10049
+ const mutationDedupeBase = mutationPatchBase;
9788
10050
  await persistIssueInteractionEvent(ctx, {
9789
10051
  schemaVersion: 1,
9790
10052
  companyId,
@@ -9866,11 +10128,15 @@ async function updatePaperclipIssueState(ctx, params) {
9866
10128
  if (statusWillChange) {
9867
10129
  const commentIntentKey = `${interactionDedupeBase}:comment:intent`;
9868
10130
  const commentChangedKey = `${interactionDedupeBase}:comment:result:changed`;
10131
+ const commentFailedBeforeReturnKey = `${interactionDedupeBase}:comment:result:failed-before-return`;
9869
10132
  const priorCommentIntent = existingInteractionEvents.find((event) => event.dedupeKey === commentIntentKey);
9870
10133
  const priorCommentChanged = existingInteractionEvents.find((event) => event.dedupeKey === commentChangedKey);
10134
+ const priorCommentFailedBeforeReturn = existingInteractionEvents.find(
10135
+ (event) => event.dedupeKey === commentFailedBeforeReturnKey
10136
+ );
9871
10137
  if (priorCommentChanged) {
9872
10138
  transitionCommentComplete = true;
9873
- } else if (priorCommentIntent) {
10139
+ } else if (priorCommentIntent && !priorCommentFailedBeforeReturn) {
9874
10140
  throw new Error("GitHub Sync refused to repeat an uncertain transition comment; reconcile the durable interaction intent before retrying.");
9875
10141
  } else {
9876
10142
  const commentEventBase = {
@@ -9895,8 +10161,10 @@ async function updatePaperclipIssueState(ctx, params) {
9895
10161
  outcome: "observed",
9896
10162
  dedupeKey: commentIntentKey
9897
10163
  });
10164
+ let commentReturned = false;
9898
10165
  try {
9899
10166
  createdTransitionComment = await ctx.issues.createComment(issueId, trimmedTransitionComment, companyId);
10167
+ commentReturned = true;
9900
10168
  if (transitionCommentAnnotation) {
9901
10169
  await upsertStatusTransitionCommentAnnotation(ctx, {
9902
10170
  issueId,
@@ -9918,7 +10186,7 @@ async function updatePaperclipIssueState(ctx, params) {
9918
10186
  await persistIssueInteractionEvent(ctx, {
9919
10187
  ...commentEventBase,
9920
10188
  outcome: "failed",
9921
- dedupeKey: `${interactionDedupeBase}:comment:result:failed`
10189
+ dedupeKey: commentReturned ? `${interactionDedupeBase}:comment:result:failed-after-return` : commentFailedBeforeReturnKey
9922
10190
  });
9923
10191
  throw error;
9924
10192
  }
@@ -10124,51 +10392,6 @@ function shouldIgnoreGitHubIssue(issue, advancedSettings) {
10124
10392
  (ignoredUsername) => buildGitHubUsernameAliases(ignoredUsername).some((alias) => issueAuthorAliases.has(alias))
10125
10393
  );
10126
10394
  }
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
10395
  async function ensurePaperclipIssueStandardWorkMode(ctx, issue, companyId) {
10173
10396
  if (!("workMode" in issue) || issue.workMode === "standard") {
10174
10397
  return issue;
@@ -10185,7 +10408,6 @@ async function createPaperclipIssue(ctx, mapping, advancedSettings, issue, avail
10185
10408
  }
10186
10409
  const title = issue.title;
10187
10410
  const description = buildPaperclipIssueDescription(issue);
10188
- const defaultAssignee = getConfiguredAdvancedAssigneePrincipal(advancedSettings, "default");
10189
10411
  const createdIssue = await ensurePaperclipIssueStandardWorkMode(
10190
10412
  ctx,
10191
10413
  await ctx.issues.create({
@@ -10193,24 +10415,15 @@ async function createPaperclipIssue(ctx, mapping, advancedSettings, issue, avail
10193
10415
  projectId: mapping.paperclipProjectId,
10194
10416
  title,
10195
10417
  ...description ? { description } : {},
10196
- status: advancedSettings.defaultStatus,
10418
+ status: "backlog",
10197
10419
  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 } : {}
10420
+ originId: normalizeGitHubIssueHtmlUrl(issue.htmlUrl) ?? issue.htmlUrl
10200
10421
  }),
10201
10422
  mapping.companyId
10202
10423
  );
10203
10424
  const ensuredCreatedIssueId = createdIssue.id;
10204
10425
  const normalizedCreatedIssueDescription = createdIssue.description ?? void 0;
10205
10426
  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
10427
  if (normalizeIssueDescriptionValue(normalizedCreatedIssueDescription) !== description) {
10215
10428
  logIssueDescriptionDiagnostic(
10216
10429
  ctx,
@@ -10302,7 +10515,8 @@ async function ensurePaperclipIssueImported(ctx, mapping, advancedSettings, issu
10302
10515
  mapping,
10303
10516
  issue,
10304
10517
  existingImportedPaperclipIssue.id,
10305
- coerceDate(existingImportedPaperclipIssue.createdAt ?? /* @__PURE__ */ new Date()).toISOString()
10518
+ coerceDate(existingImportedPaperclipIssue.createdAt ?? /* @__PURE__ */ new Date()).toISOString(),
10519
+ true
10306
10520
  )
10307
10521
  );
10308
10522
  importRegistryByIssueId.set(issue.id, repairedRecord);
@@ -10321,7 +10535,7 @@ async function ensurePaperclipIssueImported(ctx, mapping, advancedSettings, issu
10321
10535
  );
10322
10536
  const registryRecord = upsertImportedIssueRecord(
10323
10537
  nextRegistry,
10324
- buildImportedIssueRecord(mapping, issue, createdIssue.id, (/* @__PURE__ */ new Date()).toISOString())
10538
+ buildImportedIssueRecord(mapping, issue, createdIssue.id, (/* @__PURE__ */ new Date()).toISOString(), true)
10325
10539
  );
10326
10540
  importRegistryByIssueId.set(issue.id, registryRecord);
10327
10541
  ensuredPaperclipIssueIds.set(issue.id, createdIssue.id);
@@ -10746,15 +10960,35 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10746
10960
  }
10747
10961
  }
10748
10962
  }
10749
- const hasTrustedNewLinkedPullRequestComment = paperclipIssue.status === "backlog" || currentLinkedPullRequestCommentCounts.length === 0 ? false : await hasTrustedNewLinkedPullRequestComments({
10963
+ const trustedNewLinkedPullRequestCommentSources = paperclipIssue.status === "backlog" || currentLinkedPullRequestCommentCounts.length === 0 ? [] : await listTrustedNewLinkedPullRequestCommentSources({
10750
10964
  octokit,
10751
10965
  originalPosterLogin: githubIssue.authorLogin,
10752
10966
  previousCommentCounts: importedIssue.linkedPullRequestCommentCounts,
10753
10967
  currentCommentCounts: currentLinkedPullRequestCommentCounts,
10754
10968
  maintainerCache: repositoryMaintainerCache
10755
10969
  });
10970
+ const hasTrustedNewLinkedPullRequestComment = trustedNewLinkedPullRequestCommentSources.length > 0;
10756
10971
  const hasTrustedNewComment = hasTrustedNewIssueComment || hasTrustedNewLinkedPullRequestComment;
10757
- const remoteActionFingerprint = buildRemoteActionFingerprint(snapshot);
10972
+ const issueLinkedPullRequestLinks = snapshot.linkedPullRequests.length === 0 ? [] : await listGitHubPullRequestLinkRecords(ctx, {
10973
+ paperclipIssueId: importedIssue.paperclipIssueId
10974
+ });
10975
+ const effectiveGate = selectEffectiveIssueLinkedPullRequestGate(
10976
+ snapshot.linkedPullRequests,
10977
+ trustedNewLinkedPullRequestCommentSources,
10978
+ hasTrustedNewIssueComment,
10979
+ issueLinkedPullRequestLinks,
10980
+ importedIssue.selectedPullRequestGate
10981
+ );
10982
+ const followThroughAssigneeAgentId = await resolveValidFollowThroughAssigneeAgentId(
10983
+ ctx,
10984
+ mapping.companyId,
10985
+ effectiveGate?.ownerCandidate
10986
+ );
10987
+ const transitionFollowThroughAssigneeAgentId = isActionableDirectPullRequestGate(effectiveGate) ? followThroughAssigneeAgentId : void 0;
10988
+ const remoteActionFingerprint = createHash("sha256").update(JSON.stringify({
10989
+ issue: buildRemoteActionFingerprint(snapshot, effectiveGate),
10990
+ followThroughAssigneeAgentId
10991
+ })).digest("hex");
10758
10992
  const actionJournalFingerprint = createHash("sha256").update(JSON.stringify({
10759
10993
  remoteActionFingerprint,
10760
10994
  issueCommentCount: snapshot.commentCount,
@@ -10762,9 +10996,14 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10762
10996
  currentLinkedPullRequestCommentCounts
10763
10997
  )
10764
10998
  })).digest("hex");
10765
- if (importedIssue.pendingRemoteActionWake) {
10999
+ const createWakeFingerprint = () => createRemoteActionWakeFingerprint(remoteActionFingerprint);
11000
+ if (importedIssue.pendingRemoteActionWake && isPendingWakeApplied(
11001
+ importedIssue.pendingRemoteActionWake,
11002
+ paperclipIssue.status,
11003
+ getPaperclipIssueSyncContext(paperclipIssue).assignee
11004
+ )) {
10766
11005
  const pendingWake2 = importedIssue.pendingRemoteActionWake;
10767
- await wakePaperclipIssueAssignee(ctx, {
11006
+ const admitted = await wakePaperclipIssueAssignee(ctx, {
10768
11007
  assigneeAgentId: pendingWake2.assigneeAgentId,
10769
11008
  paperclipIssueId: importedIssue.paperclipIssueId,
10770
11009
  companyId: mapping.companyId,
@@ -10775,11 +11014,15 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10775
11014
  previousStatus: pendingWake2.previousStatus,
10776
11015
  nextStatus: pendingWake2.nextStatus
10777
11016
  });
10778
- delete importedIssue.pendingRemoteActionWake;
10779
- await persistImportRegistry();
11017
+ if (admitted) {
11018
+ delete importedIssue.pendingRemoteActionWake;
11019
+ delete importedIssue.activationPending;
11020
+ await persistImportRegistry();
11021
+ }
10780
11022
  }
10781
11023
  const wasImportedThisRun = createdIssueIds.has(importedIssue.githubIssueId);
10782
- const maintainerAuthoredImportedIssue = wasImportedThisRun && advancedSettings.defaultStatus !== "todo" && snapshot.state === "open" && snapshot.linkedPullRequests.length === 0 ? await isMaintainerAuthoredGitHubIssue({
11024
+ const isPendingInitialActivation = wasImportedThisRun || importedIssue.activationPending === true;
11025
+ const maintainerAuthoredImportedIssue = isPendingInitialActivation && advancedSettings.defaultStatus !== "todo" && snapshot.state === "open" && snapshot.linkedPullRequests.length === 0 ? await isMaintainerAuthoredGitHubIssue({
10783
11026
  octokit,
10784
11027
  repository,
10785
11028
  githubIssue,
@@ -10788,13 +11031,15 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10788
11031
  const paperclipIssueSyncContext = getPaperclipIssueSyncContext(paperclipIssue);
10789
11032
  const executorTransitionAssignee = resolvePaperclipIssueExecutorAssignee(
10790
11033
  paperclipIssueSyncContext,
10791
- advancedSettings
11034
+ advancedSettings,
11035
+ transitionFollowThroughAssigneeAgentId
10792
11036
  );
10793
11037
  let nextStatus = resolvePaperclipIssueStatus({
10794
11038
  currentStatus: paperclipIssue.status,
10795
11039
  snapshot,
11040
+ effectiveGate,
10796
11041
  hasTrustedNewComment,
10797
- wasImportedThisRun,
11042
+ wasImportedThisRun: isPendingInitialActivation,
10798
11043
  defaultImportedStatus: advancedSettings.defaultStatus,
10799
11044
  maintainerAuthoredImportedIssue,
10800
11045
  hasExecutorHandoffTarget: Boolean(executorTransitionAssignee)
@@ -10802,41 +11047,57 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10802
11047
  if (paperclipIssue.status === "blocked" && nextStatus !== "blocked" && await hasUnresolvedPaperclipIssueBlocker(ctx, paperclipIssue, mapping.companyId)) {
10803
11048
  nextStatus = "blocked";
10804
11049
  }
10805
- if (paperclipIssue.status !== nextStatus && !hasTrustedNewComment && importedIssue.remoteActionFingerprint === remoteActionFingerprint) {
10806
- nextStatus = paperclipIssue.status;
10807
- }
10808
11050
  const shouldPreserveMaintainerWaitRouting = isHealthyMaintainerWaitTransition({
10809
11051
  currentStatus: paperclipIssue.status,
10810
11052
  nextStatus,
10811
11053
  syncContext: paperclipIssueSyncContext
10812
11054
  });
10813
11055
  const shouldClearCompletedExecutionPolicy = nextStatus === "done" || nextStatus === "cancelled";
10814
- const shouldPreserveImportedTriageRouting = shouldPreserveImportedTriageAssignee({
11056
+ const shouldPreserveImportedTriageRouting = Boolean(paperclipIssueSyncContext.assignee) && shouldPreserveImportedTriageAssignee({
10815
11057
  currentStatus: paperclipIssue.status,
10816
11058
  nextStatus,
10817
- wasImportedThisRun,
11059
+ wasImportedThisRun: isPendingInitialActivation,
10818
11060
  maintainerAuthoredImportedIssue
10819
11061
  });
10820
- const nextTransitionAssignee = shouldPreserveImportedTriageRouting ? null : resolveSyncTransitionAssignee({
11062
+ const configuredDefaultAssignee = getConfiguredAdvancedAssigneePrincipal(advancedSettings, "default");
11063
+ const nextTransitionAssignee = isPendingInitialActivation && configuredDefaultAssignee ? { principal: configuredDefaultAssignee, role: "executor" } : shouldPreserveImportedTriageRouting ? null : resolveSyncTransitionAssignee({
10821
11064
  currentStatus: paperclipIssue.status,
10822
11065
  nextStatus,
10823
11066
  syncContext: paperclipIssueSyncContext,
10824
- advancedSettings
11067
+ advancedSettings,
11068
+ followThroughAssigneeAgentId: transitionFollowThroughAssigneeAgentId
10825
11069
  });
10826
11070
  const shouldClearTransitionAssignee = nextStatus === "in_review" && (nextTransitionAssignee === null || shouldPreserveMaintainerWaitRouting);
10827
11071
  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);
11072
+ const importedActivationAssignee = paperclipIssueSyncContext.assignee?.kind === "agent" ? paperclipIssueSyncContext.assignee : nextTransitionAssignee?.principal.kind === "agent" ? nextTransitionAssignee.principal : void 0;
11073
+ const shouldWakeImportedAssignee = isPendingInitialActivation && nextStatus === "todo" && Boolean(importedActivationAssignee);
11074
+ const shouldWakeTransitionAssignee = nextTransitionAssignee?.principal.kind === "agent" && isActionablePaperclipIssueStatus(nextStatus) && (nextAssigneeChanged || paperclipIssue.status !== nextStatus);
10830
11075
  const persistObservedRemoteState = async (pendingWake2) => {
10831
11076
  importedIssue.githubIssueNumber = githubIssue.number;
10832
11077
  importedIssue.lastSeenCommentCount = snapshot.commentCount;
10833
11078
  importedIssue.lastSeenGitHubState = snapshot.state;
10834
11079
  importedIssue.linkedPullRequestCommentCounts = currentLinkedPullRequestCommentCounts;
10835
11080
  importedIssue.remoteActionFingerprint = remoteActionFingerprint;
11081
+ importedIssue.selectedPullRequestGate = effectiveGate ? { repositoryUrl: effectiveGate.repositoryUrl, number: effectiveGate.number } : void 0;
10836
11082
  if (pendingWake2) importedIssue.pendingRemoteActionWake = pendingWake2;
11083
+ else delete importedIssue.activationPending;
10837
11084
  await persistImportRegistry();
10838
11085
  };
10839
11086
  if (paperclipIssue.status === nextStatus) {
11087
+ const pendingWake2 = shouldWakeImportedAssignee && importedActivationAssignee ? reuseOrCreatePendingWake(importedIssue.pendingRemoteActionWake, {
11088
+ assigneeAgentId: importedActivationAssignee.id,
11089
+ reason: IMPORTED_ISSUE_WAKE_REASON,
11090
+ mutation: "import",
11091
+ nextStatus
11092
+ }, createWakeFingerprint) : shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? reuseOrCreatePendingWake(importedIssue.pendingRemoteActionWake, {
11093
+ assigneeAgentId: nextTransitionAssignee.principal.id,
11094
+ reason: STATUS_TRANSITION_WAKE_REASON,
11095
+ mutation: "status_transition",
11096
+ previousStatus: paperclipIssue.status,
11097
+ nextStatus
11098
+ }, createWakeFingerprint) : void 0;
11099
+ if (pendingWake2) importedIssue.pendingRemoteActionWake = pendingWake2;
11100
+ if (pendingWake2 || isPendingInitialActivation) await persistImportRegistry();
10840
11101
  updateSyncFailureContext(syncFailureContext, {
10841
11102
  phase: "updating_paperclip_status",
10842
11103
  repositoryUrl: repository.url,
@@ -10848,31 +11109,27 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10848
11109
  currentStatus: paperclipIssue.status,
10849
11110
  syncContext: paperclipIssueSyncContext,
10850
11111
  nextStatus,
11112
+ ...nextAssigneeChanged && nextTransitionAssignee ? { nextAssignee: nextTransitionAssignee.principal } : {},
10851
11113
  ...shouldClearTransitionAssignee ? { clearAssignee: true } : {},
10852
11114
  ...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
10853
11115
  transitionComment: "",
10854
11116
  actionFingerprint: actionJournalFingerprint,
10855
11117
  paperclipApiBaseUrl
10856
11118
  });
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
- };
11119
+ if (pendingWake2) {
10865
11120
  await persistObservedRemoteState(pendingWake2);
10866
11121
  queuedIssueWakeups.push({
10867
11122
  assigneeAgentId: pendingWake2.assigneeAgentId,
10868
11123
  paperclipIssueId: importedIssue.paperclipIssueId,
10869
11124
  reason: pendingWake2.reason,
10870
- mutation: "import",
11125
+ mutation: pendingWake2.mutation,
10871
11126
  actionFingerprint: pendingWake2.fingerprint,
11127
+ previousStatus: pendingWake2.previousStatus,
10872
11128
  nextStatus,
10873
11129
  onSuccess: async () => {
10874
11130
  if (importedIssue.pendingRemoteActionWake?.fingerprint === pendingWake2.fingerprint) {
10875
11131
  delete importedIssue.pendingRemoteActionWake;
11132
+ delete importedIssue.activationPending;
10876
11133
  await persistImportRegistry();
10877
11134
  }
10878
11135
  }
@@ -10895,6 +11152,21 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10895
11152
  repositoryUrl: repository.url,
10896
11153
  githubIssueNumber: githubIssue.number
10897
11154
  });
11155
+ const pendingWake = shouldWakeImportedAssignee && importedActivationAssignee ? reuseOrCreatePendingWake(importedIssue.pendingRemoteActionWake, {
11156
+ assigneeAgentId: importedActivationAssignee.id,
11157
+ reason: IMPORTED_ISSUE_WAKE_REASON,
11158
+ mutation: "import",
11159
+ previousStatus: paperclipIssue.status,
11160
+ nextStatus
11161
+ }, createWakeFingerprint) : shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? reuseOrCreatePendingWake(importedIssue.pendingRemoteActionWake, {
11162
+ assigneeAgentId: nextTransitionAssignee.principal.id,
11163
+ reason: STATUS_TRANSITION_WAKE_REASON,
11164
+ mutation: "status_transition",
11165
+ previousStatus: paperclipIssue.status,
11166
+ nextStatus
11167
+ }, createWakeFingerprint) : void 0;
11168
+ if (pendingWake) importedIssue.pendingRemoteActionWake = pendingWake;
11169
+ if (pendingWake || isPendingInitialActivation) await persistImportRegistry();
10898
11170
  await updatePaperclipIssueState(ctx, {
10899
11171
  companyId: mapping.companyId,
10900
11172
  issueId: importedIssue.paperclipIssueId,
@@ -10909,21 +11181,6 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10909
11181
  actionFingerprint: actionJournalFingerprint,
10910
11182
  paperclipApiBaseUrl
10911
11183
  });
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
11184
  await persistObservedRemoteState(pendingWake);
10928
11185
  updatedStatusesCount += 1;
10929
11186
  if (pendingWake) {
@@ -10938,6 +11195,7 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10938
11195
  onSuccess: async () => {
10939
11196
  if (importedIssue.pendingRemoteActionWake?.fingerprint === pendingWake.fingerprint) {
10940
11197
  delete importedIssue.pendingRemoteActionWake;
11198
+ delete importedIssue.activationPending;
10941
11199
  await persistImportRegistry();
10942
11200
  }
10943
11201
  }
@@ -10965,7 +11223,7 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10965
11223
  queuedIssueWakeups,
10966
11224
  IMPORTED_ISSUE_WAKEUP_CONCURRENCY,
10967
11225
  async (queuedWakeup) => {
10968
- await wakePaperclipIssueAssignee(ctx, {
11226
+ const admitted = await wakePaperclipIssueAssignee(ctx, {
10969
11227
  assigneeAgentId: queuedWakeup.assigneeAgentId,
10970
11228
  paperclipIssueId: queuedWakeup.paperclipIssueId,
10971
11229
  companyId: mapping.companyId,
@@ -10976,7 +11234,7 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10976
11234
  previousStatus: queuedWakeup.previousStatus,
10977
11235
  nextStatus: queuedWakeup.nextStatus
10978
11236
  });
10979
- await queuedWakeup.onSuccess?.();
11237
+ if (admitted) await queuedWakeup.onSuccess?.();
10980
11238
  }
10981
11239
  );
10982
11240
  return {
@@ -11115,9 +11373,13 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11115
11373
  remoteAction = { key: remoteActionKey };
11116
11374
  remoteActionRegistry.push(remoteAction);
11117
11375
  }
11118
- if (remoteAction.pendingWake) {
11376
+ if (remoteAction.pendingWake && isPendingWakeApplied(
11377
+ remoteAction.pendingWake,
11378
+ paperclipIssue.status,
11379
+ getPaperclipIssueSyncContext(paperclipIssue).assignee
11380
+ )) {
11119
11381
  const pendingWake2 = remoteAction.pendingWake;
11120
- await wakePaperclipIssueAssignee(ctx, {
11382
+ const admitted = await wakePaperclipIssueAssignee(ctx, {
11121
11383
  assigneeAgentId: pendingWake2.assigneeAgentId,
11122
11384
  paperclipIssueId,
11123
11385
  companyId: mapping.companyId,
@@ -11128,49 +11390,62 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11128
11390
  previousStatus: pendingWake2.previousStatus,
11129
11391
  nextStatus: pendingWake2.nextStatus
11130
11392
  });
11131
- delete remoteAction.pendingWake;
11132
- await persistRemoteActionRegistry();
11393
+ if (admitted) {
11394
+ delete remoteAction.pendingWake;
11395
+ await persistRemoteActionRegistry();
11396
+ }
11133
11397
  }
11134
11398
  const currentCommentCounts = pullRequestSnapshots.map((snapshot) => snapshot.commentCounts).filter((counts) => Boolean(counts));
11135
- let hasTrustedNewComment = false;
11399
+ const trustedCommentSources = [];
11136
11400
  if (paperclipIssue.status !== "backlog" && remoteAction.linkedPullRequestCommentCounts) {
11137
11401
  const maintainerCache = /* @__PURE__ */ new Map();
11138
11402
  for (const snapshot of pullRequestSnapshots) {
11139
11403
  if (!snapshot.commentCounts) continue;
11140
- if (await hasTrustedNewLinkedPullRequestComments({
11404
+ trustedCommentSources.push(...await listTrustedNewLinkedPullRequestCommentSources({
11141
11405
  octokit,
11142
11406
  originalPosterLogin: snapshot.authorLogin,
11143
11407
  previousCommentCounts: remoteAction.linkedPullRequestCommentCounts,
11144
11408
  currentCommentCounts: [snapshot.commentCounts],
11145
11409
  maintainerCache
11146
- })) {
11147
- hasTrustedNewComment = true;
11148
- break;
11149
- }
11410
+ }));
11150
11411
  }
11151
11412
  }
11152
- const remoteActionFingerprint = buildDirectPullRequestActionFingerprint(pullRequestSnapshots);
11413
+ const effectiveGate = selectEffectiveDirectPullRequestGate(
11414
+ pullRequestSnapshots,
11415
+ trustedCommentSources,
11416
+ remoteAction.selectedPullRequestGate
11417
+ );
11418
+ const hasTrustedNewComment = Boolean(effectiveGate?.trustedCommentKinds.length);
11419
+ const followThroughAssigneeAgentId = await resolveValidFollowThroughAssigneeAgentId(
11420
+ ctx,
11421
+ mapping.companyId,
11422
+ effectiveGate?.ownerCandidate
11423
+ );
11424
+ const transitionFollowThroughAssigneeAgentId = isActionableDirectPullRequestGate(effectiveGate) ? followThroughAssigneeAgentId : void 0;
11425
+ const remoteActionFingerprint = createHash("sha256").update(JSON.stringify({
11426
+ pullRequest: buildDirectPullRequestActionFingerprint(pullRequestSnapshots, effectiveGate),
11427
+ followThroughAssigneeAgentId
11428
+ })).digest("hex");
11153
11429
  const actionJournalFingerprint = createHash("sha256").update(JSON.stringify({
11154
11430
  remoteActionFingerprint,
11155
11431
  commentCounts: canonicalizeGitHubPullRequestCommentCounts(currentCommentCounts)
11156
11432
  })).digest("hex");
11433
+ const createWakeFingerprint = () => createRemoteActionWakeFingerprint(remoteActionFingerprint);
11157
11434
  const paperclipIssueSyncContext = getPaperclipIssueSyncContext(paperclipIssue);
11158
11435
  const executorTransitionAssignee = resolvePaperclipIssueExecutorAssignee(
11159
11436
  paperclipIssueSyncContext,
11160
- advancedSettings
11437
+ advancedSettings,
11438
+ transitionFollowThroughAssigneeAgentId
11161
11439
  );
11162
11440
  let nextStatus = resolvePaperclipDirectPullRequestIssueStatus({
11163
11441
  currentStatus: paperclipIssue.status,
11164
11442
  pullRequests: pullRequestSnapshots,
11165
- hasExecutorHandoffTarget: Boolean(executorTransitionAssignee),
11166
- hasTrustedNewComment
11443
+ effectiveGate,
11444
+ hasExecutorHandoffTarget: Boolean(executorTransitionAssignee)
11167
11445
  });
11168
11446
  if (paperclipIssue.status === "blocked" && nextStatus !== "blocked" && pullRequestSnapshots.some((entry) => entry.lifecycleState === "open") && await hasUnresolvedPaperclipIssueBlocker(ctx, paperclipIssue, mapping.companyId)) {
11169
11447
  nextStatus = "blocked";
11170
11448
  }
11171
- if (paperclipIssue.status !== nextStatus && remoteAction.fingerprint === remoteActionFingerprint && !hasTrustedNewComment) {
11172
- nextStatus = paperclipIssue.status;
11173
- }
11174
11449
  const shouldPreserveMaintainerWaitRouting = isHealthyMaintainerWaitTransition({
11175
11450
  currentStatus: paperclipIssue.status,
11176
11451
  nextStatus,
@@ -11181,13 +11456,31 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11181
11456
  currentStatus: paperclipIssue.status,
11182
11457
  nextStatus,
11183
11458
  syncContext: paperclipIssueSyncContext,
11184
- advancedSettings
11459
+ advancedSettings,
11460
+ followThroughAssigneeAgentId: transitionFollowThroughAssigneeAgentId
11185
11461
  });
11186
11462
  const shouldClearTransitionAssignee = nextStatus === "in_review" && (nextTransitionAssignee === null || shouldPreserveMaintainerWaitRouting);
11187
11463
  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);
11464
+ const shouldWakeTransitionAssignee = nextTransitionAssignee?.principal.kind === "agent" && isActionablePaperclipIssueStatus(nextStatus) && (nextAssigneeChanged || paperclipIssue.status !== nextStatus);
11189
11465
  if (paperclipIssue.status === nextStatus) {
11190
- if (shouldClearTransitionAssignee || shouldClearCompletedExecutionPolicy) {
11466
+ if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" && !canReservePendingWake(remoteActionRegistry, remoteAction)) {
11467
+ throw new Error(
11468
+ `Remote action registry pending-wake capacity ${MAX_REMOTE_ACTION_REGISTRY_RECORDS} reached; refusing an untracked assignment update`
11469
+ );
11470
+ }
11471
+ const pendingWake2 = shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? reuseOrCreatePendingWake(remoteAction.pendingWake, {
11472
+ assigneeAgentId: nextTransitionAssignee.principal.id,
11473
+ reason: STATUS_TRANSITION_WAKE_REASON,
11474
+ mutation: "status_transition",
11475
+ previousStatus: paperclipIssue.status,
11476
+ nextStatus
11477
+ }, createWakeFingerprint) : void 0;
11478
+ if (pendingWake2) {
11479
+ remoteAction.pendingWake = pendingWake2;
11480
+ await persistRemoteActionRegistry();
11481
+ remoteAction = remoteActionRegistry.find((record) => record.key === remoteActionKey) ?? remoteAction;
11482
+ }
11483
+ if (shouldClearTransitionAssignee || shouldClearCompletedExecutionPolicy || nextAssigneeChanged) {
11191
11484
  updateSyncFailureContext(syncFailureContext, {
11192
11485
  phase: "updating_paperclip_status",
11193
11486
  repositoryUrl: primaryRepository?.url,
@@ -11199,6 +11492,7 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11199
11492
  currentStatus: paperclipIssue.status,
11200
11493
  syncContext: paperclipIssueSyncContext,
11201
11494
  nextStatus,
11495
+ ...nextAssigneeChanged && nextTransitionAssignee ? { nextAssignee: nextTransitionAssignee.principal } : {},
11202
11496
  ...shouldClearTransitionAssignee ? { clearAssignee: true } : {},
11203
11497
  ...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
11204
11498
  transitionComment: "",
@@ -11208,7 +11502,27 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11208
11502
  }
11209
11503
  remoteAction.fingerprint = remoteActionFingerprint;
11210
11504
  remoteAction.linkedPullRequestCommentCounts = currentCommentCounts;
11505
+ remoteAction.selectedPullRequestGate = effectiveGate ? { repositoryUrl: effectiveGate.repositoryUrl, number: effectiveGate.number } : void 0;
11506
+ if (pendingWake2) remoteAction.pendingWake = pendingWake2;
11211
11507
  await persistRemoteActionRegistry();
11508
+ if (pendingWake2) {
11509
+ queuedIssueWakeups.push({
11510
+ assigneeAgentId: pendingWake2.assigneeAgentId,
11511
+ paperclipIssueId,
11512
+ reason: pendingWake2.reason,
11513
+ mutation: "status_transition",
11514
+ actionFingerprint: pendingWake2.fingerprint,
11515
+ previousStatus: pendingWake2.previousStatus,
11516
+ nextStatus: pendingWake2.nextStatus,
11517
+ onSuccess: async () => {
11518
+ const persistedRemoteAction = remoteActionRegistry.find((record) => record.key === remoteActionKey);
11519
+ if (persistedRemoteAction?.pendingWake?.fingerprint === pendingWake2.fingerprint) {
11520
+ delete persistedRemoteAction.pendingWake;
11521
+ await persistRemoteActionRegistry();
11522
+ }
11523
+ }
11524
+ });
11525
+ }
11212
11526
  continue;
11213
11527
  }
11214
11528
  const transitionComment = buildPaperclipPullRequestIssueStatusTransitionComment({
@@ -11221,11 +11535,23 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11221
11535
  repositoryUrl: primaryRepository?.url,
11222
11536
  githubIssueNumber: void 0
11223
11537
  });
11224
- if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" && remoteActionRegistry.filter((record) => record.pendingWake).length >= MAX_REMOTE_ACTION_REGISTRY_RECORDS) {
11538
+ if (shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" && !canReservePendingWake(remoteActionRegistry, remoteAction)) {
11225
11539
  throw new Error(
11226
11540
  `Remote action registry pending-wake capacity ${MAX_REMOTE_ACTION_REGISTRY_RECORDS} reached; refusing an untracked status transition`
11227
11541
  );
11228
11542
  }
11543
+ const pendingWake = shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? reuseOrCreatePendingWake(remoteAction.pendingWake, {
11544
+ assigneeAgentId: nextTransitionAssignee.principal.id,
11545
+ reason: STATUS_TRANSITION_WAKE_REASON,
11546
+ mutation: "status_transition",
11547
+ previousStatus: paperclipIssue.status,
11548
+ nextStatus
11549
+ }, createWakeFingerprint) : void 0;
11550
+ if (pendingWake) {
11551
+ remoteAction.pendingWake = pendingWake;
11552
+ await persistRemoteActionRegistry();
11553
+ remoteAction = remoteActionRegistry.find((record) => record.key === remoteActionKey) ?? remoteAction;
11554
+ }
11229
11555
  await updatePaperclipIssueState(ctx, {
11230
11556
  companyId: mapping.companyId,
11231
11557
  issueId: paperclipIssueId,
@@ -11239,16 +11565,9 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11239
11565
  actionFingerprint: actionJournalFingerprint,
11240
11566
  paperclipApiBaseUrl
11241
11567
  });
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
11568
  remoteAction.fingerprint = remoteActionFingerprint;
11251
11569
  remoteAction.linkedPullRequestCommentCounts = currentCommentCounts;
11570
+ remoteAction.selectedPullRequestGate = effectiveGate ? { repositoryUrl: effectiveGate.repositoryUrl, number: effectiveGate.number } : void 0;
11252
11571
  if (pendingWake) remoteAction.pendingWake = pendingWake;
11253
11572
  await persistRemoteActionRegistry();
11254
11573
  updatedStatusesCount += 1;
@@ -11262,8 +11581,9 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11262
11581
  previousStatus: pendingWake.previousStatus,
11263
11582
  nextStatus: pendingWake.nextStatus,
11264
11583
  onSuccess: async () => {
11265
- if (remoteAction.pendingWake?.fingerprint === pendingWake.fingerprint) {
11266
- delete remoteAction.pendingWake;
11584
+ const persistedRemoteAction = remoteActionRegistry.find((record) => record.key === remoteActionKey);
11585
+ if (persistedRemoteAction?.pendingWake?.fingerprint === pendingWake.fingerprint) {
11586
+ delete persistedRemoteAction.pendingWake;
11267
11587
  await persistRemoteActionRegistry();
11268
11588
  }
11269
11589
  }
@@ -11280,7 +11600,7 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11280
11600
  queuedIssueWakeups,
11281
11601
  IMPORTED_ISSUE_WAKEUP_CONCURRENCY,
11282
11602
  async (queuedWakeup) => {
11283
- await wakePaperclipIssueAssignee(ctx, {
11603
+ const admitted = await wakePaperclipIssueAssignee(ctx, {
11284
11604
  assigneeAgentId: queuedWakeup.assigneeAgentId,
11285
11605
  paperclipIssueId: queuedWakeup.paperclipIssueId,
11286
11606
  companyId: mapping.companyId,
@@ -11291,7 +11611,7 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11291
11611
  previousStatus: queuedWakeup.previousStatus,
11292
11612
  nextStatus: queuedWakeup.nextStatus
11293
11613
  });
11294
- await queuedWakeup.onSuccess?.();
11614
+ if (admitted) await queuedWakeup.onSuccess?.();
11295
11615
  }
11296
11616
  );
11297
11617
  return {
@@ -11828,19 +12148,24 @@ async function handleCompanyMetricApiRoute(ctx, input) {
11828
12148
  let linkedRepository = null;
11829
12149
  let linkedPullRequestNumber;
11830
12150
  let linkedPullRequestUrl;
12151
+ let linkedFollowThroughAssigneeAgentId;
12152
+ let linkedFollowThroughAssigneeUpdatedAt;
11831
12153
  if (paperclipIssueId) {
11832
12154
  const linkResult = await linkPaperclipIssueToGitHubPullRequest(ctx, {
11833
12155
  companyId,
11834
12156
  issueId: paperclipIssueId,
11835
12157
  repositoryUrl: repository?.url,
11836
12158
  pullRequestNumber,
11837
- pullRequestUrl
12159
+ pullRequestUrl,
12160
+ followThroughAssigneeAgentId: payload.followThroughAssigneeAgentId
11838
12161
  });
11839
12162
  linkedPaperclipIssueId = typeof linkResult.paperclipIssueId === "string" ? linkResult.paperclipIssueId : paperclipIssueId;
11840
12163
  const resultRepositoryUrl = normalizeOptionalString2(linkResult.repositoryUrl);
11841
12164
  linkedRepository = resultRepositoryUrl ? parseRepositoryReference(resultRepositoryUrl) : null;
11842
12165
  linkedPullRequestNumber = normalizeToolPositiveInteger(linkResult.githubPullRequestNumber);
11843
12166
  linkedPullRequestUrl = normalizeGitHubPullRequestHtmlUrl(normalizeOptionalString2(linkResult.githubPullRequestUrl));
12167
+ linkedFollowThroughAssigneeAgentId = normalizeOptionalString2(linkResult.followThroughAssigneeAgentId);
12168
+ linkedFollowThroughAssigneeUpdatedAt = normalizeOptionalString2(linkResult.followThroughAssigneeUpdatedAt);
11844
12169
  }
11845
12170
  const metricRepositoryUrl = repository?.url ?? linkedRepository?.url;
11846
12171
  const metricPullRequestNumber = pullRequestNumber ?? linkedPullRequestNumber;
@@ -11894,7 +12219,9 @@ async function handleCompanyMetricApiRoute(ctx, input) {
11894
12219
  recorded: recordedMetric.recorded,
11895
12220
  companyId,
11896
12221
  metric: "pull_request_created",
11897
- ...linkedPaperclipIssueId ? { paperclipIssueId: linkedPaperclipIssueId } : {}
12222
+ ...linkedPaperclipIssueId ? { paperclipIssueId: linkedPaperclipIssueId } : {},
12223
+ ...linkedFollowThroughAssigneeAgentId ? { followThroughAssigneeAgentId: linkedFollowThroughAssigneeAgentId } : {},
12224
+ ...linkedFollowThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt: linkedFollowThroughAssigneeUpdatedAt } : {}
11898
12225
  }
11899
12226
  };
11900
12227
  }
@@ -14261,6 +14588,11 @@ async function createProjectPullRequestPaperclipIssue(ctx, input) {
14261
14588
  throw new Error("This Paperclip runtime does not expose plugin issue creation yet.");
14262
14589
  }
14263
14590
  const scope = await requireProjectPullRequestScope(ctx, input);
14591
+ const followThroughAssigneeAgentId = await validateFollowThroughAssigneeAgentId(
14592
+ ctx,
14593
+ scope.companyId,
14594
+ input.followThroughAssigneeAgentId
14595
+ );
14264
14596
  const octokit = await createGitHubToolOctokit(ctx, scope.companyId);
14265
14597
  const pullRequestResponse = await octokit.rest.pulls.get({
14266
14598
  owner: scope.repository.owner,
@@ -14272,59 +14604,111 @@ async function createProjectPullRequestPaperclipIssue(ctx, input) {
14272
14604
  });
14273
14605
  const pullRequest = pullRequestResponse.data;
14274
14606
  const pullRequestUrl = pullRequest.html_url;
14275
- const existingLinks = await listGitHubPullRequestLinkRecords(ctx, {
14276
- externalId: pullRequestUrl
14607
+ const pullRequestState = getPullRequestApiState({
14608
+ state: pullRequest.state,
14609
+ merged: pullRequest.merged
14610
+ }) === "open" ? "open" : "closed";
14611
+ const pullRequestReferenceKey = buildGitHubPullRequestReferenceKey({
14612
+ repositoryUrl: scope.repository.url,
14613
+ number: pullRequestNumber
14277
14614
  });
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
14615
+ const creationLockKey = `hosted-create:${scope.companyId}:${scope.projectId}:${pullRequestReferenceKey}`;
14616
+ return withPullRequestLinkMutationLock(creationLockKey, async () => {
14617
+ const sortMatchingLinks = (records) => records.filter(
14618
+ (record) => record.data.githubPullRequestNumber === pullRequestNumber && buildGitHubPullRequestReferenceKey({
14619
+ repositoryUrl: record.data.repositoryUrl,
14620
+ number: record.data.githubPullRequestNumber
14621
+ }) === pullRequestReferenceKey
14622
+ ).sort(
14623
+ (left, right) => left.paperclipIssueId.localeCompare(right.paperclipIssueId) || (left.externalId ?? "").localeCompare(right.externalId ?? "")
14624
+ );
14625
+ const findReusableLinkedIssue = async (records) => {
14626
+ for (const link of sortMatchingLinks(records)) {
14627
+ const issue = await ctx.issues.get(link.paperclipIssueId, scope.companyId);
14628
+ if (issue?.companyId === scope.companyId && issue.projectId === scope.projectId) {
14629
+ return { link, issue };
14630
+ }
14631
+ }
14632
+ return null;
14287
14633
  };
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,
14634
+ const exactLinks = await listGitHubPullRequestLinkRecords(ctx, {
14635
+ externalId: pullRequestUrl
14636
+ });
14637
+ const linkedMatch = await findReusableLinkedIssue(exactLinks) ?? await findReusableLinkedIssue(await listGitHubPullRequestLinkRecords(ctx));
14638
+ const existingLink = linkedMatch?.link ?? null;
14639
+ const existingIssue = linkedMatch?.issue ?? null;
14640
+ const recoveredOriginIssue = existingIssue ? null : (await listPaperclipIssuesForProject(ctx, scope.companyId, scope.projectId)).find((issue) => {
14641
+ const originLink = resolvePaperclipIssueOriginGitHubPullRequestLink(issue);
14642
+ if (!originLink) {
14643
+ return false;
14644
+ }
14645
+ return buildGitHubPullRequestReferenceKey({
14646
+ repositoryUrl: originLink.repositoryUrl,
14647
+ number: originLink.githubPullRequestNumber
14648
+ }) === pullRequestReferenceKey;
14649
+ }) ?? null;
14650
+ const reusableIssue = existingIssue ?? recoveredOriginIssue;
14651
+ if (reusableIssue) {
14652
+ const persistedLink2 = await upsertGitHubPullRequestLinkRecord(ctx, {
14653
+ companyId: scope.companyId,
14654
+ projectId: scope.projectId,
14655
+ issueId: reusableIssue.id,
14656
+ repositoryUrl: scope.repository.url,
14301
14657
  pullRequestNumber,
14302
14658
  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"
14659
+ pullRequestTitle: pullRequest.title,
14660
+ pullRequestState,
14661
+ followThroughAssigneeAgentId
14662
+ });
14663
+ invalidateProjectPullRequestCaches(scope);
14664
+ return {
14665
+ paperclipIssueId: reusableIssue.id,
14666
+ ...reusableIssue.identifier ? { paperclipIssueKey: reusableIssue.identifier } : {},
14667
+ ...persistedLink2.followThroughAssigneeAgentId ? { followThroughAssigneeAgentId: persistedLink2.followThroughAssigneeAgentId } : {},
14668
+ ...persistedLink2.followThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt: persistedLink2.followThroughAssigneeUpdatedAt } : {},
14669
+ alreadyLinked: Boolean(existingLink && existingIssue)
14670
+ };
14671
+ }
14672
+ const requestedTitle = typeof input.title === "string" && input.title.trim() ? input.title.trim() : pullRequest.title.trim();
14673
+ const createdIssue = await ensurePaperclipIssueStandardWorkMode(
14674
+ ctx,
14675
+ await ctx.issues.create({
14676
+ companyId: scope.companyId,
14677
+ projectId: scope.projectId,
14678
+ title: requestedTitle,
14679
+ status: "todo",
14680
+ originKind: GITHUB_PULL_REQUEST_ORIGIN_KIND,
14681
+ originId: pullRequestUrl,
14682
+ description: buildPaperclipIssueDescriptionFromPullRequest({
14683
+ repository: scope.repository,
14684
+ pullRequestNumber,
14685
+ pullRequestUrl,
14686
+ body: pullRequest.body
14687
+ })
14688
+ }),
14689
+ scope.companyId
14690
+ );
14691
+ const resolvedIssue = await ctx.issues.get(createdIssue.id, scope.companyId) ?? createdIssue;
14692
+ const persistedLink = await upsertGitHubPullRequestLinkRecord(ctx, {
14693
+ companyId: scope.companyId,
14694
+ projectId: scope.projectId,
14695
+ issueId: resolvedIssue.id,
14696
+ repositoryUrl: scope.repository.url,
14697
+ pullRequestNumber,
14698
+ pullRequestUrl,
14699
+ pullRequestTitle: pullRequest.title,
14700
+ pullRequestState,
14701
+ followThroughAssigneeAgentId
14702
+ });
14703
+ invalidateProjectPullRequestCaches(scope);
14704
+ return {
14705
+ paperclipIssueId: resolvedIssue.id,
14706
+ ...resolvedIssue.identifier ? { paperclipIssueKey: resolvedIssue.identifier } : {},
14707
+ ...persistedLink.followThroughAssigneeAgentId ? { followThroughAssigneeAgentId: persistedLink.followThroughAssigneeAgentId } : {},
14708
+ ...persistedLink.followThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt: persistedLink.followThroughAssigneeUpdatedAt } : {},
14709
+ alreadyLinked: false
14710
+ };
14321
14711
  });
14322
- invalidateProjectPullRequestCaches(scope);
14323
- return {
14324
- paperclipIssueId: resolvedIssue.id,
14325
- ...resolvedIssue.identifier ? { paperclipIssueKey: resolvedIssue.identifier } : {},
14326
- alreadyLinked: false
14327
- };
14328
14712
  }
14329
14713
  async function refreshProjectPullRequests(ctx, input) {
14330
14714
  const scope = await requireProjectPullRequestScope(ctx, input);
@@ -16355,7 +16739,33 @@ function registerGitHubAgentTools(ctx) {
16355
16739
  getGitHubAgentToolDeclaration("update_issue"),
16356
16740
  async (params, runCtx) => executeTrackedGitHubMutation(ctx, "update_issue", params, runCtx, async () => {
16357
16741
  const input = getToolInputRecord(params);
16742
+ const state = input.state === "open" || input.state === "closed" ? input.state : void 0;
16743
+ const stateReason = input.stateReason === "completed" || input.stateReason === "not_planned" || input.stateReason === "duplicate" || input.stateReason === "reopened" ? input.stateReason : void 0;
16744
+ const stateReasonRequested = Object.prototype.hasOwnProperty.call(input, "stateReason");
16745
+ const duplicateIssueNumberRequested = Object.prototype.hasOwnProperty.call(input, "duplicateIssueNumber");
16746
+ const duplicateIssueNumber = duplicateIssueNumberRequested ? normalizeToolPositiveInteger(input.duplicateIssueNumber) : void 0;
16747
+ if (stateReasonRequested && !stateReason) {
16748
+ throw new Error("stateReason must be completed, not_planned, duplicate, or reopened.");
16749
+ }
16750
+ if (stateReason && !state) {
16751
+ throw new Error("stateReason requires state.");
16752
+ }
16753
+ if (stateReason === "reopened" && state !== "open") {
16754
+ throw new Error("stateReason reopened requires state=open.");
16755
+ }
16756
+ if (stateReason && stateReason !== "reopened" && state !== "closed") {
16757
+ throw new Error(`stateReason ${stateReason} requires state=closed.`);
16758
+ }
16759
+ if (stateReason === "duplicate" && duplicateIssueNumber === void 0) {
16760
+ throw new Error("stateReason duplicate requires duplicateIssueNumber.");
16761
+ }
16762
+ if (duplicateIssueNumberRequested && stateReason !== "duplicate") {
16763
+ throw new Error("duplicateIssueNumber requires stateReason=duplicate.");
16764
+ }
16358
16765
  const target = await resolveGitHubIssueToolTarget(ctx, runCtx, input);
16766
+ if (duplicateIssueNumber === target.issueNumber) {
16767
+ throw new Error("An issue cannot be marked as a duplicate of itself.");
16768
+ }
16359
16769
  const octokit = await createAgentToolOctokit(runCtx, "update_issue", target.repository);
16360
16770
  const currentResponse = await octokit.rest.issues.get({
16361
16771
  owner: target.repository.owner,
@@ -16381,11 +16791,30 @@ function registerGitHubAgentTools(ctx) {
16381
16791
  const title = Object.prototype.hasOwnProperty.call(input, "title") && typeof input.title === "string" ? input.title : void 0;
16382
16792
  const llmModel = normalizeOptionalToolString(input.llmModel);
16383
16793
  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
16794
  const milestoneNumber = Object.prototype.hasOwnProperty.call(input, "milestoneNumber") ? input.milestoneNumber === null ? null : normalizeToolPositiveInteger(input.milestoneNumber) : void 0;
16386
16795
  const milestoneRequested = Object.prototype.hasOwnProperty.call(input, "milestoneNumber");
16387
16796
  const currentMilestoneNumber = currentIssue.milestone?.number ?? null;
16797
+ const currentStateReason = normalizeGitHubIssueStateReason(currentIssue.state_reason);
16798
+ if (stateReason && state === currentIssue.state && state === "closed" && stateReason !== currentStateReason) {
16799
+ throw new Error(
16800
+ `GitHub only applies stateReason when state changes; reopen issue #${target.issueNumber} before closing it as ${stateReason}.`
16801
+ );
16802
+ }
16803
+ if (stateReason === "duplicate" && state === currentIssue.state && currentStateReason === "duplicate") {
16804
+ throw new Error(
16805
+ `GitHub does not expose the current canonical duplicate target; reopen issue #${target.issueNumber} before marking it as a duplicate again.`
16806
+ );
16807
+ }
16808
+ const effectiveStateReason = state === currentIssue.state ? currentStateReason : stateReason;
16388
16809
  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);
16810
+ const duplicateIssueId = hasChanges && stateReason === "duplicate" && duplicateIssueNumber !== void 0 ? (await octokit.rest.issues.get({
16811
+ owner: target.repository.owner,
16812
+ repo: target.repository.repo,
16813
+ issue_number: duplicateIssueNumber,
16814
+ headers: {
16815
+ "X-GitHub-Api-Version": GITHUB_API_VERSION
16816
+ }
16817
+ })).data.id : void 0;
16389
16818
  const updatedResponse = hasChanges ? await octokit.rest.issues.update({
16390
16819
  owner: target.repository.owner,
16391
16820
  repo: target.repository.repo,
@@ -16393,6 +16822,8 @@ function registerGitHubAgentTools(ctx) {
16393
16822
  ...title !== void 0 ? { title } : {},
16394
16823
  ...body !== void 0 ? { body } : {},
16395
16824
  ...state ? { state } : {},
16825
+ ...stateReason ? { state_reason: stateReason } : {},
16826
+ ...duplicateIssueId !== void 0 ? { duplicate_issue_id: duplicateIssueId } : {},
16396
16827
  ...milestoneRequested ? { milestone: milestoneNumber } : {},
16397
16828
  labels: nextLabels,
16398
16829
  assignees: nextAssignees,
@@ -16411,7 +16842,7 @@ function registerGitHubAgentTools(ctx) {
16411
16842
  body: updatedIssue.body,
16412
16843
  url: updatedIssue.htmlUrl,
16413
16844
  state: updatedIssue.state,
16414
- stateReason: updatedIssue.stateReason,
16845
+ stateReason: updatedIssue.stateReason ?? effectiveStateReason,
16415
16846
  labels: normalizeGitHubIssueLabels(updatedResponse.data.labels),
16416
16847
  assignees: (updatedResponse.data.assignees ?? []).map((assignee) => assignee?.login ?? "").filter(Boolean),
16417
16848
  milestone: updatedResponse.data.milestone ? {
@@ -16537,6 +16968,11 @@ function registerGitHubAgentTools(ctx) {
16537
16968
  if (!issue) {
16538
16969
  throw new Error("Paperclip issue was not found.");
16539
16970
  }
16971
+ const followThroughAssigneeAgentId = await validateFollowThroughAssigneeAgentId(
16972
+ ctx,
16973
+ runCtx.companyId,
16974
+ input.followThroughAssigneeAgentId
16975
+ );
16540
16976
  const issueProjectId = normalizeOptionalToolString(issue.projectId);
16541
16977
  if (!issueProjectId || issueProjectId !== runCtx.projectId) {
16542
16978
  throw new Error("The selected Paperclip issue does not belong to the current tool run project.");
@@ -16630,9 +17066,11 @@ function registerGitHubAgentTools(ctx) {
16630
17066
  }
16631
17067
  pullRequestData = existingPullRequest;
16632
17068
  }
17069
+ let persistedFollowThroughAssigneeAgentId = followThroughAssigneeAgentId ?? void 0;
17070
+ let persistedFollowThroughAssigneeUpdatedAt;
16633
17071
  if (paperclipIssueId) {
16634
17072
  const pullRequestUrl = normalizeGitHubPullRequestHtmlUrl(pullRequestData.html_url) ?? `${repository.url}/pull/${pullRequestData.number}`;
16635
- await upsertGitHubPullRequestLinkRecord(ctx, {
17073
+ const persistedLink = await upsertGitHubPullRequestLinkRecord(ctx, {
16636
17074
  companyId: runCtx.companyId,
16637
17075
  projectId: issueProjectId,
16638
17076
  issueId: paperclipIssueId,
@@ -16643,8 +17081,11 @@ function registerGitHubAgentTools(ctx) {
16643
17081
  pullRequestState: getGitHubPullRequestStateForLink({
16644
17082
  state: pullRequestData.state,
16645
17083
  merged: false
16646
- })
17084
+ }),
17085
+ followThroughAssigneeAgentId
16647
17086
  });
17087
+ persistedFollowThroughAssigneeAgentId = persistedLink.followThroughAssigneeAgentId;
17088
+ persistedFollowThroughAssigneeUpdatedAt = persistedLink.followThroughAssigneeUpdatedAt;
16648
17089
  invalidateProjectPullRequestCaches({
16649
17090
  companyId: runCtx.companyId,
16650
17091
  projectId: issueProjectId,
@@ -16673,6 +17114,10 @@ function registerGitHubAgentTools(ctx) {
16673
17114
  commitSha: publishedBranch.commitSha,
16674
17115
  remoteRef: publishedBranch.remoteRef
16675
17116
  },
17117
+ ...persistedFollowThroughAssigneeAgentId ? {
17118
+ followThroughAssigneeAgentId: persistedFollowThroughAssigneeAgentId,
17119
+ ...persistedFollowThroughAssigneeUpdatedAt ? { followThroughAssigneeUpdatedAt: persistedFollowThroughAssigneeUpdatedAt } : {}
17120
+ } : {},
16676
17121
  pullRequest: {
16677
17122
  number: pullRequestData.number,
16678
17123
  title: pullRequestData.title,
@@ -17206,7 +17651,8 @@ function registerGitHubAgentTools(ctx) {
17206
17651
  repositoryUrl: normalizeOptionalToolString(input.repository),
17207
17652
  pullRequestNumber: input.pullRequestNumber,
17208
17653
  pullRequestUrl: input.pullRequestUrl,
17209
- allowUnmapped: true
17654
+ allowUnmapped: true,
17655
+ followThroughAssigneeAgentId: input.followThroughAssigneeAgentId
17210
17656
  });
17211
17657
  const itemLabel = kind === "issue" ? `issue #${normalizeToolPositiveInteger(linkResult.githubIssueNumber) ?? ""}`.trim() : `pull request #${normalizeToolPositiveInteger(linkResult.githubPullRequestNumber) ?? ""}`.trim();
17212
17658
  return buildToolSuccessResult(
@@ -17241,6 +17687,7 @@ function shouldStartWorkerHost(moduleUrl, entry = process.argv[1]) {
17241
17687
  var __testing = {
17242
17688
  buildDirectPullRequestActionFingerprint,
17243
17689
  buildRemoteActionFingerprint,
17690
+ canReservePendingWake,
17244
17691
  canonicalizeGitHubPullRequestCommentCounts,
17245
17692
  buildSyncFallbackExecutionStatePatch,
17246
17693
  createGitHubToolOctokit,
@@ -17248,17 +17695,24 @@ var __testing = {
17248
17695
  hasUnresolvedPaperclipIssueBlocker,
17249
17696
  isHealthyMaintainerWaitTransition,
17250
17697
  isPaperclipIssuePatchApplied,
17698
+ listTrustedNewLinkedPullRequestCommentSources,
17251
17699
  normalizePaperclipIssueAssigneePrincipal,
17252
17700
  normalizeImportRegistry,
17253
17701
  normalizeRemoteActionRegistry,
17254
17702
  persistIssueInteractionEvent,
17255
17703
  trackedMutationOutcome,
17704
+ selectHighestPriorityEffectivePullRequestGate,
17705
+ selectEffectiveDirectPullRequestGate,
17706
+ selectEffectiveIssueLinkedPullRequestAction,
17707
+ selectEffectiveIssueLinkedPullRequestGate,
17256
17708
  resolvePaperclipApiAuthTokens,
17257
17709
  resolveGithubToken,
17710
+ resolvePaperclipIssueStatus,
17258
17711
  resolvePaperclipPullRequestIssueStatus,
17259
17712
  resolveSyncTransitionAssignee,
17260
17713
  resolveTrustedWorkspacePath,
17261
17714
  updatePaperclipIssueState,
17715
+ upsertGitHubPullRequestLinkRecord,
17262
17716
  wakePaperclipIssueAssignee,
17263
17717
  setCreatePullRequestBranchPublisher(publisher) {
17264
17718
  createPullRequestBranchPublisher = publisher ?? publishLocalBranchForPullRequest;
@@ -17275,11 +17729,14 @@ var plugin = definePlugin({
17275
17729
  const saved = await ctx.state.get(SETTINGS_SCOPE);
17276
17730
  const importRegistry = normalizeImportRegistry(await ctx.state.get(IMPORT_REGISTRY_SCOPE));
17277
17731
  const normalizedSettings = normalizeSettings(saved);
17278
- const config = await getResolvedConfig(ctx);
17732
+ const [config, trustedConfig] = await Promise.all([
17733
+ getResolvedConfig(ctx),
17734
+ ctx.config.get().then((value) => normalizeConfig(value))
17735
+ ]);
17279
17736
  const githubTokenConfigured = hasConfiguredGithubToken(normalizedSettings, config, requestedCompanyId);
17280
- const configuredGitHubTokenRef = getConfiguredGitHubTokenRef(config, requestedCompanyId);
17737
+ const configuredGitHubTokenRef = getConfiguredGitHubTokenRef(trustedConfig, requestedCompanyId);
17281
17738
  const savedGitHubTokenRef = getSavedGitHubTokenRef(normalizedSettings, requestedCompanyId);
17282
- const configuredBoardTokenRef = getConfiguredPaperclipBoardApiTokenRef(config, requestedCompanyId);
17739
+ const configuredBoardTokenRef = getConfiguredPaperclipBoardApiTokenRef(trustedConfig, requestedCompanyId);
17283
17740
  const savedBoardTokenRef = getSavedPaperclipBoardApiTokenRef(normalizedSettings, requestedCompanyId);
17284
17741
  const settingsForResponse = sanitizeSettingsForCurrentSetup(
17285
17742
  materializeScopedSettings(normalizedSettings, config, requestedCompanyId),
@@ -17303,7 +17760,9 @@ var plugin = definePlugin({
17303
17760
  ...savedGitHubTokenRef ? { githubTokenConfigSyncRef: savedGitHubTokenRef } : {},
17304
17761
  githubTokenNeedsConfigSync: Boolean(savedGitHubTokenRef && configuredGitHubTokenRef !== savedGitHubTokenRef),
17305
17762
  ...savedBoardTokenRef ? { paperclipBoardAccessConfigSyncRef: savedBoardTokenRef } : {},
17306
- paperclipBoardAccessNeedsConfigSync: Boolean(savedBoardTokenRef && !configuredBoardTokenRef)
17763
+ paperclipBoardAccessNeedsConfigSync: Boolean(
17764
+ savedBoardTokenRef && configuredBoardTokenRef !== savedBoardTokenRef
17765
+ )
17307
17766
  };
17308
17767
  });
17309
17768
  ctx.data.register("dashboard.metrics", async (input) => {
@@ -17375,7 +17834,8 @@ var plugin = definePlugin({
17375
17834
  repositoryUrl: normalizeOptionalString2(record.repository),
17376
17835
  pullRequestNumber: record.pullRequestNumber,
17377
17836
  pullRequestUrl: record.pullRequestUrl,
17378
- requireUnlinked: true
17837
+ requireUnlinked: true,
17838
+ followThroughAssigneeAgentId: record.followThroughAssigneeAgentId
17379
17839
  });
17380
17840
  });
17381
17841
  ctx.actions.register("issue.unlinkGitHubItem", async (input, actionContext) => {