Skip to content
safran

Type to search. Enter opens the first result.

    Keeping the index fresh

    Code tools answer from the last index run and work history from the last refresh. This page explains what the two maintenance commands do each time they run, how to schedule them, how they behave when interrupted or run twice at once, what changes when a repository disappears or the embedding model is replaced, and how people and agents can see how old the data is.

    The two commands

    $ safran sync
    payments-api  scanning files
    payments-api  indexing 4/4 files  100%
    ledger  scanning files
    ledger  indexing 1/1 files  100%
       repo          status  changed  unchanged  chunks   time  detail
    ✔  payments-api  ok            1          3       1  82 ms  1 embedded, 0 from cache
    ✔  ledger        ok            0          1       0  12 ms  no changes
    
    2 repos: 2 ok in 99 ms
    $ safran links refresh
    payments-api  1 pull request read
       repo          pull requests  with a ticket  detail
    ✔  payments-api              1              0
    ✔  ledger                    0              0
    
    1 pull request read, 0 with a ticket, in 11 ms

    This is a second run on the toy setup of the new-company guide, after one file in payments-api was edited: one file re-chunked, one chunk embedded, everything else untouched. Both commands are incremental and safe to run as often as you like.

    What a sync does

    For every repository the code hosts list (after include / exclude), in order:

    1. List. A sync of everything asks the code hosts for their repositories again, so new and removed repositories are noticed. A sync of named repositories uses the listing the process already has.
    2. Open the index. Before anything is cloned, so a missing embedding server fails in a second and not after every repository has been fetched.
    3. Fetch. A repository not on disk yet is cloned shallow (depth 1, the default branch, no tags) into a temporary directory and moved into place when complete. One that is on disk is fetched at depth 1 and checked out at the fetched commit. local hosts are read in place: nothing is fetched and nothing is written to them.
    4. Scan. The files of the working tree are listed and each one is classified: indexed, kept for grep only, or left out.
    5. Chunk what changed. A file is re-chunked only when its content hash differs from the stored one. Files that vanished are removed from the index.
    6. Embed what is new. An embedding is computed only when the pair (embedder id, chunk text) is not in the cache. A reverted file, a renamed file or a chunk that occurs twice costs nothing. Cached vectors no chunk points at are kept for 30 days before they are pruned.
    7. Write. Chunks are written in batches, so searches keep working while a sync runs, and the repository's indexed_at is set when its run completes.

    Reading the table

    ColumnMeaning
    statusok, failed (the reason is printed in full below the table) or skipped.
    changedFiles chunked in this run: new, changed, or all of them after an embedder change.
    unchangedFiles whose content hash matched.
    chunksChunks written in this run.
    detailN embedded, M from cache, no changes, N files left out, or why the repository was skipped.

    One repository failing never fails the others. The exit code is 0 when nothing failed, 1 when at least one repository failed and 130 when the run was interrupted. --json prints the whole report as one document (per-repo counters, files_skipped by reason, removed, warnings).

    Options

    OptionEffect
    --offlineSkip the git fetch; index what is on disk. A repository that was never cloned is skipped.
    --fetch-onlyUpdate the working trees; do not index. The embedder is not needed.

    Name repositories to sync only those: safran sync payments-api ledger. An unknown name stops the command before any work starts, with the closest known names as a hint. The two options cannot be combined.

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

    defined in packages/core/src/api.ts

    Files that are left out

    The scan decides per file, from its path and size and then from its content:

    Reason (files_skipped key)What it covers
    ignored-dirDirectories never entered: .git, node_modules, virtual environments, IDE and build caches.
    secretFiles that usually hold credentials (.env*, key files, credential stores, Terraform state and variables), and any file that contains a private key block.
    binaryBinary extensions (images, archives, fonts, compiled code, office files), and any file with a NUL byte in its first 8000 bytes.
    generatedLock files, minified bundles, source maps.
    largeFiles over 1,000,000 bytes.
    emptyZero-byte files.
    not-a-file, nested-repoEntries that are not regular files, and repositories nested in the working tree.
    unreadableFiles that vanished or could not be read between the scan and the read.
    chunk_too_long_for_embedderCounts chunks, not files: a chunk the embedding model refused even after shortening is stored without a vector. Lexical search and grep still find it.

    Some files are stored for grep and reading but get no chunks and no vectors: files over 400,000 bytes, build output and vendored directories (dist, build, vendor, …), machine-written source (.d.ts, .g.cs, …), files with a mean line length above 300 characters, and JSON or XML files other than a short list of well-known names. A file that was indexed and later turns into a secret or a binary is deleted from the index on the next sync. The security side of this is in the security model.

    Refreshing the work history

    safran links refresh reads merged pull requests from the code hosts into the local ticket ↔ code store. It needs a host that lists pull requests (azure-repos, github, gitlab); local hosts are left out quietly.

    OptionEffect
    --since <date>How far back the history must reach. Default: where earlier refreshes of the repository reached, or 12 months back on its first one. An explicit date always re-reads its window.
    --max-per-repo <n>Cap on pull requests newly stored per repository in one run (default 500).

    How a run resumes:

    • A repository whose stored history already reaches its horizon is resumed from its newest stored pull request. That one is listed again and recognised, so a run with nothing new still reports one pull request read.
    • A repository with more pull requests inside the horizon than the cap is reported truncated. Hosts list newest first, so the next run walks down from the top again: stored pull requests are recognised and cost nothing, and only new ones count against the cap. Each run gets one cap further until a listing is read to its end.
    $ safran links refresh --max-per-repo 2
    payments-api  1 pull request read
       repo          pull requests  with a ticket  detail
    ✔  payments-api              2              1  history not fully fetched yet; run again to continue
    ✔  ledger                    0              0
    
    2 pull requests read, 1 with a ticket, in 11 ms
    ! History not fully fetched yet for payments-api. Run `safran links refresh --profile safran.yaml` again to continue.
    $ safran links status
    records        2 merged pull requests
    with a ticket  1 (50%)
    refreshed      just now
    ! History not fully fetched yet for 1 repo: payments-api
    → Run `safran links refresh --profile safran.yaml` again to continue.

    safran links status keeps showing the incomplete repositories until a later run has read their history to the end (incomplete_repos in --json, incompleteRepos in the SDK).

    export interface LinkRefreshOptions extends CallOptions {
      repos?: string[];
      /**
       * ISO date: how far back the history must reach (the horizon). Default: the horizon of the
       * repo's earlier refreshes, or 12 months back on its first one.
       */
      since?: string;
      /**
       * Cap on pull requests newly stored per repo in one run. A repo with more than that inside
       * the horizon is reported `truncated` and later runs continue where this one stopped.
       */
      maxPerRepo?: number;
      /**
       * Project keys used to recognise ticket keys in titles, branches and descriptions.
       * Default: every project declared under `trackers[].projects` in the profile (none in a
       * profile that does not declare its projects yet).
       */
      projectKeys?: string[];
      onProgress?: (progress: { repo: string; fetched: number }) => void;
    }
    
    export interface LinkRefreshRepoResult {
      repo: string;
      /** "skipped": the run was cancelled before this repo was read completely; nothing of it was stored. */
      status: "ok" | "failed" | "skipped";
      /** Pull requests written to the store in this run (new ones, and stored ones seen again). */
      fetched: number;
      /** How many of those carry at least one ticket key. */
      linked: number;
      /**
       * True while the store does not reach back to the horizon for this repo, because `maxPerRepo`
       * stopped the run. Run the refresh again to continue.
       */
      truncated?: boolean;
      /** Present when status is "failed". */
      error?: BatchError;
    }
    
    export interface LinksStatus {
      records: number;
      linked: number;
      refreshedAt?: string;
      /** Repos whose stored history does not reach back to their horizon yet (see `truncated`). */
      incompleteRepos: string[];
    }

    defined in packages/core/src/api.ts

    Scheduling

    Safran has no scheduler of its own; use the one the machine has. Three things matter:

    • Call bin/safran of the checkout by its absolute path and name the profile with --profile. A profile that is named may load its plugins:; one merely found in the working directory may not.
    • The scheduler's PATH must contain bun and git.
    • Tokens come from the .env next to the profile, so the job needs no secrets of its own.

    A crontab (/opt/safran stands for the Safran checkout):

    PATH=/usr/local/bin:/usr/bin:/bin
    
    # m   h  dom mon dow  command
    */30  *  *   *   *    /opt/safran/bin/safran sync --profile /work/acme/safran.yaml >> /work/acme/sync.log 2>&1
    15    6  *   *   *    /opt/safran/bin/safran links refresh --profile /work/acme/safran.yaml >> /work/acme/links.log 2>&1

    The same sync as a launchd agent on macOS:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
      <key>Label</key>
      <string>test.acme.safran-sync</string>
      <key>ProgramArguments</key>
      <array>
        <string>/opt/safran/bin/safran</string>
        <string>sync</string>
        <string>--profile</string>
        <string>/work/acme/safran.yaml</string>
      </array>
      <key>EnvironmentVariables</key>
      <dict>
        <key>PATH</key>
        <string>/usr/local/bin:/usr/bin:/bin</string>
      </dict>
      <key>StartInterval</key>
      <integer>1800</integer>
      <key>StandardOutPath</key>
      <string>/work/acme/sync.log</string>
      <key>StandardErrorPath</key>
      <string>/work/acme/sync.log</string>
    </dict>
    </plist>

    Adjust the PATH to where bun and git are installed on that machine. How often to run is your call: a sync with nothing to do costs one fetch per repository and a scan. When output is not a terminal, progress is printed as plain lines on stderr and the report on stdout; with --json there is no progress and stdout carries one JSON document, which is the form to parse in a wrapper script. A job that overlaps the previous one is safe; see the next section.

    Ctrl-C and concurrent runs

    Interrupting. Ctrl-C (or SIGTERM) cancels the run cleanly. The report is still printed: repositories that finished are ok, the one that was interrupted and the ones not reached are skipped, a closing line says the run was interrupted and that running safran sync again continues it, and the exit code is 130. Nothing is lost: batches of the interrupted repository that were already written stay searchable, its embeddings are in the cache, and the next run continues from there. A repository whose first run never finished has no indexed_at yet, and safran doctor names it.

    safran links refresh behaves the same way with one difference: a repository is stored in one transaction, so the interrupted repository stores nothing of that run.

    Two syncs at once. Each cloned repository has a lock file under <data dir>/repos/<host>/.locks/. A sync that finds a repository locked by another process (a second terminal, a scheduled job, a running server) does not wait: it reports the repository as skipped with the reason and moves on.

    What you seeMeaning
    skipped, detail Another sync is working on this repo (process …, since …). It was left alone; sync again once that one has finished.Another process holds the repository's lock. Not a failure: the exit code stays 0.
    skipped, detail not reachedThe run was interrupted before this repository, or --offline met a repository that was never cloned.
    skipped, detail not indexed (--fetch-only)A local repository under --fetch-only: there is nothing to fetch.
    INDEX_NOT_READY: The code index is locked by another Safran processThe index file itself was busy for longer than the wait. Run the command again when the other one has finished.

    A lock left by a process that died is taken over: when its process no longer exists, or when it is older than 24 hours. Clones a dead process left half-way are removed before the next fetch. Inside one process (one SDK instance) syncs run one after another, and so do link refreshes. local repositories have no lock, because Safran never writes to them.

    Repositories that disappear

    When a repository is deleted or renamed on the host, excluded by exclude, or its host is removed from the profile, the next full sync drops it from the index and says so: Dropped from the index (no code host lists it any more): … (removed in the report).

    This happens only when it is safe to conclude the repository is gone: a sync of everything (no repository names), every code host answered its listing, the run was not interrupted, and the index is the one Safran opened itself. If one host could not list its repositories, nothing is removed: what is missing is then unknown, not gone. The working tree under data/repos/ is not deleted; remove the directory by hand if you want the disk space back. Stored pull requests of the repository stay in the link store.

    Changing the embedder

    Vectors of two models cannot be compared, so the index records which embedder built each repository and refuses to mix them. After you change embeddings in the profile and before you sync:

    $ safran status
    profile      acme  safran.yaml
    trackers     jira
    code hosts   azure (azure-repos)
    doc sources  none
    knowledge    0 groups, 0 teams, 0 glossary terms
    environment  3 of 3 variables set
    index        ✘ 2 repos built with another embedder than ollama:bge-large → safran sync
    links        3 pull requests, 2 with a ticket, refreshed just now
    data         data
    $ safran search refund policy
    ✘ The code index holds vectors from "ollama:bge-m3" but the configured embedder is "ollama:bge-large" (repositories: ledger, payments-api)
    → Run `safran sync` to re-index these repositories with the configured embedder, or configure the embedder they were built with. Until then only lexical search (mode "lexical"), grep and reading files work.

    The error is INDEX_NOT_READY. Until the re-index, safran search --mode lexical, safran grep and safran read keep working. Then:

    safran sync

    Every indexed file of every repository is chunked and embedded again; this is as expensive as the first sync. A repository keeps its old marker until its run completes, so an interrupted re-index is repeated on the next run, cheaply: the vectors already computed are cache hits. Switching back to the previous embedder within 30 days is also mostly cache hits, because unused vectors are kept that long. The embedder's identity is its id (for the built-in ones the type and the model, such as ollama:bge-m3); see the embedder pages under connectors. Run the retrieval evaluation before and after a change of model.

    Seeing how fresh things are

    safran status and safran doctor

    safran statussafran doctor
    Calls a tracker, a code host or the embedderno Local state onlyyes One embedding call and one repo listing
    ShowsProfile, connectors, index size and age, link store size and age, unset variablesBun, git, launch, profile, each variable, embedder, repos, index, links
    Index problems it namesNot built, built with another embedder, no sync finished yetThe same, plus repositories listed but not indexed, runs that did not finish, and repositories older than 7 days
    Exit code01 when a check fails; warnings do not fail it

    safran status is the quick look; safran doctor is the first thing to run when something is wrong. safran repos lists every repository with its indexed time.

    $ safran doctor
    ✔ bun             Bun 1.3.2
    ✔ git             git version 2.50.1 (Apple Git-155)
    ✔ launch          started through bin/safran: Bun loaded no .env or bunfig.toml from this directory
    ✔ profile         safran.yaml (acme): 1 tracker, 1 code host
    ✔ env JIRA_TOKEN  set (used by trackers.jira.token_env)
    ✔ embedder        ollama:bge-m3 answered in 32 ms (1024 dimensions)
    ✔ repos           2 repos listed
    ✔ index           2 repos, 5 chunks, embedder ollama:bge-m3, oldest index just now
    ✔ links           3 pull requests, 2 with a ticket, refreshed just now
    
    ✔ Everything is in place.

    The dashboard

    safran dashboard serves a local web UI on 127.0.0.1 that shows the same status, and its API can start a sync or a link refresh and stream their progress. Its contract allows one sync or refresh at a time per dashboard server; a second request is refused while one is running. The link it prints carries a session token: anyone who has it can read tickets and source code through that server while it runs. It is a window for a person at the machine, not a scheduler: keep the scheduled jobs above.

    What agents see

    Agents cannot run a sync, so the MCP tools tell them how old their answers are:

    • list_repos returns indexed_at for every repository. Its description tells the agent to say that an answer reflects code from that date when it is old, and that a repository without indexed_at is not searchable yet.
    • get_company_profile returns index with the embedder, the number of repositories and chunks, and oldest_indexed_at. When the index cannot be read, index.error carries the message and the profile is still returned.
    • A code tool that hits INDEX_NOT_READY returns the error with a hint to ask the user to run safran sync, instead of guessing what the code contains.

    A running MCP server sees the commits of a safran sync in another process without a restart. It read the profile when it started, though: restart it after you edit safran.yaml. The tools are described in the MCP reference.

    From the SDK

    refresh.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran({ profile: "/work/acme/safran.yaml" });
    
    const report = await safran.repos.sync({
      onProgress: ({ repo, phase, done, total }) => console.error(`${repo} ${phase} ${done}/${total}`),
    });
    
    for (const result of report.results) {
      if (result.status === "failed") console.error(`${result.repo}: ${result.error?.code} ${result.error?.message}`);
      if (result.status === "skipped") console.error(`${result.repo}: skipped ${result.reason ?? ""}`);
    }
    if (report.removed) console.log(`dropped from the index: ${report.removed.join(", ")}`);
    
    // A cancelled run is a report with `aborted: true`, never a thrown error.
    if (!report.aborted) {
      const links = await safran.links.refresh();
      const unfinished = links.repos.filter((repo) => repo.truncated === true).map((repo) => repo.repo);
      if (unfinished.length > 0) console.log(`history not complete yet: ${unfinished.join(", ")}`);
    }
    
    for (const repo of await safran.repos.list()) {
      console.log(repo.name, repo.indexedAt ?? "not indexed");
    }

    repos.sync and links.refresh throw only before any work has started (an unknown repository name, an index that cannot be opened). Everything after that is in the report. More in repositories and work history.

    Where the data lives

    Everything Safran derives is under the data directory: data/ next to the profile, or the directory given with --data-dir (dataDir in the SDK).

    data/
      repos/<host>/<repo>/      working trees (shallow clones); local hosts are read in place
      repos/<host>/.tmp/        clones in progress
      repos/<host>/.locks/      one lock file per repository
      index/index.db            the code index: files, chunks, full-text table, vectors, embedding cache
      safran.db                 the link store: merged pull requests, their tickets and files
      eval/golden.json          the golden set, once you have built one
      cache/                    per-plugin caches

    Everything under it can be deleted and rebuilt:

    DeleteRebuild withCost
    data/index/safran sync --offlineEvery chunk is embedded again; no network besides the embedder.
    data/repos/safran syncEvery repository is cloned again; unchanged files are not re-embedded.
    data/safran.dbsafran links refreshThe history is read again from the code hosts, 12 months back unless --since says otherwise.
    All of data/safran sync, then safran links refreshThe first setup again.

    The profile and .env are not under data/ and are never rewritten by these commands.

    Common mistakes

    • Scheduling a bare bun run from a project directory. Use bin/safran by absolute path; the reasons are in the security model.
    • Reading skipped as an error. It is not one. Look at the detail: another sync had the repository, or the run was interrupted.
    • Expecting a sync of named repositories to clean up. Only a full safran sync drops repositories that no host lists any more.
    • Changing embeddings and forgetting the sync. Dense search refuses to answer until every repository is re-indexed; safran status shows it in one line.
    • Treating safran links refresh reporting one pull request as "nothing happened". It is the newest stored pull request, listed again to find where to resume.

    Error codes and their fixes are in troubleshooting.