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
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.890Zrefresh 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?
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.tsWhich tickets touched this file?
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 1query 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:
| Field | Meaning |
|---|---|
host | Id of the code host entry it came from. |
ticketKeys | The 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. |
changedFiles | Repo-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:
- 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.
- 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:
| Text | With project PAY | Why |
|---|---|---|
PAY-1423, pay-1423, PAY_1423 | PAY-1423 | A dash or underscore separator matches in any case, which covers branch names. |
PAY 1423, PAY/1423, PAY1423 | PAY-1423 | A space, a slash or no separator match only when the key is written in upper case. |
pay 1423, Pay1423 | nothing | Lower case with a loose separator is ordinary prose. |
REPAY-3, PAY-4x | nothing | A letter or digit directly before or after is not a boundary. |
PAY-0042 | PAY-42 | Keys are upper-cased and leading zeros are dropped. |
Which hosts provide pull requests
| Code host | Merged pull requests |
|---|---|
azure-repos | yes |
github | yes |
gitlab | yes (merge requests) |
local | no 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
| Option | Default | Meaning |
|---|---|---|
repos | every repo of a host with pull requests | Repo names. An unknown name throws NOT_FOUND. |
since | the repo's earlier horizon, or 12 months back on its first refresh | ISO date: how far back the stored history must reach. |
maxPerRepo | 500 | Cap on pull requests newly stored per repo in one run. A whole number of at least 1. |
projectKeys | every project declared in the profile | Project keys used to recognise ticket keys in text. |
onProgress | none | Called 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
| Field | Meaning |
|---|---|
repo | Repo name. |
status | ok, failed, or skipped (the run was cancelled before this repo was read completely; nothing of it was stored). |
fetched | Pull requests written to the store in this run: new ones, and stored ones seen again. |
linked | How many of those carry at least one ticket key. |
truncated | true while the store does not reach back to the horizon for this repo. Absent otherwise. |
error | Present 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
| Field | Matches |
|---|---|
ticket | Records that carry this ticket key. Case does not matter and leading zeros are ignored: pay-0042 finds PAY-42. |
repo | Records of this repository (case-insensitive). |
path | Records that changed this repo-relative file. A trailing slash asks for everything under a directory: src/refund/. |
since | mergedAt at or after this ISO date. |
until | mergedAt before this ISO date (exclusive). |
limit | Records 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:
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 after the project keys changed
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.
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 changedUse 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
| Field | Meaning |
|---|---|
records | Stored pull requests. |
linked | How 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. |
refreshedAt | Time of the last refresh in which at least one repo succeeded. Absent before the first one. |
incompleteRepos | Repos 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
| Symptom | Cause |
|---|---|
linked is 0 although branches carry ticket keys | The profile declares no projects for the tracker. Declare them and call relink(). |
| A ticket's older pull requests are missing | The repo is in incompleteRepos (run refresh again), or they are older than the horizon (pass an earlier since). |
query({ path: "src/refund" }) finds nothing | Without a trailing slash path is an exact file path. Use src/refund/ for a directory. |
Expecting refresh to throw on a failing repo | Failures are rows. Check status of each row and aborted. |
Nothing stored for a local host's repo | A local host has no pull requests. |