Skip to content
safran

Type to search. Enter opens the first result.

    Architecture

    How the repository is put together: which package does what, which way dependencies point, what ends up on disk, and where the CLI, the MCP server and the dashboard fit. Read this before changing Safran or building on a package directly.

    The shape

    One async factory, and everything else is built on what it returns:

    shape.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran({ profile: "/work/acme/safran.yaml" });
    
    const ticket = await safran.tickets.get("PAY-1423");
    const { hits } = await safran.code.search("kısmi iade", { groups: ["backend"] });
    
    console.log(ticket.title, hits.length);

    createSafran loads and validates the profile, registers plugins and builds every connector. It touches no network. The code index and the embedder start on first use, so an instance that only reads tickets never needs them.

    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;
      /** 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;
    
      /**
       * 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

    Packages

    The repository is a Bun workspace. Each package under packages/ has one flat entry point, src/index.ts, and nothing imports another package's internals.

    PackageWhat it exports
    @safran/kitThe contracts (Tracker, CodeHost, DocSource, Embedder, CodeIndex), the domain types, SafranError and its codes, the HTTP client, defineTracker / defineCodeHost / defineDocSource / defineEmbedder, the plugin registry, wrapUntrusted. @safran/kit/testing has fakes of every contract and mockFetch. @safran/kit/markup converts HTML, ADF and wiki markup to Markdown.
    @safran/profileprofileSchema, parseProfile, loadProfileFile, stringifyProfile, defineProfile, and pure lookups over a profile (matchGlossary, teamsOwningRepo, reposInGroups, …).
    @safran/trackersThe tracker plugins jira, azureBoards, linear, githubIssues, and builtinTrackers.
    @safran/hostsThe code host plugins azureRepos, github, gitlab, local, and builtinCodeHosts.
    @safran/docsourcesThe doc source plugin confluence, and builtinDocSources.
    @safran/embeddersThe embedder plugins ollama, openaiCompatible, and builtinEmbedders.
    @safran/codeindexcreateCodeIndex: the SQLite index with chunking, hybrid search, grep and file reads.
    @safran/corecreateSafran, the Safran API types, builtinPlugins, named defaults. It re-exports what most callers need from kit.
    @safran/mcpcreateSafranMcpServer, serveSafranStdio, createSafranHttpHandler.
    @safran/discoverdiscoverProfile and the pure inference steps behind it; renderFindings.
    @safran/evalbuildGoldenSet, runRetrievalEval, runReplayEval, metrics and report rendering.
    @safran/dashboardcreateDashboardHandler, serveDashboard: a local HTTP API over one instance, plus a static file server for the dashboard UI.
    @safran/cliThe safran command.

    Outside packages/: plugin/ is the Claude Code plugin (the four skills and the wiring that starts the MCP server), bin/safran is the launcher, brand/ holds the colour tokens and logo files, and web/ is this site.

    Dependency direction

    Dependencies point downwards only. kit depends on nothing in the workspace; every connector package depends only on kit; core assembles them; the shells sit on core.

    cli ───────────┬───────────┬───────────┬───────────┐
                   ▼           ▼           ▼           ▼
                  mcp       discover      eval     dashboard
                   └───────────┴─────┬─────┴───────────┘
                                     ▼
                                   core
           ┌──────────┬──────────┬───┴──────┬───────────┬──────────┐
           ▼          ▼          ▼          ▼           ▼          ▼
       trackers     hosts    docsources  embedders  codeindex   profile
           └──────────┴──────────┴────┬─────┴───────────┴──────────┘
                                      ▼
                                     kit

    This is why a plugin author needs only @safran/kit (or @safran/core, which re-exports it), and why the connectors can be tested without the index.

    None of the packages is published to a registry. They are used from a checkout of the repository; see Installation.

    Thin shells over one factory

    The CLI, the MCP server and the dashboard hold no logic. Each one builds a Safran instance with createSafran and translates between its own surface and the library.

    ShellWhat it adds
    CLI (@safran/cli)Argument parsing, the .env next to the profile, terminal output and --json, exit codes. Each command opens one instance, calls it and closes it.
    MCP server (@safran/mcp)Tool schemas, output budgets and truncation markers, the untrusted-data wrapper, server instructions. A failing tool returns an error result instead of throwing.
    Dashboard (@safran/dashboard)A loopback HTTP API with a session token, and the static UI. safran dashboard starts it.

    You can write a fourth shell the same way. This is a complete stdio MCP server:

    serve.ts
    import { createSafran } from "@safran/core";
    import { serveSafranStdio } from "@safran/mcp";
    
    const safran = await createSafran({ profile: "/work/acme/safran.yaml" });
    const server = serveSafranStdio(safran);
    
    process.once("SIGTERM", () => {
      void server.close().then(() => safran.close());
    });

    How the shells are started matters for one reason. Bun loads .env and bunfig.toml from its working directory before any code runs, so bin/safran and the plugin both start Bun with the Safran checkout as its working directory and pass on the directory the user is in. Quickstart and Security explain the consequence.

    Contracts

    Two files are the source of truth for the API: the contracts in packages/kit/src/types.ts and the instance API in packages/core/src/api.ts. The rules around them:

    • A connector is a small domain interface. Optional methods are paired with a capabilities entry; callers check the capability and raise UNSUPPORTED otherwise.
    • A plugin is data plus a factory: a type, a description, a strict configSchema for the whole profile entry, and create(config, context). create does no network I/O and reads secrets through the context, never from process.env.
    • Errors are SafranErrors with a stable code. The HTTP client maps vendor status codes so no vendor error crosses a connector raw.
    • Long calls take a signal and stop with ABORTED; long operations report through an onProgress callback.
    • close() is idempotent and Safran is AsyncDisposable: it cancels what is in flight, waits a bounded time, then releases the index and every open handle.

    The API reference renders these declarations from the source: Safran, kit, types.

    Data on disk

    Everything Safran writes is under the data directory: data/ next to the profile unless --data-dir or dataDir says otherwise.

    <dataDir>/
      repos/<host>/<repo>/      working trees of cloned repositories (shallow clones)
      repos/<host>/.tmp/        clones in progress; moved into place when complete
      repos/<host>/.locks/      one lock file per repo, so two syncs never share a working tree
      index/index.db            SQLite: files, chunks, the full-text table, vectors, the embedding cache
      safran.db                 SQLite: work history (merged pull requests, their tickets and files), sync state
      cache/<id>/               a cache directory handed to each connector
      eval/                     golden set and evaluation reports (golden.json by default)
    • Repositories of a local code host are read in place and never copied under repos/.
    • <host> and <repo> are percent-encoded when used as directory names, so two different names never share a directory and no name can leave its parent.
    • SQLite may keep -wal and -shm files next to a database while it is open.
    • Everything here can be deleted and rebuilt with safran sync and safran links refresh. The profile and the .env are the only files that are yours.
    • Data written by a newer version of Safran is refused with INCOMPATIBLE_DATA instead of being read wrongly.

    The code index

    • Storage is Bun's built-in SQLite. The lexical channel is an FTS5 table ranked with BM25. The dense channel is a brute-force dot product over L2-normalised vectors held in memory. There is no vector database and no native extension.
    • Incremental. A file is chunked again only when its content hash changes. An embedding is computed only when the pair of embedder id and chunk text is not in the cache.
    • One embedder per index. Vectors from different embedders are never mixed; a repository indexed with another embedder is refused with INDEX_NOT_READY until it is indexed again.
    • Chunking uses per-language boundary patterns packed to a size budget, with overlapping line windows for oversized blocks and unknown languages. There is no parser dependency, and a file that cannot be chunked structurally is chunked by lines: chunking never fails a run.
    • Search mode auto picks the channel weights from the shape of the query (identifier-like queries lean lexical, prose leans dense). Every hit reports both scores.

    The agent-facing surface

    • Tools are registered with an input schema and an output schema, are marked read-only, and return both compact text for the model and structured content.
    • Tool names are tracker-neutral: get_ticket, never a vendor's name.
    • Third-party text is wrapped by wrapUntrusted with a tag whose random suffix is new for every tool result; metadata shown outside a wrapper is one line with format characters removed.
    • Outputs are bounded and nothing is cut silently.

    See MCP reference.

    Testing

    Tests run with bun test and live in packages/<name>/test/. No test reaches the network: connectors are tested with mockFetch against fixtures shaped like the vendors' responses, and everything above them with the fakes from @safran/kit/testing, which are real implementations of the contracts. Retrieval quality is not a unit test; it is measured by evaluation.

    See Testing and Design principles.