Skip to content
safran

Type to search. Enter opens the first result.

    Company knowledge and linked documents

    Two small APIs sit next to tickets and code. safran.company answers what the profile says about the company: teams, glossary, conventions and ownership. safran.docs fetches the pages tickets link to, and only those that belong to a doc source the profile configures. This page covers both, and the pure functions in @safran/profile for when you have a profile but no instance.

    Company knowledge

    company.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    for (const team of safran.company.teams()) {
      const note = team.confidence === "low" ? `  (unconfirmed: ${team.source ?? "no source"})` : "";
      console.log(`${team.name}: projects ${team.projects.join(", ")}; repos ${team.repos.join(", ")}${note}`);
    }
    
    for (const entry of safran.company.glossary()) console.log(`${entry.term} → ${entry.code.join(", ")}`);
    for (const rule of safran.company.conventions()) console.log(`rule: ${rule}`);
    
    console.log(safran.company.expand("Sepetteki ürünler için kısmi iade"));
    $ bun company.ts
    Payments: projects PAY; repos payments-api, ledger
    Mobile: projects MOB; repos acme-ios, acme-android  (unconfirmed: 9 ticket-PR links)
    Web: projects WEB; repos web-app, admin-panel
    Sepet → basket, cart
    İade → refund, chargeback
    rule: Task titles are written in English.
    rule: Branch names follow feature/<TICKET-KEY>-short-description.
    [ "basket", "cart", "refund", "chargeback" ]
    MethodReturnsNotes
    teams()Team[]The profile's teams, as written. Synchronous.
    glossary()GlossaryEntry[]The profile's glossary. Synchronous.
    conventions()string[]The profile's conventions: free-form rules that skills quote to the agent. Synchronous.
    expand(text)string[]The code-side words of every glossary term found in the text, without duplicates. Synchronous.
    whoOwns(target, options?)Promise<Ownership>The teams that own a repo or a tracker project, and how the answer was reached.

    The four synchronous methods read the profile in memory. They return the profile's own arrays; treat them as read-only.

    Teams and confidence

    A Team has name, projects (tracker project keys) and repos. Two optional fields say where the mapping came from: confidence (low, medium, high) and source (free text, such as 9 ticket-PR links). Discovery sets them when it infers a team; confidence: low means a person has not confirmed it yet. Show that to your users instead of presenting a guess as a fact.

    Expanding text with the glossary

    expand finds glossary terms as whole words or word beginnings, so suffixed forms match: Sepetteki contains Sepet, iadeler contains İade. Matching folds case without a locale, so İADE, iade and IADE are one word on every machine. code.search applies the same expansion to its query automatically; call expand yourself when you build a query for something else, such as a tracker search.

    export type Team = Profile["teams"][number];
    
    export type GlossaryEntry = Profile["glossary"][number];

    defined in packages/profile/src/schema.ts

    Who owns it

    who-owns.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    for (const target of [{ repo: "payments-api" }, { project: "MOB" }, { repo: "reporting-jobs" }]) {
      const { teams, basis } = await safran.company.whoOwns(target);
      console.log(JSON.stringify(target), "→", teams.map((team) => team.name).join(", ") || "nobody", `(${basis})`);
    }
    $ bun who-owns.ts
    {"repo":"payments-api"} → Payments (profile)
    {"project":"MOB"} → Mobile (profile)
    {"repo":"reporting-jobs"} → nobody (none)

    basis says how much to trust the answer:

    basisMeaning
    profileDeclared: a team lists the repo under repos or the project under projects. Project keys compare case-insensitively.
    historyNot declared; inferred from merged pull requests in the links store. Only for repos.
    noneNobody declared it and history has nothing to say. teams is empty.

    Several teams can own the same thing; teams then holds all of them. A target that is neither { repo } nor { project } is INVALID_INPUT.

    How history votes

    When no team declares a repo, Safran reads the repo's most recent stored pull requests (up to 500) and lets each one vote:

    1. Take the pull request's ticket keys and their projects (PAY-1500 → PAY).
    2. Find the teams that own those projects in the profile.
    3. Each such team gets one vote from this pull request, however many of its tickets the pull request names.

    The teams with the most votes win; a tie returns all of them. Pull requests without a ticket key, or with keys of projects no team owns, do not vote. A project can only be owned by declaration: history links tickets to code, not to teams.

    The example below is complete and runs offline, on the fakes from @safran/kit/testing. refund-worker is in no team's repos; two of its three pull requests carry PAY keys, one in the title and one in the branch name.

    ownership-from-history.ts
    import { mkdtempSync } from "node:fs";
    import { tmpdir } from "node:os";
    import { join } from "node:path";
    import { createSafran, defineProfile } from "@safran/core";
    import { FakeCodeHost, FakeTracker, fakePlugins } from "@safran/kit/testing";
    
    // `refund-worker` is in no team's `repos`, so the profile cannot answer.
    const profile = defineProfile({
      version: 1,
      company: "acme",
      trackers: [{ id: "jira", type: "fake", projects: ["PAY", "WEB"] }],
      code: { hosts: [{ id: "azure", type: "fake" }] },
      teams: [
        { name: "Payments", projects: ["PAY"], repos: ["payments-api", "ledger"] },
        { name: "Web", projects: ["WEB"], repos: ["web-app", "admin-panel"] },
      ],
    });
    
    const azure = new FakeCodeHost({
      id: "azure",
      repos: [{ name: "refund-worker" }],
      pullRequests: [
        { id: "7", repo: "refund-worker", title: "PAY-1500 retry queue", description: "", mergedAt: "2026-10-02T09:00:00Z", linkedTicketKeys: [], changedFiles: ["src/queue.ts"] },
        { id: "8", repo: "refund-worker", title: "Dead-letter handling", description: "", sourceBranch: "feature/PAY-1423-dead-letter", mergedAt: "2026-10-09T09:00:00Z", linkedTicketKeys: [], changedFiles: ["src/dead-letter.ts"] },
        { id: "9", repo: "refund-worker", title: "WEB-88 status endpoint", description: "", mergedAt: "2026-10-12T09:00:00Z", linkedTicketKeys: [], changedFiles: ["src/status.ts"] },
      ],
    });
    
    await using safran = await createSafran({
      profile,
      dataDir: mkdtempSync(join(tmpdir(), "acme-")),
      builtinPlugins: false,
      plugins: fakePlugins({ trackers: [new FakeTracker({ id: "jira" })], hosts: [azure] }),
      index: false,
    });
    
    console.log(await safran.company.whoOwns({ repo: "refund-worker" }));
    
    await safran.links.refresh({ since: "2026-01-01" });
    const { teams, basis } = await safran.company.whoOwns({ repo: "refund-worker" });
    console.log(teams.map((team) => team.name), basis);
    $ bun ownership-from-history.ts
    {
      teams: [],
      basis: "none",
    }
    [ "Payments" ] history

    Before the refresh the store is empty and the answer is none. Afterwards Payments has two votes and Web one. An answer on the history basis is evidence, not a decision: surface it as such, and put the repo under a team in the profile once someone confirms it.

    export interface Ownership {
      teams: Team[];
      /** How the answer was reached: "profile" when declared, "history" when inferred from past work. */
      basis: "profile" | "history" | "none";
    }
    
    /** What the profile says about the company, in the shape agents ask for it. */
    export interface CompanyApi {
      teams(): Team[];
      glossary(): GlossaryEntry[];
      conventions(): string[];
      /** Teams owning a repo or a tracker project. */
      whoOwns(target: { repo: string } | { project: string }, options?: CallOptions): Promise<Ownership>;
      /** Code-side words for the glossary terms found in the text. */
      expand(text: string): string[];
    }

    defined in packages/core/src/api.ts

    Linked documents

    Tickets link to wiki pages, specs and runbooks. safran.docs fetches such a page as Markdown, through the doc sources under docs: in the profile.

    fetch-doc.ts
    import { createSafran, isSafranError } from "@safran/core";
    
    await using safran = await createSafran();
    
    for (const link of await safran.tickets.links("PAY-1423")) {
      if (link.kind !== "web" || link.url === undefined) continue;
      if (!safran.docs.canFetch(link.url)) {
        console.log(`not a configured doc source: ${link.url}`);
        continue;
      }
      const page = await safran.docs.fetch(link.url);
      console.log(`${page.title} (${page.source}, updated ${page.updatedAt ?? "unknown"})`);
      console.log(page.content.slice(0, 400));
    }
    
    try {
      await safran.docs.fetch("https://intranet.acme.test/handbook");
    } catch (error) {
      if (!isSafranError(error, "UNSUPPORTED")) throw error;
      console.log(error.format());
    }

    The last call fails by design, with acme's wiki source configured:

    No doc source in the profile recognises https://intranet.acme.test
    → Configured doc sources: wiki. Safran only fetches pages that belong to one of them.

    Safran never fetches arbitrary URLs

    This is the rule that makes it safe to hand docs.fetch a URL found in a ticket: a URL is fetched only when a configured doc source recognises it as its own, and then by that source, with that source's credentials and limits. Everything else is refused before any request is made. A ticket cannot make Safran call an internal address, a metadata endpoint or a third-party site.

    CallBehaviour
    docs.canFetch(url)Synchronous, offline. true when the string is an http(s) URL and a configured source recognises it. Never throws.
    docs.fetch(url, options?)Returns a DocPage. INVALID_INPUT when the string is not an http(s) URL; UNSUPPORTED when no source recognises it, with the configured source ids in the hint and in details.sources.

    Errors of the source itself pass through: NOT_FOUND for a page that does not exist, AUTH_MISSING / AUTH_FAILED for credentials, and FORBIDDEN when the page is real but outside what the source is allowed to read (a Confluence space that is not in the entry's spaces). Sources are asked in profile order and the first that recognises the URL fetches it.

    A DocPage carries source (the doc source entry id), url, title, content as Markdown, and updatedAt / author when the source knows them. Like ticket text, page content is third-party text: wrap it with wrapUntrusted before giving it to a model.

    /** Pages that tickets link to (wiki, specs), fetched through the profile's doc sources. */
    export interface DocsApi {
      /** Whether any configured source recognises the URL. Offline. */
      canFetch(url: string): boolean;
      /** Throws UNSUPPORTED when no doc source recognises the URL. Safran never fetches arbitrary URLs. */
      fetch(url: string, options?: CallOptions): Promise<DocPage>;
    }
    
    export interface DocPage {
      /** Id of the doc source entry in the profile. */
      source: string;
      url: string;
      title: string;
      /** Markdown. */
      content: string;
      updatedAt?: string;
      author?: Person;
    }

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

    Which sources exist and which URL forms each recognises is on the connector pages. A custom source is a plugin.

    When you only have a profile

    Everything safran.company answers from the profile is also available as pure functions in @safran/profile. They take a validated Profile, do no I/O after loading and need no instance, no tokens and no data directory: useful in a build step, a linter for the profile, or a test.

    profile-only.ts
    import { expandWithGlossary, groupsOfRepo, loadProfile, reposInGroups, teamsOwningProject, teamsOwningRepo, trackerForProject, unconfirmedTeams } from "@safran/profile";
    
    const profile = await loadProfile("safran.yaml");
    
    console.log(teamsOwningRepo(profile, "payments-api").map((team) => team.name));
    console.log(teamsOwningProject(profile, "mob").map((team) => team.name));
    console.log(groupsOfRepo(profile, "ledger"), reposInGroups(profile, ["mobile", "frontend"]));
    console.log(trackerForProject(profile, "PAY"), unconfirmedTeams(profile));
    console.log(expandWithGlossary(profile, "sepet iadesi"));
    $ bun profile-only.ts
    [ "Payments" ]
    [ "Mobile" ]
    [ "backend" ] [ "acme-ios", "acme-android", "web-app", "admin-panel" ]
    jira [ "Mobile" ]
    [ "basket", "cart", "refund", "chargeback" ]
    FunctionAnswers
    loadProfile(file?)Reads and validates a YAML profile. loadProfileFile also returns the file's absolute path and directory.
    parseProfile(data, file?)Validates data you already parsed. file is only used in error messages.
    teamsOwningRepo(profile, repo)Teams that list the repo.
    teamsOwningProject(profile, project)Teams that list the project (case-insensitive).
    groupsOfRepo(profile, repo)Groups that contain the repo.
    reposInGroups(profile, groups)Repo names in any of the groups; unknown groups contribute nothing.
    trackerForProject(profile, project)Id of the tracker entry that declares the project.
    allProjectKeys(profile)Every declared project key, upper-cased.
    unconfirmedTeams(profile)Names of teams with confidence: low.
    matchGlossary(profile, text)Glossary entries whose term occurs in the text.
    expandWithGlossary(profile, text)Their code-side words, without duplicates.

    These functions answer from declarations only. Ownership from history needs the links store, so it exists only as safran.company.whoOwns. The full list with signatures is in the profile API reference.

    Common mistakes

    SymptomCause
    whoOwns says none for a repo you know is activeNo team lists it, and the links store is empty or its pull requests carry no keys of owned projects. Run links.refresh(), or declare the repo.
    Treating a history answer as declaredCheck basis. An inferred owner should be shown as inferred.
    UNSUPPORTED from docs.fetch for a wiki URLThe URL's origin or path is not one a docs: entry covers. Call canFetch first to branch without an exception.
    expand returns nothing for an inflected wordA term matches at the start of a word only: iadeler matches İade, yeniiade does not. Add the other form as its own glossary entry.