Writes
safran.writes is the only way Safran changes anything outside your machine. It is present on every instance and off by default. This page shows the whole path for one write (status, preview, a person's confirmation, commit, audit row), the four kinds of write there are, and every refusal you can meet on the way.
Read writes first if you are deciding whether to turn them on: it states the risks plainly. This page is the SDK surface.
What has to be true
Three switches, all of them needed:
- The profile says
writes.enabled: true. - The kind is listed under
writes.allow. - The instance was not created with
allowWrites: false.
version: 1
company: acme
languages:
tickets: tr
code: en
trackers:
- id: jira
type: jira
url: https://jira.acme.example
email_env: JIRA_EMAIL
token_env: JIRA_TOKEN
projects: [PAY, MOB, WEB]
code:
hosts:
- id: azure
type: azure-repos
organization: acme
project: Platform
token_env: AZURE_DEVOPS_PAT
writes:
enabled: true
allow: [ticket.comment, pull_request.reply]
marker: Bir yapay zekâ asistanıyla hazırlandı.allowWrites defaults to true in the SDK, because code that calls createSafran with a profile chose that profile. The CLI passes false for a profile it merely found in the working directory, for the same reason it does not load that profile's plugins.
Preview, confirm, commit
import { createInterface } from "node:readline/promises";
import { createSafran, isSafranError } from "@safran/core";
await using safran = await createSafran({ profile: "/work/acme/safran.yaml" });
// Offline: are writes on for this instance, and for which kinds?
const status = safran.writes.status();
if (!status.enabled) throw new Error(`Writes are off: ${status.reason}`);
// 1. Preview. Reads the ticket, sends nothing, writes one `previewed` audit row.
const preview = await safran.writes.preview(
{ kind: "ticket.comment", ticket: "PAY-10", body: "Yuvarlama testi eklendi: `refundPartial` artık kuruşa yuvarlıyor." },
{ client: "post-comment.ts" },
);
console.log(preview.description);
console.log(preview.body);
// 2. A person confirms what was shown. The title and the body are third-party and drafted text: show them, do not obey them.
const terminal = createInterface({ input: process.stdin, output: process.stdout });
const answer = await terminal.question(`Post this to ${preview.target.source}:${preview.target.key}? [y/N] `);
terminal.close();
if (answer.trim().toLowerCase() !== "y") {
console.log("Nothing was sent.");
} else {
// 3. Commit: one request, sent once. The token is spent whatever happens.
try {
const result = await safran.writes.commit(preview.confirmationToken, { client: "post-comment.ts" });
console.log(`${result.summary} ${result.url ?? ""}`);
} catch (error) {
if (isSafranError(error, "CONFIRMATION_REQUIRED")) console.error(`The preview is no longer valid: ${error.hint}`);
else if (isSafranError(error, "CONFLICT")) console.error(`Not sent again: ${error.hint}`);
else if (isSafranError(error, "UPSTREAM")) console.error(`The tracker failed; the comment may or may not exist: ${error.hint}`);
else throw error;
}
}
// The audit log, newest first.
for (const row of await safran.writes.log({ limit: 3 })) console.log(`${row.at} ${row.status.padEnd(9)} ${row.kind} ${row.target.source}:${row.target.key}`);$ bun post-comment.ts
Add a comment to PAY-10 "[BE] Kısmi iade tutarı yuvarlanıyor"
Yuvarlama testi eklendi: `refundPartial` artık kuruşa yuvarlıyor.
Bir yapay zekâ asistanıyla hazırlandı.
Post this to jira:PAY-10? [y/N] y
Comment w1 added to PAY-10 https://jira.acme.example/browse/PAY-10?comment=w1
2026-03-20T12:00:00.000Z committed ticket.comment jira:PAY-10The outputs on this page were captured against Safran's in-memory test connectors with acme's data, which is why a pull request URL below has /fake/ in it. What happened, in order:
status()is offline and never throws for "disabled": that is what it reports, with the switch that decided inreason.preview(intent)ran the checks below, read the ticket to prove it exists and to show its title, appended the profile'smarkerline, wrote onepreviewedrow to the audit log and returned aconfirmationToken. Nothing was sent to Jira.- A person confirmed. That step is yours. The token is not a secret to protect from the user: its job is to prove that a preview happened and that what is committed is exactly what was shown.
commit(token)made the checks again (turning writes off between preview and commit wins), sent one request, and moved the audit row tocommitted.
The comment appears under the account the tracker token belongs to. Safran cannot edit or delete it afterwards.
The four kinds
kind | Fields | Creates | Connector capability |
|---|---|---|---|
ticket.comment | ticket, body | One comment on a ticket. | write:comment |
ticket.create_child | parent, title, description, optional type, labels | One ticket as a real child of parent, in the parent's project. | write:create-child |
pull_request.comment | pullRequest, body, optional path, line, side | One new review thread: on a line, on a file, or in the general conversation. | write:pr-comment |
pull_request.reply | pullRequest, threadId, body | One comment in an existing review thread. | write:pr-reply |
ticket and parent are ticket references as tickets.resolve accepts them; pullRequest is a pull request reference as pulls.resolve accepts it. Bodies are Markdown; the connector converts them to what the system stores.
Deliberately not offered: deleting anything, editing an existing body, status transitions, votes, resolving threads, assignee, estimate or sprint changes, uploads, bulk creation. A created child gets a title, a description, a type and labels, and nothing else.
export type WriteIntent = TicketCommentIntent | TicketCreateChildIntent | PullRequestCommentIntent | PullRequestReplyIntent;
/** Add one comment to a ticket. */
export interface TicketCommentIntent {
kind: "ticket.comment";
/** Ticket reference, as `TicketsApi.resolve` accepts it: a key, a URL, `<tracker>:<key>`. */
ticket: string;
/** Markdown. */
body: string;
}
/** Create one ticket as a child of another. */
export interface TicketCreateChildIntent {
kind: "ticket.create_child";
/** Reference of the parent ticket. The child is created in the parent's project. */
parent: string;
title: string;
/** Markdown. */
description: string;
/** Ticket type by its name in the tracker ("Sub-task", "Task"). Default: the tracker's default child type. */
type?: string;
labels?: string[];
}
/** Start one new review thread on a pull request. */
export interface PullRequestCommentIntent {
kind: "pull_request.comment";
/** Pull request reference, as `PullsApi.resolve` accepts it: a URL, `<host>:<repo>#<id>`, `<repo>#<id>`. */
pullRequest: string;
/** Markdown. */
body: string;
/** Repo-relative file to comment on. Without it the comment goes to the general conversation. */
path?: string;
/** 1-based line in `path`; needs `path`. Without it the comment is on the file as a whole. */
line?: number;
/** Which version of the file `line` counts in. Default `new`. */
side?: "old" | "new";
}
/** Reply inside an existing review thread. */
export interface PullRequestReplyIntent {
kind: "pull_request.reply";
pullRequest: string;
/** `ReviewThread.id` of the thread being answered. */
threadId: string;
/** Markdown. */
body: string;
}defined in packages/kit/src/writes.ts
What a preview holds
import { createSafran } from "@safran/core";
await using safran = await createSafran({ profile: "/work/acme/safran.yaml" });
const threads = await safran.pulls.threads("payments-api#7", { statuses: ["active"] });
const thread = threads.items.find((candidate) => candidate.path === "src/refund/service.ts");
if (!thread) throw new Error("No active thread on that file");
const preview = await safran.writes.preview({
kind: "pull_request.reply",
pullRequest: "payments-api#7",
threadId: thread.id,
body: "Test eklendi, `service.test.ts` içinde.",
});
console.log(JSON.stringify(preview, null, 2));{
"kind": "pull_request.reply",
"target": {
"source": "azure",
"type": "pull_request",
"key": "payments-api#7",
"url": "https://git.acme.example/fake/payments-api/pull/7",
"title": "PAY-10 fix partial refund rounding",
"threadId": "t-active",
"path": "src/refund/service.ts",
"line": 6
},
"description": "Reply in review thread t-active of pull request payments-api#7 \"PAY-10 fix partial refund rounding\"",
"body": "Test eklendi, `service.test.ts` içinde.\n\nBir yapay zekâ asistanıyla hazırlandı.",
"markerAdded": true,
"inReplyTo": {
"author": "Çağrı Öztürk",
"excerpt": "Yuvarlama için test eksik."
},
"confirmationToken": "V1DuxxolUL5w939ShP_K6TgYa3LhAK8SU9aPdy4xTBM",
"expiresAt": "2026-03-20T12:10:00.000Z"
}| Field | Meaning |
|---|---|
target | What the write will touch, resolved from the reference: the connector entry (source), the key, the URL and the title read at preview time. For a reply also the thread and its position. For ticket.create_child the key is the parent. |
description | One line a person can confirm. It contains the target's title, which is third-party text. |
body | The body that will be sent, character for character: your Markdown plus the profile's marker. |
markerAdded | true when writes.marker was appended. |
title, ticketType, labels | ticket.create_child only. ticketType absent means the tracker's default child type. |
possibleDuplicates | ticket.create_child only: existing children of the parent with a very similar title. Not a refusal; a reason to ask. |
inReplyTo | pull_request.reply only: the author and the first DEFAULT_WRITE_REPLY_EXCERPT_CHARS (300) characters of the comment that opened the thread. Third-party text. |
confirmationToken | Opaque, unguessable, single use, bound to this instance and to exactly this payload. |
expiresAt | DEFAULT_WRITE_CONFIRMATION_TTL_MS (10 minutes) after the preview. |
Tokens live in memory. Closing the instance, or restarting the process, invalidates every preview, which is the safe direction. At most DEFAULT_WRITE_MAX_PENDING_PREVIEWS (100) previews wait at once; the oldest is dropped beyond that.
The checks, in order
Every method that can write makes the same checks and fails with the first that applies:
| # | Check | Failure |
|---|---|---|
| 1 | allowWrites is not false | FORBIDDEN: "Writes are turned off for this instance" |
| 2 | Profile writes.enabled is true | FORBIDDEN, the hint names writes.enabled |
| 3 | The intent's kind is in writes.allow | FORBIDDEN, the hint names writes.allow, the kind and what is allowed now |
| 4 | The input is valid | INVALID_INPUT: an empty body, a body over MAX_WRITE_BODY_CHARS (20,000 characters, marker included), a title over MAX_WRITE_TITLE_CHARS (255), more than MAX_WRITE_LABELS (20) labels, line without path |
| 5 | The target resolves and exists | NOT_FOUND or INVALID_INPUT from resolving the reference; NOT_FOUND for a thread id the pull request does not have |
| 6 | The connector lists the write: capability | UNSUPPORTED, naming the connector |
A body that is too long is refused, never cut. If the audit row cannot be stored, nothing is sent.
What commit can answer
| Outcome | Meaning | What to do |
|---|---|---|
A WriteCommitResult | The write went through. id is the new comment (or the new ticket's key, or the new thread), url a link to it, auditId the audit row. | Show summary and url. |
CONFIRMATION_REQUIRED | The token is unknown, expired, or from another instance. Nothing was sent. | Preview again and confirm again. |
CONFLICT | The token was already used. The hint carries what it created and its URL. Nothing was sent again. | Nothing: the write exists. |
FORBIDDEN | Writes were turned off, or the kind was removed from allow, since the preview. | Nothing was sent. |
UPSTREAM, ABORTED, INTERNAL | The request may have left and its outcome is unknown. The hint says the write may have happened and names the target. | Look at the target before trying again. |
Any other code (AUTH_FAILED, NOT_FOUND, INVALID_INPUT, …) | The connector said no. Nothing was created. | Fix the cause, then preview again. |
The token is spent the moment the request is sent, whatever the outcome: a failed commit needs a new preview. A write request is never retried by the HTTP client, so a timeout surfaces as UPSTREAM instead of a possible duplicate.
One step, for scripts
execute(intent) previews and commits in one call, for code that has its confirmation elsewhere (a script someone reviewed, a CI job). It fails with CONFIRMATION_REQUIRED while the profile has writes.require_confirmation: true, which is the default, and it is audited like any other write. The MCP tools never use it: an agent always goes through preview and commit, whatever the profile says.
The audit log
log(query?) returns audit rows, newest first. It reads the local store only (write_audit in <dataDir>/safran.db) and works while writes are disabled.
WriteLogQuery | Meaning |
|---|---|
since | ISO date, lower bound on at (inclusive). |
kinds | Only these kinds. |
statuses | Only previewed, committed or failed. |
limit | Default DEFAULT_WRITE_LOG_LIMIT (50), at most DEFAULT_MAX_WRITE_LOG_LIMIT (1,000). |
A row holds the kind, the target, the status, the SHA-256 of the previewed body, and who asked (client, when the caller said so). The body itself is kept for committed and failed rows, cut to DEFAULT_WRITE_AUDIT_BODY_CHARS (2,000) characters; a preview that was never committed keeps only the hash. safran writes log prints the same rows; see the CLI.
/** One row of the audit log (`write_audit` in `<dataDir>/safran.db`). */
export interface WriteAuditEntry {
id: string;
/** ISO time of the last change of the row (the preview, then the commit or the failure). */
at: string;
kind: WriteIntentKind;
target: WriteTarget;
status: WriteAuditStatus;
/** SHA-256 (hex) of the body that was previewed, so a row can be matched to a posted text without storing it twice. */
bodySha256: string;
/** The body. Kept for `committed` and `failed` rows; a preview never committed keeps only the hash. */
body?: string;
/** For `committed`: what the connector reported. */
resultId?: string;
resultUrl?: string;
/** For `failed`. */
error?: BatchError;
/** Who asked, when the caller said so (`WriteCallOptions.client`): an MCP client name, "cli". */
client?: string;
}defined in packages/core/src/api.ts
A read-only instance
import { createSafran, isSafranError } from "@safran/core";
// Whatever the profile says, this instance cannot write.
await using safran = await createSafran({ profile: "/work/acme/safran.yaml", allowWrites: false });
console.log(safran.writes.status());
try {
await safran.writes.preview({ kind: "ticket.comment", ticket: "PAY-10", body: "…" });
} catch (error) {
if (isSafranError(error, "FORBIDDEN")) console.error(`${error.message}. ${error.hint ?? ""}`);
else throw error;
}$ bun read-only-instance.ts
{
enabled: false,
allowed: [],
requireConfirmation: true,
reason: "Writes are turned off for this instance (`allowWrites: false`).",
}
Writes are turned off for this instance. The instance was created with `allowWrites: false`, which makes it read-only whatever the profile says. Create it with `allowWrites: true` (for the CLI: name the profile with `--profile`, or pass `--allow-writes`).Use this for anything that must not write even if someone edits the profile later: a batch job, an evaluation run, a server other people connect to.
The interface
/**
* The only way anything outside this machine is changed. Off by default.
*
* Order of the checks every method makes, each failing with the first that applies:
* 1. `allowWrites: false` → FORBIDDEN ("writes are turned off for this instance").
* 2. profile `writes.enabled` false → FORBIDDEN, hint naming `writes.enabled`.
* 3. the intent's kind not in `writes.allow` → FORBIDDEN, hint naming `writes.allow` and the kind.
* 4. the input (INVALID_INPUT: empty or over-long body, `line` without `path`, …).
* 5. the target (NOT_FOUND / INVALID_INPUT from resolving the reference).
* 6. the connector's `write:` capability → UNSUPPORTED naming the connector.
* A write is never a side effect of a read: nothing outside this interface calls a connector's
* `write:` method. If the audit row cannot be stored, nothing is sent.
*/
export interface WritesApi {
/** Offline. Never throws for "disabled": that is what it reports. */
status(): WritesStatus;
/** Checks 1–6, reads the target, records the preview and returns the token. Sends nothing. */
preview(intent: WriteIntent, options?: WriteCallOptions): Promise<WritePreview>;
/**
* Performs the write a preview described. CONFIRMATION_REQUIRED for a token that is unknown,
* expired or from another instance (the hint says to preview again); CONFLICT for one that was
* already used (the hint carries the URL of what it created) or whose target changed in a way
* that invalidates the preview. Checks 1–3 are made again: turning writes off between preview
* and commit wins. The token is spent the moment the request is sent, whatever the outcome: a
* failed commit needs a new preview, and a failure after the request left is reported as
* UPSTREAM with a hint that the write may have happened.
*/
commit(confirmationToken: string, options?: WriteCallOptions): Promise<WriteCommitResult>;
/**
* Preview and commit in one call, for code that already has its confirmation elsewhere (a
* script, a CI job). CONFIRMATION_REQUIRED while the profile has `writes.require_confirmation:
* true` (the default), with a hint naming that key. Audited like any other write.
*/
execute(intent: WriteIntent, options?: WriteCallOptions): Promise<WriteCommitResult>;
/** Audit rows, newest first. Reads the local store only; works while writes are disabled. */
log(query?: WriteLogQuery, options?: CallOptions): Promise<WriteAuditEntry[]>;
}
/** Why writes are on or off, for `get_server_info`, `safran doctor` and the decision to register write tools. */
export interface WritesStatus {
/** True only when `allowWrites` is not false, the profile says `writes.enabled: true` and `allow` is not empty. */
enabled: boolean;
/** The kinds a preview would accept right now: `writes.allow`, minus kinds no configured connector can perform. Empty when disabled. */
allowed: WriteIntentKind[];
requireConfirmation: boolean;
/**
* When disabled: why, as one or more whole sentences a person can be shown as they are (the
* CLI, the dashboard and `get_server_info` do, without rewording). It names the profile key
* or the way the instance was started, never a library option.
*/
reason?: string;
/**
* When disabled: the switch that decided it, for code. The profile is asked first, so an
* instance that was refused writes AND whose profile does not want them is off because of
* the profile. The same names as `details.switch` of the FORBIDDEN error.
*/
switch?: WritesSwitch;
}
/**
* Exactly what a commit would send, and the token that commits it. Making a preview reads the
* target (to prove it exists and to show its title) and changes nothing remote; it writes one
* `previewed` row to the audit log.
*/
export interface WritePreview {
kind: WriteIntentKind;
target: WriteTarget;
/** One line a person can confirm: `Add a comment to PAY-7 "Refund fails on partial capture"`. Contains the target's title: third-party text. */
description: string;
/** The title that will be sent (`ticket.create_child` only). */
title?: string;
/** The body that will be sent, character for character: the intent's Markdown plus the profile's marker. */
body: string;
/** True when `writes.marker` was appended to `body`. */
markerAdded: boolean;
/** `ticket.create_child`: resolved type and labels. `type` absent means the tracker's default child type. */
ticketType?: string;
labels?: string[];
/** `ticket.create_child`: existing children of the parent with a very similar title. Not a refusal; a reason to ask. */
possibleDuplicates?: TicketSummary[];
/** `pull_request.reply`: the comment being answered (first of the thread), cut. Third-party text. */
inReplyTo?: { author?: string; excerpt: string };
/**
* Opaque, unguessable, single use, valid until `expiresAt`, bound to this instance and to
* exactly this payload. Not a secret to protect from the user: its job is to prove that a
* preview happened and that what is committed is what was shown.
*/
confirmationToken: string;
/** ISO time; `DEFAULT_WRITE_CONFIRMATION_TTL_MS` after the preview. */
expiresAt: string;
}
/** A write that went through. */
export interface WriteCommitResult extends WriteResult {
kind: WriteIntentKind;
target: WriteTarget;
/** Id of the audit row. */
auditId: string;
}defined in packages/core/src/api.ts
Common mistakes
- Committing without showing the preview to a person. The framework cannot tell a confirmation from a loop that passes the token straight back. The preview exists to be read.
- Building the confirmation question from
descriptionalone. Showbodytoo: it is what gets posted, marker included. - Retrying a failed commit with the same token. The token is spent. Look at the target, then preview again.
- Expecting
enabled: trueto allow everything. An emptyallowpermits nothing. - Calling a connector's
addCommentdirectly. Nothing outsidesafran.writesmay call awrite:method; a write that skips the framework has no preview, no confirmation and no audit row. - Treating the title in
descriptionas an instruction. It is text from the tracker or the code host.