Skip to content

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

fix: stale badge on editorial-check findings when analyzed content changes (#1345)

Adam Eivy4879e0cc6312
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b6fa3f6545..d4f8fe5cbb 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -79,6 +79,8 @@
## Fixed
+- **[issue-1345] Editorial-check findings now show a "stale" badge when the manuscript or canon they analyzed has since changed.** #1285's acceptance called for a stale badge on findings — mirroring the editorial-analysis snapshot's `sourceContentHash` — but the editorial-check runner seeded findings into the manuscript review without recording any per-check source hash, so the UI had nothing to compare against and the badge shipped missing. The runner now **stamps each finding with a fingerprint of the exact content its check analyzed**: a manuscript-consuming check hashes the stitched corpus + canon, while a canon-only check (naming, object-attachment) hashes canon alone — so a prose edit doesn't falsely stale a finding that never read the prose. The manuscript-review GET annotates each finding with a `stale` flag (computed per-read, never stored, so it stays local to each install's current content), and the Editorial Checks triage view surfaces an amber **Stale** badge per-finding plus a per-check **"N stale"** count in the group header. Re-running a check against edited content refreshes the finding's hash (clearing the badge), and the hash survives cross-machine sync (additive, sanitized through the same shaper) while legacy/completeness findings with no hash are treated as never-stale. (`server/services/pipeline/editorial/checkRunner.js`, `server/services/pipeline/manuscriptReview.js`, `server/routes/pipeline/manuscript.js`, `client/src/lib/editorialChecks.js`, `client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`, #1345)
+
- **[issue-1328] When a sync peer is too old to understand a new kind of record, you now see "this peer needs to update PortOS" instead of a silent retry that never lands.** PortOS already surfaces a "peer is behind — they need to update" badge on the Instances page when a peer rejects a push because its storage layout is older than yours. But that badge only appeared for peers that recognized the *record* and balked at its *version* — the first time a brand-new kind of record ships (author personas were the latest; media collections did the same when they arrived), a peer running a PortOS version old enough to not know that record kind at all would reject the push one step earlier, and the rejection slipped past the badge: the push just kept quietly retrying on every edit, with nothing in the UI explaining why that record never reached the peer. Now that earlier rejection is recognized too, so the same "peer needs to update PortOS to sync \<record kind\>" badge appears and the retries back off until the peer upgrades — at which point the record syncs automatically. No data is ever lost: the push simply waits for the peer to catch up. (#1328)
- **[issue-1327] Uploaded (non-gallery) author headshots now transfer to federated peers.** The authors federation only shipped a headshot's image bytes when its `headshotImageUrl` pointed at `/data/images/<f>` (a gallery-picked image) — `headshotImageFilename()` maps that to the `image` asset the peer-sync pull worker fetches. But the Authors page's **upload** button routed through the generic `POST /api/uploads`, storing the file in `data/uploads/` and setting `headshotImageUrl = /api/uploads/<f>`, which is **not** a pullable asset kind — so on a peer the author record synced but the headshot 404'd. Author-headshot uploads now go through the gallery instead: a new `POST /api/image-gen/upload` saves the uploaded bytes into `data/images/` — sniffing the real format from the magic bytes (PNG/JPEG/WebP/GIF), rejecting non-image payloads, and re-encoding to PNG so the saved file is a first-class gallery citizen (it lists in the gallery and deletes through the gallery API, both PNG-only) — and returns a `/data/images/<f>` URL, so the headshot rides the existing `image` pull path and its bytes reach every peer. The magic-byte sniffer is consolidated into a shared `detectImageFormat()` in `fileUtils.js` (reused by `imageClean.js`). (`server/lib/fileUtils.js`, `server/lib/imageClean.js`, `server/services/imageGen/local.js`, `server/routes/imageGen.js`, `client/src/services/apiSystem.js`, `client/src/pages/Authors.jsx`, #1327)
diff --git a/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx b/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx
index d8c8fc762a..66c17b87e0 100644
--- a/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx
+++ b/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx
@@ -7,7 +7,7 @@
* only, so triage logic stays in one place.
*/
import { Link } from 'react-router-dom';
-import { ChevronDown, ChevronRight, ExternalLink } from 'lucide-react';
+import { ChevronDown, ChevronRight, ExternalLink, History } from 'lucide-react';
import { useMemo, useState } from 'react';
import { groupFindingsByCheck, findingManuscriptLink, openFindingsTotal } from '../../../lib/editorialChecks';
@@ -35,6 +35,22 @@ function CountPills({ counts }) {
);
}
+// Findings whose analyzed manuscript/canon changed since the check last ran
+// (#1345) — re-run the check (or dismiss) so the finding reflects current content.
+function StaleBadge({ count }) {
+ return (
+ <span
+ className="flex items-center gap-1 rounded-full bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-medium text-amber-400"
+ title={count != null
+ ? `${count} open finding${count === 1 ? '' : 's'} analyzed content that has since changed — re-run this check`
+ : 'Analyzed content has changed since this check ran — re-run the check'}
+ >
+ <History size={10} className="shrink-0" />
+ {count != null ? `${count} stale` : 'Stale'}
+ </span>
+ );
+}
+
function CheckGroup({ seriesId, group }) {
const [open, setOpen] = useState(group.open > 0);
return (
@@ -50,7 +66,10 @@ function CheckGroup({ seriesId, group }) {
<span className="text-sm font-medium text-gray-100 truncate">{group.label}</span>
<span className="text-[10px] text-gray-500 shrink-0">{group.open} open · {group.total} total</span>
</span>
- <CountPills counts={group.counts} />
+ <span className="flex items-center gap-1.5 shrink-0">
+ {group.stale > 0 ? <StaleBadge count={group.stale} /> : null}
+ <CountPills counts={group.counts} />
+ </span>
</button>
{open ? (
<ul className="divide-y divide-port-border/60 border-t border-port-border/60">
@@ -65,7 +84,10 @@ function CheckGroup({ seriesId, group }) {
<span className={`mr-1.5 inline-block h-2 w-2 rounded-full align-middle ${SEVERITY_DOT[c.severity] || SEVERITY_DOT.low}`} />
{c.problem}
</span>
- {c.location ? <span className="block text-[11px] text-gray-500">{c.location}</span> : null}
+ <span className="flex items-center gap-2">
+ {c.location ? <span className="block text-[11px] text-gray-500">{c.location}</span> : null}
+ {c.status === 'open' && c.stale ? <StaleBadge /> : null}
+ </span>
</span>
<ExternalLink size={13} className="mt-0.5 shrink-0 text-gray-600 group-hover:text-port-accent" />
</Link>
diff --git a/client/src/components/pipeline/editorial/EditorialFindingsTriage.test.jsx b/client/src/components/pipeline/editorial/EditorialFindingsTriage.test.jsx
index 0541019b45..8e6c966a23 100644
--- a/client/src/components/pipeline/editorial/EditorialFindingsTriage.test.jsx
+++ b/client/src/components/pipeline/editorial/EditorialFindingsTriage.test.jsx
@@ -29,4 +29,26 @@ describe('EditorialFindingsTriage', () => {
const link = screen.getByText('Confusable names: Alice / Adam').closest('a');
expect(link.getAttribute('href')).toBe(findingManuscriptLink('ser-1', comments[0]));
});
+
+ it('renders a stale badge (group + per-finding) when an open finding is stale (#1345)', () => {
+ const comments = [
+ { id: 'c1', checkId: 'naming.dissimilar-names', status: 'open', severity: 'high', problem: 'Stale finding', stale: true },
+ { id: 'c2', checkId: 'naming.dissimilar-names', status: 'open', severity: 'low', problem: 'Fresh finding' },
+ ];
+ renderTriage({ comments });
+ // Group header badge ("1 stale") + per-finding badge ("Stale") = 2 badges.
+ expect(screen.getByText('1 stale')).toBeTruthy();
+ expect(screen.getByText('Stale')).toBeTruthy();
+ });
+
+ it('does NOT render a stale badge when no open finding is stale', () => {
+ const comments = [
+ { id: 'c1', checkId: 'naming.dissimilar-names', status: 'open', severity: 'high', problem: 'Fresh finding' },
+ // A dismissed-but-stale finding must not surface a badge.
+ { id: 'c2', checkId: 'naming.dissimilar-names', status: 'dismissed', severity: 'low', problem: 'Old', stale: true },
+ ];
+ renderTriage({ comments });
+ expect(screen.queryByText('Stale')).toBeNull();
+ expect(screen.queryByText(/stale/i)).toBeNull();
+ });
});
diff --git a/client/src/lib/editorialChecks.js b/client/src/lib/editorialChecks.js
index 1103eb2827..a8726baf3b 100644
--- a/client/src/lib/editorialChecks.js
+++ b/client/src/lib/editorialChecks.js
@@ -44,10 +44,12 @@ const emptyCounts = () => ({ high: 0, medium: 0, low: 0 });
* Group review comments that came from an editorial check into per-check
* sections for the triage view. Only comments carrying a `checkId` are
* included (completeness findings have none). Returns
- * `[{ checkId, label, scope, kind, comments, open, total, counts }]`
+ * `[{ checkId, label, scope, kind, comments, open, total, counts, stale }]`
* ordered by the catalog's scope order then label, with `counts` tallying the
- * OPEN comments by severity. `rowsById` is a Map/object of catalog rows so each
- * group can show its human label even when the check is currently disabled.
+ * OPEN comments by severity and `stale` counting the OPEN findings whose
+ * analyzed content has drifted since the check ran (#1345). `rowsById` is a
+ * Map/object of catalog rows so each group can show its human label even when
+ * the check is currently disabled.
*/
export function groupFindingsByCheck(comments = [], rowsById = {}) {
const lookup = rowsById instanceof Map ? rowsById : new Map(Object.entries(rowsById || {}));
@@ -65,6 +67,7 @@ export function groupFindingsByCheck(comments = [], rowsById = {}) {
open: 0,
total: 0,
counts: emptyCounts(),
+ stale: 0,
});
}
const g = groups.get(c.checkId);
@@ -74,6 +77,7 @@ export function groupFindingsByCheck(comments = [], rowsById = {}) {
g.open += 1;
const sev = SEVERITY_ORDER.includes(c.severity) ? c.severity : 'low';
g.counts[sev] += 1;
+ if (c.stale) g.stale += 1;
}
}
const scopeRank = (s) => {
diff --git a/client/src/lib/editorialChecks.test.js b/client/src/lib/editorialChecks.test.js
index 7bb2e48132..ac7a99f1ce 100644
--- a/client/src/lib/editorialChecks.test.js
+++ b/client/src/lib/editorialChecks.test.js
@@ -63,6 +63,18 @@ describe('groupFindingsByCheck', () => {
it('openFindingsTotal sums open findings across groups', () => {
expect(openFindingsTotal(groupFindingsByCheck(comments, rows))).toBe(3);
});
+
+ it('tallies the per-group stale count from OPEN findings only (#1345)', () => {
+ const staleComments = [
+ { id: '1', checkId: 'a.series', status: 'open', severity: 'high', stale: true },
+ { id: '2', checkId: 'a.series', status: 'open', severity: 'low' }, // fresh
+ { id: '3', checkId: 'a.series', status: 'dismissed', severity: 'high', stale: true }, // dismissed → not counted
+ { id: '4', checkId: 'b.issue', status: 'open', severity: 'medium' }, // no stale field
+ ];
+ const groups = groupFindingsByCheck(staleComments, rows);
+ expect(groups.find((g) => g.checkId === 'a.series').stale).toBe(1);
+ expect(groups.find((g) => g.checkId === 'b.issue').stale).toBe(0);
+ });
});
describe('findingManuscriptLink', () => {
diff --git a/server/routes/pipeline/manuscript.js b/server/routes/pipeline/manuscript.js
index 061e5744ae..bd0718ec80 100644
--- a/server/routes/pipeline/manuscript.js
+++ b/server/routes/pipeline/manuscript.js
@@ -17,6 +17,7 @@ import * as arcPlanner from '../../services/pipeline/arcPlanner.js';
import * as manuscriptReview from '../../services/pipeline/manuscriptReview.js';
import * as manuscriptFix from '../../services/pipeline/manuscriptFix.js';
import * as completenessRunner from '../../services/pipeline/manuscriptCompletenessRunner.js';
+import { getReviewWithStaleness } from '../../services/pipeline/editorial/checkRunner.js';
import { mapServiceError, providerOverrideShape } from './shared.js';
const router = Router();
@@ -153,7 +154,10 @@ router.get('/series/:id/manuscript', asyncHandler(async (req, res) => {
router.get('/series/:id/manuscript/review', asyncHandler(async (req, res) => {
await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
- res.json(await manuscriptReview.getReview(req.params.id));
+ // Annotates each editorial-check finding with a `stale` flag when its analyzed
+ // content has drifted since the check ran (#1345); completeness-only reviews
+ // pass through untouched.
+ res.json(await getReviewWithStaleness(req.params.id));
}));
router.patch('/series/:id/manuscript/review/comments/:commentId', asyncHandler(async (req, res) => {
diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.js
index 0e599cc052..aab16e59a8 100644
--- a/server/services/pipeline/editorial/checkRunner.js
+++ b/server/services/pipeline/editorial/checkRunner.js
@@ -15,16 +15,34 @@
* late-connecting clients via lib/sseUtils.js.
*/
-import { randomUUID } from 'crypto';
+import { randomUUID, createHash } from 'crypto';
import { createSseRunner } from '../../../lib/sseUtils.js';
import { runStagedLLM } from '../../../lib/stageRunner.js';
-import { getEnabledChecks, getEnabledCheckRows } from '../../../lib/editorial/index.js';
+import { getEnabledChecks, getEnabledCheckRows, getCheck } from '../../../lib/editorial/index.js';
import { getSettings } from '../../settings.js';
import { getSeries } from '../series.js';
import { listIssues } from '../issues.js';
import { getSeriesCanon } from '../seriesCanon.js';
import { collectManuscriptSections, sectionsCorpus } from '../arcPlanner.js';
-import { seedReviewFromFindings } from '../manuscriptReview.js';
+import { seedReviewFromFindings, getReview } from '../manuscriptReview.js';
+
+// Source-content fingerprinting for finding staleness (#1345). Each finding is
+// stamped with a hash of the exact content its check analyzed; the manuscript
+// editor / triage view flags a finding `stale` once that content drifts. A
+// manuscript-consuming check (`needsManuscript`) hashes the stitched corpus +
+// canon; a canon-only check hashes canon alone, so a prose edit doesn't falsely
+// stale a canon-only finding (e.g. naming / object-attachment checks). NUL
+// separates the two segments so they can't run together ambiguously.
+const HASH_SEP = '\u0000';
+const sha256 = (text) => createHash('sha256').update(text || '').digest('hex');
+function computeSourceHashes(manuscript, canon) {
+ const canonStr = JSON.stringify(canon ?? {});
+ return {
+ withManuscript: sha256(`${manuscript || ''}${HASH_SEP}${canonStr}`),
+ canonOnly: sha256(canonStr),
+ };
+}
+const hashForCheck = (hashes, needsManuscript) => (needsManuscript ? hashes.withManuscript : hashes.canonOnly);
/**
* Run the enabled editorial checks for a series and seed their findings into the
@@ -60,6 +78,9 @@ export async function runEditorialChecks(seriesId, options = {}) {
listIssues({ seriesId }).catch(() => []),
]);
const manuscript = sectionsCorpus(sections);
+ // Fingerprint the analyzed content once per run — stamped onto every finding
+ // below so the editor can flag it `stale` when the manuscript/canon drifts (#1345).
+ const sourceHashes = computeSourceHashes(manuscript, canon);
const baseCtx = {
seriesId,
series,
@@ -92,7 +113,8 @@ export async function runEditorialChecks(seriesId, options = {}) {
continue;
}
const raw = (await check.run(ctx)) || [];
- const stamped = raw.map((f) => ({ ...f, checkId: check.id }));
+ const sourceContentHash = hashForCheck(sourceHashes, !!check.needsManuscript);
+ const stamped = raw.map((f) => ({ ...f, checkId: check.id, sourceContentHash }));
findings.push(...stamped);
perCheck.push({ checkId: check.id, count: stamped.length });
onProgress?.({ type: 'check:complete', checkId: check.id, count: stamped.length });
@@ -132,6 +154,42 @@ export async function buildEditorialCheckPlan(seriesId, { checkIds = null, setti
return { seriesId, checks, enabledCount: checks.length };
}
+/**
+ * Read the manuscript review and annotate each editorial-check finding with a
+ * `stale` flag (#1345): true when the content the check analyzed has changed
+ * since the finding was seeded. Mirrors `editorialAnalysis.isSnapshotStale` —
+ * recompute the current source hash and compare against the one stamped on the
+ * finding. Findings without a `sourceContentHash` (completeness-pass comments,
+ * older peers, legacy records) or whose check is no longer registered are left
+ * unannotated → the UI treats absent `stale` as not-stale.
+ *
+ * Staleness is derived per-read (never stored), so it stays local to each
+ * install's current content and never rides the synced review document.
+ */
+export async function getReviewWithStaleness(seriesId) {
+ const review = await getReview(seriesId);
+ // Only recompute hashes when there's at least one hash-stamped finding from a
+ // still-registered check — a pure completeness review pays no extra I/O.
+ const evaluable = review.comments.filter((c) => c.checkId && c.sourceContentHash && getCheck(c.checkId));
+ if (!evaluable.length) return review;
+ const needsManuscript = evaluable.some((c) => getCheck(c.checkId).needsManuscript);
+ const series = await getSeries(seriesId);
+ const [sections, canon] = await Promise.all([
+ needsManuscript ? collectManuscriptSections(seriesId) : Promise.resolve([]),
+ getSeriesCanon(series),
+ ]);
+ const sourceHashes = computeSourceHashes(sectionsCorpus(sections), canon);
+ return {
+ ...review,
+ comments: review.comments.map((c) => {
+ const check = c.checkId && c.sourceContentHash ? getCheck(c.checkId) : null;
+ if (!check) return c;
+ const current = hashForCheck(sourceHashes, !!check.needsManuscript);
+ return { ...c, stale: c.sourceContentHash !== current };
+ }),
+ };
+}
+
// ---------------------------------------------------------------------------
// SSE run-tracking — shared lifecycle via createSseRunner (server/lib/sseUtils.js),
// the same factory backing manuscriptCompletenessRunner + editorialAnalysisRunner.
diff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.js
index 9a53343698..5d69710bbf 100644
--- a/server/services/pipeline/editorial/checkRunner.test.js
+++ b/server/services/pipeline/editorial/checkRunner.test.js
@@ -41,12 +41,18 @@ const seedReviewFromFindings = vi.fn(async (_seriesId, findings) => {
}
return { comments: seedStore };
});
-vi.mock('../manuscriptReview.js', () => ({ seedReviewFromFindings: (...a) => seedReviewFromFindings(...a) }));
+// `getReview` is backed by a mutable fixture the staleness tests set per-case.
+let reviewState = { comments: [] };
+vi.mock('../manuscriptReview.js', () => ({
+ seedReviewFromFindings: (...a) => seedReviewFromFindings(...a),
+ getReview: async () => reviewState,
+}));
-const { runEditorialChecks, buildEditorialCheckPlan } = await import('./checkRunner.js');
+const { runEditorialChecks, buildEditorialCheckPlan, getReviewWithStaleness } = await import('./checkRunner.js');
const { runStagedLLM } = await import('../../../lib/stageRunner.js');
const { collectManuscriptSections } = await import('../arcPlanner.js');
-const { listChecks } = await import('../../../lib/editorial/index.js');
+const { getSeriesCanon } = await import('../seriesCanon.js');
+const { listChecks, getCheck } = await import('../../../lib/editorial/index.js');
// Build a `pipelineEditorialChecks.checks` map that disables every check
// matching `predicate` — keeps these fixtures robust as the registry grows
@@ -59,9 +65,11 @@ const disableWhere = (predicate) => ({
beforeEach(() => {
seedStore.length = 0;
+ reviewState = { comments: [] };
seedReviewFromFindings.mockClear();
runStagedLLM.mockClear();
collectManuscriptSections.mockClear();
+ getSeriesCanon.mockClear();
});
describe('runEditorialChecks', () => {
@@ -148,6 +156,80 @@ describe('runEditorialChecks', () => {
});
});
+describe('source-content hash stamping (#1345)', () => {
+ it('stamps every finding with a non-empty sourceContentHash', async () => {
+ const result = await runEditorialChecks('s1');
+ expect(result.findings.length).toBeGreaterThan(0);
+ for (const f of result.findings) {
+ expect(typeof f.sourceContentHash).toBe('string');
+ expect(f.sourceContentHash.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('hashes canon-only checks differently from manuscript-consuming checks', async () => {
+ const result = await runEditorialChecks('s1');
+ const naming = result.findings.find((f) => f.checkId === 'naming.dissimilar-names');
+ const infodump = result.findings.find((f) => f.checkId === 'prose.info-dumping');
+ // Naming is canon-only (no needsManuscript); info-dumping reads the manuscript.
+ expect(getCheck('naming.dissimilar-names').needsManuscript).toBeFalsy();
+ expect(getCheck('prose.info-dumping').needsManuscript).toBe(true);
+ expect(naming.sourceContentHash).not.toBe(infodump.sourceContentHash);
+ });
+});
+
+describe('getReviewWithStaleness (#1345)', () => {
+ // Seed the review fixture from a real run so each comment carries the exact
+ // hash the runner stamped, then re-read under (un)changed content.
+ const seedReviewFromRun = async () => {
+ const { findings } = await runEditorialChecks('s1');
+ reviewState = { comments: findings.map((f) => ({ ...f, status: 'open' })) };
+ return findings;
+ };
+
+ it('flags nothing stale when the content is unchanged', async () => {
+ await seedReviewFromRun();
+ const review = await getReviewWithStaleness('s1');
+ expect(review.comments.length).toBeGreaterThan(0);
+ for (const c of review.comments) expect(c.stale).toBe(false);
+ });
+
+ it('flags manuscript-consuming findings stale when the manuscript changes (canon-only stay fresh)', async () => {
+ await seedReviewFromRun();
+ // Only the manuscript drifts — canon is unchanged.
+ collectManuscriptSections.mockResolvedValueOnce([
+ { number: 1, title: 'Pilot', stageId: 'prose', content: 'A completely rewritten opening paragraph.' },
+ ]);
+ const review = await getReviewWithStaleness('s1');
+ const naming = review.comments.find((c) => c.checkId === 'naming.dissimilar-names');
+ const infodump = review.comments.find((c) => c.checkId === 'prose.info-dumping');
+ expect(infodump.stale).toBe(true);
+ expect(naming.stale).toBe(false);
+ });
+
+ it('flags canon-only findings stale when the canon changes', async () => {
+ await seedReviewFromRun();
+ getSeriesCanon.mockResolvedValueOnce({ characters: [{ name: 'Reardon' }], places: [], objects: [] });
+ const review = await getReviewWithStaleness('s1');
+ const naming = review.comments.find((c) => c.checkId === 'naming.dissimilar-names');
+ expect(naming.stale).toBe(true);
+ });
+
+ it('leaves legacy findings (no hash), completeness comments (no checkId), and unknown checks unannotated', async () => {
+ reviewState = {
+ comments: [
+ { id: 'a', checkId: 'naming.dissimilar-names', anchorQuote: 'x', problem: 'legacy', status: 'open' }, // no hash
+ { id: 'b', checkId: null, anchorQuote: 'y', problem: 'completeness', status: 'open', sourceContentHash: 'abc' },
+ { id: 'c', checkId: 'does.not-exist', anchorQuote: 'z', problem: 'unknown check', status: 'open', sourceContentHash: 'abc' },
+ ],
+ };
+ const review = await getReviewWithStaleness('s1');
+ // No evaluable comment → passthrough, no recompute, no `stale` key added.
+ for (const c of review.comments) expect(c).not.toHaveProperty('stale');
+ expect(collectManuscriptSections).not.toHaveBeenCalled();
+ expect(getSeriesCanon).not.toHaveBeenCalled();
+ });
+});
+
describe('buildEditorialCheckPlan', () => {
it('lists enabled checks for a dry run', async () => {
const plan = await buildEditorialCheckPlan('s1');
diff --git a/server/services/pipeline/manuscriptReview.js b/server/services/pipeline/manuscriptReview.js
index dadfd45c2b..2f40689ac3 100644
--- a/server/services/pipeline/manuscriptReview.js
+++ b/server/services/pipeline/manuscriptReview.js
@@ -114,6 +114,12 @@ function sanitizeComment(raw) {
// — those predate the registry, so they group as a single un-checked set.
// Optional + additive, so the synced review doc stays backward-compatible.
checkId: typeof raw.checkId === 'string' && raw.checkId ? raw.checkId : null,
+ // Fingerprint of the content the editorial check analyzed when it raised this
+ // finding (#1345) — the runner stamps it so the editor can flag the finding
+ // `stale` once the manuscript/canon drifts. `null` for completeness-pass
+ // 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',
fix: sanitizeFix(raw.fix),
sourceRunId: typeof raw.sourceRunId === 'string' ? raw.sourceRunId : null,
@@ -238,26 +244,34 @@ export async function seedReviewFromFindings(seriesId, findings, { runId = null,
// Carry every existing comment forward. In 'fresh' mode, an open comment the
// new pass no longer surfaces is flipped to dismissed (a synced status
// change, not a deletion — see the doc comment). Accepted/dismissed are
- // always left untouched. A with-edits re-run also backfills a fix onto an
- // existing open comment that has none yet (so enabling "generate edits" on a
- // series whose notes came from an earlier findings-only run still drafts them).
+ // always left untouched. For a still-open comment re-surfaced by this run we
+ // also: backfill a fix onto one that has none yet (so enabling "generate
+ // edits" on a series whose notes came from an earlier findings-only run still
+ // drafts them); and refresh its `sourceContentHash` to the current run's, so
+ // re-running a check against edited content clears the stale badge (#1345).
let dismissedCount = 0;
let backfilledCount = 0;
+ let refreshedCount = 0;
const carried = review.comments.map((c) => {
if (mode === 'fresh' && c.status === 'open' && (c.checkId ?? null) === scopeCheckId && !freshKeys.has(findingKey(c))) {
dismissedCount += 1;
return sanitizeComment({ ...c, status: 'dismissed', updatedAt: now });
}
- if (c.status === 'open' && !c.fix) {
- const match = candidateByKey.get(findingKey(c));
+ if (c.status !== 'open') return c;
+ const match = candidateByKey.get(findingKey(c));
+ if (!match) return c;
+ const patch = {};
+ if (!c.fix) {
const section = c.issueNumber != null ? byNumber.get(c.issueNumber) : null;
- const fix = match?.replace ? buildSeedFix({ ...c, replace: match.replace }, section) : null;
- if (fix) {
- backfilledCount += 1;
- return sanitizeComment({ ...c, fix, updatedAt: now });
- }
+ const fix = match.replace ? buildSeedFix({ ...c, replace: match.replace }, section) : null;
+ if (fix) { patch.fix = fix; backfilledCount += 1; }
+ }
+ if (match.sourceContentHash && match.sourceContentHash !== (c.sourceContentHash ?? null)) {
+ patch.sourceContentHash = match.sourceContentHash;
+ refreshedCount += 1;
}
- return c;
+ if (Object.keys(patch).length === 0) return c;
+ return sanitizeComment({ ...c, ...patch, updatedAt: now });
});
// Append only findings not already represented by an existing comment (any
@@ -290,7 +304,7 @@ export async function seedReviewFromFindings(seriesId, findings, { runId = null,
// opens auto-dismissed by a 'fresh' re-run, OR fixes backfilled onto existing
// opens. Skipped on the sync RECEIVE path (`mergeReviewFromSync`) to avoid
// an echo loop.
- if (fresh.length > 0 || dismissedCount > 0 || backfilledCount > 0) emitRecordUpdated('series', seriesId);
+ if (fresh.length > 0 || dismissedCount > 0 || backfilledCount > 0 || refreshedCount > 0) emitRecordUpdated('series', seriesId);
return next;
});
}
diff --git a/server/services/pipeline/manuscriptReview.test.js b/server/services/pipeline/manuscriptReview.test.js
index d51df9134a..00b8e58a80 100644
--- a/server/services/pipeline/manuscriptReview.test.js
+++ b/server/services/pipeline/manuscriptReview.test.js
@@ -25,7 +25,7 @@ vi.mock('./arcPlanner.js', () => ({
import { recordEvents } from '../sharing/recordEvents.js';
import { collectManuscriptSections } from './arcPlanner.js';
-import { seedReviewFromFindings, updateComment, mergeReviewFromSync } from './manuscriptReview.js';
+import { seedReviewFromFindings, updateComment, mergeReviewFromSync, getReview } from './manuscriptReview.js';
describe('manuscriptReview — record-event emission on write', () => {
let updates;
@@ -304,3 +304,47 @@ describe('manuscriptReview — with-edits fix seeding', () => {
expect(second.comments[0].fix.replace).toBe(original); // untouched
});
});
+
+describe('manuscriptReview — sourceContentHash staleness fingerprint (#1345)', () => {
+ beforeEach(() => { fileStore.clear(); });
+
+ it('preserves a stamped sourceContentHash through seed + read (survives sanitize/sync round-trip)', async () => {
+ const seeded = await seedReviewFromFindings('ser-hash', [
+ { problem: 'naming clash', anchorQuote: 'Alina', checkId: 'naming.x', sourceContentHash: 'hash-v1' },
+ ]);
+ expect(seeded.comments[0].sourceContentHash).toBe('hash-v1');
+ // Read back through sanitizeComment (the same shaper the sync importer uses).
+ const review = await getReview('ser-hash');
+ expect(review.comments[0].sourceContentHash).toBe('hash-v1');
+ });
+
+ it('defaults legacy findings with no hash to null', async () => {
+ const seeded = await seedReviewFromFindings('ser-legacy', [
+ { problem: 'no hash here', anchorQuote: 'q', checkId: 'naming.x' },
+ ]);
+ expect(seeded.comments[0].sourceContentHash).toBeNull();
+ });
+
+ it('refreshes the hash on a re-surfaced open finding when content changed (clears stale after re-run)', async () => {
+ await seedReviewFromFindings('ser-refresh', [
+ { problem: 'naming clash', anchorQuote: 'Alina', checkId: 'naming.x', sourceContentHash: 'hash-v1' },
+ ]);
+ // Same finding (same key) re-surfaces from a run against edited content → new hash.
+ const second = await seedReviewFromFindings('ser-refresh', [
+ { problem: 'naming clash', anchorQuote: 'Alina', checkId: 'naming.x', sourceContentHash: 'hash-v2' },
+ ]);
+ expect(second.comments).toHaveLength(1); // deduped, not appended
+ expect(second.comments[0].sourceContentHash).toBe('hash-v2'); // refreshed
+ });
+
+ it('does NOT churn updatedAt when the re-surfaced finding has the same hash', async () => {
+ const first = await seedReviewFromFindings('ser-nochurn', [
+ { problem: 'naming clash', anchorQuote: 'Alina', checkId: 'naming.x', sourceContentHash: 'hash-v1' },
+ ]);
+ const stamp = first.comments[0].updatedAt;
+ const second = await seedReviewFromFindings('ser-nochurn', [
+ { problem: 'naming clash', anchorQuote: 'Alina', checkId: 'naming.x', sourceContentHash: 'hash-v1' },
+ ]);
+ expect(second.comments[0].updatedAt).toBe(stamp); // unchanged — no rewrite
+ });
+});