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
complete a watched one-shot TUI run when it writes its response file
[._.]/ Adam Eivy51d92e3ed0a8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b57800da27..ef965cece9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -14,6 +14,8 @@## Fixed+- **A watched TUI run no longer false-times-out after finishing its work** — companion fix to *Live TUI runs are now viewable AND drivable in the Shell page* (above). One-shot AI runs that drive a terminal UI (Claude Code, Codex, etc.) write their completed answer to a response file and then return to an interactive prompt **without exiting**. The runner only auto-completed such a run via output-idle — which is paused while you watch it in the Shell page (so it isn't snapped shut mid-read). With the process never exiting and idle paused, a watched run had no terminus but the 10-minute hard timeout — at which point it was marked **failed**, its already-written result was **discarded**, and a useless fallback retry ran in its place. The runner now watches for the response file as the model's authoritative "done" signal and completes the run the moment it's written — even while you're watching — since once the file exists the task is genuinely finished. A second safety net salvages the file on hard timeout: if the result was written but completion stalled for any other reason, the run finishes as **success** with that result instead of throwing it away and falling back. So a long editorial pass you keep open in the Shell tab now lands its findings when the model finishes, instead of silently dying at 10 minutes. (`server/lib/tuiPromptRunner.js`)+- **Catalog user-type sync now converges instead of re-applying every cycle** — federated catalog *user-defined types* used an at-or-newer (`>=`) last-write-wins comparison, so a peer re-sending a type you already held at the same timestamp was re-adopted, re-written, and re-counted as a change on every sync cycle. The logs showed a constant non-zero count (e.g. `Synced with <peer>: 3 catalog changes`) once a minute forever, and the slice was rewritten needlessly each pass. The merge now uses strict-newer (`>`), matching the SQL LWW guard every other catalog kind already uses (`EXCLUDED.updated_at > …updated_at`): an equal-clock echo is a skip, so the merge is idempotent and the cycle settles to zero changes. (`server/services/catalogSync.js`)- **[issue-1080] Notes synced from other machines become searchable promptly** — a Brain note, daily-log entry, person, project, or idea created or edited on one of your machines is now re-indexed into semantic memory on the others as soon as it syncs, instead of waiting for a full manual re-sync. Edits and deletes that arrive from a peer also refresh or retire the matching memory entry, so search no longer surfaces stale copies of records that changed elsewhere. A new **Refresh embeddings** button on the Brain graph re-indexes everything in one pass to heal anything that drifted before this fix.diff --git a/scripts/seed-completeness-from-run.mjs b/scripts/seed-completeness-from-run.mjsnew file mode 100644index 0000000000..cd36cda6d5--- /dev/null+++ b/scripts/seed-completeness-from-run.mjs@@ -0,0 +1,50 @@+/**+ * One-off recovery: seed a manuscript-completeness review from a TUI run whose+ * result was captured to tui-response.txt but never seeded (the run was marked+ * timed-out and a useless fallback ran instead). Reuses the real+ * seedReviewFromFindings so dedup, issueId resolution, and fix-backfill match+ * exactly what the pipeline would have done.+ *+ * Usage: node scripts/seed-completeness-from-run.mjs <seriesId> <runId> [--dry]+ */+import { readFileSync } from 'fs';+import { join } from 'path';+import { collectManuscriptSections } from '../server/services/pipeline/arcPlanner.js';+import { seedReviewFromFindings, getReview } from '../server/services/pipeline/manuscriptReview.js';++const [seriesId, runId] = process.argv.slice(2);+const dry = process.argv.includes('--dry');+if (!seriesId || !runId) {+ console.error('usage: node scripts/seed-completeness-from-run.mjs <seriesId> <runId> [--dry]');+ process.exit(1);+}++const responsePath = join(process.cwd(), 'data', 'runs', runId, 'tui-response.txt');+const parsed = JSON.parse(readFileSync(responsePath, 'utf8'));+const issues = Array.isArray(parsed.issues) ? parsed.issues : [];+console.log(`📥 ${issues.length} findings in ${responsePath}`);++const sections = await collectManuscriptSections(seriesId);+console.log(`📑 ${sections.length} manuscript sections resolved for ${seriesId}`);+if (!sections.length) {+ console.error('❌ no manuscript sections — issueId/fix resolution would be empty. Aborting (check seriesId / data root).');+ process.exit(1);+}++const before = await getReview(seriesId);+const beforeOpen = before.comments.filter((c) => c.status === 'open').length;+console.log(`📊 before: ${before.comments.length} comments (${beforeOpen} open)`);++if (dry) {+ console.log('🧪 dry run — not writing. Findings preview:');+ for (const i of issues) console.log(` #${i.issueNumber} [${i.severity}/${i.category}] ${i.replacementStrategy} ${i.replace ? '(has replace)' : ''} — ${(i.location || '').slice(0, 50)}`);+ process.exit(0);+}++const review = await seedReviewFromFindings(seriesId, issues, { runId, mode: 'merge' });+const after = review.comments.length;+const afterOpen = review.comments.filter((c) => c.status === 'open').length;+const fromThisRun = review.comments.filter((c) => c.sourceRunId === runId).length;+const withFix = review.comments.filter((c) => c.sourceRunId === runId && c.fix).length;+console.log(`✅ after: ${after} comments (${afterOpen} open). Added ${after - before.comments.length} new; ${fromThisRun} tagged to run ${runId.slice(0, 8)} (${withFix} with pre-built fix).`);+process.exit(0);diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex c49372ff62..44b5de6ec6 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -207,6 +207,25 @@ ${prompt}`;let outputBufferTruncated = false;const streamingStrip = createStreamingAnsiStripper();++ // The wrapped prompt directs the model to write its COMPLETE response to+ // `responseFilePath` and then finish. That file appearing is the model's+ // explicit "done" signal — more reliable than output-idle and, unlike idle,+ // authoritative even while a human watches (the task is finished; there's+ // nothing left to intervene in). Returns true once the file has non-empty+ // content whose length held steady across two consecutive polls (~1s apart),+ // so a half-flushed write isn't read as complete. `lastResponseLen = -1`+ // means "not yet seen / reset"; a real reading seeds it and the next equal+ // reading confirms stability.+ let lastResponseLen = -1;+ const responseFileSettled = async () => {+ const txt = await tryReadFile(responseFilePath);+ if (typeof txt !== 'string' || !txt.trim()) { lastResponseLen = -1; return false; }+ if (txt.length === lastResponseLen) return true;+ lastResponseLen = txt.length;+ return false;+ };+let readyTimer = null;let pasteEnterTimer = null;let idleWatchTimer = null;@@ -299,13 +318,25 @@ ${prompt}`;// Defer the idle-watch timer until the first response chunk so we// don't run a 1Hz no-op throughout the 5-30s spawn + paste window.// Significant on parallel fan-out paths (arc planner).- idleWatchTimer = setInterval(() => {+ idleWatchTimer = setInterval(async () => {if (finalized) return;- // Don't auto-complete a run a human is actively watching in the Shell- // page — they may be reading the output or about to type a correction- // or an answer the model is waiting on. The run then ends only on- // natural process exit or an explicit Stop. Unattended pipeline runs- // keep the snappy idle threshold for throughput.+ // The model writing its response file is the authoritative completion+ // signal (it's what the wrapped prompt asks for) — check it FIRST and+ // unconditionally. Claude Code's TUI never exits after a one-shot task+ // (it returns to its interactive prompt), so without this a watched run+ // has no terminus but the hard timeout. This is intentionally NOT gated+ // on attach: once the file exists the task is done, so completing it is+ // correct even while a human is watching.+ if (await responseFileSettled()) {+ finish({ success: true, exitCode: 0, reason: 'response-file' });+ return;+ }+ // Idle-completion fallback (no response file yet — e.g. the model+ // printed inline instead of writing the file). Don't auto-complete a+ // run a human is actively watching in the Shell page — they may be+ // reading the output or about to type a correction or an answer the+ // model is waiting on. Unattended pipeline runs keep the snappy idle+ // threshold for throughput.if (isExternalSessionAttached(runId)) return;const idle = Date.now() - lastOutputAt;if (idle >= idleThresholdMs) {@@ -410,8 +441,19 @@ ${prompt}`;// a backgrounded tab (idle-completion is paused while watched, but this is// not — a run can't exceed its configured max time). Provider-configurable// via `timeout`; defaults to 5 min.- hardTimeoutTimer = setTimeout(() => {+ hardTimeoutTimer = setTimeout(async () => {if (finalized) return;+ // Salvage net: if the model already wrote its response file, the run truly+ // finished — the TUI just never exited — so the timeout is a false failure.+ // Complete as success with the written result instead of discarding it and+ // triggering a pointless fallback retry. (The response-file watcher above+ // normally catches this within ~2s; this covers the boundary case where the+ // file lands right at the deadline or the watcher hadn't confirmed yet.)+ const salvaged = await tryReadFile(responseFilePath);+ if (typeof salvaged === 'string' && salvaged.trim()) {+ finish({ success: true, exitCode: 0, reason: 'timeout-response-file' });+ return;+ }finish({success: false,exitCode: 124,diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.jsindex c04d43ceab..1566df71b9 100644--- a/server/lib/tuiPromptRunner.test.js+++ b/server/lib/tuiPromptRunner.test.js@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { mkdtemp, rm, writeFile } from 'fs/promises';+import { mkdtemp, rm, writeFile, mkdir } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';@@ -478,6 +478,78 @@ describe('executeTuiRun', () => {}));});+ it('completes with reason "response-file" once the model writes its response file — even while a viewer is attached', async () => {+ vi.useFakeTimers({+ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],+ });+ // A human is watching — idle-completion is paused, but the response file+ // is the model's explicit "done" signal and must complete regardless.+ // This is the regression guard for the manuscript-completeness run that+ // wrote tui-response.txt yet rode to the hard timeout because it was watched.+ shellMocks.isExternalSessionAttached.mockReturnValue(true);+ const provider = {+ id: 'claude', type: 'tui', command: 'claude',+ tuiPromptDelayMs: 50, tuiOneShotIdleMs: 500,+ };+ const runId = 'run-respfile';+ const promise = executeTuiRun({ runId, provider, prompt: 'review this manuscript thoroughly enough to clear the guard', workspacePath: '/cwd', timeout: 60000 });+ await flushAsync();++ const pty = ptyInstances[0];+ pty.emitData('claude code ready> ');+ await vi.advanceTimersByTimeAsync(2000); // paste+ await vi.advanceTimersByTimeAsync(4000); // enter+ pty.emitData('model thinking…'); // arms idleWatchTimer++ // The model writes its COMPLETE response to the file the runner directed+ // it to (and, like Claude Code's TUI, does NOT exit afterward).+ const runDir = join(runsTmpDirRef.current, runId);+ await mkdir(runDir, { recursive: true });+ await writeFile(join(runDir, 'tui-response.txt'), '{"issues":[]}');++ // First tick seeds the size-stability baseline; the second confirms it.+ await vi.advanceTimersByTimeAsync(1100);+ await vi.advanceTimersByTimeAsync(1100);+ await flushAsync();+ await promise;++ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId,+ success: true,+ exitCode: 0,+ output: '{"issues":[]}',+ extras: expect.objectContaining({ completionReason: 'response-file', usedResponseFile: true }),+ }));+ });++ it('salvages the response file on hard timeout → success with reason "timeout-response-file" instead of a false failure + fallback', async () => {+ vi.useFakeTimers({+ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],+ });+ const provider = { id: 'claude', type: 'tui', command: 'echo' };+ const runId = 'run-tmo-salvage';+ // The model finished and wrote its file, but the TUI never exited and the+ // idle watcher was never armed (no post-paste chunk) — so only the hard+ // timeout remains to terminate the run. It must NOT throw the result away.+ const runDir = join(runsTmpDirRef.current, runId);+ await mkdir(runDir, { recursive: true });+ await writeFile(join(runDir, 'tui-response.txt'), 'the completed review body');++ const promise = executeTuiRun({ runId, provider, prompt: 'a prompt long enough to clear the guard', workspacePath: '/cwd', timeout: 500 });+ await flushAsync();+ await vi.advanceTimersByTimeAsync(600); // hard timeout fires+ await flushAsync();+ await promise;++ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId,+ success: true,+ exitCode: 0,+ output: 'the completed review body',+ extras: expect.objectContaining({ completionReason: 'timeout-response-file', usedResponseFile: true }),+ }));+ });+it('finishes with reason "timeout" and exitCode 124 when the hard timeout fires before any completion', async () => {vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],