@safran/discover
@safran/discover, bir Safran örneğinin iş takip sistemlerinden ve kod barındırıcılarından görebildiklerine bakarak şirket profilinin taslağını çıkarır: takip sistemi projeleri, repo grupları, takımlar, sözlük adayları, kurallar ve diller. Bu sayfa discoverProfile fonksiyonunu, her seçeneği ve eşiği varsayılan değeriyle, sonuç tiplerini, renderFindings fonksiyonunu ve paketin dışa açtığı saf çıkarım fonksiyonlarını belgeler. Yapılan iş sayma ve sezgisel kurallardan ibarettir; dil modeli kullanılmaz ve sonuç, bir insanın gözden geçirmesi gereken bir taslaktır. safran discover komutu (CLI: kurulum) bu paketin üzerinde ince bir kabuktur; taslağın nasıl gözden geçirileceğini keşif kılavuzu anlatır.
Örnek: sahte bağlayıcılarla keşif
Örnek, @safran/kit/testing içindeki bellek içi bağlayıcılarla (Test sayfasına bakın) bir Safran örneği kurar; başlangıç profilinde yalnızca bağlayıcılar vardır, gerisini keşif önerir. Ağa hiç çıkılmaz.
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) her önerinin gerekçesini yazdırır:
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, başlangıç profili ile eklenenlerin birleşimidir; eklenen her değer bulunduğu satırda işaretlenir. Bu çalıştırmada sözlük girdisi önerilmedi: on iki başlıkta, başlıkların yarısında geçen bir kelime glossaryMaxTicketShare eşiğinin üzerindedir ve fazla genel sayılır.
# 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>;tanımlandığı yer: packages/discover/src/discover.ts
Veriyi Safran örneği üzerinden toplar ve saf çıkarım adımlarına verir. Paketin bütün girdi/çıktı işlemleri burada yapılır; profilinize ya da başka bir dosyanıza hiçbir şey yazılmaz. Sırasıyla şunları yapar:
- Başlangıç profilini (seed) okur: önce
options.seed, yoksa örneğin yüklendiği profil dosyası (ham okunur, böylece şema varsayılanları taslağa yazılmaz), o da yoksa varsayılana eşit değerleri "yazılmamış" sayaraksafran.profile. - Repoları (
safran.repos.list) ve başlangıç profilindeki her iş takip sisteminin projelerini (tracker.listProjects) listeler. refreshLinksfalsedeğilse, birleştirilmiş pull request'lerisafran.links.refreshile yerel bağlantı deposuna çeker (Bağlantılar sayfasına bakın), sonra ilgili zaman aralığı için depoyusafran.links.queryile okur.- Gürültüyü ayıklar: bot yazarlar, merge ve revert başlıkları, toplu değişiklikler, çok sayıda kayıt anan pull request'ler ve aynı değişikliğin birden çok dala açılmış kopyaları.
- Kayıt başlıklarından örnek alır: en çok
sampleTicketskadarsafran.tickets.getçağrısı yapar, aynı anda en fazlaDEFAULT_TICKET_CONCURRENCY(4) istek açık tutar ve anahtarları repolardan sırayla seçer; böylece yoğun bir repo örneklemi tek başına doldurmaz. - Adımları çalıştırır: projeler → gruplar → takımlar → kurallar ve diller → sözlük. Sözlük adayları için ayrıca kod indeksine (
safran.code.status,safran.code.grep) terimin kodda zaten geçip geçmediğini sorar. - Eklenenleri başlangıç profiliyle birleştirir, taslağı
parseProfileile doğrular ve YAML'ı üretir.
Dokunduğu yerler: iş takip sistemi ve kod barındırıcı API'leri (yalnızca okuma), veri dizinindeki yerel bağlantı deposu (yenileme sırasında yazılır), zaten klonlanmış repoların kök girdileri ve package.json dosyası, açıksa kod indeksi. Hiçbir zaman klonlamaz ve indekslemez.
Her adım, çalıştırmayı durdurmak yerine bir bulguya dönüşür. Token'ı reddeden bir iş takip sistemi, pull request listeleyemeyen bir kod barındırıcı ya da henüz kurulmamış bir indeks, problem veya coverage türünde bir bulgu olur; çalışabilen adımlar çalışmaya devam eder. Yalnızca şu durumlarda hata fırlatılır:
| Kod | Ne zaman |
|---|---|
INVALID_INPUT | since bir tarih değil; maxPerRepo pozitif bir tam sayı değil; sampleTickets ya da glossary.maxTerms negatif olmayan bir tam sayı değil |
PROFILE_INVALID | options.seed doğrulamadan geçmiyor |
ABORTED | Çalışırken options.signal iptal edildi ya da örnek kapatıldı |
Sonucun uyduğu kurallar: insanın yazdığı hiçbir şey silinmez, yeniden sıralanmaz, yeniden yazılmaz; projects alanını zaten bildiren bir iş takip sistemine dokunulmaz; insanın bir gruba koyduğu repo yeniden gruplanmaz; başlangıç profilinde takım varsa yeni takım uydurulmaz, repolar yalnızca projenin sahibi olan tek takıma eklenir. Aynı girdi aynı çıktıyı verir: güncellik hesabının referans noktası saat değil, verideki en yeni birleştirme tarihidir.
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;
}tanımlandığı yer: packages/discover/src/types.ts
| Seçenek | Tip | Varsayılan | Anlamı |
|---|---|---|---|
signal | AbortSignal | yok | Çalıştırmayı iptal eder; ABORTED ile reddedilir. |
onProgress | (progress: DiscoverProgress) => void | yok | Her adımda, uzun adımlarda ise kayıt ve repo başına çağrılır. |
since | ISO tarih metni | now değerinden DEFAULT_LOOKBACK_MONTHS (12) ay öncesi | Birleştirilmiş pull request'lerin depodan ne kadar geriye okunacağı. links.refresh çağrısına yalnızca siz verdiğinizde iletilir; aksi halde yenileme kendi ufkunu kullanır. |
maxPerRepo | pozitif tam sayı | links.refresh varsayılanı | Yenilemenin repo başına çekeceği pull request üst sınırı. |
refreshLinks | boolean | true | false hiçbir şey çekmez, yerel depoda ne varsa onu kullanır. |
sampleTickets | negatif olmayan tam sayı | DEFAULT_SAMPLE_TICKETS (200) | Başlığı için okunan kayıt sayısı; her biri bir istektir. 0 hiç okumaz: kayıt dili ve sözlük çıkarılamaz. |
glossary | GlossaryOptions | açık, 20 terim | Aşağıya bakın. |
thresholds | Partial<DiscoverThresholds> | DEFAULT_* sabitleri | Ayarlanabilir sayıların herhangi bir alt kümesi. |
botAuthors | readonly string[] | [] | Yerleşik kalıplara ek olarak bot sayılacak yazar adları (büyük/küçük harf duyarsız). |
seed | ProfileInput | profil dosyası, yoksa safran.profile | İnsanın yazdığı haliyle profil. |
now | Date | şimdiki zaman | Yalnızca varsayılan since değerini hesaplamak için kullanılır. |
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;
}tanımlandığı yer: packages/discover/src/types.ts
| Seçenek | Tip | Varsayılan | Anlamı |
|---|---|---|---|
enabled | boolean | true | false sözlük adaylarını atlar. |
maxTerms | negatif olmayan tam sayı | DEFAULT_GLOSSARY_MAX_TERMS (20) | Önerilen girdi sayısının üst sınırı. |
language | ISO 639-1 metni | başlangıç profilindeki languages.tickets, yoksa örneklenen başlıklardan algılanan dil | Kayıt başlıklarının dili. Kod diliyle aynıysa aday aranmaz. |
İlerleme olayları adımı, uzun adımlarda ayrıca sayıları taşır:
export interface DiscoverProgress {
step: "repos" | "projects" | "links" | "tickets" | "groups" | "teams" | "glossary" | "conventions" | "profile";
message: string;
done?: number;
total?: number;
}tanımlandığı yer: 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
Ayarlanabilir bütün sayılar. İstediğiniz alt kümeyi options.thresholds olarak verin; kalanlar aşağıdaki varsayılanlarda kalır. Varsayılanların her biri dışa açılmış bir sabittir.
/** 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;
}tanımlandığı yer: packages/discover/src/types.ts
| Eşik | Varsayılan | Sabit | Anlamı |
|---|---|---|---|
maxProjectsPerTracker | 25 | DEFAULT_MAX_PROJECTS_PER_TRACKER | Bundan uzun bir proje listesi, yalnızca birleştirilmiş pull request'lerin andığı kadarıyla önerilir. |
massChangeFiles | 50 | DEFAULT_MASS_CHANGE_FILES | Bundan çok dosya değiştiren pull request toplu değişikliktir ve yok sayılır. |
maxTicketsPerPull | 5 | DEFAULT_MAX_TICKETS_PER_PULL | Bundan çok kayıt anan pull request bir sürüm ya da dal birleştirmesidir ve yok sayılır. |
minLinks | 3 | DEFAULT_MIN_LINKS | Bir repo ↔ proje çifti için herhangi bir öneri yapılmadan önce gereken, kayda bağlı pull request sayısı. |
ownerShare | 0.6 | DEFAULT_OWNER_SHARE | Bir projenin repoya sahip sayılması için, reponun bağlı pull request'lerinde güncelliğe göre ağırlıklı olarak tutması gereken pay. |
sharedShare | 0.3 | DEFAULT_SHARED_SHARE | Tek sahibi olmayan bir repoda bir projenin ortak sahip sayıldığı pay. |
maxCoOwners | 2 | DEFAULT_MAX_CO_OWNERS | Listelenecek en fazla ortak sahip; daha fazlası olan repo "paylaşılan" olarak bildirilir ve atanmaz. |
recencyHalfLifeDays | 180 | DEFAULT_RECENCY_HALF_LIFE_DAYS | Bir bağlantının yarı ağırlığa düştüğü gün sayısı. |
mediumMinLinks | 8 | DEFAULT_MEDIUM_MIN_LINKS | Takım eşlemesinin medium olması için gereken bağlantı sayısı. |
highMinLinks | 20 | DEFAULT_HIGH_MIN_LINKS | Takım eşlemesinin high olabilmesi için gereken bağlantı sayısı. |
highShare | 0.8 | DEFAULT_HIGH_SHARE | high için highMinLinks ile birlikte gereken pay. |
glossaryMinTickets | 3 | DEFAULT_GLOSSARY_MIN_TICKETS | Bir terimin aday olabilmesi için geçmesi gereken kayıt sayısı. |
glossaryMaxTicketShare | 0.4 | DEFAULT_GLOSSARY_MAX_TICKET_SHARE | Kayıtların bundan büyük bir payında geçen terim fazla geneldir. |
glossaryMaxFiles | 20 | DEFAULT_GLOSSARY_MAX_FILES | Bundan geniş pull request'ler, hangi dosyaların bir terime ait olduğu konusunda bir şey söylemez. |
glossaryMinSupport | 3 | DEFAULT_GLOSSARY_MIN_SUPPORT | Bir yol kelimesinin önerilebilmesi için, terimin pull request'lerinden o kelimeye dokunması gerekenlerin sayısı. |
glossaryMinContrast | 3 | DEFAULT_GLOSSARY_MIN_CONTRAST | Karşılaştırma için aynı repolarda bulunması gereken diğer pull request sayısı. |
glossaryMinLift | 0.4 | DEFAULT_GLOSSARY_MIN_LIFT | Bir yol kelimesi için en düşük fark: (terimin pull request'lerindeki pay − diğerlerindeki pay). |
glossaryMaxCodeWords | 3 | DEFAULT_GLOSSARY_MAX_CODE_WORDS | Terim başına önerilen en fazla kod kelimesi. |
conventionMinSamples | 10 | DEFAULT_CONVENTION_MIN_SAMPLES | Bir kural ya da dil önerilmeden önce gereken örnek sayısı. |
conventionMajority | 0.7 | DEFAULT_CONVENTION_MAJORITY | Örneklerin hemfikir olması gereken payı. |
Takımlarla ilgili sekiz sayı tek bir nesne olarak da bulunur:
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,
};tanımlandığı yer: packages/discover/src/teams.ts
Orkestratörün dışa açtığı diğer varsayılanlar:
/** 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;
}tanımlandığı yer: packages/discover/src/types.ts
| Alan | Tip | Anlamı |
|---|---|---|
profile | ProfileInput | Başlangıç profili ile keşfin ekledikleri. parseProfile ile doğrulanır (profil API'si); beklenmedik biçimde doğrulanmazsa bunu bir problem bulgusu söyler. |
yaml | string | profile nesnesinin YAML hali; başında gözden geçirme notu, eklenen her değerin yanında # discovered yorumu bulunur. |
findings | Finding[] | Her öneri ya da gözlem için bir gerekçe; FINDING_KINDS sırasıyla. |
stats | DiscoveryStats | Çalıştırmanın sayıları. |
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";tanımlandığı yer: packages/discover/src/types.ts
| Alan | Anlamı |
|---|---|
kind | problem (bir şey okunamadı), coverage (ne kadar veri vardı), ardından adım başına bir tür: project, group, team, glossary, convention, language. |
subject | Neyle ilgili olduğu; örneğin Payments ↔ payments-api ya da tracker jira. |
confidence | low, medium ya da high. low şu demektir: bir insan kontrol edene kadar güvenmeyin. |
evidence | Sözle yazılmış gerekçe, arkasındaki sayılarla birlikte. |
detail | Aynı sayılar, JSON'a çevrilebilir biçimde. Her zaman applied alanını taşır: bulgu taslağı değiştirdiyse true, yalnızca gözlemse false. |
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>;
}tanımlandığı yer: packages/discover/src/types.ts
| Alan | Anlamı |
|---|---|
repos | Kod barındırıcıların listelediği repo sayısı. |
clonedRepos | Bunlardan kaçının yerelde klonlu olduğu (yalnızca onların manifest dosyaları okunur). |
pullRequests | Zaman aralığı için yerel depodan okunan birleştirilmiş pull request sayısı. |
pullRequestsUsed | Gürültü filtrelerinden sonra kalanlar. |
dropped | Filtre başına sayılar: bot, noiseTitle, massChange, manyTickets, duplicate. |
linkedPullRequests | Kullanılan pull request'lerden en az bir kayda atıf yapanlar. |
unlinkedShare | Kullanılan pull request'ler içinde hiç kayıt anahtarı taşımayanların payı, 0..1. |
ticketsSampled | Okunan kayıt başlığı sayısı. |
ticketsFailed | Başarısız olan kayıt okumaları. |
added | Taslağa eklenenler: projects, groupedRepos, teams, teamRepos, glossary, conventions (sayı) ve languages (boolean). |
findings | Güven düzeyine göre bulgu sayıları. |
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;
}tanımlandığı yer: packages/discover/src/render.ts
Yukarıda gösterilen düz metin özetini döndürür: türe göre gruplanmış bulgular, her birinde güven işareti ve taslağı değiştirdiyse + (gözlemse ·), sonunda da toplamlar. Saf bir fonksiyondur ve yalnızca findings ile stats alanlarını ister; dolayısıyla JSON olarak sakladığınız bir sonucu da yazdırabilir. color: true ANSI renkleri ekler; varsayılan, 100 sütunda kaydırılmış düz metindir.
Çıkarım adımları
discoverProfile, her adım için bir tane olmak üzere saf fonksiyonların üzerinde bir orkestratördür. Bu fonksiyonlar dışa açıktır; böylece her kural ayrı ayrı test edilebilir ya da elinizdeki kayıtlar üzerinde çalıştırılabilir. Hepsi düz veri alır, öneriler ile Finding[] döndürür; hiçbiri girdi/çıktı yapmaz.
Kayıt biçimi
/**
* 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;
}tanımlandığı yer: packages/discover/src/types.ts
safran.links.query çağrısının döndürdüğü WorkRecord (createSafran API'si) PullRecord tipine atanabilir.
Kayıtların hazırlanması
/**
* 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 };
}tanımlandığı yer: packages/discover/src/records.ts
withTicketKeys, başlıkta ve kaynak dalda bulunan kayıt anahtarlarını ekler (açıklamaya yalnızca bu ikisi hiçbir şey anmıyorsa bakar); anahtarları normalleştirir (pay-0042 → PAY-42) ve UTF-8 gibi anahtara benzeyen teknik ifadeleri (DEFAULT_KEY_LOOKALIKES) dışarıda bırakır. Ardından filterRecords şu sırayla ayıklar: bot yazarlar, merge ve revert başlıkları, toplu değişiklikler, çok sayıda kayıt anan pull request'ler ve aynı değişikliğin tekrarları (aynı repo, başlık ve kayıtlar; en yenisi kalır).
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 }Aynı modülün daha küçük yardımcıları: isBotAuthor, isNoiseTitle, normaliseKey, projectOfKey, projectsOfRecord, countProjectReferences, sortRecords (en yeni önce; her adımın dolaştığı sıra), recordId ve pickTicketKeys (hangi anahtarların örnekleneceği).
Adımlar
| Adım | Fonksiyon | Girdi → sonuç | Tek cümleyle kural |
|---|---|---|---|
| 1. Projeler | proposeTrackerProjects | ProjectProposalInput → ProjectProposal | Projelerini bildiren iş takip sistemlerine dokunulmaz; kısa bir liste bütünüyle, uzun bir liste yalnızca birleştirilmiş pull request'lerin andığı kadarıyla önerilir. |
| 2. Gruplar | inferRepoGroups, guessRepoGroup | RepoGroupInput → RepoGroupResult | Manifest, ad ve ana dil GROUP_NAMES içinden bir gruba oy verir; güven düzeyi, işaretlerin birbiriyle uyuşmasıdır. |
| 3. Takımlar | inferTeams | TeamInferenceInput → TeamInferenceResult | Bir proje, repoda minLinks pull request'i ve güncelliğe göre ağırlıklı toplamın ownerShare kadarı varsa o repoya sahiptir. |
| 4. Sözlük | collectTicketTerms, inferGlossary | GlossaryInput → GlossaryResult | Kayıtlarda yinelenen bir kelime, pull request'lerinin değiştirdiği dosyalarda beklenenden sık görülen yol kelimeleriyle eşleştirilir. |
| 5. Kurallar | inferConventions | ConventionInput → ConventionResult | Yalnızca açık bir çoğunluğun uyduğu alışkanlık için cümle önerilir; insanın zaten yazdığı bir konuda asla. |
| 6. Diller | inferLanguages, proposeLanguage | LanguagesInput → LanguagesResult | languages.tickets, örneklenen başlıklar hemfikirse onlardan çıkarılır; languages.code her zaman en olarak önerilir ve ölçülmez. |
/**
* 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;tanımlandığı yer: 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;tanımlandığı yer: packages/discover/src/glossary.ts
Her adımın girdi, sonuç ve ara tipleri kendisiyle birlikte dışa açılır (TrackerListing, RepoSignals, RepoGroupGuess, ExistingTeam, ProposedTeam, RepoAssignment, TicketTitle, TermGroup, TermOptions, GlossaryThresholds, GlossaryCandidate, LanguageProposal, BranchShape, TitleShape); kendi varsayılanları da öyle (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);Metin yardımcıları
Sözcüklere ayırma ve dil sezgileri de dışa açıktır: tokenizeTitle, stripTicketKeys, lowerIn (dile duyarlı küçük harfe çevirme), fold (aksanları sadeleştirme), pathTokens, repoNameTokens, commonPrefixLength, isStopWord, detectTitleLanguage, summariseLanguages, branchShape, titleShape; kullandıkları kelime listeleri (STOP_WORDS, LANGUAGE_MARKERS, LANGUAGE_NAMES, GENERIC_PATH_TOKENS) ve sınırlarıyla (DEFAULT_MAX_TITLE_CHARS, DEFAULT_MIN_TERM_LENGTH, DEFAULT_MAX_TERM_LENGTH) birlikte.
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);Taslağın yazılması
/**
* 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;tanımlandığı yer: packages/discover/src/draft.ts
buildDraft, eklenenleri başlangıç profilinin bir kopyasına ekler; var olan dizilerin öğeleri yerinde kalır, yenileri sona gelir. renderDraftYaml baştaki yorum bloğunu yazar ve eklenen her değeri satır sonu yorumuyla işaretler; işaretli metin geri okunduğunda tam olarak aynı veriyi vermiyorsa işaretsiz metin döndürülür. Yardımcı tipler DraftAdditions, Draft, Annotation ve HeaderCounts.
Adımların ortak kullandığı dört küçük yardımcı da dışa açıktır: minConfidence, compareText (yerel ayardan bağımsız sıralama), percent ve plural.
Sık yapılan hatalar
- Geçmiş oluşmadan çalıştırmak. Pull request listeleyebilen bir kod barındırıcı yoksa ya da repo başına
minLinksdeğerinden az bağlı pull request varsa, takım adımı "Not enough history" der ve hiçbir şey önermez. Doğru sonuç budur;minLinksdeğerini ancak her eşlemeyi elle kontrol edecekseniz düşürün. - Taslağı profil sanmak.
result.yamlgözden geçirilmek içindir. Takımlar, bir insan onaylayana kadarconfidencevesourcealanlarını taşır (profil başvurusu sayfasına bakın). - Kayıtlar ve kod aynı dildeyken sözlük adayı beklemek.
languages.ticketsilelanguages.codeaynıysa adım bunu söyler ve hiçbir şey önermez: eşlenecek bir şey yoktur. - Başlangıç profili olarak
safran.profilevermek. Bu nesnede şema varsayılanları doldurulmuştur; taslak her varsayılanı tek tek yazar. Profili yazıldığı haliyle verin ya da profil dosyasınıdiscoverProfilefonksiyonunun kendisinin okumasına bırakın. - Klonlanmamış repolarda manifest dosyalarının okunmasını beklemek. Bu durumda grup tahminleri yalnızca ada ve ana dile dayanır ve gerekçelerinde bunu belirtir. Daha iyi gruplar için önce
safran syncçalıştırın.