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:
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.
| Package | What it exports |
|---|---|
@safran/kit | The 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/profile | profileSchema, parseProfile, loadProfileFile, stringifyProfile, defineProfile, and pure lookups over a profile (matchGlossary, teamsOwningRepo, reposInGroups, …). |
@safran/trackers | The tracker plugins jira, azureBoards, linear, githubIssues, and builtinTrackers. |
@safran/hosts | The code host plugins azureRepos, github, gitlab, local, and builtinCodeHosts. |
@safran/docsources | The doc source plugin confluence, and builtinDocSources. |
@safran/embedders | The embedder plugins ollama, openaiCompatible, and builtinEmbedders. |
@safran/codeindex | createCodeIndex: the SQLite index with chunking, hybrid search, grep and file reads. |
@safran/core | createSafran, the Safran API types, builtinPlugins, named defaults. It re-exports what most callers need from kit. |
@safran/mcp | createSafranMcpServer, serveSafranStdio, createSafranHttpHandler. |
@safran/discover | discoverProfile and the pure inference steps behind it; renderFindings. |
@safran/eval | buildGoldenSet, runRetrievalEval, runReplayEval, metrics and report rendering. |
@safran/dashboard | createDashboardHandler, serveDashboard: a local HTTP API over one instance, plus a static file server for the dashboard UI. |
@safran/cli | The 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
└──────────┴──────────┴────┬─────┴───────────┴──────────┘
▼
kitThis 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.
| Shell | What 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:
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
capabilitiesentry; callers check the capability and raiseUNSUPPORTEDotherwise. - A plugin is data plus a factory: a
type, a description, a strictconfigSchemafor the whole profile entry, andcreate(config, context).createdoes no network I/O and reads secrets through the context, never fromprocess.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
signaland stop withABORTED; long operations report through anonProgresscallback. close()is idempotent andSafranisAsyncDisposable: 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
localcode host are read in place and never copied underrepos/. <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
-waland-shmfiles next to a database while it is open. - Everything here can be deleted and rebuilt with
safran syncandsafran links refresh. The profile and the.envare the only files that are yours. - Data written by a newer version of Safran is refused with
INCOMPATIBLE_DATAinstead 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_READYuntil 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
autopicks 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
wrapUntrustedwith 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.