Skip to content
safran

Type to search. Enter opens the first result.

    Work history: tickets and code

    safran.links is the memory of finished work. It stores every merged pull request of your repositories with the tickets it was done for and the files it touched, in a local SQLite file. From it you can answer "what did PAY-1423 change" and "which tickets touched this file" without asking a code host. The same store feeds ownership inference, discovery and the evaluation golden set.

    Fill the store

    refresh-links.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const controller = new AbortController();
    process.once("SIGINT", () => controller.abort());
    
    const report = await safran.links.refresh({
      signal: controller.signal,
      onProgress: ({ repo, fetched }) => process.stderr.write(`\r${repo}: ${fetched} pull requests`),
    });
    process.stderr.write("\n");
    
    for (const row of report.repos) {
      if (row.status === "failed") console.log(`failed   ${row.repo}  ${row.error?.code}: ${row.error?.message}`);
      else if (row.status === "skipped") console.log(`skipped  ${row.repo}`);
      else console.log(`ok       ${row.repo}  ${row.fetched} stored, ${row.linked} with a ticket key${row.truncated ? "  (more to fetch: run again)" : ""}`);
    }
    if (report.aborted) console.log("cancelled: the repos marked skipped were not stored");
    
    const status = await safran.links.status();
    console.log(`${status.records} records, ${status.linked} linked, refreshed ${status.refreshedAt ?? "never"}`);
    if (status.incompleteRepos.length > 0) console.log(`history incomplete for: ${status.incompleteRepos.join(", ")}`);

    Standard output for two of acme's repositories (the progress line goes to standard error):

    $ bun refresh-links.ts
    ok       payments-api  3 stored, 2 with a ticket key
    ok       ledger  0 stored, 0 with a ticket key
    3 records, 2 linked, refreshed 2026-11-23T11:34:36.890Z

    refresh is the only call here that uses the network. query, count, relink and status read the local store.

    Ask the store

    What did PAY-1423 change?

    ticket-changes.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const records = await safran.links.query({ ticket: "PAY-1423" });
    
    for (const record of records) {
      console.log(`${record.repo} #${record.id}  ${record.title}  (${record.author?.name ?? "unknown"}, merged ${record.mergedAt?.slice(0, 10)})`);
      for (const file of record.changedFiles) console.log(`  ${file}`);
    }
    $ bun ticket-changes.ts
    payments-api #101  PAY-1423 fix partial refund rounding  (Ayşe Yılmaz, merged 2026-11-03)
      src/refund/service.ts
      src/refund/policy.ts

    Which tickets touched this file?

    file-tickets.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const query = { repo: "payments-api", path: "src/refund/service.ts" };
    const records = await safran.links.query({ ...query, limit: 20 });
    const total = await safran.links.count(query);
    
    const tickets = new Map<string, number>();
    for (const record of records) {
      for (const key of record.ticketKeys) tickets.set(key, (tickets.get(key) ?? 0) + 1);
    }
    
    console.log(`${total} merged pull requests changed ${query.path}`);
    for (const [key, count] of [...tickets].sort((a, b) => b[1] - a[1])) console.log(`${key}  ${count}`);
    $ bun file-tickets.ts
    1 merged pull requests changed src/refund/service.ts
    PAY-1423  1

    query returns at most limit records; count tells you how many match in total, so you can say "20 of 87" honestly.

    What a record is

    A WorkRecord is one merged pull request as the code host reported it, plus three fields Safran adds:

    FieldMeaning
    hostId of the code host entry it came from.
    ticketKeysThe tickets it was done for: the host's own links first, then keys recognised in the title, the branch name and the description. May be empty.
    changedFilesRepo-relative paths it changed, with forward slashes.

    The inherited PullRequest fields are id, repo (the name Safran uses for the repository), title, description, url, author, sourceBranch, targetBranch, mergedAt (normalised to ISO 8601 in UTC), mergeCommit and linkedTicketKeys (only what the host itself links).

    /** A merged pull request with the tickets it was done for and the files it touched. */
    export interface WorkRecord extends PullRequest {
      host: string;
      /** Host-native links plus keys recognised in the title, branch and description. */
      ticketKeys: string[];
      changedFiles: string[];
    }
    
    export interface PullRequest {
      id: string;
      repo: string;
      title: string;
      description: string;
      url?: string;
      author?: Person;
      sourceBranch?: string;
      targetBranch?: string;
      mergedAt?: string;
      /** Commit the PR was merged as. */
      mergeCommit?: string;
      /** Ticket keys the host itself links to the PR (work items, closing references). */
      linkedTicketKeys: string[];
      /** Repo-relative paths changed by the PR. Absent when the host needs a second call. */
      changedFiles?: string[];
    }

    defined in packages/core/src/api.ts, packages/kit/src/types.ts

    How ticket keys are recognised

    Two sources are combined, in this order, without duplicates:

    1. Host-native links: work items or closing references the code host attaches to the pull request. They are always kept, whatever the project keys are.
    2. Keys in text: the title, then the source branch, then the description are scanned for keys of known projects.

    "Known projects" are the keys declared under trackers[].projects in the profile (or the projectKeys option). The scan is deliberately narrow, so that prose does not turn into tickets:

    TextWith project PAYWhy
    PAY-1423, pay-1423, PAY_1423PAY-1423A dash or underscore separator matches in any case, which covers branch names.
    PAY 1423, PAY/1423, PAY1423PAY-1423A space, a slash or no separator match only when the key is written in upper case.
    pay 1423, Pay1423nothingLower case with a loose separator is ordinary prose.
    REPAY-3, PAY-4xnothingA letter or digit directly before or after is not a boundary.
    PAY-0042PAY-42Keys are upper-cased and leading zeros are dropped.

    Which hosts provide pull requests

    Code hostMerged pull requests
    azure-reposyes
    githubyes
    gitlabyes (merge requests)
    localno A directory has no pull requests.

    A refresh without repos quietly leaves out the repositories of hosts without the pull-requests capability. Naming such a repo in repos gives a failed row with UNSUPPORTED.

    Refresh in detail

    OptionDefaultMeaning
    reposevery repo of a host with pull requestsRepo names. An unknown name throws NOT_FOUND.
    sincethe repo's earlier horizon, or 12 months back on its first refreshISO date: how far back the stored history must reach.
    maxPerRepo500Cap on pull requests newly stored per repo in one run. A whole number of at least 1.
    projectKeysevery project declared in the profileProject keys used to recognise ticket keys in text.
    onProgressnoneCalled with { repo, fetched } after each pull request.

    signal from CallOptions cancels the run.

    The horizon, and resuming

    Every repo has a horizon: the date its stored history is meant to reach back to. The first refresh sets it to twelve months ago, or to since. Later refreshes keep it unless you pass an earlier since.

    A repo with more pull requests inside the horizon than maxPerRepo is not finished in one run. Its row has truncated: true, and links.status() lists it under incompleteRepos. Run refresh again to continue: pull requests that are already stored are recognised and do not count against the cap, so each run gets maxPerRepo records further. Once a listing was read to its end the repo is complete, and later refreshes only fetch what was merged since the newest stored record.

    Passing since explicitly always re-reads that whole window.

    The report

    FieldMeaning
    repoRepo name.
    statusok, failed, or skipped (the run was cancelled before this repo was read completely; nothing of it was stored).
    fetchedPull requests written to the store in this run: new ones, and stored ones seen again.
    linkedHow many of those carry at least one ticket key.
    truncatedtrue while the store does not reach back to the horizon for this repo. Absent otherwise.
    errorPresent when status is failed: a BatchError.

    The report itself has repos (the rows), durationMs and aborted.

    export interface LinkRefreshOptions extends CallOptions {
      repos?: string[];
      /**
       * ISO date: how far back the history must reach (the horizon). Default: the horizon of the
       * repo's earlier refreshes, or 12 months back on its first one.
       */
      since?: string;
      /**
       * Cap on pull requests newly stored per repo in one run. A repo with more than that inside
       * the horizon is reported `truncated` and later runs continue where this one stopped.
       */
      maxPerRepo?: number;
      /**
       * Project keys used to recognise ticket keys in titles, branches and descriptions.
       * Default: every project declared under `trackers[].projects` in the profile (none in a
       * profile that does not declare its projects yet).
       */
      projectKeys?: string[];
      onProgress?: (progress: { repo: string; fetched: number }) => void;
    }
    
    export interface LinkRefreshReport {
      repos: LinkRefreshRepoResult[];
      durationMs: number;
      /** True when the run was cancelled (by the signal or by `close()`). Never thrown instead. */
      aborted?: boolean;
    }
    
    export interface LinkRefreshRepoResult {
      repo: string;
      /** "skipped": the run was cancelled before this repo was read completely; nothing of it was stored. */
      status: "ok" | "failed" | "skipped";
      /** Pull requests written to the store in this run (new ones, and stored ones seen again). */
      fetched: number;
      /** How many of those carry at least one ticket key. */
      linked: number;
      /**
       * True while the store does not reach back to the horizon for this repo, because `maxPerRepo`
       * stopped the run. Run the refresh again to continue.
       */
      truncated?: boolean;
      /** Present when status is "failed". */
      error?: BatchError;
    }

    defined in packages/core/src/api.ts

    What throws and what is reported

    refresh throws only before any work starts: INVALID_INPUT for a since that is not a date, a maxPerRepo below 1 or an empty project key; NOT_FOUND for an unknown repo; the listing error when no host can list its repositories; INCOMPATIBLE_DATA or INTERNAL when the store file cannot be opened.

    After that it always returns a report. A repo that fails is a failed row and the others continue. A cancelled run (by the signal or by close()) returns with aborted: true: each repo is written in one transaction when it is finished, so the repos done before the cancellation are stored and the one that was interrupted is not.

    Calls on one instance run one after the other: a second refresh, or a relink, waits for the running one.

    Query in detail

    FieldMatches
    ticketRecords that carry this ticket key. Case does not matter and leading zeros are ignored: pay-0042 finds PAY-42.
    repoRecords of this repository (case-insensitive).
    pathRecords that changed this repo-relative file. A trailing slash asks for everything under a directory: src/refund/.
    sincemergedAt at or after this ISO date.
    untilmergedAt before this ISO date (exclusive).
    limitRecords returned by query. Default 100. count ignores it.

    Fields combine with AND. An empty query matches everything. Records come back newest first. A since or until that is not a date is INVALID_INPUT. Before the first refresh there is no store: query returns an empty list and count returns 0; neither creates the file.

    since and until make a half-open window, which is what counting per period needs:

    per-month.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const october = { repo: "payments-api", since: "2026-10-01", until: "2026-11-01" };
    console.log(`${await safran.links.count(october)} pull requests merged in October`);
    console.log(`${await safran.links.count({ ...october, path: "src/refund/" })} of them touched src/refund/`);

    path is matched against the paths as they were when the pull request merged. A file that was renamed later is found under its old name in older records.

    relink recomputes ticketKeys of every stored record from its stored title, branch and description, with the current project keys. Host-native links are kept. It makes no network call.

    relink.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const report = await safran.links.relink();
    console.log(`${report.records} records looked at, ${report.linked} linked, ${report.changed} changed`);
    $ bun relink.ts
    3 records looked at, 2 linked, 0 changed

    Use it after adding a tracker project to the profile, or pass projectKeys to try a set of keys. Records are rewritten in batches, each in its own transaction, so a cancelled relink (it throws ABORTED) leaves every record either old or new.

    export interface RelinkOptions extends CallOptions {
      /** Same meaning and default as `LinkRefreshOptions.projectKeys`. */
      projectKeys?: string[];
    }
    
    export interface RelinkReport {
      /** Stored records looked at. */
      records: number;
      /** Records that carry at least one ticket key afterwards. */
      linked: number;
      /** Records whose ticket keys are different from before. */
      changed: number;
    }

    defined in packages/core/src/api.ts

    Status

    FieldMeaning
    recordsStored pull requests.
    linkedHow many carry at least one ticket key. A low share means the keys are not being recognised: check projects in the profile and your branch naming.
    refreshedAtTime of the last refresh in which at least one repo succeeded. Absent before the first one.
    incompleteReposRepos whose stored history does not reach their horizon yet.

    Where the store lives

    The store is <dataDir>/safran.db, a SQLite database (LINKS_DB_FILE). It holds titles, descriptions, author names and file paths of your pull requests, so treat it like the repositories themselves. It can always be rebuilt: delete the file and refresh again.

    A store written by a newer Safran, or a file that is not a database, fails with INCOMPATIBLE_DATA and a hint that says exactly that.

    Common mistakes

    SymptomCause
    linked is 0 although branches carry ticket keysThe profile declares no projects for the tracker. Declare them and call relink().
    A ticket's older pull requests are missingThe repo is in incompleteRepos (run refresh again), or they are older than the horizon (pass an earlier since).
    query({ path: "src/refund" }) finds nothingWithout a trailing slash path is an exact file path. Use src/refund/ for a directory.
    Expecting refresh to throw on a failing repoFailures are rows. Check status of each row and aborted.
    Nothing stored for a local host's repoA local host has no pull requests.