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
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.239Zlist() 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. Async()of everything refreshes it too. - Disk state is read fresh on every call:
cloned,headandindexedAtreflect 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
indexedAtopens 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.
| Field | From the code host |
|---|---|
name | Short name, the key used everywhere in Safran: in code.search scopes, in code.groups, in team repos. |
fullName | Host-qualified name, such as acme/Platform/payments-api. |
defaultBranch | The branch Safran clones and indexes. |
cloneUrl | HTTPS clone URL without credentials. For a local host, an absolute directory path. |
webUrl | Link for people, when the host has one. |
archived | Whether the host marks it archived. |
sizeKb | Size as the host reports it. |
primaryLanguage | Main language as the host reports it. |
| Field | Added by Safran |
|---|---|
host | Id of the code host entry in the profile. |
groups | Groups from code.groups that contain this repo. |
teams | Names of the teams whose repos contain it. |
dir | Absolute path of the working tree. For a local host this is the source directory itself. |
cloned | Whether the working tree exists on disk. |
head | Commit the working tree is at, when cloned. |
indexedAt | ISO 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.
code | Meaning |
|---|---|
a failure code (AUTH_FAILED, UPSTREAM, …) | The code host named in source could not list its repositories. |
UPSTREAM | A host listed the same repository name twice. The first one is kept. |
INVALID_INPUT | The 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:
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.
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 msThe 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
| Option | Default | Meaning |
|---|---|---|
repos | every repo the hosts list | Repo names to sync. An unknown name throws NOT_FOUND before anything is done; all unknown names are reported at once. |
offline | false | Skip the git fetch and index what is on disk. A repo that was never cloned is skipped. |
fetchOnly | false | Update the working trees and do not index. Works with index: false. |
onProgress | none | Called 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.
phase | Emitted | done / total |
|---|---|---|
fetch | Before and after the clone or fetch of a repo. Not emitted for local hosts or with offline. | 0/1, then 1/1 |
scan | Before and after the working tree is listed. | 0/0, then files found |
chunk | While files are read, compared and cut into chunks. | files examined / files found |
embed | Before each embedder call. Not emitted when every vector is already cached. | changed files written / changed files found so far |
write | After 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
| Field | Meaning |
|---|---|
results | One row per selected repo, in order. |
durationMs | Wall-clock time of the run. |
removed | Repos 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. |
aborted | true when the run was cancelled. Absent otherwise. |
| Field | Meaning |
|---|---|
repo | Repo name. |
status | ok, failed or skipped. |
updated | Whether the working tree moved to a new commit. Absent when no fetch ran. |
head | Commit the working tree is at afterwards. |
index | What the indexer did, an IndexRepoResult. Absent with fetchOnly. |
error | Present when status is failed: a BatchError with code, message and hint. |
reason | Present 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 field | Meaning |
|---|---|
repo | Repo name. |
filesIndexed | Files whose content changed and were stored again. |
filesUnchanged | Files whose content hash matched; not touched. |
filesRemoved | Files that left the working tree and were dropped from the index. |
chunksWritten | Chunks written for the changed files. |
embeddingsComputed | Vectors the embedder was asked for. |
embeddingsCached | Vectors taken from the cache instead. |
durationMs | Time spent indexing this repo. |
filesSkipped | Files 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:
| Thrown | When |
|---|---|
NOT_FOUND | A name in repos is not a known repository. |
| the listing error | No code host could list its repositories. |
UNSUPPORTED | Indexing was asked for and the instance has index: false. Pass fetchOnly: true. |
| the index's error | The 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 row | Typical causes |
|---|---|
AUTH_FAILED | The 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_FOUND | The repository or its branch does not exist on the remote; or the directory of a local repo is gone. |
UPSTREAM | Network failure, a git timeout (ten minutes per clone or fetch), an empty remote, an embedder that could not be reached. |
INTERNAL | git 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,
synccalls run one after the other. A second call waits for the first; if its signal fires while it waits, it returnsaborted: truewithout 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
skippedwith areasonnaming 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 progressCharacters 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
| Symptom | Cause |
|---|---|
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 reason | Another process is syncing those repos. Run again afterwards. |
Wrapping sync in try/catch to detect failures | Failures of single repos are rows, not exceptions. Check results for failed and aborted. |
UNSUPPORTED from sync on a tickets-only instance | Indexing needs an index. Use fetchOnly: true, or do not pass index: false. |
| Code search still finds a deleted repository | Only a sync of everything removes it (removed). A sync with repos never does. |