Skip to content
safran

Type to search. Enter opens the first result.

    @safran/core

    This page is the reference for @safran/core: the factory createSafran, the options it takes, the Safran instance it returns and every method of its six sub-APIs, with parameters, return shapes, the error codes each one throws and the named defaults. Declarations are taken from the source when the site is built. For task-oriented explanations, start in the SDK guide.

    A complete example

    Every example on this page runs against the same in-memory company. createAcme() builds a real Safran over the fakes of @safran/kit/testing, so nothing reaches a network; the only thing written to disk is a temporary data directory.

    acme.ts
    import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
    import { tmpdir } from "node:os";
    import { join } from "node:path";
    import { createSafran, type Safran } from "@safran/core";
    import { FakeCodeHost, FakeCodeIndex, FakeDocSource, FakeTracker, fakePlugins } from "@safran/kit/testing";
    
    const REFUND_SERVICE = `export function refundPartially(orderId: string, amount: number): Refund {
      const order = loadOrder(orderId);
      assertRefundable(order, amount);
      return ledger.post({ orderId, amount, kind: "refund" });
    }
    `;
    
    /** The acme story in memory: fake connectors, a fake index, and a temporary data directory. */
    export async function createAcme(): Promise<Safran> {
      const work = mkdtempSync(join(tmpdir(), "acme-"));
      const paymentsApi = join(work, "payments-api");
      mkdirSync(join(paymentsApi, "src/refund"), { recursive: true });
      writeFileSync(join(paymentsApi, "src/refund/service.ts"), REFUND_SERVICE);
    
      const jira = new FakeTracker({
        id: "jira",
        baseUrl: "https://acme.atlassian.net",
        tickets: [
          {
            key: "PAY-1423",
            title: "Kısmi iade işlemi İstanbul şubesinde başarısız oluyor",
            type: "Bug",
            status: "Done",
            statusCategory: "done",
            description: "Kısmi iade 500 hatası veriyor. Ayrıntı: https://acme.atlassian.net/wiki/spaces/PAY/pages/1/Refunds",
            comments: [{ id: "1", author: { name: "Deniz" }, body: "Sadece İstanbul şubesinde tekrarlanıyor.", createdAt: "2026-03-02T09:00:00Z" }],
            history: [{ at: "2026-03-04T10:00:00Z", field: "status", from: "In Progress", to: "Done" }],
          },
          { key: "PAY-1500", title: "Refund webhook retries are not idempotent", type: "Bug", status: "In Progress", statusCategory: "in_progress" },
          { key: "PAY-1501", title: "Checkout basket total ignores the campaign discount", type: "Bug", status: "To Do", statusCategory: "todo" },
        ],
      });
      const azure = new FakeCodeHost({
        id: "azure",
        // An absolute path as clone URL is read in place, like a `local` host: no git involved.
        repos: [{ name: "payments-api", cloneUrl: paymentsApi }],
        pullRequests: [
          {
            id: "812",
            repo: "payments-api",
            title: "PAY-1423 fix partial refund rounding",
            description: "",
            sourceBranch: "bugfix/PAY-1423-partial-refund",
            mergedAt: "2026-03-04T09:30:00Z",
            linkedTicketKeys: [],
            changedFiles: ["src/refund/service.ts", "src/refund/policy.ts"],
          },
        ],
      });
      const wiki = new FakeDocSource({
        id: "wiki",
        origin: "https://acme.atlassian.net",
        pages: { "https://acme.atlassian.net/wiki/spaces/PAY/pages/1/Refunds": { title: "Refunds", content: "Partial refunds are posted to the ledger." } },
      });
      const index = new FakeCodeIndex({
        files: { "payments-api": { "src/refund/service.ts": REFUND_SERVICE } },
        groups: { backend: ["payments-api", "ledger"] },
      });
    
      return createSafran({
        profile: {
          version: 1,
          company: "acme",
          languages: { tickets: "tr", code: "en" },
          trackers: [{ id: "jira", type: "fake", projects: ["PAY", "MOB", "WEB"] }],
          code: { hosts: [{ id: "azure", type: "fake" }], groups: { backend: ["payments-api", "ledger"] } },
          docs: [{ id: "wiki", type: "fake" }],
          teams: [{ name: "Payments", projects: ["PAY"], repos: ["payments-api", "ledger"] }],
          glossary: [{ term: "İade", code: ["refund", "chargeback"] }],
          conventions: ["Branch names start with the ticket key."],
          embeddings: { type: "fake" },
        },
        builtinPlugins: false,
        plugins: fakePlugins({ trackers: [jira], hosts: [azure], docs: [wiki] }),
        index,
        dataDir: join(work, "data"),
      });
    }

    With that file next to it, this is a whole program: read a ticket, find the code its words point at, and see which merged pull request was done for it.

    first-look.ts
    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    try {
      const ticket = await safran.tickets.get("PAY-1423");
      console.log(ticket.title, ticket.statusCategory);
    
      const { hits, effectiveQuery } = await safran.code.search("kısmi iade nerede yapılıyor", { groups: ["backend"] });
      console.log(effectiveQuery); // "kısmi iade nerede yapılıyor refund chargeback"
      for (const hit of hits) console.log(`${hit.repo} ${hit.path}:${hit.startLine}-${hit.endLine}`);
    
      await safran.links.refresh({ since: "2026-01-01" });
      for (const record of await safran.links.query({ ticket: "PAY-1423" })) {
        console.log(record.repo, record.title, record.changedFiles);
      }
    } finally {
      await safran.close();
    }

    In a real project the profile is a file and the connectors are the built-in ones, so the setup is one line: await createSafran() reads ./safran.yaml. See createSafran in the SDK guide.

    What the package exports

    ExportKindSection
    createSafran, SafranOptions, builtinPluginsfactorycreateSafran
    SafraninterfaceThe Safran instance
    TicketsApi and its typesinterfacesafran.tickets
    CodeApi and its typesinterfacesafran.code
    DocsApiinterfacesafran.docs
    ReposApi and its typesinterfacesafran.repos
    LinksApi and its typesinterfacesafran.links
    CompanyApi, Ownershipinterfacesafran.company
    BatchError, SafranWarninginterfaceShared result shapes
    DEFAULT_*, LINKS_DB_FILE, LINKS_SCHEMA_VERSIONconstantsDefaults
    createGlobMatcher, matchesGlobfunctionsGlob matching

    @safran/core also re-exports what most callers and plugin authors need from the lower packages, so one import is usually enough: SafranError, isSafranError, toSafranError, throwIfAborted, ERROR_CODES, defineTracker, defineCodeHost, defineDocSource, defineEmbedder, PluginRegistry, isSafranPlugin, parsePluginConfig, createHttpClient, envVarName, httpUrl, wrapUntrusted, silentLogger, TRACKER_CAPABILITIES, CODE_HOST_CAPABILITIES and the domain types from @safran/kit (kit reference, domain types); defineProfile, DEFAULT_PROFILE_FILE and the types Profile, ProfileInput, Team, GlossaryEntry from @safran/profile (profile reference). The fakes stay in @safran/kit/testing.

    createSafran

    /**
     * Builds a Safran instance: loads the profile, registers plugins and builds every connector.
     * Nothing here touches the network; the code index and the embedder start on first use.
     */
    export async function createSafran(options: SafranOptions = {}): Promise<Safran>;

    defined in packages/core/src/create.ts

    Loads and validates the profile, registers plugins, and builds every tracker, code host and doc source of the profile. It performs no network I/O: connectors are built without being contacted, and the embedder and the code index start on the first code call. A ticket-only program therefore needs neither an embedder running nor an index on disk.

    Returns a Safran instance. Close it when you are done (await safran.close(), or await using).

    Throws

    CodeWhen
    PROFILE_INVALIDThe profile file does not exist, is not valid YAML, or fails the schema. details.problems lists every problem with its path.
    FORBIDDENThe profile lists plugins: and allowProfilePlugins is false.
    PLUGIN_NOT_FOUNDA module under plugins: cannot be imported or exports no plugin, or an entry names a type no registered plugin provides.
    PLUGIN_CONFIG_INVALIDA connector entry (or embeddings) fails its plugin's config schema, or entries failed with different codes.
    INVALID_INPUTA plugin's kind:type is registered twice (a plugin passed in plugins or loaded from the profile collides with one already registered).
    AUTH_MISSINGA connector read a secret while being built and the environment variable is not set.
    INTERNALA plugin built a connector that lists a capability without implementing its method.

    Every connector entry is tried before the function throws, so one error reports all configuration problems at once: the message lists them line by line and details.problems carries the same lines. When all problems share one code that code is used; otherwise the error is PLUGIN_CONFIG_INVALID.

    import { createSafran, isSafranError } from "@safran/core";
    
    try {
      await using safran = await createSafran({ profile: "/work/acme/safran.yaml" });
      console.log(safran.profile.company, [...safran.trackers.keys()]);
    } catch (error) {
      if (isSafranError(error, "PROFILE_INVALID")) console.error(error.format());
      else throw error;
    }

    SafranOptions

    /**
     * Options for `createSafran`. Every field is optional: with none, Safran reads
     * `./safran.yaml`, keeps its data in `./data` and uses the built-in plugins.
     *
     * Convention used throughout: `undefined` means "use the default", `false` means "off".
     */
    export interface SafranOptions {
      /**
       * The company profile: a path to a YAML file, or the profile itself.
       * Default: `safran.yaml` in the current directory.
       */
      profile?: string | ProfileInput;
      /** Where clones, the index and caches live. Default: `data` next to the profile file. */
      dataDir?: string;
      /** Extra plugins, registered next to the built-in ones. A type collision is an error. */
      plugins?: SafranPlugin[];
      /** `false` starts with an empty registry, so only `plugins` are available. Default: true. */
      builtinPlugins?: boolean;
      /** Overrides the embedder built from `profile.embeddings`. */
      embedder?: Embedder;
      /**
       * Overrides the code index. `false` disables code search entirely (tickets-only use).
       * An index passed in here is owned by the caller: `close()` does not close it, so one index
       * can serve several instances. Only the index Safran opens itself is closed with it.
       */
      index?: CodeIndex | false;
      /** Environment used to resolve secrets. Default: `process.env`. */
      env?: Record<string, string | undefined>;
      /** Default: silent. */
      logger?: Logger;
      /** Default: the global `fetch`. */
      fetch?: typeof fetch;
      /**
       * Whether modules listed under `plugins:` in the profile may be imported (which runs their
       * code). Default: true. A caller that did not choose the profile itself (a CLI picking up
       * `./safran.yaml` from the working directory) passes `false`; a profile that lists plugins then
       * fails with FORBIDDEN instead of executing them.
       */
      allowProfilePlugins?: boolean;
    }

    defined in packages/core/src/api.ts

    Every field is optional. undefined means "use the default"; false means "off".

    OptionTypeDefaultMeaning
    profilestring | ProfileInputsafran.yaml in the current directory (DEFAULT_PROFILE_FILE)A path to a YAML profile, or the profile as an object. An object is validated the same way a file is.
    dataDirstringdata next to the profile file; ./data for an inline profile (DEFAULT_DATA_DIR)Where clones, the index, the link store and caches live.
    pluginsSafranPlugin[]noneExtra plugins, registered after the built-in ones and after the profile's plugins:. A kind:type that is already registered is an error (INVALID_INPUT).
    builtinPluginsbooleantruefalse starts with an empty registry, so only plugins and the profile's own are available.
    embedderEmbedderbuilt from profile.embeddings on first useA live embedder that replaces the configured one.
    indexCodeIndex | falsean index opened under <dataDir>/index on first useA live index, or false to turn code search off. An index passed in is owned by the caller: close() does not close it.
    envRecord<string, string | undefined>process.envWhere secrets named in the profile (*_env fields) are resolved.
    loggerLoggersilent (silentLogger)Receives warnings such as "one tracker failed during search".
    fetchtypeof fetchthe global fetchThe HTTP implementation handed to every connector.
    allowProfilePluginsbooleantrueWhether modules under plugins: in the profile may be imported. A caller that did not choose the profile itself passes false.

    Notes that the types do not show:

    • With index: false, every method of safran.code and the indexing half of repos.sync throw UNSUPPORTED. repos.sync({ fetchOnly: true }) still works.
    • When embedder or index is passed, the embeddings entry of the profile is not validated at creation, because it will not be used to build anything.
    • Relative paths under plugins: resolve against the directory of the profile file; for an inline profile, against the current working directory.

    builtinPlugins

    /** Every plugin that ships with Safran. */
    export const builtinPlugins: SafranPlugin[] = [...builtinTrackers, ...builtinCodeHosts, ...builtinDocSources, ...builtinEmbedders];

    defined in packages/core/src/create.ts

    Every tracker, code host, doc source and embedder plugin that ships with Safran, in one array. It is what the registry starts with unless builtinPlugins: false is passed. The connectors overview lists them.

    import { builtinPlugins } from "@safran/core";
    
    for (const plugin of builtinPlugins) console.log(plugin.kind, plugin.type, plugin.description);

    The Safran instance

    export interface Safran extends AsyncDisposable {
      readonly profile: Profile;
      /** Absolute path of the profile file, when it was loaded from disk. */
      readonly profileFile: string | undefined;
      readonly dataDir: string;
      /** Connectors by profile entry id. Built eagerly; building them does no network I/O. */
      readonly trackers: ReadonlyMap<string, Tracker>;
      readonly hosts: ReadonlyMap<string, CodeHost>;
      readonly docSources: ReadonlyMap<string, DocSource>;
    
      readonly tickets: TicketsApi;
      readonly code: CodeApi;
      readonly docs: DocsApi;
      readonly repos: ReposApi;
      readonly links: LinksApi;
      readonly company: CompanyApi;
    
      /**
       * Stops the instance: later calls fail, calls still running are cancelled (they end with
       * ABORTED; `repos.sync` and `links.refresh` return their report with `aborted: true`) and are
       * waited for, then the index and every open handle are released. Nothing can open a handle
       * afterwards. Safe to call more than once; never rejects because a running call failed.
       */
      close(): Promise<void>;
    }

    defined in packages/core/src/api.ts

    MemberTypeMeaning
    profileProfileThe validated profile, defaults applied.
    profileFilestring | undefinedAbsolute path of the profile file; undefined for an inline profile.
    dataDirstringAbsolute path of the data directory.
    trackersReadonlyMap<string, Tracker>Trackers by profile entry id.
    hostsReadonlyMap<string, CodeHost>Code hosts by profile entry id.
    docSourcesReadonlyMap<string, DocSource>Doc sources by profile entry id.
    ticketsTicketsApiTickets across every tracker.
    codeCodeApiSearch, grep and read over the code index.
    docsDocsApiPages tickets link to.
    reposReposApiListing and syncing repositories.
    linksLinksApiTicket ↔ code history from merged pull requests.
    companyCompanyApiTeams, glossary, conventions, ownership.
    close() => Promise<void>Stops the instance and releases every handle.

    The connector maps give direct access to the contracts of @safran/kit (for example safran.trackers.get("jira")?.listProjects()). Calls made that way bypass the instance's lifecycle: they are not cancelled by close().

    close

    close(): Promise<void> — also [Symbol.asyncDispose], so await using works.

    In order: new calls are refused, running calls are cancelled, the instance waits for them (at most DEFAULT_CLOSE_GRACE_MS, 30 seconds), then the index Safran opened itself and the link store are released. It is idempotent and never rejects because a running call failed.

    • A call made after close() throws INVALID_INPUT ("This Safran instance is closed").
    • A call that was running ends with ABORTED. repos.sync and links.refresh do not throw; they return their report with aborted: true.
    import { isSafranError } from "@safran/core";
    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    await safran.close();
    await safran.close(); // safe: the second call returns the same promise
    
    try {
      await safran.tickets.get("PAY-1423");
    } catch (error) {
      if (isSafranError(error, "INVALID_INPUT")) console.log(error.message); // "This Safran instance is closed"
    }

    Errors and cancellation, everywhere

    Every method below shares three rules, so they are not repeated in each "Throws" list:

    • Every intentional failure is a SafranError; branch on error.code (errors). Connector failures surface with the code the connector raised: AUTH_MISSING, AUTH_FAILED, NOT_FOUND, FORBIDDEN, RATE_LIMITED, UPSTREAM.
    • Every asynchronous method accepts signal?: AbortSignal in its last options argument and ends with ABORTED when it fires. A signal that already fired stops the call before any connector is reached.
    • After close(), every method throws INVALID_INPUT.

    safran.tickets

    /**
     * Ticket access across every tracker in the profile. `ref` is whatever a person would
     * paste: a key ("PAY-1423"), a URL, or a tracker-specific short form ("#412").
     * Methods a tracker does not support throw UNSUPPORTED.
     */
    export interface TicketsApi {
      /** Finds the tracker a reference belongs to. Throws NOT_FOUND when none recognises it. */
      resolve(ref: string): ResolvedTicketRef;
      get(ref: string, options?: CallOptions): Promise<Ticket>;
      comments(ref: string, options?: PageOptions): Promise<Page<Comment>>;
      attachments(ref: string, options?: CallOptions): Promise<Attachment[]>;
      attachment(ref: string, attachmentId: string, options?: CallOptions): Promise<AttachmentContent>;
      links(ref: string, options?: CallOptions): Promise<TicketLink[]>;
      history(ref: string, options?: PageOptions): Promise<Page<HistoryEntry>>;
      search(query: TicketSearchQuery, options?: TicketSearchOptions): Promise<TicketSearchResult>;
    }

    defined in packages/core/src/api.ts

    A ticket reference (ref) is whatever a person would paste: a key (PAY-1423, case-insensitive where the tracker allows it), a ticket URL, a tracker-specific short form, or the explicit form <trackerId>:<ref> (jira:PAY-1423). The optional methods of a tracker are guarded by its capabilities: calling one the tracker does not support throws UNSUPPORTED, with the tracker's capabilities in the hint.

    tickets.resolve

    resolve(ref: string): ResolvedTicketRef — synchronous, offline.

    Finds the tracker a reference belongs to and the canonical key in that tracker. When several trackers accept the shape, the one whose projects in the profile lists the key's project wins.

    FieldTypeMeaning
    trackerTrackerThe connector that recognised the reference.
    keystringCanonical key in that tracker.

    Throws INVALID_INPUT for an empty reference, and when several trackers match and the profile does not decide (the hint shows the <trackerId>:<ref> form); NOT_FOUND when no tracker recognises it, or the named tracker does not.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const { tracker, key } = safran.tickets.resolve("https://acme.atlassian.net/browse/PAY-1423");
    console.log(tracker.id, key); // "jira" "PAY-1423"
    await safran.close();

    tickets.get

    get(ref: string, options?: CallOptions): Promise<Ticket>

    Fetches one ticket. Returns a Ticket: the description is Markdown, and fields holds the tracker-specific values.

    Throws what resolve throws; NOT_FOUND when the tracker has no such ticket.

    import { isSafranError } from "@safran/core";
    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    try {
      const ticket = await safran.tickets.get("pay-1423");
      console.log(ticket.key, ticket.project, ticket.status, ticket.url);
    } catch (error) {
      if (isSafranError(error, "NOT_FOUND")) console.error(error.message, error.hint);
      else throw error;
    } finally {
      await safran.close();
    }

    tickets.comments

    comments(ref: string, options?: PageOptions): Promise<Page<Comment>>

    One page of comments. options.limit and options.cursor page through them; pass nextCursor back unchanged (pagination). The page size default and the order are the tracker's.

    Throws what resolve throws; UNSUPPORTED without the comments capability.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    let cursor: string | undefined;
    do {
      const page = await safran.tickets.comments("PAY-1423", { limit: 20, ...(cursor === undefined ? {} : { cursor }) });
      for (const comment of page.items) console.log(comment.author?.name, comment.body);
      cursor = page.nextCursor;
    } while (cursor !== undefined);
    await safran.close();

    tickets.attachments

    attachments(ref: string, options?: CallOptions): Promise<Attachment[]>

    Lists the attachments of a ticket: metadata only, no content.

    Throws what resolve throws; UNSUPPORTED without the attachments capability.

    tickets.attachment

    attachment(ref: string, attachmentId: string, options?: CallOptions): Promise<AttachmentContent>

    Downloads one attachment. data is a Uint8Array; mimeType and filename are what the tracker declares and are not verified.

    Throws what resolve throws; UNSUPPORTED without the attachments capability; NOT_FOUND for an unknown attachment id.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    for (const attachment of await safran.tickets.attachments("PAY-1423")) {
      const content = await safran.tickets.attachment("PAY-1423", attachment.id);
      console.log(content.filename, content.mimeType, content.data.length);
    }
    await safran.close();

    links(ref: string, options?: CallOptions): Promise<TicketLink[]>

    Other tickets and web pages the ticket links to. A link of kind: "web" whose URL belongs to a doc source can be read with docs.fetch.

    Throws what resolve throws; UNSUPPORTED without the links capability.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    for (const link of await safran.tickets.links("PAY-1423")) {
      if (link.kind === "ticket") console.log(link.relation, link.ticket?.key);
      else if (link.url !== undefined && safran.docs.canFetch(link.url)) console.log("readable page:", link.url);
    }
    await safran.close();

    tickets.history

    history(ref: string, options?: PageOptions): Promise<Page<HistoryEntry>>

    One page of field changes (status transitions, reassignment).

    Throws what resolve throws; UNSUPPORTED without the history capability.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const { items } = await safran.tickets.history("PAY-1423");
    for (const change of items) console.log(change.at, change.field, change.from, "→", change.to);
    await safran.close();

    tickets.search

    search(query: TicketSearchQuery, options?: TicketSearchOptions): Promise<TicketSearchResult>

    Searches every tracker that supports search and merges the answers into one page. Each tracker with results left gets an equal share of limit; the cursor remembers where each one is. TicketSearchQuery carries the filters (text, projects, statusCategories, updatedSince, native).

    TicketSearchOptions extends PageOptions (limit, cursor, signal) with:

    OptionTypeDefaultMeaning
    trackerstringevery tracker that supports searchRestrict the search to one tracker entry id.

    limit defaults to DEFAULT_TICKET_SEARCH_LIMIT (50) and is clamped to DEFAULT_MAX_TICKET_SEARCH_LIMIT (500).

    TicketSearchResult is a Page of TicketSummary & { tracker: string } (items, nextCursor?) with:

    FieldTypeMeaning
    warningsSafranWarning[]Present when the page does not cover every tracker: one entry per tracker that failed (with its code) or was left out because it cannot run this search (UNSUPPORTED).

    Which trackers are asked:

    • With query.native, only trackers with the native-query capability.
    • With query.projects, trackers that declare projects in the profile and have none of the wanted ones are skipped. If that would skip all of them, all are asked.
    • A tracker that fails is dropped from the cursor and reported in warnings; the items of the others are returned.

    Throws INVALID_INPUT for an unknown tracker, a limit that is not a whole number of at least 1, or a cursor from another search; UNSUPPORTED when no configured tracker supports search (or native queries), or the named one does not. When every tracker asked fails, the call throws: the single failure itself, or an error with the first failure's code and all messages listed.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const page = await safran.tickets.search({ text: "refund", projects: ["PAY"], statusCategories: ["todo", "in_progress"] }, { limit: 10 });
    for (const item of page.items) console.log(item.tracker, item.key, item.title);
    for (const warning of page.warnings ?? []) console.warn(warning.source, warning.code, warning.message);
    if (page.nextCursor !== undefined) console.log("more results: pass cursor", page.nextCursor);
    await safran.close();

    safran.code

    export interface CodeApi {
      search(query: string, options?: SafranCodeSearchOptions): Promise<CodeSearchResult>;
      grep(pattern: string, options?: GrepOptions): Promise<GrepResult>;
      readFile(repo: string, path: string, range?: { startLine?: number; endLine?: number }, options?: CallOptions): Promise<FileSlice>;
      status(options?: CallOptions): Promise<IndexStatus>;
    }

    defined in packages/core/src/api.ts

    All four methods read the local code index, which opens on first use. They answer from the last repos.sync, not from the code hosts.

    Shared by all four: UNSUPPORTED when the instance was created with index: false; INDEX_NOT_READY when the index cannot answer yet (for example it was built with another embedder; the hint says what to run); INCOMPATIBLE_DATA when the index on disk was written by a newer version. The first call may also surface configuration or connection errors of the embedder, because that is when it is built.

    code.search

    search(query: string, options?: SafranCodeSearchOptions): Promise<CodeSearchResult>

    Ranked search by meaning and by words. Before the query reaches the index, glossary terms found in it add their code-side words (İade → refund, chargeback); words already present are not added twice.

    SafranCodeSearchOptions extends CodeSearchOptions (repos, groups, languages, kinds, pathPrefix, limit, mode, snippetLines, signal) with:

    OptionTypeDefaultMeaning
    expandGlossarybooleantrueAdd the code-side words of glossary terms found in the query.
    FieldTypeMeaning
    hitsCodeHit[]Ranked hits. score is comparable only within this list.
    effectiveQuerystringThe query actually sent to the index, after glossary expansion.
    glossaryGlossaryEntry[]Glossary entries that fired; empty when none did or expandGlossary is false.

    Scope rules: groups are resolved from the profile's code.groups. Several groups widen the scope (union); repos together with groups narrows it (intersection). A scope that can match nothing returns no hits without asking the index.

    Throws INVALID_INPUT for a group the profile does not define (details.known lists the defined ones) and for values the index refuses (such as an invalid limit).

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const result = await safran.code.search("kısmi iade nerede yapılıyor", { groups: ["backend"], limit: 5 });
    console.log(result.effectiveQuery, result.glossary.map((entry) => entry.term));
    for (const hit of result.hits) {
      console.log(`${hit.repo} ${hit.path}:${hit.startLine}-${hit.endLine}`, hit.channels);
      console.log(hit.snippet);
    }
    await safran.close();

    code.grep

    grep(pattern: string, options?: GrepOptions): Promise<GrepResult>

    Exact search: a literal string, or a regular expression with regex: true. Use it for complete lists and counts, where ranked search returns a sample. GrepOptions takes the same scope filters as search plus caseSensitive, wholeWord, pathGlob, context and limit.

    Returns a GrepResult: matches, total (all matches, also beyond limit), truncated, and incomplete when some repos could not be scanned completely.

    Throws INVALID_INPUT for an unknown group, or a pattern or option the index refuses (for example an invalid regular expression).

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const result = await safran.code.grep("refundPartially", { repos: ["payments-api"], wholeWord: true, context: 1 });
    console.log(`${result.matches.length} of ${result.total}`, result.truncated ? "(truncated)" : "");
    for (const match of result.matches) console.log(`${match.repo} ${match.path}:${match.line}`, match.text);
    await safran.close();

    code.readFile

    readFile(repo: string, path: string, range?: { startLine?: number; endLine?: number }, options?: CallOptions): Promise<FileSlice>

    Reads a file, or a line range of it, from an indexed repo. Lines are 1-based and inclusive. Without a range the index returns the first lines up to its own default; truncated and totalLines in the FileSlice say whether there is more.

    Throws NOT_FOUND for a repo that is not indexed or a path that does not exist in it; INVALID_INPUT for a path that leaves the repo or a range that makes no sense.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const slice = await safran.code.readFile("payments-api", "src/refund/service.ts", { startLine: 1, endLine: 3 });
    console.log(`${slice.path}:${slice.startLine}-${slice.endLine} of ${slice.totalLines}`);
    console.log(slice.content);
    await safran.close();

    code.status

    status(options?: CallOptions): Promise<IndexStatus>

    What the index holds: the embedder id, one row per indexed repo (files, chunks, indexedAt) and the total chunk count. See IndexStatus.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const status = await safran.code.status();
    console.log(status.embedder, status.chunks);
    for (const repo of status.repos) console.log(repo.name, repo.files, repo.indexedAt ?? "never indexed");
    await safran.close();

    safran.docs

    /** 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>;
    }

    defined in packages/core/src/api.ts

    Pages that tickets link to. Safran fetches a URL only when a doc source of the profile claims it; it never fetches arbitrary URLs.

    docs.canFetch

    canFetch(url: string): boolean — synchronous, offline.

    true when the string is an http(s) URL and a configured doc source recognises it. It never throws for a bad URL; it returns false.

    docs.fetch

    fetch(url: string, options?: CallOptions): Promise<DocPage>

    Fetches the page through the first doc source that recognises the URL. The DocPage content is Markdown.

    Throws INVALID_INPUT when the string is not an http(s) URL; UNSUPPORTED when no doc source recognises it (details.sources lists the configured ids); NOT_FOUND and FORBIDDEN from the source (a page that does not exist, a space outside the allow-list).

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const url = "https://acme.atlassian.net/wiki/spaces/PAY/pages/1/Refunds";
    if (safran.docs.canFetch(url)) {
      const page = await safran.docs.fetch(url);
      console.log(page.source, page.title, page.content.length);
    }
    await safran.close();

    safran.repos

    export interface ReposApi {
      /** Repos from every host, filtered by each host's include/exclude. */
      list(options?: CallOptions & { refresh?: boolean }): Promise<ManagedRepo[]>;
      /**
       * Problems of the most recent listing (by `list`, `get`, `sync` or a links refresh): hosts
       * that could not list their repos (with the code of the failure), a host that lists one name
       * twice (UPSTREAM), and a short name that exists on two hosts and how it was resolved
       * (INVALID_INPUT: the name alone is ambiguous). Empty when the listing was complete and
       * unambiguous, and before the first listing.
       */
      warnings(): SafranWarning[];
      /** Looks one up by short name. Throws NOT_FOUND with the closest names as a hint. */
      get(name: string, options?: CallOptions): Promise<ManagedRepo>;
      /**
       * Clones or fetches working trees, then indexes what changed. Without `repos` it asks the
       * hosts for their repos again instead of using the cached listing.
       *
       * Throws only before any work starts: NOT_FOUND for an unknown repo name, the listing error
       * when no host can list its repos, UNSUPPORTED when indexing is asked for but off. From then on
       * it always returns a report: a failing repo is a "failed" row, a cancelled run has
       * `aborted: true`. Calls on one instance run one after the other; a repo another process is
       * syncing is "skipped" with a `reason`.
       */
      sync(options?: SyncOptions): Promise<SyncReport>;
    }

    defined in packages/core/src/api.ts

    repos.list

    list(options?: CallOptions & { refresh?: boolean }): Promise<ManagedRepo[]>

    The repositories every code host lists, after each host's include / exclude. The listing is cached per instance; refresh: true asks the hosts again. A listing with a host missing is returned but not cached, so the next call retries that host. Problems of the listing are available from repos.warnings.

    ManagedRepo extends RepoInfo (name, fullName, defaultBranch, cloneUrl, …) with:

    FieldTypeMeaning
    hoststringCode host entry id.
    groupsstring[]Groups of the profile this repo belongs to.
    teamsstring[]Names of the teams of the profile that own it.
    dirstringAbsolute path of the working tree. For local hosts this is the source directory itself.
    clonedbooleanWhether the working tree exists on disk.
    headstringCommit the working tree is at, when cloned.
    indexedAtstringISO time of the last successful index run. Absent when never indexed, when code search is off, and when the index on disk could not be opened. Reading it never creates an index and makes no embedder call.

    Throws the listing error when no host can list its repos: the single failure itself, or an error with the first failure's code and every host's message.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    for (const repo of await safran.repos.list()) {
      console.log(repo.host, repo.name, repo.groups, repo.teams, repo.cloned ? repo.dir : "not cloned", repo.indexedAt ?? "not indexed");
    }
    await safran.close();

    repos.warnings

    warnings(): SafranWarning[] — synchronous.

    Problems of the most recent listing (made by list, get, sync or a links refresh): a host that could not list its repos (with the code of the failure), a host that lists one name twice (UPSTREAM), and a short name that exists on two hosts and how it was resolved (INVALID_INPUT). Empty when the listing was complete and unambiguous, and before the first listing.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const repos = await safran.repos.list({ refresh: true });
    for (const warning of safran.repos.warnings()) console.warn(`${warning.source}: ${warning.code} ${warning.message}`);
    console.log(repos.length);
    await safran.close();

    repos.get

    get(name: string, options?: CallOptions): Promise<ManagedRepo>

    Looks one repo up by its short name. An exact match wins; otherwise a case-insensitive match is accepted when it is unique.

    Throws NOT_FOUND, with the closest names in the hint ("Did you mean: payments-api?", at most DEFAULT_SUGGESTIONS) and in details.closest.

    import { isSafranError } from "@safran/core";
    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    try {
      await safran.repos.get("payment-api");
    } catch (error) {
      if (isSafranError(error, "NOT_FOUND")) console.log(error.message, "→", error.hint);
    }
    await safran.close();

    repos.sync

    sync(options?: SyncOptions): Promise<SyncReport>

    Clones or fetches the working trees under <dataDir>/repos, then indexes what changed. Repos of a local host are read in place. Without repos it asks the hosts for a fresh listing. Calls on one instance run one after the other; a repo another process is syncing is reported skipped with a reason.

    SyncOptions extends CallOptions (signal) with:

    OptionTypeDefaultMeaning
    reposstring[]every listed repoRepo names to sync.
    offlinebooleanfalseSkip the git fetch; index what is on disk.
    fetchOnlybooleanfalseUpdate the working trees; do not index.
    onProgress(progress: SyncProgress) => voidnoneCalled as each repo moves through its phases.
    FieldTypeMeaning
    repostringRepo name.
    phase"fetch" | "scan" | "chunk" | "embed" | "write"fetch, or a phase of the index run.
    donenumberUnits finished in this phase.
    totalnumberUnits in this phase.
    FieldTypeMeaning
    resultsRepoSyncResult[]One row per repo.
    durationMsnumberWall time of the run.
    removedstring[]Repos dropped from the index because no host lists them any more. Only a sync of every repo with every host answering does this, and only in the index the instance opened itself.
    abortedbooleantrue when the run was cancelled by the signal or by close().
    FieldTypeMeaning
    repostringRepo name.
    status"ok" | "failed" | "skipped"Outcome for this repo.
    updatedbooleanWhether the working tree moved to a new commit.
    headstringCommit the working tree is at.
    indexIndexRepoResultCounts of the index run (IndexRepoResult).
    errorBatchErrorPresent when status is "failed".
    reasonstringPresent when status is "skipped" because another sync holds the repo.

    Throws only before any work starts: NOT_FOUND for unknown repo names (all of them reported at once), the listing error when no host can list its repos, UNSUPPORTED when indexing is asked for but code search is off. After that it always returns a report: a failing repo is a "failed" row, and a cancelled run has aborted: true with the interrupted repo and the ones not reached "skipped".

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const report = await safran.repos.sync({
      repos: ["payments-api"],
      onProgress: ({ repo, phase, done, total }) => console.log(repo, phase, `${done}/${total}`),
    });
    for (const result of report.results) {
      if (result.status === "failed") console.error(result.repo, result.error?.code, result.error?.message, result.error?.hint);
      else console.log(result.repo, result.status, result.index?.filesIndexed, result.reason ?? "");
    }
    if (report.aborted) console.log("cancelled; run it again to continue");
    await safran.close();
    /**
     * History of finished work: which tickets changed which files. Built from merged pull
     * requests, stored locally. It powers "what did similar tickets touch", team inference
     * in discovery, and the evaluation golden set.
     */
    export interface LinksApi {
      /**
       * Pulls merged PRs from the code hosts into the local store.
       *
       * Hosts are expected to list merged pull requests newest first, so a run stopped by
       * `maxPerRepo` holds the newest ones; the next run skips what is stored and continues towards
       * the horizon. Correctness does not depend on the order: a repo counts as complete only once a
       * listing was read to its end.
       *
       * Throws only before any work starts (NOT_FOUND for an unknown repo, a listing error, an
       * unreadable store). From then on it always returns a report: a failing repo is a "failed" row
       * and a cancelled run has `aborted: true` with the repos not finished "skipped". Calls on one
       * instance run one after the other.
       */
      refresh(options?: LinkRefreshOptions): Promise<LinkRefreshReport>;
      /**
       * Recomputes the ticket keys of every stored record from its stored title, branch and
       * description (host-native links are kept). No network call. Use it after the profile's
       * project keys changed.
       */
      relink(options?: RelinkOptions): Promise<RelinkReport>;
      /** Records matching the query, newest first. Reads the local store only. */
      query(query?: WorkQuery, options?: CallOptions): Promise<WorkRecord[]>;
      /** How many records match the query (`limit` is ignored). Reads the local store only. */
      count(query?: WorkQuery, options?: CallOptions): Promise<number>;
      /** Number of stored records and the time of the last refresh. */
      status(options?: CallOptions): Promise<LinksStatus>;
    }

    defined in packages/core/src/api.ts

    The link store is a local SQLite file, safran.db (LINKS_DB_FILE) in the data directory. refresh is the only method that reaches a code host; the others read or rewrite the local store. A store written by a newer Safran, or a file that is not a readable database, throws INCOMPATIBLE_DATA with a hint to rebuild it.

    links.refresh

    refresh(options?: LinkRefreshOptions): Promise<LinkRefreshReport>

    Pulls merged pull requests from the code hosts into the store and recognises ticket keys in their titles, branches and descriptions (host-native ticket links are kept as well). A run stopped by maxPerRepo holds the newest pull requests; the next run continues towards the horizon.

    LinkRefreshOptions extends CallOptions (signal) with:

    OptionTypeDefaultMeaning
    reposstring[]every listed repoRepo names to refresh.
    sincestringthe horizon of the repo's earlier refreshes, or DEFAULT_LINKS_LOOKBACK_MONTHS (12) months back on its first oneISO date the stored history must reach back to.
    maxPerReponumberDEFAULT_LINKS_MAX_PER_REPO (500)Cap on pull requests newly stored per repo in one run.
    projectKeysstring[]every project under trackers[].projects in the profileProject keys used to recognise ticket keys.
    onProgress(progress: { repo: string; fetched: number }) => voidnoneCalled as pull requests of a repo are read.
    FieldTypeMeaning
    reposLinkRefreshRepoResult[]One row per repo.
    durationMsnumberWall time of the run.
    abortedbooleantrue when the run was cancelled. Never thrown instead.
    FieldTypeMeaning
    repostringRepo name.
    status"ok" | "failed" | "skipped""skipped": the run was cancelled before this repo was read completely; nothing of it was stored.
    fetchednumberPull requests written to the store in this run (new ones, and stored ones seen again).
    linkednumberHow many of those carry at least one ticket key.
    truncatedbooleantrue while the store does not reach back to the horizon for this repo, because maxPerRepo stopped the run.
    errorBatchErrorPresent when status is "failed". A host without the pull-requests capability fails its repos with UNSUPPORTED.

    Throws only before any work starts: INVALID_INPUT for a since that is not a date, a maxPerRepo that is not a whole number of at least 1, or projectKeys that are not non-empty strings; NOT_FOUND for an unknown repo; the listing error; INCOMPATIBLE_DATA for an unreadable store. A signal that fired before the call still returns a report with aborted: true.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const report = await safran.links.refresh({ since: "2026-01-01", maxPerRepo: 200 });
    for (const repo of report.repos) {
      console.log(repo.repo, repo.status, `${repo.linked}/${repo.fetched} linked`, repo.truncated ? "run again to continue" : "");
      if (repo.error) console.error(repo.error.code, repo.error.message);
    }
    await safran.close();

    relink(options?: RelinkOptions): Promise<RelinkReport>

    Recomputes the ticket keys of every stored record from its stored title, branch and description. No network call. Run it after the project keys of the profile changed.

    OptionTypeDefaultMeaning
    projectKeysstring[]every project under trackers[].projects in the profileSame meaning as in LinkRefreshOptions.
    FieldTypeMeaning
    recordsnumberStored records looked at.
    linkednumberRecords that carry at least one ticket key afterwards.
    changednumberRecords whose ticket keys are different from before.

    Throws INVALID_INPUT for invalid projectKeys; ABORTED when cancelled (records are rewritten in batches, so each one is either old or new).

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    await safran.links.refresh();
    const report = await safran.links.relink({ projectKeys: ["PAY", "MOB", "WEB", "OPS"] });
    console.log(`${report.changed} of ${report.records} records changed; ${report.linked} linked`);
    await safran.close();

    links.query

    query(query?: WorkQuery, options?: CallOptions): Promise<WorkRecord[]>

    Records matching the query, newest first. Reads the local store only; an empty store gives an empty array.

    FieldTypeMeaning
    ticketstringTicket key the record was done for.
    repostringRepo name.
    pathstringRepo-relative file path; matches records that changed it.
    sincestringISO date, lower bound on mergedAt (inclusive).
    untilstringISO date, upper bound on mergedAt (exclusive).
    limitnumberUsed by query only. Default DEFAULT_WORK_QUERY_LIMIT (100), clamped to DEFAULT_MAX_WORK_QUERY_LIMIT.

    WorkRecord extends PullRequest (id, repo, title, description, url, author, sourceBranch, mergedAt, …) with:

    FieldTypeMeaning
    hoststringCode host entry id.
    ticketKeysstring[]Host-native links plus keys recognised in the title, branch and description.
    changedFilesstring[]Repo-relative paths the pull request touched.

    Throws INVALID_INPUT for a since / until that is not a date or a limit that is not a whole number of at least 1.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    await safran.links.refresh();
    const forTicket = await safran.links.query({ ticket: "PAY-1423" });
    const forFile = await safran.links.query({ repo: "payments-api", path: "src/refund/service.ts", since: "2026-01-01", limit: 20 });
    for (const record of [...forTicket, ...forFile]) console.log(record.mergedAt, record.id, record.title, record.ticketKeys);
    await safran.close();

    links.count

    count(query?: WorkQuery, options?: CallOptions): Promise<number>

    How many records match the query. limit is ignored. Reads the local store only.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    await safran.links.refresh();
    console.log(await safran.links.count({ repo: "payments-api" }), "merged pull requests stored for payments-api");
    await safran.close();

    links.status

    status(options?: CallOptions): Promise<LinksStatus>

    FieldTypeMeaning
    recordsnumberStored records.
    linkednumberRecords with at least one ticket key.
    refreshedAtstringISO time of the last refresh in which at least one repo succeeded. Absent before that.
    incompleteReposstring[]Repos whose stored history does not reach back to their horizon yet.
    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const status = await safran.links.status();
    console.log(status.records, status.linked, status.refreshedAt ?? "never refreshed", status.incompleteRepos);
    await safran.close();

    safran.company

    /** 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

    What the profile says about the company. teams, glossary, conventions and expand are synchronous and read the profile only; text from the profile was written by the operator and is trusted.

    company.teams, company.glossary, company.conventions

    teams(): Team[] · glossary(): GlossaryEntry[] · conventions(): string[]

    The corresponding sections of the profile, with defaults applied (each is an empty array when the profile has none). The entry types are in the profile reference.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    for (const team of safran.company.teams()) console.log(team.name, team.projects, team.repos, team.confidence ?? "declared");
    for (const entry of safran.company.glossary()) console.log(entry.term, "→", entry.code.join(", "));
    console.log(safran.company.conventions());
    await safran.close();

    company.whoOwns

    whoOwns(target: { repo: string } | { project: string }, options?: CallOptions): Promise<Ownership>

    Teams owning a repo or a tracker project. For a repo, the profile is asked first; when no team declares it, the link store votes: every stored record of the repo (the newest DEFAULT_OWNERSHIP_HISTORY_LIMIT, 500) counts for the teams that own the projects of its tickets, and the teams with the most votes are returned. A project's owners can only be declared.

    FieldTypeMeaning
    teamsTeam[]The owning teams; empty when nothing is known.
    basis"profile" | "history" | "none""profile" when declared, "history" when inferred from past work, "none" when there is no answer.

    Throws INVALID_INPUT when the target has neither a repo nor a project string.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    const byRepo = await safran.company.whoOwns({ repo: "payments-api" });
    console.log(byRepo.basis, byRepo.teams.map((team) => team.name)); // "profile" ["Payments"]
    const byProject = await safran.company.whoOwns({ project: "MOB" });
    console.log(byProject.basis, byProject.teams.length); // "none" 0
    await safran.close();

    company.expand

    expand(text: string): string[]

    Code-side words for the glossary terms found in the text, de-duplicated. It is expandWithGlossary bound to the instance's profile.

    import { createAcme } from "./acme";
    
    const safran = await createAcme();
    console.log(safran.company.expand("Kısmi iade başarısız")); // ["refund", "chargeback"]
    await safran.close();

    Shared result shapes

    Batch operations and multi-source calls carry failures inside their result instead of throwing, so the part that succeeded is not lost.

    FieldTypeMeaning
    codeSafranErrorCodeThe same code a thrown SafranError would carry.
    messagestringWhat went wrong.
    hintstringWhat to do next, when there is something to do.
    FieldTypeMeaning
    sourcestringProfile entry id of the tracker or code host the warning is about.
    codeSafranErrorCodeWhy that source is missing from the answer, or what is ambiguous.
    messagestringOne sentence naming the source.

    BatchError appears in RepoSyncResult.error and LinkRefreshRepoResult.error; SafranWarning in TicketSearchResult.warnings and repos.warnings().

    Defaults

    Named constants exported by @safran/core. The values shown are read from the source.

    /** Named defaults of `@safran/core`. Everything here is overridable per call or per instance. */
    
    /** Directory name used next to the profile file (or in the cwd for inline profiles). */
    export const DEFAULT_DATA_DIR = "data";
    
    /** Total page size of `tickets.search` across all trackers. */
    export const DEFAULT_TICKET_SEARCH_LIMIT = 50;
    
    /** Largest `tickets.search` page; a larger `limit` is clamped. */
    export const DEFAULT_MAX_TICKET_SEARCH_LIMIT = 500;
    
    /**
     * How long `close()` waits for cancelled calls to settle before it releases the handles anyway.
     * A connector that ignores its signal must not keep the process from exiting.
     */
    export const DEFAULT_CLOSE_GRACE_MS = 30_000;
    /** Clone / fetch budget. A cold shallow clone of a large monorepo over a slow VPN takes minutes. */
    export const DEFAULT_GIT_NETWORK_TIMEOUT_MS = 10 * 60_000;
    
    /** Budget for git commands that never leave the machine (rev-parse, checkout). */
    export const DEFAULT_GIT_LOCAL_TIMEOUT_MS = 60_000;
    
    /** How long a killed git gets to clean up after SIGTERM before SIGKILL. */
    export const DEFAULT_GIT_KILL_GRACE_MS = 2_000;
    
    /** Characters of git stderr kept in an error message. */
    export const DEFAULT_GIT_ERROR_CHARS = 500;
    
    /**
     * Age after which a repo lock is taken over even though its process id is alive: the id may
     * belong to an unrelated process by then. Far above any real sync of one repo.
     */
    export const DEFAULT_REPO_LOCK_STALE_MS = 24 * 60 * 60_000;
    /** Merged pull requests newly stored per repo in one `links.refresh`. */
    export const DEFAULT_LINKS_MAX_PER_REPO = 500;
    
    /** How far back the first `links.refresh` of a repo looks. */
    export const DEFAULT_LINKS_LOOKBACK_MONTHS = 12;
    
    export const DEFAULT_LINKS_PAGE_SIZE = 100;
    
    export const DEFAULT_WORK_QUERY_LIMIT = 100;
    
    /** Largest `links.query` page; discovery and evaluation read the whole store in one call. */
    export const DEFAULT_MAX_WORK_QUERY_LIMIT = 1_000_000;
    
    /** Records of a repo read when ownership is inferred from history. */
    export const DEFAULT_OWNERSHIP_HISTORY_LIMIT = 500;
    
    /** Names offered in a "did you mean" hint. */
    export const DEFAULT_SUGGESTIONS = 3;
    export const LINKS_DB_FILE = "safran.db";
    
    export const LINKS_SCHEMA_VERSION = 2;
    ConstantUsed by
    DEFAULT_DATA_DIRSafranOptions.dataDir
    DEFAULT_TICKET_SEARCH_LIMIT, DEFAULT_MAX_TICKET_SEARCH_LIMITtickets.search
    DEFAULT_CLOSE_GRACE_MSclose
    DEFAULT_GIT_NETWORK_TIMEOUT_MS, DEFAULT_GIT_LOCAL_TIMEOUT_MS, DEFAULT_GIT_KILL_GRACE_MS, DEFAULT_GIT_ERROR_CHARSthe git commands of repos.sync
    DEFAULT_REPO_LOCK_STALE_MSthe per-repo lock of repos.sync
    DEFAULT_LINKS_MAX_PER_REPO, DEFAULT_LINKS_LOOKBACK_MONTHS, DEFAULT_LINKS_PAGE_SIZElinks.refresh
    DEFAULT_WORK_QUERY_LIMIT, DEFAULT_MAX_WORK_QUERY_LIMITlinks.query
    DEFAULT_OWNERSHIP_HISTORY_LIMITcompany.whoOwns
    DEFAULT_SUGGESTIONS"did you mean" hints
    LINKS_DB_FILE, LINKS_SCHEMA_VERSIONthe link store on disk

    The constants are values to read, not switches: the per-call ones are overridden through the options of the method that uses them (limit, maxPerRepo, since); the git budgets, the lock age and the close grace have no option.

    Glob matching

    /**
     * The small glob dialect of `include` / `exclude` in a code host entry:
     * `*` is any run of characters, `?` is exactly one, everything else is literal.
     * Matching is case-insensitive and always covers the whole name.
     *
     * Matched with two pointers and one remembered star instead of a regular expression: a pattern
     * of several stars compiled to `.*.*.*` backtracks polynomially (six stars against a 200-character
     * name took 74 s), and both the pattern and the names come from outside. Here the worst case is
     * pattern length × name length.
     */
    export function createGlobMatcher(pattern: string): (name: string) => boolean;
    
    export function matchesGlob(name: string, pattern: string): boolean;

    defined in packages/core/src/glob.ts

    The dialect of include / exclude in a code host entry: * is any run of characters, ? is exactly one, everything else is literal. Matching is case-insensitive and always covers the whole name. createGlobMatcher compiles a pattern once for many names; matchesGlob is the one-off form. The matcher runs in time proportional to pattern length × name length, whatever the pattern.

    import { createGlobMatcher, matchesGlob } from "@safran/core";
    
    const isAcmeApp = createGlobMatcher("acme-*");
    console.log(["acme-ios", "acme-android", "web-app"].filter(isAcmeApp)); // ["acme-ios", "acme-android"]
    console.log(matchesGlob("Payments-API", "payments-???")); // true: case-insensitive, whole name
    console.log(matchesGlob("payments-api-v2", "payments-api")); // false: no partial match

    Common mistakes

    • Catching by message. Messages are for people and may change; code is the contract. Use isSafranError(error, "NOT_FOUND").
    • Expecting repos.sync or links.refresh to throw for a failing repo. They return a report. Check status per row and aborted on the report.
    • Searching code before a sync. safran.code answers from the local index. On a fresh data directory, run repos.sync() (or safran sync) first.
    • Reusing a search cursor with a different query. A cursor belongs to the query and options that produced it; anything else is INVALID_INPUT.
    • Forgetting close(). The index and the link store hold file handles. Use await using, or try / finally.
    • Passing an index and expecting close() to close it. An index passed in SafranOptions.index belongs to the caller.