Skip to content
safran

Type to search. Enter opens the first result.

    Searching and reading code

    safran.code answers four questions about the repositories Safran has indexed: where is code like this (search), where is exactly this (grep), what does this file say (readFile) and what is indexed (status). All four read the local index; none of them contacts a code host. This page explains each call, its limits and what the results mean.

    The index is filled by repos.sync() or safran sync. Until then search and grep return nothing and readFile throws NOT_FOUND.

    search-code.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const result = await safran.code.search("kısmi iade tutarı nasıl yuvarlanıyor", {
      groups: ["backend"],
      languages: ["typescript"],
      limit: 3,
      snippetLines: 6,
    });
    
    console.log(`query sent to the index: ${result.effectiveQuery}`);
    console.log(`glossary: ${result.glossary.map((entry) => `${entry.term} → ${entry.code.join(", ")}`).join("; ")}`);
    
    for (const hit of result.hits) {
      console.log(`\n${hit.repo}/${hit.path}:${hit.startLine}-${hit.endLine}  score ${hit.score}  dense ${hit.channels.dense}  lexical ${hit.channels.lexical}`);
      if (hit.symbol !== undefined) console.log(`symbols: ${hit.symbol}`);
      if (hit.chunk !== undefined) console.log(`window of a chunk spanning lines ${hit.chunk.startLine}-${hit.chunk.endLine}`);
      console.log(hit.snippet);
    }
    $ bun search-code.ts
    query sent to the index: kısmi iade tutarı nasıl yuvarlanıyor refund chargeback
    glossary: İade → refund, chargeback
    
    payments-api/src/refund/policy.ts:1-6  score 0.5417  dense 0.6019  lexical 0
    symbols: RefundPolicy
    window of a chunk spanning lines 1-11
    /** Rules a refund must satisfy before it is sent to the provider. */
    export class RefundPolicy {
      /** Amounts are rounded to two decimals before they are compared. */
      roundRefundAmount(amount: number): number {
        return Math.round(amount * 100) / 100;
      }
    
    ledger/src/entry.ts:3-8  score 0.5165  dense 0.521  lexical 0.4758
    symbols: refundEntry, LedgerEntry
    window of a chunk spanning lines 1-9
      amount: number;
      reason: "payment" | "refund" | "chargeback";
    }
    
    export function refundEntry(account: string, amount: number): LedgerEntry {
      return { account, amount: -amount, reason: "refund" };
    
    payments-api/src/refund/service.ts:8-13  score 0.5059  dense 0.5621  lexical 0
    symbols: RefundService, RefundRequest
    window of a chunk spanning lines 1-19
    /** Issues full and partial refunds through the payment provider. */
    export class RefundService {
      constructor(private readonly policy: RefundPolicy) {}
    
      async createPartialRefund(request: RefundRequest, orderTotal: number): Promise<number> {
        const amount = this.policy.roundRefundAmount(request.amount);

    This output is from an index of four small files, embedded with a local bge-m3 model. A Turkish question found English code, and the file that rounds refund amounts came first. On a corpus this small a word that occurs in most chunks (refund) carries almost no lexical weight, which is why two hits show lexical 0.

    Glossary expansion

    Tickets say iade, code says refund. Before the query reaches the index, Safran looks for the profile's glossary terms in it and appends their code-side words:

    • A term matches as a whole word or as the start of one, so inflected forms count: iadeler, iadenin. Case is folded the same way on every machine, including the Turkish İ/ı.
    • A code word that is already in the query is not added twice.
    • effectiveQuery is what was actually searched; glossary lists the entries that fired, so you can show why a result appeared.
    • expandGlossary: false sends the query untouched.

    Expansion applies to search only. grep matches the pattern as written.

    Search modes

    A search has two channels. The dense channel compares the query's embedding with the embedding of every chunk (meaning). The lexical channel is BM25 over the chunk text, the symbol names and the path (words). The final score is a weighted blend of the two, and mode chooses the weight of the dense channel:

    modeDense weightWhen to use it
    auto (default)0.35 for an identifier-shaped query, 0.9 for proseAlmost always.
    hybrid0.5An explicit even blend.
    dense1Meaning only; the lexical channel is not run.
    lexical0Words only. The embedder is not called, so it works when the embedding server is down or the index holds another model's vectors.

    auto decides by the shape of the query. A query is identifier-shaped when it has at most two whitespace-separated tokens and one of them looks like a symbol: a camelCase hump (roundRefund), a capitalised start (RefundPolicy), an underscore or a dot. Everything else is prose. For an identifier-shaped query the lexical channel also matches prefixes, so RefundPol finds RefundPolicy.

    One consequence to know: a one- or two-word query that starts with a capital letter (Sepete Ekle) is treated as an identifier. That is usually right for labels copied from a screen, which the lexical channel finds verbatim.

    Reading a hit

    FieldMeaning
    repoRepository name, as in repos.list().
    pathRepo-relative path with forward slashes.
    startLineFirst line of snippet (1-based).
    endLineLast line of snippet.
    chunkLine range of the whole chunk. Present only when snippet is a window of it; read the rest with readFile.
    languageLanguage by file extension: typescript, csharp, kotlin, …
    kindStructural role guessed from the file name and directories: test, controller, api-service, repository, dto, screen, … Present on every hit of the built-in index.
    symbolUp to four names defined in the snippet or its chunk, comma-separated.
    scoreThe blended score, higher is better. Only comparable inside one result list.
    channelsThe per-channel scores: dense is a cosine similarity, lexical is BM25 scaled to 0..1. A channel that was not run or did not find the chunk is absent.
    snippetThe lines startLine..endLine.
    alsoInOther files with the identical chunk (forks, copied modules), collapsed into this hit. At most 20 are listed.

    A hit is a chunk, not a file: the indexer cuts files at declaration boundaries. To keep answers small, snippet is the window of the chunk that best matches the query (40 lines by default). snippetLines changes the window for one call; 0 returns whole chunks and values above 400 are clamped.

    channels tells you how a hit was found. A high lexical score with a low dense one is an exact word match in unrelated code; the reverse is related code that uses other words.

    Search options

    OptionDefaultMeaning
    limit10Hits to return. Above 50 it is clamped.
    modeautoSee search modes. An unknown value is INVALID_INPUT.
    snippetLines40Window size per hit; 0 for whole chunks; at most 400.
    expandGlossarytrueAppend glossary code words to the query.
    reposallOnly these repositories.
    groupsallOnly repositories in these profile groups.
    languagesallLanguage names. A name selects its family: typescript also matches typescript-react.
    kindsallStructural roles, as in CodeHit.kind.
    pathPrefixnoneRepo-relative path prefix, such as src/refund/.
    signalnoneCancels the search.

    An empty query is INVALID_INPUT. A query longer than 4000 characters is cut there.

    export interface SafranCodeSearchOptions extends CodeSearchOptions {
      /**
       * Add the code-side words of glossary terms found in the query before searching.
       * Default: true.
       */
      expandGlossary?: boolean;
    }
    
    export interface CodeSearchOptions extends CodeFilter, CallOptions {
      limit?: number;
      mode?: SearchMode;
      /** Lines of each hit's snippet window for this call, overriding the index default. 0 returns whole chunks. */
      snippetLines?: number;
    }
    
    export interface CodeFilter {
      repos?: string[];
      /** Repo groups from the profile. */
      groups?: string[];
      languages?: string[];
      kinds?: string[];
      /** Repo-relative path prefix. */
      pathPrefix?: string;
    }
    
    export interface CodeSearchResult {
      hits: CodeHit[];
      /** The query actually sent to the index, after glossary expansion. */
      effectiveQuery: string;
      /** Glossary entries that fired, so the caller can show why. */
      glossary: GlossaryEntry[];
    }

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

    Scope: repos and groups

    repos, groups, languages, kinds and pathPrefix narrow search and grep alike. Two of them interact:

    • Several groups widen the scope. groups: ["backend", "mobile"] is the union of both groups' repos.
    • repos together with groups narrows it. The result is the repos that are in the list and in one of the groups.
    • An unknown group is INVALID_INPUT, with the known groups in the hint and in details.known. A typo should not look like "no results".
    • A scope that can match nothing returns nothing. groups: ["backend"], repos: ["acme-ios"] gives no hits without asking the index. An unknown name in repos simply matches nothing; repos.get(name) is the call that tells you a repository does not exist.

    Group membership comes from the profile at query time, so editing code.groups takes effect without re-indexing.

    scope.ts
    import { createSafran, isSafranError } from "@safran/core";
    
    await using safran = await createSafran();
    
    // Union of two groups, then only the repos that are also named.
    const { hits } = await safran.code.search("refund policy", { groups: ["backend", "frontend"], repos: ["payments-api", "web-app"] });
    console.log(hits.map((hit) => hit.repo));
    
    try {
      await safran.code.search("refund policy", { groups: ["backnd"] });
    } catch (error) {
      if (!isSafranError(error, "INVALID_INPUT")) throw error;
      console.log(error.format());
    }
    $ bun scope.ts
    [ "payments-api", "payments-api", "payments-api" ]
    Unknown repo group: backnd
    → Known groups: backend, mobile, frontend.

    Grep

    Similarity search answers "where is something like this". Impact analysis needs every occurrence, with an exact count. grep scans the stored text of every searchable file line by line, including files the vector index leaves out (build output, vendored code, large files).

    grep-code.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const result = await safran.code.grep("roundRefundAmount", { repos: ["payments-api"], pathGlob: "*.ts", wholeWord: true, context: 1 });
    
    console.log(`${result.matches.length} of ${result.total} matches${result.truncated ? " (truncated)" : ""}`);
    for (const match of result.matches) {
      for (const line of match.before ?? []) console.log(`    ${line}`);
      console.log(`${match.repo}/${match.path}:${match.line}: ${match.text}`);
      for (const line of match.after ?? []) console.log(`    ${line}`);
    }
    if (result.incomplete !== undefined) console.warn(`not searched completely: ${result.incomplete.join(", ")}`);
    $ bun grep-code.ts
    2 of 2 matches
          /** Amounts are rounded to two decimals before they are compared. */
    payments-api/src/refund/policy.ts:4:   roundRefundAmount(amount: number): number {
            return Math.round(amount * 100) / 100;
          async createPartialRefund(request: RefundRequest, orderTotal: number): Promise<number> {
    payments-api/src/refund/service.ts:13:     const amount = this.policy.roundRefundAmount(request.amount);
            if (!this.policy.allowsPartialRefund(amount, orderTotal)) {

    Grep options

    OptionDefaultMeaning
    regexfalseTreat the pattern as a JavaScript regular expression. Otherwise it is matched literally.
    caseSensitivesmart caseUnset: case-sensitive exactly when the pattern contains an upper-case letter. In a regular expression, the letters of escapes such as \W do not count.
    wholeWordfalseOnly matches with no letter, digit or underscore directly before or after.
    pathGlobnoneGlob on the repo-relative path: * stays inside a directory, ** crosses them. A pattern without / matches the file name at any depth (*.ts).
    context0Lines before and after each match. Above 5 it is clamped.
    limit50Matches to return. Above 200 it is clamped. total still counts all of them.
    repos, groups, languages, kinds, pathPrefixallThe same scope as search.
    signalnoneCancels the scan.

    The pattern must be 2 to 1000 characters on one line; matching is per line. An invalid regular expression is INVALID_INPUT. Case-insensitive matching folds the Turkish İ/ı/I onto i, so sipariş finds SİPARİŞ.

    total, truncated, incomplete

    FieldMeaning
    matchesUp to limit matches, ordered by repository name, then path, then line.
    totalEvery matching line in the scope, whatever limit is.
    truncatedtrue when total is larger than matches.length.
    incompleteRepositories that were not searched to the end. Absent when the scan was complete.

    One grep call has a wall-clock budget of 20 seconds. When it runs out, the repository being scanned and every later one are listed in incomplete; the counts are exact for every repository that is not listed. Treat a result with incomplete as a lower bound, and narrow the scope (repos, pathGlob) to get an exact answer. Regular expressions run in a separate process that is killed at the budget, so an expression that backtracks badly cannot stall other calls.

    export interface GrepOptions extends CodeFilter, CallOptions {
      regex?: boolean;
      caseSensitive?: boolean;
      /** Only matches that are not directly preceded or followed by a letter, digit or underscore. */
      wholeWord?: boolean;
      /**
       * Glob on the repo-relative path (`*` stays inside a directory, `**` crosses them).
       * A pattern without `/` matches the file name in any directory: `*.ts`.
       */
      pathGlob?: string;
      /** Lines of context around each match. */
      context?: number;
      limit?: number;
    }
    
    export interface GrepMatch {
      repo: string;
      path: string;
      line: number;
      text: string;
      before?: string[];
      after?: string[];
    }
    
    export interface GrepResult {
      matches: GrepMatch[];
      /** Matches found in total, which may exceed `matches.length` when the limit cut the list. */
      total: number;
      truncated: boolean;
      /** Repos that could not be searched completely (time budget, unreadable files). Never silent. */
      incomplete?: string[];
    }

    defined in packages/kit/src/types.ts

    Read a file

    read-file.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const slice = await safran.code.readFile("payments-api", "src/refund/policy.ts", { startLine: 3, endLine: 6 });
    console.log(`${slice.path} lines ${slice.startLine}-${slice.endLine} of ${slice.totalLines}${slice.truncated ? " (truncated)" : ""}`);
    console.log(slice.content);
    $ bun read-file.ts
    src/refund/policy.ts lines 3-6 of 11
      /** Amounts are rounded to two decimals before they are compared. */
      roundRefundAmount(amount: number): number {
        return Math.round(amount * 100) / 100;
      }

    readFile(repo, path, range?, options?) reads from the working tree on disk, not from the index, so it returns the file as it is now and also serves files the index skipped.

    • Ranges. Lines are 1-based and inclusive. Without endLine you get 200 lines from startLine. With one you get at most 400 lines per call. truncated is true when a cap cut the range you asked for; totalLines tells you how much is left, so continue from endLine + 1.
    • Paths are repo-relative. Absolute paths, .. segments and anything in .git are refused with INVALID_INPUT, and so is a symbolic link that leads outside the repository.
    • Credentials files are never served. A path that looks like one (.env, key files, cloud credential files) or a file that holds a private key is INVALID_INPUT, with a hint to ask the user for the specific setting instead.
    • Binary files and files larger than 5 MB are INVALID_INPUT.
    • An unknown repository or a missing file is NOT_FOUND. startLine past the end of the file is INVALID_INPUT, with the valid range in the hint.
    FieldMeaning
    repoRepository name.
    pathThe normalised repo-relative path.
    startLineFirst line returned.
    endLineLast line returned. 0 for an empty file.
    totalLinesLines in the whole file.
    contentThe lines, joined with \n.
    truncatedWhether a cap shortened the range that was asked for.

    Index status

    code-status.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const status = await safran.code.status();
    console.log(`embedder ${status.embedder}, ${status.chunks} chunks`);
    for (const repo of status.repos) {
      console.log(`${repo.name}  group ${repo.group ?? "-"}  ${repo.files} files  ${repo.chunks} chunks  indexed ${repo.indexedAt ?? "never"}${repo.stale ? "  STALE" : ""}`);
    }
    $ bun code-status.ts
    embedder ollama:bge-m3, 4 chunks
    ledger  group backend  1 files  1 chunks  indexed 2026-11-23T11:28:54.355Z
    payments-api  group backend  3 files  3 chunks  indexed 2026-11-23T11:28:54.345Z

    status.embedder is the embedder the instance is configured with. A repository row carries the embedder its vectors were made with, and stale: true when that is a different one: such a repository must be synced again before dense search works.

    export interface IndexStatus {
      /** Id of the embedder the index is opened with (the current one), whatever the stored vectors came from. */
      embedder: string;
      repos: IndexedRepoStatus[];
      chunks: number;
    }
    
    export interface IndexedRepoStatus {
      name: string;
      group?: string;
      files: number;
      chunks: number;
      indexedAt?: string;
      /** Id of the embedder this repo's vectors were made with. */
      embedder?: string;
      /** True when the repo holds vectors from an embedder other than the current one and must be indexed again. */
      stale?: boolean;
    }

    defined in packages/kit/src/types.ts

    What is in the index

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

    OutcomeFiles
    Indexed: chunked, embedded and grep-ableSource files of a known language, up to 400 kB.
    Grep only: text stored, no vectorsFiles in build or vendor directories (dist, build, vendor, generated, …), files of no known language, generated sources, minified files, most .json and .xml files, files between 400 kB and 1 MB.
    Skipped entirelyDependency and tool directories (node_modules, .git, .venv, .gradle, …), binary files, lock files and bundles, empty files, files over 1 MB, and files that hold credentials.

    In a git working tree the file list comes from git, so .gitignore is honoured; untracked files that are not ignored are included. Each sync reports how many files were skipped and why in index.filesSkipped.

    Without an index

    An instance created with index: false has no code search. Every safran.code.* call throws UNSUPPORTED ("Code search is disabled for this Safran instance"), and so does a repos.sync() that would index. Everything else works. See ticket-only use.

    INDEX_NOT_READY

    The index exists but cannot answer this call:

    Message saysCauseWhat to do
    "holds vectors from … but the configured embedder is …"The embeddings entry changed after repositories were indexed. Vectors of different models cannot be compared.Run safran sync (or repos.sync()) to re-index, or configure the earlier embedder again. Until then mode: "lexical", grep and readFile work.
    "holds N-dimensional vectors but the embedder returned M"The model behind the same embedder id changed.Delete <dataDir>/index and sync again.
    "is locked by another Safran process"Another process held the index file exclusively while it was being opened.Wait for the other command and retry.
    "The code index is closed"The index was closed while the call was running, or before it started.Create a new instance.

    A related code is INCOMPATIBLE_DATA: the index file was written by a newer Safran, or is not a database at all. The hint says to update, or to delete the index directory and sync again; nothing in the index is irreplaceable.

    When the embedding server itself is unreachable, a dense search fails with the embedder's error (usually UPSTREAM), not with INDEX_NOT_READY. Opening the index never calls the embedder, so grep, readFile, status and mode: "lexical" keep working.

    Common mistakes

    SymptomCause
    No hits for a query that should matchNothing is indexed yet (code.status() shows no repos), or the scope excludes the repository.
    INVALID_INPUT: Unknown repo groupThe group is not under code.groups in the profile.
    A hit's snippet stops in the middle of a functionIt is a window. hit.chunk has the full range; pass it to readFile, or search with snippetLines: 0.
    grep reports fewer matches than expectedCheck truncated (raise limit or read total) and incomplete (narrow the scope).
    Comparing scores of two different searchesScores are only comparable inside one result list.