Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: undo an accepted editorial fix from the findings UI (#1609)
[._.]/ Adam Eivy78a288ced457
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f97491e457..0e19345749 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -57,6 +57,8 @@## Editorial checks+- **[issue-1609] Undo an accepted editorial fix — restore the pre-edit manuscript text and re-open the finding.** Accepting a suggested fix rewrote the manuscript with no quick way back: a mistaken acceptance meant hunting the spot and hand-reverting (or digging through the section's version history). Accept now **captures the section's pre-edit text** and offers an undo in two places: an **Undo** button on the success toast right after you accept (the immediate "oops"), and a per-finding **Undo fix** button on the accepted finding in the Editorial Checks triage list. Undo restores the exact pre-edit text and flips the finding back to *open*. The restore is itself a versioned stage write (it lands in the section's history like any edit), and it's guarded: if you kept editing the section after accepting, undo refuses rather than clobber that later work and points you to the version history instead. The snapshot is stored on the finding only while it's accepted (a re-open or dismiss drops it) and is optional + additive, so the synced review document stays backward-compatible with older peers. (`server/services/pipeline/manuscriptFix.js`, `server/services/pipeline/manuscriptReview.js`, `server/routes/pipeline/manuscript.js`, `client/src/services/apiPipeline.js`, `client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx`, `client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`)+- **[issue-1606] The editorial health panel's category and check breakdowns are now clickable — tap one to filter the findings list to it.** The "Open by category" and "Open by check" rows (and their regression flags) showed you *where* the problems were but weren't navigable: spotting a regressed category meant manually re-scanning the list for its findings. Each row whose findings you can triage is now a button that deep-links the triage filter to that category or check and scrolls the findings list into view; clicking the active row again clears the filter, and the row shows a highlighted state while it's the active filter. (Rows that only count findings the triage doesn't list — e.g. the "completeness" bucket — stay as plain text rather than linking to an empty list.) Because the filter writes the same URL query the toolbar uses, the resulting view stays deep-linkable. This also adds a proper **Category** filter to the triage toolbar — distinct from the existing scope filter, which is now correctly labeled **Scope** (its Noun/Scene/Issue/Series values were mislabeled "Category"). (`client/src/components/pipeline/editorial/EditorialHealthPanel.jsx`, `client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`, `client/src/lib/editorialChecks.js`)- **[issue-1608] Editorial findings are now deep-linkable by their comment id alone.** There was no direct URL to a single finding: to act on a `comment-…` id referenced elsewhere (a note, a chat, an agent hand-off) you had to open Editorial Checks, pick the right series, wait for it to load, then hunt the list. A new route — **`/pipeline/findings/:commentId`** — resolves the owning series for you and redirects straight to that finding in the manuscript editor, focused and ready to accept/dismiss/fix, reusing the exact deep-link the triage already produces (`findingManuscriptLink`). A new server endpoint (`GET /api/pipeline/findings/:commentId/locate`) scans every series' review for the id (comment ids are UUID-based, so the match is unambiguous) and returns `{ seriesId, comment }`, or 404 when no series owns it; the client `locatePipelineFinding` wrapper maps that 404 to a tidy "Finding not found" page with a path back to Editorial Checks (it may have been dismissed-and-cleared, or the link is stale). The resolver is a redirect, not a navigable destination (the target depends on the id), so it is intentionally left out of `NAV_COMMANDS` — the navigable surface stays the Editorial Checks page, which already carries the `findings` keyword for ⌘K/voice. (`server/services/pipeline/manuscriptReview.js`, `server/routes/pipeline/manuscript.js`, `client/src/services/apiPipeline.js`, `client/src/pages/PipelineFindingRedirect.jsx`, `client/src/App.jsx`)diff --git a/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx b/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsxindex ed14aaa97b..12a5ecac94 100644--- a/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx+++ b/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx@@ -35,7 +35,7 @@ import { fixEditsOf, selectedEditsFor } from '../manuscript/ManuscriptCommentCarimport InlineDiff from '../../ui/InlineDiff';import toast from '../../ui/Toast';import { useAsyncAction } from '../../../hooks/useAsyncAction';-import { acceptPipelineManuscriptFix, patchPipelineManuscriptComment } from '../../../services/api';+import { acceptPipelineManuscriptFix, patchPipelineManuscriptComment, undoPipelineManuscriptFix } from '../../../services/api';const SEVERITY_DOT = {high: 'bg-rose-400',@@ -147,6 +147,13 @@ function FindingRow({ seriesId, comment, onCommentChange, selected, onToggleSele() => patchPipelineManuscriptComment(seriesId, comment.id, { status: 'dismissed', dismissReason: 'false-positive' }, { silent: true }),{ errorMessage: 'Failed to flag false positive' },);+ const [runUndo, undoing] = useAsyncAction(+ () => undoPipelineManuscriptFix(seriesId, comment.id, { silent: true }),+ { errorMessage: 'Failed to undo the fix' },+ );+ // An accepted fix is undoable only while its pre-edit snapshot survives (#1609)+ // — captured on accept, dropped if the finding is later re-opened/dismissed.+ const canUndo = comment.status === 'accepted' && !!comment.acceptedSnapshot;const accept = async () => {const result = await runAccept();@@ -164,6 +171,12 @@ function FindingRow({ seriesId, comment, onCommentChange, selected, onToggleSeleconst result = await runFalsePositive();if (result?.comment) onCommentChange?.(result.comment);};+ const undo = async () => {+ const result = await runUndo();+ if (!result?.comment) return;+ onCommentChange?.(result.comment);+ toast.success('Fix undone — finding re-opened');+ };return (<li className="p-2.5 space-y-2">@@ -258,6 +271,21 @@ function FindingRow({ seriesId, comment, onCommentChange, selected, onToggleSele</div>) : null}</div>+ ) : canUndo ? (+ // Accepted finding — offer a per-finding undo that restores the pre-edit+ // manuscript text and re-opens it (#1609).+ <div className="flex flex-wrap items-center gap-1.5">+ <button+ type="button"+ onClick={undo}+ disabled={undoing}+ className="inline-flex items-center gap-1 rounded border border-port-border px-1.5 py-0.5 text-[10px] text-gray-400 hover:text-white hover:border-port-accent/40 disabled:opacity-40"+ title="Undo this fix — restore the pre-edit text and re-open the finding"+ >+ {undoing ? <Loader2 size={11} className="animate-spin" /> : <Undo2 size={11} />}+ Undo fix+ </button>+ </div>) : null}</li>);diff --git a/client/src/components/pipeline/editorial/EditorialFindingsTriage.test.jsx b/client/src/components/pipeline/editorial/EditorialFindingsTriage.test.jsxindex 83c3e2581a..f74715727e 100644--- a/client/src/components/pipeline/editorial/EditorialFindingsTriage.test.jsx+++ b/client/src/components/pipeline/editorial/EditorialFindingsTriage.test.jsx@@ -4,7 +4,7 @@ import { MemoryRouter } from 'react-router-dom';import EditorialFindingsTriage from './EditorialFindingsTriage';import { Toaster, toast } from '../../ui/Toast';import { findingManuscriptLink } from '../../../lib/editorialChecks';-import { acceptPipelineManuscriptFix, patchPipelineManuscriptComment } from '../../../services/api';+import { acceptPipelineManuscriptFix, patchPipelineManuscriptComment, undoPipelineManuscriptFix } from '../../../services/api';// Mock the whole api barrel — include every export the component tree touches.// EditorialFindingsTriage transitively imports ManuscriptCommentCard, which also@@ -13,6 +13,7 @@ import { acceptPipelineManuscriptFix, patchPipelineManuscriptComment } from '../vi.mock('../../../services/api', () => ({acceptPipelineManuscriptFix: vi.fn(),patchPipelineManuscriptComment: vi.fn(),+ undoPipelineManuscriptFix: vi.fn(),generatePipelineManuscriptFix: vi.fn(),}));@@ -425,3 +426,40 @@ describe('EditorialFindingsTriage', () => {await waitFor(() => expect(screen.getByText('Noisy finding')).toBeTruthy());});});++describe('EditorialFindingsTriage — per-finding undo of an accepted fix (#1609)', () => {+ beforeEach(() => {+ acceptPipelineManuscriptFix.mockReset();+ patchPipelineManuscriptComment.mockReset();+ undoPipelineManuscriptFix.mockReset();+ toast.dismiss();+ });++ it('offers Undo on an accepted finding with a snapshot and re-opens it on click', async () => {+ const onCommentChange = vi.fn();+ const comments = [+ // An open sibling keeps the group expanded so the accepted row renders.+ { id: 'open-1', checkId: 'naming.dissimilar-names', status: 'open', severity: 'low', problem: 'Still open' },+ {+ id: 'acc-1', checkId: 'naming.dissimilar-names', status: 'accepted', severity: 'high',+ problem: 'Accepted finding', acceptedSnapshot: { acceptedAt: 't', sections: [{ issueId: 'i1', stageId: 'prose', priorText: 'before' }] },+ },+ ];+ undoPipelineManuscriptFix.mockResolvedValue({ comment: { ...comments[1], status: 'open', acceptedSnapshot: null }, sections: [] });+ renderTriage({ comments, onCommentChange });++ const undoBtn = screen.getByRole('button', { name: /Undo fix/i });+ fireEvent.click(undoBtn);+ await waitFor(() => expect(undoPipelineManuscriptFix).toHaveBeenCalledWith('ser-1', 'acc-1', { silent: true }));+ await waitFor(() => expect(onCommentChange).toHaveBeenCalledWith(expect.objectContaining({ id: 'acc-1', status: 'open' })));+ });++ it('does NOT offer Undo on an accepted finding without a snapshot (older/synced record)', () => {+ const comments = [+ { id: 'open-1', checkId: 'naming.dissimilar-names', status: 'open', severity: 'low', problem: 'Still open' },+ { id: 'acc-2', checkId: 'naming.dissimilar-names', status: 'accepted', severity: 'high', problem: 'No snapshot' },+ ];+ renderTriage({ comments });+ expect(screen.queryByRole('button', { name: /Undo fix/i })).toBeNull();+ });+});diff --git a/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx b/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsxindex fe8588faa8..11dd243d96 100644--- a/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx+++ b/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx@@ -11,7 +11,7 @@*/import { useMemo, useState } from 'react';-import { Loader2, Sparkles, Check, X, Ban, Columns2, Rows2, Copy, ChevronLeft, ChevronRight } from 'lucide-react';+import { Loader2, Sparkles, Check, X, Ban, Columns2, Rows2, Copy, ChevronLeft, ChevronRight, Undo2 } from 'lucide-react';import InlineDiff from '../../ui/InlineDiff';import SideBySideDiff from '../../ui/SideBySideDiff';import toast from '../../ui/Toast';@@ -21,6 +21,7 @@ import useKeyboardShortcuts from '../../../hooks/useKeyboardShortcuts';import Kbd from '../../ui/Kbd';import {patchPipelineManuscriptComment, generatePipelineManuscriptFix, acceptPipelineManuscriptFix,+ undoPipelineManuscriptFix,} from '../../../services/api';import { SEVERITY_TONE, CATEGORY_LABEL } from './constants';@@ -65,6 +66,61 @@ function ShortcutHints({ hasNav, hasFix, hasFalsePositive }) {);}+// Success toast for an accepted fix that carries an inline Undo (#1609). The+// accepted comment leaves the open-note flow (its card unmounts as the editor+// auto-advances), so this self-contained toast — not the card — owns the+// immediate "oops, undo that" affordance. `onUndo` resolves true on success;+// once undone the toast swaps to a confirmation and clears itself.+export function UndoFixToast({ t, count, onUndo }) {+ const [undoing, setUndoing] = useState(false);+ const [undone, setUndone] = useState(false);+ const label = count === 1 ? 'Fix applied to the manuscript' : `${count} fixes applied to the manuscript`;+ return (+ <span className="flex items-center gap-3">+ <span className="inline-flex items-center gap-1.5 text-gray-200">+ <Check size={14} className="text-port-success shrink-0" />+ {undone ? 'Fix undone — finding re-opened' : label}+ </span>+ {!undone ? (+ <button+ type="button"+ disabled={undoing}+ onClick={async () => {+ setUndoing(true);+ const ok = await onUndo();+ setUndoing(false);+ if (ok) { setUndone(true); setTimeout(() => toast.dismiss(t.id), 1500); }+ }}+ className="inline-flex items-center gap-1 rounded border border-port-border px-2 py-0.5 text-xs text-port-accent hover:border-port-accent/50 disabled:opacity-40"+ >+ {undoing ? <Loader2 size={12} className="animate-spin" /> : <Undo2 size={12} />} Undo+ </button>+ ) : null}+ </span>+ );+}++// Show the accept confirmation + Undo toast. `applyResult` re-applies the undo's+// { comment, section, sections } through the same handler an accept uses.+export function showAcceptedFixToast({ seriesId, commentId, count, applyResult }) {+ toast(+ (t) => (+ <UndoFixToast+ t={t}+ count={count}+ onUndo={async () => {+ const undone = await undoPipelineManuscriptFix(seriesId, commentId, { silent: true })+ .catch((err) => { toast.error(err.message || 'Failed to undo the fix'); return null; });+ if (!undone) return false;+ applyResult?.(undone);+ return true;+ }}+ />+ ),+ { duration: 10000 },+ );+}+export function Badge({ comment }) {return (<span className="flex items-center gap-1.5">@@ -198,7 +254,12 @@ export default function ManuscriptCommentCard({const result = await runAccept(selected);if (!result) return;onAccepted(result);- toast.success(selected.length === 1 ? 'Fix applied to the manuscript' : `${selected.length} fixes applied to the manuscript`);+ showAcceptedFixToast({+ seriesId,+ commentId: result.comment?.id || comment.id,+ count: selected.length,+ applyResult: onAccepted,+ });};const dismiss = async () => {diff --git a/client/src/components/pipeline/manuscript/ManuscriptCommentCard.test.jsx b/client/src/components/pipeline/manuscript/ManuscriptCommentCard.test.jsxindex aa101a6ecc..cd2071f259 100644--- a/client/src/components/pipeline/manuscript/ManuscriptCommentCard.test.jsx+++ b/client/src/components/pipeline/manuscript/ManuscriptCommentCard.test.jsx@@ -1,17 +1,19 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, fireEvent, waitFor } from '@testing-library/react';import ManuscriptCommentCard from './ManuscriptCommentCard';-import { Toaster } from '../../ui/Toast';+import { Toaster, toast } from '../../ui/Toast';import {acceptPipelineManuscriptFix,patchPipelineManuscriptComment,generatePipelineManuscriptFix,+ undoPipelineManuscriptFix,} from '../../../services/api';vi.mock('../../../services/api', () => ({acceptPipelineManuscriptFix: vi.fn(),patchPipelineManuscriptComment: vi.fn(),generatePipelineManuscriptFix: vi.fn(),+ undoPipelineManuscriptFix: vi.fn(),}));const baseComment = {@@ -139,3 +141,32 @@ describe('ManuscriptCommentCard keyboard shortcuts (#1603)', () => {expect(patchPipelineManuscriptComment).not.toHaveBeenCalled();});});++describe('ManuscriptCommentCard — accept toast offers Undo (#1609)', () => {+ beforeEach(() => {+ acceptPipelineManuscriptFix.mockReset();+ undoPipelineManuscriptFix.mockReset();+ toast.dismiss(); // clear any accept toast left over from a prior test+ });++ it('shows an Undo action after accept, and clicking it undoes the fix', async () => {+ acceptPipelineManuscriptFix.mockResolvedValue({ comment: { ...withFix, status: 'accepted' }, sections: [] });+ undoPipelineManuscriptFix.mockResolvedValue({ comment: { ...withFix, status: 'open' }, sections: [] });+ const onAccepted = vi.fn();+ renderCard({ comment: withFix, onAccepted });++ pressKey('a');+ await waitFor(() => expect(acceptPipelineManuscriptFix).toHaveBeenCalled());+ // The success toast renders with an inline Undo button.+ const undoBtn = await screen.findByRole('button', { name: /undo/i });+ expect(screen.getByText('Fix applied to the manuscript')).toBeTruthy();++ fireEvent.click(undoBtn);+ await waitFor(() => expect(undoPipelineManuscriptFix).toHaveBeenCalledWith('ser-1', 'c1', { silent: true }));+ // The undo result is re-applied through onAccepted (re-opens the finding).+ await waitFor(() => expect(onAccepted).toHaveBeenCalledWith(expect.objectContaining({+ comment: expect.objectContaining({ status: 'open' }),+ })));+ expect(await screen.findByText(/Fix undone/i)).toBeTruthy();+ });+});diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 299938a466..3551cf6ed0 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -542,6 +542,16 @@ export const acceptPipelineManuscriptFix = (seriesId, commentId, { find, replace...options,});+// Undo a previously-accepted fix — restores the captured pre-edit manuscript+// text and re-opens the finding. No body (the snapshot lives on the comment).+// Returns { comment, section, sections } like accept, so callers reapply through+// the same path.+export const undoPipelineManuscriptFix = (seriesId, commentId, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/review/comments/${encodeURIComponent(commentId)}/undo`, {+ method: 'POST',+ ...options,+ });+// Versioned free-text save of one manuscript section. Snapshots the prior text// into history (revert via restorePipelineStageVersion). Returns { section }// where section.versions is the updated [{ runId, createdAt }] list.diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex 81643c7429..f6381f125e 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -2483,6 +2483,47 @@ describe('pipeline routes', () => {.send({ find: 'x' }); // legacy accept must still include `replace`expect(acceptMissingReplace.status).toBe(400);});++ it('accept captures an undo snapshot; undo restores the pre-edit text and re-opens (#1609)', async () => {+ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'One' });+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({+ stages: { prose: { output: 'Hello old world.', status: 'ready' } },+ });+ // Seed a review comment anchored to this issue by id (not number — the+ // shared test DB reuses series ids across tests, so a number lookup is+ // ambiguous; the explicit id resolves to this issue regardless).+ const { seedReviewFromFindings } = await import('../services/pipeline/manuscriptReview.js');+ const seeded = await seedReviewFromFindings(ser.body.id, [{+ problem: 'wording', anchorQuote: 'old', issueId: iss.body.id, stageId: 'prose',+ }]);+ const commentId = seeded.comments[0].id;++ // Accept applies the edit + records the pre-edit snapshot.+ const accepted = await request(app)+ .post(`/api/pipeline/series/${ser.body.id}/manuscript/review/comments/${commentId}/accept`)+ .send({ edits: [{ issueId: iss.body.id, stageId: 'prose', issueNumber: 1, find: 'old', replace: 'new' }] });+ expect(accepted.status).toBe(200);+ expect(accepted.body.comment.status).toBe('accepted');+ expect(accepted.body.comment.acceptedSnapshot.sections[0].priorText).toBe('Hello old world.');+ expect(accepted.body.section.content).toBe('Hello new world.');++ // Undo restores the pre-edit text and re-opens the finding.+ const undone = await request(app)+ .post(`/api/pipeline/series/${ser.body.id}/manuscript/review/comments/${commentId}/undo`)+ .send({});+ expect(undone.status).toBe(200);+ expect(undone.body.comment.status).toBe('open');+ expect(undone.body.comment.acceptedSnapshot).toBeNull();+ expect(undone.body.section.content).toBe('Hello old world.');++ // Undo again is a 400 — nothing left to undo.+ const again = await request(app)+ .post(`/api/pipeline/series/${ser.body.id}/manuscript/review/comments/${commentId}/undo`)+ .send({});+ expect(again.status).toBe(400);+ });});describe('audio stage routes', () => {diff --git a/server/routes/pipeline/manuscript.js b/server/routes/pipeline/manuscript.jsindex 01a54fe5b3..3fc5c9d23a 100644--- a/server/routes/pipeline/manuscript.js+++ b/server/routes/pipeline/manuscript.js@@ -209,6 +209,15 @@ router.post('/series/:id/manuscript/review/comments/:commentId/accept', asyncHanres.json(result);}));+// Undo a previously-accepted fix: restore the captured pre-edit text and re-open+// the finding (#1609). No body — the authoritative snapshot lives on the comment.+router.post('/series/:id/manuscript/review/comments/:commentId/undo', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const result = await manuscriptFix.undoManuscriptFix(req.params.id, { commentId: req.params.commentId })+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));+// Versioned free-text save of one manuscript section (snapshots the prior text// into history so the edit is revertible). Revert reuses the stage-restore route// (POST /issues/:id/stages/:stageId/restore).diff --git a/server/services/pipeline/manuscriptFix.js b/server/services/pipeline/manuscriptFix.jsindex 8f9d7f9f8c..e723df4ad0 100644--- a/server/services/pipeline/manuscriptFix.js+++ b/server/services/pipeline/manuscriptFix.js@@ -12,7 +12,7 @@* arcPlanner.js (which owns the completeness pass that creates the comments).*/-import { randomUUID } from 'crypto';+import { randomUUID, createHash } from 'crypto';import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';import { planManuscriptPass, estimateTokens } from '../../lib/contextBudget.js';import { getSeries, MANUSCRIPT_TYPES } from './series.js';@@ -28,6 +28,11 @@ const makeErr = (message, code) => Object.assign(new Error(message), { code });// Mirrors arcPlanner's stageTextOf (inlined there to avoid an import cycle).const stageTextOf = (stage) => (stage?.output?.trim() || stage?.input?.trim() || '');+// Fingerprint of stage text — stamped at accept so undo can tell whether the+// section still holds exactly what the fix wrote (and so refuse to clobber any+// later edit). Cheap; the text is already in memory.+const textHash = (s) => createHash('sha256').update(typeof s === 'string' ? s : '', 'utf8').digest('hex');+async function loadStageText(issueId, stageId) {const issue = await getIssue(issueId).catch(() => null);if (!issue) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);@@ -575,6 +580,59 @@ export async function acceptManuscriptFix(seriesId, { commentId, find, replace,const planned = await planEditsBySection(acceptedEdits, comment);const sections = await applyPlannedEdits(seriesId, planned);- const updated = await updateComment(seriesId, commentId, { status: 'accepted' });+ // Capture the pre-edit text per section so the accept is undoable (#1609).+ // `priorText` is the full pre-fix stage text (exact restore for any edit+ // shape); `appliedHash` fingerprints what we just wrote so undo can detect a+ // later edit and bail instead of clobbering it. Hash the PERSISTED section+ // text (`sections[i].content`, aligned to `planned` order) — the same+ // `stageTextOf` normalization undo reads — so a freshly-accepted, untouched+ // section always matches (hashing raw `g.output` could differ by boundary+ // whitespace and falsely trip the guard).+ const acceptedSnapshot = {+ acceptedAt: new Date().toISOString(),+ sections: planned.map((g, i) => ({+ issueId: g.issueId,+ stageId: g.stageId,+ priorText: g.originalText,+ appliedHash: textHash(sections[i]?.content ?? g.output),+ })),+ };+ const updated = await updateComment(seriesId, commentId, { status: 'accepted', acceptedSnapshot });return { comment: updated, section: sections[0] || null, sections };}++/**+ * Undo a previously-accepted fix: restore each touched section's pre-edit text+ * (captured in `comment.acceptedSnapshot`) and re-open the finding. The restore+ * is itself a versioned stage write (`snapshotPrior`), so it lands in runHistory+ * and is reversible like any edit. Bails (ERR_VALIDATION) when the section has+ * drifted since accept — a blind restore would clobber that later work, so we+ * point the user at the version history instead. Returns refreshed manuscript+ * sections + the re-opened comment, mirroring acceptManuscriptFix's shape so the+ * client applies the result through the same path.+ */+export async function undoManuscriptFix(seriesId, { commentId } = {}) {+ const comment = await getComment(seriesId, commentId);+ if (!comment) throw makeErr(`Comment not found: ${commentId}`, ERR_NOT_FOUND);+ const snapshot = comment.acceptedSnapshot;+ if (!snapshot || !Array.isArray(snapshot.sections) || snapshot.sections.length === 0) {+ throw makeErr('There is no accepted edit to undo for this finding', ERR_VALIDATION);+ }+ const updates = snapshot.sections.map((s) => ({+ issueId: s.issueId,+ stageId: s.stageId,+ computeFn: (cur) => {+ if (s.appliedHash && textHash(stageTextOf(cur)) !== s.appliedHash) {+ throw makeErr(+ 'The manuscript changed since this fix was accepted, so undo is unavailable — revert via the section version history instead',+ ERR_VALIDATION,+ );+ }+ return { output: s.priorText, status: 'edited', lastRunId: `undo-${randomUUID()}` };+ },+ }));+ const updated = await updateStagesWithLatest(seriesId, updates, { snapshotPrior: true });+ const sections = updated.map(({ issue, stage }, i) => sectionFrom(issue, snapshot.sections[i].stageId, stage));+ const updatedComment = await updateComment(seriesId, commentId, { status: 'open', acceptedSnapshot: null });+ return { comment: updatedComment, section: sections[0] || null, sections };+}diff --git a/server/services/pipeline/manuscriptFixUndo.test.js b/server/services/pipeline/manuscriptFixUndo.test.jsnew file mode 100644index 0000000000..66190e0916--- /dev/null+++ b/server/services/pipeline/manuscriptFixUndo.test.js@@ -0,0 +1,115 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';++// In-memory issue + review stores so acceptManuscriptFix/undoManuscriptFix+// round-trip through the same persistence shape the real services use, without+// touching disk. Names are `mock`-prefixed so vitest's hoisted vi.mock factories+// may reference them (#1609).+const mockIssues = new Map();+const mockComments = new Map();++vi.mock('./series.js', () => ({+ getSeries: vi.fn(async () => ({ id: 'ser-1', name: 'S' })),+ MANUSCRIPT_TYPES: ['prose', 'comicScript', 'teleplay'],+}));++vi.mock('./arcPlanner.js', () => ({+ // resolveTargets resolves a comment's section here.+ collectManuscriptSections: vi.fn(async () => (+ [...mockIssues.values()].map((iss) => ({+ issueId: iss.id,+ stageId: 'prose',+ number: iss.number,+ title: iss.title || '',+ content: iss.stages.prose?.output || '',+ }))+ )),+ stageVersionsOf: () => [],+ sectionsCorpus: (sections) => sections.map((s) => s.content || '').join('\n'),+ manuscriptSectionHeader: (s) => `Issue ${s.number}`,+}));++vi.mock('./issues.js', () => ({+ getIssue: vi.fn(async (id) => mockIssues.get(id) || null),+ updateStageWithLatest: vi.fn(),+ // Mirror the real serialized write: call each computeFn against the freshest+ // stage, persist the merged patch, return [{ issue, stage }] in update order.+ updateStagesWithLatest: vi.fn(async (_seriesId, updates) => updates.map((u) => {+ const issue = mockIssues.get(u.issueId);+ const cur = issue.stages[u.stageId];+ const patch = u.computeFn(cur);+ const stage = { ...cur, ...patch };+ issue.stages[u.stageId] = stage;+ return { issue, stage };+ })),+}));++vi.mock('./manuscriptReview.js', () => ({+ getComment: vi.fn(async (_seriesId, id) => mockComments.get(id) || null),+ updateComment: vi.fn(async (_seriesId, id, patch) => {+ const cur = mockComments.get(id);+ const next = { ...cur, ...patch };+ // Mimic the real sanitizer's status-gating of the undo snapshot so the test+ // exercises the same drop-on-reopen contract.+ if (next.status !== 'accepted') next.acceptedSnapshot = null;+ mockComments.set(id, next);+ return next;+ }),+}));++import { acceptManuscriptFix, undoManuscriptFix } from './manuscriptFix.js';++function seed({ content = 'Hello old world.' } = {}) {+ mockIssues.clear();+ mockComments.clear();+ mockIssues.set('i1', { id: 'i1', number: 1, title: 'One', stages: { prose: { output: content, status: 'ready' } } });+ mockComments.set('mrc-1', {+ id: 'mrc-1', issueId: 'i1', stageId: 'prose', issueNumber: 1,+ anchorQuote: 'old', problem: 'wording', status: 'open',+ fix: { find: 'old', replace: 'new', edits: [{ issueId: 'i1', stageId: 'prose', issueNumber: 1, find: 'old', replace: 'new' }] },+ });+}++describe('acceptManuscriptFix — captures an undo snapshot (#1609)', () => {+ beforeEach(seed);++ it('records the pre-edit text + applied hash, then undo restores it and re-opens', async () => {+ const accepted = await acceptManuscriptFix('ser-1', {+ commentId: 'mrc-1',+ edits: [{ issueId: 'i1', stageId: 'prose', issueNumber: 1, find: 'old', replace: 'new' }],+ });+ // The edit applied.+ expect(mockIssues.get('i1').stages.prose.output).toBe('Hello new world.');+ expect(accepted.comment.status).toBe('accepted');+ // The snapshot captured the section's pre-edit text.+ const snap = accepted.comment.acceptedSnapshot;+ expect(snap.sections).toEqual([+ expect.objectContaining({ issueId: 'i1', stageId: 'prose', priorText: 'Hello old world.' }),+ ]);+ expect(snap.sections[0].appliedHash).toMatch(/^[0-9a-f]{64}$/);++ // Undo restores the pre-edit text and re-opens the finding.+ const undone = await undoManuscriptFix('ser-1', { commentId: 'mrc-1' });+ expect(mockIssues.get('i1').stages.prose.output).toBe('Hello old world.');+ expect(undone.comment.status).toBe('open');+ expect(undone.comment.acceptedSnapshot).toBeNull();+ expect(undone.sections[0].content).toBe('Hello old world.');+ });++ it('refuses to undo when the section changed since accept (no clobber)', async () => {+ await acceptManuscriptFix('ser-1', {+ commentId: 'mrc-1',+ edits: [{ issueId: 'i1', stageId: 'prose', issueNumber: 1, find: 'old', replace: 'new' }],+ });+ // The user keeps editing the section after accepting.+ mockIssues.get('i1').stages.prose.output = 'Hello new world. Plus more.';+ await expect(undoManuscriptFix('ser-1', { commentId: 'mrc-1' }))+ .rejects.toThrow(/changed since this fix was accepted/i);+ // The later edit is preserved (no restore happened).+ expect(mockIssues.get('i1').stages.prose.output).toBe('Hello new world. Plus more.');+ });++ it('throws when the comment has no accepted snapshot to undo', async () => {+ await expect(undoManuscriptFix('ser-1', { commentId: 'mrc-1' }))+ .rejects.toThrow(/no accepted edit to undo/i);+ });+});diff --git a/server/services/pipeline/manuscriptReview.js b/server/services/pipeline/manuscriptReview.jsindex 853b0eb8eb..5c1322df82 100644--- a/server/services/pipeline/manuscriptReview.js+++ b/server/services/pipeline/manuscriptReview.js@@ -94,6 +94,36 @@ function sanitizeFix(raw) {return out;}+// Snapshot of the manuscript text a fix overwrote, captured at accept-time so+// the finding can be undone back to its pre-edit state (#1609). `priorText` is+// the section's FULL stage text before the fix applied (full restore handles+// every edit shape — multi-edit, deletion, full-page rewrite — exactly, unlike+// a span-level reverse-splice); `appliedHash` is a fingerprint of the text the+// accept WROTE, so undo can detect later edits and refuse to clobber them. Only+// carried while `status === 'accepted'` (a status flip drops it, mirroring+// `dismissReason`). Optional + additive → older peers ignore it and the synced+// review doc stays backward-compatible (no schema bump needed).+function sanitizeAcceptedSnapshot(raw) {+ if (!raw || typeof raw !== 'object' || !Array.isArray(raw.sections)) return null;+ const sections = raw.sections+ .map((s) => {+ if (!s || typeof s !== 'object') return null;+ const issueId = typeof s.issueId === 'string' && s.issueId ? s.issueId : null;+ const stageId = typeof s.stageId === 'string' && s.stageId ? s.stageId : null;+ const priorText = typeof s.priorText === 'string' ? s.priorText : null;+ if (!issueId || !stageId || priorText == null) return null;+ const out = { issueId, stageId, priorText };+ if (typeof s.appliedHash === 'string' && s.appliedHash) out.appliedHash = s.appliedHash;+ return out;+ })+ .filter(Boolean);+ if (!sections.length) return null;+ return {+ acceptedAt: typeof raw.acceptedAt === 'string' ? raw.acceptedAt : new Date().toISOString(),+ sections,+ };+}+// Shape one stored comment. Tolerant of partial/legacy records so a hand-edited// or older-peer file round-trips without dropping fields.function sanitizeComment(raw) {@@ -102,6 +132,7 @@ function sanitizeComment(raw) {if (!problem) return null;const category = clampStr(raw.category, 40) || 'other';const severity = ['high', 'medium', 'low'].includes(raw.severity) ? raw.severity : 'medium';+ const status = STATUS_SET.has(raw.status) ? raw.status : 'open';return {id: typeof raw.id === 'string' && raw.id ? raw.id : `mrc-${randomUUID()}`,issueNumber: Number.isInteger(raw.issueNumber) ? raw.issueNumber : null,@@ -138,7 +169,7 @@ function sanitizeComment(raw) {// findings, older peers, and legacy records (treated as never-stale).// Optional + additive, so the synced review doc stays backward-compatible.sourceContentHash: typeof raw.sourceContentHash === 'string' && raw.sourceContentHash ? raw.sourceContentHash : null,- status: STATUS_SET.has(raw.status) ? raw.status : 'open',+ status,// Dismissal reason (#1605) — only carried while dismissed. A status flip// back to open/accepted drops it here so a re-opened finding can't keep a// stale `false-positive` mark. Legacy/older-peer records lack the field and@@ -147,6 +178,11 @@ function sanitizeComment(raw) {? raw.dismissReason: null,fix: sanitizeFix(raw.fix),+ // Pre-edit snapshot for undo (#1609) — only meaningful once accepted, so a+ // re-open/dismiss flip drops it (the undo path also clears it explicitly).+ acceptedSnapshot: status === 'accepted'+ ? sanitizeAcceptedSnapshot(raw.acceptedSnapshot)+ : null,sourceRunId: typeof raw.sourceRunId === 'string' ? raw.sourceRunId : null,createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString(),updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : new Date().toISOString(),@@ -397,6 +433,11 @@ export async function updateComment(seriesId, commentId, patch) {}// `fix: null` is an explicit clear; absent leaves it untouched.if (patch.fix !== undefined) merged.fix = sanitizeFix(patch.fix);+ // Pre-edit undo snapshot (#1609). `null` is an explicit clear (the undo+ // path); absent leaves it untouched. sanitizeComment below drops it anyway+ // whenever the resulting status isn't `accepted`, so re-opening a finding+ // can't leave a stale snapshot behind.+ if (patch.acceptedSnapshot !== undefined) merged.acceptedSnapshot = patch.acceptedSnapshot;merged.updatedAt = new Date().toISOString();const next = { ...review, comments: review.comments.map((c, i) => (i === idx ? sanitizeComment(merged) : c)) };await writeReview(seriesId, next);diff --git a/server/services/pipeline/manuscriptReview.test.js b/server/services/pipeline/manuscriptReview.test.jsindex 2ddc9a5b5d..e565270d50 100644--- a/server/services/pipeline/manuscriptReview.test.js+++ b/server/services/pipeline/manuscriptReview.test.js@@ -530,3 +530,45 @@ describe('manuscriptReview — locateComment (cross-series deep-link resolver, #expect(await locateComment(undefined)).toBeNull();});});++describe('manuscriptReview — accepted-fix undo snapshot (#1609)', () => {+ beforeEach(() => { fileStore.clear(); });++ const snapshot = () => ({+ acceptedAt: '2026-06-25T00:00:00.000Z',+ sections: [{ issueId: 'i1', stageId: 'prose', priorText: 'Before.', appliedHash: 'a'.repeat(64) }],+ });++ it('persists the snapshot while accepted and round-trips it through getReview', async () => {+ const seeded = await seedReviewFromFindings('ser-1', [{ problem: 'P', anchorQuote: 'q' }]);+ const id = seeded.comments[0].id;+ const updated = await updateComment('ser-1', id, { status: 'accepted', acceptedSnapshot: snapshot() });+ expect(updated.status).toBe('accepted');+ expect(updated.acceptedSnapshot.sections[0]).toMatchObject({ issueId: 'i1', stageId: 'prose', priorText: 'Before.' });+ const review = await getReview('ser-1');+ expect(review.comments[0].acceptedSnapshot.sections[0].priorText).toBe('Before.');+ });++ it('drops the snapshot when the comment is re-opened (status gate)', async () => {+ const seeded = await seedReviewFromFindings('ser-1', [{ problem: 'P', anchorQuote: 'q' }]);+ const id = seeded.comments[0].id;+ await updateComment('ser-1', id, { status: 'accepted', acceptedSnapshot: snapshot() });+ const reopened = await updateComment('ser-1', id, { status: 'open' });+ expect(reopened.status).toBe('open');+ expect(reopened.acceptedSnapshot).toBeNull();+ });++ it('drops a malformed snapshot (missing priorText) and an open-comment snapshot', async () => {+ const seeded = await seedReviewFromFindings('ser-1', [{ problem: 'P', anchorQuote: 'q' }]);+ const id = seeded.comments[0].id;+ // Snapshot on an open comment never persists.+ const stillOpen = await updateComment('ser-1', id, { acceptedSnapshot: snapshot() });+ expect(stillOpen.acceptedSnapshot).toBeNull();+ // Accepted but malformed (no priorText) sanitizes to null.+ const bad = await updateComment('ser-1', id, {+ status: 'accepted',+ acceptedSnapshot: { sections: [{ issueId: 'i1', stageId: 'prose' }] },+ });+ expect(bad.acceptedSnapshot).toBeNull();+ });+});