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

refactor([issue-1544]): extract shared season-tree grouping + episode-match helpers

[._.]/ Adam Eivy662ba00d87f9
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 0c900ae09f..796e36834a 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -2163,3 +2163,101 @@ describe('arcPlanner — manuscript completeness + derive-from-manuscript', () =
expect(f1.seasonId).toBe(v1.id); // the kept (lowest, unlocked) volume reused its id
});
});
+
+// Pure helpers extracted in #1544 to dedup the season-tree grouping (shared by
+// buildVerifyContext + buildBeatTree) and the episode-match logic (shared by
+// applyEpisodeResolutions + applyBeatResolutions). No I/O — tested directly.
+describe('arcPlanner — groupIssuesBySeasonTree (#1544)', () => {
+ const seasons = [
+ { id: 's1', number: 1, title: 'One' },
+ { id: 's2', number: 2, title: 'Two' },
+ ];
+ // Deliberately out of arcPosition order to prove the per-bucket sort.
+ const issues = [
+ { id: 'b', number: 2, seasonId: 's1', arcPosition: 2 },
+ { id: 'a', number: 1, seasonId: 's1', arcPosition: 1 },
+ { id: 'c', number: 3, seasonId: 's2', arcPosition: 1 },
+ { id: 'u', number: 9, seasonId: null, arcPosition: 1 },
+ ];
+ const opts = {
+ renderLeaf: (iss) => ({ number: iss.number }),
+ seasonFields: (s) => ({ number: s.number, title: s.title }),
+ };
+
+ it('buckets by seasonId and sorts each bucket by arcPosition', () => {
+ const tree = planner.groupIssuesBySeasonTree(seasons, issues, opts);
+ expect(tree[0]).toMatchObject({ number: 1, title: 'One' });
+ expect(tree[0].episodes.map((e) => e.number)).toEqual([1, 2]); // arcPosition order, not input order
+ expect(tree[1].episodes.map((e) => e.number)).toEqual([3]);
+ });
+
+ it('appends a null-seasonId bucket as the (ungrouped issues) node', () => {
+ const tree = planner.groupIssuesBySeasonTree(seasons, issues, opts);
+ const ungrouped = tree[tree.length - 1];
+ expect(ungrouped).toMatchObject({ number: null, title: '(ungrouped issues)' });
+ expect(ungrouped.episodes.map((e) => e.number)).toEqual([9]);
+ });
+
+ it('omits the ungrouped node when every issue has a season', () => {
+ const grouped = issues.filter((i) => i.seasonId);
+ const tree = planner.groupIssuesBySeasonTree(seasons, grouped, opts);
+ expect(tree.some((n) => n.title === '(ungrouped issues)')).toBe(false);
+ });
+
+ it('uses seasonFields for node shape and appends episodes last (key order)', () => {
+ const tree = planner.groupIssuesBySeasonTree(
+ [{ id: 's1', number: 1, title: 'One', status: 'active' }],
+ [],
+ { renderLeaf: opts.renderLeaf, seasonFields: (s) => ({ number: s.number, title: s.title, status: s.status }) },
+ );
+ expect(Object.keys(tree[0])).toEqual(['number', 'title', 'status', 'episodes']);
+ });
+});
+
+describe('arcPlanner — matchIssueForEpisodeEdit (#1544)', () => {
+ const issues = [
+ { id: 'a', number: 5, seasonId: 's1' },
+ { id: 'b', number: 5, seasonId: 's2' },
+ { id: 'c', number: 7, seasonId: 's1' },
+ ];
+ const seasonIdByNumber = new Map([[1, 's1'], [2, 's2']]);
+
+ it('requires the season match when the named season resolves', () => {
+ const m = planner.matchIssueForEpisodeEdit(issues, seasonIdByNumber, { seasonNumber: 2, episodeNumber: 5 });
+ expect(m?.id).toBe('b'); // not the global-first issue 5 (id 'a')
+ });
+
+ it('returns undefined (no number fallback) when the resolved season has no such issue', () => {
+ const m = planner.matchIssueForEpisodeEdit(issues, seasonIdByNumber, { seasonNumber: 1, episodeNumber: 99 });
+ expect(m).toBeUndefined();
+ });
+
+ it('matches on series-global number when no season is given', () => {
+ const m = planner.matchIssueForEpisodeEdit(issues, seasonIdByNumber, { episodeNumber: 7 });
+ expect(m?.id).toBe('c');
+ });
+
+ it('matches on number alone when the named season does not resolve', () => {
+ const m = planner.matchIssueForEpisodeEdit(issues, seasonIdByNumber, { seasonNumber: 99, episodeNumber: 5 });
+ expect(m?.id).toBe('a'); // first issue with number 5
+ });
+});
+
+describe('arcPlanner — seasonIdByNumberOf (#1544)', () => {
+ it('indexes only integer-numbered seasons', () => {
+ const map = planner.seasonIdByNumberOf({
+ seasons: [
+ { id: 's1', number: 1 },
+ { id: 's2', number: 2 },
+ { id: 'bad', number: null },
+ { id: 'bad2' },
+ ],
+ });
+ expect([...map.entries()]).toEqual([[1, 's1'], [2, 's2']]);
+ });
+
+ it('returns an empty map for a seasonless series', () => {
+ expect(planner.seasonIdByNumberOf({}).size).toBe(0);
+ expect(planner.seasonIdByNumberOf(null).size).toBe(0);
+ });
+});
diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.js
index f92edf9eba..0f82cc6c3d 100644
--- a/server/services/pipeline/arcPlanner/arcCore.js
+++ b/server/services/pipeline/arcPlanner/arcCore.js
@@ -16,7 +16,7 @@ import { emitRecordUpdated, withReexportSuppressed } from '../../sharing/recordE
import { getSeason } from '../seasons.js';
import { READER_MAP_BEAT_KINDS, buildSeason, cleanThemes, renderArcShapeGuidance, renderArcShapePositionSummary, sanitizeArc, sanitizeReaderMap, sanitizeSeason, sanitizeSeasonList } from '../../../lib/storyArc.js';
import { runPromptRefineRaw, trimChanges } from '../refineHelpers.js';
-import { ERR_VALIDATION, SHAPE_GUIDANCE_NONE, appendTickingClock, buildArcBaseContext, buildArcOverviewContext, buildNeighborVolumes, buildReaderMapContext, buildResolveContext, buildVerifyContext, compareIssuesByPosition, makeErr, renderVolumeIssue, resolveWorldContext, shapeEpisodeResolutions, shapeFindings, shapeSeasonOutlines, shapeVerifyIssues } from './context.js';
+import { ERR_VALIDATION, SHAPE_GUIDANCE_NONE, appendTickingClock, buildArcBaseContext, buildArcOverviewContext, buildNeighborVolumes, buildReaderMapContext, buildResolveContext, buildVerifyContext, compareIssuesByPosition, makeErr, matchIssueForEpisodeEdit, renderVolumeIssue, resolveWorldContext, seasonIdByNumberOf, shapeEpisodeResolutions, shapeFindings, shapeSeasonOutlines, shapeVerifyIssues } from './context.js';
export async function generateArcOverview(seriesId, options = {}) {
const series = await getSeries(seriesId);
@@ -479,24 +479,13 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
export async function applyEpisodeResolutions(seriesId, series, episodes) {
if (!Array.isArray(episodes) || episodes.length === 0) return [];
const issues = await listIssues({ seriesId });
- const seasonIdByNumber = new Map(
- (series?.seasons || []).filter((s) => Number.isInteger(s?.number)).map((s) => [s.number, s.id]),
- );
+ const seasonIdByNumber = seasonIdByNumberOf(series);
const applied = [];
for (const edit of episodes) {
- const wantSeasonId = edit.seasonNumber != null ? seasonIdByNumber.get(edit.seasonNumber) : null;
- // Match an issue by series-global number. When the correction names a season
- // that resolved to a real season id, REQUIRE the issue to be in it — do NOT
- // fall back to a season-agnostic number match. The arc tree numbers episodes
- // series-globally, but if an LLM ever emits a per-season `episodeNumber`, a
- // bare-number fallback would silently rewrite the wrong season's issue (e.g.
- // global issue 5 when the model meant season 2 episode 5) and could clear its
- // beats. Failing safe to `no-match` (logged below) is the correct outcome for
- // a numbering-scheme mismatch. Only when no season is given (or it didn't
- // resolve) do we match on the globally-unique number alone.
- const issue = wantSeasonId
- ? issues.find((i) => i.number === edit.episodeNumber && i.seasonId === wantSeasonId)
- : issues.find((i) => i.number === edit.episodeNumber);
+ // Season match required when the named season resolves, else series-global
+ // number; fail-safe to no-match on a numbering-scheme mismatch (see
+ // matchIssueForEpisodeEdit). A bad match is logged below, never fatal.
+ const issue = matchIssueForEpisodeEdit(issues, seasonIdByNumber, edit);
if (!issue) {
// A correction we can't land is a silent path to non-convergence — log it
// so a number-scheme mismatch (per-season vs series-global) is diagnosable.
diff --git a/server/services/pipeline/arcPlanner/beatContinuity.js b/server/services/pipeline/arcPlanner/beatContinuity.js
index adb822f9a6..0b032f99e8 100644
--- a/server/services/pipeline/arcPlanner/beatContinuity.js
+++ b/server/services/pipeline/arcPlanner/beatContinuity.js
@@ -31,6 +31,8 @@ import { listIssues, updateStageWithLatest, TEXT_STAGE_IDS } from '../issues.js'
import {
buildBeatContinuityContext,
buildBeatContinuityResolveContext,
+ matchIssueForEpisodeEdit,
+ seasonIdByNumberOf,
shapeVerifyIssues,
shapeFindings,
shapeBeatResolutions,
@@ -157,18 +159,12 @@ export async function resolveBeatContinuity(seriesId, options = {}) {
export async function applyBeatResolutions(seriesId, series, episodes) {
if (!Array.isArray(episodes) || episodes.length === 0) return [];
const issues = await listIssues({ seriesId });
- const seasonIdByNumber = new Map(
- (series?.seasons || []).filter((s) => Number.isInteger(s?.number)).map((s) => [s.number, s.id]),
- );
+ const seasonIdByNumber = seasonIdByNumberOf(series);
const applied = [];
for (const edit of episodes) {
- const wantSeasonId = edit.seasonNumber != null ? seasonIdByNumber.get(edit.seasonNumber) : null;
- // Require the season match when a resolvable season was named — a bare
- // number fallback could rewrite the wrong season's issue (see the same
- // reasoning in applyEpisodeResolutions). Fail safe to `no-match`.
- const issue = wantSeasonId
- ? issues.find((i) => i.number === edit.episodeNumber && i.seasonId === wantSeasonId)
- : issues.find((i) => i.number === edit.episodeNumber);
+ // Season match required when a resolvable season was named, else
+ // series-global number; fail-safe to `no-match` (see matchIssueForEpisodeEdit).
+ const issue = matchIssueForEpisodeEdit(issues, seasonIdByNumber, edit);
if (!issue) {
console.log(`⚠️ beat-continuity: no issue matched beat correction (season ${edit.seasonNumber}, episode ${edit.episodeNumber})`);
applied.push({ seasonNumber: edit.seasonNumber, episodeNumber: edit.episodeNumber, skipped: 'no-match' });
diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.js
index a736937bfc..8e77f6fbf9 100644
--- a/server/services/pipeline/arcPlanner/context.js
+++ b/server/services/pipeline/arcPlanner/context.js
@@ -414,53 +414,65 @@ export async function buildReaderMapContext(series, preloadedWorld) {
* looked up via `listIssues` so the verify pass sees the *current* set, not
* a stale snapshot.
*/
-export async function buildVerifyContext(series, preloadedWorld) {
- const seasons = sanitizeSeasonList(series.seasons || []);
- const [issues, base, canon] = await Promise.all([
- listIssues({ seriesId: series.id }),
- buildArcBaseContext(series, preloadedWorld),
- getSeriesCanon(series),
- ]);
- // Group issues by seasonId so the tree's leaf order matches the seasons'
- // arcPosition order. Ungrouped issues land in a `null` bucket so the LLM
- // sees them too.
+// Group issues into the season→episode tree both verify passes feed the LLM.
+// Mechanically shared shape: issues bucket by `seasonId` (an `null` bucket for
+// ungrouped issues so the LLM still sees them), each bucket sorted by
+// arcPosition, then mapped onto the season list with an appended
+// `(ungrouped issues)` node. Callers supply the two things that diverge:
+// - `renderLeaf(iss)` — how each issue renders (synopsis-object vs. beats)
+// - `seasonFields(s)` — the per-season metadata (verify carries `status`,
+// the beat pass does not); `episodes` is always appended last so the JSON
+// key order matches the previous hand-rolled builders byte-for-byte.
+export function groupIssuesBySeasonTree(seasons, issues, { renderLeaf, seasonFields }) {
const issuesBySeason = new Map();
for (const iss of issues) {
const key = iss.seasonId || null;
if (!issuesBySeason.has(key)) issuesBySeason.set(key, []);
- // `synopsis` key (not `beats`) so it matches the prompt's existing
- // language; sourced from idea.input which carries the LLM's logline+synopsis.
- const synopsis = (iss.stages?.idea?.input || '').trim();
- issuesBySeason.get(key).push({
- number: iss.number,
- title: iss.title,
- status: iss.status,
- arcPosition: iss.arcPosition,
- synopsis: synopsis || null,
- });
+ issuesBySeason.get(key).push(iss);
}
for (const list of issuesBySeason.values()) {
list.sort(compareIssuesByPosition);
}
+ const renderBucket = (list) => list.map(renderLeaf);
const tree = seasons.map((s) => ({
- number: s.number,
- title: s.title,
- logline: s.logline,
- synopsis: s.synopsis,
- endingHook: s.endingHook,
- episodeCountTarget: s.episodeCountTarget,
- themes: s.themes,
- status: s.status,
- episodes: issuesBySeason.get(s.id) || [],
+ ...seasonFields(s),
+ episodes: renderBucket(issuesBySeason.get(s.id) || []),
}));
const ungrouped = issuesBySeason.get(null) || [];
if (ungrouped.length) {
- tree.push({
- number: null,
- title: '(ungrouped issues)',
- episodes: ungrouped,
- });
+ tree.push({ number: null, title: '(ungrouped issues)', episodes: renderBucket(ungrouped) });
}
+ return tree;
+}
+
+export async function buildVerifyContext(series, preloadedWorld) {
+ const seasons = sanitizeSeasonList(series.seasons || []);
+ const [issues, base, canon] = await Promise.all([
+ listIssues({ seriesId: series.id }),
+ buildArcBaseContext(series, preloadedWorld),
+ getSeriesCanon(series),
+ ]);
+ const tree = groupIssuesBySeasonTree(seasons, issues, {
+ // `synopsis` key (not `beats`) so it matches the prompt's existing
+ // language; sourced from idea.input which carries the LLM's logline+synopsis.
+ renderLeaf: (iss) => ({
+ number: iss.number,
+ title: iss.title,
+ status: iss.status,
+ arcPosition: iss.arcPosition,
+ synopsis: (iss.stages?.idea?.input || '').trim() || null,
+ }),
+ seasonFields: (s) => ({
+ number: s.number,
+ title: s.title,
+ logline: s.logline,
+ synopsis: s.synopsis,
+ endingHook: s.endingHook,
+ episodeCountTarget: s.episodeCountTarget,
+ themes: s.themes,
+ status: s.status,
+ }),
+ });
return {
...base,
seasonsTreeJson: JSON.stringify(tree, null, 2),
@@ -565,6 +577,31 @@ export function sliceSeasonForNeighbor(s) {
};
}
+// Build the season-number → seasonId lookup the episode-correction passes use
+// to disambiguate a correction that names a season. Only integer-numbered
+// seasons are indexed (a malformed season can't be a resolution target).
+export const seasonIdByNumberOf = (series) => new Map(
+ (series?.seasons || []).filter((s) => Number.isInteger(s?.number)).map((s) => [s.number, s.id]),
+);
+
+// Match the issue an episode-level correction targets. The arc tree numbers
+// episodes series-globally, but when a correction names a season that resolved
+// to a real season id we REQUIRE the issue to be in it — we do NOT fall back to
+// a season-agnostic number match, because if an LLM ever emits a per-season
+// `episodeNumber` a bare-number fallback would silently rewrite the wrong
+// season's issue (e.g. global issue 5 when the model meant season 2 episode 5).
+// Failing safe to no-match (the caller logs it) is the correct outcome for a
+// numbering-scheme mismatch. Only when no season is given (or it didn't resolve)
+// do we match on the globally-unique number alone. Returns the issue or
+// undefined. Shared by applyEpisodeResolutions (arc-resolve) and
+// applyBeatResolutions (beat-continuity).
+export function matchIssueForEpisodeEdit(issues, seasonIdByNumber, edit) {
+ const wantSeasonId = edit.seasonNumber != null ? seasonIdByNumber.get(edit.seasonNumber) : null;
+ return wantSeasonId
+ ? issues.find((i) => i.number === edit.episodeNumber && i.seasonId === wantSeasonId)
+ : issues.find((i) => i.number === edit.episodeNumber);
+}
+
export async function buildResolveContext(series, findings, preloadedWorld) {
const ctx = await buildVerifyContext(series, preloadedWorld);
const structure = recommendStructure(series.issueCountTarget);
@@ -604,35 +641,22 @@ async function buildBeatTree(series, preloadedWorld) {
buildArcBaseContext(series, preloadedWorld),
getSeriesCanon(series),
]);
- const issuesBySeason = new Map();
- for (const iss of issues) {
- const key = iss.seasonId || null;
- if (!issuesBySeason.has(key)) issuesBySeason.set(key, []);
- issuesBySeason.get(key).push(iss);
- }
- let beatBearing = 0;
- const renderList = (list) => list
- .slice()
- .sort(compareIssuesByPosition)
- .map((iss) => {
- const leaf = renderVolumeIssue(iss);
- if (leaf.beats) beatBearing += 1;
- return leaf;
- });
- const tree = seasons.map((s) => ({
- number: s.number,
- title: s.title,
- logline: s.logline,
- synopsis: s.synopsis,
- endingHook: s.endingHook,
- episodeCountTarget: s.episodeCountTarget,
- themes: s.themes,
- episodes: renderList(issuesBySeason.get(s.id) || []),
- }));
- const ungrouped = issuesBySeason.get(null) || [];
- if (ungrouped.length) {
- tree.push({ number: null, title: '(ungrouped issues)', episodes: renderList(ungrouped) });
- }
+ const tree = groupIssuesBySeasonTree(seasons, issues, {
+ renderLeaf: renderVolumeIssue,
+ seasonFields: (s) => ({
+ number: s.number,
+ title: s.title,
+ logline: s.logline,
+ synopsis: s.synopsis,
+ endingHook: s.endingHook,
+ episodeCountTarget: s.episodeCountTarget,
+ themes: s.themes,
+ }),
+ });
+ // Report how many issues actually carry beats, so the conductor/prompt can
+ // tell a real beat corpus from a synopsis-only one. Counted from the built
+ // tree — every leaf with `.beats` came through renderVolumeIssue's beats branch.
+ const beatBearing = tree.reduce((n, s) => n + s.episodes.filter((e) => e.beats).length, 0);
return { base, canon, tree, beatBearing };
}