Skip to content
safran

Type to search. Enter opens the first result.

    Repositories and sync

    safran.repos knows which repositories the profile's code hosts provide and keeps local working trees and the code index up to date with them. This page covers listing, looking one up, and sync: its options, its progress events, how to cancel it, what it reports and what it throws.

    List repositories

    list-repos.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    for (const repo of await safran.repos.list()) {
      const state = repo.cloned ? `at ${repo.head?.slice(0, 7)}` : "not cloned";
      console.log(`${repo.name}  host ${repo.host}  groups ${repo.groups.join(",") || "-"}  teams ${repo.teams.join(",") || "-"}  ${state}  indexed ${repo.indexedAt ?? "never"}`);
    }
    for (const warning of safran.repos.warnings()) console.warn(`${warning.source}: ${warning.code}: ${warning.message}`);

    Before the first sync, and after it (two of acme's repositories):

    $ bun list-repos.ts
    payments-api  host azure  groups backend  teams Payments  not cloned  indexed never
    ledger  host azure  groups backend  teams Payments  not cloned  indexed never
    $ bun list-repos.ts
    payments-api  host azure  groups backend  teams Payments  at e947460  indexed 2026-11-23T11:33:00.124Z
    ledger  host azure  groups backend  teams Payments  at bccec78  indexed 2026-11-23T11:33:00.239Z

    list() asks every code host for its repositories, applies each host entry's include / exclude globs and adds what Safran knows locally.

    • The host listing is cached for the life of the instance. list({ refresh: true }) asks the hosts again. A sync() of everything refreshes it too.
    • Disk state is read fresh on every call: cloned, head and indexedAt reflect the latest sync, also one made by another process.
    • One host failing does not fail the list. The repositories of the other hosts are returned, the failure is in warnings(), and the incomplete listing is not cached, so the next call tries that host again. When every host fails, list() throws: the single host's own error, or one error naming each host.
    • Reading indexedAt opens an index that already exists on disk. It never creates one and never calls the embedder.

    ManagedRepo

    A ManagedRepo is the host's RepoInfo plus what the profile and the disk add.

    FieldFrom the code host
    nameShort name, the key used everywhere in Safran: in code.search scopes, in code.groups, in team repos.
    fullNameHost-qualified name, such as acme/Platform/payments-api.
    defaultBranchThe branch Safran clones and indexes.
    cloneUrlHTTPS clone URL without credentials. For a local host, an absolute directory path.
    webUrlLink for people, when the host has one.
    archivedWhether the host marks it archived.
    sizeKbSize as the host reports it.
    primaryLanguageMain language as the host reports it.
    FieldAdded by Safran
    hostId of the code host entry in the profile.
    groupsGroups from code.groups that contain this repo.
    teamsNames of the teams whose repos contain it.
    dirAbsolute path of the working tree. For a local host this is the source directory itself.
    clonedWhether the working tree exists on disk.
    headCommit the working tree is at, when cloned.
    indexedAtISO time of the last successful index run. Absent when never indexed, when code search is off, and when the index could not be opened.
    export interface ManagedRepo extends RepoInfo {
      /** Code host entry id. */
      host: string;
      /** Groups from the profile this repo belongs to. */
      groups: string[];
      /** Teams from the profile that own it. */
      teams: string[];
      /** Absolute path of the local working tree. For `local` hosts this is the source itself. */
      dir: string;
      /** Whether the working tree exists on disk. */
      cloned: boolean;
      /** Commit the working tree is at, when cloned. */
      head?: string;
      /**
       * ISO time of the last successful index run. Absent when the repo was never indexed, when code
       * search is off (`index: false`), and when the index exists on disk but could not be opened
       * (for example the embedder entry cannot be built). Reading it opens an index that already
       * exists on disk; that makes no embedder call, and it never creates an index.
       */
      indexedAt?: string;
    }
    
    export interface RepoInfo {
      /** Short name, unique inside the host entry. Used everywhere else in Safran. */
      name: string;
      /** Host-qualified name, e.g. "org/project/repo". */
      fullName: string;
      defaultBranch: string;
      /** HTTPS clone URL WITHOUT credentials. For local hosts, an absolute directory path. */
      cloneUrl: string;
      webUrl?: string;
      archived?: boolean;
      sizeKb?: number;
      primaryLanguage?: string;
    }

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

    Warnings

    repos.warnings() returns the problems of the most recent listing, whichever call made it (list, get, sync or a links refresh). It is synchronous and empty before the first listing.

    codeMeaning
    a failure code (AUTH_FAILED, UPSTREAM, …)The code host named in source could not list its repositories.
    UPSTREAMA host listed the same repository name twice. The first one is kept.
    INVALID_INPUTThe same short name exists on two hosts. The host listed first in the profile keeps the short name; the later one is named <hostId>/<name>.

    Look one up

    repos.get(name) returns one ManagedRepo. The name matches exactly, or case-insensitively when that is unambiguous. An unknown name is NOT_FOUND with the closest names in the hint and in details.closest:

    get-repo.ts
    import { createSafran, isSafranError } from "@safran/core";
    
    await using safran = await createSafran();
    
    try {
      const repo = await safran.repos.get("payment-api");
      console.log(repo.dir);
    } catch (error) {
      if (!isSafranError(error, "NOT_FOUND")) throw error;
      console.log(error.format());
      console.log(error.details);
    }
    $ bun get-repo.ts
    No repo named "payment-api"
    → Did you mean: payments-api?
    {
      unknown: [ "payment-api" ],
      closest: [ "payments-api" ],
    }

    Sync with progress and cancellation

    repos.sync() clones the repositories that are not on disk, fetches the ones that are, and indexes what changed. It is the SDK form of safran sync.

    sync.ts
    import { createSafran, type SyncProgress } from "@safran/core";
    
    await using safran = await createSafran();
    
    // Ctrl-C cancels the run; what finished stays finished.
    const controller = new AbortController();
    process.once("SIGINT", () => controller.abort());
    
    let last = "";
    const onProgress = (progress: SyncProgress): void => {
      const line = `${progress.repo}: ${progress.phase}`;
      if (line !== last) console.log(line);
      last = line;
    };
    
    const report = await safran.repos.sync({ signal: controller.signal, onProgress });
    
    for (const row of report.results) {
      if (row.status === "ok") {
        console.log(`ok       ${row.repo}  ${row.updated ? "updated" : "unchanged"}  ${row.index?.filesIndexed ?? 0} files indexed, ${row.index?.embeddingsComputed ?? 0} embeddings computed`);
      } else if (row.status === "failed") {
        console.log(`failed   ${row.repo}  ${row.error?.code}: ${row.error?.message}`);
        if (row.error?.hint !== undefined) console.log(`         → ${row.error.hint}`);
      } else {
        console.log(`skipped  ${row.repo}  ${row.reason ?? ""}`);
      }
    }
    if (report.removed !== undefined) console.log(`removed from the index: ${report.removed.join(", ")}`);
    console.log(report.aborted ? "cancelled before the end" : `done in ${report.durationMs} ms`);
    
    const failed = report.results.filter((row) => row.status === "failed");
    if (failed.length > 0) process.exitCode = 1;

    The first run clones and embeds; the second finds nothing to do:

    $ bun sync.ts
    payments-api: fetch
    payments-api: scan
    payments-api: chunk
    payments-api: embed
    payments-api: write
    ledger: fetch
    ledger: scan
    ledger: chunk
    ledger: embed
    ledger: write
    ok       payments-api  updated  3 files indexed, 3 embeddings computed
    ok       ledger  updated  1 files indexed, 1 embeddings computed
    done in 313 ms
    $ bun sync.ts
    payments-api: fetch
    payments-api: scan
    payments-api: chunk
    ledger: fetch
    ledger: scan
    ledger: chunk
    ok       payments-api  unchanged  0 files indexed, 0 embeddings computed
    ok       ledger  unchanged  0 files indexed, 0 embeddings computed
    done in 238 ms

    The timings are from two example repositories of a few files each, cloned from the same machine. A first sync of real repositories is dominated by embedding and takes far longer.

    Options

    OptionDefaultMeaning
    reposevery repo the hosts listRepo names to sync. An unknown name throws NOT_FOUND before anything is done; all unknown names are reported at once.
    offlinefalseSkip the git fetch and index what is on disk. A repo that was never cloned is skipped.
    fetchOnlyfalseUpdate the working trees and do not index. Works with index: false.
    onProgressnoneCalled with a SyncProgress as the work advances.

    signal from CallOptions cancels the run.

    export interface SyncOptions extends CallOptions {
      /** Repo names. Default: every repo the hosts list after include/exclude. */
      repos?: string[];
      /** Skip the git fetch and only re-index what is on disk. */
      offline?: boolean;
      /** Skip indexing and only update the working trees. */
      fetchOnly?: boolean;
      onProgress?: (progress: SyncProgress) => void;
    }
    
    export interface SyncProgress {
      repo: string;
      phase: "fetch" | IndexProgress["phase"];
      done: number;
      total: number;
    }

    defined in packages/core/src/api.ts

    Progress

    onProgress receives { repo, phase, done, total }. Repositories are processed one after the other, in listing order.

    phaseEmitteddone / total
    fetchBefore and after the clone or fetch of a repo. Not emitted for local hosts or with offline.0/1, then 1/1
    scanBefore and after the working tree is listed.0/0, then files found
    chunkWhile files are read, compared and cut into chunks.files examined / files found
    embedBefore each embedder call. Not emitted when every vector is already cached.changed files written / changed files found so far
    writeAfter a batch is written to the index.changed files written / changed files found so far

    The callback runs inside the sync. Keep it fast and do not throw from it.

    Cancellation

    Abort the signal to stop. A cancelled sync returns its report with aborted: true; it does not throw. The repo that was interrupted and the ones not reached are skipped; every repo that finished before the cancellation keeps its ok row and its work. Index batches already written stay written, so the next sync continues instead of starting over.

    close() cancels a running sync the same way. A signal that has already fired when sync is called gives a report with aborted: true at once.

    The report

    FieldMeaning
    resultsOne row per selected repo, in order.
    durationMsWall-clock time of the run.
    removedRepos dropped from the code index because no host lists them any more. Only a sync of every repo, with every host answering, in an index Safran opened itself, does this. Absent when nothing was removed.
    abortedtrue when the run was cancelled. Absent otherwise.
    FieldMeaning
    repoRepo name.
    statusok, failed or skipped.
    updatedWhether the working tree moved to a new commit. Absent when no fetch ran.
    headCommit the working tree is at afterwards.
    indexWhat the indexer did, an IndexRepoResult. Absent with fetchOnly.
    errorPresent when status is failed: a BatchError with code, message and hint.
    reasonPresent when a repo was skipped because another sync is working on it.

    A row is skipped in four situations: the run was cancelled before or during this repo; offline and the repo is not cloned; fetchOnly and the repo belongs to a local host; or another sync holds the repo's lock (then reason says who).

    index fieldMeaning
    repoRepo name.
    filesIndexedFiles whose content changed and were stored again.
    filesUnchangedFiles whose content hash matched; not touched.
    filesRemovedFiles that left the working tree and were dropped from the index.
    chunksWrittenChunks written for the changed files.
    embeddingsComputedVectors the embedder was asked for.
    embeddingsCachedVectors taken from the cache instead.
    durationMsTime spent indexing this repo.
    filesSkippedFiles left out, counted by reason: binary, large, secret, generated, ignored-dir, empty, …
    export interface SyncReport {
      results: RepoSyncResult[];
      durationMs: number;
      /**
       * Repos dropped from the code index because no code 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 (never in one passed as `SafranOptions.index`).
       */
      removed?: string[];
      /**
       * True when the run was cancelled (by the signal or by `close()`): the repo that was
       * interrupted and the ones not reached are reported as "skipped". A cancelled run is always
       * reported this way, never thrown, so what did finish is not lost.
       */
      aborted?: boolean;
    }
    
    export interface RepoSyncResult {
      repo: string;
      status: "ok" | "failed" | "skipped";
      /** Whether the working tree moved to a new commit. */
      updated?: boolean;
      head?: string;
      index?: IndexRepoResult;
      /** Present when status is "failed". One repo failing never aborts the others. */
      error?: BatchError;
      /**
       * Present when status is "skipped" for a reason the options do not explain: another sync
       * (this process or another one) is working on the repo right now.
       */
      reason?: string;
    }
    
    export interface IndexRepoResult {
      repo: string;
      filesIndexed: number;
      filesUnchanged: number;
      filesRemoved: number;
      chunksWritten: number;
      embeddingsComputed: number;
      embeddingsCached: number;
      durationMs: number;
      /** Files left out of the index, counted by reason ("binary", "large", "secret", …). */
      filesSkipped?: Record<string, number>;
    }

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

    What throws and what is reported

    sync throws only before any work starts:

    ThrownWhen
    NOT_FOUNDA name in repos is not a known repository.
    the listing errorNo code host could list its repositories.
    UNSUPPORTEDIndexing was asked for and the instance has index: false. Pass fetchOnly: true.
    the index's errorThe index could not be opened (for example INCOMPATIBLE_DATA, or the embedder entry cannot be built). It is opened before the first clone, so this fails in a moment rather than after every repository was fetched.

    From then on it always returns a report. One repo failing never stops the others:

    In a rowTypical causes
    AUTH_FAILEDThe host rejected the credentials, or the token may not read this repo. When the host rejected the credential itself, its remaining repos are failed at once with "Not attempted" instead of being tried one by one.
    NOT_FOUNDThe repository or its branch does not exist on the remote; or the directory of a local repo is gone.
    UPSTREAMNetwork failure, a git timeout (ten minutes per clone or fetch), an empty remote, an embedder that could not be reached.
    INTERNALgit is not installed, or the data directory is not writable.

    Error messages from git are scrubbed of credentials before they reach a row or a log.

    Incremental indexing

    Indexing is incremental at two levels:

    • Per file. A file is read, chunked and stored again only when its content hash changed. Unchanged files are counted in filesUnchanged; files that disappeared are removed.
    • Per chunk. A vector is computed only when no vector for that exact chunk text and embedder is in the cache. Moving a function between files, reverting a change or switching branches re-uses cached vectors (embeddingsCached). Vectors no chunk points at any more are kept for 30 days before they are pruned.

    Changing the profile's embedder invalidates every chunk of a repo: its next sync re-embeds it completely, and until then dense search refuses to mix models (INDEX_NOT_READY). An interrupted run keeps the batches it wrote, so repeating it is cheap.

    Locking

    Two syncs must not work in one working tree.

    • Inside one instance, sync calls run one after the other. A second call waits for the first; if its signal fires while it waits, it returns aborted: true without having run.
    • Across processes (a CLI sync next to a running MCP server, two terminals), each cloned repo has a lock file. A sync never waits for a lock: a repo that another process is syncing is reported skipped with a reason naming the process id and the time, and the run moves on. Sync again when the other one has finished.

    A lock whose process is gone is taken over. local repos have no lock, because Safran never writes to them.

    Where clones live

    <dataDir>/repos/<hostId>/<repo>            the working tree
    <dataDir>/repos/<hostId>/.locks/<repo>.lock
    <dataDir>/repos/<hostId>/.tmp/             clones in progress

    Characters outside letters, digits, ., _ and - in a host id or repo name are percent-encoded in the directory name, so ManagedRepo.dir is the reliable way to find a clone.

    Clones are shallow (depth 1) checkouts of the default branch, detached at the fetched commit. Each sync resets them to the remote's state, so do not edit files in a clone: changes are discarded. Credentials are handed to git through its environment, never in the URL, so they do not end up in .git/config.

    Local hosts are read in place

    A repository of a local host is not cloned. dir is the directory named in the profile, Safran reads it where it is and never writes to it, and a sync only indexes: there is no fetch, no lock and no updated flag. Files you have not committed yet are indexed too, unless .gitignore excludes them.

    Common mistakes

    SymptomCause
    A repo is missing from list()The host entry's include / exclude filters it out, or the host failed (see warnings()), or it was created after the listing was cached (refresh: true).
    skipped rows with a reasonAnother process is syncing those repos. Run again afterwards.
    Wrapping sync in try/catch to detect failuresFailures of single repos are rows, not exceptions. Check results for failed and aborted.
    UNSUPPORTED from sync on a tickets-only instanceIndexing needs an index. Use fetchOnly: true, or do not pass index: false.
    Code search still finds a deleted repositoryOnly a sync of everything removes it (removed). A sync with repos never does.