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 the series-review verdict on manuscript/canon/foundation edits, not just findings (#4111)

[._.]/ Adam Eivyab56694435e3
diff --git a/.changelog/next/fixed-issue-4111.md b/.changelog/next/fixed-issue-4111.md
new file mode 100644
index 0000000000..1e31cb8d9a
--- /dev/null
+++ b/.changelog/next/fixed-issue-4111.md
@@ -0,0 +1 @@
+- Series review now invalidates its stored verdict when the manuscript, canon, or foundation changes — not only when findings are accepted or dismissed
diff --git a/client/src/components/pipeline/SeriesReviewPanel.jsx b/client/src/components/pipeline/SeriesReviewPanel.jsx
index 06e9b7065a..e7c8c1673c 100644
--- a/client/src/components/pipeline/SeriesReviewPanel.jsx
+++ b/client/src/components/pipeline/SeriesReviewPanel.jsx
@@ -23,6 +23,14 @@ import {
import { severityColor } from './constants.js';
const RUN_ENDED = new Set(['complete', 'canceled', 'error']);
+// Why a stored verdict is out of date, keyed by the server's `staleReason`
+// (#4111). `findings` is also the fallback for a pre-#4111 snapshot, whose
+// staleness could only ever come from the findings store.
+const STALE_NOTICE = {
+ findings: 'The findings changed since this review ran — re-review for an up-to-date verdict.',
+ sources: 'The manuscript, canon, or foundation changed since this review ran — re-review for an up-to-date verdict.',
+ both: 'The findings and the reviewed manuscript/canon changed since this review ran — re-review for an up-to-date verdict.',
+};
// The fix run's terminal frames: `rejected` = the cos gate/budget refused it.
const FIX_RUN_ENDED = new Set(['complete', 'canceled', 'error', 'rejected']);
@@ -357,12 +365,13 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpda
)}
</div>
- {/* Stale banner — the findings changed since this verdict (e.g. a
- finding was fixed/dismissed via "Fix here"), so it's out of date. */}
+ {/* Stale banner — either the findings changed since this verdict (e.g. a
+ finding was fixed/dismissed via "Fix here") or the reviewed sources
+ themselves did (manuscript/canon/foundation edits), so it's out of date. */}
{review.stale ? (
<p className="text-[11px] text-port-warning flex items-center gap-1.5">
<AlertTriangle size={12} />
- The findings changed since this review ran — re-review for an up-to-date verdict.
+ {STALE_NOTICE[review.staleReason] || STALE_NOTICE.findings}
</p>
) : null}
diff --git a/server/services/pipeline/canonReadiness.js b/server/services/pipeline/canonReadiness.js
index 3fc2bae05b..fd75c70379 100644
--- a/server/services/pipeline/canonReadiness.js
+++ b/server/services/pipeline/canonReadiness.js
@@ -57,6 +57,27 @@ const KINDS = [
},
];
+/**
+ * PURE: the canon text this check actually grades, as a stable projection for
+ * input hashing (#4111). Reads the SAME `descOf` accessors the grading uses, so
+ * a caller pinning "the canon this verdict was computed from" can never drift
+ * from what readiness reads. Entries are sorted by id/name so an unrelated
+ * re-order (a sync import, a drag-reorder) doesn't look like an edit.
+ */
+export function canonDescriptionInputs(canon) {
+ return Object.fromEntries(KINDS.map(({ kind, listKey, descOf }) => [
+ kind,
+ (Array.isArray(canon?.[listKey]) ? canon[listKey] : [])
+ .map((e) => ({
+ id: e?.id || '',
+ name: e?.name || '',
+ locked: e?.locked === true,
+ description: descOf(e || {}) || '',
+ }))
+ .sort((a, b) => a.id.localeCompare(b.id) || a.name.localeCompare(b.name)),
+ ]));
+}
+
export function gradeCanonDescription(descOf, entry, thinChars = CANON_THIN_CHARS) {
const desc = (descOf(entry) || '').trim();
if (!desc) return 'none';
diff --git a/server/services/pipeline/canonReadiness.test.js b/server/services/pipeline/canonReadiness.test.js
index d7f08cba79..3c6910b282 100644
--- a/server/services/pipeline/canonReadiness.test.js
+++ b/server/services/pipeline/canonReadiness.test.js
@@ -161,3 +161,34 @@ describe('checkSeriesCanonReadiness (roll-up)', () => {
expect(report.blockingIssues).toHaveLength(1);
});
});
+
+describe('canonDescriptionInputs (fingerprint projection, #4111)', () => {
+ const { canonDescriptionInputs } = readiness;
+
+ it('projects the same description text the grading reads, per kind', () => {
+ const out = canonDescriptionInputs({
+ characters: [{ id: 'c1', name: 'Aria', description: 'a tall figure' }],
+ places: [{ id: 'p1', name: 'The Bay', description: 'grey water', palette: 'slate' }],
+ objects: [{ id: 'o1', name: 'The Key', significance: 'opens the vault' }],
+ });
+ expect(out.character[0]).toMatchObject({ id: 'c1', name: 'Aria', description: 'a tall figure', locked: false });
+ expect(out.place[0].description).toBe('grey water. slate');
+ expect(out.object[0].description).toBe('opens the vault');
+ });
+
+ it('changes when a description is edited', () => {
+ const before = canonDescriptionInputs({ characters: [{ id: 'c1', name: 'Aria', description: 'a tall figure' }] });
+ const after = canonDescriptionInputs({ characters: [{ id: 'c1', name: 'Aria', description: 'a short figure' }] });
+ expect(after).not.toEqual(before);
+ });
+
+ it('is stable across a canon re-order (a re-order is not an edit)', () => {
+ const a = { id: 'c1', name: 'Aria', description: 'x' };
+ const b = { id: 'c2', name: 'Bex', description: 'y' };
+ expect(canonDescriptionInputs({ characters: [a, b] })).toEqual(canonDescriptionInputs({ characters: [b, a] }));
+ });
+
+ it('tolerates a missing/empty canon', () => {
+ expect(canonDescriptionInputs(null)).toEqual({ character: [], place: [], object: [] });
+ });
+});
diff --git a/server/services/pipeline/seriesReview.js b/server/services/pipeline/seriesReview.js
index 3b17b73da1..a839d90cd7 100644
--- a/server/services/pipeline/seriesReview.js
+++ b/server/services/pipeline/seriesReview.js
@@ -40,7 +40,8 @@
import { join } from 'path';
import { unlink } from 'fs/promises';
-import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';
+import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse, sha256Text } from '../../lib/fileUtils.js';
+import { canonicalStringify } from '../../lib/objects.js';
import { createSseRunner } from '../../lib/sseUtils.js';
import { runStageScopedInlineLLM } from '../../lib/stageRunner.js';
import { getDomainMode } from '../../lib/domainAutonomy.js';
@@ -48,12 +49,14 @@ import { readReadinessGate, mergeSeverityWeights } from '../../lib/editorial/ind
import { loadState } from '../cosState.js';
import { getSettings } from '../settings.js';
import { getDomainBudgetStatus, recordDomainUsage } from '../domainUsage.js';
-import { getSeries } from './series.js';
+import { getUniverse } from '../universeBuilder.js';
+import { getSeries, MANUSCRIPT_TYPES } from './series.js';
import { listIssues } from './issues.js';
-import { judgeFoundation, DEFAULT_FOUNDATION_THRESHOLD } from './foundationJudge.js';
+import { judgeFoundation, foundationInputs, DEFAULT_FOUNDATION_THRESHOLD } from './foundationJudge.js';
import { runEditorialChecks } from './editorial/checkRunner.js';
import { getSeriesHealth, isOpenFinding, DEFAULT_READINESS_GATE } from './editorialScore.js';
-import { checkSeriesCanonReadiness } from './canonReadiness.js';
+import { checkSeriesCanonReadiness, canonDescriptionInputs } from './canonReadiness.js';
+import { pickCanon } from './seriesCanon.js';
import { getReview, seedReviewFromFindings } from './manuscriptReview.js';
import { generateManuscriptFix, acceptManuscriptFix } from './manuscriptFix.js';
@@ -127,6 +130,122 @@ export function collectReviewFindings(comments) {
});
}
+// ---------------------------------------------------------------------------
+// Reviewed-source fingerprinting (#4111).
+//
+// The findingIds divergence below only notices findings being accepted/dismissed
+// or appearing. It cannot see the manuscript being rewritten, canon being
+// edited, or the foundation changing through some other path — so the stored
+// verdict's foundation/canon/health dimensions could report old scores as
+// current. Mirroring `foundationJudge`'s `sourceInputsHash` / `isFoundationStale`,
+// a run pins a hash of everything it reviewed and the GET recomputes it.
+// ---------------------------------------------------------------------------
+
+// Separator for concatenated fields inside one fingerprint — a byte that can't
+// occur in authored text, so two fields can't blur into each other. Mirrors
+// checkRunner's per-finding fingerprinting.
+const HASH_SEP = '\u0000';
+
+/**
+ * The manuscript text the editorial checks + canon readiness read, as a stable
+ * projection: EVERY drafted manuscript stage per issue (not just the highest-
+ * precedence one), each stage's input AND output hashed, so any authored edit
+ * flips the fingerprint. Sorted by issue id so a listing re-order isn't an edit.
+ * Pure.
+ */
+export function manuscriptInputs(issues) {
+ return [...(Array.isArray(issues) ? issues : [])]
+ .map((iss) => ({
+ id: iss?.id || '',
+ stages: Object.fromEntries(MANUSCRIPT_TYPES.map((sid) => {
+ const stage = iss?.stages?.[sid];
+ // NUL-joined so text moving across the input/output boundary can't hash identically.
+ return [sid, sha256Text([stage?.input || '', stage?.output || ''].join(HASH_SEP))];
+ })),
+ }))
+ .sort((a, b) => a.id.localeCompare(b.id));
+}
+
+/**
+ * Everything this review reads, as a stable projection. Pure.
+ *
+ * - `foundation` reuses `foundationInputs` verbatim, so the review's staleness
+ * and the foundation judge's can never disagree about what the foundation is.
+ * - `manuscript` is the drafted text the editorial checks and canon readiness
+ * grade — absent from the foundation projection (which only carries the `idea`
+ * synopsis), and the single biggest silent-drift source.
+ * - `canon` is the descriptive text canon readiness grades. It overlaps the
+ * foundation projection but is NOT covered by it: a character's plain
+ * `description` (the fallback canon readiness grades on) is not a foundation
+ * field, so a description-only edit would otherwise go unnoticed.
+ * - `scoring` carries inputs that change how a dimension SCORES rather than what
+ * it reads (the canon source text depends on `targetFormat`; health weights
+ * the open findings by `severityWeights`).
+ */
+export function seriesReviewInputs({ series, universe, issues } = {}) {
+ const list = Array.isArray(issues) ? issues : [];
+ return {
+ foundation: foundationInputs(series, universe, list),
+ manuscript: manuscriptInputs(list),
+ canon: canonDescriptionInputs(pickCanon(universe)),
+ scoring: {
+ targetFormat: series?.targetFormat || '',
+ severityWeights: series?.severityWeights ?? null,
+ },
+ };
+}
+
+// Key-sorted so the hash is stable across machines (a synced/imported record can
+// re-order keys without being an edit). Mirrors checkRunner's fingerprinting.
+export const seriesReviewInputsHash = (parts) => sha256Text(canonicalStringify(seriesReviewInputs(parts)));
+
+/**
+ * Whether a stored verdict's reviewed sources have drifted. A snapshot written
+ * before this feature carries no hash — it can't be judged, so it is NOT flagged
+ * (the findings divergence still applies). A snapshot that HAS a hash we could
+ * not recompute (`currentHash` null — the series/universe/issues were unreadable)
+ * IS flagged: the verdict is unverifiable, and failing closed matches how the
+ * review's own verdict treats a dimension it couldn't evaluate. Pure.
+ */
+export function isSeriesReviewSourceStale(snapshot, currentHash) {
+ if (!snapshot?.sourceInputsHash) return false;
+ if (!currentHash) return true;
+ return snapshot.sourceInputsHash !== currentHash;
+}
+
+/**
+ * Whether the live open-finding set has diverged from the one a stored verdict
+ * was computed from — findings accepted/dismissed (e.g. via a "Fix here" link)
+ * or new findings appearing. Falls back to the snapshot's embedded findings for
+ * a snapshot written before `findingIds` existed. Pure.
+ */
+export function isSeriesReviewFindingsStale(snapshot, liveFindingIds) {
+ const live = liveFindingIds instanceof Set ? liveFindingIds : new Set(liveFindingIds || []);
+ const snapshotIds = Array.isArray(snapshot?.findingIds)
+ ? snapshot.findingIds
+ : (snapshot?.findings || []).map((f) => f?.commentId).filter(Boolean);
+ return snapshotIds.length !== live.size || snapshotIds.some((id) => !live.has(id));
+}
+
+/**
+ * Resolve the CURRENT reviewed-source hash for a series. Returns null when the
+ * inputs can't be fully read — never a hash computed from a partial read, which
+ * would silently report a changed foundation as unchanged. Pass the records the
+ * caller already holds to skip the re-read.
+ */
+async function resolveSourceInputsHash(seriesId, { series, issues } = {}) {
+ const ser = series || await getSeries(seriesId).catch(() => null);
+ if (!ser) return null;
+ const list = issues || await listIssues({ seriesId }).catch(() => null);
+ if (!list) return null;
+ // `undefined` = a linked universe we failed to read (distinct from `null` = no
+ // linked universe at all). Hashing the failed read as "unlinked" would produce
+ // a fresh-looking hash for a world we never saw.
+ const universe = ser.universeId ? await getUniverse(ser.universeId).catch(() => undefined) : null;
+ if (universe === undefined) return null;
+ return seriesReviewInputsHash({ series: ser, universe, issues: list });
+}
+
/**
* Build the inline prompt that routes a free-text user observation to the best
* issue + anchor. Given the issue roster (number + title) and the feedback, the
@@ -240,11 +359,15 @@ export async function runSeriesReview(seriesId, {
// on a run whose verdict would be discarded anyway.
if (signal?.aborted) return null;
// Three independent reads — resolve concurrently.
- const [series, settings, issues] = await Promise.all([
+ // `issuesRead` keeps `null` = the read FAILED distinct from `[]` = the series
+ // genuinely has no issues: the composition below is happy with an empty list,
+ // but the source fingerprint must not pin a hash computed from a failed read.
+ const [series, settings, issuesRead] = await Promise.all([
getSeries(seriesId),
getSettings().catch(() => null),
- listIssues({ seriesId }).catch(() => []),
+ listIssues({ seriesId }).catch(() => null),
]);
+ const issues = issuesRead || [];
const gate = readinessGate || readReadinessGate(settings) || DEFAULT_READINESS_GATE;
const weights = mergeSeverityWeights(series?.severityWeights);
@@ -360,6 +483,9 @@ export async function runSeriesReview(seriesId, {
// individual check errored — the verdict then fails closed (never 'ready').
const incomplete = failedStages.length > 0 || checksErrored > 0;
const verdict = computeReviewVerdict({ health, foundation, canon, threshold, incomplete });
+ // Pin what this verdict was computed FROM. The review performs no manuscript
+ // writes, so the records read at entry are still the ones it reviewed.
+ const sourceInputsHash = await resolveSourceInputsHash(seriesId, { series, issues: issuesRead });
const result = {
seriesId,
@@ -390,6 +516,11 @@ export async function runSeriesReview(seriesId, {
// GET can detect that the review is stale (findings were accepted/dismissed,
// e.g. via a "Fix here" link) without re-running.
findingIds: findings.map((f) => f.commentId),
+ // A fingerprint of everything this verdict was computed FROM (manuscript,
+ // canon, foundation inputs), so a later GET can detect that the reviewed
+ // sources changed — not just the findings store (#4111). Null when the
+ // inputs couldn't be fully read; a null hash is never flagged stale.
+ sourceInputsHash,
hadFeedback: !!(feedback && String(feedback).trim()),
};
// Don't persist (or return) a verdict for a run the user canceled mid-flight —
@@ -422,12 +553,17 @@ async function clearSnapshot(seriesId) {
* reports whether the FIX path is currently available (cos-domain autonomy):
* with the domain `off`, review still works read-only but fixing is disabled.
*
- * Stamps a `stale` flag when the live open-finding set no longer matches the
- * snapshot's `findingIds` — i.e. findings were accepted/dismissed since (e.g. via
- * a "Fix here" link) or new findings appeared — so a reload can warn the verdict
- * is out of date instead of presenting it as current. (This covers the
- * findings-store drift this feature introduces; foundation/canon/manuscript edits
- * through other paths are a broader pre-existing concern tracked in #4111.)
+ * Stamps a `stale` flag when the stored verdict no longer describes the series,
+ * from two independent signals, plus a `staleReason` naming which fired:
+ *
+ * - `findings` — the live open-finding set no longer matches the snapshot's
+ * `findingIds` (findings accepted/dismissed via a "Fix here" link, or new
+ * ones appeared).
+ * - `sources` — the reviewed sources themselves drifted: the manuscript was
+ * edited, canon changed, or a foundation input moved (#4111). Without this,
+ * the verdict's foundation/canon/health dimensions could keep reporting old
+ * scores as current after a direct manuscript edit.
+ * - `both` — both fired.
*/
export async function getSeriesReview(seriesId) {
assertValidSeriesId(seriesId);
@@ -435,15 +571,21 @@ export async function getSeriesReview(seriesId) {
const verdict = content === null
? null
: safeJSONParse(content, null, { allowArray: false, logError: true, context: snapshotPath(seriesId) });
- const [fix, review] = await Promise.all([
+ const [fix, review, currentHash] = await Promise.all([
getFixAvailability(),
verdict ? getReview(seriesId).catch(() => ({ comments: [] })) : Promise.resolve(null),
+ // Only worth the reads when there IS a snapshot to judge, and only when that
+ // snapshot carries a hash (a pre-#4111 snapshot can't be judged this way).
+ verdict?.sourceInputsHash ? resolveSourceInputsHash(seriesId) : Promise.resolve(null),
]);
- if (verdict && review) {
- const liveOpen = new Set(collectReviewFindings(review.comments).map((f) => f.commentId));
- const snapshotIds = Array.isArray(verdict.findingIds) ? verdict.findingIds : (verdict.findings || []).map((f) => f?.commentId).filter(Boolean);
- const stale = snapshotIds.length !== liveOpen.size || snapshotIds.some((id) => !liveOpen.has(id));
- verdict.stale = stale;
+ if (verdict) {
+ const liveOpen = new Set(collectReviewFindings(review?.comments).map((f) => f.commentId));
+ const reasons = [
+ review && isSeriesReviewFindingsStale(verdict, liveOpen) && 'findings',
+ isSeriesReviewSourceStale(verdict, currentHash) && 'sources',
+ ].filter(Boolean);
+ verdict.stale = reasons.length > 0;
+ verdict.staleReason = reasons.length > 1 ? 'both' : (reasons[0] || null);
}
return { review: verdict, fix };
}
diff --git a/server/services/pipeline/seriesReview.run.test.js b/server/services/pipeline/seriesReview.run.test.js
index 16776d423f..b72e797d58 100644
--- a/server/services/pipeline/seriesReview.run.test.js
+++ b/server/services/pipeline/seriesReview.run.test.js
@@ -13,7 +13,7 @@
* rejection.
*/
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
-import { mkdtempSync, rmSync } from 'fs';
+import { mkdtempSync, rmSync, readFileSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -52,7 +52,9 @@ const { checkSeriesCanonReadiness } = await import('./canonReadiness.js');
const { runEditorialChecks } = await import('./editorial/checkRunner.js');
const { getSeriesHealth } = await import('./editorialScore.js');
const { getReview, seedReviewFromFindings } = await import('./manuscriptReview.js');
-const { runSeriesReview } = await import('./seriesReview.js');
+const { getSeries } = await import('./series.js');
+const { listIssues } = await import('./issues.js');
+const { runSeriesReview, getSeriesReview } = await import('./seriesReview.js');
afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
@@ -230,3 +232,78 @@ describe('runSeriesReview — failure and cancellation paths', () => {
expect(unhandled).toEqual([]);
});
});
+
+/**
+ * The reviewed-source fingerprint (#4111) end to end: a run pins what it
+ * reviewed, and the GET recomputes it so a manuscript/canon/foundation edit made
+ * through ANY other path invalidates the stored verdict — not just accepting or
+ * dismissing a finding.
+ */
+describe('getSeriesReview — reviewed-source staleness (#4111)', () => {
+ const issueWith = (prose) => ({ id: 'iss-1', seriesId: 'ser-test', number: 1, seasonId: null, title: 'One', stages: { prose: { output: prose } } });
+ const SERIES = { id: 'ser-test', severityWeights: null };
+ const openFinding = { id: 'c1', status: 'open', severity: 'high', issueNumber: 1, problem: 'the middle sags' };
+
+ beforeEach(() => {
+ getSeries.mockResolvedValue({ ...SERIES });
+ listIssues.mockResolvedValue([issueWith('the original draft')]);
+ });
+
+ // The default mocks the rest of the suite relies on.
+ afterAll(() => {
+ getSeries.mockResolvedValue({ ...SERIES });
+ listIssues.mockResolvedValue([]);
+ });
+
+ it('stamps the fingerprint on the run and reports the unchanged verdict as fresh', async () => {
+ const result = await run();
+ expect(typeof result.sourceInputsHash).toBe('string');
+ const { review } = await getSeriesReview('ser-test');
+ expect(review.sourceInputsHash).toBe(result.sourceInputsHash);
+ expect(review.stale).toBe(false);
+ expect(review.staleReason).toBeNull();
+ });
+
+ it("flips stale with reason 'sources' when the manuscript was edited after the review", async () => {
+ await run();
+ listIssues.mockResolvedValue([issueWith('a completely rewritten draft')]);
+ const { review } = await getSeriesReview('ser-test');
+ expect(review.stale).toBe(true);
+ expect(review.staleReason).toBe('sources');
+ });
+
+ it("keeps the findings-divergence signal working alongside it ('findings')", async () => {
+ await run();
+ getReview.mockResolvedValue({ comments: [openFinding] });
+ const { review } = await getSeriesReview('ser-test');
+ expect(review.stale).toBe(true);
+ expect(review.staleReason).toBe('findings');
+ });
+
+ it("reports 'both' when the findings AND the sources moved", async () => {
+ await run();
+ getReview.mockResolvedValue({ comments: [openFinding] });
+ listIssues.mockResolvedValue([issueWith('a completely rewritten draft')]);
+ const { review } = await getSeriesReview('ser-test');
+ expect(review.stale).toBe(true);
+ expect(review.staleReason).toBe('both');
+ });
+
+ it('never source-flags a pre-#4111 snapshot that carries no pinned hash', async () => {
+ await run();
+ const snapshotFile = join(TEST_DATA_ROOT, 'pipeline-series-review', 'ser-test.json');
+ const stored = JSON.parse(readFileSync(snapshotFile, 'utf8'));
+ delete stored.sourceInputsHash;
+ writeFileSync(snapshotFile, JSON.stringify(stored));
+ listIssues.mockResolvedValue([issueWith('a completely rewritten draft')]);
+ const { review } = await getSeriesReview('ser-test');
+ expect(review.stale).toBe(false);
+ expect(review.staleReason).toBeNull();
+ });
+
+ it('does not pin a fingerprint computed from a failed issues read', async () => {
+ listIssues.mockRejectedValue(new Error('store unavailable'));
+ const result = await run();
+ expect(result.sourceInputsHash).toBeNull();
+ });
+});
diff --git a/server/services/pipeline/seriesReview.test.js b/server/services/pipeline/seriesReview.test.js
index d34578ba63..3d413268a9 100644
--- a/server/services/pipeline/seriesReview.test.js
+++ b/server/services/pipeline/seriesReview.test.js
@@ -4,6 +4,10 @@ import {
collectReviewFindings,
shapeFeedbackFinding,
buildFeedbackRoutePrompt,
+ manuscriptInputs,
+ seriesReviewInputsHash,
+ isSeriesReviewSourceStale,
+ isSeriesReviewFindingsStale,
} from './seriesReview.js';
describe('computeReviewVerdict', () => {
@@ -159,3 +163,130 @@ describe('buildFeedbackRoutePrompt', () => {
expect(prompt).toContain('(no issues yet)');
});
});
+
+describe('manuscriptInputs', () => {
+ const issue = (over = {}) => ({ id: 'iss-1', number: 1, stages: { prose: { output: 'the draft' } }, ...over });
+
+ it('flips the projection when a drafted stage OUTPUT changes', () => {
+ const before = manuscriptInputs([issue()]);
+ const after = manuscriptInputs([issue({ stages: { prose: { output: 'a rewritten draft' } } })]);
+ expect(after).not.toEqual(before);
+ });
+
+ it('flips the projection when a stage INPUT (the seed) changes, not only the output', () => {
+ const before = manuscriptInputs([issue({ stages: { prose: { input: 'beats', output: 'the draft' } } })]);
+ const after = manuscriptInputs([issue({ stages: { prose: { input: 'new beats', output: 'the draft' } } })]);
+ expect(after).not.toEqual(before);
+ });
+
+ it('covers every manuscript stage, not just the highest-precedence one', () => {
+ const base = { id: 'iss-1', stages: { comicScript: { output: 'PAGE 1' }, prose: { output: 'the draft' } } };
+ const edited = { id: 'iss-1', stages: { comicScript: { output: 'PAGE 1' }, prose: { output: 'edited prose' } } };
+ // `comicScript` outranks `prose` in the stitched corpus, so a prose-only edit
+ // is exactly the drift a precedence-picking projection would miss.
+ expect(manuscriptInputs([edited])).not.toEqual(manuscriptInputs([base]));
+ });
+
+ it('is stable across a listing re-order (a re-order is not an edit)', () => {
+ const a = issue();
+ const b = issue({ id: 'iss-2', number: 2 });
+ expect(manuscriptInputs([a, b])).toEqual(manuscriptInputs([b, a]));
+ });
+
+ it('tolerates a non-array input and issues with no stages', () => {
+ expect(manuscriptInputs(null)).toEqual([]);
+ expect(manuscriptInputs([{}])).toHaveLength(1);
+ });
+});
+
+describe('seriesReviewInputsHash', () => {
+ const series = { id: 'ser-1', targetFormat: 'comic+tv', severityWeights: null };
+ const universe = {
+ id: 'uni-1',
+ logline: 'A quiet town keeps a loud secret.',
+ characters: [{ id: 'ch-1', name: 'Ada', description: 'a tall figure in a long coat' }],
+ places: [],
+ objects: [],
+ };
+ const issues = [{ id: 'iss-1', number: 1, stages: { prose: { output: 'the draft' } } }];
+ const base = () => seriesReviewInputsHash({ series, universe, issues });
+
+ it('is deterministic for unchanged inputs', () => {
+ expect(base()).toBe(seriesReviewInputsHash({ series, universe, issues }));
+ });
+
+ it('changes when the manuscript is edited', () => {
+ const edited = [{ id: 'iss-1', number: 1, stages: { prose: { output: 'a rewritten draft' } } }];
+ expect(seriesReviewInputsHash({ series, universe, issues: edited })).not.toBe(base());
+ });
+
+ it('changes when a canon DESCRIPTION is edited (a field the foundation projection does not carry)', () => {
+ const edited = { ...universe, characters: [{ id: 'ch-1', name: 'Ada', description: 'a short figure in a raincoat' }] };
+ expect(seriesReviewInputsHash({ series, universe: edited, issues })).not.toBe(base());
+ });
+
+ it('changes when a foundation input (the world logline) is edited', () => {
+ const edited = { ...universe, logline: 'A loud town keeps a quiet secret.' };
+ expect(seriesReviewInputsHash({ series, universe: edited, issues })).not.toBe(base());
+ });
+
+ it('changes when the health severity weights change (same sources, different scoring)', () => {
+ const edited = { ...series, severityWeights: { high: 20, medium: 5, low: 1 } };
+ expect(seriesReviewInputsHash({ series: edited, universe, issues })).not.toBe(base());
+ });
+
+ it('changes when the target format changes (it selects the canon source text)', () => {
+ expect(seriesReviewInputsHash({ series: { ...series, targetFormat: 'tv' }, universe, issues })).not.toBe(base());
+ });
+
+ it('is unchanged by key ordering (a synced/imported record may re-order keys)', () => {
+ const reordered = { objects: [], places: [], characters: universe.characters, logline: universe.logline, id: 'uni-1' };
+ expect(seriesReviewInputsHash({ series, universe: reordered, issues })).toBe(base());
+ });
+
+ it('tolerates a series with no linked universe', () => {
+ expect(typeof seriesReviewInputsHash({ series, universe: null, issues })).toBe('string');
+ });
+});
+
+describe('isSeriesReviewSourceStale', () => {
+ it('flags a snapshot whose pinned hash no longer matches the current sources', () => {
+ expect(isSeriesReviewSourceStale({ sourceInputsHash: 'aaa' }, 'bbb')).toBe(true);
+ });
+
+ it('does not flag a snapshot whose sources are unchanged', () => {
+ expect(isSeriesReviewSourceStale({ sourceInputsHash: 'aaa' }, 'aaa')).toBe(false);
+ });
+
+ it('never flags a pre-#4111 snapshot that carries no hash (it cannot be judged)', () => {
+ expect(isSeriesReviewSourceStale({ verdict: 'ready' }, 'aaa')).toBe(false);
+ expect(isSeriesReviewSourceStale(null, 'aaa')).toBe(false);
+ });
+
+ it('flags a hashed snapshot whose current hash could not be recomputed (fails closed)', () => {
+ expect(isSeriesReviewSourceStale({ sourceInputsHash: 'aaa' }, null)).toBe(true);
+ });
+});
+
+describe('isSeriesReviewFindingsStale', () => {
+ it('is false when the live open set matches the pinned ids', () => {
+ expect(isSeriesReviewFindingsStale({ findingIds: ['a', 'b'] }, new Set(['a', 'b']))).toBe(false);
+ });
+
+ it('is true when a pinned finding was accepted/dismissed', () => {
+ expect(isSeriesReviewFindingsStale({ findingIds: ['a', 'b'] }, new Set(['a']))).toBe(true);
+ });
+
+ it('is true when a new finding appeared', () => {
+ expect(isSeriesReviewFindingsStale({ findingIds: ['a'] }, new Set(['a', 'b']))).toBe(true);
+ });
+
+ it('falls back to the embedded findings for a snapshot with no findingIds', () => {
+ expect(isSeriesReviewFindingsStale({ findings: [{ commentId: 'a' }] }, new Set(['a']))).toBe(false);
+ expect(isSeriesReviewFindingsStale({ findings: [{ commentId: 'a' }] }, new Set())).toBe(true);
+ });
+
+ it('accepts an array of live ids (not only a Set)', () => {
+ expect(isSeriesReviewFindingsStale({ findingIds: ['a'] }, ['a'])).toBe(false);
+ });
+});