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: show saved completion summaries separately from runner transcripts
Adam Eivy45a6ea8f11bd
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 2231fbe369..e90f9af1d2 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -624,7 +624,8 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,? (fullOutput?.lines || agent.output || []): (liveOutput || agent.output || [])), [inactive, fullOutput, liveOutput, agent.output]);- const taskSummary = completed && (fullMetadata?.taskSummary ?? agent.metadata?.taskSummary);+ const taskSummary = completed && (fullMetadata && Object.hasOwn(fullMetadata, 'taskSummary')+ ? fullMetadata.taskSummary : agent.metadata?.taskSummary);const lastOutput = output.length > 0 ? output[output.length - 1]?.line : null;// Why this run has NO "Open Shell" link. Scoped to the one case where the user@@ -1304,13 +1305,18 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,</div>)}- {taskSummary && (+ {completed && !taskSummary && (+ <p className="text-sm text-port-text-muted">+ {loadingOutput ? 'Loading completion summary…' : 'No completion summary was saved. The runner transcript is available separately.'}+ </p>+ )}+ {(completed || taskSummary) && (<button type="button" className="mt-2 text-xs text-port-accent hover:underline"aria-expanded={transcriptExpanded} onClick={() => setTranscriptExpanded(value => !value)}>{transcriptExpanded ? 'Hide full transcript' : 'Show full transcript'}</button>)}- {(!taskSummary || transcriptExpanded) && <>+ {((!completed && !taskSummary) || transcriptExpanded) && <>{/* Pipeline stage tabs */}{pipelineStages && (<div className="flex items-center gap-1 mb-2 overflow-x-auto">diff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsxindex cd7fc265b4..f5fd07bf74 100644--- a/client/src/components/cos/tabs/AgentCard.test.jsx+++ b/client/src/components/cos/tabs/AgentCard.test.jsx@@ -647,6 +647,7 @@ describe('AgentCard transcript truncation (#3498)', () => {await user.click(screen.getByRole('button', { name: 'Show' }));+ await user.click(screen.getByRole('button', { name: 'Show full transcript' }));expect(await screen.findByText(/Showing the last 1 line —/)).toBeInTheDocument();expect(screen.getByText(/12 MB/)).toBeInTheDocument();});@@ -668,6 +669,7 @@ describe('AgentCard transcript truncation (#3498)', () => {await user.click(screen.getByRole('button', { name: 'Show' }));+ await user.click(screen.getByRole('button', { name: 'Show full transcript' }));// "No output captured" would call a multi-MB log empty.expect(await screen.findByText(/no readable lines/)).toBeInTheDocument();expect(screen.queryByText('No output captured')).not.toBeInTheDocument();@@ -1330,3 +1332,15 @@ it('loads prior pipeline stage output through the full transcript disclosure', aawait userEvent.click(screen.getByRole('button', { name: /Plan/ }));expect(await screen.findByText('Prior planning transcript')).toBeInTheDocument();});+++it('keeps the runner transcript separate when no completion summary was saved', async () => {+ const completedAgent = { ...agent, metadata: {}, output: [{ line: 'exec: example tool output' }] };+ api.getCosAgent.mockResolvedValue(completedAgent);+ render(<MemoryRouter><AgentCard agent={completedAgent} completed /></MemoryRouter>);+ await userEvent.click(screen.getByRole('button', { name: 'Show', exact: true }));+ expect(await screen.findByText('No completion summary was saved. The runner transcript is available separately.')).toBeInTheDocument();+ expect(screen.queryByText('exec: example tool output')).not.toBeInTheDocument();+ await userEvent.click(screen.getByRole('button', { name: 'Show full transcript' }));+ expect(screen.getByText('exec: example tool output')).toBeInTheDocument();+});diff --git a/server/lib/streamJsonParser.js b/server/lib/streamJsonParser.jsindex 5f37e65488..622b4e95ef 100644--- a/server/lib/streamJsonParser.js+++ b/server/lib/streamJsonParser.js@@ -187,5 +187,8 @@ export function createStreamJsonParser() {return finalResult;};- return { processChunk, flush, getFinalResult };+ // Only the explicit terminal result is a completion summary. Intermediate+ // assistant sections can contain planning or tool narration.+ const getCompletionResult = () => typeof finalResult === 'string' ? finalResult : null;+ return { processChunk, flush, getFinalResult, getCompletionResult };}diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 3007cd36eb..b6150c5cf9 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -813,6 +813,7 @@ export async function spawnDirectly({exitCode: code,duration,outputBuffer,+ finalSummary: streamParser?.getCompletionResult() ?? null,errorAnalysis,terminatedByUser,error: finalError || undefined,diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex b0e39c88b0..7cdcacceb7 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -744,6 +744,25 @@ describe('stream error containment', () => {expect(appendRunEvent.mock.calls.map(([e]) => e.kind)).not.toContain('run.output');});+ it.each([+ ['final result', { type: 'result', result: 'Saved a partial checkpoint.' }, 'Saved a partial checkpoint.'],+ ['missing result', null, ''],+ ['malformed result', { type: 'result', result: { text: 'invalid' } }, null],+ ])('passes only an explicit completion through finalization: %s', async (_label, result, expected) => {+ const { finalizeAgent } = await import('./agentFinalization.js');+ finalizeAgent.mockClear();+ await spawnDirectly(minimalArgs);+ const events = [+ { type: 'assistant', message: { content: [{ type: 'text', text: 'Thinking about files.' }] } },+ { type: 'assistant', message: { content: [{ type: 'text', text: 'Running another command.' }] } },+ ...(result ? [result] : []),+ ];+ fakeProcess.stdout.emit('data', Buffer.from(events.map(event => JSON.stringify(event)).join('\n') + '\n'));+ fakeProcess.stderr.emit('data', Buffer.from('trailing runner diagnostics\n'));+ fakeProcess.emit('close', 0);+ await vi.waitFor(() => expect(finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({ finalSummary: expected })));+ });+it('drains stdout output on close and a failed batch flush is logged, not leaked as an unhandled rejection', async () => {// stdout output is now batched: the data handler pushes lines to the output// batcher and the close handler drains it. Make the drain's state write faildiff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex 981f816037..87f1ab23ba 100644--- a/server/services/agentCompletionCleanup.js+++ b/server/services/agentCompletionCleanup.js@@ -356,7 +356,7 @@ async function runCompletionCleanupSteps(context, { onStepError }) {// must not be able to abort the worktree cleanup and pipeline hand-off above.//// Gated on the record actually reaching an outcome. `finalizeAgent` runs- // `persistSimplifySummaries` and `resolveFailedTaskUpdate` BEFORE it+ // `persistCompletionSummary` and `resolveFailedTaskUpdate` BEFORE it// dispatches the output hook and calls `completeAgent`; a throw in either// leaves the record `running`, and the orphan sweep's recovery hook is then// what salvages the run — for a programmatic-I/O type the sentinel IS thediff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex c247240d10..f82b203931 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -832,7 +832,7 @@ describe.each(['runner', 'spawner'])('%s completion side effects', (path) => {});});-// `finalizeAgent` runs persistSimplifySummaries and resolveFailedTaskUpdate+// `finalizeAgent` runs persistCompletionSummary and resolveFailedTaskUpdate// BEFORE it dispatches the output hook and calls completeAgent, and both// spawners run cleanup from a `finally` — so a throw in either lands here with// the record still `running`. The orphan sweep's recovery hook is what salvagesdiff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex a700615b40..f4fb4e142d 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -59,7 +59,7 @@ import { SKIP_LEARNING_VERDICT } from '../lib/learningVerdict.js';import { detectPrimaryCheckoutDrift } from '../lib/primaryCheckoutGuard.js';import { canRunTaskOutputHookWithoutPayload, getTaskOutputPayloadPredicate, isProgrammaticIoTaskType, resolveTaskHookType, declaresNoCommitCriterion, isClaimFlowDispatch } from './taskTypeHooks.js';import { processAgentCompletion } from './agentCompletion.js';-import { extractFinalSummary, extractSimplifySummaries } from './agentSummaryExtraction.js';+import { extractFinalSummary } from './agentSummaryExtraction.js';import { usesCreativeDirectorScratchCwd, removeCreativeDirectorScratchCwd } from '../lib/spawnCwd.js';import { issueNumberFromRef } from './issueReconcile.js';@@ -1311,6 +1311,7 @@ export async function finalizeAgent({exitCode,duration,outputBuffer,+ finalSummary = null,errorAnalysis: reportedErrorAnalysis,terminatedByUser = false,error,@@ -1525,8 +1526,8 @@ export async function finalizeAgent({cosEvents.emit(GOAL_FIDELITY_HOLD_EVENT, { agentId, taskId: task?.id, review: fidelity.review });}- if (judgedVerdict.success) {- await persistSimplifySummaries(agentId, task, outputBuffer);+ if (!terminatedByUser && !isPrivateSecurityTask(task)) {+ await persistCompletionSummary(agentId, { workspacePath, finalSummary });}// Programmatic-I/O task types (e.g. layered-intelligence) run a deterministic@@ -2004,21 +2005,45 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, areturn { ran: true, outcome };}-/**- * Persist task/simplify summaries for agents that ran with /simplify.- * Shared by handleAgentCompletion (runner mode) and spawnDirectly (direct mode).+/** Persist an explicitly delivered completion, independently of delivery success.+ * The transcript remains available separately; it is never a substitute for a+ * missing final response, including on a partial Deep checkpoint.*/-export async function persistSimplifySummaries(agentId, task, outputBuffer) {- if (!isTruthyMeta(task.metadata?.simplify)) return;- const summaries = extractSimplifySummaries(outputBuffer);- if (!summaries) return;- // Persist whenever *either* summary is present — e.g. if the /simplify- // marker appears at the very top of the output, taskSummary will be null- // but simplifySummary is still worth keeping.- if (summaries.taskSummary || summaries.simplifySummary) {- await updateAgent(agentId, { metadata: {- taskSummary: summaries.taskSummary || null,- simplifySummary: summaries.simplifySummary || null- } });+async function persistCompletionSummary(agentId, { workspacePath, finalSummary = null }) {+ const { doneSentinelPath, parseSentinelPayload } = await import('../lib/agentSentinel.js');+ const sentinelPath = doneSentinelPath(workspacePath, agentId);+ const contents = sentinelPath ? await tryReadFile(sentinelPath) : null;+ let summary = null;+ let source = null;+ if (typeof contents === 'string' && contents.trim()) {+ const trimmed = contents.trim();+ const envelope = trimmed.match(/^```json\s*\n([\s\S]*?)\n```$/)?.[1]?.trim() ?? trimmed;+ // A malformed structured envelope must not be rendered as a human answer.+ // Legacy markdown sentinels remain supported.+ const structured = trimmed.startsWith('{') || trimmed.startsWith('[') || trimmed.startsWith('```json');+ const parsed = structured ? safeJSONParse(envelope, null) : null;+ if (!structured || (parsed && !Array.isArray(parsed) && typeof parsed.summary === 'string')) {+ summary = parseSentinelPayload(envelope).summary.trim() || null;+ if (summary) source = 'sentinel';+ }+ }+ if (!summary && typeof finalSummary === 'string') {+ summary = finalSummary.trim() || null;+ if (summary) source = 'terminal-result';+ }+ if (!summary) {+ // Cleanup may already have removed the sentinel on a finalization replay.+ // Only retain a completion whose source was recorded for this same agent;+ // older heuristic transcript summaries are not evidence of a final reply.+ const existing = await getAgentRecord(agentId);+ if (existing?.id === agentId+ && ['sentinel', 'terminal-result'].includes(existing.metadata?.taskSummarySource)+ && typeof existing.metadata?.taskSummary === 'string'+ && existing.metadata.taskSummary.trim()) return;}+ await updateAgent(agentId, { metadata: {+ taskSummary: summary,+ taskSummarySource: source,+ simplifySummary: null,+ } });}diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.jsindex e8e1dda478..e4ba3276ed 100644--- a/server/services/agentFinalization.outputHooks.test.js+++ b/server/services/agentFinalization.outputHooks.test.js@@ -40,7 +40,7 @@ vi.mock('./taskTypeHooks.js', () => ({resolveTaskHookType: vi.fn(task => task?.metadata?.analysisType || null),}));-import { getAgent, updateAgent, completeAgent } from './cosAgentLifecycle.js';+import { getAgent, getAgentRecord, updateAgent, completeAgent } from './cosAgentLifecycle.js';import { canRunTaskOutputHookWithoutPayload, getTaskOutputHook, isProgrammaticIoTaskType } from './taskTypeHooks.js';import {finalizeAgent,@@ -105,6 +105,7 @@ describe('recovery output-hook dispatch (#3182)', () => {metadata: {},};getAgent.mockImplementation(async () => persistedAgent);+ getAgentRecord.mockImplementation(async () => persistedAgent);updateAgent.mockImplementation(async (_agentId, updates) => {persistedAgent = {...persistedAgent,@@ -208,6 +209,59 @@ describe('recovery output-hook dispatch (#3182)', () => {isProgrammaticIoTaskType.mockReturnValue(true);});+ it.each([+ ['markdown checkpoint', 'Reviewed this batch. Deep coverage remains incomplete.', 'Reviewed this batch. Deep coverage remains incomplete.'],+ ['structured checkpoint', JSON.stringify({ summary: 'Saved a partial checkpoint.', payload: null }), 'Saved a partial checkpoint.'],+ ['missing summary', null, null],+ ['terminal result fallback', null, 'Explicit terminal result.', 'Explicit terminal result.'],+ ['sentinel precedence', 'Saved checkpoint.', 'Saved checkpoint.', 'Provider terminal response.'],+ ['fenced valid envelope', '```json\n{"summary":"Fenced completion."}\n```', 'Fenced completion.'],+ ['fenced malformed envelope', '```json\n{"summary":\n```', null],+ ['malformed envelope', '{"summary":', null],+ ['invalid summary', JSON.stringify({ summary: { text: 'not a string' } }), null],+ ])('persists only explicit completion text for a resumed Deep %s', async (_label, sentinel, expected, finalSummary = null) => {+ const { mkdtemp, writeFile, rm } = await import('node:fs/promises');+ const { tmpdir } = await import('node:os');+ const workspacePath = await mkdtemp(join(tmpdir(), 'completion-summary-'));+ try {+ if (sentinel !== null) await writeFile(join(workspacePath, '.agent-done-summary-example'), sentinel);+ const task = { ...TASK, metadata: { ...TASK.metadata, auditDepth: 'deep', simplify: false } };+ await finalizeAgent({ agentId: 'summary-example', task, success: true, exitCode: 0,+ duration: 1000, workspacePath, finalSummary, outputBuffer: 'Thinking: inspect files\nexec\npython command output' });+ expect(persistedAgent.metadata.taskSummary).toBe(expected);+ expect(persistedAgent.metadata.simplifySummary).toBeNull();+ expect(deep.checkpointDeepAudit).toHaveBeenCalled();+ } finally {+ await rm(workspacePath, { recursive: true, force: true });+ }+ });++ it.each(['sentinel', 'terminal-result', 'legacy'])('retains only authoritative %s summaries on repeat finalization after cleanup', async (source) => {+ const { mkdtemp, writeFile, rm } = await import('node:fs/promises');+ const { tmpdir } = await import('node:os');+ const workspacePath = await mkdtemp(join(tmpdir(), 'completion-replay-'));+ const sentinelPath = join(workspacePath, '.agent-done-summary-replay');+ persistedAgent.id = 'summary-replay';+ const task = { ...TASK, metadata: { ...TASK.metadata, auditDepth: 'deep' } };+ const finish = (finalSummary = null) => finalizeAgent({ agentId: 'summary-replay', task, success: true,+ exitCode: 0, duration: 1000, workspacePath, finalSummary, outputBuffer: 'exec: tool output' });+ try {+ if (source === 'legacy') {+ persistedAgent.metadata.taskSummary = 'Old heuristic tool transcript';+ } else {+ if (source === 'sentinel') await writeFile(sentinelPath, 'Saved partial completion.');+ await finish(source === 'terminal-result' ? 'Saved partial completion.' : null);+ expect(persistedAgent.metadata).toMatchObject({ taskSummary: 'Saved partial completion.', taskSummarySource: source });+ await rm(sentinelPath, { force: true });+ }+ await finish();+ expect(persistedAgent.metadata.taskSummary).toBe(source === 'legacy' ? null : 'Saved partial completion.');+ expect(persistedAgent.metadata.taskSummarySource).toBe(source === 'legacy' ? null : source);+ } finally {+ await rm(workspacePath, { recursive: true, force: true });+ }+ });+it('parks a failed Deep attempt without the normal automatic retry path', async () => {const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'security', auditDepth: 'deep' } };await finalizeAgent({ agentId: 'deep-failed', task, success: false, exitCode: 1, duration: 1000,diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.jsindex 154904e2d3..5961985f45 100644--- a/server/services/agentTuiSpawning/sessionController.js+++ b/server/services/agentTuiSpawning/sessionController.js@@ -704,7 +704,7 @@ export function createTuiSessionController({// Read the `.agent-done` sentinel (if present) and append its markdown task// summary line-by-line into the agent's output so downstream consumers- // (extractFinalSummary, persistSimplifySummaries, completion hooks, the agent+ // (extractFinalSummary, persistCompletionSummary, completion hooks, the agent// card, output.txt) get the resolution. Called only from finish() (the single// finalize chokepoint); idempotent via `sentinelIngested` so it reads at most// once. Capped at 4 KB so an agent that pasted the whole diff into thediff --git a/server/services/codexSummaryRepair.js b/server/services/codexSummaryRepair.jsindex c86699d85a..788a63e04f 100644--- a/server/services/codexSummaryRepair.js+++ b/server/services/codexSummaryRepair.js@@ -24,6 +24,9 @@ export function isWonkyTaskSummary(summary) {// Also clears any wonky `simplifySummary` — Codex CLI cannot execute the// `/simplify` slash command, so any pre-fix split was a false positive.export async function repairCodexTaskSummary(agentDir, agent) {+ // Explicit completions can legitimately be long. Never replace one with a+ // guessed transcript tail or undermine its persisted source provenance.+ if (['sentinel', 'terminal-result'].includes(agent?.metadata?.taskSummarySource)) return null;const storedTask = agent?.metadata?.taskSummary;const storedSimplify = agent?.metadata?.simplifySummary;const taskWonky = isWonkyTaskSummary(storedTask);diff --git a/server/services/codexSummaryRepair.test.js b/server/services/codexSummaryRepair.test.jsindex 79a46c0331..0327e8c514 100644--- a/server/services/codexSummaryRepair.test.js+++ b/server/services/codexSummaryRepair.test.js@@ -36,6 +36,14 @@ describe('repairCodexTaskSummary', () => {if (outputBuffer != null) await writeFile(join(agentDir, 'output.txt'), outputBuffer);}+ it.each(['sentinel', 'terminal-result'])('does not heuristically replace a long authoritative %s completion', async (taskSummarySource) => {+ const metadata = { taskSummary: 'Complete documented findings.\n'.repeat(1000), taskSummarySource };+ await seed(metadata, 'tokens used\n123\nA different transcript tail');+ const before = await readFile(join(agentDir, 'metadata.json'), 'utf8');+ expect(await repairCodexTaskSummary(agentDir, { id: 'agent-test', metadata })).toBeNull();+ expect(await readFile(join(agentDir, 'metadata.json'), 'utf8')).toBe(before);+ });+it('rewrites metadata.json when stored summary is wonky and tail is recoverable', async () => {const fakeTranscript = 'x'.repeat(25_000);const output = [