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 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://jira.acme.example",
        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://jira.acme.example/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://jira.acme.example",
        pages: { "https://jira.acme.example/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
    PullsApi and its typesinterfacesafran.pulls
    WritesApi and its typesinterfacesafran.writes
    ToolPacksApi, RegisteredToolPack, toolNameCollisionsinterface, functionsafran.toolPacks
    tokenExpiry, TokenExpiryfunctionToken expiry
    linkRole, LINK_ROLE_PHRASESfunction, constanttickets.linkedWork
    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;
      /**
       * The hard switch for writes. `false` makes this instance read-only whatever the profile
       * says: `writes.status()` reports them off, `preview` / `commit` / `execute` fail with
       * FORBIDDEN, and a server built on the instance registers no write tool. Default: true, which
       * grants nothing by itself: the profile's `writes` section still has to enable them. A caller
       * that did not choose the profile itself (a CLI picking up `./safran.yaml`) passes `false`,
       * for the reason it passes `allowProfilePlugins: false`.
       */
      allowWrites?: boolean;
      /**
       * The instance's clock: confirmation-token expiry, audit times, index staleness. Default: the
       * real one. A seam for tests and replays; nothing in a normal setup passes it.
       */
      clock?: () => Date;
      /**
       * The in-memory answer cache of the work surface (`WorkCacheApi`): windows per kind of
       * question, size bounds, per-source concurrency. `false` turns caching off. Default: on, with
       * the `DEFAULT_WORK_CACHE_…` values.
       */
      workCache?: WorkCacheOptions | false;
    }

    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.
    allowWritesbooleantrueThe hard switch for writes. false: writes.status() reports them off, preview / commit / execute fail with FORBIDDEN, and a server built on the instance registers no write tool. true grants nothing by itself; the profile's writes section decides. A caller that did not choose the profile itself passes false.
    clock() => Datethe real clockUsed for confirmation-token expiry, audit times and index staleness. A seam for tests and replays.
    workCacheWorkCacheOptions | falseon, with the DEFAULT_WORK_CACHE_… valuesThe in-memory answer cache of the work surface: windows per kind of question, size bounds, per-source concurrency. false turns caching off; the concurrency limit and the rate-limit cool-down stay on either way.

    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;
      /**
       * When this instance was created, by its own clock: read before the profile file is, so a
       * profile edited later than this is one the instance may not have. What "since the server
       * started" means for anything serving it.
       */
      readonly startedAt: Date;
      /**
       * The instance's clock (`SafranOptions.clock`; the system clock by default), for callers that
       * must agree with it on what "now" is: token expiry, index staleness, relative ages.
       */
      readonly clock: () => Date;
      /** 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;
      /** Live pull requests (wave 2). */
      readonly pulls: PullsApi;
      /** The guarded write framework (wave 2). Present on every instance; disabled unless the profile and `allowWrites` say otherwise. */
      readonly writes: WritesApi;
      /** Namespaced JSON records in `<dataDir>/safran.db`, for plugins and for Safran's own small state. Opened on first use. */
      readonly store: StoreService;
      readonly toolPacks: ToolPacksApi;
      /** Boards with their columns and tickets (`work-api.ts`). */
      readonly boards: BoardsApi;
      /** Iterations: listings, tickets and the digest of one. */
      readonly iterations: IterationsApi;
      /** The ticket table, the home view, teams, epics, stand-up, and the cache they read through. */
      readonly work: WorkApi;
      /** Who "my work" means on this instance, and on what basis. */
      readonly me: MeApi;
    
      /**
       * 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.
    startedAtDateWhen this instance was created, by its own clock. What "since the server started" means for anything serving it.
    clock() => DateThe instance's clock (SafranOptions.clock; the system clock by default), for callers that must agree with it on what "now" is: token expiry, index staleness, relative ages.
    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.
    pullsPullsApiLive pull requests.
    writesWritesApiThe guarded write framework. Present on every instance; disabled unless the profile and allowWrites say otherwise.
    storeStoreServiceNamespaced JSON records in <dataDir>/safran.db. Opened on first use.
    toolPacksToolPacksApiTool packs of the profile.
    close() => Promise<void>Stops the instance and releases every handle.
    boardsBoardsApiBoards with their columns and tickets.
    iterationsIterationsApiIterations: listings, tickets and the digest of one.
    workWorkApiThe ticket table, the home view, teams, epics, stand-up, and the cache they read through.
    meMeApiWho "my work" means on this instance, and on what basis.

    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.
     *
     * `get` also fills `Ticket.designLinks` (kit `extractDesignLinks` over the description, the text
     * fields and the web links); connectors do not. `search` with `createdSince` leaves out, with a
     * warning, every tracker that lacks the `created-since` capability.
     */
    export interface TicketsApi extends TicketDepthApi {
      /** 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://jira.acme.example/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();

    tickets.children

    children(ref: string, options?: PageOptions): Promise<Page<TicketChild>>

    Direct children, one page, each with its current status and assignee. Throws UNSUPPORTED without the children capability.

    tickets.family

    family(ref: string, options?: TicketFamilyOptions): Promise<TicketFamily>

    The parent, the direct children and the siblings, with progress counts. Works on any tracker: a part it cannot provide ("children") is listed in unsupported and comes back empty. limit caps children and siblings each: default DEFAULT_FAMILY_LIMIT, at most DEFAULT_MAX_FAMILY_LIMIT.

    FieldTypeMeaning
    ticketTicketSummaryThe ticket asked for.
    parentTicketSummaryAbsent when the ticket has no parent.
    childrenFamilyMember[]Direct children, in the tracker's order.
    childProgressFamilyProgressCounted over the children returned; exact when childrenTruncated is false.
    childrenTruncatedbooleanTrue when the ticket has more children than limit.
    siblingsFamilyMember[]The parent's other children. Empty without a parent.
    siblingProgressFamilyProgressCounted over the siblings returned plus this ticket: the progress of the parent.
    siblingsTruncatedbooleanTrue when the parent has more children than limit.
    unsupportedstring[]Parts the tracker cannot provide.
    /** How many members are in each status category. `unknown`: the tracker gave no category. */
    export interface FamilyProgress {
      total: number;
      todo: number;
      inProgress: number;
      done: number;
      unknown: number;
    }
    
    export interface TicketFamilyOptions extends CallOptions {
      /** Most children and most siblings returned (each). Default `DEFAULT_FAMILY_LIMIT`, max `DEFAULT_MAX_FAMILY_LIMIT`. */
      limit?: number;
    }

    defined in packages/core/src/api.ts

    tickets.linkedWork

    linkedWork(ref: string, options?: LinkedWorkOptions): Promise<LinkedWork>

    The links of a ticket, digested for "can I start, and what else must I read". Linked tickets are read again for their current status, at most DEFAULT_LINKED_WORK_MAX_TICKETS of them, DEFAULT_LINKED_WORK_CONCURRENCY at a time. Throws UNSUPPORTED without the links capability; INVALID_INPUT for an expandBodies that is not a whole number of at least 0.

    FieldTypeMeaning
    ticketTicketSummaryThe ticket asked for.
    verdict"blocked" | "not_blocked" | "unknown"blocked when at least one blocker is not done, not_blocked when every blocker is done or there is none, unknown when a blocker's status could not be read.
    reasonsstring[]One line per blocker that decided it. Keys and status names only.
    unfinishedBlockersLinkedTicket[]Blockers that are not done, the ones with a body first.
    finishedBlockersLinkedTicket[]Blockers that are done.
    blocksLinkedTicket[]Tickets waiting for this one.
    relatedLinkedTicket[]Everything else, duplicates included (role says which).
    counterpartsCounterpartTicket[]Tickets for another side of the same feature, found through tickets.title_prefixes, not through a link.
    web{ relation, url, title? }[]Web links as the tracker gave them.
    warningsSafranWarning[]Linked tickets that could not be read now; their link data is still in the lists.
    unsupportedstring[]Parts the tracker cannot provide.
    export interface LinkedTicket extends TicketSummary {
      /** The relation as the tracker words it. */
      relation: string;
      role: LinkRole;
      /** Current status category, read now (a link's own snapshot may be old). Absent when the ticket could not be read. */
      statusCategory?: StatusCategory;
      assignee?: Person;
      /**
       * The ticket's description (Markdown), cut to `bodyChars`. Present only for unfinished
       * blockers and counterparts, at most `expandBodies` of them, blockers first.
       */
      body?: string;
      bodyTruncated?: boolean;
    }
    
    /** A ticket for the other side of the same feature, found through the profile's title prefixes, not through a link. */
    export interface CounterpartTicket extends LinkedTicket {
      /** The side its title prefix names (a key of `tickets.title_prefixes`). */
      side: string;
    }
    
    /**
     * What a link means for doing the work, decided from the tracker's relation wording:
     * `blocker` (this ticket is blocked by / depends on it), `blocks` (it waits for this ticket),
     * `duplicate`, `related` (everything else).
     */
    export type LinkRole = "blocker" | "blocks" | "duplicate" | "related";
    
    export interface LinkedWorkOptions extends CallOptions {
      /** How many unfinished blockers and counterparts get their body. Default `DEFAULT_LINKED_WORK_BODIES` (3); 0 for none. */
      expandBodies?: number;
      /** Characters of each body. Default `DEFAULT_LINKED_WORK_BODY_CHARS`. */
      bodyChars?: number;
      /** Look for counterpart tickets. Default: true when the profile has `tickets.title_prefixes` and the tracker can search. */
      counterparts?: boolean;
    }

    defined in packages/core/src/api.ts

    linkRole(relation) and LINK_ROLE_PHRASES are the mapping from a tracker's relation wording to a LinkRole, exported for callers that classify links themselves.

    /** The role of one relation, by `LINK_ROLE_PHRASES`. */
    export function linkRole(relation: string): LinkRole;

    defined in packages/core/src/ticket-depth.ts

    tickets.changes

    changes(ref: string, options?: TicketChangesOptions): Promise<TicketChanges>

    What happened to a ticket since a point in time: a HistoryDigest and the comments created inside the window. Throws UNSUPPORTED when the tracker has neither history nor comments; INVALID_INPUT for a since that is not a date, a duration or last_status_change.

    export interface TicketChangesOptions extends CallOptions {
      /**
       * Where the window starts: an ISO date or date-time, a duration back from now (`36h`, `3d`,
       * `2w`), or `"last_status_change"` (everything since the ticket last changed status).
       * Default: `"last_status_change"`.
       */
      since?: string;
      /** Clock, for durations and for the time in the current status. Default: now. */
      now?: Date;
      /** History entries read at most. Default `DEFAULT_CHANGES_HISTORY_LIMIT`. */
      historyLimit?: number;
      /** New comments returned at most. Default `DEFAULT_CHANGES_COMMENT_LIMIT`. */
      commentLimit?: number;
    }
    
    /** "What happened to this ticket since …", in one answer. */
    export interface TicketChanges {
      ticket: TicketSummary;
      /** Start of the window as an ISO time. Absent when it could not be determined (no status change on record): the digest then covers everything read. */
      since?: string;
      digest: HistoryDigest;
      /** False when the history was longer than `historyLimit`: older entries were not read, so durations of early statuses may be missing. */
      historyComplete: boolean;
      /** Comments created inside the window, oldest first. */
      comments: Comment[];
      commentsTruncated: boolean;
      /** Of "history", "comments": what the tracker cannot provide. */
      unsupported: string[];
    }

    defined in packages/core/src/api.ts

    tickets.worklogs and tickets.time

    worklogs(ref: string, options?: PageOptions): Promise<Page<Worklog>> · time(ref: string, options?: TicketTimeOptions): Promise<TicketTime>

    worklogs is one page of logged work and throws UNSUPPORTED without the worklogs capability. time puts the tracker's time summary, the worklogs (at most worklogLimit, default DEFAULT_TIME_WORKLOG_LIMIT) and the iterations in one answer and is never UNSUPPORTED as a whole.

    export interface TicketTimeOptions extends CallOptions {
      /** Worklogs read at most. Default `DEFAULT_TIME_WORKLOG_LIMIT`. */
      worklogLimit?: number;
    }
    
    /** Estimate, logged work and scheduling of one ticket, each part present when the tracker has it. */
    export interface TicketTime {
      ticket: TicketSummary;
      tracking?: TimeTracking;
      /** Oldest first. */
      worklogs: Worklog[];
      /** True when the ticket has more worklogs than were read; the sums below then cover only those read. */
      worklogsTruncated: boolean;
      /** Seconds logged per person, most first, over the worklogs read. */
      loggedByPerson: { person: string; seconds: number }[];
      /** Oldest first, current last. */
      iterations: Iteration[];
      /** Of "worklogs", "time-tracking", "iterations": what the tracker cannot provide. */
      unsupported: string[];
    }

    defined in packages/core/src/api.ts

    safran.code

    export interface CodeApi {
      search(query: string, options?: SafranCodeSearchOptions): Promise<CodeSearchResult>;
      /** `GrepResult.byRepo` and `byRepoExact` are always present here: taken from the index when it counts, otherwise counted over `matches` (then exact only when `truncated` is false). */
      grep(pattern: string, options?: SafranGrepOptions): Promise<GrepResult>;
      /** The slice carries `indexedAt` and `stale` of its repository (the rule of `isIndexStale`), unless the index status cannot be read. */
      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.
    allGroupsstring[]noneOnly repos that are in every one of these groups (an intersection), where groups is a union. Both may be given. Unknown names are INVALID_INPUT.
    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.
    byRepo{ repo: string; hits: number }[]Hits per repository in hits, most first.

    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?: SafranGrepOptions): 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://jira.acme.example/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; /** Ask each host for its remote heads to fill `behind` (one call per cloned repo). Default false. */ checkRemote?: 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; checkRemote?: 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.
    indexedFilesnumberFiles of this repo in the index. Absent exactly when indexedAt is.
    indexedChunksnumberChunks of this repo in the index. Absent exactly when indexedAt is.
    stalebooleanTrue when the index of this repo is older than DEFAULT_INDEX_STALE_AFTER_DAYS or was built with another embedder. Absent when never indexed.
    behindbooleanTrue when the default branch on the host is at another commit than the working tree. Present only when the listing was asked to checkRemote, the host has remote-head and the repo is cloned; a host that could not be asked leaves it out and adds a warning.

    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[]>;
      /**
       * The same records one page at a time: `limit` is the page size and `nextCursor` (present while
       * more match) goes back as `WorkQuery.cursor`. A cursor made for other filters is INVALID_INPUT.
       */
      queryPage(query?: WorkQuery, options?: CallOptions): Promise<Page<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.
    cursorstringnextCursor of the previous queryPage call with the same filters. A cursor made for other filters is INVALID_INPUT. Used by query and queryPage only.

    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.pulls

    /**
     * Live pull requests across every code host of the profile, with the conventions of
     * `TicketsApi`. `ref` is whatever a person would paste: a pull request URL, the explicit form
     * `<host id>:<repo>#<id>`, or `<repo>#<id>` when the repo name is unique across hosts
     * (`!` is accepted for `#`). A host without the needed capability makes the call UNSUPPORTED,
     * naming the host and its capabilities.
     */
    export interface PullsApi {
      /**
       * Finds the host and repo a reference belongs to. NOT_FOUND when no host recognises it,
       * INVALID_INPUT when several do (the hint shows the explicit form). Asynchronous, unlike
       * `tickets.resolve`: the `<repo>#<id>` form needs the repo listing. It does not check that the
       * pull request exists.
       */
      resolve(ref: string, options?: CallOptions): Promise<ResolvedPullRequestRef>;
      find(query: PullRequestFindQuery, options?: PullRequestFindOptions): Promise<PullRequestFindResult>;
      /** One merged page over hosts and repos, roughly newest first. The cursor is opaque and belongs to the same options. */
      list(options?: PullRequestListOptions): Promise<PullRequestListResult>;
      get(ref: string, options?: CallOptions): Promise<LivePullRequest>;
      changes(ref: string, options?: PageOptions): Promise<Page<PullRequestChange>>;
      /** Needs `pr-diff`. */
      diff(ref: string, options?: PullRequestDiffOptions): Promise<Page<PullRequestDiff>>;
      /** Needs `pr-threads`. Group the result for display with kit `groupThreadsByFile`. */
      threads(ref: string, options?: ReviewThreadQuery): Promise<Page<ReviewThread>>;
    }

    defined in packages/core/src/api.ts

    Live pull requests across every code host of the profile. A pull request reference (ref) is a pull request URL, the explicit form <host id>:<repo>#<id>, or <repo>#<id> when the repo name is unique across hosts (! is accepted for #). A host without the needed capability makes the call UNSUPPORTED, naming the host and its capabilities. Guide and a complete example: pull requests.

    MethodReturnsCapabilityThrows
    resolve(ref, options?)ResolvedPullRequestRefpull-requests-liveNOT_FOUND when no host recognises the reference; INVALID_INPUT when it is empty or several hosts recognise it. It does not check that the pull request exists.
    find(query, options?)PullRequestFindResultpull-requests-liveINVALID_INPUT unless exactly one of url, ticket, branch is given, or for an unknown state; UNSUPPORTED when no configured host has live pull requests.
    list(options?)PullRequestListResultpull-requests-liveINVALID_INPUT for an unknown host, group or state, or a cursor of another listing; NOT_FOUND for an unknown repo; UNSUPPORTED when no configured host has live pull requests.
    get(ref, options?)LivePullRequestpull-requests-liveNOT_FOUND when the id does not exist in that repo.
    changes(ref, options?)Page<PullRequestChange>pull-requests-live
    diff(ref, options?)Page<PullRequestDiff>pr-diff
    threads(ref, options?)Page<ReviewThread>pr-threads
    OptionTypeMeaning
    hoststringRestrict to one code host entry id. Default: every host with pull-requests-live.
    reposstring[]Repo short names. Default: every managed repo.
    groupsstring[]Repo groups from the profile (a union), combined with repos as in code search.

    It extends PullRequestListQuery (state, draft, author, reviewer, sourceBranch, targetBranch, createdSince, updatedSince, limit, cursor, signal). limit defaults to DEFAULT_PULL_REQUEST_LIST_LIMIT and is clamped to DEFAULT_MAX_PULL_REQUEST_LIST_LIMIT.

    FieldTypeMeaning
    matchesLivePullRequest[]Newest first. Empty when nothing matches: an answer, not an error.
    bestLivePullRequestThe match to read without asking: the only one, or the only open one among several. Absent when the choice is not obvious.
    truncatedbooleanTrue when more matched than limit (default DEFAULT_PULL_REQUEST_FIND_LIMIT).
    warningsSafranWarning[]Hosts that failed or could not be asked.
    /**
     * How to look for a pull request. Exactly one of `url`, `ticket`, `branch`:
     * - `url`: a pull request link; at most one match.
     * - `ticket`: a ticket reference; matches pull requests that carry its key (native link, title,
     *   branch, description), found among the live ones and, for merged work, in the link store.
     * - `branch`: a source branch name (the branch of the working tree, usually).
     */
    export type PullRequestFindQuery = ({ url: string } | { ticket: string } | { branch: string }) & {
      /** Narrow `ticket` / `branch` lookups to these repos. */
      repos?: string[];
      /** Default: `all` for `url`, otherwise open first: open matches are returned alone when there are any, else merged and closed ones. */
      state?: PullRequestState | "all";
    };
    
    export interface PullRequestFindOptions extends CallOptions {
      /** Most matches returned. Default `DEFAULT_PULL_REQUEST_FIND_LIMIT`. */
      limit?: number;
    }
    
    /**
     * A pull request as it is now, with the code host entry it came from and every ticket key
     * found for it: the host's native links plus keys recognised in the title, the source branch
     * and the description (the same recognition the link store uses).
     */
    export interface LivePullRequest extends PullRequestDetails {
      host: string;
      ticketKeys: string[];
    }
    
    export interface PullRequestListResult extends Page<LivePullRequest> {
      /** One entry per host that failed, cannot list live pull requests, or cannot apply one of the filters; the others are still returned. */
      warnings?: SafranWarning[];
    }
    
    export interface ResolvedPullRequestRef {
      host: CodeHost;
      /** Short repository name. */
      repo: string;
      id: string;
    }

    defined in packages/core/src/api.ts

    safran.writes

    /**
     * The only way anything outside this machine is changed. Off by default.
     *
     * Order of the checks every method makes, each failing with the first that applies:
     * 1. `allowWrites: false` → FORBIDDEN ("writes are turned off for this instance").
     * 2. profile `writes.enabled` false → FORBIDDEN, hint naming `writes.enabled`.
     * 3. the intent's kind not in `writes.allow` → FORBIDDEN, hint naming `writes.allow` and the kind.
     * 4. the input (INVALID_INPUT: empty or over-long body, `line` without `path`, …).
     * 5. the target (NOT_FOUND / INVALID_INPUT from resolving the reference).
     * 6. the connector's `write:` capability → UNSUPPORTED naming the connector.
     * A write is never a side effect of a read: nothing outside this interface calls a connector's
     * `write:` method. If the audit row cannot be stored, nothing is sent.
     */
    export interface WritesApi {
      /** Offline. Never throws for "disabled": that is what it reports. */
      status(): WritesStatus;
      /** Checks 1–6, reads the target, records the preview and returns the token. Sends nothing. */
      preview(intent: WriteIntent, options?: WriteCallOptions): Promise<WritePreview>;
      /**
       * Performs the write a preview described. CONFIRMATION_REQUIRED for a token that is unknown,
       * expired or from another instance (the hint says to preview again); CONFLICT for one that was
       * already used (the hint carries the URL of what it created) or whose target changed in a way
       * that invalidates the preview. Checks 1–3 are made again: turning writes off between preview
       * and commit wins. The token is spent the moment the request is sent, whatever the outcome: a
       * failed commit needs a new preview, and a failure after the request left is reported as
       * UPSTREAM with a hint that the write may have happened.
       */
      commit(confirmationToken: string, options?: WriteCallOptions): Promise<WriteCommitResult>;
      /**
       * Preview and commit in one call, for code that already has its confirmation elsewhere (a
       * script, a CI job). CONFIRMATION_REQUIRED while the profile has `writes.require_confirmation:
       * true` (the default), with a hint naming that key. Audited like any other write.
       */
      execute(intent: WriteIntent, options?: WriteCallOptions): Promise<WriteCommitResult>;
      /** Audit rows, newest first. Reads the local store only; works while writes are disabled. */
      log(query?: WriteLogQuery, options?: CallOptions): Promise<WriteAuditEntry[]>;
    }

    defined in packages/core/src/api.ts

    The only way anything outside this machine is changed. Present on every instance; off unless the profile's writes section enables it and the instance was not created with allowWrites: false. Guide, the order of the checks and a complete preview → commit example: writes.

    MethodReturnsNotes
    status()WritesStatusSynchronous and offline. Never throws for "disabled": that is what it reports.
    preview(intent, options?)WritePreviewMakes every check, reads the target, records the preview and returns the token. Sends nothing.
    commit(confirmationToken, options?)WriteCommitResultPerforms the write a preview described. CONFIRMATION_REQUIRED for a token that is unknown, expired or from another instance; CONFLICT for one that was already used.
    execute(intent, options?)WriteCommitResultPreview and commit in one call. CONFIRMATION_REQUIRED while the profile has writes.require_confirmation: true.
    log(query?, options?)WriteAuditEntry[]Audit rows, newest first. Local store only; works while writes are disabled.
    FieldTypeMeaning
    enabledbooleanTrue only when allowWrites is not false, the profile says writes.enabled: true and allow is not empty.
    allowedWriteIntentKind[]The kinds a preview would accept right now: writes.allow, minus kinds no configured connector can perform. Empty when disabled.
    requireConfirmationbooleanThe profile's writes.require_confirmation.
    reasonstringWhen disabled: what turned them off, naming the switch.
    switchWritesSwitchWhen disabled: the switch that decided it, for code. The same names as details.switch of the FORBIDDEN error.
    /**
     * Exactly what a commit would send, and the token that commits it. Making a preview reads the
     * target (to prove it exists and to show its title) and changes nothing remote; it writes one
     * `previewed` row to the audit log.
     */
    export interface WritePreview {
      kind: WriteIntentKind;
      target: WriteTarget;
      /** One line a person can confirm: `Add a comment to PAY-7 "Refund fails on partial capture"`. Contains the target's title: third-party text. */
      description: string;
      /** The title that will be sent (`ticket.create_child` only). */
      title?: string;
      /** The body that will be sent, character for character: the intent's Markdown plus the profile's marker. */
      body: string;
      /** True when `writes.marker` was appended to `body`. */
      markerAdded: boolean;
      /** `ticket.create_child`: resolved type and labels. `type` absent means the tracker's default child type. */
      ticketType?: string;
      labels?: string[];
      /** `ticket.create_child`: existing children of the parent with a very similar title. Not a refusal; a reason to ask. */
      possibleDuplicates?: TicketSummary[];
      /** `pull_request.reply`: the comment being answered (first of the thread), cut. Third-party text. */
      inReplyTo?: { author?: string; excerpt: string };
      /**
       * Opaque, unguessable, single use, valid until `expiresAt`, bound to this instance and to
       * exactly this payload. Not a secret to protect from the user: its job is to prove that a
       * preview happened and that what is committed is what was shown.
       */
      confirmationToken: string;
      /** ISO time; `DEFAULT_WRITE_CONFIRMATION_TTL_MS` after the preview. */
      expiresAt: string;
    }
    
    /** What a write will touch, resolved from the intent's reference. */
    export interface WriteTarget {
      /** Profile entry id of the tracker or code host. */
      source: string;
      type: "ticket" | "pull_request";
      /** Ticket key, or `<repo>#<id>`. For `ticket.create_child`: the PARENT. */
      key: string;
      url?: string;
      /** Title of the ticket or pull request, read at preview time. Third-party text. */
      title?: string;
      /** For `pull_request.reply`: the thread, and for a line comment the position. */
      threadId?: string;
      path?: string;
      line?: number;
    }
    
    /** A write that went through. */
    export interface WriteCommitResult extends WriteResult {
      kind: WriteIntentKind;
      target: WriteTarget;
      /** Id of the audit row. */
      auditId: string;
    }
    
    /** One row of the audit log (`write_audit` in `<dataDir>/safran.db`). */
    export interface WriteAuditEntry {
      id: string;
      /** ISO time of the last change of the row (the preview, then the commit or the failure). */
      at: string;
      kind: WriteIntentKind;
      target: WriteTarget;
      status: WriteAuditStatus;
      /** SHA-256 (hex) of the body that was previewed, so a row can be matched to a posted text without storing it twice. */
      bodySha256: string;
      /** The body. Kept for `committed` and `failed` rows; a preview never committed keeps only the hash. */
      body?: string;
      /** For `committed`: what the connector reported. */
      resultId?: string;
      resultUrl?: string;
      /** For `failed`. */
      error?: BatchError;
      /** Who asked, when the caller said so (`WriteCallOptions.client`): an MCP client name, "cli". */
      client?: string;
    }
    
    export type WriteAuditStatus = "previewed" | "committed" | "failed";
    
    export interface WriteLogQuery {
      /** ISO date lower bound on `at` (inclusive). */
      since?: string;
      kinds?: WriteIntentKind[];
      statuses?: WriteAuditStatus[];
      /** Default `DEFAULT_WRITE_LOG_LIMIT`. */
      limit?: number;
    }
    
    export interface WriteCallOptions extends CallOptions {
      /** Recorded in the audit row. One line, no secrets. */
      client?: string;
    }

    defined in packages/core/src/api.ts

    safran.store

    store: StoreService

    Namespaced JSON records in <dataDir>/safran.db, for plugins and for small state of your own. namespace(name) hands out one namespace (two calls with the same name see the same records) and opens nothing until first use; it throws INVALID_INPUT for a name that does not match STORE_NAMESPACE_PATTERN. The interfaces and limits are in the kit reference; the guide is tool packs and the store.

    safran.toolPacks

    /**
     * Tool packs are built with the connectors when the instance is created (no network I/O).
     * Creation fails with PLUGIN_CONFIG_INVALID when a pack has no tools, a tool name is not
     * snake_case, or two packs define the same tool name.
     */
    export interface ToolPacksApi {
      /** In profile order. Empty when the profile lists none. */
      list(): RegisteredToolPack[];
      /**
       * Runs one tool by name with a fresh `ToolPackContext` (the instance's read services, the
       * pack's store namespace, a signal that also fires on `close()`). NOT_FOUND for an unknown
       * tool; FORBIDDEN for a tool that changes the outside world (`readOnly: false` and
       * `openWorld: true`) while writes are disabled.
       */
      call(tool: string, args: unknown, options?: ToolPackCallOptions): Promise<AgentToolOutput>;
    }
    
    /** A tool pack built from a `tool_packs` entry of the profile. */
    export interface RegisteredToolPack {
      /** Profile entry id; also the name of the pack's store namespace (kit `toolPackNamespace`). */
      id: string;
      /** Plugin type. */
      type: string;
      tools: readonly AgentTool[];
      instructions?: string;
    }
    
    export interface ToolPackCallOptions extends CallOptions {
      /**
       * The wrapper handed to the handler as `ToolPackContext.untrusted`. A server that shows the
       * result to a model passes its own (so the tag matches the rest of that result). Default: kit
       * `wrapUntrusted` with a nonce made for this call.
       */
      untrusted?: (text: string, source: string) => string;
    }

    defined in packages/core/src/api.ts

    The tool packs built from the profile's tool_packs. They are built with the connectors when the instance is created, without network I/O; creation fails with PLUGIN_CONFIG_INVALID when a pack has no tools, a tool name is not snake_case, or two packs define the same tool name.

    MethodReturnsThrows
    list()RegisteredToolPack[], in profile order
    call(tool, args, options?)AgentToolOutputNOT_FOUND for an unknown tool; FORBIDDEN for a tool that changes the outside world while writes are disabled; INVALID_INPUT for arguments its schema refuses; INTERNAL when the handler fails or returns something its own output schema rejects.

    toolNameCollisions(packs, reserved?) lists tool names that cannot be registered together: a name two packs define, and a name that is also in reserved. A server calls it with its own tool names before it registers the packs.

    /**
     * Tool names that cannot be registered together: a name two packs define, and a name that is
     * also in `reserved` (the names a server keeps for its own tools). One entry per clash, in pack
     * order. `createSafran` refuses a profile whose packs clash with each other; a server calls
     * this with its own tool names before it registers the packs.
     */
    export function toolNameCollisions(packs: readonly Pick<RegisteredToolPack, "id" | "tools">[], reserved: Iterable<string> = []): { tool: string; pack: string; with: string }[];

    defined in packages/core/src/tool-packs.ts

    Token expiry

    /**
     * Connector tokens that need attention, from the `token_expires` dates of the profile: expired
     * ones first, then the soonest. Pure and offline; an entry without the key is never listed.
     * An expired token otherwise shows up as every tool failing at once, so `safran doctor` and
     * `get_server_info` show this, and `createSafran` logs it.
     */
    export function tokenExpiry(profile: Profile, options: TokenExpiryOptions = {}): TokenExpiry[];
    
    /** A connector entry whose token has expired, or will within the warning window. */
    export interface TokenExpiry {
      /** Profile entry id. */
      source: string;
      /** Which list of the profile the entry is in. */
      kind: "tracker" | "code-host" | "doc-source";
      /** The entry's `token_expires`, `YYYY-MM-DD`. The token works through the end of that day (UTC). */
      expires: string;
      /** Whole days left; 0 on the last day, negative once it has passed. */
      daysLeft: number;
      expired: boolean;
      /** One line a person can act on. Holds no secret: the profile never does. */
      message: string;
    }
    
    export interface TokenExpiryOptions {
      /** Default: now. */
      now?: Date;
      /** Report tokens expiring within this many days. Default `DEFAULT_TOKEN_EXPIRY_WARNING_DAYS`. */
      withinDays?: number;
    }

    defined in packages/core/src/token-expiry.ts

    tokenExpiry(profile, options?) lists the connector entries whose token has expired or will within withinDays (default DEFAULT_TOKEN_EXPIRY_WARNING_DAYS), from the token_expires dates of the profile: expired ones first, then the soonest. Pure and offline. createSafran logs the same list as warnings.

    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, LinkRefreshRepoResult.error and WriteAuditEntry.error; SafranWarning in TicketSearchResult.warnings, repos.warnings(), LinkedWork.warnings and the pull request listings.

    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;
    /**
     * `<dataDir>/safran.db`: the one SQLite file behind the link store, the write audit log and the
     * plugin store. One handle per instance, opened on first use and closed with the instance.
     */
    export const LINKS_DB_FILE = "safran.db";
    
    /** Version of the whole file. The name is historical: the link store was its first tenant. */
    export const LINKS_SCHEMA_VERSION = 3;
    /** A repo whose index is older than this is reported `stale` on hits and in the repo list. */
    export const DEFAULT_INDEX_STALE_AFTER_DAYS = 7;
    
    /**
     * What the score of a code hit in a `code.deprioritise` group is multiplied by before the list
     * is re-sorted: such a hit must score a quarter higher than a hit elsewhere to keep its place.
     * Not yet tuned with `safran eval retrieval`; with an empty `deprioritise` list ranking is
     * untouched.
     */
    export const DEFAULT_DEPRIORITISE_FACTOR = 0.8;
    
    /** Remote heads asked for at once by `repos.list({ checkRemote: true })`. */
    export const DEFAULT_REMOTE_HEAD_CONCURRENCY = 6;
    
    /** A connector token that expires within this many days is reported by `tokenExpiry`. */
    export const DEFAULT_TOKEN_EXPIRY_WARNING_DAYS = 14;
    
    /** Pages a core method reads from a connector to gather one bounded answer (a family, a thread lookup); a connector that never ends its listing cannot hold a call forever. */
    export const DEFAULT_MAX_CONNECTOR_PAGES = 50;
    /** Children and siblings returned by `tickets.family` (each). */
    export const DEFAULT_FAMILY_LIMIT = 40;
    
    export const DEFAULT_MAX_FAMILY_LIMIT = 200;
    
    /** Unfinished blockers and counterparts whose body `tickets.linkedWork` includes. */
    export const DEFAULT_LINKED_WORK_BODIES = 3;
    
    export const DEFAULT_MAX_LINKED_WORK_BODIES = 10;
    
    export const DEFAULT_LINKED_WORK_BODY_CHARS = 2_000;
    
    export const DEFAULT_MAX_LINKED_WORK_BODY_CHARS = 20_000;
    
    /** Linked tickets whose current status is read in one `tickets.linkedWork` call; the rest keep the link's snapshot. */
    export const DEFAULT_LINKED_WORK_MAX_TICKETS = 50;
    
    /** Linked tickets `tickets.linkedWork` reads at the same time. */
    export const DEFAULT_LINKED_WORK_CONCURRENCY = 4;
    
    /** Search results looked at when `tickets.linkedWork` looks for counterpart tickets. */
    export const DEFAULT_COUNTERPART_SEARCH_LIMIT = 20;
    export const DEFAULT_TIME_WORKLOG_LIMIT = 200;
    
    export const DEFAULT_MAX_TIME_WORKLOG_LIMIT = 5_000;
    
    export const DEFAULT_CHANGES_HISTORY_LIMIT = 500;
    
    export const DEFAULT_MAX_CHANGES_HISTORY_LIMIT = 5_000;
    
    export const DEFAULT_CHANGES_COMMENT_LIMIT = 30;
    
    export const DEFAULT_MAX_CHANGES_COMMENT_LIMIT = 500;
    
    /** Comments `tickets.changes` reads to find the ones inside its window. */
    export const DEFAULT_CHANGES_COMMENT_SCAN_LIMIT = 500;
    /** Page size of `pulls.list` across all hosts. */
    export const DEFAULT_PULL_REQUEST_LIST_LIMIT = 20;
    
    export const DEFAULT_MAX_PULL_REQUEST_LIST_LIMIT = 100;
    
    export const DEFAULT_PULL_REQUEST_FIND_LIMIT = 10;
    
    /**
     * Pull requests `pulls.find` looks at per host (or per repo, when repos are named) for one
     * lookup by ticket or branch. Older open pull requests than that are not found by ticket.
     */
    export const DEFAULT_PULL_REQUEST_FIND_SCAN_LIMIT = 200;
    /** How long a confirmation token stays valid after its preview. */
    export const DEFAULT_WRITE_CONFIRMATION_TTL_MS = 10 * 60_000;
    
    /** Previews kept waiting at once; the oldest is dropped (its token then answers CONFIRMATION_REQUIRED). */
    export const DEFAULT_WRITE_MAX_PENDING_PREVIEWS = 100;
    
    export const DEFAULT_WRITE_LOG_LIMIT = 50;
    
    export const DEFAULT_MAX_WRITE_LOG_LIMIT = 1_000;
    
    /** Characters of a written body kept in an audit row (the SHA-256 always covers the whole body). */
    export const DEFAULT_WRITE_AUDIT_BODY_CHARS = 2_000;
    
    /** Characters of the comment a reply answers that a preview shows. */
    export const DEFAULT_WRITE_REPLY_EXCERPT_CHARS = 300;
    
    /** Existing children compared with a new child's title when a preview looks for duplicates. */
    export const DEFAULT_WRITE_DUPLICATE_SCAN_LIMIT = 200;
    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_VERSION<dataDir>/safran.db: the one SQLite file behind the link store, the write audit log and the plugin store. The names are historical
    DEFAULT_INDEX_STALE_AFTER_DAYSstale on code hits and in repos.list
    DEFAULT_DEPRIORITISE_FACTORranking of hits in a code.deprioritise group
    DEFAULT_REMOTE_HEAD_CONCURRENCYrepos.list({ checkRemote: true })
    DEFAULT_TOKEN_EXPIRY_WARNING_DAYStokenExpiry
    DEFAULT_MAX_CONNECTOR_PAGESevery core method that gathers one bounded answer from a paged connector
    DEFAULT_FAMILY_LIMIT, DEFAULT_MAX_FAMILY_LIMITtickets.family
    DEFAULT_LINKED_WORK_*, DEFAULT_MAX_LINKED_WORK_*, DEFAULT_COUNTERPART_SEARCH_LIMITtickets.linkedWork
    DEFAULT_TIME_WORKLOG_LIMIT, DEFAULT_MAX_TIME_WORKLOG_LIMITtickets.time
    DEFAULT_CHANGES_*, DEFAULT_MAX_CHANGES_*tickets.changes
    DEFAULT_PULL_REQUEST_LIST_LIMIT, DEFAULT_MAX_PULL_REQUEST_LIST_LIMITpulls.list
    DEFAULT_PULL_REQUEST_FIND_LIMIT, DEFAULT_PULL_REQUEST_FIND_SCAN_LIMITpulls.find
    DEFAULT_WRITE_*, DEFAULT_MAX_WRITE_LOG_LIMITsafran.writes

    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.