Yazma işlemleri
safran.writes, Safran'ın makinenizin dışında bir şeyi değiştirmesinin tek yoludur. Her örnekte vardır ve varsayılan olarak kapalıdır. Bu sayfa tek bir yazma işleminin bütün yolunu (durum, önizleme, bir insanın onayı, gönderme, denetim satırı), var olan dört yazma türünü ve yolda karşılaşabileceğiniz her reddi gösterir.
Yazmayı açıp açmamaya karar veriyorsanız önce Yazma nasıl çalışır sayfasını okuyun: riskleri açıkça söyler. Bu sayfa SDK yüzeyidir.
Neyin doğru olması gerekir
Üç anahtar; üçü de gerekir:
- Profil
writes.enabled: trueder. - Tür
writes.allowaltında listelenmiştir. - Örnek
allowWrites: falseile oluşturulmamıştır.
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 SDK'da varsayılan olarak true değerindedir, çünkü createSafran çağrısını bir profille yapan kod o profili seçmiştir. CLI ise adı verilmeyen, yalnızca çalışma dizininde bulduğu bir profil için false verir; o profilin eklentilerini yüklememesinin nedeni de aynıdır.
Önizleme, onay, gönderme
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-10Bu sayfadaki çıktılar, acme verisiyle Safran'ın bellek içi test bağlayıcılarıyla alındı; aşağıdaki bir pull request URL'sinde /fake/ bulunması bundandır. Sırasıyla olanlar:
status()çevrimdışıdır ve "kapalı" için asla hata fırlatmaz: bildirdiği şey budur; kararı veren anahtarreasoniçindedir.preview(intent)aşağıdaki denetimleri yaptı, var olduğunu kanıtlamak ve başlığını göstermek için iş kaydını okudu, profilinmarkersatırını ekledi, denetim günlüğüne birpreviewedsatırı yazdı ve birconfirmationTokendöndürdü. Jira'ya hiçbir şey gönderilmedi.- Bir insan onayladı. Bu adım size aittir. Token, kullanıcıdan korunacak bir sır değildir: görevi, bir önizlemenin yapıldığını ve gönderilenin tam olarak gösterilen şey olduğunu kanıtlamaktır.
commit(token)denetimleri yeniden yaptı (önizleme ile gönderme arasında yazma kapatılırsa kapatma kazanır), tek bir istek gönderdi ve denetim satırınıcommitteddurumuna taşıdı.
Yorum, iş takip sistemi token'ının ait olduğu hesap adına görünür. Safran sonradan onu düzenleyemez ya da silemez.
Dört tür
kind | Alanlar | Oluşturduğu | Bağlayıcı yeteneği |
|---|---|---|---|
ticket.comment | ticket, body | Bir iş kaydında tek bir yorum. | write:comment |
ticket.create_child | parent, title, description, isteğe bağlı type, labels | parent kaydının gerçek alt kaydı olarak, üst kaydın projesinde tek bir iş kaydı. | write:create-child |
pull_request.comment | pullRequest, body, isteğe bağlı path, line, side | Tek bir yeni yorum dizisi: bir satırda, bir dosyada ya da genel konuşmada. | write:pr-comment |
pull_request.reply | pullRequest, threadId, body | Var olan bir yorum dizisinde tek bir yorum. | write:pr-reply |
ticket ve parent, tickets.resolve çağrısının kabul ettiği iş kaydı referanslarıdır; pullRequest ise pulls.resolve çağrısının kabul ettiği pull request referansıdır. Gövdeler Markdown'dır; bağlayıcı bunları sistemin sakladığı biçime çevirir.
Bilerek sunulmayanlar: herhangi bir şeyi silmek, var olan bir gövdeyi düzenlemek, durum geçişleri, oylar, yorum dizisi çözmek, atanan kişi, tahmin ya da sprint değişiklikleri, dosya yükleme, toplu oluşturma. Oluşturulan alt kayıt bir başlık, bir açıklama, bir tür ve etiketler alır; başka hiçbir şey almaz.
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;
}tanımlandığı yer: packages/kit/src/writes.ts
Bir önizleme ne taşır
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"
}| Alan | Anlamı |
|---|---|
target | Yazma işleminin dokunacağı şey; referanstan çözülür: bağlayıcı girdisi (source), anahtar, URL ve önizleme anında okunan başlık. Yanıt için ayrıca yorum dizisi ve konumu. ticket.create_child için anahtar üst kayıttır. |
description | Bir insanın onaylayabileceği tek satır. Hedefin başlığını içerir; bu, üçüncü taraflara ait metindir. |
body | Harfi harfine gönderilecek gövde: sizin Markdown'ınız artı profilin işaret satırı. |
markerAdded | writes.marker eklendiyse true. |
title, ticketType, labels | Yalnızca ticket.create_child. ticketType yoksa iş takip sisteminin varsayılan alt kayıt türü kullanılır. |
possibleDuplicates | Yalnızca ticket.create_child: üst kaydın, başlığı çok benzeyen mevcut alt kayıtları. Ret değildir; sormak için bir nedendir. |
inReplyTo | Yalnızca pull_request.reply: yorum dizisini açan yorumun yazarı ve ilk DEFAULT_WRITE_REPLY_EXCERPT_CHARS (300) karakteri. Üçüncü taraflere ait metin. |
confirmationToken | Opak, tahmin edilemez, tek kullanımlık; bu örneğe ve tam olarak bu içeriğe bağlı. |
expiresAt | Önizlemeden DEFAULT_WRITE_CONFIRMATION_TTL_MS (10 dakika) sonra. |
Token'lar bellekte yaşar. Örneği kapatmak ya da süreci yeniden başlatmak her önizlemeyi geçersiz kılar; güvenli yön de budur. Aynı anda en çok DEFAULT_WRITE_MAX_PENDING_PREVIEWS (100) önizleme bekler; fazlasında en eskisi düşürülür.
Denetimler, sırasıyla
Yazabilen her metot aynı denetimleri yapar ve geçerli olan ilkiyle başarısız olur:
| # | Denetim | Başarısızlık |
|---|---|---|
| 1 | allowWrites, false değildir | FORBIDDEN: "Writes are turned off for this instance" |
| 2 | Profilde writes.enabled, true değerindedir | FORBIDDEN; ipucu writes.enabled anahtarını söyler |
| 3 | İsteğin türü writes.allow içindedir | FORBIDDEN; ipucu writes.allow anahtarını, türü ve şu an izin verilenleri söyler |
| 4 | Girdi geçerlidir | INVALID_INPUT: boş gövde, MAX_WRITE_BODY_CHARS değerini (işaret satırı dâhil 20.000 karakter) aşan gövde, MAX_WRITE_TITLE_CHARS (255) değerini aşan başlık, MAX_WRITE_LABELS (20) değerinden fazla etiket, path olmadan line |
| 5 | Hedef çözülür ve vardır | Referansın çözülmesinden gelen NOT_FOUND ya da INVALID_INPUT; pull request'te bulunmayan bir yorum dizisi kimliği için NOT_FOUND |
| 6 | Bağlayıcı write: yeteneğini listeler | UNSUPPORTED; bağlayıcının adıyla |
Fazla uzun bir gövde reddedilir, asla kesilmez. Denetim satırı saklanamıyorsa hiçbir şey gönderilmez.
commit ne yanıt verebilir
| Sonuç | Anlamı | Ne yapılır |
|---|---|---|
Bir WriteCommitResult | Yazma gerçekleşti. id yeni yorumdur (ya da yeni iş kaydının anahtarı, ya da yeni yorum dizisi), url ona giden bağlantı, auditId denetim satırıdır. | summary ve url değerlerini gösterin. |
CONFIRMATION_REQUIRED | Token bilinmiyor, süresi dolmuş ya da başka bir örneğe ait. Hiçbir şey gönderilmedi. | Yeniden önizleyin ve yeniden onay alın. |
CONFLICT | Token zaten kullanılmış. İpucu, oluşturduğu şeyi ve URL'sini taşır. Yeniden hiçbir şey gönderilmedi. | Hiçbir şey: yazılan şey zaten var. |
FORBIDDEN | Önizlemeden sonra yazma kapatıldı ya da tür allow listesinden çıkarıldı. | Hiçbir şey gönderilmedi. |
UPSTREAM, ABORTED, INTERNAL | İstek çıkmış olabilir ve sonucu bilinmiyor. İpucu, yazmanın gerçekleşmiş olabileceğini söyler ve hedefin adını verir. | Yeniden denemeden önce hedefe bakın. |
Başka herhangi bir kod (AUTH_FAILED, NOT_FOUND, INVALID_INPUT, …) | Bağlayıcı hayır dedi. Hiçbir şey oluşturulmadı. | Nedeni giderin, sonra yeniden önizleyin. |
Token, sonuç ne olursa olsun istek gönderildiği anda harcanır: başarısız bir gönderme yeni bir önizleme gerektirir. Yazma isteği HTTP istemcisi tarafından asla yeniden denenmez; böylece zaman aşımı, olası bir çift gönderim yerine UPSTREAM olarak görünür.
Betikler için tek adım
execute(intent), onayını başka yerde almış kodlar için (birinin gözden geçirdiği bir betik, bir CI işi) tek çağrıda önizler ve gönderir. Profilde writes.require_confirmation: true iken (varsayılan budur) CONFIRMATION_REQUIRED ile başarısız olur ve diğer yazma işlemleri gibi denetim günlüğüne geçer. MCP araçları bunu asla kullanmaz: bir ajan, profil ne derse desin her zaman önizleme ve gönderme adımlarından geçer.
Denetim günlüğü
log(query?), denetim satırlarını en yeniden eskiye döndürür. Yalnızca yerel depoyu okur (<dataDir>/safran.db içindeki write_audit) ve yazma kapalıyken de çalışır.
WriteLogQuery | Anlamı |
|---|---|
since | ISO tarihi; at için alt sınır (dâhil). |
kinds | Yalnızca bu türler. |
statuses | Yalnızca previewed, committed ya da failed. |
limit | Varsayılan DEFAULT_WRITE_LOG_LIMIT (50), en çok DEFAULT_MAX_WRITE_LOG_LIMIT (1.000). |
Bir satır türü, hedefi, durumu, önizlenen gövdenin SHA-256 özetini ve kimin istediğini (client; çağıran söylediyse) tutar. Gövdenin kendisi committed ve failed satırlarında, DEFAULT_WRITE_AUDIT_BODY_CHARS (2.000) karakterle sınırlı olarak saklanır; hiç gönderilmemiş bir önizleme yalnızca özeti tutar. safran writes log aynı satırları yazdırır (bkz. Yazma komutları).
/** 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;
}tanımlandığı yer: packages/core/src/api.ts
Salt okunur bir örnek
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`).Bunu, biri profili sonradan düzenlese bile yazmaması gereken her şey için kullanın: toplu bir iş, bir değerlendirme çalıştırması, başkalarının bağlandığı bir sunucu.
Arayüz
/**
* 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;
}tanımlandığı yer: packages/core/src/api.ts
Sık yapılan hatalar
- Önizlemeyi bir insana göstermeden göndermek. Çatı, gerçek bir onayı token'ı doğrudan geri veren bir döngüden ayıramaz. Önizleme okunmak için vardır.
- Onay sorusunu yalnızca
descriptionalanından kurmak.bodyalanını da gösterin: gönderilen şey odur; işaret satırı dâhil. - Başarısız bir göndermeyi aynı token'la yeniden denemek. Token harcanmıştır. Hedefe bakın, sonra yeniden önizleyin.
enabled: truedeğerinin her şeye izin vermesini beklemek. Boş birallowhiçbir şeye izin vermez.- Bir bağlayıcının
addCommentmetodunu doğrudan çağırmak.safran.writesdışında hiçbir şey birwrite:metodunu çağıramaz; çatıyı atlayan bir yazma işleminin önizlemesi, onayı ve denetim satırı olmaz. descriptioniçindeki başlığı talimat saymak. O, iş takip sisteminden ya da kod barındırıcıdan gelen metindir.