Pagination, logging and defaults
Three conventions hold across the whole SDK, so they are described once here: how paged calls work, how Safran logs, and where the default numbers live. Learn them once and every sub-API behaves the way you expect.
Pagination
A paged call returns a Page<T> and accepts PageOptions:
/** 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
| Field | Meaning |
|---|---|
items | The items of this page. May be fewer than limit, and may be empty, while more pages exist. |
nextCursor | Present when there is another page. Pass it back as cursor. Absent on the last page. |
| Option | Meaning |
|---|---|
limit | Page size. Each call has its own default and maximum. |
cursor | nextCursor of the previous page. Leave it out for the first page. |
PageOptions also carries signal, like every options type.
The paged calls are tickets.comments, tickets.history and tickets.search. Calls that return a bounded list take a limit and no cursor (code.search, code.grep, links.query); they tell you what the limit cut in their own way (GrepResult.total, links.count).
The rules
The end of the data is the absence of nextCursor. Never stop because a page came back shorter than limit: tickets.search splits the limit across trackers, and a connector may filter after fetching.
Cursors are opaque. A cursor is a string made by the call that returned it. Do not build, parse or shorten one. Pass it back unchanged, to the same method, with the same query and options. Cursors are not meant to be stored: use them to continue a listing you started, not as a bookmark for next week.
A bad cursor is INVALID_INPUT, never a silently different page. That covers a string that is not a cursor at all and a cursor that belongs to another search.
limit follows one rule everywhere, implemented by resolveLimit:
| You pass | You get |
|---|---|
nothing (undefined) | The call's default. |
| a whole number from 1 to the maximum | That many. |
| a number above the maximum | The maximum. Clamped silently: asking for "as many as possible" is not an error. |
0, a negative number, a fraction, NaN | INVALID_INPUT. Zero is refused rather than read as "no limit". |
Defaults and maximums
| Call | Default limit | Maximum |
|---|---|---|
tickets.search | 50 | 500 |
tickets.comments, tickets.history | the connector's own | the connector's own |
code.search | 10 | 50 |
code.grep | 50 | 200 |
links.query | 100 | 1 000 000 |
Read all pages
A small generic helper covers every paged call. It is an async generator, so the caller can stop early and no page is fetched before it is needed:
import type { Page, PageOptions } from "@safran/core";
/** Yields every item of a paged call, one page at a time. Stops when the signal fires. */
export async function* readAll<T>(fetchPage: (options: PageOptions) => Promise<Page<T>>, options: { pageSize?: number; signal?: AbortSignal } = {}): AsyncGenerator<T, void, void> {
let cursor: string | undefined;
do {
const page = await fetchPage({
...(options.pageSize === undefined ? {} : { limit: options.pageSize }),
...(cursor === undefined ? {} : { cursor }),
...(options.signal === undefined ? {} : { signal: options.signal }),
});
yield* page.items;
// The end is the absence of a cursor, never a short page.
cursor = page.nextCursor;
} while (cursor !== undefined);
}The examples on this page run offline. They share one fixture: an acme with a working tracker and a second one whose search always fails, built on the fakes from @safran/kit/testing.
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createSafran, defineProfile, type Logger, type Safran } from "@safran/core";
import { FakeTracker, fakePlugins } from "@safran/kit/testing";
const tickets = [
{
key: "PAY-1423",
title: "Kısmi iade işlemi İstanbul şubesinde başarısız oluyor",
comments: ["Sağlayıcı yanıtını inceledim.", "Yuvarlama hatası görünüyor.", "Düzeltme hazır.", "Test ortamında doğrulandı.", "Canlıya alındı."].map((body, index) => ({ id: `c${index + 1}`, body })),
},
{ key: "PAY-1500", title: "Refund webhook retries are not idempotent" },
{ key: "PAY-1501", title: "Checkout basket total ignores the campaign discount" },
];
/** An offline acme: one working tracker (`jira`) and one whose search always fails (`legacy`). */
export async function createAcme(logger?: Logger): Promise<Safran> {
const legacy = new FakeTracker({ id: "legacy", tickets: [{ key: "OPS-7", title: "Rotate the refund signing key" }] });
legacy.searchTickets = async () => {
throw new Error("connection reset");
};
return createSafran({
profile: defineProfile({
version: 1,
company: "acme",
trackers: [
{ id: "jira", type: "fake", projects: ["PAY"] },
{ id: "legacy", type: "fake", projects: ["OPS"] },
],
}),
dataDir: mkdtempSync(join(tmpdir(), "acme-")),
builtinPlugins: false,
plugins: fakePlugins({ trackers: [new FakeTracker({ id: "jira", tickets }), legacy] }),
index: false,
...(logger === undefined ? {} : { logger }),
});
}import { isSafranError } from "@safran/core";
import { createAcme } from "./acme";
import { readAll } from "./read-all";
await using safran = await createAcme();
// Page by page, by hand.
const first = await safran.tickets.comments("PAY-1423", { limit: 2 });
console.log(first.items.map((comment) => comment.id), first.nextCursor !== undefined);
// Everything, with the helper.
const bodies: string[] = [];
for await (const comment of readAll((options) => safran.tickets.comments("PAY-1423", options), { pageSize: 2 })) {
bodies.push(comment.body);
}
console.log(bodies.length);
// The limit rules.
for (const limit of [0, 2.5, 100_000]) {
try {
const page = await safran.tickets.search({ text: "refund" }, { limit, tracker: "jira" });
console.log(`limit ${limit}: ${page.items.length} item(s)`);
} catch (error) {
if (!isSafranError(error, "INVALID_INPUT")) throw error;
console.log(`limit ${limit}: ${error.format()}`);
}
}
// A cursor is only good for the search it came from.
const page = await safran.tickets.search({}, { limit: 1, tracker: "jira" });
try {
await safran.tickets.search({}, { limit: 1, tracker: "legacy", ...(page.nextCursor === undefined ? {} : { cursor: page.nextCursor }) });
} catch (error) {
if (!isSafranError(error, "INVALID_INPUT")) throw error;
console.log(error.format());
}
try {
await safran.tickets.search({}, { cursor: "page-2" });
} catch (error) {
if (!isSafranError(error, "INVALID_INPUT")) throw error;
console.log(error.format());
}$ bun paging.ts
[ "c1", "c2" ] true
5
limit 0: `limit` must be a whole number of at least 1
→ Pass a value between 1 and 500, or leave it out for the default of 50.
limit 2.5: `limit` must be a whole number of at least 1
→ Pass a value between 1 and 500, or leave it out for the default of 50.
limit 100000: 1 item(s)
The search cursor does not belong to this search
→ Pass the cursor of the previous page back unchanged, with the same query and options, or omit it to start over.
The pagination cursor is not valid
→ Pass the cursor of the previous page back unchanged, with the same query and options, or omit it to start over.Writing a paged method
Plugin authors get the same rules from three helpers in @safran/kit: resolveLimit(limit, { default, max }) applies the limit rule, and encodeCursor(value) / decodeCursor(cursor, guard) pack any JSON value into an opaque cursor and refuse anything that is not one with INVALID_INPUT. See plugins.
Logging
Safran is silent by default. Pass a logger to createSafran to see what it does.
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 | Detail for diagnosing: HTTP retries with their wait, what a scan skipped, optional lookups that failed without consequence. |
info | Events worth knowing in normal operation: a repository indexed, a repository removed from the index, a repository skipped because another process is syncing it. |
warn | Something was worked around and the result may be incomplete: one tracker or code host failed and the others answered, one repo of a sync failed, a listing stopped at a page cap, an incomplete clone was replaced. |
error | Not used by the library itself: a failure is thrown or carried in a result, where the caller decides. It is there for applications built on Safran. |
Each method takes a message and an optional object of fields. The message is a constant English sentence; what varies is in the fields (repo, tracker, code, status), so entries are easy to filter and to ship as structured logs.
A logger that writes to the console:
import type { Logger } from "@safran/core";
const LEVELS = ["debug", "info", "warn", "error"] as const;
type Level = (typeof LEVELS)[number];
/** Writes one line per entry to stderr, at `minLevel` and above. */
export function consoleLogger(minLevel: Level = "info"): Logger {
const threshold = LEVELS.indexOf(minLevel);
const at =
(level: Level) =>
(message: string, fields?: Record<string, unknown>): void => {
if (LEVELS.indexOf(level) < threshold) return;
console.error(`[safran] ${level.padEnd(5)} ${message}${fields === undefined ? "" : ` ${JSON.stringify(fields)}`}`);
};
return { debug: at("debug"), info: at("info"), warn: at("warn"), error: at("error") };
}import { createAcme } from "./acme";
import { consoleLogger } from "./console-logger";
await using safran = await createAcme(consoleLogger("debug"));
const result = await safran.tickets.search({ text: "refund" });
console.log(result.items.map((item) => item.key), result.warnings);$ bun logging.ts
[safran] warn Ticket search failed on one tracker; results from the others are returned {"tracker":"legacy","code":"INTERNAL","error":"connection reset"}
[ "PAY-1500" ] [
{
source: "legacy",
code: "INTERNAL",
message: "Tracker \"legacy\" failed: connection reset",
}
]The same event reaches you twice, on purpose: as a log entry for the operator, and as a warning in the result for the program.
What a logger must and must not do
- Write to stderr or a file, not stdout, in a program whose stdout is a protocol or a result (an MCP server on stdio, a command with JSON output).
- Do not throw. The methods are called from the middle of syncs and searches.
- Be cheap.
debugcan be called once per HTTP retry and once per unreadable file.
The same logger is handed to every connector as ctx.logger, and to the code index.
What is never logged
Safran does not log credentials. The HTTP client logs a request's URL without its query string and never logs headers; git output is scrubbed of every form of the credential before it is logged or put into an error. Log entries do contain names from your systems (repository names, tracker ids, file paths in debug entries) and upstream error messages, so treat a debug log as internal.
Named defaults
Every number Safran picks for you is a named, exported constant, so nothing is a magic value in your code either. The constants of @safran/core:
| Constant | Value | Used by |
|---|---|---|
DEFAULT_DATA_DIR | "data" | The data directory next to the profile file. |
DEFAULT_TICKET_SEARCH_LIMIT | 50 | tickets.search page size across all trackers. |
DEFAULT_MAX_TICKET_SEARCH_LIMIT | 500 | Largest tickets.search page. |
DEFAULT_CLOSE_GRACE_MS | 30 000 | How long close() waits for cancelled calls. |
DEFAULT_GIT_NETWORK_TIMEOUT_MS | 600 000 | Budget of one clone or fetch. |
DEFAULT_GIT_LOCAL_TIMEOUT_MS | 60 000 | Budget of a git command that stays on the machine. |
DEFAULT_GIT_KILL_GRACE_MS | 2 000 | Time a cancelled git gets to clean up before it is killed. |
DEFAULT_GIT_ERROR_CHARS | 500 | Characters of git's error output kept in a message. |
DEFAULT_REPO_LOCK_STALE_MS | 86 400 000 | Age after which a repo lock is taken over even if its process id is alive. |
DEFAULT_LINKS_MAX_PER_REPO | 500 | Pull requests newly stored per repo in one links.refresh. |
DEFAULT_LINKS_LOOKBACK_MONTHS | 12 | How far back a repo's first links.refresh looks. |
DEFAULT_LINKS_PAGE_SIZE | 100 | Pull requests asked from a code host per request. |
DEFAULT_WORK_QUERY_LIMIT | 100 | links.query default limit. |
DEFAULT_MAX_WORK_QUERY_LIMIT | 1 000 000 | Largest links.query result. |
DEFAULT_OWNERSHIP_HISTORY_LIMIT | 500 | Records read when ownership is inferred from history. |
DEFAULT_SUGGESTIONS | 3 | Names offered in a "did you mean" hint. |
The declarations, as they are in the source:
/** Named defaults of `@safran/core`. Everything here is overridable per call or per instance. */
/** Directory name used next to the profile file (or in the cwd for inline profiles). */
export const DEFAULT_DATA_DIR = "data";
/** Total page size of `tickets.search` across all trackers. */
export const DEFAULT_TICKET_SEARCH_LIMIT = 50;
/** Largest `tickets.search` page; a larger `limit` is clamped. */
export const DEFAULT_MAX_TICKET_SEARCH_LIMIT = 500;
/**
* How long `close()` waits for cancelled calls to settle before it releases the handles anyway.
* A connector that ignores its signal must not keep the process from exiting.
*/
export const DEFAULT_CLOSE_GRACE_MS = 30_000;
/** Clone / fetch budget. A cold shallow clone of a large monorepo over a slow VPN takes minutes. */
export const DEFAULT_GIT_NETWORK_TIMEOUT_MS = 10 * 60_000;
/** Budget for git commands that never leave the machine (rev-parse, checkout). */
export const DEFAULT_GIT_LOCAL_TIMEOUT_MS = 60_000;
/** How long a killed git gets to clean up after SIGTERM before SIGKILL. */
export const DEFAULT_GIT_KILL_GRACE_MS = 2_000;
/** Characters of git stderr kept in an error message. */
export const DEFAULT_GIT_ERROR_CHARS = 500;
/**
* Age after which a repo lock is taken over even though its process id is alive: the id may
* belong to an unrelated process by then. Far above any real sync of one repo.
*/
export const DEFAULT_REPO_LOCK_STALE_MS = 24 * 60 * 60_000;
/** Merged pull requests newly stored per repo in one `links.refresh`. */
export const DEFAULT_LINKS_MAX_PER_REPO = 500;
/** How far back the first `links.refresh` of a repo looks. */
export const DEFAULT_LINKS_LOOKBACK_MONTHS = 12;
export const DEFAULT_LINKS_PAGE_SIZE = 100;
export const DEFAULT_WORK_QUERY_LIMIT = 100;
/** Largest `links.query` page; discovery and evaluation read the whole store in one call. */
export const DEFAULT_MAX_WORK_QUERY_LIMIT = 1_000_000;
/** Records of a repo read when ownership is inferred from history. */
export const DEFAULT_OWNERSHIP_HISTORY_LIMIT = 500;
/** Names offered in a "did you mean" hint. */
export const DEFAULT_SUGGESTIONS = 3;defined in packages/core/src/defaults.ts
The limits of code search and grep live in the code index, and those of HTTP requests in the kit's client:
export const DEFAULT_SEARCH_LIMIT = 10;
/** Hits returned by one search at most; a larger `limit` is clamped, not refused. */
export const DEFAULT_MAX_SEARCH_LIMIT = 50;
/**
* A chunk grows to 6000 chars (~130 lines); ten of them were ~15k tokens, the agent filled
* its context and stopped querying, and most of each chunk was irrelevant to the query.
* So a hit shows the most query-relevant window of lines instead.
*/
export const DEFAULT_SNIPPET_LINES = 40;
export const DEFAULT_MAX_SNIPPET_LINES = 400;
export const DEFAULT_GREP_LIMIT = 50;
/** Matches returned by one call at most; `total` still counts every matching line. */
export const DEFAULT_MAX_GREP_LIMIT = 200;
/** Lines of context on each side at most: the `context` range of the `grep_code` tool. */
export const DEFAULT_MAX_GREP_CONTEXT = 5;
/**
* Wall-clock budget for one grep. When it runs out the repo being scanned and every later
* one are reported in `incomplete`; the answer is never silently partial.
*/
export const DEFAULT_GREP_BUDGET_MS = 20_000;
/** Lines returned when no end line is given. */
export const DEFAULT_READ_LINES = 200;
/** Hard cap per call, whatever range is asked for. */
export const DEFAULT_MAX_READ_LINES = 400;
export const DEFAULT_MAX_READ_FILE_BYTES = 5_000_000;
export const DEFAULT_HTTP_TIMEOUT_MS = 30_000;
export const DEFAULT_HTTP_MAX_RETRIES = 3;
export const DEFAULT_HTTP_MAX_RETRY_DELAY_MS = 20_000;defined in packages/codeindex/src/search.ts, packages/codeindex/src/snippet.ts, packages/codeindex/src/grep.ts, packages/codeindex/src/readfile.ts, packages/kit/src/http.ts
Where a value can be changed, it is changed per call (limit, snippetLines, maxPerRepo, since) or per instance (dataDir). The constants are the defaults, not settings: assigning to them has no effect.
Common mistakes
| Mistake | What happens |
|---|---|
Stopping at the first page shorter than limit | Results are lost. Loop until nextCursor is absent. |
Passing limit: 0 to mean "everything" | INVALID_INPUT. Leave limit out, or pass a large number and let it be clamped. |
| Reusing a cursor with different filters | INVALID_INPUT, or a page that belongs to the earlier query. A cursor goes with the query that produced it. |
{ cursor: undefined } under exactOptionalPropertyTypes | A type error. Leave the key out: ...(cursor === undefined ? {} : { cursor }). |
| Logging to stdout from an MCP server on stdio | The log lines corrupt the protocol stream. Log to stderr. |