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;
/**
* When this instance was created, by its own clock: read before the profile file is, so a
* profile edited later than this is one the instance may not have. What "since the server
* started" means for anything serving it.
*/
readonly startedAt: Date;
/**
* The instance's clock (`SafranOptions.clock`; the system clock by default), for callers that
* must agree with it on what "now" is: token expiry, index staleness, relative ages.
*/
readonly clock: () => Date;
/** 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;
/** Live pull requests (wave 2). */
readonly pulls: PullsApi;
/** The guarded write framework (wave 2). Present on every instance; disabled unless the profile and `allowWrites` say otherwise. */
readonly writes: WritesApi;
/** Namespaced JSON records in `<dataDir>/safran.db`, for plugins and for Safran's own small state. Opened on first use. */
readonly store: StoreService;
readonly toolPacks: ToolPacksApi;
/** Boards with their columns and tickets (`work-api.ts`). */
readonly boards: BoardsApi;
/** Iterations: listings, tickets and the digest of one. */
readonly iterations: IterationsApi;
/** The ticket table, the home view, teams, epics, stand-up, and the cache they read through. */
readonly work: WorkApi;
/** Who "my work" means on this instance, and on what basis. */
readonly me: MeApi;
/**
* 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 / defineToolPack / defineAgentTool, the plugin registry, wrapUntrusted, the shapes of live pull requests and of the write model. @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 (tickets, code, docs, repos, links, company, pulls, writes, store, tool packs), 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/harness | createHarness: a queue of jobs for an unattended coding agent, the check layers (runGates, auditDiff, evidenceCheck, reviewBlocks), humanQueue, pullRequestDraft, detectProject, and the AgentDriver seam. See the job harness. |
@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 sixteen 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,
the write audit log, the plugin store
cache/<id>/ a cache directory handed to each connector
eval/ golden set and evaluation reports (golden.json by default)
harness/ the job harness: its queue (harness.db), worktrees, evidence and session logs- 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, exceptharness/: it holds the job queue and the record of every job, and is not a cache. Apart from it, the profile and the.envare the only files that are yours. - The job harness also works in the repository of each of its projects: it adds worktrees and local branches there, and commits on those branches. It never pushes them.
- 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.
Writes
Safran changes something outside the machine through one guarded path only.
- Off by default, and opt-in per kind:
writes.enabledpluswrites.allowin the profile. The four kinds are a ticket comment, a child ticket, a pull request comment and a reply in a review thread. There is no kind for anything else. - A hard switch above the profile.
allowWrites: falsemakes an instance read-only whatever the profile says. The CLI passes it for a profile it merely found in the current directory, and forsafran mcp --no-writes. - Preview, then commit.
safran.writes.previewresolves the target and renders exactly what would be sent, with a single-use token valid for ten minutes;safran.writes.commitsends that and nothing else, once, without a retry. - Audited. Every preview, commit and failure is a row in
safran.db. If the row cannot be stored, nothing is sent. - Never a side effect. Only
safran.writescalls a connector's write method. No read API, no read tool, no sync and no tool pack does.
See Writes.
Tool packs and the store
A tool-pack plugin builds a named set of agent tools, selected by a tool_packs: entry in the
profile. Each tool call receives read-only access to tickets, code, pull requests and the
company profile, the pack's own namespace of a small key-value store kept in safran.db, a
logger, the call's signal and the untrusted-data wrapper of that result. It receives no
connector, no write API and no way to close the instance.
See Tool packs.
The agent-facing surface
- Tools are registered with an input schema and an output schema and return both compact text for the model and structured content. The 29 tools of a default server are marked read-only. The only ones that are not are the two write tools, registered when the profile enables writes, and tool-pack tools that say so.
- A failing tool returns
isError: truewith the message, the hint and the code as a last line ([code: NOT_FOUND]). It does not throw. - 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.