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
fix: keep post-arc transitions structure-owned
[._.]/ Adam Eivye0bc2643216a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 489de5e900..1dbacfbdd2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -57,6 +57,7 @@## Fixed- **A note that iCloud wrongly reports as "not downloaded" can now be saved anyway.** The write guard screens for an offloaded note by looking for a real byte length with no local blocks — a shape an ordinary sparse or compressed file also has. When that misfired the lockout was permanent: asking iCloud to download an already-local file succeeds instantly and changes nothing, so every save was refused forever while the message told the user to try again shortly. The server now checks whether the download both succeeded and actually moved the file, so it can tell a download still in flight (or one that failed) from a refusal that will never clear — and only the second of those, twice in a row on the same note, offers the Brain Notes and Wiki editors a deliberate "Save anyway" row that writes it regardless. While a download really is in flight you still just wait, and the ordinary Save button, ⌘S, and background mirrors always refuse, so nothing bypasses the guard without an explicit click. The message no longer says to try again shortly when trying again cannot help.+- **Post-arc character repair no longer invents plot events that the episode plan never stages.** Character reconciliation could improve a supporting cast member by adding new early `atIssue` transitions, then the next foundation verdict correctly penalized structure because those characters were absent from the corresponding synopses. Existing transition beats are now read-only after the macro arc exists: character repair may deepen motivation, arc type, and start/end states, while the structure editor exclusively owns adding or moving dramatized events. Pre-arc character-first planning still authors provisional transitions normally.- **Complete LLM answers no longer fail on recoverable JSON serialization mistakes.** Long foundation calls could begin as normal JSON, then emit the complete remaining objects as escaped `\\n` / `\\"` text, leave quotation marks inside prose unescaped, or omit a prose field's closing quote immediately before its structural `}` line. The shared parser now decodes an escaped tail only from the JSON parser's exact failure position, repairs quotes only at structurally unambiguous boundaries, and accepts repairs only when the entire reconstructed response parses—preserving expensive completed work without making partial or arbitrary text look valid.diff --git a/data.reference/prompts/stages/pipeline-character-foundation.md b/data.reference/prompts/stages/pipeline-character-foundation.mdindex cb4966cf4a..9fdc0f966c 100644--- a/data.reference/prompts/stages/pipeline-character-foundation.md+++ b/data.reference/prompts/stages/pipeline-character-foundation.md@@ -7,7 +7,7 @@ You are the senior character architect for a long-form series. Build the human e{{phase}}- In **pre-arc character foundation**, the plot spine does not exist yet. Establish characters whose Ghost → Wound → Lie → Want → Need chains create unavoidable choices and relationship tensions. Do not pre-write an arbitrary sequence of events and retrofit people to it.-- In **post-arc reconciliation**, preserve the established character foundation. Change an existing character only where the planned story genuinely tests or transforms them. Add a character only when the arc already requires a story function the current ensemble cannot carry.+- In **post-arc reconciliation**, preserve the established character foundation. Change an existing character only where the planned story genuinely tests or transforms them. Add a character only when the arc already requires a story function the current ensemble cannot carry. The synopsis-level plan owns event placement: preserve every existing transition beat exactly, and do not add, move, or rewrite an `atIssue` event. If the requested character change needs a scene the plan does not yet contain, deepen the Want / Need / start / end state without inventing that scene; the structure editor will stage it separately.## Editorial finding@@ -43,6 +43,7 @@ You are the senior character architect for a long-form series. Build the human e- Give each target character distinct values, contradictions, motivation, speech rhythm, secrets, and relationships that exert pressure in both directions.- Return every supplied target whose framework is incomplete or whose existing engine needs the requested editorial repair. Never silently omit a target merely because the batch is large; later batches handle the rest of the roster.- A provisional character arc describes choices and state changes, not moods. Place transitions at concrete issue numbers within the series target when one is known.+- During post-arc reconciliation, the supplied transition list is read-only evidence of what the plan already dramatizes. Never manufacture an early appearance, disclosure, refusal, or relationship turn to justify a character revision.- `newCharacters` is additive and capped at three. Use it only for a missing protagonist/foil/intimate/mentor role before the arc, or a named story function the current arc truly requires afterward. Never return a replacement or near-duplicate of an existing character.- Return only target existing characters whose framework materially improves. Never delete a character or character arc.- Character arc types: `positive|negative|flat`. Transition kinds: `decision|realization|point-of-no-return|relapse|sacrifice`.diff --git a/scripts/migrations/240-character-foundation-exhaustive-cast.js b/scripts/migrations/240-character-foundation-exhaustive-cast.jsindex 8e62f0c119..d36c954413 100644--- a/scripts/migrations/240-character-foundation-exhaustive-cast.js+++ b/scripts/migrations/240-character-foundation-exhaustive-cast.js@@ -15,7 +15,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-character-foundation.md': 'cda34127b40754ddbcc8544e3d82572b',+ 'pipeline-character-foundation.md': 'd6c449c06de73a0868141c899b26e52c',};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/243-post-arc-character-transition-ownership.js b/scripts/migrations/243-post-arc-character-transition-ownership.jsnew file mode 100644index 0000000000..b870416280--- /dev/null+++ b/scripts/migrations/243-post-arc-character-transition-ownership.js@@ -0,0 +1,31 @@+/**+ * Keep post-arc character repair from inventing unstaged plot events.+ *+ * The character editor may deepen a planned person's motivation and ending,+ * but episode-numbered transition beats belong to the structure editor once a+ * macro arc exists. Hash replacement upgrades only the prior shipped prompt;+ * customized installs remain untouched and receive a manual-upgrade hint.+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'pipeline-character-foundation.md': ['cda34127b40754ddbcc8544e3d82572b'],+};++export const NEW_SHIPPED_MD5 = {+ 'pipeline-character-foundation.md': 'd6c449c06de73a0868141c899b26e52c',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'post-arc character transition ownership',+ customizedHint: (filename) =>+ ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` ++ ` against data/prompts/stages/${filename} and keep transition beats read-only\n` ++ ' during post-arc character reconciliation.',+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/243-post-arc-character-transition-ownership.test.js b/scripts/migrations/243-post-arc-character-transition-ownership.test.jsnew file mode 100644index 0000000000..7ab22eaa1e--- /dev/null+++ b/scripts/migrations/243-post-arc-character-transition-ownership.test.js@@ -0,0 +1,31 @@+import { readFileSync } from 'fs';+import { describe, expect, it } from 'vitest';++import { repoRoot, runPromptMigrationTests } from './_testHelpers.js';+import migration, {+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ applyMigration,+} from './243-post-arc-character-transition-ownership.js';++const FILENAME = 'pipeline-character-foundation.md';++describe('migration 243 — post-arc character transition ownership', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-243-character-transition-ownership-',+ });++ it('keeps episode-numbered transition beats owned by structure after the arc exists', () => {+ const body = readFileSync(+ `${repoRoot}/data.reference/prompts/stages/${FILENAME}`,+ 'utf8',+ );+ expect(body).toContain('The synopsis-level plan owns event placement');+ expect(body).toContain('preserve every existing transition beat exactly');+ expect(body).toContain('the supplied transition list is read-only evidence');+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex 44b9e53ed1..e3ea9c4108 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -50,7 +50,7 @@ const EXPECTED_STAGE_OLD = {'cd-treatment.md': ['2ffa482e7bfb6fe8b7224505fedbf712', '16d0ef6a7fd2533719a846019122ebee', '95b7685690ecfee4f682b0293b790277'],'cd-plan.md': ['3ce871196a8fd04781b71b6780e89c86', '0768d6809645c2c1fe73cacae9740fe9'],'pipeline-series-generate.md': ['bc72731124a2bd6304362f4402c6305d'],- 'pipeline-character-foundation.md': ['f1c0b75a8161c0bc7f26752d148a5c1c'],+ 'pipeline-character-foundation.md': ['f1c0b75a8161c0bc7f26752d148a5c1c', 'cda34127b40754ddbcc8544e3d82572b'],'pipeline-judge-foundation.md': ['74c0244e641dcf7a73e9c83123ebdee9'],};const EXPECTED_STAGE_NEW = {@@ -80,7 +80,7 @@ const EXPECTED_STAGE_NEW = {'cd-treatment.md': 'd940eadfb406ce584f0e244032f33382','cd-plan.md': 'ef0d96f6ebde43af6c4579969d31cfb7','pipeline-series-generate.md': '21352c21ed6d4edb7a4b7c32704eff55',- 'pipeline-character-foundation.md': 'cda34127b40754ddbcc8544e3d82572b',+ 'pipeline-character-foundation.md': 'd6c449c06de73a0868141c899b26e52c','pipeline-judge-foundation.md': '4c0bd349ff4d329048c9f4ac068745d4',};const EXPECTED_PARTIAL_OLD = {diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex 545ca94e85..9e9974e290 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -948,12 +948,32 @@ async function repairCharacters(series, issues, universe, finding, options) {let arcsApplied = false;if (proposedArcs.length > 0) {const latestSeries = await getSeries(series.id);+ const existingArcByKey = new Map((latestSeries.characterArcs || []).flatMap((arc) => [+ arc?.characterId ? [arc.characterId, arc] : null,+ arc?.characterName ? [`name:${arc.characterName.trim().toLowerCase()}`, arc] : null,+ ].filter(Boolean)));+ // Character repairs after the macro arc may deepen motivation, arc type,+ // and start/end states, but transition beats are plot events. Letting this+ // editor add or move them silently creates an arc-ledger event that no+ // episode synopsis stages; the next judge then (correctly) penalizes the+ // structure for a contradiction the previous repair just invented. Keep+ // existing authored transitions unchanged in post-arc reconciliation and leave+ // missing scene placement to the structure owner (`resolveVerifyIssues`).+ const boundedProposedArcs = options.phase === 'post-arc reconciliation'+ ? proposedArcs.map((arc) => {+ const existing = existingArcByKey.get(arc.characterId)+ || existingArcByKey.get(`name:${String(arc.characterName || '').trim().toLowerCase()}`);+ return existing+ ? { ...arc, transitions: Array.isArray(existing.transitions) ? existing.transitions : [] }+ : arc;+ })+ : proposedArcs;// A legacy name-only arc and a newly canon-linked arc otherwise have// different sanitizer keys and survive as duplicates. Remove every prior// identity the proposal replaces, then rely on last-write-wins within the// proposal itself. This preserves untouched arcs while upgrading the// authored character to its stable canon id.- const replacementKeys = new Set(proposedArcs.flatMap((arc) => [+ const replacementKeys = new Set(boundedProposedArcs.flatMap((arc) => [arc.characterId || '',arc.characterName ? `name:${arc.characterName.trim().toLowerCase()}` : '',]).filter(Boolean));@@ -961,7 +981,7 @@ async function repairCharacters(series, issues, universe, finding, options) {!replacementKeys.has(arc?.characterId || '')&& !replacementKeys.has(arc?.characterName ? `name:${arc.characterName.trim().toLowerCase()}` : '')));- const mergedArcs = sanitizeCharacterArcList([...untouchedArcs, ...proposedArcs]);+ const mergedArcs = sanitizeCharacterArcList([...untouchedArcs, ...boundedProposedArcs]);if (JSON.stringify(mergedArcs) !== JSON.stringify(latestSeries.characterArcs || [])) {await updateSeries(series.id, { characterArcs: mergedArcs });arcsApplied = true;diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.jsindex 42370e3073..9fd429dcb1 100644--- a/server/services/pipeline/foundationJudge.test.js+++ b/server/services/pipeline/foundationJudge.test.js@@ -540,6 +540,46 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()expect(r).toMatchObject({ dimension: 'character', applied: true, characterArcsUpdated: true });});+ it('keeps existing transition beats structure-owned during post-arc character repair', async () => {+ const existingTransition = { kind: 'decision', atIssue: 6, label: 'refuses the unsupported shortcut' };+ const series = {+ id: 'ser-1', name: 'S', premise: 'P', universeId: 'uni-1',+ characterArcs: [{+ characterId: 'chr-1', characterName: 'Example Listener', want: 'Prove the protocol',+ need: 'Accept uncertainty', startState: 'certain', endState: 'careful',+ transitions: [existingTransition], status: 'draft',+ }],+ };+ const universe = { id: 'uni-1', characters: [{ id: 'chr-1', name: 'Example Listener' }] };+ seriesSvc.getSeries.mockResolvedValue(series);+ universeBuilder.getUniverse.mockResolvedValue(universe);+ universeBuilder.updateUniverse.mockImplementation(async (id, mutator) => ({ id, ...(mutator(universe) || {}) }));+ stageRunner.runStagedLLM.mockResolvedValue({ content: {+ characters: [{+ id: 'chr-1', name: 'Example Listener', ghost: 'A failed test', wound: 'Fears ambiguity',+ lie: 'One protocol can prove innocence', want: 'Prove the protocol', need: 'Accept uncertainty',+ coreTheme: 'restraint without innocence', motivations: 'Protect workers and avoid blame',+ speechPattern: 'measured sensory clauses', arcType: 'flat', secrets: ['Cannot hear the upper band'],+ }],+ characterArcs: [{+ characterId: 'chr-1', characterName: 'Example Listener', want: 'Prove the protocol',+ need: 'Accept uncertainty', startState: 'certain', endState: 'still opposed to the lead',+ transitions: [{ kind: 'decision', atIssue: 2, label: 'new unsupported early appearance' }],+ status: 'draft',+ }],+ } });++ await applyFoundationFix('ser-1', 'character', {+ finding: { gap: 'too agreeable', fix: 'retain a principled opponent' },+ });++ const patch = seriesSvc.updateSeries.mock.calls.at(-1)[1];+ expect(patch.characterArcs[0]).toMatchObject({ endState: 'still opposed to the lead' });+ expect(patch.characterArcs[0].transitions).toEqual([+ expect.objectContaining(existingTransition),+ ]);+ });+it('repairs a large referenced cast through exhaustive sequential batches', async () => {const characters = Array.from({ length: 8 }, (_, index) => ({id: `chr-${index + 1}`,@@ -643,6 +683,9 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()expect(stageRunner.runStagedLLM).toHaveBeenCalledWith('pipeline-character-foundation', expect.objectContaining({phase: 'pre-arc character foundation',}), expect.objectContaining({ providerDefault: 'codex', modelDefault: 'gpt-x', effortDefault: 'high' }));+ expect(seriesSvc.updateSeries.mock.calls.at(-1)[1].characterArcs[0].transitions).toEqual([+ expect.objectContaining({ kind: 'decision', atIssue: 2, label: 'asks for help' }),+ ]);});it('routes worldbuilding → expandWorldTemplate + a lock-aware updateUniverse write', async () => {