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

test: add field-contract test for renderVolumeIssue vs pipeline-volume-verify.md (#4136)

Adam Eivy1a13448c731a
diff --git a/.changelog/next/added-issue-4136.md b/.changelog/next/added-issue-4136.md
new file mode 100644
index 0000000000..78808187f3
--- /dev/null
+++ b/.changelog/next/added-issue-4136.md
@@ -0,0 +1 @@
+- Field-contract test guarding the volume-verify prompt against its rendered context, so a checklist item can no longer cite a volume/issue field the context never renders
diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.js
index 32b5aca578..eeccd53f12 100644
--- a/server/services/pipeline/arcPlanner/arcCore.js
+++ b/server/services/pipeline/arcPlanner/arcCore.js
@@ -17,7 +17,7 @@ import { getSeason } from '../seasons.js';
import { ARC_LIMITS, READER_MAP_BEAT_KINDS, buildSeason, cleanThemes, renderArcShapeGuidance, renderArcShapePositionSummary, sanitizeArc, sanitizeReaderMap, sanitizeSeason, sanitizeSeasonList } from '../../../lib/storyArc.js';
import { sanitizeCharacterArcList } from '../../../lib/seriesCharacterArc.js';
import { runPromptRefineRaw, trimChanges } from '../refineHelpers.js';
-import { ERR_VALIDATION, SHAPE_GUIDANCE_NONE, appendTickingClock, buildArcBaseContext, buildArcOverviewContext, buildNeighborVolumes, buildReaderMapContext, buildResolveContext, buildVerifyContext, compareIssuesByPosition, findingIdSet, makeErr, matchIssueForEpisodeEdit, matchResolvedFindings, renderVolumeIssue, resolveWorldContext, seasonIdByNumberOf, shapeEpisodeResolutions, shapeFindings, shapeSeasonOutlines, shapeVerifyIssues } from './context.js';
+import { ERR_VALIDATION, SHAPE_GUIDANCE_NONE, appendTickingClock, buildArcBaseContext, buildArcOverviewContext, buildNeighborVolumes, buildReaderMapContext, buildResolveContext, buildVerifyContext, compareIssuesByPosition, findingIdSet, makeErr, matchIssueForEpisodeEdit, matchResolvedFindings, renderVolumeFields, renderVolumeIssue, resolveWorldContext, seasonIdByNumberOf, shapeEpisodeResolutions, shapeFindings, shapeSeasonOutlines, shapeVerifyIssues } from './context.js';
export async function generateArcOverview(seriesId, options = {}) {
const series = await getSeries(seriesId);
@@ -287,15 +287,7 @@ export async function buildVolumeVerifyContext(series, season, preloadedWorld, {
const volumeIssues = allIssues
.filter((iss) => iss.seasonId === season.id)
.sort(compareIssuesByPosition)
- .map((issue) => (synopsisOnly
- ? {
- number: issue.number,
- title: issue.title,
- status: issue.status,
- arcPosition: issue.arcPosition,
- synopsis: (issue.stages?.idea?.input || '').trim() || null,
- }
- : renderVolumeIssue(issue)));
+ .map((issue) => renderVolumeIssue(issue, { synopsisOnly }));
// Volume-specific curve placement layered on top of base's arc-wide
// shapeGuidance so the verifier can flag "this volume inverts the expected
// fortune at its position."
@@ -304,15 +296,7 @@ export async function buildVolumeVerifyContext(series, season, preloadedWorld, {
|| '(no story shape selected — do not flag shape adherence for this volume)';
return {
...base,
- volume: {
- number: season.number ?? '',
- title: season.title || '',
- logline: season.logline || '',
- synopsis: season.synopsis || '',
- endingHook: season.endingHook || '',
- episodeCountTarget: season.episodeCountTarget ?? '',
- themesCsv: Array.isArray(season.themes) ? season.themes.join(', ') : '',
- },
+ volume: renderVolumeFields(season),
volumeShapePosition,
neighborsJson: JSON.stringify(buildNeighborVolumes(series.seasons, season.id), null, 2),
volumeIssuesJson: JSON.stringify(volumeIssues, null, 2),
diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.js
index acd7f3cbe7..26f9f4fa52 100644
--- a/server/services/pipeline/arcPlanner/context.js
+++ b/server/services/pipeline/arcPlanner/context.js
@@ -494,7 +494,10 @@ export function groupIssuesBySeasonTree(seasons, issues, { renderLeaf, seasonFie
for (const list of issuesBySeason.values()) {
list.sort(compareIssuesByPosition);
}
- const renderBucket = (list) => list.map(renderLeaf);
+ // Arity-safe: bare `list.map(renderLeaf)` would feed the array index as a
+ // second argument, so a renderer with an options bag (`renderVolumeIssue`'s
+ // `{ synopsisOnly }`) would silently receive the index as its options.
+ const renderBucket = (list) => list.map((iss) => renderLeaf(iss));
const tree = seasons.map((s) => ({
...seasonFields(s),
episodes: renderBucket(issuesBySeason.get(s.id) || []),
@@ -620,9 +623,15 @@ export function shapeEpisodeResolutions(rawEpisodes) {
// Set exactly one of `beats` / `synopsis` so the prompt's beat-level checks
// don't run against synopsis-only issues (and vice-versa). Beats land in
// idea.output once the LLM-expand pass runs; before that, idea.input still
-// carries the seed synopsis.
-export function renderVolumeIssue(iss) {
- const beats = (iss.stages?.idea?.output || '').trim();
+// carries the seed synopsis. `synopsisOnly` forces the synopsis branch for
+// callers that deliberately verify at synopsis depth even where beats exist.
+//
+// EXPORTED for the same reason as `renderVerifyIssueLeaf`: the volume-verify
+// prompt's checklist and this shape are two independent lists that must agree,
+// and a check naming a field this drops becomes a finding no resolver can close
+// — see `volumeVerifyPromptContract.test.js`.
+export function renderVolumeIssue(iss, { synopsisOnly = false } = {}) {
+ const beats = synopsisOnly ? '' : (iss.stages?.idea?.output || '').trim();
const synopsis = (iss.stages?.idea?.input || '').trim();
const base = {
number: iss.number,
@@ -634,6 +643,20 @@ export function renderVolumeIssue(iss) {
return { ...base, synopsis: synopsis || null };
}
+// The volume node `pipeline-volume-verify.md` scores, as `{{volume.*}}`.
+// Exported alongside `renderVolumeIssue` so the same contract test can assert
+// every volume field the prompt interpolates is actually rendered. Empty-string
+// fallbacks (not null) keep the Mustache render clean for an unfilled volume.
+export const renderVolumeFields = (s) => ({
+ number: s.number ?? '',
+ title: s.title || '',
+ logline: s.logline || '',
+ synopsis: s.synopsis || '',
+ endingHook: s.endingHook || '',
+ episodeCountTarget: s.episodeCountTarget ?? '',
+ themesCsv: Array.isArray(s.themes) ? s.themes.join(', ') : '',
+});
+
// Neighbor volumes — only the immediately-prior and immediately-next season
// (by `number`) — so the LLM can check boundary continuity (#5 in the
// prompt) without ballooning the context. Excludes the volume under review.
diff --git a/server/services/pipeline/arcPlanner/promptContractHelpers.js b/server/services/pipeline/arcPlanner/promptContractHelpers.js
new file mode 100644
index 0000000000..fb3ab66b12
--- /dev/null
+++ b/server/services/pipeline/arcPlanner/promptContractHelpers.js
@@ -0,0 +1,49 @@
+/**
+ * Shared test-support for the arc-planner prompt ↔ context contract suites
+ * (`verifyPromptContract.test.js`, `volumeVerifyPromptContract.test.js`).
+ *
+ * Each verify prompt's checklist and the context object that feeds it are two
+ * independent lists with nothing but those suites enforcing agreement. Both
+ * suites need the same three primitives, so they live here rather than being
+ * copied per prompt — a copy would drift exactly the way the prompts do.
+ */
+
+import { readFile } from 'fs/promises';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..');
+
+/**
+ * Read a SHIPPED stage prompt. Deliberately reads `data.reference/` and not
+ * `data/` — `data/` is gitignored per-install state that a user may have
+ * customized, so only the seed the repo ships is a contract worth enforcing.
+ */
+export const readShippedPrompt = (name) =>
+ readFile(join(REPO_ROOT, 'data.reference', 'prompts', 'stages', name), 'utf-8');
+
+/**
+ * Candidate record-field identifiers a prompt cites in backticks. Strips the
+ * illustrative value a check may attach (`episodeCountTarget: 12`) and the
+ * array marker (`issues[]`) so the bare identifier is what gets tested. Only
+ * single lowerCamelCase identifiers are candidates — JSON blobs, dotted paths
+ * (`arc.themes`), kebab vocabulary, and prose fragments are not record fields.
+ */
+export const backtickedTokens = (markdown) => {
+ const out = new Set();
+ for (const match of markdown.matchAll(/`([^`\n]+)`/g)) {
+ const token = match[1].split(':')[0].replace(/\[\]$/, '').trim();
+ if (/^[a-z][A-Za-z0-9]*$/.test(token)) out.add(token);
+ }
+ return out;
+};
+
+/** The `{{worldX}}` blocks a prompt interpolates. */
+export const worldVars = (markdown) => new Set(
+ [...markdown.matchAll(/\{\{\{?(world[A-Za-z0-9]*)\}?\}\}/g)].map((m) => m[1]),
+);
+
+/** The leaf names a prompt interpolates under a dotted `{{prefix.x}}` namespace. */
+export const namespacedVars = (markdown, prefix) => new Set(
+ [...markdown.matchAll(new RegExp(`\\{\\{\\{?${prefix}\\.([A-Za-z0-9]+)\\}?\\}\\}`, 'g'))].map((m) => m[1]),
+);
diff --git a/server/services/pipeline/arcPlanner/verifyPromptContract.test.js b/server/services/pipeline/arcPlanner/verifyPromptContract.test.js
index af2ce4b387..dcd9c1a847 100644
--- a/server/services/pipeline/arcPlanner/verifyPromptContract.test.js
+++ b/server/services/pipeline/arcPlanner/verifyPromptContract.test.js
@@ -23,14 +23,9 @@
*/
import { describe, it, expect } from 'vitest';
-import { readFile } from 'fs/promises';
-import { join, dirname } from 'path';
-import { fileURLToPath } from 'url';
import { renderVerifyIssueLeaf, renderVerifySeasonFields } from './context.js';
-
-const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..');
-const shippedPrompt = (name) => join(REPO_ROOT, 'data.reference', 'prompts', 'stages', name);
+import { readShippedPrompt, backtickedTokens, worldVars } from './promptContractHelpers.js';
// Backticked tokens that are deliberately NOT record fields. Anything backticked
// in the prompt that is not here must be renderable — that is the whole point of
@@ -42,20 +37,6 @@ const NON_FIELD_TOKENS = new Set([
'pilot', 'finale', 'complication', 'midpoint', 'b-plot', 'all-is-lost',
]);
-const backtickedTokens = (markdown) => {
- const out = new Set();
- for (const match of markdown.matchAll(/`([^`\n]+)`/g)) {
- // Strip the illustrative value a check may attach (`episodeCountTarget: 12`)
- // and the array marker (`issues[]`) so the bare identifier is what's tested.
- const token = match[1].split(':')[0].replace(/\[\]$/, '').trim();
- // Only single identifiers are candidate record fields. JSON blobs, dotted
- // arc paths (`arc.themes` — an arc field, not a leaf/season one), and prose
- // fragments are not.
- if (/^[a-z][A-Za-z0-9]*$/.test(token)) out.add(token);
- }
- return out;
-};
-
const renderableFields = () => new Set([
...Object.keys(renderVerifyIssueLeaf({ stages: { idea: { input: 'x' } } })),
...Object.keys(renderVerifySeasonFields({})),
@@ -63,7 +44,7 @@ const renderableFields = () => new Set([
describe('pipeline-arc-verify prompt ↔ buildVerifyContext leaf contract', () => {
it('renders every record field the shipped checklist cites', async () => {
- const markdown = await readFile(shippedPrompt('pipeline-arc-verify.md'), 'utf-8');
+ const markdown = await readShippedPrompt('pipeline-arc-verify.md');
const renderable = renderableFields();
const unrenderable = [...backtickedTokens(markdown)]
.filter((token) => !NON_FIELD_TOKENS.has(token) && !renderable.has(token));
@@ -88,14 +69,10 @@ describe('pipeline-arc-verify ↔ pipeline-arc-resolve world parity', () => {
// world bag. A world variable the resolver renders but the verifier does not is
// exactly the asymmetry that manufactures unsatisfiable groundedness findings:
// the verifier calls a canon entity invented, the resolver can see it is not.
- const worldVars = (markdown) => new Set(
- [...markdown.matchAll(/\{\{\{?(world[A-Za-z0-9]*)\}?\}\}/g)].map((m) => m[1]),
- );
-
it('shows the verifier every world block the resolver can see', async () => {
const [verify, resolve] = await Promise.all([
- readFile(shippedPrompt('pipeline-arc-verify.md'), 'utf-8'),
- readFile(shippedPrompt('pipeline-arc-resolve.md'), 'utf-8'),
+ readShippedPrompt('pipeline-arc-verify.md'),
+ readShippedPrompt('pipeline-arc-resolve.md'),
]);
const verifyVars = worldVars(verify);
const missing = [...worldVars(resolve)].filter((v) => !verifyVars.has(v));
@@ -103,7 +80,7 @@ describe('pipeline-arc-verify ↔ pipeline-arc-resolve world parity', () => {
});
it('renders the category canon the world actually defines', async () => {
- const markdown = await readFile(shippedPrompt('pipeline-arc-verify.md'), 'utf-8');
+ const markdown = await readShippedPrompt('pipeline-arc-verify.md');
expect(markdown).toContain('{{worldCategoriesText}}');
});
});
diff --git a/server/services/pipeline/arcPlanner/volumeVerifyPromptContract.test.js b/server/services/pipeline/arcPlanner/volumeVerifyPromptContract.test.js
new file mode 100644
index 0000000000..ba7249fc8a
--- /dev/null
+++ b/server/services/pipeline/arcPlanner/volumeVerifyPromptContract.test.js
@@ -0,0 +1,108 @@
+/**
+ * Contract between `pipeline-volume-verify.md` and the context
+ * `buildVolumeVerifyContext` hands it — the volume-scope sibling of
+ * `verifyPromptContract.test.js`.
+ *
+ * Same failure mode, same stakes: the prompt's checklist and the rendered
+ * context are two independent lists that must agree, with nothing but this file
+ * enforcing it. The volume verifier feeds the same revert-on-any-blocker gate as
+ * the arc verifier, so a check reading a field the context never renders emits a
+ * finding no resolver can close, and the gate stalls forever on a volume with
+ * nothing wrong with it. Two instances of that class already shipped against the
+ * arc verifier (an `arcRole` check the leaf never rendered; a world-canon check
+ * reading `worldCanonText` while the canon lived in `worldCategoriesText`).
+ *
+ * Both halves of the contract are covered: the record fields the checklist cites
+ * in backticks, and the `{{volume.*}}` fields the prompt interpolates.
+ */
+
+import { describe, it, expect } from 'vitest';
+
+import { renderVolumeIssue, renderVolumeFields } from './context.js';
+import { readShippedPrompt, backtickedTokens, namespacedVars } from './promptContractHelpers.js';
+
+const PROMPT = 'pipeline-volume-verify.md';
+
+// Backticked tokens that are deliberately NOT record fields. Anything backticked
+// in the prompt that is not here must be renderable — that is the whole point of
+// the guard, so extend this list only for genuinely non-field vocabulary.
+const NON_FIELD_TOKENS = new Set([
+ // Output-contract vocabulary.
+ 'issues', 'severity', 'location', 'high', 'medium', 'low',
+ // `location` VALUE forms (`episode:3`, `episode:2-3`, bare `volume`), not
+ // field names.
+ 'episode', 'volume',
+]);
+
+// The prompt scores an issue at whichever depth it has, so BOTH branches of the
+// leaf are legitimately citable: `beats` on an LLM-expanded issue, `synopsis` on
+// an un-expanded one.
+const renderableFields = () => new Set([
+ ...Object.keys(renderVolumeIssue({ stages: { idea: { output: 'beat sheet' } } })),
+ ...Object.keys(renderVolumeIssue({ stages: { idea: { input: 'seed synopsis' } } })),
+ ...Object.keys(renderVolumeFields({})),
+]);
+
+const unrenderableIn = (markdown, renderable) => [...backtickedTokens(markdown)]
+ .filter((token) => !NON_FIELD_TOKENS.has(token) && !renderable.has(token));
+
+describe('pipeline-volume-verify prompt ↔ buildVolumeVerifyContext contract', () => {
+ it('renders every record field the shipped checklist cites', async () => {
+ const markdown = await readShippedPrompt(PROMPT);
+ expect(unrenderableIn(markdown, renderableFields())).toEqual([]);
+ });
+
+ it('fails when a cited field is dropped from the issue leaf (bypass probe)', () => {
+ // Proves the assertion above has teeth: a checklist naming `beats` against a
+ // leaf that no longer renders it must be caught, not silently pass.
+ const renderableWithoutBeats = new Set(
+ [...renderableFields()].filter((field) => field !== 'beats'),
+ );
+ const cited = 'Beat-level findings are only valid against issues that have `beats`.';
+ expect(unrenderableIn(cited, renderableWithoutBeats)).toEqual(['beats']);
+ });
+
+ it('renders every {{volume.*}} field the prompt interpolates', async () => {
+ const markdown = await readShippedPrompt(PROMPT);
+ const rendered = new Set(Object.keys(renderVolumeFields({})));
+ const missing = [...namespacedVars(markdown, 'volume')].filter((v) => !rendered.has(v));
+ expect(missing).toEqual([]);
+ });
+
+ it('fails when an interpolated volume field is dropped (bypass probe)', () => {
+ // A renamed/removed volume field renders as an empty Mustache slot, so the
+ // prompt silently judges the volume against a blank `endingHook` instead of
+ // erroring — exactly the drift this half of the contract has to catch.
+ const rendered = new Set(
+ Object.keys(renderVolumeFields({})).filter((field) => field !== 'endingHook'),
+ );
+ const cited = namespacedVars('- **Ending hook:** {{volume.endingHook}}', 'volume');
+ expect([...cited].filter((v) => !rendered.has(v))).toEqual(['endingHook']);
+ });
+});
+
+describe('renderVolumeIssue depth selection', () => {
+ const issue = {
+ number: 4,
+ title: 'Example Issue',
+ status: 'draft',
+ arcPosition: 4,
+ stages: { idea: { input: 'seed synopsis', output: 'beat sheet' } },
+ };
+
+ it('renders beats (and never synopsis) once the expand pass has run', () => {
+ expect(renderVolumeIssue(issue)).toEqual({
+ number: 4, title: 'Example Issue', status: 'draft', arcPosition: 4, beats: 'beat sheet',
+ });
+ });
+
+ it('renders synopsis (and never beats) when synopsisOnly is requested', () => {
+ expect(renderVolumeIssue(issue, { synopsisOnly: true })).toEqual({
+ number: 4, title: 'Example Issue', status: 'draft', arcPosition: 4, synopsis: 'seed synopsis',
+ });
+ });
+
+ it('nulls synopsis rather than emitting an empty string for an unseeded issue', () => {
+ expect(renderVolumeIssue({ ...issue, stages: {} }).synopsis).toBeNull();
+ });
+});