@safran/discover
@safran/discover drafts a company profile from what the trackers and code hosts of a Safran instance reveal: tracker projects, repo groups, teams, glossary candidates, conventions and languages. This page documents discoverProfile, every option and threshold with its default, the result types, renderFindings, and the pure inference functions the package exports. It is counting and heuristics; no language model is involved, and the result is a draft a person must review. The safran discover command (CLI: set up) is a thin shell over this package, and the discovery guide walks through reviewing a draft.
Example: discovery over fakes
The example builds a Safran instance over the in-memory connectors of @safran/kit/testing (see Testing), with a seed profile that only has the connectors, and lets discovery propose the rest. Nothing touches the network.
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createSafran } from "@safran/core";
import { discoverProfile, renderFindings } from "@safran/discover";
import type { PullRequest } from "@safran/kit";
import { FakeCodeHost, FakeCodeIndex, FakeTracker, fakePlugins, type FakeTicket } from "@safran/kit/testing";
// Twelve finished tickets and the pull requests that closed them, one a week.
const tickets: FakeTicket[] = [];
const pullRequests: PullRequest[] = [];
for (let n = 0; n < 12; n++) {
const key = `PAY-${1400 + n}`;
const refund = n % 2 === 0;
tickets.push({ key, title: refund ? `Kısmi iade tutarı yanlış hesaplanıyor (${n})` : `Sepet toplamı kampanya indirimini yok sayıyor (${n})` });
pullRequests.push({
id: String(100 + n),
repo: "payments-api",
title: `${key}: ${refund ? "fix partial refund amount" : "apply campaign discount to basket total"}`,
description: "",
author: { name: refund ? "Deniz" : "Ece" },
sourceBranch: `feature/${key}`,
mergedAt: new Date(Date.UTC(2026, 5, 1 + n * 7)).toISOString(),
linkedTicketKeys: [key],
changedFiles: refund ? ["src/refund/service.ts", "src/refund/policy.ts"] : ["src/basket/total.ts"],
});
}
await using safran = await createSafran({
// The seed: connectors only. Discovery proposes the rest.
profile: {
version: 1,
company: "acme",
trackers: [{ id: "jira", type: "fake" }],
code: { hosts: [{ id: "azure", type: "fake" }] },
embeddings: { type: "fake" },
},
builtinPlugins: false,
plugins: fakePlugins({
trackers: [new FakeTracker({ id: "jira", projects: [{ key: "PAY", name: "Payments" }], tickets })],
hosts: [
new FakeCodeHost({
id: "azure",
repos: [
{ name: "payments-api", primaryLanguage: "TypeScript" },
{ name: "acme-ios", primaryLanguage: "Swift" },
],
pullRequests,
}),
],
}),
index: new FakeCodeIndex(),
dataDir: mkdtempSync(join(tmpdir(), "acme-discover-")),
});
const result = await discoverProfile(safran, { since: "2026-01-01" });
console.log(renderFindings(result)); // the reasoning, for a person
console.log(result.yaml); // the draft profile, ready to write to a file
console.log(result.stats.added);renderFindings(result) prints the reasoning behind every proposal:
Safran discovery — draft for review (statistics and heuristics, no language model)
2 repos (0 cloned), 12 merged PRs read, 12 used, 12 with a ticket (0% without), 12 ticket titles
sampled.
Legend: + added to the draft, · observation only; [high] [med ] [low ] = confidence.
Coverage (1)
· [low ] ticket references in merged PRs
All 12 merged PRs read reference a ticket.
Tracker projects (1)
+ [med ] tracker jira
Tracker "jira" lists 1 project; all were added. Merged pull requests reference 1 of them
(PRs per project: PAY 12). Remove the ones no team here works on.
Repo groups (2)
+ [med ] acme-ios → mobile
name contains "ios"; primary language Swift. Not cloned, so manifests were not read.
+ [low ] payments-api → backend
name contains "api". Not cloned, so manifests were not read.
Teams (1)
+ [med ] Payments ↔ payments-api
Payments ↔ payments-api: 12 of 12 ticket-linked PRs in this repo reference PAY tickets
(recency-weighted share 100%).
Glossary candidates (1)
· [low ] glossary candidates
0 recurring terms in 12 sampled ticket titles: 0 already appear in code or changed paths,
0 have too few focused PRs to compare, 0 have no path word that stands out, 0 point at a
code word a commoner term already took; 0 proposed. Single words only; expect misses and
some wrong pairs.
Conventions (3)
+ [low ] ticket title language
12 of 12 sampled ticket titles look Turkish, 0 English, 0 another language, 0 undecided
(100% of the classified ones). Language detection is a heuristic (Turkish-only letters
and small word lists for tr/en).
+ [low ] branch naming
12 of 12 source branches (100%) have the shape type/key.
+ [low ] pull request titles
12 of 12 PR titles (100%) have the shape "key: text".
Languages (1)
+ [low ] languages.tickets = tr
12 of 12 sampled ticket titles look Turkish, 0 English, 0 another language, 0 undecided
(100% of the classified ones). Language detection is a heuristic (Turkish-only letters
and small word lists for tr/en). `languages.code` is set to "en" by default; it was not
measured.
Added to the draft: 1 project key(s), 2 grouped repo(s), 1 team(s), 0 repo(s) on existing teams, 0
glossary candidate(s), 3 convention(s), languages.
Findings by confidence: 0 high, 3 medium, 7 low.result.yaml is the seed plus the additions, each marked where it sits. No glossary entry was proposed in this run: with twelve titles, a word that appears in half of them is above glossaryMaxTicketShare and counts as too generic.
# DRAFT profile written by `safran discover`. Review it before use.
#
# What you wrote was kept as it was. Everything else was inferred from tracker and code-host
# data with counting and heuristics (no language model), so some of it is wrong.
# Added: 1 tracker project key(s), 2 repo(s) in new groups, 1 team(s), 3 convention(s), languages.
#
# How to review:
# 1. Lines ending in `# discovered`, teams with `confidence:` / `source:` and glossary entries
# whose `note:` starts with "discovered" are guesses. `low` means: do not trust until checked.
# 2. `safran discover` printed 10 finding(s) with the numbers behind every guess; read the
# low-confidence ones first. Glossary candidates are co-occurrence, not translation.
# 3. Fix or delete what is wrong. Once a team is confirmed, remove its `confidence` and `source`.
# 4. Run `safran profile check`.
version: 1
company: acme
trackers:
- id: jira
type: fake
projects:
- PAY # discovered
code:
hosts:
- id: azure
type: fake
groups:
backend:
- payments-api # discovered (low)
mobile:
- acme-ios # discovered (medium)
embeddings:
type: fake
languages:
tickets: tr # discovered from ticket titles
code: en # default, not measured
teams:
- name: Payments
projects:
- PAY
repos:
- payments-api
confidence: medium
source: 12 ticket-PR links
conventions:
- Ticket titles are written in Turkish. # discovered
- "Branch names follow <type>/<TICKET-KEY>-short-description (types in use: feature)." # discovered
- "Pull request titles start with the ticket key: \"<TICKET-KEY>: short description\"." # discovereddiscoverProfile
/**
* Drafts a company profile from what the trackers and code hosts of a Safran instance
* reveal. The instance is built from a seed profile that has the connectors configured;
* the result is that seed plus proposals, each explained by a finding. Nothing is written
* to disk and no language model is involved.
*/
export async function discoverProfile(safran: Safran, options: DiscoverOptions = {}): Promise<DiscoveryResult>;defined in packages/discover/src/discover.ts
Gathers data through the instance and hands it to the pure inference steps. All I/O of the package happens here; nothing is written to the profile or to any file of yours. What it does, in order:
- Reads the seed:
options.seed, else the profile file the instance was loaded from (read raw, so schema defaults are not written into the draft), elsesafran.profilewith values equal to a default treated as "not written". - Lists the repositories (
safran.repos.list) and the projects of every tracker in the seed (tracker.listProjects). - Unless
refreshLinksisfalse, pulls merged pull requests into the local link store withsafran.links.refresh(see Links), then reads the store withsafran.links.queryfor the window. - Drops noise: bot authors, merge and revert titles, mass changes, pull requests naming many tickets, and the same change opened against several branches.
- Samples ticket titles: up to
sampleTicketscalls tosafran.tickets.get, at mostDEFAULT_TICKET_CONCURRENCY(4) in flight, taking keys from each repo in turn so one busy repo does not fill the sample. - Runs the steps: projects → groups → teams → conventions and languages → glossary. For glossary candidates it also asks the code index (
safran.code.status,safran.code.grep) whether a term already occurs in code. - Merges the additions into the seed, validates the draft with
parseProfile, and renders the YAML.
What it touches: the tracker and code-host APIs (read-only), the local link store under the data directory (written by the refresh), root entries and package.json of repos that are already cloned, and the code index if one is open. It never clones and never indexes.
Every step degrades to a finding instead of failing the run. A tracker that rejects its token, a code host that cannot list pull requests or an index that is not built becomes a finding of kind problem or coverage, and the steps that can still run do. Only two things throw:
| Code | When |
|---|---|
INVALID_INPUT | since is not a date; maxPerRepo is not a positive integer; sampleTickets or glossary.maxTerms is not a non-negative integer |
PROFILE_INVALID | options.seed does not validate |
ABORTED | options.signal was aborted, or the instance was closed, while it ran |
Rules the result keeps: nothing the human wrote is removed, reordered or reworded; a tracker that already declares projects is left alone; a repo already in a human group is not regrouped; with teams in the seed no team is invented, and repos are only added to the one team that owns the project. The same input gives the same output: the reference point for recency is the newest merge date in the data, not the clock.
DiscoverOptions
export interface DiscoverOptions {
signal?: AbortSignal;
onProgress?: (progress: DiscoverProgress) => void;
/** ISO date: how far back merged PRs are read. Default: `DEFAULT_LOOKBACK_MONTHS` before `now`. */
since?: string;
/** Cap on PRs fetched per repo, newest first. Default: the core default. */
maxPerRepo?: number;
/** Default true. `false` uses what is already in the local store and fetches nothing. */
refreshLinks?: boolean;
/** Tickets fetched at most for titles. `0` fetches none. Default: `DEFAULT_SAMPLE_TICKETS`. */
sampleTickets?: number;
glossary?: GlossaryOptions;
thresholds?: Partial<DiscoverThresholds>;
/** Author names (case-insensitive) treated as bots on top of the built-in patterns. */
botAuthors?: readonly string[];
/**
* The profile exactly as the human wrote it. Default: the profile file the instance was
* loaded from, else `safran.profile` (which has schema defaults filled in).
*/
seed?: ProfileInput;
/** Only used to compute the default `since`. Default: the current time. */
now?: Date;
}defined in packages/discover/src/types.ts
| Option | Type | Default | Meaning |
|---|---|---|---|
signal | AbortSignal | none | Cancels the run; it rejects with ABORTED. |
onProgress | (progress: DiscoverProgress) => void | none | Called at each step and per ticket and repo inside the long ones. |
since | ISO date string | DEFAULT_LOOKBACK_MONTHS (12) months before now | How far back merged pull requests are read from the store. Passed to links.refresh only when you set it; otherwise the refresh uses its own horizon. |
maxPerRepo | positive integer | the default of links.refresh | Cap on pull requests fetched per repo by the refresh. |
refreshLinks | boolean | true | false fetches nothing and uses what the local store already holds. |
sampleTickets | non-negative integer | DEFAULT_SAMPLE_TICKETS (200) | Tickets fetched for their titles, one request each. 0 fetches none: no ticket language, no glossary. |
glossary | GlossaryOptions | enabled, 20 terms | See below. |
thresholds | Partial<DiscoverThresholds> | the DEFAULT_* constants | Any subset of the tunable numbers. |
botAuthors | readonly string[] | [] | Author names (case-insensitive) treated as bots on top of the built-in patterns. |
seed | ProfileInput | the profile file, else safran.profile | The profile exactly as the human wrote it. |
now | Date | the current time | Only used to compute the default since. |
export interface GlossaryOptions {
/** Default: true. */
enabled?: boolean;
/** Cap on proposed entries. Default: `DEFAULT_GLOSSARY_MAX_TERMS`. */
maxTerms?: number;
/** ISO 639-1 language of ticket titles. Default: detected from the sampled titles. */
language?: string;
}defined in packages/discover/src/types.ts
| Option | Type | Default | Meaning |
|---|---|---|---|
enabled | boolean | true | false skips glossary candidates. |
maxTerms | non-negative integer | DEFAULT_GLOSSARY_MAX_TERMS (20) | Cap on proposed entries. |
language | ISO 639-1 string | languages.tickets of the seed, else detected from the sampled titles | Language of ticket titles. When it equals the code language, no candidates are looked for. |
Progress events carry the step and, inside the long steps, counts:
export interface DiscoverProgress {
step: "repos" | "projects" | "links" | "tickets" | "groups" | "teams" | "glossary" | "conventions" | "profile";
message: string;
done?: number;
total?: number;
}defined in packages/discover/src/types.ts
import type { DiscoverOptions } from "@safran/discover";
const controller = new AbortController();
const options: DiscoverOptions = {
signal: controller.signal,
refreshLinks: false, // work from the local link store only
sampleTickets: 50,
glossary: { maxTerms: 10, language: "tr" },
botAuthors: ["acme-release-bot"],
onProgress: ({ step, message, done, total }) => {
console.error(total === undefined ? `${step}: ${message}` : `${step}: ${message} ${done ?? 0}/${total}`);
},
};DiscoverThresholds
Every tunable number. Pass any subset as options.thresholds; the rest keep the defaults below, which are exported constants.
/** Every tunable number. Defaults are the `DEFAULT_*` constants next to the code that uses them. */
export interface DiscoverThresholds {
/** Tracker projects proposed per tracker at most. */
maxProjectsPerTracker: number;
/** A PR changing more files than this is a mass change and is ignored for team inference. */
massChangeFiles: number;
/** A PR naming more tickets than this is a release / merge PR and is ignored. */
maxTicketsPerPull: number;
/** Ticket-linked PRs a repo ↔ project pair needs before anything is proposed. */
minLinks: number;
/** Recency-weighted share of a repo's linked PRs one project needs to own it. */
ownerShare: number;
/** Share at which a project co-owns a repo nobody owns outright. */
sharedShare: number;
/** Co-owners listed at most; a repo with more is reported as shared and left unassigned. */
maxCoOwners: number;
/** Days after which a link counts half. */
recencyHalfLifeDays: number;
mediumMinLinks: number;
highMinLinks: number;
highShare: number;
/** Tickets a term must appear in before it is a glossary candidate. */
glossaryMinTickets: number;
/** A term in more than this share of tickets is too generic to mean anything. */
glossaryMaxTicketShare: number;
/** PRs wider than this say nothing about which files belong to a term. */
glossaryMaxFiles: number;
/** PRs of a term that must touch a path token before the token is suggested. */
glossaryMinSupport: number;
/** Other PRs in the same repos needed to compare against. */
glossaryMinContrast: number;
/** Minimum (share in the term's PRs − share in other PRs) for a path token. */
glossaryMinLift: number;
glossaryMaxCodeWords: number;
/** Samples needed before a convention or a language is proposed. */
conventionMinSamples: number;
/** Share of samples that must agree. */
conventionMajority: number;
}defined in packages/discover/src/types.ts
| Threshold | Default | Constant | Meaning |
|---|---|---|---|
maxProjectsPerTracker | 25 | DEFAULT_MAX_PROJECTS_PER_TRACKER | A tracker listing longer than this is proposed only as far as merged pull requests reference it. |
massChangeFiles | 50 | DEFAULT_MASS_CHANGE_FILES | A pull request changing more files is a mass change and is ignored. |
maxTicketsPerPull | 5 | DEFAULT_MAX_TICKETS_PER_PULL | A pull request naming more tickets is a release or branch merge and is ignored. |
minLinks | 3 | DEFAULT_MIN_LINKS | Ticket-linked pull requests a repo ↔ project pair needs before anything is proposed. |
ownerShare | 0.6 | DEFAULT_OWNER_SHARE | Recency-weighted share of a repo's linked pull requests one project needs to own it. |
sharedShare | 0.3 | DEFAULT_SHARED_SHARE | Share at which a project co-owns a repo nobody owns outright. |
maxCoOwners | 2 | DEFAULT_MAX_CO_OWNERS | Co-owners listed at most; a repo with more is reported as shared and left unassigned. |
recencyHalfLifeDays | 180 | DEFAULT_RECENCY_HALF_LIFE_DAYS | Days after which a link counts half. |
mediumMinLinks | 8 | DEFAULT_MEDIUM_MIN_LINKS | Links needed before a team mapping is medium. |
highMinLinks | 20 | DEFAULT_HIGH_MIN_LINKS | Links needed before a team mapping can be high. |
highShare | 0.8 | DEFAULT_HIGH_SHARE | Share needed, together with highMinLinks, for high. |
glossaryMinTickets | 3 | DEFAULT_GLOSSARY_MIN_TICKETS | Tickets a term must appear in before it is a candidate. |
glossaryMaxTicketShare | 0.4 | DEFAULT_GLOSSARY_MAX_TICKET_SHARE | A term in more than this share of tickets is too generic. |
glossaryMaxFiles | 20 | DEFAULT_GLOSSARY_MAX_FILES | Pull requests wider than this say nothing about which files belong to a term. |
glossaryMinSupport | 3 | DEFAULT_GLOSSARY_MIN_SUPPORT | Pull requests of a term that must touch a path word before the word is suggested. |
glossaryMinContrast | 3 | DEFAULT_GLOSSARY_MIN_CONTRAST | Other pull requests in the same repos needed to compare against. |
glossaryMinLift | 0.4 | DEFAULT_GLOSSARY_MIN_LIFT | Minimum (share in the term's pull requests − share in the others) for a path word. |
glossaryMaxCodeWords | 3 | DEFAULT_GLOSSARY_MAX_CODE_WORDS | Code words suggested per term at most. |
conventionMinSamples | 10 | DEFAULT_CONVENTION_MIN_SAMPLES | Samples needed before a convention or a language is proposed. |
conventionMajority | 0.7 | DEFAULT_CONVENTION_MAJORITY | Share of samples that must agree. |
The eight team numbers are also available as one object:
export interface TeamThresholds {
minLinks: number;
ownerShare: number;
sharedShare: number;
maxCoOwners: number;
recencyHalfLifeDays: number;
mediumMinLinks: number;
highMinLinks: number;
highShare: number;
}
export const DEFAULT_TEAM_THRESHOLDS: TeamThresholds = {
minLinks: DEFAULT_MIN_LINKS,
ownerShare: DEFAULT_OWNER_SHARE,
sharedShare: DEFAULT_SHARED_SHARE,
maxCoOwners: DEFAULT_MAX_CO_OWNERS,
recencyHalfLifeDays: DEFAULT_RECENCY_HALF_LIFE_DAYS,
mediumMinLinks: DEFAULT_MEDIUM_MIN_LINKS,
highMinLinks: DEFAULT_HIGH_MIN_LINKS,
highShare: DEFAULT_HIGH_SHARE,
};defined in packages/discover/src/teams.ts
Other exported defaults of the orchestrator:
/** How far back merged PRs are read when `since` is not given. */
export const DEFAULT_LOOKBACK_MONTHS = 12;
/** Tickets fetched for their titles. One request each, so this bounds the tracker load. */
export const DEFAULT_SAMPLE_TICKETS = 200;
export const DEFAULT_TICKET_CONCURRENCY = 4;
/** Ticket reads that may fail in a row from the start before sampling gives up (a bad token fails them all). */
export const DEFAULT_TICKET_FAILURE_LIMIT = 10;
/** Records read from the local store at most. */
export const DEFAULT_MAX_RECORDS = 50_000;
/** Root entries looked at per cloned repo. */
export const DEFAULT_MAX_ROOT_ENTRIES = 400;
/** Glossary candidates checked against the code index, as a multiple of `maxTerms`. */
export const DEFAULT_GLOSSARY_CHECK_FACTOR = 3;DiscoveryResult
export interface DiscoveryResult {
/** The seed profile plus what discovery added. Validates with `parseProfile`. */
profile: ProfileInput;
/** `profile` as YAML with a review header, ready to write. */
yaml: string;
findings: Finding[];
stats: DiscoveryStats;
}defined in packages/discover/src/types.ts
| Field | Type | Meaning |
|---|---|---|
profile | ProfileInput | The seed plus what discovery added. It validates with parseProfile (profile API); in the unexpected case that it does not, a problem finding says so. |
yaml | string | profile as YAML with a review header and a # discovered comment on every added scalar. |
findings | Finding[] | One piece of reasoning per proposal or observation, ordered by FINDING_KINDS. |
stats | DiscoveryStats | The numbers of the run. |
Finding
/**
* One piece of reasoning a human can check. Every item discovery adds to the profile has a
* finding; findings with `detail.applied === false` are observations that changed nothing.
*/
export interface Finding {
kind: FindingKind;
/** What it is about: "Payments ↔ payments-api", "glossary: iade", "tracker jira". */
subject: string;
confidence: Confidence;
/** Human-readable reasoning with the numbers behind it. */
evidence: string;
/** The same numbers, machine-readable. JSON-serialisable. Always has `applied`. */
detail: Readonly<Record<string, unknown>> & { readonly applied: boolean };
}
/** Order findings are reported in. */
export const FINDING_KINDS = ["problem", "coverage", "project", "group", "team", "glossary", "convention", "language"] as const;
export type FindingKind = (typeof FINDING_KINDS)[number];
export type Confidence = "low" | "medium" | "high";defined in packages/discover/src/types.ts
| Field | Meaning |
|---|---|
kind | problem (something could not be read), coverage (how much data there was), then one kind per step: project, group, team, glossary, convention, language. |
subject | What it is about, for example Payments ↔ payments-api or tracker jira. |
confidence | low, medium or high. low means: do not trust until a person has checked. |
evidence | The reasoning in words, with the numbers behind it. |
detail | The same numbers, JSON-serialisable. Always has applied: true when the finding changed the draft, false for an observation. |
import type { DiscoveryResult, Finding } from "@safran/discover";
/** What a reviewer should read first: applied guesses at low confidence, and everything that failed. */
export function reviewFirst(result: DiscoveryResult): Finding[] {
return result.findings.filter((finding) => finding.kind === "problem" || (finding.detail.applied && finding.confidence === "low"));
}DiscoveryStats
export interface DiscoveryStats {
repos: number;
clonedRepos: number;
/** Merged PRs read from the local store for the window. */
pullRequests: number;
/** Left after bots, mass changes, merge/revert titles and duplicates were dropped. */
pullRequestsUsed: number;
dropped: { bot: number; noiseTitle: number; massChange: number; manyTickets: number; duplicate: number };
/** Used PRs that reference at least one ticket. */
linkedPullRequests: number;
/** Share of used PRs without any ticket key, 0..1. */
unlinkedShare: number;
ticketsSampled: number;
ticketsFailed: number;
added: { projects: number; groupedRepos: number; teams: number; teamRepos: number; glossary: number; conventions: number; languages: boolean };
findings: Record<Confidence, number>;
}defined in packages/discover/src/types.ts
| Field | Meaning |
|---|---|
repos | Repositories the code hosts listed. |
clonedRepos | How many of them are cloned locally (only those have their manifests read). |
pullRequests | Merged pull requests read from the local store for the window. |
pullRequestsUsed | Left after the noise filters. |
dropped | Counts per filter: bot, noiseTitle, massChange, manyTickets, duplicate. |
linkedPullRequests | Used pull requests that reference at least one ticket. |
unlinkedShare | Share of used pull requests without any ticket key, 0..1. |
ticketsSampled | Ticket titles read. |
ticketsFailed | Ticket reads that failed. |
added | What the draft gained: projects, groupedRepos, teams, teamRepos, glossary, conventions (counts) and languages (boolean). |
findings | Number of findings per confidence. |
renderFindings
/**
* Findings grouped by kind, each with a confidence marker and `+` when it changed the
* profile (`·` when it is an observation only). Ends with the run's numbers.
*/
export function renderFindings(result: Pick<DiscoveryResult, "findings" | "stats">, options: RenderOptions = {}): string;
export interface RenderOptions {
/** ANSI colours. Default: false. */
color?: boolean;
}defined in packages/discover/src/render.ts
Returns the plain-text review summary shown above: findings grouped by kind, each with a confidence marker and + when it changed the draft (· for an observation), followed by the totals. It is pure and takes only findings and stats, so it can render a result you stored as JSON. color: true adds ANSI colours; the default is plain text, wrapped at 100 columns.
Inference steps
discoverProfile is an orchestrator over pure functions, one per step. They are exported so each rule can be tested, or run on records you already hold. All of them take plain data and return proposals plus Finding[]; none does I/O.
The record shape
/**
* A merged pull request as the inference functions see it. `WorkRecord` from `@safran/core`
* is assignable to it; tests build it by hand.
*/
export interface PullRecord {
host: string;
/** Safran repo name: the short name, or `<hostId>/<name>` when two hosts share a name. */
repo: string;
id: string;
title: string;
description?: string;
sourceBranch?: string;
mergedAt?: string;
author?: { name: string; id?: string; email?: string };
ticketKeys: readonly string[];
changedFiles: readonly string[];
}
/** A tracker project discovery works with (declared in the seed or proposed). */
export interface ProjectInfo {
/** Key as the tracker spells it. Compared case-insensitively. */
key: string;
/** Display name; the key when the tracker gave none. */
name: string;
/** Tracker entry id. */
tracker: string;
}defined in packages/discover/src/types.ts
A WorkRecord from safran.links.query (createSafran API) is assignable to PullRecord.
Preparing records
/**
* Adds the ticket keys found with a wider project list than the one the records were
* stored with. A seed profile has no project keys yet, so its stored records carry only
* host-native links; discovery knows the keys from `listProjects` and looks again.
* Title and branch are read first; the description only when they name nothing, because
* descriptions mention other people's tickets.
*/
export function withTicketKeys(records: readonly PullRecord[], projectKeys: readonly string[]): PullRecord[];
/**
* Drops what would mislead the statistics, in this order: bot authors, merge / revert
* titles, mass changes, release PRs naming many tickets, and the same change opened to
* several target branches (same repo, title and tickets: the newest is kept).
*/
export function filterRecords(records: readonly PullRecord[], options: RecordFilterOptions = {}): FilteredRecords;
export interface RecordFilterOptions {
botAuthors?: readonly string[];
massChangeFiles?: number;
maxTicketsPerPull?: number;
}
export interface FilteredRecords {
kept: PullRecord[];
dropped: { bot: number; noiseTitle: number; massChange: number; manyTickets: number; duplicate: number };
}defined in packages/discover/src/records.ts
withTicketKeys adds the ticket keys found in the title and source branch (the description only when those name nothing), normalised (pay-0042 → PAY-42) and without technical look-alikes such as UTF-8 (DEFAULT_KEY_LOOKALIKES). filterRecords then drops, in this order: bot authors, merge and revert titles, mass changes, pull requests naming many tickets, and repeats of the same change (same repo, title and tickets; the newest is kept).
import { countProjectReferences, filterRecords, withTicketKeys, type PullRecord } from "@safran/discover";
const stored: PullRecord[] = [
{ host: "azure", repo: "payments-api", id: "101", title: "PAY-1423 fix partial refund rounding", ticketKeys: [], changedFiles: ["src/refund/service.ts"] },
{ host: "azure", repo: "payments-api", id: "103", title: "bump dependencies", author: { name: "renovate[bot]" }, ticketKeys: [], changedFiles: ["package.json"] },
];
const { kept, dropped } = filterRecords(withTicketKeys(stored, ["PAY"]), { botAuthors: ["acme-release-bot"] });
console.log(kept.map((record) => record.ticketKeys)); // [ [ "PAY-1423" ] ]
console.log(dropped.bot); // 1
console.log(countProjectReferences(kept)); // Map { "PAY" => 1 }Smaller helpers of the same module: isBotAuthor, isNoiseTitle, normaliseKey, projectOfKey, projectsOfRecord, countProjectReferences, sortRecords (newest first, the order every step iterates in), recordId and pickTicketKeys (which keys to sample).
Steps
| Step | Function | Input → result | Rule in one sentence |
|---|---|---|---|
| 1. Projects | proposeTrackerProjects | ProjectProposalInput → ProjectProposal | Trackers that declare projects are left alone; a short listing is proposed whole, a long one only as far as merged pull requests reference it. |
| 2. Groups | inferRepoGroups, guessRepoGroup | RepoGroupInput → RepoGroupResult | Manifest, name and primary language vote for one of GROUP_NAMES; confidence is agreement between the signals. |
| 3. Teams | inferTeams | TeamInferenceInput → TeamInferenceResult | A project owns a repo when it has minLinks pull requests there and ownerShare of the recency-weighted total. |
| 4. Glossary | collectTicketTerms, inferGlossary | GlossaryInput → GlossaryResult | A recurring ticket word is paired with path words over-represented in the files its pull requests changed. |
| 5. Conventions | inferConventions | ConventionInput → ConventionResult | A sentence is proposed only for a habit a clear majority follows, and never on a topic the human already wrote about. |
| 6. Languages | inferLanguages, proposeLanguage | LanguagesInput → LanguagesResult | languages.tickets from the sampled titles when they agree; languages.code is always proposed as en and is not measured. |
/**
* The rules, in order:
* 1. A PR counts for every known project among its tickets; its weight (0.5 per half-life of
* age, measured from the newest PR in the data) is split between them.
* 2. A project owns a repo when it has `minLinks` PRs there and `ownerShare` of the weight.
* 3. Otherwise up to `maxCoOwners` projects with `sharedShare` each are co-owners, at low
* confidence. A repo spread thinner than that is reported as shared and left unassigned.
* 4. Confidence is `high` only from `highMinLinks` links and `highShare`; a repo whose
* all-time leader differs from its recency-weighted leader is capped at `low`, and so is
* a repo whose "project" is the repo itself (issues kept in the code host).
* 5. With teams in the profile, repos are added to the one team owning the project and no
* team is invented; a repo a human already gave to a team is never moved or shared out.
*/
export function inferTeams(input: TeamInferenceInput): TeamInferenceResult;defined in packages/discover/src/teams.ts
/**
* For each term: its PRs are the focused PRs (at most `maxFiles` files) of tickets whose
* title has the term; the comparison set is the other focused PRs of sampled tickets,
* repo by repo (a repo with fewer than `minContrast` of those is left out). A path word is
* suggested when at least `minSupport` and half of the term's PRs touch it and its share
* there exceeds its share among the comparison PRs of the same repo by `minLift`, averaged
* over repos by the number of the term's PRs in each. Terms already present in changed paths or in the code index are dropped, and
* when two terms point at the same code word only the more frequent one is kept.
*/
export function inferGlossary(input: GlossaryInput): GlossaryResult;defined in packages/discover/src/glossary.ts
Each step's input, result and intermediate types are exported next to it (TrackerListing, RepoSignals, RepoGroupGuess, ExistingTeam, ProposedTeam, RepoAssignment, TicketTitle, TermGroup, TermOptions, GlossaryThresholds, GlossaryCandidate, LanguageProposal, BranchShape, TitleShape), as are their own defaults (DEFAULT_MIN_PROJECT_REFERENCES, DEFAULT_PROJECT_HIGH_REFERENCES, DEFAULT_MAX_GROUP_FINDINGS, DEFAULT_BRANCH_TYPE_MIN_AUTHORS, KNOWN_BRANCH_TYPES, DEFAULT_STEM_MIN_LENGTH, DEFAULT_STEM_MAX_SUFFIX, DEFAULT_PREFIX_GROUP_LENGTH).
import { guessRepoGroup, inferTeams, type PullRecord } from "@safran/discover";
const guess = guessRepoGroup({ name: "acme-ios", primaryLanguage: "Swift" });
console.log(guess.group, guess.confidence, guess.reasons);
const records: PullRecord[] = Array.from({ length: 9 }, (_, n) => ({
host: "azure",
repo: "acme-ios",
id: String(n),
title: `MOB-${200 + n} tidy the basket screen`,
mergedAt: `2026-0${(n % 9) + 1}-10T09:00:00Z`,
ticketKeys: [`MOB-${200 + n}`],
changedFiles: ["Basket/BasketView.swift"],
}));
const teams = inferTeams({
records,
projects: [{ key: "MOB", name: "Mobile", tracker: "jira" }],
existingTeams: [],
thresholds: { minLinks: 5 },
});
for (const team of teams.newTeams) console.log(team.name, team.repos, team.confidence, team.source);Text helpers
The tokenising and language heuristics are exported too: tokenizeTitle, stripTicketKeys, lowerIn (locale-aware lower-casing), fold (diacritic folding), pathTokens, repoNameTokens, commonPrefixLength, isStopWord, detectTitleLanguage, summariseLanguages, branchShape, titleShape, with the word lists they use (STOP_WORDS, LANGUAGE_MARKERS, LANGUAGE_NAMES, GENERIC_PATH_TOKENS) and their limits (DEFAULT_MAX_TITLE_CHARS, DEFAULT_MIN_TERM_LENGTH, DEFAULT_MAX_TERM_LENGTH).
import { detectTitleLanguage, pathTokens, summariseLanguages } from "@safran/discover";
console.log(detectTitleLanguage("Kısmi iade işlemi İstanbul şubesinde başarısız oluyor")); // "tr"
console.log(pathTokens("src/refund/service.ts"));
console.log(summariseLanguages(["Refund webhook retries are not idempotent", "Sepet toplamı yanlış"]).counts);Writing the draft
/**
* Returns the seed with the additions appended. Nothing the human wrote is removed,
* reordered or reworded: existing arrays keep their items in place and get new ones at the
* end; existing objects keep their keys.
*/
export function buildDraft(seed: ProfileInput, additions: DraftAdditions): Draft;
/**
* YAML for the draft: header comment, then the profile with added scalars marked. If the
* marked text does not parse back to exactly the same data, the unmarked text is returned.
*/
export function renderDraftYaml(draft: Draft, header: string): string;
export function draftHeader(counts: HeaderCounts): string;
/**
* Appends `# note` to the lines of added scalars. It follows the block layout
* `Bun.YAML.stringify` writes (two-space indent, one item per line) and only ever appends
* a comment to a line whose scalar it parsed back to the expected value; a multi-line
* scalar is simply not annotated.
*/
export function annotateYaml(yaml: string, annotations: readonly Annotation[]): string;defined in packages/discover/src/draft.ts
buildDraft appends the additions to a clone of the seed; existing arrays keep their items in place and get new ones at the end. renderDraftYaml writes the header comment and marks every added scalar with a trailing comment; if the marked text does not parse back to exactly the same data, the unmarked text is returned instead. The supporting types are DraftAdditions, Draft, Annotation and HeaderCounts.
Four small utilities shared by the steps are exported as well: minConfidence, compareText (locale-independent order), percent and plural.
Common mistakes
- Running it before there is history. With no code host that lists pull requests, or fewer than
minLinkslinked pull requests per repo, the team step reports "Not enough history" and proposes nothing. That is the correct result; lowerminLinksonly if you will check every mapping by hand. - Treating the draft as the profile.
result.yamlis for review. Teams carryconfidenceandsourceuntil a person confirms them (see the profile reference). - Expecting glossary candidates when tickets and code share a language. When
languages.ticketsequalslanguages.codethe step says so and proposes nothing: there is nothing to map. - Passing
safran.profileas the seed. It has schema defaults filled in, so the draft would spell out every default. Pass the profile as written, or letdiscoverProfileread the profile file. - Expecting manifests to be read for repos that are not cloned. Group guesses then rest on the name and primary language only and say so in their evidence. Run
safran syncfirst for better groups.