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-1295]): add pov.justified editorial check (POV→arc)
[._.]/ Adam Eivy091c9f9e1e78
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex c08ebe9276..fc8319831c 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -56,12 +56,17 @@ 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`, `reverseOutline`). The staleness+`series.styleGuide`, `series.arc.tickingClock`, `reverseOutline`,+`editorialArcs`). The stalenessrunner fingerprints exactly those sources, so a finding goes stale only whencontent the check actually analyzed drifts — declare too few and a finding staysfalsely 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+inject `ctx.reverseOutline` (the scenes array). `editorialArcs` (#1295) makes the+runner fetch the series editorial aggregate and inject `ctx.editorialArcs` (the+detected per-character `{ name, arcDirection, issueCount, isProtagonist }`+projection — the graceful-degradation fallback for the dedicated arc model until+`#arc-transitions` lands). 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`.diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex a474ff7c30..5bd07339e8 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -48,12 +48,19 @@ const SEVERITIES = CHECK_SEVERITIES;// scenes carry components/povCharacter/charactersPresent.// The runner fetches it (gated on this source) and injects// `ctx.reverseOutline` (the scenes array).+// - 'editorialArcs' — the detected per-character arc directions from the series+// editorial analysis aggregate (#1295). The runner fetches it+// (gated on this source) and injects `ctx.editorialArcs`+// (`[{ name, arcDirection, issueCount, isProtagonist }]`). This+// is the graceful-degradation fallback for the dedicated arc+// model (#arc-transitions) until that lands.export const EDITORIAL_SOURCES = Object.freeze(['manuscript','canon','series.styleGuide','series.arc.tickingClock','reverseOutline',+ 'editorialArcs',]);// Default per-run finding cap for user-defined checks (#1346) — mirrors the@@ -1146,6 +1153,121 @@ export const EDITORIAL_CHECKS = [return findings;},},+ {+ id: 'pov.justified',+ sources: ['reverseOutline', 'editorialArcs'],+ label: 'POV justification (every viewpoint earns its arc)',+ description:+ 'Cross-references the reverse-outline POV-per-scene map against detected character arcs. Flags a POV character who narrates a viewpoint but has no arc ("POV without arc — justify or cut"), and the inverse imbalance — a drive-by POV who holds the viewpoint in only a scene or two. Falls back to the editorial analysis\'s detected arc direction until a dedicated arc model is populated, and stays silent on the no-arc check when neither is available (the structural drive-by check still runs).',+ scope: 'series',+ kind: 'deterministic',+ category: 'arc',+ severityDefault: 'low',+ defaultEnabled: true,+ configSchema: z.object({+ // A POV character holding the viewpoint in this many scenes or fewer is a+ // drive-by POV. 1 flags single-scene POVs; 0 disables the drive-by check.+ driveByMaxScenes: z.number().int().min(0).max(20).default(1),+ // When an arc model (detected or dedicated) is available, flag a POV+ // character whose arc is flat (no arc). Off keeps only the drive-by check.+ flagUnjustifiedPov: z.boolean().default(true),+ }),+ configFields: [+ {+ key: 'driveByMaxScenes',+ label: 'Drive-by POV threshold (max scenes)',+ type: 'number',+ min: 0,+ max: 20,+ step: 1,+ help: 'Flag a POV character who holds the viewpoint in this many scenes or fewer as a drive-by POV. 1 flags single-scene POVs; 0 disables the drive-by check.',+ },+ {+ key: 'flagUnjustifiedPov',+ label: 'Flag POV characters with no arc',+ type: 'boolean',+ help: 'When a character arc model is available, flag a POV character whose detected arc is flat (no arc) — "POV without arc — justify or cut". Disable to keep only the drive-by check.',+ },+ ],+ // Needs a generated reverse outline with at least one POV-tagged scene to read.+ gate: (ctx) => Array.isArray(ctx.reverseOutline)+ && ctx.reverseOutline.some((s) => s && typeof s.povCharacter === 'string' && s.povCharacter.trim()),+ run: (ctx) => {+ const scenes = Array.isArray(ctx.reverseOutline) ? ctx.reverseOutline : [];+ const driveByMax = ctx.config?.driveByMaxScenes ?? 1;+ const flagUnjustified = ctx.config?.flagUnjustifiedPov !== false;++ // POV holder → the scenes they narrate, keyed by normalized name so casing /+ // spacing variants of the same name collapse into one holder. Preserves+ // first-appearance order (scenes arrive sequence-ordered) for stable output.+ const holders = new Map();+ for (const s of scenes) {+ if (!s || typeof s !== 'object') continue;+ const pov = typeof s.povCharacter === 'string' ? s.povCharacter.trim() : '';+ if (!pov) continue;+ const key = normalizeName(pov);+ if (!key) continue;+ let entry = holders.get(key);+ if (!entry) { entry = { name: pov, key, scenes: [] }; holders.set(key, entry); }+ entry.scenes.push(s);+ }+ if (holders.size === 0) return [];++ // Detected arc directions (the #arc-transitions fallback). Empty when neither+ // the dedicated arc model nor the editorial analysis has run — in that case we+ // can't tell a justified POV from an unjustified one, so the no-arc check stays+ // silent (degrade gracefully, no false positives). The structural drive-by+ // check below reads only the outline, so it still runs.+ const arcs = Array.isArray(ctx.editorialArcs) ? ctx.editorialArcs : [];+ const arcByName = new Map(+ arcs.map((a) => [normalizeName(a?.name), a]).filter(([k]) => k)+ );+ const haveArcModel = arcByName.size > 0;++ const findings = [];+ const flag = ({ severity, location, problem, suggestion, anchorQuote = '', issueNumber = null }) =>+ findings.push({ severity, category: 'arc', location, problem, suggestion, anchorQuote, issueNumber });++ for (const holder of holders.values()) {+ const sceneCount = holder.scenes.length;+ const first = holder.scenes[0];+ const issueNumber = Number.isInteger(first?.issueNumber) ? first.issueNumber : null;+ const where = issueNumber != null ? `Issue ${issueNumber}: ${sceneLabel(first)}` : `POV: ${holder.name}`;+ const anchorQuote = typeof first?.anchorQuote === 'string' ? first.anchorQuote : '';++ // 1) Unjustified POV — narrates a viewpoint but has no detected arc. Only+ // when an arc model exists to judge against (else we can't tell).+ if (flagUnjustified && haveArcModel) {+ const arc = arcByName.get(holder.key) || null;+ const hasArc = !!arc && typeof arc.arcDirection === 'string' && arc.arcDirection !== 'flat';+ if (!hasArc) {+ flag({+ severity: ctx.severityDefault,+ location: where,+ problem: `"${holder.name}" holds POV in ${sceneCount} scene${sceneCount === 1 ? '' : 's'} but has no detected character arc (${arc ? `arc direction is ${arc.arcDirection}` : 'not present in the detected arcs'}). A POV that exists only to deliver information — no arc, no stakes — should be cut or folded into another POV.`,+ suggestion: `Give "${holder.name}" their own arc — a want, stakes, and a change across the story — or fold their viewpoint scenes into a POV character who already has one.`,+ anchorQuote,+ issueNumber,+ });+ }+ }++ // 2) Drive-by POV (inverse imbalance) — viewpoint used in only a scene or+ // two. Purely structural over the outline, so it runs without an arc model.+ if (driveByMax > 0 && sceneCount <= driveByMax) {+ flag({+ severity: ctx.severityDefault,+ location: where,+ problem: `"${holder.name}" holds POV in only ${sceneCount} scene${sceneCount === 1 ? '' : 's'} — a drive-by viewpoint. A POV used once reads as a structural seam (a head-hop for a single scene), diluting the viewpoints that carry the story.`,+ suggestion: `Route ${holder.name}'s scene${sceneCount === 1 ? '' : 's'} through an established POV character, or give them enough presence across the story that the viewpoint earns its place.`,+ 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 9036d383be..2c234de226 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -707,6 +707,104 @@ describe('scene.component-balance — deterministic check', () => {});});+describe('pov.justified — deterministic check', () => {+ const POV = 'pov.justified';+ const scene = (pov, over = {}) => ({+ heading: `${pov || 'no'}-pov scene`, issueNumber: 1, anchorQuote: 'q', povCharacter: pov, ...over,+ });+ const runPov = (scenes, { config = {}, arcs = [] } = {}) =>+ getCheck(POV).run({ reverseOutline: scenes, editorialArcs: arcs, config, severityDefault: 'low' });++ it('declares both reverseOutline and editorialArcs sources', () => {+ const c = getCheck(POV);+ expect(c.scope).toBe('series');+ expect(c.kind).toBe('deterministic');+ expect(c.sources).toEqual(['reverseOutline', 'editorialArcs']);+ expect(c.defaultEnabled).toBe(true);+ });++ it('gate requires at least one POV-tagged scene', () => {+ const c = getCheck(POV);+ expect(c.gate({ reverseOutline: [] })).toBe(false);+ expect(c.gate({ reverseOutline: [scene('')] })).toBe(false);+ expect(c.gate({ reverseOutline: [scene('Aria')] })).toBe(true);+ });++ it('flags a POV holder with no detected arc as unjustified (arc model present)', () => {+ const findings = runPov(+ [scene('Aria'), scene('Aria'), scene('Bram'), scene('Bram')],+ { arcs: [{ name: 'Aria', arcDirection: 'rising', issueCount: 2 }, { name: 'Bram', arcDirection: 'flat', issueCount: 2 }] },+ );+ // Bram holds POV but his arc is flat → "POV without arc". Aria is justified (rising).+ const unjustified = findings.filter((f) => /no detected character arc/.test(f.problem));+ expect(unjustified).toHaveLength(1);+ expect(unjustified[0].problem).toMatch(/"Bram"/);+ expect(unjustified[0].category).toBe('arc');+ expect(unjustified[0].location).toBe('Issue 1: Bram-pov scene');+ expect(unjustified[0].anchorQuote).toBe('q');+ });++ it('flags a POV holder absent from the detected arcs entirely', () => {+ const findings = runPov(+ [scene('Ghost'), scene('Ghost')],+ { config: { driveByMaxScenes: 0 }, arcs: [{ name: 'Aria', arcDirection: 'rising', issueCount: 2 }] },+ );+ expect(findings).toHaveLength(1);+ expect(findings[0].problem).toMatch(/not present in the detected arcs/);+ });++ it('flags a drive-by (single-scene) POV via the inverse-imbalance check', () => {+ const findings = runPov(+ [scene('Aria'), scene('Aria'), scene('Cameo')],+ { arcs: [{ name: 'Aria', arcDirection: 'rising', issueCount: 2 }, { name: 'Cameo', arcDirection: 'rising', issueCount: 1 }] },+ );+ // Cameo has an arc (so not unjustified) but holds POV in only 1 scene → drive-by.+ const driveBy = findings.filter((f) => /drive-by viewpoint/.test(f.problem));+ expect(driveBy).toHaveLength(1);+ expect(driveBy[0].problem).toMatch(/"Cameo"/);+ expect(driveBy[0].problem).toMatch(/only 1 scene/);+ });++ it('degrades gracefully with no arc model: only the structural drive-by check runs', () => {+ const findings = runPov([scene('Aria'), scene('Aria'), scene('Solo')]); // no arcs passed+ // No arc data → no "unjustified" findings, but Solo (1 scene) is still a drive-by.+ expect(findings.every((f) => !/no detected character arc/.test(f.problem))).toBe(true);+ const driveBy = findings.filter((f) => /drive-by viewpoint/.test(f.problem));+ expect(driveBy).toHaveLength(1);+ expect(driveBy[0].problem).toMatch(/"Solo"/);+ });++ it('collapses casing/spacing variants of a POV name into one holder', () => {+ const findings = runPov(+ [scene('Aria'), scene(' aria '), scene('ARIA')],+ { config: { driveByMaxScenes: 0 }, arcs: [{ name: 'aria', arcDirection: 'flat', issueCount: 3 }] },+ );+ // One holder (3 scenes), flat arc → exactly one unjustified finding, not three.+ expect(findings).toHaveLength(1);+ expect(findings[0].problem).toMatch(/holds POV in 3 scenes/);+ });++ it('driveByMaxScenes=0 disables the drive-by check; flagUnjustifiedPov=false disables the arc check', () => {+ const scenes = [scene('Solo')];+ const arcs = [{ name: 'Solo', arcDirection: 'flat', issueCount: 1 }];+ expect(runPov(scenes, { config: { driveByMaxScenes: 0, flagUnjustifiedPov: false }, arcs })).toEqual([]);+ });++ it('tolerates an empty / malformed outline', () => {+ expect(runPov([])).toEqual([]);+ expect(runPov([null, 'x', {}, scene('')])).toEqual([]);+ });++ it('falls back to a POV: label when issueNumber is absent', () => {+ const findings = runPov(+ [scene('Aria', { issueNumber: null })],+ { config: { driveByMaxScenes: 1, flagUnjustifiedPov: false } },+ );+ expect(findings[0].location).toBe('POV: Aria');+ expect(findings[0].issueNumber).toBeNull();+ });+});+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 a3a990be29..620a80cd72 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -26,6 +26,7 @@ import { listIssues } from '../issues.js';import { getSeriesCanon } from '../seriesCanon.js';import { collectManuscriptSections, sectionsCorpus, manuscriptSectionHeader } from '../arcPlanner.js';import { getReverseOutline } from '../reverseOutline.js';+import { getSeriesEditorial } from '../editorialAnalysis.js';import { seedReviewFromFindings, getReview } from '../manuscriptReview.js';import { canonicalStringify } from '../../../lib/objects.js';@@ -58,7 +59,25 @@ const SOURCE_RESOLVERS = {// 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),+ // The detected per-character arc directions a POV check reads (#1295). The+ // injected `editorialArcs` is the stable projection (name/arcDirection/issueCount/+ // isProtagonist) — NOT the raw getSeriesEditorial output, which carries a+ // per-call `generatedAt` timestamp that would re-stale every finding each run.+ editorialArcs: ({ editorialArcs }) => canonicalStringify(editorialArcs ?? null),};++// Stable projection of the series editorial aggregate down to the arc fields a+// POV/arc check reads — drops the volatile `generatedAt` (and the rest) so the+// staleness fingerprint only moves when a character's detected arc actually does.+function projectEditorialArcs(editorial) {+ const chars = Array.isArray(editorial?.characters) ? editorial.characters : [];+ return chars.map((c) => ({+ name: c?.name || '',+ arcDirection: c?.arcDirection || 'flat',+ issueCount: Number.isFinite(c?.issueCount) ? c.issueCount : 0,+ isProtagonist: c?.isProtagonist === true,+ }));+}for (const token of EDITORIAL_SOURCES) {if (typeof SOURCE_RESOLVERS[token] !== 'function') {throw new Error(`checkRunner: editorial source "${token}" has no fingerprint resolver — keep SOURCE_RESOLVERS in sync with EDITORIAL_SOURCES`);@@ -143,18 +162,26 @@ export async function runEditorialChecks(seriesId, options = {}) {// 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([+ // Editorial-arc fetch is gated on the declared source (#1295) so a run with no+ // POV/arc check pays no extra snapshot I/O — mirrors the needsReverseOutline gate.+ const needsEditorialArcs = enabled.some(({ check }) => checkSources(check).includes('editorialArcs'));+ const [sections, canon, issues, outline, editorial] = await Promise.all([needsManuscript ? collectManuscriptSections(seriesId) : Promise.resolve([]),getSeriesCanon(series),listIssues({ seriesId }).catch(() => []),needsReverseOutline ? getReverseOutline(seriesId).catch(() => null) : Promise.resolve(null),+ // Reuse the already-loaded series so the aggregate skips a redundant getSeries.+ // (issues is fetched in this same Promise.all, so it can't be passed here —+ // it's still in the temporal dead zone — and stays an internal fetch.)+ needsEditorialArcs ? getSeriesEditorial(seriesId, { series }).catch(() => null) : Promise.resolve(null),]);const manuscript = sectionsCorpus(sections);const reverseOutline = Array.isArray(outline?.scenes) ? outline.scenes : [];+ const editorialArcs = projectEditorialArcs(editorial);// 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, reverseOutline });+ const resolvedSources = resolveSources({ manuscript, canon, series, reverseOutline, editorialArcs });const baseCtx = {seriesId,series,@@ -162,6 +189,7 @@ export async function runEditorialChecks(seriesId, options = {}) {sections,manuscript,reverseOutline,+ editorialArcs,canon,providerOverride,modelOverride,@@ -305,14 +333,18 @@ export async function getReviewWithStaleness(seriesId) {// 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 needsEditorialArcs = evaluable.some((c) => checkSources(checkFor(c.checkId)).includes('editorialArcs'));const series = await getSeries(seriesId);- const [sections, canon, outline] = await Promise.all([+ const [sections, canon, outline, editorial] = await Promise.all([needsManuscript ? collectManuscriptSections(seriesId) : Promise.resolve([]),getSeriesCanon(series),needsReverseOutline ? getReverseOutline(seriesId).catch(() => null) : Promise.resolve(null),+ // Reuse the already-loaded series (issues isn't fetched on this path).+ needsEditorialArcs ? getSeriesEditorial(seriesId, { series }).catch(() => null) : Promise.resolve(null),]);const reverseOutline = Array.isArray(outline?.scenes) ? outline.scenes : [];- const resolvedSources = resolveSources({ manuscript: sectionsCorpus(sections), canon, series, reverseOutline });+ const editorialArcs = projectEditorialArcs(editorial);+ const resolvedSources = resolveSources({ manuscript: sectionsCorpus(sections), canon, series, reverseOutline, editorialArcs });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 20c4b5365b..cb7b81a2f0 100644--- a/server/services/pipeline/editorial/checkRunner.test.js+++ b/server/services/pipeline/editorial/checkRunner.test.js@@ -63,6 +63,11 @@ vi.mock('../manuscriptReview.js', () => ({// 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) }));+// Editorial-arcs source (#1295) — backed by a mutable fixture; default empty so+// the pov.justified arc cross-reference degrades gracefully unless a test+// populates detected character arcs.+let editorialState = { characters: [] };+vi.mock('../editorialAnalysis.js', () => ({ getSeriesEditorial: vi.fn(async () => editorialState) }));const { runEditorialChecks, buildEditorialCheckPlan, getReviewWithStaleness } = await import('./checkRunner.js');const { runStagedLLM, resolveStageContext } = await import('../../../lib/stageRunner.js');@@ -85,6 +90,7 @@ beforeEach(() => {seedStore.length = 0;reviewState = { comments: [] };outlineState = { scenes: [] };+ editorialState = { characters: [] };seedReviewFromFindings.mockClear();runStagedLLM.mockClear();resolveStageContext.mockClear();diff --git a/server/services/pipeline/editorialAnalysis.js b/server/services/pipeline/editorialAnalysis.jsindex df2d5375e2..64ba69b9a2 100644--- a/server/services/pipeline/editorialAnalysis.js+++ b/server/services/pipeline/editorialAnalysis.js@@ -316,10 +316,14 @@ function resolveDirection(directions) {* Aggregate every analyzed issue in a series into the Editorial Roadmap:* Plot / Character / Reader curves, character arcs (with protagonist detection),* and coverage stats.+ *+ * A caller that already holds the series and/or issue list (e.g. the editorial+ * check runner, which loads both for its shared ctx) can pass them in to avoid a+ * redundant `getSeries` + `listIssues` round-trip; both default to a fresh fetch.*/-export async function getSeriesEditorial(seriesId) {- const series = await getSeries(seriesId).catch(() => null);- const issues = await listIssues({ seriesId });+export async function getSeriesEditorial(seriesId, { series: seriesArg, issues: issuesArg } = {}) {+ const series = seriesArg !== undefined ? seriesArg : await getSeries(seriesId).catch(() => null);+ const issues = Array.isArray(issuesArg) ? issuesArg : await listIssues({ seriesId });const ordered = [...issues].sort((a, b) => (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0));