Domain types
These are the tracker-neutral and host-neutral shapes of Safran: what a connector returns, what the SDK hands you, and what the MCP tools are built from. A Ticket looks the same whether it came from Jira or from Azure Boards; a CodeHit looks the same for every embedder. All of them are declared in @safran/kit (packages/kit/src/types.ts), and most are re-exported by @safran/core, so application code can import them from there. The interfaces that use these shapes (Tracker, CodeHost, DocSource, Embedder, CodeIndex) are on @safran/kit; the options and results of the Safran instance itself are on createSafran and the Safran instance.
Conventions that hold for every type on this page:
- Dates are ISO 8601 strings. Connectors normalise them to UTC.
- Rich text (
description,body,content) is Markdown. Connectors convert vendor formats before returning. - An optional field is absent when unknown. It is never
nulland never an empty placeholder. - Text fields hold third-party content. Wrap it before showing it to an agent (see untrusted text).
Example
The types in use: a function that renders a ticket with the code found for it. It runs over the fakes, so it needs no network.
import { createSafran } from "@safran/core";
import type { CodeHit, Logger, Page, Ticket, TicketSummary } from "@safran/core";
import { FakeCodeIndex, fakePlugins, FakeTracker } from "@safran/kit/testing";
function headline(ticket: Ticket): string {
const state = ticket.statusCategory === "done" ? "closed" : "open";
const owner = ticket.assignee?.name ?? "unassigned";
return `${ticket.key} [${ticket.type ?? "?"}, ${state}, ${owner}] ${ticket.title}`;
}
function location(hit: CodeHit): string {
const how = hit.channels.dense !== undefined && hit.channels.lexical !== undefined ? "both" : hit.channels.dense !== undefined ? "meaning" : "words";
return `${hit.repo}/${hit.path}:${hit.startLine}-${hit.endLine} (${how})`;
}
async function drain(next: (cursor?: string) => Promise<Page<TicketSummary>>): Promise<TicketSummary[]> {
const all: TicketSummary[] = [];
let cursor: string | undefined;
do {
const page = await next(cursor);
all.push(...page.items);
cursor = page.nextCursor;
} while (cursor !== undefined);
return all;
}
const logger: Logger = {
debug() {},
info: (message, fields) => console.error(message, fields ?? ""),
warn: (message, fields) => console.error(`warning: ${message}`, fields ?? ""),
error: (message, fields) => console.error(`error: ${message}`, fields ?? ""),
};
const tracker = new FakeTracker({
id: "jira",
tickets: [
{ key: "PAY-1423", title: "Kısmi iade işlemi İstanbul şubesinde başarısız oluyor", type: "Bug", statusCategory: "done" },
{ key: "PAY-1500", title: "Refund webhook retries are not idempotent", type: "Bug", statusCategory: "todo" },
],
});
const index = new FakeCodeIndex({ files: { "payments-api": { "src/refund/service.ts": "export function partialRefund() {}\n" } } });
await using safran = await createSafran({
profile: { version: 1, company: "acme", trackers: [{ id: "jira", type: "fake", projects: ["PAY"] }], embeddings: { type: "fake" } },
builtinPlugins: false,
plugins: fakePlugins({ trackers: [tracker] }),
index,
logger,
dataDir: "/work/acme/test-data",
});
console.log(headline(await safran.tickets.get("PAY-1423")));
for (const hit of await index.search("partialRefund")) console.log(location(hit));
const summaries = await drain((cursor) => tracker.searchTickets({ projects: ["PAY"] }, { limit: 1, ...(cursor !== undefined ? { cursor } : {}) }));
console.log(summaries.map((summary) => summary.key));Calls, pages and logging
CallOptions, Page and PageOptions
/** Options accepted by every async call that may hit the network or the disk. */
export interface CallOptions {
signal?: AbortSignal;
}
/** Cursor pagination. `nextCursor` is opaque; pass it back unchanged. */
export interface Page<T> {
items: T[];
nextCursor?: string;
}
export interface PageOptions extends CallOptions {
limit?: number;
cursor?: string;
}defined in packages/kit/src/types.ts
| Type | Field | Notes |
|---|---|---|
CallOptions | signal | Cancels the call. A cancelled call rejects with SafranError code ABORTED. Every call that may touch the network or the disk accepts it as part of its last argument. |
Page<T> | items | The items of this page, possibly fewer than the limit. |
Page<T> | nextCursor | Present when there is more. Opaque: pass it back unchanged, with the same query and options. Absent on the last page. |
PageOptions | limit | A whole number of at least 1. Left out, the callee's default applies; above the callee's maximum it is clamped; 0, a fraction or a negative number is INVALID_INPUT. |
PageOptions | cursor | The nextCursor of the previous page. A cursor that is not valid is INVALID_INPUT. |
PageOptions extends CallOptions. The guide is Pagination and logging.
Logger
export interface Logger {
debug(message: string, fields?: Record<string, unknown>): void;
info(message: string, fields?: Record<string, unknown>): void;
warn(message: string, fields?: Record<string, unknown>): void;
error(message: string, fields?: Record<string, unknown>): void;
}defined in packages/kit/src/types.ts
| Method | Used for |
|---|---|
debug(message, fields?) | Detail that helps when something is slow or odd: HTTP retries, cache decisions. |
info(message, fields?) | Progress worth a line. |
warn(message, fields?) | Something was left out or degraded, and the call still succeeded. |
error(message, fields?) | A failure that is not thrown to the caller. |
fields is structured context; pass the logger as logger to createSafran. Safran never puts a token into a log line. silentLogger (exported by @safran/kit and @safran/core) discards everything.
Tickets
Person
export interface Person {
id?: string;
name: string;
email?: string;
}defined in packages/kit/src/types.ts
Only name is always present. email is filled only when the tracker exposes it to the token in use.
StatusCategory
export type StatusCategory = "todo" | "in_progress" | "done";defined in packages/kit/src/types.ts
The neutral form of a workflow state. Every tracker has its own status names (status on a ticket keeps the tracker's wording); statusCategory maps them onto three values so that "is this done?" has one answer across trackers.
TicketSummary
The short form of a ticket, as it appears in search results, in links and as a parent.
/** Short reference to a ticket, as it appears in links, parents and search results. */
export interface TicketSummary {
key: string;
title: string;
url?: string;
type?: string;
status?: string;
statusCategory?: StatusCategory;
}defined in packages/kit/src/types.ts
| Field | Type | Notes |
|---|---|---|
key | string | The canonical key, for example PAY-1423. |
title | string | |
url | string, optional | Web link for humans. |
type | string, optional | Ticket type in the tracker's wording: Bug, Story, … |
status | string, optional | Status in the tracker's wording. |
statusCategory | StatusCategory, optional | The neutral status. |
Ticket
A full ticket. It extends TicketSummary, so it also has key, title, type, status and statusCategory; url becomes required.
export interface Ticket extends TicketSummary {
/** Id of the tracker entry in the profile this ticket came from. */
tracker: string;
url: string;
/** Project / team / repository key the ticket belongs to. */
project: string;
/** Markdown. Rich formats (ADF, HTML) are converted by the tracker plugin. */
description: string;
priority?: string;
labels: string[];
assignee?: Person;
reporter?: Person;
parent?: TicketSummary;
createdAt?: string;
updatedAt?: string;
resolvedAt?: string;
/**
* Tracker-specific extras that have no neutral home (story points, sprint, custom fields).
* Keys are human-readable field names; values are JSON-serialisable.
*/
fields: Record<string, unknown>;
}defined in packages/kit/src/types.ts
| Field | Type | Notes |
|---|---|---|
tracker | string | The id of the tracker entry in the profile the ticket came from. |
url | string | Required on a full ticket. |
project | string | The project, team or repository key the ticket belongs to (PAY). |
description | string | Markdown. An empty string when the ticket has none. |
priority | string, optional | The tracker's wording. |
labels | string[] | Empty when there are none. |
assignee | Person, optional | |
reporter | Person, optional | |
parent | TicketSummary, optional | The epic or parent item. |
createdAt | string, optional | ISO date. |
updatedAt | string, optional | ISO date. |
resolvedAt | string, optional | ISO date. |
fields | Record<string, unknown> | Tracker-specific extras with no neutral home: story points, sprint, custom fields. Keys are human-readable field names, values are JSON-serialisable. Do not build logic on a key here unless you know the tracker; it is what differs between them. |
Comments, attachments, links and history are not part of a Ticket. They are separate calls, each behind a capability.
Comment
export interface Comment {
id: string;
author?: Person;
/** Markdown. */
body: string;
createdAt?: string;
updatedAt?: string;
}defined in packages/kit/src/types.ts
body is Markdown. id is unique within the ticket.
Attachment and AttachmentContent
export interface Attachment {
id: string;
filename: string;
mimeType?: string;
sizeBytes?: number;
createdAt?: string;
author?: Person;
}
export interface AttachmentContent extends Attachment {
data: Uint8Array;
}defined in packages/kit/src/types.ts
Attachment is metadata only: listing attachments downloads nothing. AttachmentContent adds data, the bytes, and is what fetching one attachment returns. mimeType and sizeBytes are what the tracker reports, when it reports them; they are not verified against the bytes.
TicketLink
export interface TicketLink {
/** `ticket` points at another ticket; `web` is a remote link (wiki page, design file, PR). */
kind: "ticket" | "web";
/** Relation as the tracker words it: "blocks", "is blocked by", "child", "relates to", … */
relation: string;
ticket?: TicketSummary;
url?: string;
title?: string;
}defined in packages/kit/src/types.ts
| Field | Type | Notes |
|---|---|---|
kind | "ticket" | "web" | ticket points at another ticket; web is a remote link: a wiki page, a design file, a pull request. |
relation | string | As the tracker words it: blocks, is blocked by, child, relates to, … Not normalised. |
ticket | TicketSummary, optional | The other ticket, for kind: "ticket". |
url | string, optional | The target, for kind: "web". A URL that a doc source recognises can be fetched as a DocPage. |
title | string, optional | Title of a web link. |
HistoryEntry
export interface HistoryEntry {
at: string;
author?: Person;
field: string;
from?: string;
to?: string;
}defined in packages/kit/src/types.ts
One changed field at one moment: field is the tracker's field name, from and to are the values as text, either of which may be absent (a field that was empty, or cleared).
Project
export interface Project {
key: string;
name: string;
url?: string;
}defined in packages/kit/src/types.ts
key is what ticket keys start with (PAY) and what the profile lists under a tracker's projects.
TicketSearchQuery
export interface TicketSearchQuery {
/** Free text matched against title and description. */
text?: string;
projects?: string[];
statusCategories?: StatusCategory[];
/** ISO date; only tickets updated at or after it. */
updatedSince?: string;
/** Tracker-native query (JQL, WIQL, GitHub search syntax). Needs the `native-query` capability. */
native?: string;
}defined in packages/kit/src/types.ts
| Field | Type | Notes |
|---|---|---|
text | string, optional | Free text matched against title and description. How it is matched (word forms, operators) is up to the tracker. |
projects | string[], optional | Project keys to search in. |
statusCategories | StatusCategory[], optional | |
updatedSince | string, optional | ISO date; only tickets updated at or after it. |
native | string, optional | A query in the tracker's own language (JQL, WIQL, GitHub search syntax). Only trackers with the native-query capability accept it. |
All fields combine with AND. Results are TicketSummary items in a Page.
Code hosts
RepoInfo
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/kit/src/types.ts
| Field | Type | Notes |
|---|---|---|
name | string | Short name, unique inside the host entry. This is the name used everywhere else in Safran: filters, groups, team ownership. |
fullName | string | Host-qualified, for example acme/Platform/payments-api. |
defaultBranch | string | The branch Safran clones and indexes. |
cloneUrl | string | HTTPS clone URL without credentials. For a local host, an absolute directory path. |
webUrl | string, optional | Link for humans. |
archived | boolean, optional | |
sizeKb | number, optional | As the host reports it. |
primaryLanguage | string, optional | As the host reports it. |
GitAuth
/**
* Credentials for git over HTTPS. Safran passes them to git through the environment
* (an http.extraHeader config), never inside the URL, so they cannot end up in
* `.git/config`, process listings or logs.
*/
export type GitAuth =
| { kind: "basic"; username: string; password: string }
| { kind: "bearer"; token: string };defined in packages/kit/src/types.ts
What a code host returns from gitAuth(). Safran passes it to git through the environment, as an HTTP header configuration, never inside the URL. undefined instead of a GitAuth means the repositories are public or local.
PullRequest
A merged pull request, the raw material of the ticket ↔ code link store.
export interface PullRequest {
id: string;
repo: string;
title: string;
description: string;
url?: string;
author?: Person;
sourceBranch?: string;
targetBranch?: string;
mergedAt?: string;
/** Commit the PR was merged as. */
mergeCommit?: string;
/** Ticket keys the host itself links to the PR (work items, closing references). */
linkedTicketKeys: string[];
/** Repo-relative paths changed by the PR. Absent when the host needs a second call. */
changedFiles?: string[];
}defined in packages/kit/src/types.ts
| Field | Type | Notes |
|---|---|---|
id | string | The host's id or number, as a string. |
repo | string | The repo's name. |
title | string | |
description | string | Empty when there is none. |
url | string, optional | |
author | Person, optional | |
sourceBranch | string, optional | |
targetBranch | string, optional | |
mergedAt | string, optional | ISO date. |
mergeCommit | string, optional | The commit the pull request was merged as. |
linkedTicketKeys | string[] | Ticket keys the host itself links to the pull request (work items, closing references). Keys mentioned in the title, branch or description are found by Safran afterwards and are not in this list. |
changedFiles | string[], optional | Repo-relative paths. Absent when the host needs a second call for them; Safran then calls getPullRequestFiles when the host has it. |
PullRequestQuery
export interface PullRequestQuery extends PageOptions {
/** ISO date; only PRs merged at or after it. */
mergedSince?: string;
}defined in packages/kit/src/types.ts
PageOptions plus mergedSince: an ISO date, only pull requests merged at or after it.
Document sources
DocPage
export interface DocPage {
/** Id of the doc source entry in the profile. */
source: string;
url: string;
title: string;
/** Markdown. */
content: string;
updatedAt?: string;
author?: Person;
}defined in packages/kit/src/types.ts
| Field | Type | Notes |
|---|---|---|
source | string | The id of the doc source entry in the profile. |
url | string | The page's URL. |
title | string | |
content | string | Markdown, converted from the wiki's storage format. |
updatedAt | string, optional | ISO date. |
author | Person, optional |
Embeddings
EmbedOptions
export interface EmbedOptions extends CallOptions {
/** Some models embed queries and documents differently. */
kind?: "query" | "document";
}defined in packages/kit/src/types.ts
CallOptions plus kind: "query" for a search query, "document" for text being indexed. Models that embed the two the same way ignore it. The built-in index passes kind: "query" when it embeds a search query.
Code index
SearchMode
export type SearchMode = "auto" | "hybrid" | "dense" | "lexical";defined in packages/kit/src/types.ts
| Mode | Channels used |
|---|---|
auto | Both, weighted by the shape of the query: an identifier-like query leans on words, a prose query on meaning. The default. |
hybrid | Both, as an even blend. |
dense | Only the embedding channel (meaning). |
lexical | Only the word channel (BM25). Needs no embedder call. |
CodeFilter
Narrows a search or a grep. CodeSearchOptions and GrepOptions both extend it.
export interface CodeFilter {
repos?: string[];
/** Repo groups from the profile. */
groups?: string[];
languages?: string[];
kinds?: string[];
/** Repo-relative path prefix. */
pathPrefix?: string;
}defined in packages/kit/src/types.ts
| Field | Type | Notes |
|---|---|---|
repos | string[], optional | Repo names. |
groups | string[], optional | Repo groups from the profile (backend, mobile, …). |
languages | string[], optional | Language names as the index assigns them (typescript, csharp, …). |
kinds | string[], optional | Structural roles the chunker guessed (component, controller, test, …). |
pathPrefix | string, optional | Repo-relative path prefix, for example src/refund/. |
Fields combine with AND; the values inside one field with OR. Leaving a field out means "no restriction". An empty repos or groups list is a restriction that matches nothing.
CodeSearchOptions
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;
}defined in packages/kit/src/types.ts
| Field | Type | Notes |
|---|---|---|
limit | number, optional | Number of hits. The built-in index defaults to 10 and clamps at 50. |
mode | SearchMode, optional | Default auto. |
snippetLines | number, optional | Lines of each hit's snippet window for this call. 0 returns whole chunks. The built-in index defaults to 40 and clamps at 400. |
It also has every field of CodeFilter, and signal.
CodeHit
export interface CodeHit {
repo: string;
path: string;
/** First and last line of `snippet`. */
startLine: number;
endLine: number;
/** Line range of the whole chunk, present when `snippet` is only a window of it. */
chunk?: { startLine: number; endLine: number };
language?: string;
/** Structural role guessed by the chunker: "component", "controller", "test", … */
kind?: string;
/** Main symbol defined in the chunk, when known. */
symbol?: string;
/** Final ranking score, higher is better. Only comparable within one result list. */
score: number;
/** Per-channel scores, so callers can judge how a hit was found. */
channels: { dense?: number; lexical?: number };
snippet: string;
/** Other places holding the same code (forks, copied modules), collapsed into this hit. */
alsoIn?: { repo: string; path: string }[];
}defined in packages/kit/src/types.ts
| Field | Type | Notes |
|---|---|---|
repo | string | Repo name. |
path | string | Repo-relative path. |
startLine | number | First line of snippet, 1-based. |
endLine | number | Last line of snippet. |
chunk | { startLine, endLine }, optional | Line range of the whole chunk, present when snippet is only a window of it. Read those lines to see the rest. |
language | string, optional | |
kind | string, optional | Structural role guessed by the chunker. |
symbol | string, optional | Main symbol defined in the chunk, when known. |
score | number | Final ranking score; higher is better. |
channels | { dense?, lexical? } | Per-channel scores. A channel that did not find the hit is absent. |
snippet | string | The code. Third-party text. |
alsoIn | { repo, path }[], optional | Other places holding the same code (forks, copied modules), collapsed into this hit. |
GrepOptions
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;
}defined in packages/kit/src/types.ts
| Field | Type | Notes |
|---|---|---|
regex | boolean, optional | Treat the pattern as a regular expression. Default: a literal string. An expression that does not compile is INVALID_INPUT. |
caseSensitive | boolean, optional | Left out, the built-in index uses smart case: a pattern with an upper-case letter is matched exactly, an all-lower-case one ignores case. |
wholeWord | boolean, optional | Only matches not directly preceded or followed by a letter, digit or underscore. |
pathGlob | string, optional | Glob on the repo-relative path: * stays inside a directory, ** crosses them. A pattern without / matches the file name in any directory (*.ts). |
context | number, optional | Lines of context around each match. Default none. |
limit | number, optional | Matches returned. The built-in index defaults to 50 and clamps at 200. |
It also has every field of CodeFilter, and signal.
GrepMatch
export interface GrepMatch {
repo: string;
path: string;
line: number;
text: string;
before?: string[];
after?: string[];
}defined in packages/kit/src/types.ts
line is 1-based and text is that line. before and after are present only when context was asked for.
GrepResult
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
| Field | Type | Notes |
|---|---|---|
matches | GrepMatch[] | At most limit. |
total | number | Matches found in total, which may exceed matches.length. |
truncated | boolean | True when the limit cut the list. |
incomplete | string[], optional | Repos that could not be searched completely (time budget, unreadable files). Absent when everything was searched. |
An empty matches with incomplete set does not mean "not there". Check incomplete before concluding that a string does not occur.
FileSlice
export interface FileSlice {
repo: string;
path: string;
startLine: number;
endLine: number;
totalLines: number;
content: string;
truncated: boolean;
}defined in packages/kit/src/types.ts
| Field | Type | Notes |
|---|---|---|
repo | string | |
path | string | |
startLine | number | First line returned, 1-based. |
endLine | number | Last line returned. 0 for an empty file. |
totalLines | number | Lines in the whole file. |
content | string | The lines, joined with \n. Third-party text. |
truncated | boolean | True when fewer lines came back than were asked for. Ask again from endLine + 1. |
The built-in index returns 200 lines when no end line is given and at most 400 per call.
IndexRepoInput, IndexProgress and IndexRepoResult
export interface IndexRepoInput {
name: string;
/** Absolute path of the checked-out working tree. */
dir: string;
group?: string;
}
export interface IndexProgress {
repo: string;
phase: "scan" | "chunk" | "embed" | "write";
done: number;
total: number;
}
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/kit/src/types.ts
IndexRepoInput is what the index is told to index: a name, the absolute directory of the checked-out working tree, and the repo's group. IndexProgress is what onProgress receives: phase moves through scan, chunk, embed and write, with done out of total inside each phase.
| Field | Notes |
|---|---|
repo | Repo name. |
filesIndexed | Files that were chunked in this run (new or changed). |
filesUnchanged | Files whose content hash was the same as last time; skipped. |
filesRemoved | Files that left the working tree and were dropped from the index. |
chunksWritten | Chunks stored in this run. |
embeddingsComputed | Vectors the embedder had to compute. |
embeddingsCached | Vectors taken from the embedding cache instead. |
durationMs | Wall time of the run. |
filesSkipped | Optional. Files left out of the index, counted by reason (binary, large, secret, …). |
IndexStatus and IndexedRepoStatus
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
| Field | Type | Notes |
|---|---|---|
name | string | Repo name. |
group | string, optional | |
files | number | Indexed files. |
chunks | number | Indexed chunks. |
indexedAt | string, optional | ISO date of the last index run. |
embedder | string, optional | Id of the embedder this repo's vectors were made with. |
stale | boolean, optional | True when the repo holds vectors from an embedder other than the current one and must be indexed again. |
IndexStatus.embedder is the id of the embedder the index is opened with now, whatever the stored vectors came from; IndexStatus.chunks is the total over all repos.
Common mistakes
- Comparing
scoreacross result lists, or filtering by a fixed score. It ranks one list; nothing more. - Building a clone command from
cloneUrlplus a token. Use theGitAuththe host returns, or letsafran.repos.syncclone. - Editing or constructing a cursor.
nextCursoris opaque and tied to the query and options that produced it. - Reading
Ticket.fieldsas if it had a schema. Its keys depend on the tracker and on the company's configuration. - Treating an empty grep result as proof of absence without looking at
incompleteandtruncated. - Showing
description,body,contentorsnippetto an agent unwrapped. They are third-party text; the MCP server wraps them, and your own tooling should too.