paperclip-github-plugin 0.13.0 → 0.14.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/README.md CHANGED
@@ -239,6 +239,12 @@ The plugin exposes GitHub workflow tools to Paperclip agents, including:
239
239
  - review-thread reads, replies, resolve and unresolve actions, and `request_pull_request_reviewers` reviewer requests
240
240
  - organization-level GitHub Project search/listing and pull-request-to-project association
241
241
 
242
+ `create_pull_request` is the single agent-facing delivery call for both branch publication and PR creation. The caller supplies the Paperclip issue id, a plain local branch name, the exact 40-character local branch-tip SHA, the base branch, and the PR metadata. The trusted plugin worker verifies checkout ownership, resolves the issue's execution worktree and GitHub secret, verifies the checked-out branch, worktree HEAD, local branch tip, and base ancestry, publishes only that exact commit with a non-forcing refspec, reads the remote branch SHA back, and only then creates and links the PR. The GitHub credential is never returned to or injected into the calling agent.
243
+
244
+ Branch publication uses an isolated temporary bare repository backed by the trusted workspace object database. It does not execute repository hooks, accept arbitrary refspecs, or honor agent-supplied remote URLs. Publication rejects owner-qualified heads, base-branch targets, non-fast-forward updates, cross-project issues, mismatched local branch tips, and remote SHA mismatches.
245
+
246
+ The call is ordered and retry-safe rather than a cross-system transaction: a published branch may remain if GitHub PR creation or Paperclip link persistence fails. On retry, the tool re-verifies and republishes the exact SHA, then recovers an already-open PR only when repository, head, base, and head SHA all match before repairing the link and metric. It never deletes a branch or closes a PR as automatic compensation.
247
+
242
248
  When an agent sends GitHub body content through the plugin, including issue bodies, pull request descriptions, comments, and review-thread replies, the plugin adds a GitHub-flavored Markdown footer with a horizontal rule and compact heading that discloses AI authorship. If the tool caller supplies `llmModel`, the footer also includes the model name, for example `###### ✨ This comment was AI-generated using gpt-5.4`.
243
249
 
244
250
  ### KPI attribution API route
package/dist/manifest.js CHANGED
@@ -254,20 +254,25 @@ var GITHUB_AGENT_TOOLS = [
254
254
  {
255
255
  name: "create_pull_request",
256
256
  displayName: "Create Pull Request",
257
- description: "Open a GitHub pull request once the implementation branch is pushed. When a non-empty body is provided, the plugin appends an AI-authorship footer and includes llmModel when supplied.",
257
+ description: "Publish the local branch at the exact requested commit, verify the remote branch, then create and link a GitHub pull request in one operation. The GitHub credential remains inside the trusted plugin worker. When a non-empty body is provided, the plugin appends an AI-authorship footer and includes llmModel when supplied.",
258
258
  parametersSchema: {
259
259
  type: "object",
260
260
  additionalProperties: false,
261
- required: ["head", "base", "title"],
261
+ required: ["paperclipIssueId", "head", "headCommitSha", "base", "title"],
262
262
  properties: {
263
263
  repository: repositoryProperty,
264
264
  paperclipIssueId: {
265
265
  type: "string",
266
- description: "Optional Paperclip issue id to link with the created pull request so GitHub Sync can monitor PR status for that issue."
266
+ description: "Paperclip issue id used to resolve the trusted project workspace, mapped GitHub repository, and durable pull-request link."
267
267
  },
268
268
  head: {
269
269
  type: "string",
270
- description: "Head branch name or owner:branch."
270
+ description: "Plain local branch name to publish. Owner-qualified branches and arbitrary refspecs are rejected."
271
+ },
272
+ headCommitSha: {
273
+ type: "string",
274
+ pattern: "^[0-9a-fA-F]{40}$",
275
+ description: "Full 40-character commit SHA that must equal the exact local branch tip and the verified remote branch tip."
271
276
  },
272
277
  base: {
273
278
  type: "string",
@@ -636,7 +641,7 @@ var COMPANY_METRIC_API_ROUTE_URL_PATH = `/api/plugins/${GITHUB_SYNC_PLUGIN_ID}/a
636
641
  var require2 = createRequire(import.meta.url);
637
642
  var packageJson = require2("../package.json");
638
643
  var SCHEDULE_TICK_CRON = "* * * * *";
639
- var MANIFEST_VERSION = "0.13.0"?.trim() || typeof packageJson.version === "string" && packageJson.version.trim() || process.env.npm_package_version?.trim() || "0.0.0-dev";
644
+ var MANIFEST_VERSION = "0.14.0"?.trim() || typeof packageJson.version === "string" && packageJson.version.trim() || process.env.npm_package_version?.trim() || "0.0.0-dev";
640
645
  var manifest = {
641
646
  id: GITHUB_SYNC_PLUGIN_ID,
642
647
  apiVersion: 1,
@@ -655,7 +660,9 @@ var manifest = {
655
660
  "plugin.state.write",
656
661
  "instance.settings.register",
657
662
  "projects.read",
663
+ "execution.workspaces.read",
658
664
  "issues.read",
665
+ "issues.checkout",
659
666
  "issues.create",
660
667
  "issues.update",
661
668
  "issues.wakeup",
package/dist/worker.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // src/worker.ts
2
- import { Buffer } from "node:buffer";
2
+ import { Buffer as Buffer2 } from "node:buffer";
3
3
  import { realpathSync } from "node:fs";
4
- import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
4
+ import { chmod, mkdir as mkdir2, readFile, writeFile } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
- import { dirname, join, resolve } from "node:path";
6
+ import { dirname, join as join2, resolve as resolve2 } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { Octokit } from "@octokit/rest";
9
9
  import {
@@ -264,20 +264,25 @@ var GITHUB_AGENT_TOOLS = [
264
264
  {
265
265
  name: "create_pull_request",
266
266
  displayName: "Create Pull Request",
267
- description: "Open a GitHub pull request once the implementation branch is pushed. When a non-empty body is provided, the plugin appends an AI-authorship footer and includes llmModel when supplied.",
267
+ description: "Publish the local branch at the exact requested commit, verify the remote branch, then create and link a GitHub pull request in one operation. The GitHub credential remains inside the trusted plugin worker. When a non-empty body is provided, the plugin appends an AI-authorship footer and includes llmModel when supplied.",
268
268
  parametersSchema: {
269
269
  type: "object",
270
270
  additionalProperties: false,
271
- required: ["head", "base", "title"],
271
+ required: ["paperclipIssueId", "head", "headCommitSha", "base", "title"],
272
272
  properties: {
273
273
  repository: repositoryProperty,
274
274
  paperclipIssueId: {
275
275
  type: "string",
276
- description: "Optional Paperclip issue id to link with the created pull request so GitHub Sync can monitor PR status for that issue."
276
+ description: "Paperclip issue id used to resolve the trusted project workspace, mapped GitHub repository, and durable pull-request link."
277
277
  },
278
278
  head: {
279
279
  type: "string",
280
- description: "Head branch name or owner:branch."
280
+ description: "Plain local branch name to publish. Owner-qualified branches and arbitrary refspecs are rejected."
281
+ },
282
+ headCommitSha: {
283
+ type: "string",
284
+ pattern: "^[0-9a-fA-F]{40}$",
285
+ description: "Full 40-character commit SHA that must equal the exact local branch tip and the verified remote branch tip."
281
286
  },
282
287
  base: {
283
288
  type: "string",
@@ -643,6 +648,309 @@ function getGitHubAgentToolDeclaration(name) {
643
648
  return declaration;
644
649
  }
645
650
 
651
+ // src/git-branch-publisher.ts
652
+ import { spawn } from "node:child_process";
653
+ import { mkdir, mkdtemp, rm } from "node:fs/promises";
654
+ import { tmpdir } from "node:os";
655
+ import { isAbsolute, join, resolve } from "node:path";
656
+ var FULL_GIT_SHA_PATTERN = /^[0-9a-f]{40}$/i;
657
+ var GITHUB_HOST = "github.com";
658
+ var MAX_GIT_OUTPUT_BYTES = 1024 * 1024;
659
+ var GIT_COMMAND_TIMEOUT_MS = 5 * 6e4;
660
+ var GIT_CREDENTIAL_HELPER = '!f() { if [ "$1" = get ]; then IFS= read -r password <&3; printf "%s\\n" username=x-access-token "password=$password"; fi; }; f';
661
+ var defaultRunGit = async (args, options) => {
662
+ return await new Promise((resolvePromise, rejectPromise) => {
663
+ const child = spawn("git", args, {
664
+ env: options.env,
665
+ stdio: ["ignore", "pipe", "pipe", options.credential ? "pipe" : "ignore"]
666
+ });
667
+ let stdout = "";
668
+ let stderr = "";
669
+ let settled = false;
670
+ let timeout;
671
+ const rejectOnce = (error) => {
672
+ if (settled) return;
673
+ settled = true;
674
+ if (timeout) clearTimeout(timeout);
675
+ child.kill("SIGKILL");
676
+ rejectPromise(error);
677
+ };
678
+ const appendOutput = (target, chunk) => {
679
+ if (settled) return;
680
+ if (target === "stdout") stdout += chunk.toString("utf8");
681
+ else stderr += chunk.toString("utf8");
682
+ if (Buffer.byteLength(stdout) + Buffer.byteLength(stderr) > MAX_GIT_OUTPUT_BYTES) {
683
+ rejectOnce(new Error("git output exceeded the 1 MiB safety limit"));
684
+ }
685
+ };
686
+ const stdoutPipe = child.stdout;
687
+ const stderrPipe = child.stderr;
688
+ if (!stdoutPipe || !stderrPipe) {
689
+ rejectOnce(new Error("git output pipes were not available"));
690
+ return;
691
+ }
692
+ stdoutPipe.on("data", (chunk) => appendOutput("stdout", chunk));
693
+ stderrPipe.on("data", (chunk) => appendOutput("stderr", chunk));
694
+ child.on("error", (error) => rejectOnce(error));
695
+ child.on("close", (code, signal) => {
696
+ if (settled) return;
697
+ settled = true;
698
+ if (timeout) clearTimeout(timeout);
699
+ if (code === 0) {
700
+ resolvePromise({ stdout, stderr });
701
+ return;
702
+ }
703
+ const detail = stderr.trim() || stdout.trim() || `exit code ${code ?? "unknown"}${signal ? ` (${signal})` : ""}`;
704
+ rejectPromise(new Error(detail));
705
+ });
706
+ timeout = setTimeout(() => {
707
+ rejectOnce(new Error(`git command timed out after ${GIT_COMMAND_TIMEOUT_MS}ms`));
708
+ }, GIT_COMMAND_TIMEOUT_MS);
709
+ timeout.unref();
710
+ if (options.credential) {
711
+ const credentialPipe = child.stdio[3];
712
+ if (!credentialPipe || typeof credentialPipe.end !== "function") {
713
+ rejectOnce(new Error("git credential pipe was not available"));
714
+ return;
715
+ }
716
+ credentialPipe.on("error", (error) => {
717
+ if (error.code === "EPIPE" || error.code === "ECONNRESET") return;
718
+ rejectOnce(error);
719
+ });
720
+ credentialPipe.end(`${options.credential}
721
+ `);
722
+ }
723
+ });
724
+ };
725
+ function normalizeRequiredString(value, label) {
726
+ const normalized = value.trim();
727
+ if (!normalized) {
728
+ throw new Error(`${label} is required.`);
729
+ }
730
+ return normalized;
731
+ }
732
+ function normalizePlainBranchName(value, label) {
733
+ const branch = normalizeRequiredString(value, label);
734
+ if (branch.includes(":") || branch.startsWith("-")) {
735
+ throw new Error(`${label} must be a plain local branch name, not an owner-qualified branch or refspec.`);
736
+ }
737
+ return branch;
738
+ }
739
+ function normalizeExpectedCommitSha(value) {
740
+ const sha = normalizeRequiredString(value, "headCommitSha").toLowerCase();
741
+ if (!FULL_GIT_SHA_PATTERN.test(sha)) {
742
+ throw new Error("headCommitSha must be a full 40-character commit SHA.");
743
+ }
744
+ return sha;
745
+ }
746
+ function normalizeGitHubRepositoryRemote(value) {
747
+ const normalized = normalizeRequiredString(value, "repositoryUrl");
748
+ let parsed;
749
+ try {
750
+ parsed = new URL(normalized);
751
+ } catch {
752
+ throw new Error("repositoryUrl must be an HTTPS GitHub repository URL.");
753
+ }
754
+ if (parsed.protocol !== "https:" || parsed.hostname.toLowerCase() !== GITHUB_HOST || parsed.username || parsed.password) {
755
+ throw new Error("repositoryUrl must be a credential-free HTTPS GitHub repository URL.");
756
+ }
757
+ const pathParts = parsed.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/").filter(Boolean);
758
+ if (pathParts.length !== 2) {
759
+ throw new Error("repositoryUrl must identify exactly one GitHub owner/repository pair.");
760
+ }
761
+ const [owner, repository] = pathParts;
762
+ if (!owner || !repository) {
763
+ throw new Error("repositoryUrl must identify exactly one GitHub owner/repository pair.");
764
+ }
765
+ return `https://${GITHUB_HOST}/${owner}/${repository}.git`;
766
+ }
767
+ function createBaseGitEnvironment() {
768
+ return {
769
+ PATH: process.env.PATH ?? "",
770
+ LANG: process.env.LANG ?? "C.UTF-8",
771
+ LC_ALL: process.env.LC_ALL ?? "C.UTF-8",
772
+ GIT_TERMINAL_PROMPT: "0",
773
+ GIT_CONFIG_NOSYSTEM: "1",
774
+ GIT_CONFIG_GLOBAL: "/dev/null"
775
+ };
776
+ }
777
+ function createAuthenticatedGitEnvironment(params) {
778
+ return {
779
+ ...createBaseGitEnvironment(),
780
+ HOME: params.temporaryHome,
781
+ XDG_CONFIG_HOME: params.temporaryHome,
782
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: params.alternateObjectDirectory,
783
+ GIT_CONFIG_COUNT: "3",
784
+ GIT_CONFIG_KEY_0: "credential.helper",
785
+ GIT_CONFIG_VALUE_0: "",
786
+ GIT_CONFIG_KEY_1: "credential.https://github.com.helper",
787
+ GIT_CONFIG_VALUE_1: GIT_CREDENTIAL_HELPER,
788
+ GIT_CONFIG_KEY_2: "core.hooksPath",
789
+ GIT_CONFIG_VALUE_2: "/dev/null"
790
+ };
791
+ }
792
+ function sanitizeGitError(error, token) {
793
+ const raw = error instanceof Error ? error.message : String(error);
794
+ return token ? raw.split(token).join("[REDACTED]") : raw;
795
+ }
796
+ async function runGitStep(runGit, args, env, failureMessage, credential = "") {
797
+ try {
798
+ return await runGit(args, {
799
+ env,
800
+ ...credential ? { credential } : {}
801
+ });
802
+ } catch (error) {
803
+ const details = sanitizeGitError(error, credential).trim();
804
+ throw new Error(details ? `${failureMessage}: ${details}` : failureMessage);
805
+ }
806
+ }
807
+ async function publishLocalBranchForPullRequest(input, dependencies = {}) {
808
+ const runGit = dependencies.runGit ?? defaultRunGit;
809
+ const workspacePath = normalizeRequiredString(input.workspacePath, "workspacePath");
810
+ if (!isAbsolute(workspacePath)) {
811
+ throw new Error("workspacePath must be absolute.");
812
+ }
813
+ const branchName = normalizePlainBranchName(input.branchName, "head");
814
+ const baseBranch = normalizePlainBranchName(input.baseBranch, "base");
815
+ if (branchName === baseBranch) {
816
+ throw new Error("The pull request head branch must differ from the base branch.");
817
+ }
818
+ const expectedCommitSha = normalizeExpectedCommitSha(input.expectedCommitSha);
819
+ const githubToken = normalizeRequiredString(input.githubToken, "GitHub token");
820
+ const remoteUrl = normalizeGitHubRepositoryRemote(input.repositoryUrl);
821
+ const remoteRef = `refs/heads/${branchName}`;
822
+ const baseEnvironment = createBaseGitEnvironment();
823
+ await runGitStep(
824
+ runGit,
825
+ ["-C", workspacePath, "check-ref-format", "--branch", branchName],
826
+ baseEnvironment,
827
+ "The requested head branch name is invalid"
828
+ );
829
+ await runGitStep(
830
+ runGit,
831
+ ["-C", workspacePath, "check-ref-format", "--branch", baseBranch],
832
+ baseEnvironment,
833
+ "The requested base branch name is invalid"
834
+ );
835
+ const expectedHeadRef = `refs/heads/${branchName}`;
836
+ const checkedOutBranchResult = await runGitStep(
837
+ runGit,
838
+ ["-C", workspacePath, "symbolic-ref", "--quiet", "HEAD"],
839
+ baseEnvironment,
840
+ "Could not resolve the execution worktree branch"
841
+ );
842
+ const checkedOutBranchRef = checkedOutBranchResult.stdout.trim();
843
+ if (checkedOutBranchRef !== expectedHeadRef) {
844
+ throw new Error(`The requested head branch ${branchName} is not checked out in this execution worktree. Found ${checkedOutBranchRef || "detached HEAD"}.`);
845
+ }
846
+ const checkedOutCommitResult = await runGitStep(
847
+ runGit,
848
+ ["-C", workspacePath, "rev-parse", "--verify", "HEAD^{commit}"],
849
+ baseEnvironment,
850
+ "Could not resolve the execution worktree HEAD commit"
851
+ );
852
+ const checkedOutCommitSha = checkedOutCommitResult.stdout.trim().toLowerCase();
853
+ if (checkedOutCommitSha !== expectedCommitSha) {
854
+ throw new Error(`headCommitSha does not match the execution worktree HEAD. Expected ${expectedCommitSha}, found ${checkedOutCommitSha || "no commit"}.`);
855
+ }
856
+ const commonDirResult = await runGitStep(
857
+ runGit,
858
+ ["-C", workspacePath, "rev-parse", "--git-common-dir"],
859
+ baseEnvironment,
860
+ "Could not resolve the workspace Git repository"
861
+ );
862
+ const commonGitDirRaw = commonDirResult.stdout.trim();
863
+ if (!commonGitDirRaw) {
864
+ throw new Error("Could not resolve the workspace Git repository: git returned an empty common directory.");
865
+ }
866
+ const commonGitDir = isAbsolute(commonGitDirRaw) ? commonGitDirRaw : resolve(workspacePath, commonGitDirRaw);
867
+ const localTipResult = await runGitStep(
868
+ runGit,
869
+ ["-C", workspacePath, "rev-parse", "--verify", `${remoteRef}^{commit}`],
870
+ baseEnvironment,
871
+ `The local branch ${branchName} does not resolve to a commit`
872
+ );
873
+ const localTip = localTipResult.stdout.trim().toLowerCase();
874
+ if (localTip !== expectedCommitSha) {
875
+ throw new Error(`headCommitSha does not match the local branch tip for ${branchName}. Expected ${expectedCommitSha}, found ${localTip || "no commit"}.`);
876
+ }
877
+ const temporaryRoot = await mkdtemp(join(tmpdir(), "paperclip-github-publish-"));
878
+ const temporaryGitDir = join(temporaryRoot, "repository.git");
879
+ const emptyTemplateDir = join(temporaryRoot, "empty-template");
880
+ await mkdir(emptyTemplateDir, { mode: 448 });
881
+ const authenticatedEnvironment = createAuthenticatedGitEnvironment({
882
+ temporaryHome: temporaryRoot,
883
+ alternateObjectDirectory: join(commonGitDir, "objects")
884
+ });
885
+ try {
886
+ await runGitStep(
887
+ runGit,
888
+ ["init", "--bare", `--template=${emptyTemplateDir}`, temporaryGitDir],
889
+ authenticatedEnvironment,
890
+ "Could not initialize the temporary Git publisher"
891
+ );
892
+ await runGitStep(
893
+ runGit,
894
+ [
895
+ "--git-dir",
896
+ temporaryGitDir,
897
+ "fetch",
898
+ "--no-tags",
899
+ remoteUrl,
900
+ `refs/heads/${baseBranch}:refs/remotes/origin/${baseBranch}`
901
+ ],
902
+ authenticatedEnvironment,
903
+ `Could not fetch the pull request base branch ${baseBranch}`,
904
+ githubToken
905
+ );
906
+ await runGitStep(
907
+ runGit,
908
+ ["--git-dir", temporaryGitDir, "rev-parse", "--verify", `refs/remotes/origin/${baseBranch}^{commit}`],
909
+ authenticatedEnvironment,
910
+ `The pull request base branch ${baseBranch} was not found on GitHub`
911
+ );
912
+ await runGitStep(
913
+ runGit,
914
+ ["--git-dir", temporaryGitDir, "merge-base", "--is-ancestor", `refs/remotes/origin/${baseBranch}`, expectedCommitSha],
915
+ authenticatedEnvironment,
916
+ `The local branch ${branchName} is not based on the requested base branch ${baseBranch}`
917
+ );
918
+ await runGitStep(
919
+ runGit,
920
+ [
921
+ "--git-dir",
922
+ temporaryGitDir,
923
+ "push",
924
+ "--porcelain",
925
+ "--no-verify",
926
+ remoteUrl,
927
+ `${expectedCommitSha}:${remoteRef}`
928
+ ],
929
+ authenticatedEnvironment,
930
+ `Could not publish ${branchName}; only a new branch or fast-forward update is allowed`,
931
+ githubToken
932
+ );
933
+ const remoteResult = await runGitStep(
934
+ runGit,
935
+ ["--git-dir", temporaryGitDir, "ls-remote", "--heads", remoteUrl, remoteRef],
936
+ authenticatedEnvironment,
937
+ `Could not verify the published branch ${branchName}`,
938
+ githubToken
939
+ );
940
+ const remoteCommitSha = remoteResult.stdout.trim().split(/\s+/)[0]?.toLowerCase() ?? "";
941
+ if (remoteCommitSha !== expectedCommitSha) {
942
+ throw new Error(`Remote branch verification failed for ${branchName}. Expected ${expectedCommitSha}, found ${remoteCommitSha || "no remote ref"}.`);
943
+ }
944
+ return {
945
+ branchName,
946
+ commitSha: expectedCommitSha,
947
+ remoteRef
948
+ };
949
+ } finally {
950
+ await rm(temporaryRoot, { recursive: true, force: true });
951
+ }
952
+ }
953
+
646
954
  // src/github-repo.ts
647
955
  function parseRepositoryReference(repositoryInput) {
648
956
  const trimmed = repositoryInput.trim();
@@ -721,6 +1029,7 @@ function requiresPaperclipBoardAccessForHealth(health) {
721
1029
  var GITHUB_SYNC_BASE_ORIGIN_KIND = `plugin:${GITHUB_SYNC_PLUGIN_ID}`;
722
1030
  var GITHUB_ISSUE_ORIGIN_KIND = `plugin:${GITHUB_SYNC_PLUGIN_ID}:github-issue`;
723
1031
  var GITHUB_PULL_REQUEST_ORIGIN_KIND = `plugin:${GITHUB_SYNC_PLUGIN_ID}:github-pull-request`;
1032
+ var createPullRequestBranchPublisher = publishLocalBranchForPullRequest;
724
1033
  var SETTINGS_SCOPE = {
725
1034
  scopeKind: "instance",
726
1035
  stateKey: "paperclip-github-plugin-settings"
@@ -3689,8 +3998,8 @@ async function waitForSyncResultWithinGracePeriod(promise, timeoutMs) {
3689
3998
  try {
3690
3999
  return await Promise.race([
3691
4000
  promise,
3692
- new Promise((resolve2) => {
3693
- timer = globalThis.setTimeout(() => resolve2(null), timeoutMs);
4001
+ new Promise((resolve3) => {
4002
+ timer = globalThis.setTimeout(() => resolve3(null), timeoutMs);
3694
4003
  })
3695
4004
  ]);
3696
4005
  } finally {
@@ -3770,16 +4079,16 @@ function normalizeGitHubToken(value) {
3770
4079
  }
3771
4080
  function getExternalConfigFilePath() {
3772
4081
  const paperclipHomeDirectory = getPaperclipHomeDirectory();
3773
- return paperclipHomeDirectory ? join(paperclipHomeDirectory, "plugins", "github-sync", "config.json") : void 0;
4082
+ return paperclipHomeDirectory ? join2(paperclipHomeDirectory, "plugins", "github-sync", "config.json") : void 0;
3774
4083
  }
3775
4084
  function getPaperclipHomeDirectory() {
3776
4085
  const configuredPaperclipHome = process.env.PAPERCLIP_HOME?.trim();
3777
4086
  if (configuredPaperclipHome) {
3778
- return resolve(configuredPaperclipHome);
4087
+ return resolve2(configuredPaperclipHome);
3779
4088
  }
3780
4089
  try {
3781
4090
  const resolvedHomeDirectory = homedir();
3782
- return typeof resolvedHomeDirectory === "string" && resolvedHomeDirectory.trim() ? join(resolvedHomeDirectory, ".paperclip") : void 0;
4091
+ return typeof resolvedHomeDirectory === "string" && resolvedHomeDirectory.trim() ? join2(resolvedHomeDirectory, ".paperclip") : void 0;
3783
4092
  } catch {
3784
4093
  return void 0;
3785
4094
  }
@@ -3866,7 +4175,7 @@ async function writeExternalCompanyGitHubTokenFallback(ctx, companyId, token) {
3866
4175
  [companyId]: token
3867
4176
  }
3868
4177
  };
3869
- await mkdir(dirname(externalConfigFilePath), { recursive: true });
4178
+ await mkdir2(dirname(externalConfigFilePath), { recursive: true });
3870
4179
  await writeFile(externalConfigFilePath, `${JSON.stringify(nextRecord, null, 2)}
3871
4180
  `, {
3872
4181
  encoding: "utf8",
@@ -3895,7 +4204,7 @@ async function writeExternalCompanyPaperclipBoardApiTokenFallback(ctx, companyId
3895
4204
  [companyId]: token
3896
4205
  }
3897
4206
  };
3898
- await mkdir(dirname(externalConfigFilePath), { recursive: true });
4207
+ await mkdir2(dirname(externalConfigFilePath), { recursive: true });
3899
4208
  await writeFile(externalConfigFilePath, `${JSON.stringify(nextRecord, null, 2)}
3900
4209
  `, {
3901
4210
  encoding: "utf8",
@@ -3928,7 +4237,7 @@ async function clearExternalCompanyPaperclipBoardApiTokenFallback(ctx, companyId
3928
4237
  } else {
3929
4238
  delete nextRecord.paperclipBoardApiTokensByCompanyId;
3930
4239
  }
3931
- await mkdir(dirname(externalConfigFilePath), { recursive: true });
4240
+ await mkdir2(dirname(externalConfigFilePath), { recursive: true });
3932
4241
  await writeFile(externalConfigFilePath, `${JSON.stringify(nextRecord, null, 2)}
3933
4242
  `, {
3934
4243
  encoding: "utf8",
@@ -10488,7 +10797,7 @@ function decodePullRequestAssetContent(payload) {
10488
10797
  if (!/^[A-Za-z0-9+/]*={0,2}$/.test(normalizedBase64) || normalizedBase64.length % 4 === 1) {
10489
10798
  throw new Error("Asset content must be valid base64.");
10490
10799
  }
10491
- const bytes = Buffer.from(normalizedBase64, "base64");
10800
+ const bytes = Buffer2.from(normalizedBase64, "base64");
10492
10801
  if (bytes.length === 0) {
10493
10802
  throw new Error("Asset content must not be empty.");
10494
10803
  }
@@ -15066,52 +15375,124 @@ function registerGitHubAgentTools(ctx) {
15066
15375
  const input = getToolInputRecord(params);
15067
15376
  const paperclipIssueId = normalizeOptionalToolString(input.paperclipIssueId);
15068
15377
  const explicitRepository = normalizeOptionalToolString(input.repository);
15069
- const issueLinkScope = paperclipIssueId && !explicitRepository ? await resolveIssueGitHubLinkMapping(ctx, {
15070
- companyId: runCtx.companyId,
15071
- issueId: paperclipIssueId
15072
- }) : null;
15073
- const repository = issueLinkScope?.repository ?? await resolveGitHubToolRepository(ctx, runCtx, input);
15074
15378
  const head = normalizeOptionalToolString(input.head);
15379
+ const headCommitSha = normalizeOptionalToolString(input.headCommitSha);
15075
15380
  const base = normalizeOptionalToolString(input.base);
15076
15381
  const title = normalizeOptionalToolString(input.title);
15077
- if (!head || !base || !title) {
15078
- throw new Error("head, base, and title are required.");
15382
+ if (!paperclipIssueId || !head || !headCommitSha || !base || !title) {
15383
+ throw new Error("paperclipIssueId, head, headCommitSha, base, and title are required.");
15384
+ }
15385
+ const issueLinkScope = await resolveIssueGitHubLinkMapping(ctx, {
15386
+ companyId: runCtx.companyId,
15387
+ issueId: paperclipIssueId,
15388
+ ...explicitRepository ? { repositoryUrl: explicitRepository } : {}
15389
+ });
15390
+ if (issueLinkScope.projectId !== runCtx.projectId) {
15391
+ throw new Error("The selected Paperclip issue does not belong to the current tool run project.");
15392
+ }
15393
+ if (issueLinkScope.issue.assigneeAgentId && issueLinkScope.issue.assigneeAgentId !== runCtx.agentId) {
15394
+ throw new Error("The selected Paperclip issue is assigned to another agent.");
15395
+ }
15396
+ await ctx.issues.assertCheckoutOwner({
15397
+ issueId: paperclipIssueId,
15398
+ companyId: runCtx.companyId,
15399
+ actorAgentId: runCtx.agentId,
15400
+ actorRunId: runCtx.runId
15401
+ });
15402
+ const executionWorkspaceId = normalizeOptionalToolString(issueLinkScope.issue.executionWorkspaceId);
15403
+ if (!executionWorkspaceId) {
15404
+ throw new Error("The selected Paperclip issue does not have an execution workspace for branch publication.");
15079
15405
  }
15406
+ const workspace = await ctx.executionWorkspaces.get(executionWorkspaceId, runCtx.companyId);
15407
+ if (!workspace || workspace.companyId !== runCtx.companyId || workspace.projectId !== runCtx.projectId) {
15408
+ throw new Error("The selected Paperclip issue execution workspace does not belong to the current tool run project.");
15409
+ }
15410
+ const workspacePath = normalizeOptionalToolString(workspace.cwd) ?? normalizeOptionalToolString(workspace.path);
15411
+ if (!workspacePath) {
15412
+ throw new Error("The selected Paperclip issue execution workspace is not locally realized.");
15413
+ }
15414
+ const workspaceRepository = workspace.repoUrl ? parseRepositoryReference(workspace.repoUrl) : null;
15415
+ const repository = issueLinkScope.repository;
15416
+ if (!workspaceRepository || !areRepositoriesEqual(workspaceRepository, repository)) {
15417
+ throw new Error("The execution workspace repository does not match the GitHub repository mapped to this Paperclip issue.");
15418
+ }
15419
+ const githubToken = (await resolveGithubToken(ctx, { companyId: runCtx.companyId })).trim();
15420
+ if (!githubToken) {
15421
+ throw new Error(MISSING_GITHUB_TOKEN_SYNC_MESSAGE);
15422
+ }
15423
+ const publishedBranch = await createPullRequestBranchPublisher({
15424
+ workspacePath,
15425
+ repositoryUrl: repository.url,
15426
+ branchName: head,
15427
+ expectedCommitSha: headCommitSha,
15428
+ baseBranch: base,
15429
+ githubToken
15430
+ });
15080
15431
  const body = typeof input.body === "string" ? appendOptionalAiAuthorshipFooter(
15081
15432
  input.body,
15082
15433
  "pull request description",
15083
15434
  normalizeOptionalToolString(input.llmModel)
15084
15435
  ) : void 0;
15085
- const octokit = await createAgentToolOctokit(runCtx, "create_pull_request", repository);
15086
- const response = await octokit.rest.pulls.create({
15087
- owner: repository.owner,
15088
- repo: repository.repo,
15089
- head,
15090
- base,
15091
- title,
15092
- ...body !== void 0 ? { body } : {},
15093
- ...typeof input.draft === "boolean" ? { draft: input.draft } : {},
15094
- headers: {
15095
- "X-GitHub-Api-Version": GITHUB_API_VERSION
15096
- }
15436
+ const octokit = createGitHubOctokit(ctx, githubToken, {
15437
+ companyId: runCtx.companyId,
15438
+ operation: "github-api",
15439
+ repositoryUrl: repository.url,
15440
+ toolName: "create_pull_request"
15097
15441
  });
15442
+ let pullRequestData;
15443
+ try {
15444
+ pullRequestData = (await octokit.rest.pulls.create({
15445
+ owner: repository.owner,
15446
+ repo: repository.repo,
15447
+ head: publishedBranch.branchName,
15448
+ base,
15449
+ title,
15450
+ ...body !== void 0 ? { body } : {},
15451
+ ...typeof input.draft === "boolean" ? { draft: input.draft } : {},
15452
+ headers: {
15453
+ "X-GitHub-Api-Version": GITHUB_API_VERSION
15454
+ }
15455
+ })).data;
15456
+ } catch (error) {
15457
+ if (getErrorStatus(error) !== 422) {
15458
+ throw error;
15459
+ }
15460
+ const existingResponse = await octokit.rest.pulls.list({
15461
+ owner: repository.owner,
15462
+ repo: repository.repo,
15463
+ state: "open",
15464
+ head: `${repository.owner}:${publishedBranch.branchName}`,
15465
+ base,
15466
+ per_page: 100,
15467
+ headers: {
15468
+ "X-GitHub-Api-Version": GITHUB_API_VERSION
15469
+ }
15470
+ });
15471
+ const existingPullRequest = existingResponse.data.find(
15472
+ (candidate) => candidate.head.ref === publishedBranch.branchName && candidate.base.ref === base && candidate.head.sha.toLowerCase() === publishedBranch.commitSha.toLowerCase()
15473
+ );
15474
+ if (!existingPullRequest) {
15475
+ throw error;
15476
+ }
15477
+ pullRequestData = existingPullRequest;
15478
+ }
15098
15479
  if (paperclipIssueId) {
15099
15480
  const linkScope = issueLinkScope ?? await resolveIssueGitHubLinkMapping(ctx, {
15100
15481
  companyId: runCtx.companyId,
15101
15482
  issueId: paperclipIssueId,
15102
15483
  repositoryUrl: repository.url
15103
15484
  });
15104
- const pullRequestUrl = normalizeGitHubPullRequestHtmlUrl(response.data.html_url) ?? `${repository.url}/pull/${response.data.number}`;
15485
+ const pullRequestUrl = normalizeGitHubPullRequestHtmlUrl(pullRequestData.html_url) ?? `${repository.url}/pull/${pullRequestData.number}`;
15105
15486
  await upsertGitHubPullRequestLinkRecord(ctx, {
15106
15487
  companyId: runCtx.companyId,
15107
15488
  projectId: linkScope.mapping.paperclipProjectId ?? linkScope.projectId,
15108
15489
  issueId: paperclipIssueId,
15109
15490
  repositoryUrl: repository.url,
15110
- pullRequestNumber: response.data.number,
15491
+ pullRequestNumber: pullRequestData.number,
15111
15492
  pullRequestUrl,
15112
- pullRequestTitle: response.data.title || title,
15493
+ pullRequestTitle: pullRequestData.title || title,
15113
15494
  pullRequestState: getGitHubPullRequestStateForLink({
15114
- state: response.data.state,
15495
+ state: pullRequestData.state,
15115
15496
  merged: false
15116
15497
  })
15117
15498
  });
@@ -15127,26 +15508,31 @@ function registerGitHubAgentTools(ctx) {
15127
15508
  companyId: runCtx.companyId,
15128
15509
  metric: "paperclipPullRequestsCreatedCount",
15129
15510
  repositoryUrl: repository.url,
15130
- pullRequestNumber: response.data.number,
15131
- pullRequestUrl: response.data.html_url ?? void 0
15511
+ pullRequestNumber: pullRequestData.number,
15512
+ pullRequestUrl: pullRequestData.html_url ?? void 0
15132
15513
  },
15133
15514
  {
15134
15515
  throwOnPersistFailure: false
15135
15516
  }
15136
15517
  );
15137
15518
  return buildToolSuccessResult(
15138
- `Created pull request #${response.data.number} in ${formatRepositoryLabel(repository)}.`,
15519
+ `Created pull request #${pullRequestData.number} in ${formatRepositoryLabel(repository)}.`,
15139
15520
  {
15140
15521
  repository: repository.url,
15522
+ publishedBranch: {
15523
+ name: publishedBranch.branchName,
15524
+ commitSha: publishedBranch.commitSha,
15525
+ remoteRef: publishedBranch.remoteRef
15526
+ },
15141
15527
  pullRequest: {
15142
- number: response.data.number,
15143
- title: response.data.title,
15144
- body: response.data.body ?? "",
15145
- url: response.data.html_url,
15146
- state: response.data.state,
15147
- isDraft: response.data.draft,
15148
- headRefName: response.data.head.ref,
15149
- baseRefName: response.data.base.ref
15528
+ number: pullRequestData.number,
15529
+ title: pullRequestData.title,
15530
+ body: pullRequestData.body ?? "",
15531
+ url: pullRequestData.html_url,
15532
+ state: pullRequestData.state,
15533
+ isDraft: pullRequestData.draft,
15534
+ headRefName: pullRequestData.head.ref,
15535
+ baseRefName: pullRequestData.base.ref
15150
15536
  }
15151
15537
  }
15152
15538
  );
@@ -15683,7 +16069,7 @@ function shouldStartWorkerHost(moduleUrl, entry = process.argv[1]) {
15683
16069
  try {
15684
16070
  return realpathSync(entry) === realpathSync(modulePath);
15685
16071
  } catch {
15686
- return resolve(entry) === resolve(modulePath);
16072
+ return resolve2(entry) === resolve2(modulePath);
15687
16073
  }
15688
16074
  }
15689
16075
  var __testing = {
@@ -15695,7 +16081,10 @@ var __testing = {
15695
16081
  resolvePaperclipApiAuthTokens,
15696
16082
  resolveGithubToken,
15697
16083
  resolvePaperclipPullRequestIssueStatus,
15698
- resolveSyncTransitionAssignee
16084
+ resolveSyncTransitionAssignee,
16085
+ setCreatePullRequestBranchPublisher(publisher) {
16086
+ createPullRequestBranchPublisher = publisher ?? publishLocalBranchForPullRequest;
16087
+ }
15699
16088
  };
15700
16089
  var plugin = definePlugin({
15701
16090
  async setup(ctx) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paperclip-github-plugin",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Paperclip plugin for synchronizing GitHub issues into Paperclip projects.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -34,7 +34,7 @@
34
34
  "dev": "node ./scripts/build.mjs --watch",
35
35
  "dev:ui": "paperclip-plugin-dev-server --root . --ui-dir dist/ui --port 4177",
36
36
  "prepack": "pnpm build",
37
- "test": "node --test tests/build-script.spec.mjs && tsx --test tests/plugin.spec.ts",
37
+ "test": "node --test tests/build-script.spec.mjs && tsx --test tests/git-branch-publisher.spec.ts tests/plugin.spec.ts",
38
38
  "test:e2e": "pnpm build && pnpm exec playwright install chromium && node ./scripts/e2e/run-paperclip-smoke.mjs",
39
39
  "typecheck": "tsc --noEmit",
40
40
  "verify:manual": "pnpm build && node ./scripts/e2e/manual-paperclip-verify.mjs"