Skip to content

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

Merged
gkhngyk merged 52 commits into
ansvisor:mainfrom
cihan-gyk:feature/editor-agent-steps-server
Oct 23, 2026
Merged

gkhngyk merged 52 commits into
ansvisor:mainfrom
cihan-gyk:feature/editor-agent-steps-server

Conversation

@cihan-gyk

@cihan-gyk cihan-gyk commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Content Editor v1.1, CE-027 and CE-035 (server): every Content Agent run writes its steps as it reaches them, named by the data it reads, and Stop ends a run without changing anything.

Stacked on #1399 (CE-033 web), which is stacked on #1398 → … → #1387. Merge after them. Migration 00249, applied on the dev DB.

The web half follows as its own PR, stacked on this one. It adds step chips and Stop on the agent card and on the waiting page, and a dashed placeholder card in the draft.

Runs, step by step (content-runs.js, content_agent_runs)

  • One row per run: Fix open rules, Start with Agent (a new page, or suggestions on a live one), Rewrite the whole page, and the brief.
  • Each run has its steps with counts from the run:
Kind Steps
fix read_pages 20 → match_fanouts 21 → check_queries 10 → write_changes (its count once done)
rewrite read_sources 52 → rewrite_page 14 rules → check_rules
brief read_sources → pick_fanouts → write_outline
write read_sources → write_page → check_rules
  • The run moves its step on as it gets there, and ends done, stopped or failed.
  • It's 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.
  • RLS: members read the runs of drafts they can read, as 00217's suggestions do. Only the server writes.
  • Progress is shown, never relied on. A run that can't be written still runs, with no steps shown.
  • A run a stopped server left unfinished is closed failed when the next starts on the draft, and Stop ignores runs older than 10 minutes.

Stop

  • POST /api/content-drafts/:draftId/stop { brandId }:
    • checks brand access, and that the draft is the brand's;
    • marks the draft's run stopped and aborts its model call when the run is on this server;
    • answers { stopped }.
  • Every run checks the mark before it keeps anything, so a stopped run leaves:
    • no suggestions from Fix or Start's optimize;
    • no page from Start's new page or a rewrite;
    • no brief;
    • no History entry ("before the agent").
  • Fix and the brief answer 409 stopped. A background run lets go of the draft (agent_state back to null), not failed.
  • A model call's signal is the run's Stop or the call's own timeout (callSignal). A timeout ends as failed, not stopped.
  • A call already answered is charged, as before. A call aborted before an answer isn't.
  • Background runs (Start, Rewrite) are written before Start answers, so the editor's first read shows them and Stop finds them at once.
  • outcome is what happened. A Stop that lands after a run's last check may leave stopped_at on a run that ended done (noted in the migration).

After review (2026-10-23): a Stop that names a run lets go only of that run's own claim. The run row's new nullable claimed_at (in 00249, with add column if not exists for a database that ran the old file) is compared with agent_state_at. A run started by an older server has no claimed_at: a Stop doesn't release its claim, and the run releases it when it sees the stop, or it goes stale after 10 minutes.

Related issue

Content Editor v1.1 (Drive spec, 2026-10-23): CE-027 and CE-035, server half. No GitHub issue.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Apply 00249.
  2. Run Fix open rules on a draft. content_agent_runs gets a fix row, its step moves to 3 while the model writes, and it ends done with write_changes' count.
  3. During a run, POST /api/content-drafts/:id/stop. The run ends stopped, Fix answers 409 stopped, and nothing is added.
  4. Start with Agent on a new page, then Stop. The draft is let go (agent_state null), its page and History unchanged.

Tests:

  • content-runs.test.js:
    • steps by kind;
    • written, moved on and ended, with earlier unfinished runs closed first;
    • running when it can't be written;
    • Stop marking (only runs under way, not stale ones), aborting and refusing to keep;
    • a stop read from another server;
    • a timeout told from a stop.
  • content-agent.test.js: Fix keeps nothing once stopped; the call it made is still charged.
  • content-writer.test.js: Start stopped lets go, writes no page and adds no History.
  • content-brief.test.js: the brief isn't saved once stopped.
  • content-drafts.test.js: /stop for the draft, refused for another brand's draft or a bad request, and Fix's 409 stopped.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • npm run lint passes (run from server/)
  • npm test passes (run from server/) — 2,154 tests
  • Changes are focused — one concern per PR
  • Migration added, bash supabase/build-schema.sh run, supabase/schema.sql included

🤖 Generated with Claude Code

cihan-gyk and others added 19 commits October 23, 2026 02:24
The workspace's one AI budget (Improve, the Content Editor's AI and the
Action Center's task writer) had no meter: the first sign of it was an
"AI usage is used up" error. Migration 00242 records what each AI call
was for (prompt_improve_usage.feature, backfilled) and sums the period's
spend by feature (ai_usage_by_feature). GET /api/billing/ai-usage
returns the shares of the plan's budget, and the Billing page shows the
share used, when it resets and what used it, with Agent Chat noted as
running on the workspace's own key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The workspace's AI budget was checked by reading the period's spend; the
call's cost was written once the model answered. Calls running at once
(two tabs, a teammate, an Action Center sweep) all read the same spend
and all ran past the budget. 00243's reserve_ai_usage takes a
per-organization lock, reads the spend with the calls in flight, and
holds the call's estimated cost; reserveAiBudget turns the hold into the
real cost or releases it. Improve, the brief rebuild, Apply rules with
Agent, Start Agent and the Action Center task writer use it in place of
enforceImproveQuota, which goes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes:
- Apply rules with Agent and Start Agent charge an answer the provider
  billed but that missed the schema (NoObjectGeneratedError), as Improve,
  the brief and the task writer do; before, the hold was let go and the
  call ran free.
- A call holds the org's median cost over its last 20 calls this period,
  never less than the model's typical cost, so calls in flight pass the
  budget by far less.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apply rules with Agent makes at most 8 small edits a run, which can't
bring a long page to its Length (about 2% a run on prod). The Content
Agent can now rewrite the whole page in one background call, left as ONE
suggestion (kind 'page', migration 00247) to compare and accept or reject:
- POST /api/content-drafts/:draftId/rewrite, through Start Agent's claim,
  budget hold and background run;
- passages AI quotes today, tables, images, quotes and HTML blocks go to
  the model as [[KEEP n]] lines and come back as they were; a rewrite that
  drops one fails the run;
- one H1, only the page's own links and the ones offered, the editor's
  tags; the page as it was is kept on the suggestion (before_html).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Length

Review fixes:
- Kept blocks are described under the page (a quoted passage's words, a
  table's rows, an image's alt) and their text counts toward Length, so a
  rewrite aims at the whole page's length; with Length off it keeps the
  page's own. A kept H1 stays first, and the page's language is kept.
- The answer is taken out of a code fence, text left at its root goes in
  paragraphs, and an answer in Markdown fails the run.
- The page's own links stay exactly as written (query and anchor too).
- Kept blocks go back untouched (an empty table cell stays), only the
  page's first H1 counts as its title, a page that writes "[[KEEP" gets
  markers of its own, and a page that is only kept blocks isn't sent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…compare it

The Rules tab opens with the agent's two ways to meet its rules: Apply
rules with Agent (small edits, up to 8 a run) and Rewrite the page to
these rules (the whole page as one change). The rewrite is recommended,
with a one-line reason, when the page is more than 30% off its Length or
4 rules or more are open.

A rewritten page comes back as one suggestion with its own bar over the
page: the characters before and after and the agent's reason, Compare
(the page and the rewrite side by side), Accept (History keeps the page
first), Reject, and Undo. A page that changed since the agent read it
isn't written over. The page waits for the rewrite with its own steps,
and a failed rewrite's Try again rewrites again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes:
- A page is compared with the one the agent read by its words, with a
  space between blocks, so stored line breaks and lists don't read as a
  change (Accept and Undo were refused on imported pages).
- One agent run at a time from the page; a rewrite never starts before
  the locked passages are read, and sends the editor's own locked keys.
- Accept holds the page still from the start and checks it again before
  putting the rewrite in; Undo puts the page back as it was (two H1s too),
  and the bar waits while the HTML view is open.
- No rewrite advice for an empty page or one too long to send whole; the
  rewrite mark survives a reload; the waiting view says the rewrite waits
  in the editor; Compare's links don't navigate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content Editor v1.1, part 1 (CE-025, CE-026, §4): the agent row and the
rewrite bar become one card above the toolbar, in three states:
- waiting: "Content Agent has {n} suggestions for you", what they change
  and the rules they gain ("Rules 5 → 6 of 13"), with Review (scrolls to
  the first suggestion and marks it), Reject all and Accept all; a page
  rewritten shows its characters, with Compare;
- all reviewed: what was accepted and the rules met and still open, with
  Undo all and Run Agent;
- working: while Apply rules with Agent runs.
The tile moves a little (a soft ring, a blink, a spark; a sweep and a
breath while working), never a rotating ring, and not at all with reduced
motion. The card wraps on a narrow page; Accept all and Run Agent are the
primary buttons.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Run Agent on the card keeps to one agent run at a time and says why it
  waits; Apply rules never starts beside another run or before the locked
  passages are read.
- Ghost buttons show their hover on the card's grey; the tile and its
  count are hidden from screen readers (the title says it) and the count
  is darker for contrast; "+N more" comes from en.json, the reason's first
  letter is upper-cased in the page's locale.
- Review picks the first open suggestion in the page's order and focuses
  it; the sweep shows on the light tile in dark mode; the spark is slower
  once all are reviewed; without motion the working line is a faint full
  line; "0 still open" isn't said.
- globals.css keeps its own lines; only the motion block is added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…split Run Agent

Content Editor v1.1 part 2 (CE-028–CE-031): the side panel's tabs become
Instructions · Sources · Live page. Instructions holds Brief | Rules, with
the rules still open on the tab and the segment. Each segment opens with a
status card: Rules has one split Run Agent ▾ (Fix open rules, or Rewrite
the whole page, which renames it "Rewrite page") in place of the two rule
buttons; Brief has Run Agent while empty and Rebuild brief once written.
Why the agent can't run is written under the card, and each card's ⓘ tip
opens below it. The brief shows "Not set yet" and its Length in characters
and about as many words; the toolbar counter adds the page's words.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Run Agent's choice is worked out once and falls back to Fix without a
  rewrite; once a rewrite starts, the button is back on Fix.
- ▾'s choices are menu radio items; Fix is off when only rules the agent
  can't fix are open, and the card says what to do instead.
- The reason line under the card stays mounted for screen readers; Rewrite
  from brief writes its reason too; the tab's count is read out.
- Brief | Rules switch with the arrow keys, one tab stop.
- An edited brief's rebuild question sits under the card; a brief without
  H2s says to rebuild it; an empty brief shows no origin line.
- Plural copy for the open suggestions and the counter's words; rule names
  joined by the formatter; Run Agent's tip leaves ▾ out without a rewrite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content Editor v1.1 part 3 (CE-032, CE-034): under each Run Agent card,
"Uses your data: 1 prompt · 21 fan-outs · 20 cited pages · 10 Search
Console queries · Edit sources", counted as the Sources tab keeps them, so
turning one off lowers it at once. The Sources tab carries its count, and
its top says "N sources in use" and when the Content Agent last wrote from
them (its latest suggestions or the brief it built). A first visit's note
at the top of Instructions says the agent writes from the person's data;
closing it is kept in their own user metadata.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- "Last used by Content Agent" also counts the agent writing the page
  (agent_state_at: Start with Agent, Rewrite from brief on a new page),
  not a run that failed; a value that isn't a date is skipped.
- The latest batch's time is its first suggestion's, not a sort per render.
- Tests: the Brief segment's line, no line while the sources can't be read,
  the tab's count, the note showing again after a failed write, and a
  suggestion read with its createdAt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… name them

Content Editor v1.1, CE-033 (server): Fix open rules, Start with Agent and
Rewrite the whole page read the sources the Sources tab keeps, numbered
S1, S2… (content-sources.js). Each suggestion keeps the sources it names
and the words each supports (content_draft_suggestions.sources and
source_marks, 00248); a page rewritten whole keeps its sources.

No number without a source: the model reads a source by its words only, so
a number the agent adds must be the page's, the brand's, the brief's, the
rules', today's, or in a source's own words (then marked to it). A
suggestion with any other number is not kept; a page written whole gets a
placeholder in its place. Source numbers written into the words are taken
out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content Editor v1.1, CE-033 (web) and the rest of CE-034: under each
suggestion, "Based on" chips name the sources it used (number, kind, name;
the Sources tab's details on hover), and a small number marks the words
each supports. A click on either opens Sources on that row, scrolled to
and ringed for a moment, once. The agent card adds "built from N of your
sources · See sources". Fix open rules sends the kept sources, and the
first-visit note says every change shows the sources it used.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content Editor v1.1, CE-027/035 (server): each Content Agent run (Fix open
rules, Start with Agent, Rewrite the whole page, the brief) is written in
content_agent_runs (00249) with its steps named by the data it reads
("Reading 20 cited pages", "Matching 21 fan-outs", "Writing 3 changes") as
it reaches them. POST /api/content-drafts/:id/stop marks the run stopped
and aborts its model call; the run checks before it keeps anything, so a
stopped run changes nothing (no suggestions, page, brief or History).

A run that can't be written still runs; runs a stopped server left are
closed when the next starts, and Stop ignores them. Background runs are
written before Start answers, so Stop finds them at once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 23, 2026
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk CE-027/035 server half. Stacked on #1399. Migration 00249 adds a content_agent_runs table; it's applied on the dev DB.

  • Every agent run (Fix, Start, Rewrite, brief) writes its steps as it reaches them, e.g. "Reading 20 cited pages → … → Writing 3 changes".
  • POST /api/content-drafts/:id/stop aborts a run's model call. A stopped run keeps nothing: no suggestions, page, brief or History entry.
  • It's a table rather than content_drafts columns, so a step never moves the draft's updated_at, which autosave compares against.

Worth a look:

  • Stop aborts the model call only when the run is on the same server instance as the request. On another instance, the run sees the stopped mark after the call and drops the result. Either way nothing changes, but that call is still charged.
  • Unfinished rows from a crashed server are closed when the next run starts, and ignored after 10 minutes.

Deploy: 00249 → server → web. The web PR comes next and is stacked on this one.

Checks: server lint and 2,154 tests.

Stop also clears the draft's 'writing' state at once: a background run lets
go once it sees the stop, but one no server holds any more never would, and
the waiting page would wait out the 10 minutes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few fixes before merge:

  1. A call stopped while it is out isn't charged. On Stop, callSignal aborts generateObject. Nothing calls budget.charge, and the finally releases the hold (server/src/lib/content-agent.js:651-662, server/src/lib/content-brief.js:218-228, server/src/lib/content-writer.js:595-617). These are non-streaming requests: aborting our side of the connection doesn't stop the provider from finishing the call and billing it, so the budget misses that call's cost. When the run's own Stop aborts a call that was already sent, keep the hold as the charge. One way to do it:

    • add a keep() to the reserveAiBudget handle (server/src/lib/plan-guard.js:399-431) that marks the hold charged, so release() leaves the row at the hold's cost;
    • call keep() in the stop branch;
    • add await stopIfStopped(run) right before each generateObject, so a run stopped before its call still releases the hold.

    Simpler alternative: don't abort the call on Stop. Let it finish, charge its usage, and drop the result at stopIfStopped, which is already what happens when the stop is made on another server. Either way, add a test where a Stop during the call leaves a prompt_improve_usage row. (The call's own timeout has the same gap, but that predates this PR.)

  2. A stopped background run can clear a newer run's claim. The Stop route frees the draft at once (server/src/routes/content-drafts.js:202-211), so the person can press Start again right away. A run stopped from another server instance isn't aborted, though. It only sees the stop when its call returns, up to 3 minutes later. Then finish(draft.id, { agent_state: null }) (server/src/lib/content-writer.js:604) matches the new run's 'writing' claim and clears it. After that, the new run's own finish(..., { openOnly: true }) misses, so it drops its page or suggestions after they were charged, and another Start can claim the draft in the meantime. The same can happen with an old run whose Stop lands just after its last stopIfStopped. Tie finish to the run's own claim: keep the agent_state_at that the claim writes (server/src/lib/content-writer.js:420), pass it into the run, and add .eq('agent_state_at', claimedAt) to finish (server/src/lib/content-writer.js:452-462).

  3. (low) startRun closes runs that are still going (server/src/lib/content-runs.js:85-94). It marks every unfinished run on the draft failed, not only runs a stopped server left behind. Say a brief is rebuilt from a second tab, or by another member, while Fix runs. The Fix run is closed: its steps stop moving, and Stop can't reach it any more (stopDraftRun skips finished runs), so its suggestions still land after Stop. #1401 blocks Rebuild in the same editor, but not across tabs. Only close runs started before now - RUN_STALE_MS, the window Stop already uses. Stop then stops every run going on the draft.

Merge note: apply 00249 before the server deploy that carries this PR. Without the table, /stop answers 502; runs still work but log two warnings each. #1401 reads the table from the web, so 00249 must also be on prod before #1401 merges.

Checked and fine:

  • 00249: RLS is on, and members read runs only through drafts they can read, as with 00217. There are no write policies; only the server writes. The index covers the latest-run read, Stop's update and the close on start. Runs are deleted with their draft. schema.sql matches. supabase.ts gets the table in #1401, where the web first reads it.
  • /stop checks brand access and the draft's brand before anything else. It only marks runs that are still going and under 10 minutes old.
  • Every run checks for a stop before it keeps anything: suggestions, page, rewrite, brief or History. A timeout is told apart from a stop.
  • A call answered before the Stop is still charged, and so is a schema miss.
  • A run that can't be written still runs. Progress is a few small writes per run, and runs are bounded by the AI budget, so the table needs no retention.

cihan-gyk and others added 5 commits October 23, 2026 14:45
# Conflicts:
#	server/src/lib/content-writer.js
#	server/src/lib/content-writer.test.js
#	supabase/schema.sql
…le it writes

content_drafts.agent_run ('write' or 'rewrite', in 00247 and its guard) is
set when Start or a rewrite claims the draft, so every device knows a failed
rewrite from a failed Start. Fix open rules and the MCP suggest call answer
409 'writing' while a run holds the draft, so its answer is never dropped
after it was charged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…le it writes

content_drafts.agent_run ('write' or 'rewrite', in 00247 and its guard) is
set when Start or a rewrite claims the draft, so every device knows a failed
rewrite from a failed Start. Fix open rules and the MCP suggest call answer
409 'writing' while a run holds the draft, so its answer is never dropped
after it was charged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t-steps-server

Main squash-merged ansvisor#1389 and ansvisor#1393–ansvisor#1399; its tree is ansvisor#1399's last head
(b84e724), so this is that merge: this branch's changes on top of it.
cihan-gyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 23, 2026
ansvisor#1400 adds the column to 00249.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Fixed, and main merged.

A Stop lets go only of the claim the stopped run holds.

  • The run row gets a nullable claimed_at in 00249, with add column if not exists for a database that already ran the old 00249. schema.sql is rebuilt.
  • startRun writes the draft's claim time on the run.
  • stopDraftRun selects id, claimed_at and returns the runs it stopped.
  • The route clears agent_state with .eq('agent_state_at', claimed_at), once for each stopped run that has one.
  • Tests:
    • the route: a named Fix run is stopped and the draft's claim stays, and the existing stop test checks the filter;
    • runs: the claim is stored, and Stop returns it;
    • the writer: the run's claim equals the draft's.

Main merge. Main's tree is #1399's last head (b84e724), so the merge is that one: this branch's own changes on top of it. Nothing conflicted beyond the squash itself.

Deploy note. A run started by a server older than this has no claimed_at, so a Stop doesn't let go of its claim. The run lets go when it sees the stop, or the claim goes stale after 10 minutes.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. The fix from the last review is done (7f6a445).

A Stop lets go only of the claim the stopped run holds:

  • A Start or Rewrite run is written with the claim it holds: startWritingRun gets the held draft, so claimed_at is the same agent_state_at the claim wrote. Fix and the brief write null.
  • stopDraftRun returns the runs it stopped, with id, claimed_at.
  • The route clears agent_state once for each stopped run that has a claim, filtered on agent_state_at = claimed_at. Stopping a named Fix or brief run leaves a Start's claim alone.
  • With no runId (an older editor), it still stops every live run on the draft and lets go of the Start's claim, as before.
  • The route is the only place a Stop lets go of a draft.
  • Tests cover the route (a named Fix leaves the claim, and the existing stop test checks the filter), the stored claim and its return in content-runs, and the writer (the run's claim is the draft's).

Merge commit 55fb571: main's tree is #1399's last head (b84e724). Merging 7f6a445 with b84e724 gives exactly 55fb571's tree, so it hides no changes. Against main, the PR's diff is its own 14 files only.

The PR merges cleanly on main (main is its parent).

Migration 00249:

  • claimed_at timestamptz is in the create table. The add column if not exists covers a database that ran the old file.
  • schema.sql matches a rebuild from the migrations.
  • It isn't on prod. It only depends on content_drafts, which 00250 and 00251 don't touch, so it applies cleanly on top of prod now.
  • Apply order:
    1. 00249;
    2. then the server deploy that carries this PR;
    3. then #1401's web.

@gkhngyk
gkhngyk merged commit 6a32d9c into ansvisor:main Oct 23, 2026
5 checks passed
gkhngyk added a commit that referenced this pull request Oct 23, 2026