paperclip-github-plugin 0.15.2 → 0.15.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -63,6 +63,8 @@ If a company already has a Paperclip project bound to a GitHub repository worksp
63
63
 
64
64
  The plugin does more than mirror issue text. It looks at linked pull requests, mergeability, CI, review decisions, review threads, and trusted new GitHub comments so imported Paperclip issues can reflect where the work actually is. When GitHub links an issue to a pull request in another repository, GitHub Sync now follows that pull request's actual repository for status checks, review state, and deep links instead of assuming the issue repository. When sync closes an imported issue as `done` or `cancelled`, it also clears any pending Paperclip review or approval execution policy/state so the host accepts the terminal transition cleanly and does not keep waking stale review participants.
65
65
 
66
+ Sync-driven transitions use a phase-aware durable action journal keyed by a fixed-length hash of the Paperclip issue, effective remote action, comment watermarks, and target state. A retry reuses an already completed explanatory comment or issue mutation instead of repeating it. If the worker can see an intent but cannot prove whether the corresponding side effect completed, it fails closed for operator reconciliation rather than risking a duplicate comment or status write.
67
+
66
68
  ### Company KPI dashboard
67
69
 
68
70
  GitHub Sync exposes a dedicated KPI dashboard widget alongside the operational sync widget. During full company syncs, the worker snapshots the current open GitHub backlog and records when already-imported GitHub issues move from open to closed. The KPI widget turns that worker-owned state into backlog, issue-closure, and Paperclip PR-creation cards with recent history and comparisons against older periods.
package/dist/manifest.js CHANGED
@@ -675,7 +675,7 @@ var COMPANY_METRIC_API_ROUTE_URL_PATH = `/api/plugins/${GITHUB_SYNC_PLUGIN_ID}/a
675
675
  var require2 = createRequire(import.meta.url);
676
676
  var packageJson = require2("../package.json");
677
677
  var SCHEDULE_TICK_CRON = "* * * * *";
678
- var MANIFEST_VERSION = "0.15.2"?.trim() || typeof packageJson.version === "string" && packageJson.version.trim() || process.env.npm_package_version?.trim() || "0.0.0-dev";
678
+ var MANIFEST_VERSION = "0.15.4"?.trim() || typeof packageJson.version === "string" && packageJson.version.trim() || process.env.npm_package_version?.trim() || "0.0.0-dev";
679
679
  var manifest = {
680
680
  id: GITHUB_SYNC_PLUGIN_ID,
681
681
  apiVersion: 1,
package/dist/worker.js CHANGED
@@ -1163,7 +1163,7 @@ function buildIssueInteractionSummary(input) {
1163
1163
  const timestamp = Date.parse(entry.occurredAt);
1164
1164
  return timestamp >= fromMs && timestamp < toMs;
1165
1165
  }).sort((left, right) => left.occurredAt.localeCompare(right.occurredAt) || left.dedupeKey.localeCompare(right.dedupeKey));
1166
- const resultDedupeBases = new Set(events.filter((entry) => entry.dedupeKey.endsWith(":result")).map((entry) => entry.dedupeKey.slice(0, -":result".length)));
1166
+ const resultDedupeBases = new Set(events.filter((entry) => /:result(?::(?:changed|noop|failed))?$/.test(entry.dedupeKey)).map((entry) => entry.dedupeKey.replace(/:result(?::(?:changed|noop|failed))?$/, "")));
1167
1167
  const uncertainAttempts = events.filter((entry) => entry.outcome === "observed" && entry.dedupeKey.endsWith(":intent") && !resultDedupeBases.has(entry.dedupeKey.slice(0, -":intent".length)));
1168
1168
  const runIds = new Set(events.map((entry) => entry.actor?.runId).filter((value) => Boolean(value)));
1169
1169
  const actionCounts = /* @__PURE__ */ new Map();
@@ -1474,6 +1474,11 @@ var SyncCancellationError = class extends Error {
1474
1474
  this.requestedAt = requestedAt;
1475
1475
  }
1476
1476
  };
1477
+ function canonicalizeGitHubPullRequestCommentCounts(records) {
1478
+ return [...records].sort(
1479
+ (left, right) => left.repositoryUrl.localeCompare(right.repositoryUrl) || left.number - right.number
1480
+ );
1481
+ }
1477
1482
  var SUCCESSFUL_CHECK_RUN_CONCLUSIONS = /* @__PURE__ */ new Set(["SUCCESS", "NEUTRAL", "SKIPPED"]);
1478
1483
  var FAILED_CHECK_RUN_CONCLUSIONS = /* @__PURE__ */ new Set([
1479
1484
  "ACTION_REQUIRED",
@@ -5994,6 +5999,11 @@ function normalizePaperclipIssueAssigneePrincipal(value) {
5994
5999
  return null;
5995
6000
  }
5996
6001
  const record = value;
6002
+ const normalizedKind = normalizeOptionalString2(record.kind);
6003
+ const normalizedId = normalizeOptionalString2(record.id);
6004
+ if ((normalizedKind === "agent" || normalizedKind === "user") && normalizedId) {
6005
+ return { kind: normalizedKind, id: normalizedId };
6006
+ }
5997
6007
  const principalType = normalizeOptionalString2(record.type);
5998
6008
  const agentId = normalizeOptionalString2(record.agentId);
5999
6009
  const userId = normalizeOptionalString2(record.userId);
@@ -6314,9 +6324,6 @@ function isClearableMaintainerWaitExecutionState(executionState) {
6314
6324
  }
6315
6325
  return !executionState.status || executionState.status === "idle" || executionState.status === "completed";
6316
6326
  }
6317
- function shouldClearCompletedSyncExecutionPolicy(params) {
6318
- return (params.nextStatus === "done" || params.nextStatus === "cancelled") && (params.syncContext.executionPolicy !== null || params.syncContext.executionState !== null);
6319
- }
6320
6327
  function shouldPreserveImportedTriageAssignee(params) {
6321
6328
  return params.wasImportedThisRun && params.maintainerAuthoredImportedIssue === true && params.currentStatus === "backlog" && params.nextStatus === "todo";
6322
6329
  }
@@ -8627,6 +8634,20 @@ async function unlinkPaperclipIssueFromGitHub(ctx, params) {
8627
8634
  (entry) => !(entry.paperclipIssueId === issueId && (!entry.companyId || entry.companyId === companyId))
8628
8635
  );
8629
8636
  const unlinkedAt = (/* @__PURE__ */ new Date()).toISOString();
8637
+ const shouldClearGitHubOrigin = issue.originKind === GITHUB_ISSUE_ORIGIN_KIND || issue.originKind === GITHUB_PULL_REQUEST_ORIGIN_KIND;
8638
+ const nextDescription = removeGitHubIssueLinkMetadataFromDescription(issue.description);
8639
+ const issuePatch = {};
8640
+ if (shouldClearGitHubOrigin) {
8641
+ issuePatch.originKind = GITHUB_SYNC_BASE_ORIGIN_KIND;
8642
+ issuePatch.originId = null;
8643
+ issuePatch.originRunId = null;
8644
+ }
8645
+ if (nextDescription !== void 0) {
8646
+ issuePatch.description = nextDescription;
8647
+ }
8648
+ if (Object.keys(issuePatch).length > 0) {
8649
+ await ctx.issues.update(issueId, issuePatch, companyId);
8650
+ }
8630
8651
  for (const record of issueLinkRecords) {
8631
8652
  await tombstoneGitHubIssueLinkRecord(ctx, record, unlinkedAt);
8632
8653
  invalidateGitHubLinkCachesForTarget({
@@ -8653,20 +8674,6 @@ async function unlinkPaperclipIssueFromGitHub(ctx, params) {
8653
8674
  if (removedImportRegistryEntries.length > 0) {
8654
8675
  await ctx.state.set(IMPORT_REGISTRY_SCOPE, nextImportRegistry);
8655
8676
  }
8656
- const shouldClearGitHubOrigin = issue.originKind === GITHUB_ISSUE_ORIGIN_KIND || issue.originKind === GITHUB_PULL_REQUEST_ORIGIN_KIND;
8657
- const nextDescription = removeGitHubIssueLinkMetadataFromDescription(issue.description);
8658
- const issuePatch = {};
8659
- if (shouldClearGitHubOrigin) {
8660
- issuePatch.originKind = GITHUB_SYNC_BASE_ORIGIN_KIND;
8661
- issuePatch.originId = null;
8662
- issuePatch.originRunId = null;
8663
- }
8664
- if (nextDescription !== void 0) {
8665
- issuePatch.description = nextDescription;
8666
- }
8667
- if (Object.keys(issuePatch).length > 0) {
8668
- await ctx.issues.update(issueId, issuePatch, companyId);
8669
- }
8670
8677
  await forgetExternalGitHubLinkCompanyIfEmpty(ctx, companyId);
8671
8678
  return {
8672
8679
  paperclipIssueId: issueId,
@@ -9645,6 +9652,23 @@ function classifyIssueInteractionReason(value) {
9645
9652
  if (reason.includes("open with no linked pull request")) return "issue_ready_for_triage";
9646
9653
  return "github_sync_status_decision";
9647
9654
  }
9655
+ function isPaperclipIssuePatchApplied(params) {
9656
+ const { currentStatus, syncContext, issuePatch } = params;
9657
+ if (issuePatch.status !== currentStatus) return false;
9658
+ const hasAgentAssignee = Object.prototype.hasOwnProperty.call(issuePatch, "assigneeAgentId");
9659
+ const hasUserAssignee = Object.prototype.hasOwnProperty.call(issuePatch, "assigneeUserId");
9660
+ if (hasAgentAssignee || hasUserAssignee) {
9661
+ const expectedAssignee = typeof issuePatch.assigneeAgentId === "string" ? { kind: "agent", id: issuePatch.assigneeAgentId } : typeof issuePatch.assigneeUserId === "string" ? { kind: "user", id: issuePatch.assigneeUserId } : null;
9662
+ if (JSON.stringify(syncContext.assignee) !== JSON.stringify(expectedAssignee)) return false;
9663
+ }
9664
+ if (Object.prototype.hasOwnProperty.call(issuePatch, "executionPolicy") && JSON.stringify(syncContext.executionPolicy) !== JSON.stringify(
9665
+ normalizePaperclipIssueExecutionPolicy(issuePatch.executionPolicy)
9666
+ )) return false;
9667
+ if (Object.prototype.hasOwnProperty.call(issuePatch, "executionState") && JSON.stringify(syncContext.executionState) !== JSON.stringify(
9668
+ normalizePaperclipIssueExecutionState(issuePatch.executionState)
9669
+ )) return false;
9670
+ return true;
9671
+ }
9648
9672
  async function updatePaperclipIssueState(ctx, params) {
9649
9673
  const {
9650
9674
  companyId,
@@ -9657,12 +9681,14 @@ async function updatePaperclipIssueState(ctx, params) {
9657
9681
  clearExecutionPolicy,
9658
9682
  transitionComment,
9659
9683
  transitionCommentAnnotation,
9684
+ actionFingerprint,
9660
9685
  paperclipApiBaseUrl
9661
9686
  } = params;
9662
9687
  const trimmedTransitionComment = transitionComment.trim();
9663
- const interactionOccurredAt = (/* @__PURE__ */ new Date()).toISOString();
9688
+ let interactionOccurredAt = (/* @__PURE__ */ new Date()).toISOString();
9664
9689
  const statusWillChange = currentStatus !== nextStatus;
9665
9690
  let createdTransitionComment = null;
9691
+ let transitionCommentComplete = false;
9666
9692
  let issueUpdated = false;
9667
9693
  const syncExecutionStatePatch = buildSyncFallbackExecutionStatePatch({
9668
9694
  currentStatus,
@@ -9693,8 +9719,72 @@ async function updatePaperclipIssueState(ctx, params) {
9693
9719
  if (statusWillChange && typeof ctx.issues.createComment !== "function") {
9694
9720
  throw new Error("This Paperclip runtime does not expose issue comment creation, so GitHub Sync refused to update a Paperclip issue status without an explanatory comment.");
9695
9721
  }
9722
+ const liveIssue = await ctx.issues.get(issueId, companyId);
9723
+ const liveCurrentStatus = liveIssue?.status ?? currentStatus;
9724
+ const liveSyncContext = liveIssue ? getPaperclipIssueSyncContext(liveIssue) : syncContext;
9725
+ const issuePatchAlreadyApplied = isPaperclipIssuePatchApplied({
9726
+ currentStatus: liveCurrentStatus,
9727
+ syncContext: liveSyncContext,
9728
+ issuePatch
9729
+ });
9696
9730
  const reasonCode = classifyIssueInteractionReason(transitionCommentAnnotation?.reason ?? trimmedTransitionComment);
9697
- const interactionDedupeBase = `sync:${issueId}:${interactionOccurredAt}:${currentStatus}:${nextStatus}`;
9731
+ const interactionDedupeBase = actionFingerprint ? `sync:${createHash("sha256").update(JSON.stringify({
9732
+ companyId,
9733
+ issueId,
9734
+ mutation: "status_transition",
9735
+ actionFingerprint,
9736
+ currentStatus,
9737
+ nextStatus,
9738
+ currentIssueState: syncContext,
9739
+ issuePatch
9740
+ })).digest("hex")}` : `sync:${issueId}:${interactionOccurredAt}:${currentStatus}:${nextStatus}`;
9741
+ const mutationFamilyBase = actionFingerprint ? `sync:${createHash("sha256").update(JSON.stringify({
9742
+ companyId,
9743
+ issueId,
9744
+ mutation: "status_transition",
9745
+ actionFingerprint,
9746
+ nextStatus
9747
+ })).digest("hex")}` : interactionDedupeBase;
9748
+ const hasAssigneePatch = Object.prototype.hasOwnProperty.call(issuePatch, "assigneeAgentId") || Object.prototype.hasOwnProperty.call(issuePatch, "assigneeUserId");
9749
+ const mutationExpectedState = {
9750
+ status: issuePatch.status ?? liveCurrentStatus,
9751
+ assignee: hasAssigneePatch ? normalizePaperclipIssueAssigneePrincipal({
9752
+ agentId: issuePatch.assigneeAgentId,
9753
+ userId: issuePatch.assigneeUserId
9754
+ }) : liveSyncContext.assignee,
9755
+ executionPolicy: Object.prototype.hasOwnProperty.call(issuePatch, "executionPolicy") ? normalizePaperclipIssueExecutionPolicy(issuePatch.executionPolicy) : liveSyncContext.executionPolicy,
9756
+ executionState: Object.prototype.hasOwnProperty.call(issuePatch, "executionState") ? normalizePaperclipIssueExecutionState(issuePatch.executionState) : liveSyncContext.executionState
9757
+ };
9758
+ const liveMutationState = {
9759
+ status: liveCurrentStatus,
9760
+ assignee: liveSyncContext.assignee,
9761
+ executionPolicy: liveSyncContext.executionPolicy,
9762
+ executionState: liveSyncContext.executionState
9763
+ };
9764
+ const mutationExpectedStateFingerprint = createHash("sha256").update(JSON.stringify(mutationExpectedState)).digest("hex").slice(0, 32);
9765
+ 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
+ let existingInteractionEvents = [];
9768
+ if (actionFingerprint) {
9769
+ const ledger = await listIssueInteractionEvents(ctx, companyId, issueId, {
9770
+ from: "1970-01-01T00:00:00.000Z",
9771
+ to: "9999-12-31T23:59:59.999Z"
9772
+ });
9773
+ if (ledger.integrity.malformedRows > 0 || ledger.integrity.conflictingKeys > 0 || ledger.integrity.scanTruncated) {
9774
+ throw new Error("GitHub Sync refused a status transition because its issue interaction ledger is incomplete or conflicting.");
9775
+ }
9776
+ existingInteractionEvents = ledger.events;
9777
+ const existingIntent = existingInteractionEvents.find((event) => event.dedupeKey === `${interactionDedupeBase}:intent`);
9778
+ if (existingIntent) interactionOccurredAt = existingIntent.occurredAt;
9779
+ }
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;
9698
9788
  await persistIssueInteractionEvent(ctx, {
9699
9789
  schemaVersion: 1,
9700
9790
  companyId,
@@ -9733,104 +9823,197 @@ async function updatePaperclipIssueState(ctx, params) {
9733
9823
  } : {},
9734
9824
  transition: { from: currentStatus, to: nextStatus, reasonCode },
9735
9825
  outcome,
9736
- dedupeKey: `${interactionDedupeBase}:result`
9826
+ dedupeKey: `${interactionDedupeBase}:result:${outcome}`
9737
9827
  });
9828
+ const persistMutationPhase = (outcome, dedupeBase = mutationDedupeBase) => persistIssueInteractionEvent(ctx, {
9829
+ schemaVersion: 1,
9830
+ companyId,
9831
+ paperclipIssueId: issueId,
9832
+ occurredAt: interactionOccurredAt,
9833
+ category: "sync",
9834
+ action: "update_issue",
9835
+ source: "sync",
9836
+ ...transitionCommentAnnotation ? {
9837
+ remote: {
9838
+ repositoryUrl: transitionCommentAnnotation.repositoryUrl,
9839
+ kind: "issue",
9840
+ number: transitionCommentAnnotation.githubIssueNumber,
9841
+ url: transitionCommentAnnotation.githubIssueUrl
9842
+ }
9843
+ } : {},
9844
+ outcome,
9845
+ dedupeKey: `${dedupeBase}:mutation:${outcome === "observed" ? "intent" : `result:${outcome}`}`
9846
+ });
9847
+ const priorMutationIntent = existingInteractionEvents.find((event) => event.dedupeKey === `${mutationDedupeBase}:mutation:intent`);
9848
+ const priorMutationChanged = existingInteractionEvents.find((event) => event.dedupeKey === `${mutationDedupeBase}:mutation:result:changed`);
9849
+ const priorMutationFailed = existingInteractionEvents.find((event) => event.dedupeKey === `${mutationDedupeBase}:mutation:result:failed`);
9850
+ let mutationAttemptStarted = false;
9851
+ let mutationReturned = false;
9852
+ let mutationComplete = issuePatchAlreadyApplied;
9853
+ if (issuePatchAlreadyApplied) {
9854
+ const intentSuffix = ":mutation:intent";
9855
+ for (const intent of existingInteractionEvents.filter(
9856
+ (event) => event.dedupeKey.startsWith(`${mutationFamilyBase}:`) && event.dedupeKey.includes(`:applied:${liveMutationStateFingerprint}:`) && event.dedupeKey.endsWith(intentSuffix)
9857
+ )) {
9858
+ const dedupeBase = intent.dedupeKey.slice(0, -intentSuffix.length);
9859
+ const hasResult = existingInteractionEvents.some(
9860
+ (event) => event.dedupeKey === `${dedupeBase}:mutation:result:changed` || event.dedupeKey === `${dedupeBase}:mutation:result:failed`
9861
+ );
9862
+ if (!hasResult) await persistMutationPhase("changed", dedupeBase);
9863
+ }
9864
+ }
9738
9865
  try {
9739
9866
  if (statusWillChange) {
9740
- createdTransitionComment = await ctx.issues.createComment(issueId, trimmedTransitionComment, companyId);
9741
- }
9742
- if (paperclipApiBaseUrl) {
9743
- try {
9744
- const response = await fetchPaperclipApi(
9745
- getPaperclipIssueEndpoint(paperclipApiBaseUrl, issueId),
9746
- {
9747
- method: "PATCH",
9748
- headers: {
9749
- accept: "application/json",
9750
- "content-type": "application/json"
9751
- },
9752
- body: JSON.stringify(issuePatch)
9753
- },
9754
- {
9755
- companyId
9756
- }
9757
- );
9758
- const payloadResult = await readPaperclipApiJsonResponse(response, {
9759
- operationLabel: "issue update",
9760
- bodyRequired: false
9867
+ const commentIntentKey = `${interactionDedupeBase}:comment:intent`;
9868
+ const commentChangedKey = `${interactionDedupeBase}:comment:result:changed`;
9869
+ const priorCommentIntent = existingInteractionEvents.find((event) => event.dedupeKey === commentIntentKey);
9870
+ const priorCommentChanged = existingInteractionEvents.find((event) => event.dedupeKey === commentChangedKey);
9871
+ if (priorCommentChanged) {
9872
+ transitionCommentComplete = true;
9873
+ } else if (priorCommentIntent) {
9874
+ throw new Error("GitHub Sync refused to repeat an uncertain transition comment; reconcile the durable interaction intent before retrying.");
9875
+ } else {
9876
+ const commentEventBase = {
9877
+ schemaVersion: 1,
9878
+ companyId,
9879
+ paperclipIssueId: issueId,
9880
+ occurredAt: interactionOccurredAt,
9881
+ category: "comment",
9882
+ action: "add_issue_comment",
9883
+ source: "sync",
9884
+ ...transitionCommentAnnotation ? {
9885
+ remote: {
9886
+ repositoryUrl: transitionCommentAnnotation.repositoryUrl,
9887
+ kind: "issue",
9888
+ number: transitionCommentAnnotation.githubIssueNumber,
9889
+ url: transitionCommentAnnotation.githubIssueUrl
9890
+ }
9891
+ } : {}
9892
+ };
9893
+ await persistIssueInteractionEvent(ctx, {
9894
+ ...commentEventBase,
9895
+ outcome: "observed",
9896
+ dedupeKey: commentIntentKey
9761
9897
  });
9762
- if (!payloadResult.failure) {
9763
- issueUpdated = true;
9764
- if (issuePatch.executionState === null && ctx.issues && typeof ctx.issues.update === "function") {
9765
- try {
9766
- await ctx.issues.update(
9767
- issueId,
9768
- { executionState: null },
9769
- companyId
9770
- );
9771
- } catch (error) {
9772
- issueUpdated = false;
9773
- ctx.logger.warn("GitHub sync could not clear Paperclip issue execution state after the local API update. Falling back to direct issue mutation.", {
9898
+ try {
9899
+ createdTransitionComment = await ctx.issues.createComment(issueId, trimmedTransitionComment, companyId);
9900
+ if (transitionCommentAnnotation) {
9901
+ await upsertStatusTransitionCommentAnnotation(ctx, {
9902
+ issueId,
9903
+ commentId: createdTransitionComment.id,
9904
+ annotation: {
9905
+ ...transitionCommentAnnotation,
9774
9906
  companyId,
9775
- issueId,
9776
- paperclipApiBaseUrl,
9777
- nextStatus,
9778
- error: getErrorMessage(error)
9779
- });
9780
- }
9907
+ paperclipIssueId: issueId
9908
+ }
9909
+ });
9781
9910
  }
9911
+ await persistIssueInteractionEvent(ctx, {
9912
+ ...commentEventBase,
9913
+ outcome: "changed",
9914
+ dedupeKey: commentChangedKey
9915
+ });
9916
+ transitionCommentComplete = true;
9917
+ } catch (error) {
9918
+ await persistIssueInteractionEvent(ctx, {
9919
+ ...commentEventBase,
9920
+ outcome: "failed",
9921
+ dedupeKey: `${interactionDedupeBase}:comment:result:failed`
9922
+ });
9923
+ throw error;
9782
9924
  }
9783
- if (payloadResult.failure && (payloadResult.failure.status ?? response.status) !== 404 && (payloadResult.failure.status ?? response.status) !== 405) {
9925
+ }
9926
+ }
9927
+ if (!mutationComplete) {
9928
+ if (priorMutationIntent && !priorMutationChanged && !priorMutationFailed) {
9929
+ throw new Error("GitHub Sync refused to repeat an uncertain issue mutation; reconcile the durable mutation intent before retrying.");
9930
+ }
9931
+ await persistMutationPhase("observed");
9932
+ mutationAttemptStarted = true;
9933
+ if (paperclipApiBaseUrl) {
9934
+ try {
9935
+ const response = await fetchPaperclipApi(
9936
+ getPaperclipIssueEndpoint(paperclipApiBaseUrl, issueId),
9937
+ {
9938
+ method: "PATCH",
9939
+ headers: {
9940
+ accept: "application/json",
9941
+ "content-type": "application/json"
9942
+ },
9943
+ body: JSON.stringify(issuePatch)
9944
+ },
9945
+ {
9946
+ companyId
9947
+ }
9948
+ );
9949
+ const payloadResult = await readPaperclipApiJsonResponse(response, {
9950
+ operationLabel: "issue update",
9951
+ bodyRequired: false
9952
+ });
9953
+ if (!payloadResult.failure) {
9954
+ issueUpdated = true;
9955
+ if (issuePatch.executionState === null && ctx.issues && typeof ctx.issues.update === "function") {
9956
+ try {
9957
+ await ctx.issues.update(
9958
+ issueId,
9959
+ { executionState: null },
9960
+ companyId
9961
+ );
9962
+ } catch (error) {
9963
+ issueUpdated = false;
9964
+ ctx.logger.warn("GitHub sync could not clear Paperclip issue execution state after the local API update. Falling back to direct issue mutation.", {
9965
+ companyId,
9966
+ issueId,
9967
+ paperclipApiBaseUrl,
9968
+ nextStatus,
9969
+ error: getErrorMessage(error)
9970
+ });
9971
+ }
9972
+ }
9973
+ }
9974
+ if (payloadResult.failure && (payloadResult.failure.status ?? response.status) !== 404 && (payloadResult.failure.status ?? response.status) !== 405) {
9975
+ logPaperclipIssueStatusUpdateFailure(ctx, {
9976
+ companyId,
9977
+ issueId,
9978
+ paperclipApiBaseUrl,
9979
+ nextStatus,
9980
+ status: payloadResult.failure.status ?? response.status,
9981
+ errorMessage: payloadResult.failure.errorMessage
9982
+ });
9983
+ }
9984
+ } catch (error) {
9784
9985
  logPaperclipIssueStatusUpdateFailure(ctx, {
9785
9986
  companyId,
9786
9987
  issueId,
9787
9988
  paperclipApiBaseUrl,
9788
9989
  nextStatus,
9789
- status: payloadResult.failure.status ?? response.status,
9790
- errorMessage: payloadResult.failure.errorMessage
9990
+ errorMessage: getErrorMessage(error)
9791
9991
  });
9792
9992
  }
9793
- } catch (error) {
9794
- logPaperclipIssueStatusUpdateFailure(ctx, {
9795
- companyId,
9796
- issueId,
9797
- paperclipApiBaseUrl,
9798
- nextStatus,
9799
- errorMessage: getErrorMessage(error)
9800
- });
9801
9993
  }
9802
- }
9803
- if (!issueUpdated) {
9804
- const preserveExistingUserAssigneeWithoutLocalApi = nextAssignee?.kind === "user" && !paperclipApiBaseUrl;
9805
- const sdkIssuePatch = {
9806
- ...issuePatch,
9807
- ...syncExecutionStatePatch !== void 0 ? { executionState: syncExecutionStatePatch } : {}
9808
- };
9809
- if (preserveExistingUserAssigneeWithoutLocalApi) {
9810
- delete sdkIssuePatch.assigneeAgentId;
9811
- delete sdkIssuePatch.assigneeUserId;
9812
- ctx.logger.warn("GitHub sync could not reassign a Paperclip issue to a user without the local Paperclip API. Preserving the existing assignee.", {
9813
- companyId,
9814
- issueId,
9815
- nextStatus,
9816
- assigneeUserId: nextAssignee.id
9817
- });
9818
- }
9819
- await ctx.issues.update(issueId, sdkIssuePatch, companyId);
9820
- }
9821
- if (createdTransitionComment) {
9822
- if (transitionCommentAnnotation) {
9823
- await upsertStatusTransitionCommentAnnotation(ctx, {
9824
- issueId,
9825
- commentId: createdTransitionComment.id,
9826
- annotation: {
9827
- ...transitionCommentAnnotation,
9994
+ if (!issueUpdated) {
9995
+ const preserveExistingUserAssigneeWithoutLocalApi = nextAssignee?.kind === "user" && !paperclipApiBaseUrl;
9996
+ const sdkIssuePatch = {
9997
+ ...issuePatch,
9998
+ ...syncExecutionStatePatch !== void 0 ? { executionState: syncExecutionStatePatch } : {}
9999
+ };
10000
+ if (preserveExistingUserAssigneeWithoutLocalApi) {
10001
+ delete sdkIssuePatch.assigneeAgentId;
10002
+ delete sdkIssuePatch.assigneeUserId;
10003
+ ctx.logger.warn("GitHub sync could not reassign a Paperclip issue to a user without the local Paperclip API. Preserving the existing assignee.", {
9828
10004
  companyId,
9829
- paperclipIssueId: issueId
9830
- }
9831
- });
10005
+ issueId,
10006
+ nextStatus,
10007
+ assigneeUserId: nextAssignee.id
10008
+ });
10009
+ }
10010
+ await ctx.issues.update(issueId, sdkIssuePatch, companyId);
9832
10011
  }
9833
- } else if (trimmedTransitionComment && typeof ctx.issues.createComment === "function") {
10012
+ mutationReturned = true;
10013
+ await persistMutationPhase("changed");
10014
+ mutationComplete = true;
10015
+ }
10016
+ if (!statusWillChange && trimmedTransitionComment && typeof ctx.issues.createComment === "function") {
9834
10017
  const createdComment = await ctx.issues.createComment(issueId, trimmedTransitionComment, companyId);
9835
10018
  if (transitionCommentAnnotation) {
9836
10019
  await upsertStatusTransitionCommentAnnotation(ctx, {
@@ -9844,7 +10027,17 @@ async function updatePaperclipIssueState(ctx, params) {
9844
10027
  });
9845
10028
  }
9846
10029
  }
10030
+ if (statusWillChange && !transitionCommentComplete) {
10031
+ throw new Error("GitHub Sync refused to complete a status transition without a durable transition comment result.");
10032
+ }
9847
10033
  } catch (error) {
10034
+ if (mutationAttemptStarted && !mutationReturned) {
10035
+ try {
10036
+ await persistMutationPhase("failed");
10037
+ } catch (mutationLedgerError) {
10038
+ throw new AggregateError([error, mutationLedgerError], "GitHub Sync issue mutation failed and its mutation result could not be persisted.");
10039
+ }
10040
+ }
9848
10041
  try {
9849
10042
  await persistSyncResult("failed");
9850
10043
  } catch (ledgerError) {
@@ -10285,10 +10478,6 @@ async function cancelUnmappedTransferredGitHubIssue(ctx, params) {
10285
10478
  };
10286
10479
  }
10287
10480
  const paperclipIssueSyncContext = getPaperclipIssueSyncContext(paperclipIssue);
10288
- await unlinkPaperclipIssueFromGitHub(ctx, {
10289
- companyId,
10290
- issueId: params.importedIssue.paperclipIssueId
10291
- });
10292
10481
  const nextStatus = "cancelled";
10293
10482
  await updatePaperclipIssueState(ctx, {
10294
10483
  companyId,
@@ -10296,13 +10485,18 @@ async function cancelUnmappedTransferredGitHubIssue(ctx, params) {
10296
10485
  currentStatus: paperclipIssue.status,
10297
10486
  syncContext: paperclipIssueSyncContext,
10298
10487
  nextStatus,
10299
- transitionComment: buildUnmappedTransferredIssueCancellationComment({
10488
+ transitionComment: paperclipIssue.status === nextStatus ? "" : buildUnmappedTransferredIssueCancellationComment({
10300
10489
  previousStatus: paperclipIssue.status,
10301
10490
  nextStatus,
10302
10491
  transferredRepository: params.transferredRepository
10303
10492
  }),
10493
+ actionFingerprint: `transferred-unmapped:${params.transferredRepository.url}`,
10304
10494
  paperclipApiBaseUrl: params.paperclipApiBaseUrl
10305
10495
  });
10496
+ await unlinkPaperclipIssueFromGitHub(ctx, {
10497
+ companyId,
10498
+ issueId: params.importedIssue.paperclipIssueId
10499
+ });
10306
10500
  return {
10307
10501
  updatedStatusesCount: paperclipIssue.status === nextStatus ? 0 : 1
10308
10502
  };
@@ -10561,6 +10755,13 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10561
10755
  });
10562
10756
  const hasTrustedNewComment = hasTrustedNewIssueComment || hasTrustedNewLinkedPullRequestComment;
10563
10757
  const remoteActionFingerprint = buildRemoteActionFingerprint(snapshot);
10758
+ const actionJournalFingerprint = createHash("sha256").update(JSON.stringify({
10759
+ remoteActionFingerprint,
10760
+ issueCommentCount: snapshot.commentCount,
10761
+ linkedPullRequestCommentCounts: canonicalizeGitHubPullRequestCommentCounts(
10762
+ currentLinkedPullRequestCommentCounts
10763
+ )
10764
+ })).digest("hex");
10564
10765
  if (importedIssue.pendingRemoteActionWake) {
10565
10766
  const pendingWake2 = importedIssue.pendingRemoteActionWake;
10566
10767
  await wakePaperclipIssueAssignee(ctx, {
@@ -10609,10 +10810,7 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10609
10810
  nextStatus,
10610
10811
  syncContext: paperclipIssueSyncContext
10611
10812
  });
10612
- const shouldClearCompletedExecutionPolicy = shouldClearCompletedSyncExecutionPolicy({
10613
- nextStatus,
10614
- syncContext: paperclipIssueSyncContext
10615
- });
10813
+ const shouldClearCompletedExecutionPolicy = nextStatus === "done" || nextStatus === "cancelled";
10616
10814
  const shouldPreserveImportedTriageRouting = shouldPreserveImportedTriageAssignee({
10617
10815
  currentStatus: paperclipIssue.status,
10618
10816
  nextStatus,
@@ -10625,7 +10823,7 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10625
10823
  syncContext: paperclipIssueSyncContext,
10626
10824
  advancedSettings
10627
10825
  });
10628
- const shouldClearTransitionAssignee = nextStatus === "in_review" && (nextTransitionAssignee === null || shouldPreserveMaintainerWaitRouting) && paperclipIssueSyncContext.assignee !== null;
10826
+ const shouldClearTransitionAssignee = nextStatus === "in_review" && (nextTransitionAssignee === null || shouldPreserveMaintainerWaitRouting);
10629
10827
  const nextAssigneeChanged = nextTransitionAssignee ? !doesPaperclipIssueAssigneeMatch(paperclipIssueSyncContext.assignee, nextTransitionAssignee.principal) : false;
10630
10828
  const shouldWakeImportedAssignee = wasImportedThisRun && nextStatus === "todo" && (paperclipIssue.status === nextStatus || shouldPreserveImportedTriageRouting) && paperclipIssueSyncContext.assignee?.kind === "agent";
10631
10829
  const shouldWakeTransitionAssignee = paperclipIssue.status !== nextStatus && nextTransitionAssignee?.principal.kind === "agent" && isActionablePaperclipIssueStatus(nextStatus) && (nextAssigneeChanged || paperclipIssue.status !== nextStatus);
@@ -10639,24 +10837,23 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10639
10837
  await persistImportRegistry();
10640
10838
  };
10641
10839
  if (paperclipIssue.status === nextStatus) {
10642
- if (shouldClearTransitionAssignee || shouldClearCompletedExecutionPolicy) {
10643
- updateSyncFailureContext(syncFailureContext, {
10644
- phase: "updating_paperclip_status",
10645
- repositoryUrl: repository.url,
10646
- githubIssueNumber: githubIssue.number
10647
- });
10648
- await updatePaperclipIssueState(ctx, {
10649
- companyId: mapping.companyId,
10650
- issueId: importedIssue.paperclipIssueId,
10651
- currentStatus: paperclipIssue.status,
10652
- syncContext: paperclipIssueSyncContext,
10653
- nextStatus,
10654
- ...shouldClearTransitionAssignee ? { clearAssignee: true } : {},
10655
- ...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
10656
- transitionComment: "",
10657
- paperclipApiBaseUrl
10658
- });
10659
- }
10840
+ updateSyncFailureContext(syncFailureContext, {
10841
+ phase: "updating_paperclip_status",
10842
+ repositoryUrl: repository.url,
10843
+ githubIssueNumber: githubIssue.number
10844
+ });
10845
+ await updatePaperclipIssueState(ctx, {
10846
+ companyId: mapping.companyId,
10847
+ issueId: importedIssue.paperclipIssueId,
10848
+ currentStatus: paperclipIssue.status,
10849
+ syncContext: paperclipIssueSyncContext,
10850
+ nextStatus,
10851
+ ...shouldClearTransitionAssignee ? { clearAssignee: true } : {},
10852
+ ...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
10853
+ transitionComment: "",
10854
+ actionFingerprint: actionJournalFingerprint,
10855
+ paperclipApiBaseUrl
10856
+ });
10660
10857
  if (shouldWakeImportedAssignee && paperclipIssueSyncContext.assignee?.kind === "agent") {
10661
10858
  const pendingWake2 = {
10662
10859
  fingerprint: remoteActionFingerprint,
@@ -10709,6 +10906,7 @@ async function synchronizePaperclipIssueStatuses(ctx, octokit, repository, mappi
10709
10906
  ...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
10710
10907
  transitionComment: transitionComment.body,
10711
10908
  transitionCommentAnnotation: transitionComment.annotation,
10909
+ actionFingerprint: actionJournalFingerprint,
10712
10910
  paperclipApiBaseUrl
10713
10911
  });
10714
10912
  const pendingWake = shouldWakeImportedAssignee && paperclipIssueSyncContext.assignee?.kind === "agent" ? {
@@ -10952,6 +11150,10 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10952
11150
  }
10953
11151
  }
10954
11152
  const remoteActionFingerprint = buildDirectPullRequestActionFingerprint(pullRequestSnapshots);
11153
+ const actionJournalFingerprint = createHash("sha256").update(JSON.stringify({
11154
+ remoteActionFingerprint,
11155
+ commentCounts: canonicalizeGitHubPullRequestCommentCounts(currentCommentCounts)
11156
+ })).digest("hex");
10955
11157
  const paperclipIssueSyncContext = getPaperclipIssueSyncContext(paperclipIssue);
10956
11158
  const executorTransitionAssignee = resolvePaperclipIssueExecutorAssignee(
10957
11159
  paperclipIssueSyncContext,
@@ -10974,17 +11176,14 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
10974
11176
  nextStatus,
10975
11177
  syncContext: paperclipIssueSyncContext
10976
11178
  });
10977
- const shouldClearCompletedExecutionPolicy = shouldClearCompletedSyncExecutionPolicy({
10978
- nextStatus,
10979
- syncContext: paperclipIssueSyncContext
10980
- });
11179
+ const shouldClearCompletedExecutionPolicy = nextStatus === "done" || nextStatus === "cancelled";
10981
11180
  const nextTransitionAssignee = resolveSyncTransitionAssignee({
10982
11181
  currentStatus: paperclipIssue.status,
10983
11182
  nextStatus,
10984
11183
  syncContext: paperclipIssueSyncContext,
10985
11184
  advancedSettings
10986
11185
  });
10987
- const shouldClearTransitionAssignee = nextStatus === "in_review" && (nextTransitionAssignee === null || shouldPreserveMaintainerWaitRouting) && paperclipIssueSyncContext.assignee !== null;
11186
+ const shouldClearTransitionAssignee = nextStatus === "in_review" && (nextTransitionAssignee === null || shouldPreserveMaintainerWaitRouting);
10988
11187
  const nextAssigneeChanged = nextTransitionAssignee ? !doesPaperclipIssueAssigneeMatch(paperclipIssueSyncContext.assignee, nextTransitionAssignee.principal) : false;
10989
11188
  const shouldWakeTransitionAssignee = paperclipIssue.status !== nextStatus && nextTransitionAssignee?.principal.kind === "agent" && isActionablePaperclipIssueStatus(nextStatus) && (nextAssigneeChanged || paperclipIssue.status !== nextStatus);
10990
11189
  if (paperclipIssue.status === nextStatus) {
@@ -11003,6 +11202,7 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11003
11202
  ...shouldClearTransitionAssignee ? { clearAssignee: true } : {},
11004
11203
  ...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
11005
11204
  transitionComment: "",
11205
+ actionFingerprint: actionJournalFingerprint,
11006
11206
  paperclipApiBaseUrl
11007
11207
  });
11008
11208
  }
@@ -11036,6 +11236,7 @@ async function synchronizePaperclipPullRequestIssueStatuses(ctx, octokit, mappin
11036
11236
  ...shouldClearTransitionAssignee ? { clearAssignee: true } : {},
11037
11237
  ...shouldPreserveMaintainerWaitRouting || shouldClearCompletedExecutionPolicy ? { clearExecutionPolicy: true } : {},
11038
11238
  transitionComment,
11239
+ actionFingerprint: actionJournalFingerprint,
11039
11240
  paperclipApiBaseUrl
11040
11241
  });
11041
11242
  const pendingWake = shouldWakeTransitionAssignee && nextTransitionAssignee?.principal.kind === "agent" ? {
@@ -17040,11 +17241,14 @@ function shouldStartWorkerHost(moduleUrl, entry = process.argv[1]) {
17040
17241
  var __testing = {
17041
17242
  buildDirectPullRequestActionFingerprint,
17042
17243
  buildRemoteActionFingerprint,
17244
+ canonicalizeGitHubPullRequestCommentCounts,
17043
17245
  buildSyncFallbackExecutionStatePatch,
17044
17246
  createGitHubToolOctokit,
17045
17247
  formatPaperclipApiFetchErrorMessage,
17046
17248
  hasUnresolvedPaperclipIssueBlocker,
17047
17249
  isHealthyMaintainerWaitTransition,
17250
+ isPaperclipIssuePatchApplied,
17251
+ normalizePaperclipIssueAssigneePrincipal,
17048
17252
  normalizeImportRegistry,
17049
17253
  normalizeRemoteActionRegistry,
17050
17254
  persistIssueInteractionEvent,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paperclip-github-plugin",
3
- "version": "0.15.2",
3
+ "version": "0.15.4",
4
4
  "description": "Paperclip plugin for synchronizing GitHub issues into Paperclip projects.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",