SPB Git

Repository Public

pipeline.ts 24.7 KB 283 lines typescript

1/**2 * Claude studio pipeline. Each exported function is one job kind run by the worker:3 *4 *   intake (validated brief) → extraction (attachments, links) → outline → generation → normalisation →5 *   schema validation (with repair rounds) → quality report → draft revision6 *7 * and, for an existing sheet: edit (structured patch) and translate. Nothing here publishes.8 * Model output is untrusted: it is parsed as JSON, normalised (the model cannot mark a source as checked, sign9 * as someone else, reference uploads or smuggle markup), validated against the schema, and only then stored.10 */11import type Anthropic from "@anthropic-ai/sdk";12import { z } from "zod";13import { sql } from "@/lib/db";14import { allBlocks, applyPatch, AUTHOR, diffSheets, mustParseSheet, parseSheet, PatchError, SCHEMA_VERSION, stableStringify, type Issue, type Locale, type PatchOp, type Sheet, type SheetDiff } from "@/schema";15import { getAssetRow, readAsset } from "@/server/assets";16import { qualityReport, type QualityReport } from "@/server/quality";17import { getSettings } from "@/server/settings";18import { createSheet, getSheetRow, saveDoc } from "@/server/sheets";19import { AiError, callClaude, type CallResult } from "./client";20import { htmlToText, NetError, safeFetch } from "./net";21import { BriefSchema, editTask, EditReplySchema, generateTask, materialNote, OutlineSchema, outlineTask, repairTask, systemPrompt, translateTask, type Brief, type Outline } from "./prompts";2223type Content = Anthropic.Beta.BetaContentBlockParam;24export interface JobCtx { jobId: string; userId: string | null; signal: AbortSignal; stage: (stage: string, progress?: Record<string, unknown>) => Promise<void> }2526const MAX_TEXT_CHARS = 400_000;       // per text attachment (~100k tokens)27const MAX_BINARY_BYTES = 24_000_000;  // PDFs and images of one request, before base642829// ── Extraction ──────────────────────────────────────────────────────────────────────────────────────3031/** Phrases that address an AI rather than a reader. Finding one changes nothing in the pipeline — the material is32 *  always treated as data — but the author is told, because it says something about the document. */33const INJECTION = [34  /ignore (all |any |the )?(previous|prior|above|earlier) (instructions|prompts|messages)/i, /disregard (all |the )?(previous|prior|above) /i,35  /(you are|act as|pretend to be) (now )?(an?|the) (ai|assistant|system|developer)/i, /system prompt/i, /<\/?(system|assistant|instructions?)>/i,36  /ignore[zs]? (toutes )?les instructions (précédentes|ci-dessus)/i, /oublie[zs]? (toutes )?(tes|vos|les) instructions/i,37  /(reveal|print|output|exfiltrate) (your|the) (instructions|system prompt|api key|secrets?)/i, /do not (tell|inform) the user/i,38];39export const scanInjection = (text: string): string[] => INJECTION.flatMap((re) => { const m = text.match(re); return m ? [m[0].slice(0, 80)] : []; });4041/** Closing tags inside the material cannot end our wrapper. */42const fence = (text: string) => text.replace(/<\/?source_material/gi, "<​source_material");4344export interface Extraction { content: Content[]; notes: string[]; warnings: string[] }4546export async function extractMaterial(brief: Pick<Brief, "attachments" | "urls">): Promise<Extraction> {47  const content: Content[] = [], notes: string[] = [], warnings: string[] = [];48  let binary = 0;49  for (const id of brief.attachments) {50    const a = await getAssetRow(id);51    if (!a || a.kind === "export") throw new AiError("bad_request", `Attachment ${id} was not found`);52    const data = await readAsset(a);53    if (a.kind === "pdf" || a.kind === "image") {54      binary += data.length;55      if (binary > MAX_BINARY_BYTES) throw new AiError("bad_request", "The attached PDFs and images are too large together (24 MB at most); attach fewer or smaller files");56      content.push({ type: "text", text: `<source_material name=${JSON.stringify(a.filename)} kind="${a.kind}">` });57      if (a.kind === "pdf") content.push({ type: "document", source: { type: "base64", media_type: "application/pdf", data: data.toString("base64") }, title: a.filename });58      else content.push({ type: "image", source: { type: "base64", media_type: a.mime as "image/png" | "image/jpeg" | "image/webp" | "image/gif", data: data.toString("base64") } });59      content.push({ type: "text", text: "</source_material>" });60    } else {61      const text = data.toString("utf8");62      if (text.length > MAX_TEXT_CHARS) throw new AiError("bad_request", `“${a.filename}” is too long to be read in full (${text.length.toLocaleString("en")} characters, limit ${MAX_TEXT_CHARS.toLocaleString("en")}); shorten it or split it`);63      for (const hit of scanInjection(text)) warnings.push(`“${a.filename}” contains text addressed to an AI (“${hit}”); it was handled as plain content.`);64      content.push({ type: "text", text: `<source_material name=${JSON.stringify(a.filename)} kind="${a.kind}">\n${fence(text)}\n</source_material>` });65    }66    notes.push(`${a.filename} (${a.kind})`);67  }68  for (const url of brief.urls) {69    let page;70    try { page = await safeFetch(url, { maxBytes: 3_000_000, accept: "text/html,text/plain;q=0.9" }); }71    catch (e) { throw new AiError("bad_request", `The link ${url} could not be fetched: ${e instanceof NetError ? e.message : "network error"}`); }72    if (page.status !== 200) throw new AiError("bad_request", `The link ${url} answered HTTP ${page.status}`);73    if (!/^text\/(html|plain)/i.test(page.contentType)) throw new AiError("bad_request", `The link ${url} is not a web page or text (${page.contentType || "unknown type"}); upload the file instead`);74    const raw = page.body.toString("utf8");75    const { title, text } = /html/i.test(page.contentType) ? htmlToText(raw) : { title: "", text: raw };76    if (text.length > MAX_TEXT_CHARS) throw new AiError("bad_request", `The page ${url} is too long to be read in full; upload the relevant part as a text file`);77    for (const hit of scanInjection(text)) warnings.push(`The page ${url} contains text addressed to an AI (“${hit}”); it was handled as plain content.`);78    content.push({ type: "text", text: `<source_material url=${JSON.stringify(page.url)} title=${JSON.stringify(title)} kind="web page">\n${fence(text)}\n</source_material>` });79    notes.push(page.url);80  }81  if (content.length) content.unshift({ type: "text", text: materialNote });82  return { content, notes, warnings };83}8485// ── JSON out of the model ───────────────────────────────────────────────────────────────────────────8687/** The model is asked for bare JSON; a stray code fence or sentence around it is tolerated, nothing else. */88export function extractJson(text: string): unknown {89  const t = text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");90  try { return JSON.parse(t); } catch { /* fall through */ }91  const start = t.search(/[{[]/), end = Math.max(t.lastIndexOf("}"), t.lastIndexOf("]"));92  if (start >= 0 && end > start) { try { return JSON.parse(t.slice(start, end + 1)); } catch { /* fall through */ } }93  throw new AiError("invalid_output", "The model did not return JSON");94}9596/**97 * What the model may not decide, whatever it wrote: the author, the schema version, that a source "was checked",98 * references to uploads, the example flag, cross-block interactions.99 */100export function normalizeModelDoc(raw: unknown, force: { locale: Locale; keepAssets?: Sheet["assets"] }): unknown {101  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return raw;102  const d = structuredClone(raw) as Record<string, unknown>;103  d.schemaVersion = SCHEMA_VERSION;104  d.interactions = [];105  d.assets = force.keepAssets ?? [];106  const meta = (d.metadata && typeof d.metadata === "object" ? d.metadata : {}) as Record<string, unknown>;107  meta.author = AUTHOR; meta.locale = force.locale; delete meta.example; delete meta.slug;108  d.metadata = meta;109  if (Array.isArray(d.sources)) d.sources = d.sources.map((s) => (s && typeof s === "object" ? (({ checkedAt: _c, ...rest }) => ({ ...rest, status: "unverified" }))(s as Record<string, unknown>) : s));110  const allowed = new Set((force.keepAssets ?? []).map((a) => a.id));111  const dropImages = (list: unknown): unknown => (Array.isArray(list) ? list.filter((b) => !(b && typeof b === "object" && (b as { type?: string }).type === "image" && !allowed.has(String((b as { assetRef?: string }).assetRef)))) : list);112  d.blocks = dropImages(d.blocks);113  if (Array.isArray(d.blocks)) for (const b of d.blocks as Record<string, unknown>[]) if (b?.type === "tabs" && Array.isArray(b.tabs)) for (const t of b.tabs as Record<string, unknown>[]) t.blocks = dropImages(t.blocks);114  return d;115}116117interface Tally { calls: number; inputTokens: number; outputTokens: number; costUsd: number; model: string | null }118const tally = (): Tally => ({ calls: 0, inputTokens: 0, outputTokens: 0, costUsd: 0, model: null });119const add = (t: Tally, r: CallResult) => { t.calls++; t.inputTokens += r.usage.inputTokens; t.outputTokens += r.usage.outputTokens; t.costUsd += r.usage.costUsd; t.model = r.model; };120121/**122 * Asks for a JSON value and validates it; when validation fails the problems are sent back, at most twice.123 * `check` returns the accepted value or the list of issues.124 */125async function askJson<T>(ctx: JobCtx, stage: string, effort: "low" | "medium" | "high" | "xhigh" | "max", first: Content[], check: (v: unknown) => { ok: true; value: T } | { ok: false; issues: Issue[] }, t: Tally, maxTokens?: number): Promise<T> {126  const messages: Anthropic.Beta.BetaMessageParam[] = [{ role: "user", content: first }];127  for (let round = 0; ; round++) {128    await ctx.stage(round === 0 ? stage : `${stage}.repair`, { round, chars: 0 });129    let last = 0;130    const r = await callClaude({ stage: round === 0 ? stage : `${stage}.repair`, jobId: ctx.jobId, system: systemPrompt(), messages, effort, maxTokens, signal: ctx.signal,131      onProgress: (chars) => { if (chars - last > 1500) { last = chars; void ctx.stage(round === 0 ? stage : `${stage}.repair`, { round, chars }); } } });132    add(t, r);133    let issues: Issue[];134    try { const res = check(extractJson(r.text)); if (res.ok) return res.value; issues = res.issues; }135    catch (e) { if (!(e instanceof AiError) || e.code !== "invalid_output") throw e; issues = [{ path: "", message: "The reply was not a single JSON value." }]; }136    if (round >= 2) throw new AiError("invalid_output", `The model's output did not pass validation after ${round + 1} attempts: ${issues.slice(0, 5).map((i) => `${i.path}: ${i.message}`).join("; ")}`);137    messages.push({ role: "assistant", content: r.text }, { role: "user", content: repairTask(issues) });138  }139}140141const zodCheck = <T>(schema: z.ZodType<T>) => (v: unknown) => { const r = schema.safeParse(v); return r.success ? { ok: true as const, value: r.data } : { ok: false as const, issues: r.error.issues.slice(0, 40).map((i) => ({ path: i.path.join("."), message: i.message })) }; };142143// ── Jobs ────────────────────────────────────────────────────────────────────────────────────────────144145export interface OutlineOutput { outline: Outline; material: string[]; warnings: string[]; usage: Tally; estimate: { blocks: number; outputTokens: number } }146147export async function runOutline(ctx: JobCtx, input: unknown): Promise<OutlineOutput> {148  const brief = BriefSchema.parse((input as { brief: unknown }).brief);149  await ctx.stage("extract");150  const material = await extractMaterial(brief);151  const t = tally();152  const outline = await askJson(ctx, "outline", "medium", [...material.content, { type: "text", text: outlineTask(brief) }], zodCheck(OutlineSchema), t, 8000);153  const blocks = outline.sections.reduce((n, s) => n + s.blocks.length + 1, 2);154  return { outline, material: material.notes, warnings: material.warnings, usage: t, estimate: { blocks, outputTokens: blocks * 450 } };155}156157export interface GenerateOutput { sheetId: string; revisionId: string; revisionNumber: number; quality: QualityReport; material: string[]; warnings: string[]; usage: Tally }158159export async function runGenerate(ctx: JobCtx, input: unknown): Promise<GenerateOutput> {160  const p = z.object({ brief: BriefSchema, outline: OutlineSchema.nullable().default(null) }).parse(input);161  // A restarted job must not create a second sheet.162  const [done] = await sql<{ id: string; sheet_id: string; number: number }[]>`SELECT id, sheet_id, number FROM sheet_revisions WHERE job_id = ${ctx.jobId} LIMIT 1`;163  if (done) return { sheetId: done.sheet_id, revisionId: done.id, revisionNumber: done.number, quality: qualityReport(mustParseSheet((await getSheetRow(done.sheet_id)).doc)), material: [], warnings: [], usage: tally() };164165  await ctx.stage("extract");166  const material = await extractMaterial(p.brief);167  const t = tally();168  const settings = await getSettings();169  const doc = await askJson(ctx, "generate", settings.aiEffortGenerate, [...material.content, { type: "text", text: generateTask(p.brief, p.outline) }],170    (v) => { const r = parseSheet(normalizeModelDoc(v, { locale: p.brief.locale })); return r.ok ? { ok: true as const, value: r.sheet } : { ok: false as const, issues: r.issues }; }, t);171  await ctx.stage("validate");172  const quality = qualityReport(doc);173  await ctx.stage("save");174  const created = await createSheet({ doc, origin: "ai_generation", userId: ctx.userId, summary: p.brief.prompt.slice(0, 300), jobId: ctx.jobId });175  const row = await getSheetRow(created.id);176  // The conversation of the new sheet starts with the request that created it.177  const [conv] = await sql<{ id: string }[]>`INSERT INTO ai_conversations (sheet_id, created_by) VALUES (${created.id}, ${ctx.userId}) ON CONFLICT (sheet_id) DO UPDATE SET sheet_id = EXCLUDED.sheet_id RETURNING id`;178  await sql`INSERT INTO ai_messages (conversation_id, role, content, job_id) VALUES (${conv.id}, 'user', ${p.brief.prompt}, ${ctx.jobId})`;179  await sql`INSERT INTO ai_messages (conversation_id, role, content, job_id, revision_id) VALUES (${conv.id}, 'assistant', ${p.brief.locale === "fr" ? `Fiche générée : ${doc.blocks.length} blocs, ${doc.sources.length} sources à vérifier.` : `Sheet generated: ${doc.blocks.length} blocks, ${doc.sources.length} sources to check.`}, ${ctx.jobId}, ${row.current_revision_id})`;180  await sql`UPDATE generation_jobs SET sheet_id = ${created.id} WHERE id = ${ctx.jobId}`;181  return { sheetId: created.id, revisionId: row.current_revision_id, revisionNumber: 1, quality, material: material.notes, warnings: material.warnings, usage: t };182}183184export interface EditOutput { changed: boolean; summary: string; revisionId: string | null; revisionNumber: number | null; version: number; diff: SheetDiff | null; quality: QualityReport | null; usage: Tally }185186/** Blocks an operation touches, to enforce "only the selected blocks". */187const touched = (op: PatchOp): string[] => (op.op === "replace_block" || op.op === "remove_block" || op.op === "move_block" ? [op.id] : []);188189export async function runEdit(ctx: JobCtx, input: unknown, sheetId: string): Promise<EditOutput> {190  const p = z.object({ instruction: z.string().min(2).max(4000), baseVersion: z.number().int(), scope: z.array(z.string()).max(40).nullable().default(null) }).parse(input);191  const row = await getSheetRow(sheetId);192  // A restarted job whose revision was already written reports it instead of failing on the version check.193  const [done] = await sql<{ id: string; number: number; patch: PatchOp[] | null }[]>`SELECT id, number, patch FROM sheet_revisions WHERE job_id = ${ctx.jobId} LIMIT 1`;194  if (done) return { changed: true, summary: "", revisionId: done.id, revisionNumber: done.number, version: row.version, diff: null, quality: qualityReport(mustParseSheet(row.doc)), usage: tally() };195  // The patch is computed against the version the author was looking at; if the sheet moved on, the job stops.196  if (row.version !== p.baseVersion) throw new AiError("bad_request", "The sheet changed after this request was sent; send it again");197  const doc = mustParseSheet(row.doc);198  const locked = allBlocks(doc).filter((b) => b.locked).map((b) => b.id);199  const scope = p.scope?.length ? p.scope : null;200  const t = tally();201  const settings = await getSettings();202203  const reply = await askJson(ctx, "edit", settings.aiEffortEdit, [{ type: "text", text: editTask(stableStringify(doc), p.instruction, scope, locked) }], (v) => {204    const r = EditReplySchema.safeParse(v);205    if (!r.success) return { ok: false as const, issues: r.error.issues.slice(0, 40).map((i) => ({ path: i.path.join("."), message: i.message })) };206    // Whatever the model returns, the document keeps its language and assets, and nothing becomes "checked".207    const ops = r.data.ops.map((op): PatchOp => (op.op === "upsert_source" ? { ...op, source: { ...op.source, status: doc.sources.find((s) => s.id === op.source.id && s.doi === op.source.doi && s.url === op.source.url && s.title === op.source.title)?.status ?? "unverified", checkedAt: undefined } }208      : op.op === "set_metadata" ? { ...op, metadata: (({ locale: _l, example: _e, slug: _s, ...m }) => m)(op.metadata) } : op));209    if (scope) {210      // A scoped request may rewrite the selected blocks, add blocks next to them and add the sources they cite.211      const outside = ops.flatMap(touched).filter((id) => !scope.includes(id));212      if (outside.length) return { ok: false as const, issues: [{ path: "ops", message: `Only the selected blocks may be changed; these are outside the selection: ${[...new Set(outside)].join(", ")}` }] };213      const tabsInScope = new Set(doc.blocks.flatMap((b) => (b.type === "tabs" && scope.includes(b.id) ? b.tabs.map((t) => t.id) : [])));214      const inserted = new Set(ops.flatMap((op) => (op.op === "insert_block" ? [op.block.id] : [])));215      for (const op of ops) {216        if (op.op === "insert_block" && !(op.afterId !== null && (scope.includes(op.afterId) || inserted.has(op.afterId))) && !(op.tabId && tabsInScope.has(op.tabId))) return { ok: false as const, issues: [{ path: "ops", message: "With a selection, new blocks must be inserted right after a selected block." }] };217        if (op.op === "set_metadata" || op.op === "set_theme" || op.op === "remove_source" || op.op === "set_claims") return { ok: false as const, issues: [{ path: "ops", message: `With a selection, "${op.op}" is not allowed: change only the selected blocks.` }] };218      }219    }220    if (ops.some((op) => (op.op === "replace_block" || op.op === "insert_block") && JSON.stringify(op.block).includes('"type":"image"') && !doc.assets.some((a) => JSON.stringify(op.block).includes(`"assetRef":"${a.id}"`)))) return { ok: false as const, issues: [{ path: "ops", message: "Image blocks can only reference existing assets of this sheet." }] };221    try { return { ok: true as const, value: { summary: r.data.summary, ops, next: applyPatch(doc, ops, { respectLocks: true }) } }; }222    catch (e) { if (e instanceof PatchError) return { ok: false as const, issues: [{ path: `ops.${e.opIndex}`, message: e.message }] }; throw e; }223  }, t);224225  const [conv] = await sql<{ id: string }[]>`INSERT INTO ai_conversations (sheet_id, created_by) VALUES (${sheetId}, ${ctx.userId}) ON CONFLICT (sheet_id) DO UPDATE SET sheet_id = EXCLUDED.sheet_id RETURNING id`;226  const [already] = await sql`SELECT 1 FROM ai_messages WHERE job_id = ${ctx.jobId} AND role = 'user'`;227  if (!already) await sql`INSERT INTO ai_messages (conversation_id, role, content, job_id) VALUES (${conv.id}, 'user', ${p.instruction}, ${ctx.jobId})`;228229  const diff = diffSheets(doc, reply.next);230  if (reply.ops.length === 0 || stableStringify(doc) === stableStringify(reply.next)) {231    await sql`INSERT INTO ai_messages (conversation_id, role, content, job_id) VALUES (${conv.id}, 'assistant', ${reply.summary}, ${ctx.jobId})`;232    return { changed: false, summary: reply.summary, revisionId: null, revisionNumber: null, version: row.version, diff: null, quality: null, usage: t };233  }234  await ctx.stage("save");235  const saved = await saveDoc({ sheetId, doc: reply.next, expectedVersion: p.baseVersion, origin: "ai_edit", summary: p.instruction.slice(0, 300), patch: reply.ops, jobId: ctx.jobId, userId: ctx.userId });236  await sql`INSERT INTO ai_messages (conversation_id, role, content, job_id, revision_id, diff) VALUES (${conv.id}, 'assistant', ${reply.summary}, ${ctx.jobId}, ${saved.revisionId}, ${sql.json(diff as never)})`;237  return { changed: true, summary: reply.summary, revisionId: saved.revisionId, revisionNumber: saved.revisionNumber, version: saved.version, diff, quality: saved.quality, usage: t };238}239240export interface TranslateOutput { sheetId: string; locale: Locale; quality: QualityReport; usage: Tally }241242/** Same skeleton in another language: ids, order, types, numbers and sources must survive the translation. */243function sameSkeleton(a: Sheet, b: Sheet): Issue[] {244  const issues: Issue[] = [];245  const A = allBlocks(a), B = allBlocks(b);246  if (A.length !== B.length) issues.push({ path: "blocks", message: `Expected ${A.length} blocks, got ${B.length}.` });247  A.forEach((x, i) => { const y = B[i]; if (y && (x.id !== y.id || x.type !== y.type)) issues.push({ path: `blocks.${i}`, message: `Expected block ${x.id} (${x.type}), got ${y.id} (${y.type}).` }); });248  A.forEach((x, i) => {249    const y = B[i]; if (!y || x.type !== y.type) return;250    if (x.type === "equation" && y.type === "equation" && x.latex !== y.latex) issues.push({ path: `blocks.${i}.latex`, message: `LaTeX of ${x.id} must not change.` });251    if (x.type === "chart" && y.type === "chart" && stableStringify(x.series.map((s) => s.points)) !== stableStringify(y.series.map((s) => s.points))) issues.push({ path: `blocks.${i}.series`, message: `Data points of ${x.id} must not change.` });252    if (x.type === "matrix" && y.type === "matrix" && stableStringify(x.values) !== stableStringify(y.values)) issues.push({ path: `blocks.${i}.values`, message: `Values of ${x.id} must not change.` });253    if (x.type === "diagram" && y.type === "diagram" && (x.nodes.map((n) => n.id).join() !== y.nodes.map((n) => n.id).join() || x.edges.map((e) => e.id + e.from + e.to).join() !== y.edges.map((e) => e.id + e.from + e.to).join())) issues.push({ path: `blocks.${i}`, message: `Nodes and edges of ${x.id} must keep their ids and endpoints.` });254    if (x.type === "simulation" && y.type === "simulation" && (x.kind !== y.kind || x.seed !== y.seed || stableStringify(x.params) !== stableStringify(y.params))) issues.push({ path: `blocks.${i}`, message: `Simulation ${x.id} must keep its kind, seed and parameters.` });255  });256  return issues.slice(0, 30);257}258259export async function runTranslate(ctx: JobCtx, input: unknown, sheetId: string): Promise<TranslateOutput> {260  const p = z.object({ targetLocale: z.enum(["fr", "en"]) }).parse(input);261  const [done] = await sql<{ sheet_id: string }[]>`SELECT sheet_id FROM sheet_revisions WHERE job_id = ${ctx.jobId} LIMIT 1`;262  if (done) { const d = mustParseSheet((await getSheetRow(done.sheet_id)).doc); return { sheetId: done.sheet_id, locale: p.targetLocale, quality: qualityReport(d), usage: tally() }; }263  const row = await getSheetRow(sheetId);264  if (row.locale === p.targetLocale) throw new AiError("bad_request", "The sheet is already in that language");265  const [exists] = await sql`SELECT 1 FROM sheets WHERE localization_id = ${row.localization_id} AND locale = ${p.targetLocale} AND deleted_at IS NULL`;266  if (exists) throw new AiError("bad_request", "A version in that language already exists");267  const doc = mustParseSheet(row.doc);268  const t = tally();269  const settings = await getSettings();270  const translated = await askJson(ctx, "translate", settings.aiEffortEdit, [{ type: "text", text: translateTask(stableStringify(doc), p.targetLocale) }], (v) => {271    const n = normalizeModelDoc(v, { locale: p.targetLocale, keepAssets: doc.assets }) as Record<string, unknown>;272    // References are copied from the original, not from the model: a translation cannot alter or "verify" them.273    n.sources = doc.sources; n.theme = doc.theme; n.layout = doc.layout;274    const r = parseSheet(n);275    if (!r.ok) return { ok: false as const, issues: r.issues };276    const issues = sameSkeleton(doc, r.sheet);277    return issues.length ? { ok: false as const, issues } : { ok: true as const, value: { ...r.sheet, metadata: { ...r.sheet.metadata, example: doc.metadata.example } } };278  }, t);279  await ctx.stage("save");280  const created = await createSheet({ doc: translated, origin: "ai_generation", userId: ctx.userId, summary: `Traduction (${row.locale} → ${p.targetLocale})`, localizationId: row.localization_id, jobId: ctx.jobId });281  return { sheetId: created.id, locale: p.targetLocale, quality: qualityReport(translated), usage: t };282}283
Files main
Menu

Theme