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(pipeline): honor series LLM override on prose; TUI returns clean output via response file (#263)
[._.]/ Adam Eivy3f193888372f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e69f983dd0..b8fcaeb0ff 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -5,7 +5,9 @@- **Universe canon now lives inside Universe Builder.** Characters, places, and objects are managed inline on the universe page — no separate canon page to navigate to. The old canon URL still works as a redirect, and the Series Pipeline link lands you on the same combined view. Pending edits to other universe fields are no longer lost when canon changes are saved.- **Locking a canon entry now also blocks new reference renders.** Locked characters/places/objects already prevented AI rewrites; they now prevent new reference and clean-plate image renders too, so a locked entry's identity stays frozen across both text and visuals. Disabled buttons explain the lock in their tooltips.- **Universe Builder categories now carry a canon trunk (`kind`)** so each bucket knows whether it belongs under Cast, Places, Objects, or Other. Built-in defaults are pre-tagged (landscapes/environments/structures → Places, vehicles → Objects); custom buckets default to Other until you sort them. The default `characters` category was retired — canon owns characters now, and any pre-existing character variations get folded into universe canon on upgrade. Foundation for the upcoming tabbed-trunk Universe Builder redesign.+- **TUI providers now return clean responses via a per-run output file.** Claude Code TUI / Codex TUI runs are now instructed to write their final response to `data/runs/<runId>/tui-response.txt`, which the runner reads back instead of scraping the PTY screen — no more banner art, "5% cost" meters, or "bypass permissions on" hints leaking into stage outputs. Falls back to the existing screen-scrape cleanup when the file isn't written.## Fixed- **Volume cover-concept generation no longer 500s on upgraded installs.** The per-season "generate volume cover concepts" LLM step was shipped with its prompt template but missing from `stage-config.json`, so existing installs hit `Stage pipeline-volume-cover-concepts not found`. Added the config entry and a migration that seeds both the template and the config on next launch — fresh installs were already fine.+- **Pipeline prose stage now honors the per-series provider/model override.** "Draft prose" was dropping the series LLM override and falling back to the default provider — fixed; the override (e.g. Codex on a series-by-series basis) is now respected on the prose stage the same way it already was on idea, comic script, and teleplay.diff --git a/PLAN.md b/PLAN.mdindex 242992d5e4..1386495740 100644--- a/PLAN.md+++ b/PLAN.md@@ -124,6 +124,8 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]- [ ] **Extract shared task block + review-loop section in `agentPromptBuilder.js`.** The light path (`buildLightContextPrompt` ~line 510) and full path (`buildAgentPrompt` fallback ~line 425) now emit nearly identical task blocks (`description` + optional `**Target App**:` + optional `**Screenshots**:`). The review-loop follow-up section is duplicated between the full-context block (~line 312-343) and the light-context block (~line 575-602) — same 7-step loop, same `gh pr merge --squash --delete-branch` command, same `gh pr view --json state` verification, same "10 iterations" hard stop. The auto-merge bug fix (PR removing `--auto`) had to be applied in both places. Extract `buildTaskBlock(task, { screenshotsAsList })` + `buildReviewLoopFollowUpSection(metadata, { verbose })` so the next sync edit doesn't drift.- [ ] **Flatten the giant `isReadOnly ? … : isTui ? … : worktreeInfo && willOpenPR ? …` ternary in `agentPromptBuilder.js` Guidelines bullet (~line 458).** Pre-existing 4-branch one-liner that covers readOnly/TUI/worktree+PR/worktree-only/default-empty. Extract a `buildCompletionGuidelineBullet({ isReadOnly, isTui, tuiCompletionCommand, worktreeInfo, willOpenPR, willReviewLoop })` helper mirroring the pattern the light path already uses (`worktreeCommitGuidance`, `buildTuiCompletionSection`). Returns string or `null`.- [ ] **Test the untested `worktreeCommitGuidance` branches in `agentPromptBuilder.js`.** Five-branch decision tree at ~line 617; tests don't cover `isWorktreeOnExistingBranch=true` or `hasSlashdo && !willOpenPR`.+- [ ] **Extract a `tryReadFile(path, encoding='utf8')` helper into `server/lib/fileUtils.js`.** The `readFile(path).catch(() => null)` pattern is inlined 15+ times across the codebase (`server/routes/apps.js:38` `safeReadJson`, `server/lib/fileUtils.js:505`, `server/lib/hfToken.js:16`, `server/services/agentDrafts.js:22`, `server/services/messageAccounts.js:10`, `server/services/missions.js:35`, `server/lib/tuiPromptRunner.js` new at line ~202, etc.). One helper + migrate; small win, prevents future drift. Defer until next infra pass.+- [ ] **Skip the `text` accumulator in `promptRunner.runPromptThroughProvider` for TUI providers.** `APPEND_CHUNK(acc, chunk)` runs per stream chunk regardless of provider type, but the TUI branch (post `fix-prose-stage-override`) discards the accumulated `text` and uses `result.text` from `executeTuiRun` instead. Streams can hit hundreds of KB of screen redraws per run — gate the accumulator on `effectiveProvider.type !== 'tui'` in `onData` to skip the per-chunk string concat. Pre-existing buffer cap on `outputBuffer` inside `executeTuiRun` already bounds memory; this is a CPU/alloc micro-opt, not a correctness fix.### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)diff --git a/client/src/components/pipeline/stages/ProseStage.jsx b/client/src/components/pipeline/stages/ProseStage.jsxindex c97fd431cd..005386dc8c 100644--- a/client/src/components/pipeline/stages/ProseStage.jsx+++ b/client/src/components/pipeline/stages/ProseStage.jsx@@ -2,12 +2,11 @@ import TextStagePanel from './TextStagePanel';// Bibles extraction lives on the Nouns stage now — kept the prose panel a// thin pass-through so the workflow is Idea → Prose → Nouns → Comic.-export default function ProseStage({ issue, onStageUpdate }) {+export default function ProseStage(props) {return (<TextStagePanel- issue={issue}+ {...props}stageId="prose"- onStageUpdate={onStageUpdate}generateLabel="Draft prose"outputPlaceholder="An 800–1500 word short-story draft for this issue. Will be lightly structured with `## Scene N — Slugline` H2 markers so the comic and teleplay stages have stable anchors."/>diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.jsindex 21ed4c4eb9..5e6128e1bd 100644--- a/server/lib/promptRunner.js+++ b/server/lib/promptRunner.js@@ -27,7 +27,7 @@*/import { createRun, executeApiRun, executeCliRun, extractBakedModel, hasModelFlag, stopRun, patchRunMetadata } from '../services/runner.js';-import { executeTuiRun, cleanTuiResponse } from './tuiPromptRunner.js';+import { executeTuiRun } from './tuiPromptRunner.js';const DEFAULT_TIMEOUT_MS = 300000;const APPEND_CHUNK = (acc, chunk) => acc + (typeof chunk === 'string' ? chunk : (chunk?.text || ''));@@ -215,11 +215,14 @@ export async function runPromptThroughProvider({ provider, prompt, source, modelif (result?.error || result?.success === false) {safeReject(new Error(result?.error || `${labelByType[effectiveProvider.type] || effectiveProvider.type} execution failed`));} else {- // TUI buffers contain the pasted prompt echo + UI chrome — clean- // before resolving so callers see roughly the same shape they- // get from a CLI run (model response text, possibly with noise).- const cleaned = effectiveProvider.type === 'tui' ? cleanTuiResponse(text, prompt) : text;- safeResolve({ text: cleaned, runId, model: effectiveModel });+ // TUI runs do their own cleanup inside executeTuiRun (preferring+ // the response file the model was directed to write, falling back+ // to cleanTuiResponse on the screen scrape). Trust `result.text`+ // — the accumulated `text` here is the raw chrome-laden stream.+ const finalText = effectiveProvider.type === 'tui'+ ? (typeof result?.text === 'string' ? result.text : '')+ : text;+ safeResolve({ text: finalText, runId, model: effectiveModel });}};diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.jsindex 497d08c605..563e02d746 100644--- a/server/lib/promptRunner.test.js+++ b/server/lib/promptRunner.test.js@@ -14,11 +14,12 @@ vi.mock('../services/runner.js', () => ({// TUI runner is in lib (different module from services/runner.js) — mock it// here so the central handler's tui branch is testable without spawning a-// real PTY. cleanTuiResponse is mocked to a passthrough so tests can assert-// on the raw streamed text without worrying about the prompt-echo strip.+// real PTY. executeTuiRun is responsible for its own response cleanup+// (file-write directive + screen-scrape fallback), so the central handler+// just forwards result.text. Tests drive the cleaned text directly via the+// mock's onComplete payload.vi.mock('./tuiPromptRunner.js', () => ({executeTuiRun: vi.fn(),- cleanTuiResponse: vi.fn((text) => text),}));const runner = await import('../services/runner.js');@@ -41,11 +42,10 @@ beforeEach(() => {// vi.clearAllMocks() clears calls but NOT mockReturnValue overrides,// so the default implementations set in vi.mock() above don't auto-reset// between tests. Re-apply the defaults that individual tests override- // (hasModelFlag, extractBakedModel, cleanTuiResponse) so a leak-over- // value can't poison the next test's resolveEffectiveModel run.+ // (hasModelFlag, extractBakedModel) so a leak-over value can't poison+ // the next test's resolveEffectiveModel run.runner.hasModelFlag.mockReturnValue(false);runner.extractBakedModel.mockReturnValue(null);- tuiRunner.cleanTuiResponse.mockImplementation((text) => text);});describe('promptRunner — happy paths', () => {@@ -401,12 +401,11 @@ describe('promptRunner — multi-chunk text accumulation', () => {// =============================================================================describe('promptRunner — TUI provider routing', () => {- it('routes TUI providers through executeTuiRun, accumulates stripped text, resolves { text, runId, model }', async () => {+ it('routes TUI providers through executeTuiRun and resolves with result.text', async () => {tuiRunner.executeTuiRun.mockImplementation(async (id, _p, _pr, _cwd, onData, onComplete, _t) => {- onData('once ');- onData('upon ');- onData('a time');- onComplete({ success: true, exitCode: 0 });+ onData('chrome chunk ');+ onData('more chrome');+ onComplete({ success: true, exitCode: 0, text: 'once upon a time' });});const out = await runPromptThroughProvider({@@ -439,20 +438,32 @@ describe('promptRunner — TUI provider routing', () => {expect(args[6]).toBe(60000); // timeout positional arg});- it('runs cleanTuiResponse on the accumulated text before resolving', async () => {+ it('returns result.text from executeTuiRun (which owns its own response cleanup)', async () => {tuiRunner.executeTuiRun.mockImplementation(async (id, _p, _pr, _cwd, onData, onComplete, _t) => {onData('raw with chrome');+ onComplete({ success: true, text: 'cleaned response from file' });+ });++ const out = await runPromptThroughProvider({+ provider: tuiProvider(),+ prompt: 'p', source: 't',+ });++ expect(out.text).toBe('cleaned response from file');+ });++ it('falls back to empty string when executeTuiRun omits result.text', async () => {+ tuiRunner.executeTuiRun.mockImplementation(async (id, _p, _pr, _cwd, onData, onComplete, _t) => {+ onData('streamed chrome');onComplete({ success: true });});- tuiRunner.cleanTuiResponse.mockReturnValueOnce('cleaned');const out = await runPromptThroughProvider({provider: tuiProvider(),prompt: 'p', source: 't',});- expect(tuiRunner.cleanTuiResponse).toHaveBeenCalledWith('raw with chrome', 'p');- expect(out.text).toBe('cleaned');+ expect(out.text).toBe('');});it('rejects with TUI-labeled error when executeTuiRun fires onComplete with success: false', async () => {diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex 4f89865502..2867b2f660 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -26,7 +26,8 @@*/import { spawn as ptySpawn } from 'node-pty';-import { join } from 'path';+import { readFile } from 'fs/promises';+import { join, resolve } from 'path';import { ensureDir, PATHS } from './fileUtils.js';import { createStreamingAnsiStripper } from './ansiStrip.js';import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun } from '../services/runner.js';@@ -108,7 +109,31 @@ export async function executeTuiRun(runId, provider, prompt, cwd, onData, onCompconst runDir = join(getRunsPath(), runId);await ensureDir(runDir);- console.log(`📟 Executing TUI: ${command} ${args.join(' ')} (${prompt.length} chars via paste)`);+ // TUI screens redraw their banner, input chrome, and status bar on every+ // keystroke — scraping the PTY stream for the model's reply is+ // fundamentally lossy (box-drawing chars, "5%" cost meters, "bypass+ // permissions on" hints, etc. all bleed into the captured text). Ask the+ // model to write its final response to a file we'll read back instead.+ //+ // `resolve()` is load-bearing: `runnerConfig.dataDir` defaults to the+ // relative `'./data'`, and the TUI's cwd (`workingDir`) is frequently a+ // different directory (universe/loop workspaces, target-app paths). A+ // relative path embedded in the prompt would tell the LLM to write into+ // its own cwd while the server reads from process.cwd() — different+ // files, fallback every time.+ const responseFilePath = resolve(runDir, 'tui-response.txt');+ const wrappedPrompt = `IMPORTANT — Output to file:+When you have completed the task below, write your COMPLETE final response (and nothing else — no commentary, preamble, or wrapper text) to this exact absolute path using your file-writing tool:++ ${responseFilePath}++Only the contents of that file will be used as your response, so do not print the response inline. Once the file is written, you can finish.++----- TASK -----++${prompt}`;++ console.log(`📟 Executing TUI: ${command} ${args.join(' ')} (${wrappedPrompt.length} chars via paste, response→${responseFilePath})`);// CLAUDECODE is set when PortOS itself runs inside Claude Code; passing it// through to a spawned Claude Code TUI would make the child think it's@@ -177,14 +202,22 @@ export async function executeTuiRun(runId, provider, prompt, cwd, onData, onComp// behind for the user to interact with.try { if (ptyProcess && !ptyProcess.killed) ptyProcess.kill(); } catch { /* already gone */ }+ // Prefer the response file the TUI was directed to write; fall back+ // to the ANSI-stripped screen scrape when the file is missing/empty+ // or the run didn't succeed. Logic lives in `resolveTuiResponseText`+ // so it can be unit-tested without a live PTY.+ const { text: responseText, usedResponseFile } = await resolveTuiResponseText({+ success, responseFilePath, outputBuffer, wrappedPrompt,+ });+// Delegate run-record finalization (output.txt + metadata.json merge// + onRunCompleted/onRunFailed hooks + toolkit error analysis) to the// shared runner helper. `completionReason` lands in `extras` so it// gets persisted to metadata.json BEFORE the write (was previously// set post-write and never made it to disk → /runs replay missed it).const metadata = await finalizeRunRecord({- runId, output: outputBuffer, exitCode, success, error, startTime,- extras: { completionReason: reason },+ runId, output: responseText, exitCode, success, error, startTime,+ extras: { completionReason: reason, usedResponseFile },}).catch((err) => {console.error(`❌ TUI run ${runId} finalize failed: ${err.message}`);return {@@ -192,7 +225,7 @@ export async function executeTuiRun(runId, provider, prompt, cwd, onData, onCompduration: Date.now() - startTime, completionReason: reason,};});- onComplete?.(metadata);+ onComplete?.({ ...metadata, text: responseText, usedResponseFile });resolve();};@@ -272,7 +305,7 @@ export async function executeTuiRun(runId, provider, prompt, cwd, onData, onComppromptSentAt = Date.now();const rawLenBeforePaste = rawBuffer.length;try {- ptyProcess.write(`\x1b[200~${prompt}\x1b[201~`);+ ptyProcess.write(`\x1b[200~${wrappedPrompt}\x1b[201~`);} catch (err) {finish({ success: false, exitCode: 1, error: `Failed to write prompt: ${err.message}`, reason: 'write-failed' });return;@@ -348,6 +381,27 @@ export async function executeTuiRun(runId, provider, prompt, cwd, onData, onComp* `outputBuffer` is already clean). Don't strip again — it's a wasted scan* over up to 1MB of text.*/+/**+ * Pick the TUI response text — preferring the file the model was directed+ * to write, falling back to the cleaned screen scrape.+ *+ * Returns `{ text, usedResponseFile }`. `usedResponseFile` is true when the+ * file existed and had non-empty trimmed content; false in every other+ * case (file missing, empty, whitespace-only, or run did not succeed).+ *+ * Extracted out of `executeTuiRun.finish` so the file-read + fallback+ * decision is testable without spawning a PTY.+ */+export async function resolveTuiResponseText({ success, responseFilePath, outputBuffer, wrappedPrompt }) {+ if (success) {+ const fileText = await readFile(responseFilePath, 'utf8').catch(() => null);+ if (typeof fileText === 'string' && fileText.trim()) {+ return { text: fileText.trim(), usedResponseFile: true };+ }+ }+ return { text: cleanTuiResponse(outputBuffer, wrappedPrompt), usedResponseFile: false };+}+export function cleanTuiResponse(strippedText, prompt) {if (typeof strippedText !== 'string' || !strippedText) return '';let text = strippedText.replace(/\[Pasted text #\d+[^\]]*\]/g, '');diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.jsindex 3183f915d3..6285701afe 100644--- a/server/lib/tuiPromptRunner.test.js+++ b/server/lib/tuiPromptRunner.test.js@@ -1,5 +1,8 @@-import { describe, it, expect } from 'vitest';-import { cleanTuiResponse } from './tuiPromptRunner.js';+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { cleanTuiResponse, resolveTuiResponseText } from './tuiPromptRunner.js';// Targeted coverage for the cleanTuiResponse helper — it shapes what every// TUI-provider caller sees as the model response (paste-marker removal,@@ -88,3 +91,90 @@ describe('cleanTuiResponse', () => {});});});++// resolveTuiResponseText is the file-or-fallback chooser called from+// executeTuiRun.finish. The PTY path is irreplicable in a unit test, so the+// helper was extracted to make this decision (which is the actual new+// behavior of the PR) testable in isolation.++describe('resolveTuiResponseText', () => {+ let tmpDir;+ let responseFilePath;++ beforeEach(async () => {+ tmpDir = await mkdtemp(join(tmpdir(), 'tui-response-test-'));+ responseFilePath = join(tmpDir, 'tui-response.txt');+ });+ afterEach(async () => {+ await rm(tmpDir, { recursive: true, force: true }).catch(() => null);+ });++ it('returns the response file contents trimmed and flags usedResponseFile=true on success', async () => {+ await writeFile(responseFilePath, '\n the prose body \n');+ const out = await resolveTuiResponseText({+ success: true,+ responseFilePath,+ outputBuffer: 'screen chrome',+ wrappedPrompt: 'wrapped',+ });+ expect(out).toEqual({ text: 'the prose body', usedResponseFile: true });+ });++ it('falls back to cleanTuiResponse(outputBuffer) when the file does not exist', async () => {+ const out = await resolveTuiResponseText({+ success: true,+ responseFilePath: join(tmpDir, 'does-not-exist.txt'),+ outputBuffer: '[Pasted text #1 +0 lines]\nfallback body',+ wrappedPrompt: 'wrapped',+ });+ expect(out).toEqual({ text: 'fallback body', usedResponseFile: false });+ });++ it('falls back to cleanTuiResponse when the file exists but is empty', async () => {+ await writeFile(responseFilePath, '');+ const out = await resolveTuiResponseText({+ success: true,+ responseFilePath,+ outputBuffer: 'fallback body',+ wrappedPrompt: 'wrapped',+ });+ expect(out).toEqual({ text: 'fallback body', usedResponseFile: false });+ });++ it('falls back to cleanTuiResponse when the file is whitespace-only', async () => {+ await writeFile(responseFilePath, ' \n\t \n');+ const out = await resolveTuiResponseText({+ success: true,+ responseFilePath,+ outputBuffer: 'fallback body',+ wrappedPrompt: 'wrapped',+ });+ expect(out).toEqual({ text: 'fallback body', usedResponseFile: false });+ });++ it('does NOT read the file when success=false — falls back unconditionally', async () => {+ // A failed run shouldn't trust a partial file the model may have started+ // writing. Even if the file exists with usable content, the caller+ // rejects with an error and the response text path doesn't matter much+ // — but the contract is: success=false ⇒ usedResponseFile=false.+ await writeFile(responseFilePath, 'partial response that should not be used');+ const out = await resolveTuiResponseText({+ success: false,+ responseFilePath,+ outputBuffer: 'partial screen scrape',+ wrappedPrompt: 'wrapped',+ });+ expect(out).toEqual({ text: 'partial screen scrape', usedResponseFile: false });+ });++ it('passes wrappedPrompt into cleanTuiResponse on the fallback path so prompt-echo elision strips the directive-wrapped prompt', async () => {+ const wrappedPrompt = 'WRITE TO FILE INSTRUCTIONS AND TASK BODY — a long enough string to clear the 16-char guard';+ const out = await resolveTuiResponseText({+ success: true,+ responseFilePath: join(tmpDir, 'absent.txt'),+ outputBuffer: `${wrappedPrompt}\nthe model reply`,+ wrappedPrompt,+ });+ expect(out).toEqual({ text: 'the model reply', usedResponseFile: false });+ });+});