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([issue-1296]): add scene.component-balance editorial check + reverseOutline source
[._.]/ Adam Eivy158621c60caf
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex efefbacdad..c08ebe9276 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -56,11 +56,13 @@ it. To add a new built-in check, append an entry to `EDITORIAL_CHECKS` inDeclare every input the check's `run(ctx)` reads in its `sources` array (anon-empty subset of `EDITORIAL_SOURCES`: `manuscript`, `canon`,-`series.styleGuide`, `series.arc.tickingClock`). The staleness runner-fingerprints exactly those sources, so a finding goes stale only when content the-check actually analyzed drifts — declare too few and a finding stays falsely-fresh; a `manuscript` source must pair with `needsManuscript: true`. When a new-check reads a `ctx.series` field that isn't yet a token, add the token to+`series.styleGuide`, `series.arc.tickingClock`, `reverseOutline`). The staleness+runner fingerprints exactly those sources, so a finding goes stale only when+content the check actually analyzed drifts — declare too few and a finding stays+falsely fresh; a `manuscript` source must pair with `needsManuscript: true`, and+`reverseOutline` makes the runner fetch the cached reverse-outline (#1286) and+inject `ctx.reverseOutline` (the scenes array). When a new check reads a+`ctx.series` field (or another artifact) that isn't yet a token, add the token to`EDITORIAL_SOURCES` and a matching resolver in the runner's `SOURCE_RESOLVERS`.## User-defined checks (#1346)diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex 66948e5669..77c6fe57cd 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -44,11 +44,16 @@ const SEVERITIES = CHECK_SEVERITIES;// - 'canon' — the universe/series canon (characters, relationships, objects)// - 'series.styleGuide' — the series style guide (tense/POV/rating/reading level)// - 'series.arc.tickingClock' — the series arc's ticking clock+// - 'reverseOutline' — the cached reverse-outline scene segmentation (#1286);+// scenes carry components/povCharacter/charactersPresent.+// The runner fetches it (gated on this source) and injects+// `ctx.reverseOutline` (the scenes array).export const EDITORIAL_SOURCES = Object.freeze(['manuscript','canon','series.styleGuide','series.arc.tickingClock',+ 'reverseOutline',]);// Default per-run finding cap for user-defined checks (#1346) — mirrors the@@ -724,6 +729,34 @@ function buildRosterAppearances(ctx) {return rows;}+// ---------------------------------------------------------------------------+// Scene component balance (#1296) — reads the cached reverse-outline (#1286)+// scene segmentation, where each scene carries a `components` boolean signal+// { narrative, action, dialogue }. The editorial rule: a scene should mix at+// least 2 of the 3; a single-mode scene (a narration wall, talking heads with+// no action, pure action with no interiority or voice) reads flat and is flagged.+//+// A scene with NO component flagged (all three false) is treated as+// "unclassified" (an older outline, or a scene the segmenter didn't tag), not+// "zero components" — it is skipped rather than flagged as a false positive,+// per the absent-vs-empty rule.+// ---------------------------------------------------------------------------++const SCENE_COMPONENT_KEYS = ['narrative', 'action', 'dialogue'];++// The present/missing component lists for a scene's `components` signal.+function sceneComponentMix(components) {+ const c = components && typeof components === 'object' ? components : {};+ const present = SCENE_COMPONENT_KEYS.filter((k) => c[k] === true);+ const missing = SCENE_COMPONENT_KEYS.filter((k) => c[k] !== true);+ return { present, missing };+}++// A scene's display label for finding text/location — its heading, falling back+// to the summary, then a sequence-based label.+const sceneLabel = (s) =>+ (s.heading || s.summary || `scene ${typeof s.sequence === 'number' ? s.sequence + 1 : '?'}`).trim();+// ---------------------------------------------------------------------------// Registry entries.// ---------------------------------------------------------------------------@@ -1037,6 +1070,65 @@ export const EDITORIAL_CHECKS = [return findings;},},+ {+ id: 'scene.component-balance',+ sources: ['reverseOutline'],+ label: 'Scene component balance (narrative / action / dialogue)',+ description:+ 'Flags scenes that lean on a single mode — a wall of narration, talking heads with no action, or pure action with no interiority or voice. Reads the reverse-outline scene segmentation; a balanced scene mixes at least two of narrative, action, and dialogue.',+ scope: 'scene',+ kind: 'deterministic',+ category: 'pacing',+ severityDefault: 'low',+ defaultEnabled: true,+ configSchema: z.object({+ // Minimum distinct components (narrative/action/dialogue) a scene should+ // carry. Default 2 (the "at least 2 of 3" rule); 3 demands all three; 1+ // disables the check (every scene with any signal trivially passes).+ minComponents: z.number().int().min(1).max(3).default(2),+ }),+ configFields: [+ {+ key: 'minComponents',+ label: 'Minimum scene components',+ type: 'number',+ min: 1,+ max: 3,+ step: 1,+ help: 'How many of narrative / action / dialogue a scene should mix. 2 flags single-mode scenes (a narration wall, talking heads, pure action); 3 demands all three; 1 disables the check.',+ },+ ],+ // Needs a generated reverse outline with at least one scene to read.+ gate: (ctx) => Array.isArray(ctx.reverseOutline) && ctx.reverseOutline.length > 0,+ run: (ctx) => {+ const minComponents = ctx.config?.minComponents ?? 2;+ if (minComponents <= 1) return []; // disabled — every classified scene passes+ const scenes = Array.isArray(ctx.reverseOutline) ? ctx.reverseOutline : [];+ const findings = [];+ for (const s of scenes) {+ if (!s || typeof s !== 'object') continue;+ const { present, missing } = sceneComponentMix(s.components);+ // Skip unclassified scenes (no component signal at all) — absent ≠ "zero+ // components"; flagging them would be a false positive on older outlines.+ if (present.length === 0 || present.length >= minComponents) continue;+ const label = sceneLabel(s);+ const issueNumber = Number.isInteger(s.issueNumber) ? s.issueNumber : null;+ const problem = present.length === 1+ ? `Scene "${label}" is all ${present[0]} — no ${missing.join(' or ')}. A single-mode scene reads flat; balance at least two of narrative, action, and dialogue.`+ : `Scene "${label}" has ${present.join(' and ')} but no ${missing.join(' or ')} — only ${present.length} of the ${minComponents} components you expect.`;+ findings.push({+ severity: ctx.severityDefault,+ category: 'pacing',+ location: issueNumber != null ? `Issue ${issueNumber}: ${label}` : `Scene: ${label}`,+ problem,+ suggestion: `Add ${missing.join(' or ')} so the scene isn't a ${present.join('/')}-only beat (e.g. ground talking heads in the room, give a narration wall a beat of action, or let an action scene breathe with a line of dialogue or interiority).`,+ anchorQuote: typeof s.anchorQuote === 'string' ? s.anchorQuote : '',+ issueNumber,+ });+ }+ return findings;+ },+ },{id: 'relationships.reciprocity',sources: ['canon'],diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex c041837cb7..ae938c957a 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -553,6 +553,78 @@ describe('roster.economy — deterministic check', () => {});});+describe('scene.component-balance — deterministic check', () => {+ const SCENE = 'scene.component-balance';+ const scene = (over = {}) => ({+ heading: 'A scene', issueNumber: 1, anchorQuote: 'q',+ components: { narrative: false, action: false, dialogue: false }, ...over,+ });+ const runScene = (scenes, config = {}) =>+ getCheck(SCENE).run({ reverseOutline: scenes, config, severityDefault: 'low' });++ it('declares the reverseOutline source and scene scope', () => {+ const c = getCheck(SCENE);+ expect(c.scope).toBe('scene');+ expect(c.kind).toBe('deterministic');+ expect(c.sources).toEqual(['reverseOutline']);+ });++ it('flags a single-mode scene and names the missing components', () => {+ const findings = runScene([+ scene({ heading: 'Talking heads', components: { narrative: false, action: false, dialogue: true } }),+ ]);+ expect(findings).toHaveLength(1);+ const f = findings[0];+ expect(f.category).toBe('pacing');+ expect(f.problem).toMatch(/all dialogue/);+ expect(f.problem).toMatch(/no narrative or action/);+ expect(f.anchorQuote).toBe('q');+ expect(f.issueNumber).toBe(1);+ expect(f.location).toBe('Issue 1: Talking heads');+ });++ it('passes a scene that mixes two components', () => {+ expect(runScene([scene({ components: { narrative: true, action: false, dialogue: true } })])).toEqual([]);+ });++ it('skips unclassified scenes (no component signal) rather than false-flagging', () => {+ const findings = runScene([+ scene({ components: { narrative: false, action: false, dialogue: false } }),+ scene({ components: {} }),+ scene({ components: undefined }),+ ]);+ expect(findings).toEqual([]);+ });++ it('minComponents=3 flags a two-component scene and names the one gap', () => {+ const findings = runScene(+ [scene({ heading: 'No voice', components: { narrative: true, action: true, dialogue: false } })],+ { minComponents: 3 },+ );+ expect(findings).toHaveLength(1);+ expect(findings[0].problem).toMatch(/narrative and action but no dialogue/);+ });++ it('minComponents=1 disables the check', () => {+ const findings = runScene(+ [scene({ components: { narrative: false, action: false, dialogue: true } })],+ { minComponents: 1 },+ );+ expect(findings).toEqual([]);+ });++ it('falls back to a Scene: label when issueNumber is absent', () => {+ const findings = runScene([scene({ heading: 'Loose scene', issueNumber: null, components: { narrative: true } })]);+ expect(findings[0].location).toBe('Scene: Loose scene');+ expect(findings[0].issueNumber).toBeNull();+ });++ it('tolerates an empty / malformed outline', () => {+ expect(runScene([])).toEqual([]);+ expect(runScene([null, 'x', {}])).toEqual([]);+ });+});+describe('relationships.reciprocity — deterministic check', () => {const run = (characters) =>getCheck('relationships.reciprocity').run({ canon: { characters }, config: {}, severityDefault: 'low' });diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex 270f7754ab..a3a990be29 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -25,6 +25,7 @@ import { getSeries } from '../series.js';import { listIssues } from '../issues.js';import { getSeriesCanon } from '../seriesCanon.js';import { collectManuscriptSections, sectionsCorpus, manuscriptSectionHeader } from '../arcPlanner.js';+import { getReverseOutline } from '../reverseOutline.js';import { seedReviewFromFindings, getReview } from '../manuscriptReview.js';import { canonicalStringify } from '../../../lib/objects.js';@@ -53,6 +54,10 @@ const SOURCE_RESOLVERS = {canon: ({ canon }) => canonicalStringify(canon ?? null),'series.styleGuide': ({ series }) => canonicalStringify(series?.styleGuide ?? null),'series.arc.tickingClock': ({ series }) => canonicalStringify(series?.arc?.tickingClock ?? null),+ // The reverse-outline scenes the check reads (#1296). Fingerprinting the whole+ // scenes array is intentionally over-eager (any scene edit stales a finding)+ // rather than under: safe vs. false-fresh, and the check reads several scene fields.+ reverseOutline: ({ reverseOutline }) => canonicalStringify(reverseOutline ?? null),};for (const token of EDITORIAL_SOURCES) {if (typeof SOURCE_RESOLVERS[token] !== 'function') {@@ -135,22 +140,28 @@ export async function runEditorialChecks(seriesId, options = {}) {// the stitched corpus (deterministic checks like naming use only the canon).const series = await getSeries(seriesId);const needsManuscript = enabled.some(({ check }) => check.needsManuscript);- const [sections, canon, issues] = await Promise.all([+ // Reverse-outline fetch is gated on the declared source (#1296) so a run with no+ // scene-segmentation check pays no extra I/O — mirrors the needsManuscript gate.+ const needsReverseOutline = enabled.some(({ check }) => checkSources(check).includes('reverseOutline'));+ const [sections, canon, issues, outline] = await Promise.all([needsManuscript ? collectManuscriptSections(seriesId) : Promise.resolve([]),getSeriesCanon(series),listIssues({ seriesId }).catch(() => []),+ needsReverseOutline ? getReverseOutline(seriesId).catch(() => null) : Promise.resolve(null),]);const manuscript = sectionsCorpus(sections);+ const reverseOutline = Array.isArray(outline?.scenes) ? outline.scenes : [];// Resolve every source token once — each finding's fingerprint reads from this// so the editor flags it `stale` when the content that check actually read (its// declared `sources`) drifts (#1345, #1387).- const resolvedSources = resolveSources({ manuscript, canon, series });+ const resolvedSources = resolveSources({ manuscript, canon, series, reverseOutline });const baseCtx = {seriesId,series,issues,sections,manuscript,+ reverseOutline,canon,providerOverride,modelOverride,@@ -293,12 +304,15 @@ export async function getReviewWithStaleness(seriesId) {// a source (mirrors the run path's gate, now source-derived rather than the bare// needsManuscript flag so it stays correct as the source vocabulary grows).const needsManuscript = evaluable.some((c) => checkSources(checkFor(c.checkId)).includes('manuscript'));+ const needsReverseOutline = evaluable.some((c) => checkSources(checkFor(c.checkId)).includes('reverseOutline'));const series = await getSeries(seriesId);- const [sections, canon] = await Promise.all([+ const [sections, canon, outline] = await Promise.all([needsManuscript ? collectManuscriptSections(seriesId) : Promise.resolve([]),getSeriesCanon(series),+ needsReverseOutline ? getReverseOutline(seriesId).catch(() => null) : Promise.resolve(null),]);- const resolvedSources = resolveSources({ manuscript: sectionsCorpus(sections), canon, series });+ const reverseOutline = Array.isArray(outline?.scenes) ? outline.scenes : [];+ const resolvedSources = resolveSources({ manuscript: sectionsCorpus(sections), canon, series, reverseOutline });return {...review,comments: review.comments.map((c) => {diff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.jsindex 3e458bc8e0..20c4b5365b 100644--- a/server/services/pipeline/editorial/checkRunner.test.js+++ b/server/services/pipeline/editorial/checkRunner.test.js@@ -59,6 +59,10 @@ vi.mock('../manuscriptReview.js', () => ({seedReviewFromFindings: (...a) => seedReviewFromFindings(...a),getReview: async () => reviewState,}));+// Reverse-outline source (#1296) — backed by a mutable fixture; default empty so+// the scene.component-balance check is gated off unless a test populates scenes.+let outlineState = { scenes: [] };+vi.mock('../reverseOutline.js', () => ({ getReverseOutline: vi.fn(async () => outlineState) }));const { runEditorialChecks, buildEditorialCheckPlan, getReviewWithStaleness } = await import('./checkRunner.js');const { runStagedLLM, resolveStageContext } = await import('../../../lib/stageRunner.js');@@ -80,6 +84,7 @@ const disableWhere = (predicate) => ({beforeEach(() => {seedStore.length = 0;reviewState = { comments: [] };+ outlineState = { scenes: [] };seedReviewFromFindings.mockClear();runStagedLLM.mockClear();resolveStageContext.mockClear();@@ -339,6 +344,31 @@ describe('getReviewWithStaleness (#1345)', () => {expect(review.comments.find((c) => c.checkId === 'prose.info-dumping').stale).toBe(false);});+ it('stales only the reverse-outline-reading check when the scene segmentation changes (#1296/#1387 precision)', async () => {+ // scene.component-balance declares 'reverseOutline'; naming is canon-only and+ // info-dumping manuscript-only — so editing the scenes must stale ONLY the scene+ // finding, and the scene finding must NOT stale on manuscript/canon edits.+ outlineState = { scenes: [{ id: 'scene-001', issueNumber: 1, heading: 'Talking heads', anchorQuote: 'q', components: { narrative: false, action: false, dialogue: true } }] };+ await seedReviewFromRun();+ expect(reviewState.comments.find((c) => c.checkId === 'scene.component-balance')).toBeTruthy();+ // Mutate only the scene components (give it a second mode) — the outline drifts.+ outlineState = { scenes: [{ id: 'scene-001', issueNumber: 1, heading: 'Talking heads', anchorQuote: 'q', components: { narrative: true, action: false, dialogue: true } }] };+ const review = await getReviewWithStaleness('s1');+ expect(review.comments.find((c) => c.checkId === 'scene.component-balance').stale).toBe(true);+ expect(review.comments.find((c) => c.checkId === 'naming.dissimilar-names').stale).toBe(false);+ expect(review.comments.find((c) => c.checkId === 'prose.info-dumping').stale).toBe(false);+ });++ it('keeps a scene finding fresh when the manuscript changes (reverseOutline-only source)', async () => {+ outlineState = { scenes: [{ id: 'scene-001', issueNumber: 1, heading: 'Talking heads', anchorQuote: 'q', components: { narrative: false, action: false, dialogue: true } }] };+ await seedReviewFromRun();+ collectManuscriptSections.mockResolvedValueOnce([+ { number: 1, title: 'Pilot', stageId: 'prose', content: 'A completely rewritten opening.' },+ ]);+ const review = await getReviewWithStaleness('s1');+ expect(review.comments.find((c) => c.checkId === 'scene.component-balance').stale).toBe(false);+ });+it('stales a custom-check finding when its authored prompt changes, even if the manuscript is unchanged (#1387)', async () => {// A custom check's run logic is its prompt (user data), so a prompt edit must// stale its prior findings — the manuscript source alone can't catch that.