Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(content): write the Content Agent's runs step by step and stop them (CE-027, CE-035, server) (#1400)

Cihan6a32d9cf5d99
diff --git a/server/src/lib/content-agent.js b/server/src/lib/content-agent.js
index 35c6d4d0e..7e7688891 100644
--- a/server/src/lib/content-agent.js
+++ b/server/src/lib/content-agent.js
@@ -7,6 +7,15 @@ import { resolveModel } from './ai-provider.js';
import { contentBriefModelId, rebuildSources } from './content-brief.js';
import { linkAllowList, linkKey, linkTargetsPrompt, readLinkTargets } from './content-links.js';
import { pageTypeFormat } from './content-page-types.js';
+import {
+ RunStoppedError,
+ advanceRun,
+ finishRun,
+ isStop,
+ runCall,
+ startRun,
+ stopIfStopped,
+} from './content-runs.js';
import {
SOURCES_RULE,
htmlText,
@@ -614,12 +623,45 @@ export async function fixDraftRules({ draftId, brandId, input }) {
.single();
if (brandError) throw brandError;
+ // Its steps, named by the work it does (CE-027/035); Stop aborts the call.
+ const sources = input.sources;
+ const run = await startRun({
+ draftId,
+ kind: 'fix',
+ counts: {
+ rules: input.rules.length,
+ sources: sources
+ ? sources.promptIds.length +
+ sources.fanouts.length +
+ sources.pages.length +
+ sources.queries.length
+ : 0,
+ },
+ });
+ try {
+ const result = await fixWithRun({ draft, brand, brandId, draftId, input, passages, more, run });
+ await finishRun(run, 'done', { 2: result.count });
+ return result;
+ } catch (err) {
+ if (isStop(err, run)) {
+ await finishRun(run, 'stopped');
+ throw new RunStoppedError();
+ }
+ await finishRun(run, 'failed');
+ throw err;
+ }
+}
+
+/** Fix open rules' run itself, step by step: nothing is kept once it is stopped. */
+async function fixWithRun({ draft, brand, brandId, draftId, input, passages, more, run }) {
const modelId = contentBriefModelId();
const lockedKeys = new Set(input.locked.map(passageKey));
const ruleKeys = new Set(input.rules.map((r) => r.key));
// The data it writes from, numbered; the numbers it may write unmarked.
+ await advanceRun(run, 1);
+ const prompts = await readPrompts(brandId, input.sources?.promptIds ?? []);
const numbered = numberSources({
- prompts: await readPrompts(brandId, input.sources?.promptIds ?? []),
+ prompts,
fanouts: input.sources?.fanouts,
pages: input.sources?.pages,
queries: input.sources?.queries,
@@ -649,22 +691,25 @@ export async function fixDraftRules({ draftId, brandId, input }) {
});
let object;
try {
- const generated = await generateObject({
- model: resolveModel(modelId),
- schema: suggestionsSchema,
- system: SYSTEM_PROMPT,
- prompt: buildFixPrompt({
- brand,
- draft,
- passages,
- more,
- lockedKeys,
- input,
- linkTargets: linkTargetsPrompt(targets, ruleKeys),
- sources: sourcesPrompt(numbered),
+ await advanceRun(run, 2);
+ const generated = await runCall(run, budget, CALL_TIMEOUT_MS, (abortSignal) =>
+ generateObject({
+ model: resolveModel(modelId),
+ schema: suggestionsSchema,
+ system: SYSTEM_PROMPT,
+ prompt: buildFixPrompt({
+ brand,
+ draft,
+ passages,
+ more,
+ lockedKeys,
+ input,
+ linkTargets: linkTargetsPrompt(targets, ruleKeys),
+ sources: sourcesPrompt(numbered),
+ }),
+ abortSignal,
}),
- abortSignal: AbortSignal.timeout(CALL_TIMEOUT_MS),
- });
+ );
await budget.charge(generated.usage);
object = generated.object;
} catch (err) {
@@ -677,6 +722,7 @@ export async function fixDraftRules({ draftId, brandId, input }) {
await budget.release();
}
+ await advanceRun(run, 3);
const rows = keepSuggestions(
object.suggestions,
passages,
@@ -685,6 +731,8 @@ export async function fixDraftRules({ draftId, brandId, input }) {
linkAllowList(targets),
{ numbered, known },
);
+ // Stopped meanwhile: nothing it wrote is kept.
+ await stopIfStopped(run);
if (!rows.length) return { count: 0, batchId: null };
const batchId = randomUUID();
diff --git a/server/src/lib/content-agent.test.js b/server/src/lib/content-agent.test.js
index e869ab2fe..03d40a396 100644
--- a/server/src/lib/content-agent.test.js
+++ b/server/src/lib/content-agent.test.js
@@ -48,6 +48,11 @@ vi.mock('./plan-guard.js', async (importOriginal) => ({
reserveAiBudget: (...args) => reserveAiBudget(...args),
}));
vi.mock('./logger.js', () => ({ logger: { error: vi.fn(), warn: vi.fn() } }));
+const stopIfStopped = vi.fn();
+vi.mock('./content-runs.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ stopIfStopped: (...args) => stopIfStopped(...args),
+}));
const readLinkTargets = vi.fn();
vi.mock('./content-links.js', async (importOriginal) => ({
...(await importOriginal()),
@@ -114,6 +119,7 @@ const SOURCES = {
const sourcing = { numbered: numberSources(SOURCES) };
beforeEach(() => {
+ stopIfStopped.mockReset().mockResolvedValue(undefined);
writes = [];
rows = {
content_drafts: {
@@ -780,6 +786,21 @@ describe('fixDraftRules', () => {
);
});
+ it('keeps nothing once stopped, and says so (CE-027)', async () => {
+ const { RunStoppedError } = await import('./content-runs.js');
+ stopIfStopped.mockRejectedValueOnce(new RunStoppedError());
+ generateObject.mockResolvedValue({
+ object: { suggestions: [suggestion()] },
+ usage: { inputTokens: 900, outputTokens: 200 },
+ });
+ await expect(
+ fixDraftRules({ draftId: DRAFT, brandId: BRAND, input: input({ sources: SOURCES }) }),
+ ).rejects.toMatchObject({ status: 409, code: 'stopped' });
+ expect(writes.find((w) => w.table === 'content_draft_suggestions')).toBeUndefined();
+ // The call it made is still charged: the provider billed it.
+ expect(writes.find((w) => w.table === 'prompt_improve_usage')).toBeDefined();
+ });
+
it('keeps nothing when the agent found nothing it could change', async () => {
generateObject.mockResolvedValue({ object: { suggestions: [] }, usage: {} });
await expect(
diff --git a/server/src/lib/content-brief.js b/server/src/lib/content-brief.js
index 09a4ddbf7..d32e52543 100644
--- a/server/src/lib/content-brief.js
+++ b/server/src/lib/content-brief.js
@@ -4,6 +4,15 @@ import supabaseAdmin from '../config/supabase.js';
import { resolveModel } from './ai-provider.js';
import { pageTypeFormat } from './content-page-types.js';
import { getLanguageName } from './languages.js';
+import {
+ RunStoppedError,
+ advanceRun,
+ finishRun,
+ isStop,
+ runCall,
+ startRun,
+ stopIfStopped,
+} from './content-runs.js';
import { reserveAiBudget } from './plan-guard.js';
/**
@@ -164,6 +173,31 @@ export async function rebuildDraftBrief({ draftId, brandId, sources }) {
});
}
+ // Its steps, named by the data it reads (CE-027/035); Stop aborts the call.
+ const run = await startRun({
+ draftId,
+ kind: 'brief',
+ counts: {
+ sources:
+ prompts.length + sources.fanouts.length + sources.pages.length + sources.queries.length,
+ },
+ });
+ try {
+ const brief = await briefWithRun({ draft, draftId, brand, prompts, sources, run });
+ await finishRun(run, 'done');
+ return brief;
+ } catch (err) {
+ if (isStop(err, run)) {
+ await finishRun(run, 'stopped');
+ throw new RunStoppedError();
+ }
+ await finishRun(run, 'failed');
+ throw err;
+ }
+}
+
+/** The rebuild itself, step by step: nothing is saved once it is stopped. */
+async function briefWithRun({ draft, draftId, brand, prompts, sources, run }) {
const modelId = contentBriefModelId();
// Held on the budget before the call, so calls at once can't pass it.
const budget = await reserveAiBudget(brand.organization_id, {
@@ -174,13 +208,16 @@ export async function rebuildDraftBrief({ draftId, brandId, sources }) {
let generated;
try {
- generated = await generateObject({
- model: resolveModel(modelId),
- schema: outlineSchema,
- system: SYSTEM_PROMPT,
- prompt: buildBriefPrompt({ brand, draft, prompts, sources }),
- abortSignal: AbortSignal.timeout(CALL_TIMEOUT_MS),
- });
+ await advanceRun(run, 1);
+ generated = await runCall(run, budget, CALL_TIMEOUT_MS, (abortSignal) =>
+ generateObject({
+ model: resolveModel(modelId),
+ schema: outlineSchema,
+ system: SYSTEM_PROMPT,
+ prompt: buildBriefPrompt({ brand, draft, prompts, sources }),
+ abortSignal,
+ }),
+ );
await budget.charge(generated.usage);
} catch (err) {
// An answer that didn't fit the schema was still paid for: charged as
@@ -192,6 +229,8 @@ export async function rebuildDraftBrief({ draftId, brandId, sources }) {
await budget.release();
}
const { object } = generated;
+ // Each H2 matched to the fan-out it answers (mapOutline).
+ await advanceRun(run, 2);
const brief = {
goal: object.goal.trim().slice(0, BRIEF_LIMITS.goal),
@@ -211,6 +250,8 @@ export async function rebuildDraftBrief({ draftId, brandId, sources }) {
queries: sources.queries.length,
},
};
+ // Stopped meanwhile: the brief stays as it was.
+ await stopIfStopped(run);
const { error: saveError } = await supabaseAdmin
.from('content_drafts')
.update({ brief })
diff --git a/server/src/lib/content-brief.test.js b/server/src/lib/content-brief.test.js
index 83a80868e..50a290b0b 100644
--- a/server/src/lib/content-brief.test.js
+++ b/server/src/lib/content-brief.test.js
@@ -35,6 +35,8 @@ vi.mock('../config/supabase.js', () => ({
},
},
}));
+/** The writes but the run's own steps (content_agent_runs, 00249). */
+const draftWrites = () => writes.filter((w) => w.table !== 'content_agent_runs');
class NoObjectGeneratedError extends Error {
static isInstance(err) {
return err instanceof NoObjectGeneratedError;
@@ -49,7 +51,12 @@ vi.mock('./plan-guard.js', async (importOriginal) => ({
...(await importOriginal()),
reserveAiBudget: (...args) => reserveAiBudget(...args),
}));
-vi.mock('./logger.js', () => ({ logger: { error: vi.fn() } }));
+vi.mock('./logger.js', () => ({ logger: { error: vi.fn(), warn: vi.fn() } }));
+const stopIfStopped = vi.fn();
+vi.mock('./content-runs.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ stopIfStopped: (...args) => stopIfStopped(...args),
+}));
const { buildBriefPrompt, mapOutline, rebuildDraftBrief, rebuildSources } =
await import('./content-brief.js');
@@ -87,6 +94,7 @@ const outline = [
];
beforeEach(() => {
+ stopIfStopped.mockReset().mockResolvedValue(undefined);
writes = [];
filters = [];
rows = {
@@ -163,7 +171,7 @@ describe('rebuildDraftBrief', () => {
{ heading: 'Care', keyPoints: [], fanout: null, platform: null },
]);
- expect(writes).toEqual([
+ expect(draftWrites()).toEqual([
{
table: 'prompt_improve_usage',
op: 'insert',
@@ -259,6 +267,16 @@ describe('rebuildDraftBrief', () => {
expect(brief.keywords.every((k) => k.length <= 80)).toBe(true);
});
+ it('saves nothing once stopped, and says so (CE-027)', async () => {
+ const { RunStoppedError } = await import('./content-runs.js');
+ stopIfStopped.mockRejectedValueOnce(new RunStoppedError());
+ await expect(
+ rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() }),
+ ).rejects.toMatchObject({ status: 409, code: 'stopped' });
+ // The call was made and charged; the brief stays as it was.
+ expect(draftWrites().filter((w) => w.table === 'content_drafts')).toEqual([]);
+ });
+
it('charges a call whose answer didn’t fit, then fails', async () => {
generateObject.mockRejectedValue(
Object.assign(new NoObjectGeneratedError('no object'), {
@@ -268,7 +286,7 @@ describe('rebuildDraftBrief', () => {
await expect(
rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() }),
).rejects.toBeInstanceOf(NoObjectGeneratedError);
- expect(writes).toEqual([
+ expect(draftWrites()).toEqual([
expect.objectContaining({
table: 'prompt_improve_usage',
op: 'insert',
@@ -294,7 +312,7 @@ describe('rebuildDraftBrief', () => {
rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() }),
).rejects.toBeInstanceOf(PlanLimitError);
expect(generateObject).not.toHaveBeenCalled();
- expect(writes).toEqual([]);
+ expect(draftWrites()).toEqual([]);
});
});
diff --git a/server/src/lib/content-runs.js b/server/src/lib/content-runs.js
new file mode 100644
index 000000000..a36cf94c5
--- /dev/null
+++ b/server/src/lib/content-runs.js
@@ -0,0 +1,234 @@
+import supabaseAdmin from '../config/supabase.js';
+import { logger } from './logger.js';
+
+/**
+ * The Content Agent's runs, step by step (Content Editor v1.1, CE-027 and
+ * CE-035; content_agent_runs, 00249): each run says its steps as it reaches
+ * them, named by the data they use, so the editor shows real progress; and a
+ * person can Stop it, which drops whatever the run had and changes nothing.
+ *
+ * A step written here is shown, never relied on: a failed write is logged
+ * and the run goes on. Stop is the run's own business: the request that
+ * stops it aborts the model call when the run is on this server, and the
+ * run checks the stopped mark before it keeps anything.
+ */
+
+/** Thrown when a run was stopped: nothing it had is kept. */
+export class RunStoppedError extends Error {
+ constructor() {
+ super('The run was stopped');
+ this.status = 409;
+ this.code = 'stopped';
+ }
+}
+
+/**
+ * How long a run may be under way: the longest model call (three minutes,
+ * content-writer.js) and a margin. One older was left by a server that
+ * stopped: never shown, stopped or waited on (agent-runs.ts RUN_STALE_MS).
+ */
+export const RUN_STALE_MS = 10 * 60_000;
+
+/** The runs on this server, by id: Stop aborts their model call. */
+const live = new Map();
+
+/** A write a run's progress may do without: logged when it fails, never thrown. */
+async function shown(what, runId, write) {
+ try {
+ const { data, error } = await write();
+ if (error) throw error;
+ return data;
+ } catch (err) {
+ logger.warn({ err, runId }, `[content-runs] ${what} not written`);
+ return null;
+ }
+}
+
+/**
+ * A run's steps by kind, each a short name for the work the server does
+ * then, with the counts the run gives (CE-027/035): the rules it writes to,
+ * the sources it gathers (numbered, so a number it adds can be checked), the
+ * model call, and the check of what it wrote (a number needs a source, a
+ * link must be allowed, a locked passage stays as it is).
+ */
+export function runSteps(kind, counts = {}) {
+ const n = (value) => (Number.isInteger(value) ? value : null);
+ switch (kind) {
+ case 'fix':
+ return [
+ { key: 'read_rules', count: n(counts.rules) },
+ { key: 'gather_sources', count: n(counts.sources) },
+ { key: 'write_changes', count: null },
+ { key: 'check_sources', count: null },
+ ];
+ case 'rewrite':
+ return [
+ { key: 'read_rules', count: n(counts.rules) },
+ { key: 'gather_sources', count: n(counts.sources) },
+ { key: 'rewrite_page', count: null },
+ { key: 'check_sources', count: null },
+ ];
+ case 'brief':
+ return [
+ { key: 'gather_sources', count: n(counts.sources) },
+ { key: 'write_outline', count: null },
+ { key: 'match_fanouts', count: null },
+ ];
+ default:
+ return [
+ { key: 'read_rules', count: n(counts.rules) },
+ { key: 'gather_sources', count: n(counts.sources) },
+ { key: 'write_page', count: null },
+ { key: 'check_sources', count: null },
+ ];
+ }
+}
+
+/**
+ * Starts a run on a draft: written, with its Stop signal (callSignal adds a
+ * call's timeout). Runs a stopped server left on the draft are closed first,
+ * so the latest is this one. A run that can't be written still runs, with no
+ * steps shown and Stop by its signal only. `claimedAt` is the claim a Start
+ * or Rewrite holds on the draft (its agent_state_at): a Stop lets go of that
+ * claim only, never another run's.
+ */
+export async function startRun({ draftId, kind, counts, claimedAt = null }) {
+ const steps = runSteps(kind, counts);
+ const controller = new AbortController();
+ // Runs a stopped server left on the draft are closed: only those older
+ // than any run still going, so a run another tab started goes on, with its
+ // steps and its Stop.
+ await shown('earlier runs', null, () =>
+ supabaseAdmin
+ .from('content_agent_runs')
+ .update({ finished_at: new Date().toISOString(), outcome: 'failed' })
+ .eq('draft_id', draftId)
+ .is('finished_at', null)
+ .lt('started_at', new Date(Date.now() - RUN_STALE_MS).toISOString()),
+ );
+ const data = await shown('run', null, () =>
+ supabaseAdmin
+ .from('content_agent_runs')
+ .insert({ draft_id: draftId, kind, steps, claimed_at: claimedAt })
+ .select('id')
+ .single(),
+ );
+ const id = data?.id ?? null;
+ if (id) live.set(id, controller);
+ return { id, steps, signal: controller.signal };
+}
+
+/** A model call's signal: the run's Stop, or the call's own timeout. */
+export function callSignal(run, timeoutMs) {
+ return AbortSignal.any([run.signal, AbortSignal.timeout(timeoutMs)]);
+}
+
+/**
+ * A run's model call: it isn't sent once the run is stopped, and goes with
+ * the run's Stop and its own timeout (callSignal). A call a Stop aborted was
+ * sent already, and the provider bills it all the same, so its hold on the
+ * AI budget stays as its cost (`budget.keep()`), never let go.
+ */
+export async function runCall(run, budget, timeoutMs, call) {
+ await stopIfStopped(run);
+ // Stopped since: never sent, so nothing is billed.
+ if (run.signal?.aborted) throw new RunStoppedError();
+ try {
+ return await call(callSignal(run, timeoutMs));
+ } catch (err) {
+ if (isStop(err, run)) {
+ // Never in the way of the stop it follows: a failed write is logged.
+ await budget
+ .keep()
+ .catch((keepErr) =>
+ logger.warn({ err: keepErr, runId: run.id }, '[content-runs] stopped call not kept'),
+ );
+ }
+ throw err;
+ }
+}
+
+/** Moves a run on to `step`, with counts learned on the way ({ index: count }). */
+export async function advanceRun(run, step, counts = {}) {
+ if (!run?.id) return;
+ for (const [i, count] of Object.entries(counts)) {
+ if (run.steps[i]) run.steps[i] = { ...run.steps[i], count };
+ }
+ await shown('step', run.id, () =>
+ supabaseAdmin
+ .from('content_agent_runs')
+ .update({ step, steps: run.steps })
+ .eq('id', run.id)
+ .is('finished_at', null),
+ );
+}
+
+/** Whether the run was stopped (here, or by a request on another server). */
+export async function wasStopped(run) {
+ if (!run?.id) return false;
+ if (live.get(run.id)?.signal.aborted) return true;
+ const data = await shown('stop read', run.id, () =>
+ supabaseAdmin.from('content_agent_runs').select('stopped_at').eq('id', run.id).maybeSingle(),
+ );
+ return Boolean(data?.stopped_at);
+}
+
+/** Throws RunStoppedError when the run was stopped: before anything is kept. */
+export async function stopIfStopped(run) {
+ if (await wasStopped(run)) throw new RunStoppedError();
+}
+
+/** Ends a run: done (every step), stopped, or failed. */
+export async function finishRun(run, outcome, counts = {}) {
+ if (!run?.id) return;
+ live.delete(run.id);
+ for (const [i, count] of Object.entries(counts)) {
+ if (run.steps[i]) run.steps[i] = { ...run.steps[i], count };
+ }
+ await shown('end', run.id, () =>
+ supabaseAdmin
+ .from('content_agent_runs')
+ .update({
+ finished_at: new Date().toISOString(),
+ outcome,
+ steps: run.steps,
+ ...(outcome === 'done' ? { step: run.steps.length } : {}),
+ })
+ .eq('id', run.id)
+ .is('finished_at', null),
+ );
+}
+
+/**
+ * Stops a draft's run under way (with `runId`, that run only): marks it
+ * stopped and aborts its model call when it runs here. Answers the runs it
+ * stopped, each with the claim it holds on the draft (claimed_at; null for
+ * Fix and the brief, which hold none): none when none was under way.
+ */
+export async function stopDraftRun(draftId, runId = null) {
+ let query = supabaseAdmin
+ .from('content_agent_runs')
+ .update({ stopped_at: new Date().toISOString() })
+ .eq('draft_id', draftId)
+ .is('finished_at', null)
+ .is('stopped_at', null)
+ .gt('started_at', new Date(Date.now() - RUN_STALE_MS).toISOString());
+ // The run the editor shows: another tab's on the same draft goes on.
+ if (runId) query = query.eq('id', runId);
+ const { data, error } = await query.select('id, claimed_at');
+ if (error) throw error;
+ for (const { id } of data ?? []) live.get(id)?.abort();
+ return data ?? [];
+}
+
+/**
+ * Whether a run ended by its Stop: the stopped mark, or its model call
+ * aborted by one (whatever error the provider wraps the abort in). Read
+ * before finishRun, which forgets the run.
+ */
+export function isStop(err, run) {
+ return (
+ err instanceof RunStoppedError ||
+ (Boolean(run?.id) && live.get(run.id)?.signal.aborted === true)
+ );
+}
diff --git a/server/src/lib/content-runs.test.js b/server/src/lib/content-runs.test.js
new file mode 100644
index 000000000..55477e431
--- /dev/null
+++ b/server/src/lib/content-runs.test.js
@@ -0,0 +1,269 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The Content Agent's runs, step by step (CE-027/035, 00249): written as they
+ * go, shown in the editor, and stopped from it — a run stopped keeps nothing.
+ */
+
+let rows;
+let writes;
+let failInsert;
+
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: (table) => {
+ const call = { table, filters: [] };
+ const chain = {
+ insert: (value) => {
+ writes.push({ table, op: 'insert', value });
+ return {
+ select: () => ({
+ single: async () =>
+ failInsert
+ ? { data: null, error: new Error('down') }
+ : { data: { id: 'run-1' }, error: null },
+ }),
+ };
+ },
+ update: (value) => (writes.push({ table, op: 'update', value, call }), chain),
+ select: (columns) => ((call.columns = columns), chain),
+ eq: (col, v) => (call.filters.push(['eq', col, v]), chain),
+ is: (col, v) => (call.filters.push(['is', col, v]), chain),
+ gt: (col, v) => (call.filters.push(['gt', col, v]), chain),
+ lt: (col, v) => (call.filters.push(['lt', col, v]), chain),
+ gte: () => chain,
+ order: () => chain,
+ limit: () => chain,
+ maybeSingle: async () => ({ data: rows[table] ?? null, error: null }),
+ then: (resolve) => resolve({ data: rows.updated ?? [], error: null }),
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('./logger.js', () => ({ logger: { warn: vi.fn(), error: vi.fn() } }));
+
+const {
+ RunStoppedError,
+ advanceRun,
+ callSignal,
+ finishRun,
+ isStop,
+ runCall,
+ runSteps,
+ startRun,
+ stopDraftRun,
+ stopIfStopped,
+ wasStopped,
+} = await import('./content-runs.js');
+
+beforeEach(() => {
+ rows = {};
+ writes = [];
+ failInsert = false;
+});
+
+describe('runSteps', () => {
+ it('names each kind’s steps by the work the server does, with the run’s counts', () => {
+ expect(runSteps('fix', { rules: 4, sources: 52 })).toEqual([
+ { key: 'read_rules', count: 4 },
+ { key: 'gather_sources', count: 52 },
+ { key: 'write_changes', count: null },
+ { key: 'check_sources', count: null },
+ ]);
+ expect(runSteps('rewrite', { sources: 52, rules: 14 }).map((s) => s.key)).toEqual([
+ 'read_rules',
+ 'gather_sources',
+ 'rewrite_page',
+ 'check_sources',
+ ]);
+ expect(runSteps('brief', { sources: 52 })).toEqual([
+ { key: 'gather_sources', count: 52 },
+ { key: 'write_outline', count: null },
+ { key: 'match_fanouts', count: null },
+ ]);
+ expect(runSteps('write', {}).map((s) => s.count)).toEqual([null, null, null, null]);
+ });
+});
+
+describe('a run', () => {
+ it('is written with its steps, moves on, and ends done with what it learned', async () => {
+ const run = await startRun({
+ draftId: 'd1',
+ kind: 'fix',
+ counts: { rules: 2, sources: 3 },
+ });
+ expect(run.id).toBe('run-1');
+ // Runs a stopped server left on the draft are closed first.
+ expect(writes[0]).toMatchObject({
+ table: 'content_agent_runs',
+ op: 'update',
+ value: { outcome: 'failed', finished_at: expect.any(String) },
+ });
+ // Only runs older than any still going: another tab's run goes on.
+ expect(writes[0].call.filters).toEqual([
+ ['eq', 'draft_id', 'd1'],
+ ['is', 'finished_at', null],
+ ['lt', 'started_at', expect.any(String)],
+ ]);
+ expect(writes[1]).toMatchObject({
+ table: 'content_agent_runs',
+ op: 'insert',
+ value: { draft_id: 'd1', kind: 'fix' },
+ });
+ await advanceRun(run, 2);
+ expect(writes[2].value).toMatchObject({ step: 2 });
+ expect(writes[2].call.filters).toContainEqual(['is', 'finished_at', null]);
+ await finishRun(run, 'done', { 2: 4 });
+ expect(writes[3].value).toMatchObject({
+ outcome: 'done',
+ step: 4,
+ steps: expect.arrayContaining([{ key: 'write_changes', count: 4 }]),
+ });
+ });
+
+ it('still runs when it can’t be written: no steps, and its timeout', async () => {
+ failInsert = true;
+ const run = await startRun({ draftId: 'd1', kind: 'brief', counts: {} });
+ expect(run.id).toBeNull();
+ await advanceRun(run, 1);
+ await finishRun(run, 'done');
+ // The earlier runs' close and the insert: no step, no end.
+ expect(writes).toHaveLength(2);
+ expect(await wasStopped(run)).toBe(false);
+ });
+
+ it('is stopped by a request: marked, its model call aborted, and nothing kept', async () => {
+ const run = await startRun({ draftId: 'd1', kind: 'fix', counts: {} });
+ rows.updated = [{ id: 'run-1', claimed_at: null }];
+ // The runs it stopped, each with the claim it holds (none for a Fix).
+ await expect(stopDraftRun('d1')).resolves.toEqual([{ id: 'run-1', claimed_at: null }]);
+ const mark = writes.find((w) => w.op === 'update' && 'stopped_at' in w.value);
+ expect(mark.value).toEqual({ stopped_at: expect.any(String) });
+ expect(mark.call.columns).toBe('id, claimed_at');
+ // Only a run under way: one a stopped server left long ago isn't.
+ expect(mark.call.filters).toEqual([
+ ['eq', 'draft_id', 'd1'],
+ ['is', 'finished_at', null],
+ ['is', 'stopped_at', null],
+ ['gt', 'started_at', expect.any(String)],
+ ]);
+ // The run the editor shows, when it names it.
+ rows.updated = [];
+ await stopDraftRun('d1', 'run-9');
+ const named = writes.filter((w) => w.op === 'update' && 'stopped_at' in w.value).at(-1);
+ expect(named.call.filters).toContainEqual(['eq', 'id', 'run-9']);
+ expect(run.signal.aborted).toBe(true);
+ expect(isStop(new Error('This operation was aborted'), run)).toBe(true);
+ await expect(stopIfStopped(run)).rejects.toBeInstanceOf(RunStoppedError);
+ await finishRun(run, 'stopped');
+ });
+
+ it('reads a stop made on another server, and answers no run under way', async () => {
+ const run = await startRun({ draftId: 'd1', kind: 'fix', counts: {} });
+ rows.content_agent_runs = { stopped_at: '2026-10-23T10:00:00Z' };
+ expect(await wasStopped(run)).toBe(true);
+ expect(isStop(new RunStoppedError(), run)).toBe(true);
+ expect(isStop(new Error('model down'), run)).toBe(false);
+ await finishRun(run, 'failed');
+ rows.updated = [];
+ await expect(stopDraftRun('d1')).resolves.toEqual([]);
+ });
+
+ it('carries the claim a Start or Rewrite holds on the draft, none for a Fix', async () => {
+ await startRun({
+ draftId: 'd1',
+ kind: 'write',
+ counts: {},
+ claimedAt: '2026-10-23T10:00:00.000Z',
+ });
+ await startRun({ draftId: 'd1', kind: 'fix', counts: {} });
+ const inserts = writes.filter((w) => w.op === 'insert').map((w) => w.value);
+ expect(inserts[0]).toMatchObject({ kind: 'write', claimed_at: '2026-10-23T10:00:00.000Z' });
+ expect(inserts[1]).toMatchObject({ kind: 'fix', claimed_at: null });
+ });
+
+ it('sends no call once stopped, and keeps the hold of one a Stop aborted', async () => {
+ const budget = { keep: vi.fn(async () => {}) };
+ // Stopped before its call: nothing is sent, and the hold can go.
+ const run = await startRun({ draftId: 'd1', kind: 'fix', counts: {} });
+ rows.content_agent_runs = { stopped_at: '2026-10-23T10:00:00Z' };
+ const call = vi.fn();
+ await expect(runCall(run, budget, 1000, call)).rejects.toBeInstanceOf(RunStoppedError);
+ expect(call).not.toHaveBeenCalled();
+ expect(budget.keep).not.toHaveBeenCalled();
+ await finishRun(run, 'stopped');
+
+ // Stopped while its call is out: the provider bills it, so the hold stays.
+ rows.content_agent_runs = null;
+ const next = await startRun({ draftId: 'd1', kind: 'fix', counts: {} });
+ let sent = () => {};
+ const out = runCall(
+ next,
+ budget,
+ 60_000,
+ (signal) =>
+ new Promise((_, reject) => {
+ signal.addEventListener('abort', () => reject(new Error('This operation was aborted')));
+ sent();
+ }),
+ );
+ await new Promise((resolve) => (sent = resolve));
+ rows.updated = [{ id: 'run-1' }];
+ await stopDraftRun('d1');
+ await expect(out).rejects.toThrow('aborted');
+ expect(budget.keep).toHaveBeenCalledTimes(1);
+ await finishRun(next, 'stopped');
+
+ // With the real budget: the stopped call leaves its usage row.
+ const { reserveAiBudget } = await import('./plan-guard.js');
+ const real = await reserveAiBudget('o1', { feature: 'content', modelId: 'm', draftId: 'd1' });
+ const again = await startRun({ draftId: 'd1', kind: 'fix', counts: {} });
+ let sentAgain = () => {};
+ const outAgain = runCall(
+ again,
+ real,
+ 60_000,
+ (signal) =>
+ new Promise((_, reject) => {
+ signal.addEventListener('abort', () => reject(new Error('This operation was aborted')));
+ sentAgain();
+ }),
+ );
+ await new Promise((resolve) => (sentAgain = resolve));
+ await stopDraftRun('d1');
+ await expect(outAgain).rejects.toThrow('aborted');
+ await real.release();
+ expect(writes).toContainEqual(
+ expect.objectContaining({
+ table: 'prompt_improve_usage',
+ op: 'insert',
+ value: expect.objectContaining({ feature: 'content', content_draft_id: 'd1' }),
+ }),
+ );
+ await finishRun(again, 'stopped');
+
+ // A call that fails on its own lets the hold go as before.
+ const third = await startRun({ draftId: 'd1', kind: 'fix', counts: {} });
+ await expect(
+ runCall(third, budget, 1000, async () => {
+ throw new Error('model down');
+ }),
+ ).rejects.toThrow('model down');
+ expect(budget.keep).toHaveBeenCalledTimes(1);
+ await finishRun(third, 'failed');
+ });
+
+ it('tells its own Stop from a call that timed out', async () => {
+ const run = await startRun({ draftId: 'd1', kind: 'fix', counts: {} });
+ const signal = callSignal(run, 1);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ // The call's timeout fired, not the run's Stop: a failure, not a stop.
+ expect(signal.aborted).toBe(true);
+ expect(run.signal.aborted).toBe(false);
+ expect(isStop(Object.assign(new Error('timed out'), { name: 'TimeoutError' }), run)).toBe(
+ false,
+ );
+ await finishRun(run, 'failed');
+ });
+});
diff --git a/server/src/lib/content-writer.js b/server/src/lib/content-writer.js
index b81093945..da3e29d82 100644
--- a/server/src/lib/content-writer.js
+++ b/server/src/lib/content-writer.js
@@ -45,6 +45,7 @@ import {
rewriteSchema,
textLength,
} from './content-rewrite.js';
+import { advanceRun, finishRun, isStop, runCall, startRun, stopIfStopped } from './content-runs.js';
import { getLanguageName } from './languages.js';
import { logger } from './logger.js';
import { reserveAiBudget } from './plan-guard.js';
@@ -412,12 +413,14 @@ export async function startDraftWriting({ draftId, brandId, input, rewrite = fal
// A provider that isn't set up fails here, before anything is claimed.
const model = resolveModel(modelId);
- // Claimed once: a second start meanwhile finds it writing.
+ // Claimed once: a second start meanwhile finds it writing. The claim's
+ // time is the run's own: it ends only a claim it still holds (finish).
+ const claimedAt = new Date().toISOString();
const { data: claimed, error: claimError } = await supabaseAdmin
.from('content_drafts')
.update({
agent_state: 'writing',
- agent_state_at: new Date().toISOString(),
+ agent_state_at: claimedAt,
// Which run, for every device: a failed rewrite is tried again as one.
agent_run: rewrite ? 'rewrite' : 'write',
})
@@ -434,7 +437,11 @@ export async function startDraftWriting({ draftId, brandId, input, rewrite = fal
});
}
- runDraftWriting({ draft, brand, model, input, budget, rewrite }).catch((err) =>
+ // Written before the answer, so the editor reads its steps, and Stop finds
+ // it, at once; with its claim, the one a Stop on it lets go of.
+ const held = { ...draft, agent_state: 'writing', agent_state_at: claimedAt };
+ const run = await startWritingRun(held, input, rewrite);
+ runDraftWriting({ draft: held, brand, model, input, budget, rewrite, run }).catch((err) =>
logger.error({ err, draftId }, '[content-writer] run failed'),
);
} catch (err) {
@@ -446,16 +453,19 @@ export async function startDraftWriting({ draftId, brandId, input, rewrite = fal
}
/**
- * The agent's state as it ends, only while it is still the run's to end;
- * with `openOnly`, only while the draft is still open to it (not marked ready
- * meanwhile). Answers whether it ended it.
+ * The agent's state as it ends, only while it is still the run's to end: the
+ * draft still held by this run's own claim (its agent_state_at), never a
+ * newer run's after a Stop let the draft go. With `openOnly`, only while the
+ * draft is still open to it (not marked ready meanwhile). Answers whether it
+ * ended it.
*/
-async function finish(draftId, values, { openOnly = false } = {}) {
+async function finish(draft, values, { openOnly = false } = {}) {
let query = supabaseAdmin
.from('content_drafts')
.update({ ...values, agent_state_at: new Date().toISOString() })
- .eq('id', draftId)
+ .eq('id', draft.id)
.eq('agent_state', 'writing');
+ if (draft.agent_state_at) query = query.eq('agent_state_at', draft.agent_state_at);
if (openOnly) query = query.in('status', OPEN_STATUSES);
const { data, error } = await query.select('id').maybeSingle();
if (error) throw error;
@@ -463,9 +473,9 @@ async function finish(draftId, values, { openOnly = false } = {}) {
}
/** A draft marked ready or published during the run keeps its page; the agent lets go of it. */
-async function letGo(draftId) {
- await finish(draftId, { agent_state: null });
- logger.info({ draftId }, '[content-writer] the draft was closed during the run');
+async function letGo(draft) {
+ await finish(draft, { agent_state: null });
+ logger.info({ draftId: draft.id }, '[content-writer] the draft was closed during the run');
return { skipped: true };
}
@@ -476,7 +486,7 @@ async function letGo(draftId) {
* is put back as it was (content-rewrite.js); a rewrite that drops one, or
* leaves no page, fails the run. The draft's status doesn't change.
*/
-async function rewritePage({ draft, brand, model, input, budget, numbered, known, brief }) {
+async function rewritePage({ draft, brand, model, input, budget, numbered, known, brief, run }) {
const page = keepBlocks(draft.body_html, new Set(input.locked.map(passageKey)));
const ruleKeys = new Set(input.rules.map((r) => r.key));
// The Length rule's target; with Length off, the page keeps its length.
@@ -488,22 +498,26 @@ async function rewritePage({ draft, brand, model, input, budget, numbered, known
sourceUrl: draft.source_url,
ruleKeys,
});
- const { object, usage } = await generateObject({
- model,
- schema: rewriteSchema,
- system: REWRITE_SYSTEM_PROMPT,
- prompt: buildWritePrompt({
- brand,
- draft,
- numbered,
- brief,
- input: { ...input, sources: { ...input.sources, length } },
- linkTargets: linkTargetsPrompt(targets, ruleKeys),
- current: page,
+ await advanceRun(run, 2);
+ const { object, usage } = await runCall(run, budget, CALL_TIMEOUT_MS, (abortSignal) =>
+ generateObject({
+ model,
+ schema: rewriteSchema,
+ system: REWRITE_SYSTEM_PROMPT,
+ prompt: buildWritePrompt({
+ brand,
+ draft,
+ numbered,
+ brief,
+ input: { ...input, sources: { ...input.sources, length } },
+ linkTargets: linkTargetsPrompt(targets, ruleKeys),
+ current: page,
+ }),
+ abortSignal,
}),
- abortSignal: AbortSignal.timeout(CALL_TIMEOUT_MS),
- });
+ );
await budget.charge(usage);
+ await advanceRun(run, 3);
if (!isPageHtml(object.html)) throw new Error('The agent answered with no page in HTML');
const cleaned = cleanPageHtml(
@@ -526,8 +540,10 @@ async function rewritePage({ draft, brand, model, input, budget, numbered, known
// A batch that landed during the run stays the one to decide.
if (await hasOpenSuggestions(draft.id)) {
logger.info({ draftId: draft.id }, '[content-writer] open suggestions came in during the run');
- return await letGo(draft.id);
+ return await letGo(draft);
}
+ // Stopped meanwhile: nothing it wrote is kept.
+ await stopIfStopped(run);
// The data it says it wrote from (CE-033).
const { sources } = sourceSuggestion({
named: object.sources,
@@ -554,14 +570,14 @@ async function rewritePage({ draft, brand, model, input, budget, numbered, known
...(sources.length ? { sources } : {}),
});
if (insertError) throw insertError;
- if (!(await finish(draft.id, { agent_state: null }, { openOnly: true }))) {
+ if (!(await finish(draft, { agent_state: null }, { openOnly: true }))) {
// Nobody reviews a rewrite of a page already marked ready.
const { error: dropError } = await supabaseAdmin
.from('content_draft_suggestions')
.delete()
.eq('batch_id', batchId);
if (dropError) throw dropError;
- return await letGo(draft.id);
+ return await letGo(draft);
}
return { rewritten: true };
}
@@ -572,104 +588,177 @@ async function rewritePage({ draft, brand, model, input, budget, numbered, known
* model's answer is charged to the hold Start took on the budget
* (reserveAiBudget); a run that ends before one lets the hold go.
*/
-export async function runDraftWriting({ draft, brand, model, input, budget, rewrite = false }) {
+export async function runDraftWriting({
+ draft,
+ brand,
+ model,
+ input,
+ budget,
+ rewrite = false,
+ run: started = null,
+}) {
+ // Its steps, named by the data it reads (CE-027/035): Start writes the run
+ // before it answers, so Stop finds it at once; Stop aborts the call.
+ const run = started ?? (await startWritingRun(draft, input, rewrite));
try {
- const [prompts, opportunityRes] = await Promise.all([
- readPrompts(draft.brand_id, input.sources.promptIds),
- draft.opportunity_id && !draft.brief
- ? supabaseAdmin
- .from('content_opportunities')
- .select('brief')
- .eq('id', draft.opportunity_id)
- .eq('brand_id', draft.brand_id)
- .maybeSingle()
- : Promise.resolve({ data: null, error: null }),
- ]);
- if (opportunityRes.error) throw opportunityRes.error;
- const brief = briefText(draft.brief, opportunityRes.data?.brief);
- // The data it writes from, numbered (CE-033); the numbers a suggestion
- // may write unmarked (the page's, the brand's, the brief's, the rules',
- // today's), and those a page written whole may (the sources' words too).
- const numbered = numberSources({
- prompts,
- fanouts: input.sources.fanouts,
- pages: input.sources.pages,
- queries: input.sources.queries,
- });
- const known = knownNumbers(
- htmlText(draft.body_html),
- draft.title,
- brand.name,
- brand.industry,
- brand.description,
- brief,
- ...input.rules.flatMap((r) => [r.name, r.detail]),
- ...input.textRules,
- todayText(),
+ const result = await writeWithRun({ draft, brand, model, input, budget, rewrite, run });
+ await finishRun(
+ run,
+ 'done',
+ Number.isInteger(result.suggestions) ? { 2: result.suggestions } : {},
);
- const knownInPage = new Set([...known, ...knownNumbers(...numbered.map(sourceWords))]);
-
- if (rewrite) {
- return await rewritePage({
- draft,
- brand,
- model,
- input,
- budget,
- numbered,
- known: knownInPage,
- brief,
- });
+ return result;
+ } catch (err) {
+ // An answer the provider billed but that missed the schema is charged,
+ // as Improve's is: else the costliest call, a whole page, would run free.
+ if (NoObjectGeneratedError.isInstance(err) && err.usage) await budget.charge(err.usage);
+ if (isStop(err, run)) {
+ // Stopped: the page as it was, and the agent lets go of it.
+ await finishRun(run, 'stopped');
+ await finish(draft, { agent_state: null }).catch((finishErr) =>
+ logger.error({ err: finishErr, draftId: draft.id }, '[content-writer] state not saved'),
+ );
+ return { stopped: true };
}
+ await finishRun(run, 'failed');
+ logger.error({ err, draftId: draft.id }, '[content-writer] the agent could not finish');
+ await finish(draft, { agent_state: 'failed' }).catch((finishErr) =>
+ logger.error({ err: finishErr, draftId: draft.id }, '[content-writer] state not saved'),
+ );
+ return { failed: true };
+ } finally {
+ // Nothing charged (it failed before an answer): the hold goes.
+ await budget.release();
+ }
+}
+
+/**
+ * A writing run's steps by what it does: a rewrite, a new page, or
+ * suggestions on a live one, with the claim it holds on the draft: a Start
+ * on a live page runs as 'fix', so its kind alone can't tell a Stop that it
+ * holds one.
+ */
+function startWritingRun(draft, input, rewrite) {
+ const { promptIds, fanouts, pages, queries } = input.sources;
+ return startRun({
+ draftId: draft.id,
+ claimedAt: draft.agent_state === 'writing' ? (draft.agent_state_at ?? null) : null,
+ kind: rewrite ? 'rewrite' : draft.method === 'create' ? 'write' : 'fix',
+ counts: {
+ rules: input.rules.length,
+ sources: promptIds.length + fanouts.length + pages.length + queries.length,
+ },
+ });
+}
+
+/** The run itself, step by step: nothing is kept once it is stopped. */
+async function writeWithRun({ draft, brand, model, input, budget, rewrite, run }) {
+ await advanceRun(run, 1);
+ const [prompts, opportunityRes] = await Promise.all([
+ readPrompts(draft.brand_id, input.sources.promptIds),
+ draft.opportunity_id && !draft.brief
+ ? supabaseAdmin
+ .from('content_opportunities')
+ .select('brief')
+ .eq('id', draft.opportunity_id)
+ .eq('brand_id', draft.brand_id)
+ .maybeSingle()
+ : Promise.resolve({ data: null, error: null }),
+ ]);
+ if (opportunityRes.error) throw opportunityRes.error;
+ const brief = briefText(draft.brief, opportunityRes.data?.brief);
+ // The data it writes from, numbered (CE-033); the numbers a suggestion
+ // may write unmarked (the page's, the brand's, the brief's, the rules',
+ // today's), and those a page written whole may (the sources' words too).
+ const numbered = numberSources({
+ prompts,
+ fanouts: input.sources.fanouts,
+ pages: input.sources.pages,
+ queries: input.sources.queries,
+ });
+ const known = knownNumbers(
+ htmlText(draft.body_html),
+ draft.title,
+ brand.name,
+ brand.industry,
+ brand.description,
+ brief,
+ ...input.rules.flatMap((r) => [r.name, r.detail]),
+ ...input.textRules,
+ todayText(),
+ );
+ const knownInPage = new Set([...known, ...knownNumbers(...numbered.map(sourceWords))]);
+
+ if (rewrite) {
+ return await rewritePage({
+ draft,
+ brand,
+ model,
+ input,
+ budget,
+ numbered,
+ known: knownInPage,
+ brief,
+ run,
+ });
+ }
- if (draft.method === 'create') {
- const { object, usage } = await generateObject({
+ if (draft.method === 'create') {
+ await advanceRun(run, 2);
+ const { object, usage } = await runCall(run, budget, CALL_TIMEOUT_MS, (abortSignal) =>
+ generateObject({
model,
schema: pageSchema,
system: WRITE_SYSTEM_PROMPT,
prompt: buildWritePrompt({ brand, draft, numbered, brief, input }),
- abortSignal: AbortSignal.timeout(CALL_TIMEOUT_MS),
+ abortSignal,
+ }),
+ );
+ await budget.charge(usage);
+ await advanceRun(run, 3);
+ // No number without a source: a placeholder where one had none.
+ const written = sourcedPage(object, knownInPage);
+ const title = clean(written.title).slice(0, 300) || draft.title;
+ // Stopped meanwhile: the page stays as it was, and History with it.
+ await stopIfStopped(run);
+ // Try again over a page the person has written in: History keeps it
+ // first. Their saves wait while the agent writes (saveContentDraft).
+ if (draftPassages(draft.body_html).some((p) => p.tag !== 'h1')) {
+ const { error: keepError } = await supabaseAdmin.rpc('content_draft_snapshot', {
+ p_draft_id: draft.id,
+ p_origin: 'agent_before',
});
- await budget.charge(usage);
- // No number without a source: a placeholder where one had none.
- const written = sourcedPage(object, knownInPage);
- const title = clean(written.title).slice(0, 300) || draft.title;
- // Try again over a page the person has written in: History keeps it
- // first. Their saves wait while the agent writes (saveContentDraft).
- if (draftPassages(draft.body_html).some((p) => p.tag !== 'h1')) {
- const { error: keepError } = await supabaseAdmin.rpc('content_draft_snapshot', {
- p_draft_id: draft.id,
- p_origin: 'agent_before',
- });
- if (keepError) throw keepError;
- }
- const saved = await finish(
- draft.id,
- {
- title,
- body_html: renderPage({ ...written, title }),
- status: 'in_review',
- author: 'agent',
- agent_state: null,
- },
- { openOnly: true },
- );
- // Awaited here, so a failure to let go is caught below.
- return saved ? { written: true } : await letGo(draft.id);
+ if (keepError) throw keepError;
}
+ const saved = await finish(
+ draft,
+ {
+ title,
+ body_html: renderPage({ ...written, title }),
+ status: 'in_review',
+ author: 'agent',
+ agent_state: null,
+ },
+ { openOnly: true },
+ );
+ // Awaited here, so a failure to let go is caught below.
+ return saved ? { written: true } : await letGo(draft);
+ }
- const { passages, more } = promptPassages(draftPassages(draft.body_html));
- if (!passages.length) throw new Error('The page has no text to improve');
- const lockedKeys = new Set(input.locked.map(passageKey));
- const ruleKeys = new Set(input.rules.map((r) => r.key));
- // Where it may link: the brand's pages and the draft's sources (A).
- const targets = await readLinkTargets({
- brandId: draft.brand_id,
- draftId: draft.id,
- sourceUrl: draft.source_url,
- ruleKeys,
- });
- const { object, usage } = await generateObject({
+ const { passages, more } = promptPassages(draftPassages(draft.body_html));
+ if (!passages.length) throw new Error('The page has no text to improve');
+ const lockedKeys = new Set(input.locked.map(passageKey));
+ const ruleKeys = new Set(input.rules.map((r) => r.key));
+ // Where it may link: the brand's pages and the draft's sources (A).
+ const targets = await readLinkTargets({
+ brandId: draft.brand_id,
+ draftId: draft.id,
+ sourceUrl: draft.source_url,
+ ruleKeys,
+ });
+ await advanceRun(run, 2);
+ const { object, usage } = await runCall(run, budget, CALL_TIMEOUT_MS, (abortSignal) =>
+ generateObject({
model,
schema: suggestionsSchema,
system: SUGGEST_SYSTEM_PROMPT,
@@ -684,59 +773,47 @@ export async function runDraftWriting({ draft, brand, model, input, budget, rewr
lockedKeys,
linkTargets: linkTargetsPrompt(targets, ruleKeys),
}),
- abortSignal: AbortSignal.timeout(CALL_TIMEOUT_MS),
- });
- await budget.charge(usage);
- const rows = keepSuggestions(
- object.suggestions,
- passages,
- lockedKeys,
- ruleKeys,
- linkAllowList(targets),
- { numbered, known },
- );
- if (!rows.length) throw new Error('The agent left no suggestion it could place');
- // A batch that landed during the run (Fix open rules, the API) stays the
- // one to decide: this one isn't added over it.
- if (await hasOpenSuggestions(draft.id)) {
- logger.info(
- { draftId: draft.id },
- '[content-writer] open suggestions came in during the run',
- );
- return await letGo(draft.id);
- }
- const batchId = randomUUID();
- const { error: insertError } = await supabaseAdmin.from('content_draft_suggestions').insert(
- rows.map((row, position) => ({
- ...row,
- draft_id: draft.id,
- batch_id: batchId,
- action_id: draft.action_id ?? null,
- position,
- })),
- );
- if (insertError) throw insertError;
- if (!(await finish(draft.id, { status: 'in_review', agent_state: null }, { openOnly: true }))) {
- // Nobody reviews suggestions on a page already marked ready.
- const { error: dropError } = await supabaseAdmin
- .from('content_draft_suggestions')
- .delete()
- .eq('batch_id', batchId);
- if (dropError) throw dropError;
- return await letGo(draft.id);
- }
- return { suggestions: rows.length };
- } catch (err) {
- // An answer the provider billed but that missed the schema is charged,
- // as Improve's is: else the costliest call, a whole page, would run free.
- if (NoObjectGeneratedError.isInstance(err) && err.usage) await budget.charge(err.usage);
- logger.error({ err, draftId: draft.id }, '[content-writer] the agent could not finish');
- await finish(draft.id, { agent_state: 'failed' }).catch((finishErr) =>
- logger.error({ err: finishErr, draftId: draft.id }, '[content-writer] state not saved'),
- );
- return { failed: true };
- } finally {
- // Nothing charged (it failed before an answer): the hold goes.
- await budget.release();
+ abortSignal,
+ }),
+ );
+ await budget.charge(usage);
+ await advanceRun(run, 3);
+ const rows = keepSuggestions(
+ object.suggestions,
+ passages,
+ lockedKeys,
+ ruleKeys,
+ linkAllowList(targets),
+ { numbered, known },
+ );
+ // Stopped meanwhile: nothing it wrote is kept.
+ await stopIfStopped(run);
+ if (!rows.length) throw new Error('The agent left no suggestion it could place');
+ // A batch that landed during the run (Fix open rules, the API) stays the
+ // one to decide: this one isn't added over it.
+ if (await hasOpenSuggestions(draft.id)) {
+ logger.info({ draftId: draft.id }, '[content-writer] open suggestions came in during the run');
+ return await letGo(draft);
+ }
+ const batchId = randomUUID();
+ const { error: insertError } = await supabaseAdmin.from('content_draft_suggestions').insert(
+ rows.map((row, position) => ({
+ ...row,
+ draft_id: draft.id,
+ batch_id: batchId,
+ action_id: draft.action_id ?? null,
+ position,
+ })),
+ );
+ if (insertError) throw insertError;
+ if (!(await finish(draft, { status: 'in_review', agent_state: null }, { openOnly: true }))) {
+ // Nobody reviews suggestions on a page already marked ready.
+ const { error: dropError } = await supabaseAdmin
+ .from('content_draft_suggestions')
+ .delete()
+ .eq('batch_id', batchId);
+ if (dropError) throw dropError;
+ return await letGo(draft);
}
+ return { suggestions: rows.length };
}
diff --git a/server/src/lib/content-writer.test.js b/server/src/lib/content-writer.test.js
index 9892e6a38..a7d03a7be 100644
--- a/server/src/lib/content-writer.test.js
+++ b/server/src/lib/content-writer.test.js
@@ -73,6 +73,11 @@ vi.mock('./plan-guard.js', async (importOriginal) => ({
}));
vi.mock('./logger.js', () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));
const readLinkTargets = vi.hoisted(() => vi.fn());
+const stopIfStopped = vi.fn();
+vi.mock('./content-runs.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ stopIfStopped: (...args) => stopIfStopped(...args),
+}));
vi.mock('./content-links.js', async (importOriginal) => ({
...(await importOriginal()),
readLinkTargets: (...args) => readLinkTargets(...args),
@@ -155,6 +160,7 @@ beforeEach(() => {
});
reserveAiBudget.mockReset().mockImplementation(realGuard.reserveAiBudget);
hasOpenSuggestions.mockReset().mockResolvedValue(false);
+ stopIfStopped.mockReset().mockResolvedValue(undefined);
});
const draftUpdates = () =>
@@ -210,8 +216,15 @@ describe('startDraftWriting', () => {
);
// Which run holds it, for every device (00247).
expect(draftUpdates()[0]).toMatchObject({ agent_state: 'writing', agent_run: 'write' });
+ // Its run carries the claim, the one a Stop on it lets go of (00249).
+ expect(
+ writes.find((w) => w.table === 'content_agent_runs' && w.kind === 'insert').value,
+ ).toMatchObject({ kind: 'write', claimed_at: draftUpdates()[0].agent_state_at });
await vi.waitFor(() => expect(draftUpdates()).toHaveLength(2));
+ // It ends only its own claim: a newer run's, after a Stop let go, is left alone.
+ const updates = writes.filter((w) => w.table === 'content_drafts' && w.kind === 'update');
+ expect(updates[1].filters).toContainEqual(['agent_state_at', updates[0].value.agent_state_at]);
expect(draftUpdates()[1]).toMatchObject({
title: 'How to brew pour-over coffee',
status: 'in_review',
@@ -239,6 +252,21 @@ describe('startDraftWriting', () => {
expect(prompt).toContain('Page type: How-to guide: numbered steps to get one thing done');
});
+ it('leaves the page as it was once stopped, and lets go of it (CE-027)', async () => {
+ const { RunStoppedError } = await import('./content-runs.js');
+ stopIfStopped.mockRejectedValueOnce(new RunStoppedError());
+ // A page the person wrote in: stopped, History gets no "before the agent".
+ rows.content_drafts = draftRow({
+ body_html: '<h1>How to brew pour-over coffee</h1><p>My notes.</p>',
+ });
+ await startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input() });
+ await vi.waitFor(() => expect(draftUpdates()).toHaveLength(2));
+ // Claimed, then let go: no page written, no 'failed'.
+ expect(draftUpdates()[1]).toEqual({ agent_state: null, agent_state_at: expect.any(String) });
+ expect(draftUpdates().some((u) => 'body_html' in u)).toBe(false);
+ expect(rpcCalls).toEqual([]);
+ });
+
// Rewrite from brief: a draft the agent wrote is in review, and is written again.
it('writes a draft in review again, keeping its page in History first', async () => {
rows.content_drafts = draftRow({
diff --git a/server/src/lib/plan-guard-ai-budget.test.js b/server/src/lib/plan-guard-ai-budget.test.js
index 8499d9fef..79ce1770f 100644
--- a/server/src/lib/plan-guard-ai-budget.test.js
+++ b/server/src/lib/plan-guard-ai-budget.test.js
@@ -151,6 +151,14 @@ describe('reserveAiBudget', () => {
expect(ops).toEqual([expect.objectContaining({ kind: 'delete', filters: [['id', 'u1']] })]);
});
+ it('keeps the hold as the cost of a call a Stop aborted, which the provider still bills', async () => {
+ const budget = await guard.reserveAiBudget('o1', { feature: 'content', modelId: 'm' });
+ await budget.keep();
+ await budget.release();
+ // Neither changed nor let go: the hold's row is the call's cost.
+ expect(ops).toEqual([]);
+ });
+
it('refuses once the budget is spent, as the quota did', async () => {
reserved = null;
await expect(
@@ -177,5 +185,16 @@ describe('reserveAiBudget', () => {
value: expect.objectContaining({ feature: 'action_center', action_id: 'a1' }),
}),
]);
+
+ // A call a Stop aborted is written at what a hold would be.
+ ops = [];
+ const stopped = await guard.reserveAiBudget('o1', { feature: 'content', modelId: 'm' });
+ await stopped.keep();
+ expect(ops).toEqual([
+ expect.objectContaining({
+ kind: 'insert',
+ value: expect.objectContaining({ feature: 'content', cost_usd: expect.any(Number) }),
+ }),
+ ]);
});
});
diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.js
index 065c8db60..232d7ab99 100644
--- a/server/src/lib/plan-guard.js
+++ b/server/src/lib/plan-guard.js
@@ -428,6 +428,28 @@ export async function reserveAiBudget(
.eq('id', reservedId);
if (error) logger.error({ err: error, orgId, feature }, '[ai-budget] release failed');
},
+ /**
+ * A call sent and then aborted (the run's Stop): the provider finishes
+ * and bills it all the same, so the hold stays as its cost and release()
+ * leaves it. With no hold (an unlimited budget), it is written at what a
+ * hold would be.
+ */
+ async keep() {
+ if (charged) return;
+ charged = true;
+ if (reservedId) return;
+ const since = (await quotaPeriodStart(orgId)).toISOString();
+ const { error } = await supabaseAdmin.from('prompt_improve_usage').insert({
+ organization_id: orgId,
+ feature,
+ prompt_id: promptId,
+ action_id: actionId,
+ content_draft_id: draftId,
+ model: modelId,
+ cost_usd: await holdCostUsd(orgId, modelId, since),
+ });
+ if (error) logger.error({ err: error, orgId, feature }, '[ai-budget] usage write failed');
+ },
};
}
diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.js
index 2a00d0dde..edae92e76 100644
--- a/server/src/routes/content-drafts.js
+++ b/server/src/routes/content-drafts.js
@@ -3,14 +3,17 @@ import { z } from 'zod';
import { assertBrandAccess } from '../lib/access.js';
import { fixDraftRules, fixRulesInput } from '../lib/content-agent.js';
import { rebuildDraftBrief, rebuildSources } from '../lib/content-brief.js';
+import { stopDraftRun } from '../lib/content-runs.js';
import { startDraftWriting, writeDraftInput } from '../lib/content-writer.js';
+import supabaseAdmin from '../config/supabase.js';
import { PlanLimitError } from '../lib/plan-guard.js';
/**
* Content Editor drafts: Rebuild outline in the editor's Brief tab writes
* the draft's brief from the sources the person kept (CE-007); Fix open
* rules with agent leaves the Content Agent's suggestions for review
- * (CE-018); Start's Agent has the Content Agent do the page (CE-015).
+ * (CE-018); Start's Agent has the Content Agent do the page (CE-015); and
+ * Stop ends the agent's run under way, changing nothing (v1.1 CE-027).
*/
const router = Router();
@@ -170,4 +173,58 @@ router.post('/:draftId/rewrite', async (req, res) => {
}
});
+const stopBody = z.object({ brandId: z.guid(), runId: z.guid().optional() });
+
+/**
+ * POST /api/content-drafts/:draftId/stop
+ * Body: { brandId, runId? }
+ * Stops the Content Agent's run on the draft (CE-027), the one the editor
+ * shows when it names it: it keeps nothing of what it had. Answers
+ * { stopped }: false when no run was under way.
+ */
+router.post('/:draftId/stop', async (req, res) => {
+ const draftId = z.guid().safeParse(req.params.draftId);
+ const parsed = stopBody.safeParse(req.body ?? {});
+ if (!draftId.success || !parsed.success) {
+ return res.status(400).json({ error: 'Invalid request', code: 'invalid' });
+ }
+ const { brandId, runId } = parsed.data;
+ try {
+ await assertBrandAccess(brandId, req.user.id);
+ const { data: draft, error } = await supabaseAdmin
+ .from('content_drafts')
+ .select('brand_id')
+ .eq('id', draftId.data)
+ .maybeSingle();
+ if (error) throw error;
+ if (!draft || draft.brand_id !== brandId) {
+ return res.status(404).json({ error: 'Draft not found', code: 'not_found' });
+ }
+ const stopped = await stopDraftRun(draftId.data, runId ?? null);
+ // A run in the background lets go of the draft once it sees the stop;
+ // one no server holds any more never would. The editor opens at once.
+ // Only the claim a stopped run holds: a Stop on a Fix or the brief (which
+ // hold none) leaves a Start or Rewrite on the same draft its claim.
+ for (const { claimed_at: claimedAt } of stopped) {
+ if (!claimedAt) continue;
+ const { error: letGoError } = await supabaseAdmin
+ .from('content_drafts')
+ .update({ agent_state: null, agent_state_at: new Date().toISOString() })
+ .eq('id', draftId.data)
+ .eq('agent_state', 'writing')
+ .eq('agent_state_at', claimedAt);
+ if (letGoError) throw letGoError;
+ }
+ return res.json({ stopped: stopped.length > 0 });
+ } catch (err) {
+ if (ERROR_CODES[err?.status]) {
+ return res
+ .status(err.status)
+ .json({ error: err.message, code: err.code ?? ERROR_CODES[err.status] });
+ }
+ req.log.error({ err }, 'content draft agent stop error');
+ return res.status(502).json({ error: 'The agent could not be stopped', code: 'failed' });
+ }
+});
+
export default router;
diff --git a/server/src/routes/content-drafts.test.js b/server/src/routes/content-drafts.test.js
index 55604a82b..7981e5ec3 100644
--- a/server/src/routes/content-drafts.test.js
+++ b/server/src/routes/content-drafts.test.js
@@ -6,6 +6,7 @@ import express from 'express';
* POST /api/content-drafts/:draftId/suggestions (CE-018): Fix open rules with agent; and
* POST /api/content-drafts/:draftId/write (CE-015): Start's Agent.
* POST /api/content-drafts/:draftId/rewrite: Rewrite the page to these rules.
+ * POST /api/content-drafts/:draftId/stop (v1.1 CE-027): Stop the agent's run.
*/
const BRAND = '33333333-3333-3333-3333-333333333333';
@@ -15,9 +16,34 @@ const rebuildDraftBrief = vi.fn();
const startDraftWriting = vi.fn();
const fixDraftRules = vi.fn();
const assertBrandAccess = vi.fn();
+const stopDraftRun = vi.fn();
+/** A Start's claim on the draft (its agent_state_at), as its run carries it. */
+const CLAIM = '2026-10-23T10:00:00.000+00:00';
+/** The draft Stop reads, to check it is the brand's. */
+let stopDraft;
// The route's modules read the Supabase client; CI has no credentials for it.
-vi.mock('../config/supabase.js', () => ({ default: {} }));
+/** The drafts Stop lets go of. */
+let letGo;
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: () => {
+ const filters = [];
+ const chain = {
+ select: () => chain,
+ eq: (col, v) => (filters.push([col, v]), chain),
+ update: (value) => (letGo.push({ value, filters }), chain),
+ maybeSingle: async () => ({ data: stopDraft, error: null }),
+ then: (resolve) => resolve({ error: null }),
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('../lib/content-runs.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ stopDraftRun: (...args) => stopDraftRun(...args),
+}));
vi.mock('../lib/content-brief.js', async (importOriginal) => ({
...(await importOriginal()),
rebuildDraftBrief: (...args) => rebuildDraftBrief(...args),
@@ -34,6 +60,7 @@ vi.mock('../lib/access.js', () => ({ assertBrandAccess: (...args) => assertBrand
const { default: router } = await import('./content-drafts.js');
const { PlanLimitError } = await import('../lib/plan-guard.js');
+const { RunStoppedError } = await import('../lib/content-runs.js');
let server;
let baseUrl;
@@ -43,6 +70,9 @@ beforeEach(async () => {
startDraftWriting.mockReset().mockResolvedValue({ started: true });
fixDraftRules.mockReset().mockResolvedValue({ count: 2, batchId: 'b1' });
assertBrandAccess.mockReset().mockResolvedValue({});
+ stopDraftRun.mockReset().mockResolvedValue([{ id: 'run-1', claimed_at: CLAIM }]);
+ stopDraft = { brand_id: BRAND };
+ letGo = [];
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
@@ -240,3 +270,77 @@ describe('POST /api/content-drafts/:draftId/suggestions', () => {
}
});
});
+
+describe('POST /api/content-drafts/:draftId/stop', () => {
+ const stop = (body = { brandId: BRAND }, draftId = DRAFT) =>
+ fetch(`${baseUrl}/${draftId}/stop`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+ it('stops the draft’s run under way', async () => {
+ const res = await stop();
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ stopped: true });
+ expect(assertBrandAccess).toHaveBeenCalledWith(BRAND, 'u1');
+ expect(stopDraftRun).toHaveBeenCalledWith(DRAFT, null);
+ // A background run's draft is let go at once, whichever server held it:
+ // the claim that run holds, never a newer one.
+ expect(letGo).toEqual([
+ {
+ value: { agent_state: null, agent_state_at: expect.any(String) },
+ filters: [
+ ['id', DRAFT],
+ ['agent_state', 'writing'],
+ ['agent_state_at', CLAIM],
+ ],
+ },
+ ]);
+ });
+
+ it('keeps a Start’s claim when the run it names is a Fix on the same draft', async () => {
+ const RUN = '99999999-9999-4999-8999-999999999999';
+ // A Fix, or the brief, holds no claim: the Start another tab began goes on with its own.
+ stopDraftRun.mockResolvedValue([{ id: RUN, claimed_at: null }]);
+ const res = await stop({ brandId: BRAND, runId: RUN });
+ expect(await res.json()).toEqual({ stopped: true });
+ expect(stopDraftRun).toHaveBeenCalledWith(DRAFT, RUN);
+ expect(letGo).toEqual([]);
+ });
+
+ it('stops only the run the editor names, when it names one', async () => {
+ const RUN = '99999999-9999-4999-8999-999999999999';
+ expect((await stop({ brandId: BRAND, runId: RUN })).status).toBe(200);
+ expect(stopDraftRun).toHaveBeenCalledWith(DRAFT, RUN);
+ expect((await stop({ brandId: BRAND, runId: 'not-a-run' })).status).toBe(400);
+ });
+
+ it('lets go of nothing when no run was under way', async () => {
+ stopDraftRun.mockResolvedValue([]);
+ expect(await (await stop()).json()).toEqual({ stopped: false });
+ expect(letGo).toEqual([]);
+ });
+
+ it('stops nothing of another brand’s draft, or on a bad request', async () => {
+ stopDraft = { brand_id: '44444444-4444-4444-4444-444444444444' };
+ expect((await stop()).status).toBe(404);
+ expect((await stop({})).status).toBe(400);
+ expect((await stop({ brandId: BRAND }, 'nope')).status).toBe(400);
+ expect(stopDraftRun).not.toHaveBeenCalled();
+ });
+
+ it('says a Fix open rules run was stopped', async () => {
+ fixDraftRules.mockRejectedValue(new RunStoppedError());
+ const res = await fetch(`${baseUrl}/${DRAFT}/suggestions`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ brandId: BRAND,
+ rules: [{ key: 'faq', name: 'FAQ', detail: '' }],
+ }),
+ });
+ expect(res.status).toBe(409);
+ expect(await res.json()).toMatchObject({ code: 'stopped' });
+ });
+});
diff --git a/supabase/migrations/00249_content_agent_runs.sql b/supabase/migrations/00249_content_agent_runs.sql
new file mode 100644
index 000000000..39f63be21
--- /dev/null
+++ b/supabase/migrations/00249_content_agent_runs.sql
@@ -0,0 +1,58 @@
+-- ============================================================================
+-- 00249: the Content Agent's runs, step by step
+-- ============================================================================
+-- Content Editor v1.1, CE-027 and CE-035: while the agent works, the editor
+-- shows its real steps, short names for the work the server does ("Reading 4
+-- rules → Gathering 52 sources → Writing 3 changes → Checking sources"), and
+-- Stop. The server writes each run here as it goes; the
+-- editor reads the draft's latest. Stop marks it stopped: the server drops
+-- whatever the run had and changes nothing.
+--
+-- A table of its own, not columns on content_drafts: a step written there
+-- would move the draft's updated_at, which the editor's saves check against.
+--
+-- steps: [{ "key", "count" }], key one of read_rules, gather_sources,
+-- write_changes, rewrite_page, write_page, write_outline, match_fanouts,
+-- check_sources; count null where there is none.
+-- step: the one under way (steps' index); all done once finished.
+-- outcome is what happened: a Stop that lands after the run's last check
+-- may leave stopped_at set on a run that ended 'done'. A run a stopped server
+-- left unfinished is closed 'failed' when the next starts on the draft.
+-- claimed_at: a Start or Rewrite run's claim on the draft (the
+-- content_drafts.agent_state_at it wrote); null for Fix and the brief, which
+-- hold no draft. A Stop lets go only of the claim the stopped run holds, so a
+-- Stop on a Fix leaves a Start on the same draft its claim.
+create table if not exists public.content_agent_runs (
+ id uuid primary key default gen_random_uuid(),
+ draft_id uuid not null references public.content_drafts (id) on delete cascade,
+ kind text not null check (kind in ('fix', 'rewrite', 'write', 'brief')),
+ steps jsonb not null check (
+ jsonb_typeof(steps) = 'array' and jsonb_array_length(steps) between 1 and 6
+ ),
+ step smallint not null default 0 check (step between 0 and 6),
+ started_at timestamptz not null default now(),
+ finished_at timestamptz,
+ stopped_at timestamptz,
+ outcome text check (outcome in ('done', 'stopped', 'failed')),
+ claimed_at timestamptz
+);
+
+-- For a database that ran this file before claimed_at was added to it.
+alter table public.content_agent_runs add column if not exists claimed_at timestamptz;
+
+create index if not exists content_agent_runs_draft_started
+ on public.content_agent_runs (draft_id, started_at desc);
+
+alter table public.content_agent_runs enable row level security;
+
+-- A draft the member can read is one in their organization (content_drafts'
+-- own member policies), so its runs follow it, as its suggestions do (00217).
+create policy "content_agent_runs: member select"
+ on public.content_agent_runs
+ for select
+ using (draft_id in (select d.id from public.content_drafts d));
+
+grant select on public.content_agent_runs to authenticated;
+
+comment on table public.content_agent_runs is
+ 'Content Editor v1.1 (CE-027/035): the Content Agent''s runs on a draft, step by step, and whether one was stopped (00249). Written by the server; read by the editor.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index b89bdb164..06a47f138 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -37211,6 +37211,68 @@ comment on column public.content_draft_suggestions.sources is
comment on column public.content_draft_suggestions.source_marks is
'The words each source supports: [{ "start", "end", "source" }], offsets into after_text (a replace) or an insert''s text, source an index into sources (00248).';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00249_content_agent_runs.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00249: the Content Agent's runs, step by step
+-- ============================================================================
+-- Content Editor v1.1, CE-027 and CE-035: while the agent works, the editor
+-- shows its real steps, short names for the work the server does ("Reading 4
+-- rules → Gathering 52 sources → Writing 3 changes → Checking sources"), and
+-- Stop. The server writes each run here as it goes; the
+-- editor reads the draft's latest. Stop marks it stopped: the server drops
+-- whatever the run had and changes nothing.
+--
+-- A table of its own, not columns on content_drafts: a step written there
+-- would move the draft's updated_at, which the editor's saves check against.
+--
+-- steps: [{ "key", "count" }], key one of read_rules, gather_sources,
+-- write_changes, rewrite_page, write_page, write_outline, match_fanouts,
+-- check_sources; count null where there is none.
+-- step: the one under way (steps' index); all done once finished.
+-- outcome is what happened: a Stop that lands after the run's last check
+-- may leave stopped_at set on a run that ended 'done'. A run a stopped server
+-- left unfinished is closed 'failed' when the next starts on the draft.
+-- claimed_at: a Start or Rewrite run's claim on the draft (the
+-- content_drafts.agent_state_at it wrote); null for Fix and the brief, which
+-- hold no draft. A Stop lets go only of the claim the stopped run holds, so a
+-- Stop on a Fix leaves a Start on the same draft its claim.
+create table if not exists public.content_agent_runs (
+ id uuid primary key default gen_random_uuid(),
+ draft_id uuid not null references public.content_drafts (id) on delete cascade,
+ kind text not null check (kind in ('fix', 'rewrite', 'write', 'brief')),
+ steps jsonb not null check (
+ jsonb_typeof(steps) = 'array' and jsonb_array_length(steps) between 1 and 6
+ ),
+ step smallint not null default 0 check (step between 0 and 6),
+ started_at timestamptz not null default now(),
+ finished_at timestamptz,
+ stopped_at timestamptz,
+ outcome text check (outcome in ('done', 'stopped', 'failed')),
+ claimed_at timestamptz
+);
+
+-- For a database that ran this file before claimed_at was added to it.
+alter table public.content_agent_runs add column if not exists claimed_at timestamptz;
+
+create index if not exists content_agent_runs_draft_started
+ on public.content_agent_runs (draft_id, started_at desc);
+
+alter table public.content_agent_runs enable row level security;
+
+-- A draft the member can read is one in their organization (content_drafts'
+-- own member policies), so its runs follow it, as its suggestions do (00217).
+create policy "content_agent_runs: member select"
+ on public.content_agent_runs
+ for select
+ using (draft_id in (select d.id from public.content_drafts d));
+
+grant select on public.content_agent_runs to authenticated;
+
+comment on table public.content_agent_runs is
+ 'Content Editor v1.1 (CE-027/035): the Content Agent''s runs on a draft, step by step, and whether one was stopped (00249). Written by the server; read by the editor.';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00250_traffic_anonymous_visitors.sql
-- ─────────────────────────────────────────────────────────────────────────