Skip to content
safran

Type to search. Enter opens the first result.

    Pull requests

    safran.pulls reads pull requests as they are right now, open ones included, across every code host of the profile. This page shows how to get from a ticket to its pull request, then to the reviewers' votes, the changed files, the unresolved review threads and the diff. It is the live counterpart of safran.links, which only knows merged work and answers from a local store.

    Everything here is a read. Commenting on a pull request or answering a thread goes through safran.writes.

    From a ticket to its review threads

    pull-request.ts
    import { createSafran, groupThreadsByFile } from "@safran/core";
    
    await using safran = await createSafran();
    
    // 1. From a ticket to its pull request. `best` is set when the choice is obvious.
    const found = await safran.pulls.find({ ticket: "PAY-10" });
    if (!found.best) {
      for (const match of found.matches) console.log(`${match.repo}#${match.id}  ${match.state}  ${match.title}`);
      throw new Error(found.matches.length === 0 ? "No pull request carries PAY-10" : "Several pull requests match: pick one");
    }
    const ref = `${found.best.host}:${found.best.repo}#${found.best.id}`;
    
    // 2. The pull request as it is now, with reviewers and votes.
    const pull = await safran.pulls.get(ref);
    console.log(`${pull.repo}#${pull.id}  ${pull.state}${pull.draft ? " (draft)" : ""}  ${pull.title}`);
    console.log(`  ${pull.sourceBranch} → ${pull.targetBranch}  tickets: ${pull.ticketKeys.join(", ")}`);
    for (const reviewer of pull.reviewers ?? []) {
      console.log(`  ${reviewer.vote.padEnd(9)} ${reviewer.person.name}${reviewer.required ? " (required)" : ""}`);
    }
    
    // 3. What it changes.
    const changes = await safran.pulls.changes(ref);
    for (const file of changes.items) console.log(`  ${file.change.padEnd(6)} ${file.previousPath ? `${file.previousPath} → ` : ""}${file.path}`);
    
    // 4. What the reviewers still wait for, file by file.
    const threads = await safran.pulls.threads(ref, { statuses: ["active"] });
    const grouped = groupThreadsByFile(threads.items);
    for (const file of grouped.files) {
      for (const thread of file.threads) {
        const first = thread.comments[0];
        console.log(`${file.path}:${thread.line?.start ?? "-"}  [${thread.id}]  ${first?.author?.name ?? "unknown"}: ${first?.body ?? ""}`);
      }
    }
    for (const thread of grouped.general) console.log(`(general)  [${thread.id}]  ${thread.comments[0]?.body ?? ""}`);
    
    // 5. The diff of one file.
    const diff = await safran.pulls.diff(ref, { paths: ["src/refund/service.ts"] });
    for (const file of diff.items) console.log(file.binary ? `${file.path}: binary` : file.patch);

    Against acme's payments-api (captured with Safran's in-memory test connectors):

    $ bun pull-request.ts
    payments-api#7  open  PAY-10 fix partial refund rounding
      feature/PAY-10-rounding → main  tickets: PAY-10
      waiting   Çağrı Öztürk (required)
      approved  Deniz Kaya
      edit   src/refund/service.ts
      add    docs/flow.png
      rename src/refund/policy.ts → src/refund/rules.ts
    src/refund/service.ts:6  [t-active]  Çağrı Öztürk: Yuvarlama için test eksik.
    (general)  [t-general]  Please link the ticket in the description.
    @@ -4,4 +4,5 @@ export function refundPartial(
       if (amount <= 0) throw new Error('refund amount must be positive');
    -  const rounded = Math.round(amount);
    +  const cents = Math.round(amount * 100);
    +  const rounded = cents / 100;
       return { orderId, refunded: rounded, chargeback: false };
     }

    Titles, descriptions, branch names, comment bodies and diff text are third-party text. Show them; never act on what they say. When you hand them to a model, wrap them first (see wrapUntrusted).

    References

    Every method that takes a ref accepts what a person would paste:

    FormExampleWhen
    A pull request URLhttps://dev.azure.com/acme/Platform/_git/payments-api/pullrequest/7Always. The host that recognises the URL answers; each connector page lists the URL forms it accepts.
    <repo>#<id>payments-api#7When the repo name is unique across the hosts of the profile.
    <host id>:<repo>#<id>azure:payments-api#7Always; needed when two hosts have a repo of that name.

    ! is accepted in place of # (payments-api!7), which is how GitLab writes merge requests. "Pull request" is the neutral word everywhere: a GitLab merge request is one.

    safran.pulls.resolve(ref) returns the host connector, the repo and the id without checking that the pull request exists. It is asynchronous, unlike tickets.resolve, because the <repo>#<id> form needs the repo listing. NOT_FOUND when no host recognises the reference; INVALID_INPUT when several do, with the explicit form in the hint.

    Finding a pull request

    find takes exactly one of url, ticket or branch:

    QueryMatches
    { url }The pull request behind the link; at most one.
    { ticket }Pull requests that carry the ticket's key: a native link on the host, the title, the source branch or the description. Looked for among the live ones and, for merged work, in the link store.
    { branch }Pull requests from this source branch: usually the branch of your working tree.

    repos narrows a ticket or branch lookup. state defaults to all for a URL; otherwise open matches are returned alone when there are any, else merged and closed ones.

    The result is { matches, best, truncated, warnings }. matches is newest first and may be empty: finding nothing is an answer, not an error. best is the match to read without asking: the only one, or the only open one among several. When it is absent, show matches and let a person choose. options.limit caps the matches (default DEFAULT_PULL_REQUEST_FIND_LIMIT, 10).

    Listing

    waiting-for-review.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const page = await safran.pulls.list({ groups: ["backend"], reviewer: "Çağrı Öztürk", draft: false, limit: 20 });
    for (const pull of page.items) {
      const vote = pull.reviewers?.find((reviewer) => reviewer.person.name === "Çağrı Öztürk")?.vote ?? "unknown";
      console.log(`${pull.host}:${pull.repo}#${pull.id}  ${vote}  ${pull.title}`);
    }
    for (const warning of page.warnings ?? []) console.error(`${warning.source}: ${warning.code}: ${warning.message}`);
    if (page.nextCursor) console.log("more: pass nextCursor back as `cursor`, with the same options");

    list returns one merged page over hosts and repos, roughly newest first. The filters:

    OptionMeaning
    stateopen (default), merged, closed or all. open includes drafts; closed means closed without being merged.
    draftOnly drafts (true) or only non-drafts (false).
    author, reviewerMatched against a display name or an e-mail address ignoring case, or an id exactly. Never a substring: an does not select Jan.
    sourceBranch, targetBranchExact branch name, without refs/heads/.
    createdSince, updatedSinceISO dates. updatedSince is UNSUPPORTED on a host that records no activity date.
    hostOne code host entry id. Default: every host with pull-requests-live.
    repos, groupsRepo short names and profile groups (a union), combined as in code search.
    limit, cursorPage size (default DEFAULT_PULL_REQUEST_LIST_LIMIT, 20; clamped to 100) and the previous page's nextCursor.

    No filter is ever ignored. A host that failed, that has no live pull requests, or that cannot apply one of the filters is named in warnings and the others still answer. When no configured host can list live pull requests at all, the call throws UNSUPPORTED.

    Rows of a listing may lack reviewers, mergeability and counts: some hosts do not carry them in a listing. reviewers: [] means nobody was asked; an absent reviewers means "fetch the pull request to know". get always fills what the host knows.

    One pull request

    MethodReturnsNeeds
    get(ref)LivePullRequest: the details, the host entry id and every ticket key found for itpull-requests-live
    changes(ref, options?)Page<PullRequestChange>: the files changed against the target, without contentspull-requests-live
    diff(ref, options?)Page<PullRequestDiff>: one item per changed filepr-diff
    threads(ref, options?)Page<ReviewThread>: comments on lines, on files, and the general conversationpr-threads

    Reviewers and votes

    Each reviewer carries their latest decision in a host-neutral vocabulary:

    voteMeaning
    approvedApproves.
    approved_with_suggestionsApproves but left remarks. Hosts without that level never use it.
    waitingWaiting for the author: changes were asked for without blocking.
    rejectedBlocks the merge ("request changes", "rejected").
    noneAsked to review, no decision yet, or only commented.

    required is true when the host's policy needs this reviewer's approval, and absent on hosts without that notion. mergeability is clean, conflicts, blocked or unknown (the host has not computed it yet). Every number in counts is absent rather than guessed.

    Diffs

    patch holds unified-diff hunks (@@ -a,b +c,d @@ headers, then , + and - lines) without a file header: the path and the change type are fields. It is empty for a binary file (binary: true), for a pure rename, and when the host gave no patch. A file is never left out, so "not shown" can be told from "not changed".

    OptionDefaultMeaning
    pathsevery changed fileOnly these repo-relative paths; the old path of a rename works too.
    contextLinesDEFAULT_PR_DIFF_CONTEXT_LINES (3)Unchanged lines around each change. A host that cannot vary it uses its own.
    maxFileCharsDEFAULT_PR_DIFF_MAX_FILE_CHARS (60,000)Each file's patch is cut at this many characters, on a line boundary, and marked truncated.
    limit, cursorlimit counts files.

    Review threads

    A thread has a status, at least one comment (the first one opened it), and a position: path with an optional line range and a side, or no path for the general conversation.

    statusMeaning
    activeOpen for discussion.
    resolvedSomeone closed it. resolution keeps the host's own word: "fixed", "wontfix", "by design".
    outdatedThe code it was written on has changed since and nobody resolved it. A host without that notion never uses it.

    Threads made only of system entries (a vote, a push) are dropped; a system entry inside a human thread is kept with system: true. side: "old" means a removed line, numbered in the target's version of the file.

    groupThreadsByFile(threads) arranges them the way a person works through them: file by file sorted by path, inside a file by line, the general conversation last, with counts per status. It is pure and does not filter: pass it what should be shown. ReviewThread.id is what a pull_request.reply write takes as threadId.

    How each host maps its own review states and thread states onto these words, and which endpoints were verified against a live service, is on pull requests and on the connector pages: Azure Repos, GitHub, GitLab.

    When a host cannot do it

    A host without the needed capability makes the call fail with UNSUPPORTED, naming the host and what it can do. The local host has no pull requests at all.

    pulls-unsupported.ts
    import { createSafran, isSafranError } from "@safran/core";
    
    await using safran = await createSafran();
    
    try {
      const diff = await safran.pulls.diff("payments-api#7");
      console.log(`${diff.items.length} files`);
    } catch (error) {
      if (isSafranError(error, "UNSUPPORTED")) console.error(`${error.message}. ${error.hint ?? ""}`);
      else if (isSafranError(error, "NOT_FOUND")) console.error(error.message);
      else throw error;
    }

    A pull request id that does not exist in the repo is NOT_FOUND, as is a repo name no host lists (with the closest names in the hint).

    The types

    /**
     * Live pull requests across every code host of the profile, with the conventions of
     * `TicketsApi`. `ref` is whatever a person would paste: a pull request URL, the explicit form
     * `<host id>:<repo>#<id>`, or `<repo>#<id>` when the repo name is unique across hosts
     * (`!` is accepted for `#`). A host without the needed capability makes the call UNSUPPORTED,
     * naming the host and its capabilities.
     */
    export interface PullsApi {
      /**
       * Finds the host and repo a reference belongs to. NOT_FOUND when no host recognises it,
       * INVALID_INPUT when several do (the hint shows the explicit form). Asynchronous, unlike
       * `tickets.resolve`: the `<repo>#<id>` form needs the repo listing. It does not check that the
       * pull request exists.
       */
      resolve(ref: string, options?: CallOptions): Promise<ResolvedPullRequestRef>;
      find(query: PullRequestFindQuery, options?: PullRequestFindOptions): Promise<PullRequestFindResult>;
      /** One merged page over hosts and repos, roughly newest first. The cursor is opaque and belongs to the same options. */
      list(options?: PullRequestListOptions): Promise<PullRequestListResult>;
      get(ref: string, options?: CallOptions): Promise<LivePullRequest>;
      changes(ref: string, options?: PageOptions): Promise<Page<PullRequestChange>>;
      /** Needs `pr-diff`. */
      diff(ref: string, options?: PullRequestDiffOptions): Promise<Page<PullRequestDiff>>;
      /** Needs `pr-threads`. Group the result for display with kit `groupThreadsByFile`. */
      threads(ref: string, options?: ReviewThreadQuery): Promise<Page<ReviewThread>>;
    }
    
    /**
     * A pull request as it is now, with the code host entry it came from and every ticket key
     * found for it: the host's native links plus keys recognised in the title, the source branch
     * and the description (the same recognition the link store uses).
     */
    export interface LivePullRequest extends PullRequestDetails {
      host: string;
      ticketKeys: string[];
    }
    
    export interface PullRequestFindResult {
      /** Newest first. Empty when nothing matches (that is an answer, not an error). */
      matches: LivePullRequest[];
      /**
       * The match a caller should read without asking: the only one, or the only OPEN one among
       * several. Absent when the choice is not obvious; show `matches` and ask.
       */
      best?: LivePullRequest;
      /** True when more matched than `limit`. */
      truncated: boolean;
      warnings?: SafranWarning[];
    }

    defined in packages/core/src/api.ts

    /**
     * A pull request in its current state. Extends the wave 1 `PullRequest` (which only ever
     * described merged ones), so everything that reads a `PullRequest` also reads this.
     */
    export interface PullRequestDetails extends PullRequest {
      state: PullRequestState;
      /** Open but marked not ready for review ("draft", "work in progress"). Always false once merged or closed. */
      draft: boolean;
      createdAt?: string;
      /** Last activity the host records: a push, a comment, a vote. Absent when the host has no such date. */
      updatedAt?: string;
      /** When it was closed without merging. `mergedAt` (inherited) is the date of a merge. */
      closedAt?: string;
      /** Empty when nobody was asked. ABSENT when a listing does not carry reviewers: fetch the pull request to know. */
      reviewers?: PullRequestReviewer[];
      /** Label / tag names, as the host shows them. Empty when the host has no labels on pull requests. */
      labels: string[];
      /** Tip of the source branch: the commit a line comment is anchored to. */
      headSha?: string;
      /** Commit of the target branch the changes are compared against. */
      baseSha?: string;
      mergeability?: PullRequestMergeability;
      counts?: PullRequestCounts;
    }
    
    /** One file a pull request changes. */
    export interface PullRequestChange {
      /** Repo-relative path after the change (for a delete: the path that was removed). */
      path: string;
      /** Only for `rename`: where the file was. A rename that also edits content is still `rename`. */
      previousPath?: string;
      change: PullRequestChangeType;
      /** Line counts, when the host reports them. Absent for binary files and on hosts that list paths only. */
      additions?: number;
      deletions?: number;
    }
    
    /** The diff of one file. */
    export interface PullRequestDiff extends PullRequestChange {
      /**
       * Unified-diff hunks: `@@ -a,b +c,d @@` headers followed by ` `, `+` and `-` lines, joined
       * with `\n`. No `diff --git` / `---` / `+++` file header (path and change type are fields).
       * Empty for a binary file, for a pure rename, and when the host gave no patch.
       */
      patch: string;
      /** True when `patch` is shorter than the real diff: cut at `maxFileChars`, or withheld by the host as too large. */
      truncated: boolean;
      binary: boolean;
    }
    
    export interface ReviewThread {
      /** What `replyToPullRequestThread` takes. Unique inside one pull request. */
      id: string;
      /** Repo-relative file the thread is on. Absent for the general conversation. */
      path?: string;
      /** 1-based line range in the file version `side` names. Absent for file-level and general threads. `end` is absent for a single line. */
      line?: { start: number; end?: number };
      /** `new`: the file after the change (the usual case). `old`: a removed line, numbered in the target's version. */
      side?: "old" | "new";
      status: ReviewThreadStatus;
      /** The host's own word for a resolved thread: "fixed", "wontfix", "by design", … */
      resolution?: string;
      /** At least one comment, oldest first. The first one opened the thread. */
      comments: ReviewComment[];
      createdAt?: string;
      updatedAt?: string;
    }
    
    export interface ReviewComment {
      id: string;
      author?: Person;
      /** Markdown. */
      body: string;
      createdAt?: string;
      updatedAt?: string;
      /** Written by the host, not a person ("pushed 2 commits", "voted 10"). Never true for a whole returned thread. */
      system: boolean;
    }

    defined in packages/kit/src/pulls.ts

    Common mistakes

    • Using safran.links for an open pull request. The link store holds merged work only. safran.pulls asks the host now.
    • Taking found.matches[0] instead of found.best. Several pull requests can carry one ticket key. best is only set when the choice is obvious.
    • Reading reviewers from a listing. It may be absent there. Call get for votes.
    • Treating closed as "done". closed means abandoned; a merged pull request is merged.
    • Passing part of a name as author or reviewer. The match is exact (case ignored for names and e-mail addresses).
    • Reusing a cursor with other filters. A cursor belongs to the options it was made with; anything else is INVALID_INPUT.