The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
refactor(heartbeat): extract run output recording (#15969)
Dotta37913e490732
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.mdindex 7cf3e8b147..da1bc58a96 100644--- a/doc/DEVELOPING.md+++ b/doc/DEVELOPING.md@@ -1302,8 +1302,11 @@ acquire no runtime resources. Public-path characterization tests live inRun-log formatting is in `server/src/services/heartbeat/run-log.ts`. It boundsstored event payloads, redacts and shortens log chunks, and caps stdout/stderr-excerpts. `heartbeat.ts` keeps event writes, current-user redaction, and live-event delivery. Existing public helpers remain available from `heartbeat.ts`.+excerpts. `run-output.ts` owns per-attempt log handles, current-user redaction,+output progress writes, live log delivery, and adapter event callbacks. The log+store remains service-scoped. Completion reads live excerpt getters so output+that arrives during finalization is retained. Existing public helpers and flush+interval constants remain available from `heartbeat.ts`.Workspace preparation is in `server/src/services/heartbeat/workspaces.ts`. Itowns managed checkout materialization, workspace validation and reuse, referenceddiff --git a/server/src/__tests__/heartbeat-run-output.test.ts b/server/src/__tests__/heartbeat-run-output.test.tsnew file mode 100644index 0000000000..a912d6e0e3--- /dev/null+++ b/server/src/__tests__/heartbeat-run-output.test.ts@@ -0,0 +1,121 @@+import { randomUUID } from "node:crypto";+import { eq } from "drizzle-orm";+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { agents, companies, createDb, heartbeatRunEvents, heartbeatRuns, issues } from "@paperclipai/db";+import { registerServerAdapter, unregisterServerAdapter, type AdapterExecutionContext } from "../adapters/index.js";+import { heartbeatService } from "../services/heartbeat.js";+import { getRunLogStore } from "../services/run-log-store.js";+import { subscribeCompanyLiveEvents } from "../services/live-events.js";+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";++const support = await getEmbeddedPostgresTestSupport();+const describePostgres = support.supported ? describe : describe.skip;+if (!support.supported) console.warn(`Skipping run output tests: ${support.reason}`);++describePostgres("heartbeat output through adapter dispatch and finalization", () => {+ const adapterType = "run_output_test";+ let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;+ let db: ReturnType<typeof createDb>;+ let heartbeat: ReturnType<typeof heartbeatService>;+ const executeByAgent = new Map<string, (input: AdapterExecutionContext) => Promise<void>>();++ beforeAll(async () => {+ temporary = await startEmbeddedPostgresTestDatabase("heartbeat-run-output-");+ db = createDb(temporary.connectionString);+ heartbeat = heartbeatService(db);+ registerServerAdapter({+ type: adapterType, supportsLocalAgentJwt: false,+ execute: async (input) => {+ await db.update(issues).set({ status: "in_review" }).where(eq(issues.id, String(input.context.issueId)));+ await executeByAgent.get(input.agent.id)!(input);+ return { exitCode: 0, signal: null, timedOut: false, resultJson: {} };+ },+ testEnvironment: async () => ({ adapterType, status: "pass", checks: [], testedAt: new Date().toISOString() }),+ });+ }, 30_000);+ afterEach(() => vi.restoreAllMocks());+ afterAll(async () => {+ await heartbeat?.drainActiveRunExecutions();+ unregisterServerAdapter(adapterType);+ await db?.$client.end({ timeout: 0 });+ await temporary?.cleanup();+ });++ async function seed(execute: (input: AdapterExecutionContext) => Promise<void>) {+ const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID();+ await db.insert(companies).values({ id: companyId, name: "Output fixture", issuePrefix: `O${companyId.slice(0, 6)}` });+ await db.insert(agents).values({ id: agentId, companyId, name: "Output writer", adapterType, status: "idle" });+ await db.insert(issues).values({ id: issueId, companyId, title: "Output fixture", status: "todo", assigneeAgentId: agentId, responsibleUserId: "output-user", issueNumber: 1 });+ executeByAgent.set(agentId, execute);+ return { companyId, agentId, issueId };+ }+ async function execute(f: Awaited<ReturnType<typeof seed>>) {+ const run = await heartbeat.wakeup(f.agentId, { source: "on_demand", triggerDetail: "manual", reason: "manual", payload: { issueId: f.issueId }, contextSnapshot: { issueId: f.issueId } });+ expect(run).not.toBeNull();+ await heartbeat.drainActiveRunExecutions();+ const finished = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run!.id)).then(rows => rows[0]);+ expect(finished).toBeDefined();+ const log = await heartbeat.readLog(run!.id);+ const entries = log.content.trim().split("\n").filter(Boolean).map(line => JSON.parse(line));+ return { finished, entries };+ }++ it("redacts stored and live chunks, preserves sequence, and flushes the last output at completion", async () => {+ const secret = "output-test-bearer-canary";+ const f = await seed(async input => {+ await input.onLog("stdout", `first: Authorization: Bearer ${secret}\n`);+ await input.onLog("stdout", `${"x".repeat(10_000)}live-tail\n`);+ await input.onLog("stderr", "last stderr\n");+ await input.onMeta?.({ adapterType, command: "fixture", env: { PAPERCLIP_API_KEY: secret }, prompt: "fixture prompt" });+ await input.onEvent?.({ eventType: " fixture.progress ", stream: "system", level: "info", message: "fixture event", payload: { step: 1 } });+ await input.onEvent?.({ eventType: " ", stream: "system", level: "info", message: "ignored blank event" });+ });+ const live: Record<string, unknown>[] = [];+ const unsubscribe = subscribeCompanyLiveEvents(f.companyId, event => {+ if (event.type === "heartbeat.run.log") live.push(event.payload);+ });+ try {+ const { finished, entries } = await execute(f);+ expect(finished.status, finished.error ?? undefined).toBe("succeeded");+ const ownLive = live.filter(event => event.runId === finished.id);+ expect(entries.map(entry => entry.seq)).toEqual(entries.map((_, i) => i + 1));+ expect(ownLive.map(event => event.seq)).toEqual(entries.map(entry => entry.seq));+ expect(JSON.stringify(entries)).not.toContain(secret);+ expect(JSON.stringify(ownLive)).not.toContain(secret);+ expect(finished.stdoutExcerpt).not.toContain(secret);+ expect(finished.stderrExcerpt).toContain("last stderr");+ expect(ownLive.find(event => String(event.chunk).endsWith("live-tail\n"))).toMatchObject({ truncated: true });+ expect(finished.lastOutputSeq).toBe(entries.at(-1).seq);+ expect(finished.lastOutputStream).toBe("stderr");+ expect(finished.lastOutputBytes).toBe(finished.logBytes);+ expect(finished.lastOutputAt).toEqual(new Date(entries.at(-1).ts));+ const events = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, finished.id));+ expect(JSON.stringify(events)).not.toContain(secret);+ expect(events.find(event => event.eventType === "adapter.invoke")?.payload).toMatchObject({ env: { PAPERCLIP_API_KEY: "***REDACTED***" } });+ expect(events.find(event => event.eventType === "fixture.progress")).toMatchObject({ message: "fixture event", payload: { step: 1 } });+ expect(events.some(event => event.message === "ignored blank event")).toBe(false);+ } finally { unsubscribe(); }+ });++ it.each([false, true])("retains output arriving during finalization (adapter throws: %s)", async fail => {+ let onLog: AdapterExecutionContext["onLog"];+ const f = await seed(async input => {+ onLog = input.onLog;+ await onLog("stdout", "before finalization\n");+ if (fail) throw new Error("invalid fixture configuration");+ });+ const store = getRunLogStore();+ const finalize = store.finalize.bind(store);+ vi.spyOn(store, "finalize").mockImplementationOnce(async handle => {+ await onLog("stdout", "during finalization\n");+ return finalize(handle);+ });+ const { finished, entries } = await execute(f);+ expect(finished.status, finished.error ?? undefined).toBe(fail ? "failed" : "succeeded");+ expect(finished.stdoutExcerpt).toContain("before finalization");+ expect(finished.stdoutExcerpt).toContain("during finalization");+ expect(entries.at(-1).chunk).toBe("during finalization\n");+ expect(finished.lastOutputSeq).toBe(entries.at(-1).seq);+ expect(finished.lastOutputBytes).toBe(finished.logBytes);+ });+});diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.tsindex 03274998d8..54006b8b7e 100644--- a/server/src/services/heartbeat.ts+++ b/server/src/services/heartbeat.ts@@ -1,3 +1,4 @@+import { createHeartbeatRunOutput } from "./heartbeat/run-output.js";import { prepareHeartbeatSession, resolveHeartbeatAdapterSession } from "./heartbeat/session-preparation.js";import { prepareHeartbeatTaskContext } from "./heartbeat/task-context.js";import { selectHeartbeatEnvironment } from "./heartbeat/environment-selection.js";@@ -30,8 +31,6 @@ export {} from "./heartbeat/run-control.js";import {isHeartbeatRunTerminalStatus,- isHeartbeatRunRuntimeStatusActive,- publishHeartbeatRunRuntimeProgress,decorateHeartbeatRunRuntimeStatus,createHeartbeatLifecycle,} from "./heartbeat/run-lifecycle.js";@@ -202,11 +201,7 @@ export {stripPaperclipSessionMetadataFromSessionParams,resolveTaskSessionConfigFreshness,} from "./heartbeat/workspaces.js";-import {- appendExcerpt,- boundHeartbeatRunEventPayloadForStorage,- compactRunLogChunk,-} from "./heartbeat/run-log.js";+import { boundHeartbeatRunEventPayloadForStorage } from "./heartbeat/run-log.js";export {boundHeartbeatRunEventPayloadForStorage,compactRunLogChunk,@@ -375,15 +370,11 @@ import {type NativeSessionBackend,} from "../vendor/paperclip-runner/index.js";-import { getRunLogStore, type RunLogHandle } from "./run-log-store.js";+import { getRunLogStore } from "./run-log-store.js";import {providerTraceStore,} from "./provider-trace-store.js";import { getServerAdapter, runningProcesses } from "../adapters/index.js";-import type {- AdapterInvocationMeta,- AdapterRuntimeEvent,-} from "../adapters/index.js";import { createRuntimeToolsToken } from "../runtime-tools-token.js";import {@@ -522,9 +513,6 @@ import {DIRECT_NON_INVOKABLE_STATUSES,} from "./agent-invokability.js";-import {- redactCurrentUserText,-} from "../log-redaction.js";import { createRunSecretRedactionRegistry } from "./run-secret-redaction.js";@@ -544,7 +532,6 @@ import { environmentRunOrchestrator } from "./environment-run-orchestrator.js";import {clearHeartbeatRunRuntimeStatus,sweepExpiredHeartbeatRunRuntimeStatuses,- touchHeartbeatRunRuntimeStatus,} from "./heartbeat-run-runtime-status.js";import {@@ -557,8 +544,6 @@ import type { PluginWorkerManager } from "./plugin-worker-manager.js";import { computeTaskDrain, applyTaskDrain, startTaskDrain, stopTaskDrain, readTaskDrain } from "./task-admission.js";-const MAX_LIVE_LOG_CHUNK_BYTES = 8 * 1024;-const ACCEPTED_PLAN_CONVERSION_SKILL_KEY ="paperclipai/paperclip/paperclip-converting-plans-to-tasks";@@ -574,8 +559,7 @@ export {ACTIVE_RUN_OUTPUT_CRITICAL_THRESHOLD_MS,ACTIVE_RUN_OUTPUT_SUSPICION_THRESHOLD_MS,} from "./recovery/service.js";-export const ACTIVE_RUN_OUTPUT_PROGRESS_FLUSH_INTERVAL_MS = 60 * 1000;-export const ACTIVE_RUN_LOG_RUNTIME_STATUS_REFRESH_INTERVAL_MS = 5 * 1000;+export { ACTIVE_RUN_OUTPUT_PROGRESS_FLUSH_INTERVAL_MS, ACTIVE_RUN_LOG_RUNTIME_STATUS_REFRESH_INTERVAL_MS } from "./heartbeat/run-output.js";export {INTERACTION_CONTINUATION_INFRA_RETRY_REASON,@@ -3381,49 +3365,16 @@ export function heartbeatService(evaluateSessionCompaction,});- let handle: RunLogHandle | null = null;+ const runOutput = createHeartbeatRunOutput(db, {+ run, runId, issueId, runLogStore, identityRedactor, secretKeys,+ appendRunEvent, getCurrentUserRedactionOptions,+ });const goalCheckpointSession: {current: {params: Record<string, unknown>;displayId: string;} | null;} = { current: null };- let stdoutExcerpt = "";- let stderrExcerpt = "";- let outputSeq = Number(run.lastOutputSeq ?? 0);- let lastOutputFlushAt: Date | null = run.lastOutputAt ?? null;- let lastLogRuntimeStatusTouchMs = 0;- const outputProgressState: {- pending: {- at: Date;- seq: number;- stream: "stdout" | "stderr";- bytes: number;- } | null;- } = { pending: null };- let persistedLogBytes = Number(run.logBytes ?? 0);- const flushOutputProgress = async (opts?: { force?: boolean }) => {- const pendingOutputProgress = outputProgressState.pending;- if (!pendingOutputProgress) return;- const shouldFlush =- opts?.force === true ||- !lastOutputFlushAt ||- pendingOutputProgress.at.getTime() - lastOutputFlushAt.getTime() >=- ACTIVE_RUN_OUTPUT_PROGRESS_FLUSH_INTERVAL_MS;- if (!shouldFlush) return;- await db- .update(heartbeatRuns)- .set({- lastOutputAt: pendingOutputProgress.at,- lastOutputSeq: pendingOutputProgress.seq,- lastOutputStream: pendingOutputProgress.stream,- lastOutputBytes: pendingOutputProgress.bytes,- updatedAt: new Date(),- })- .where(eq(heartbeatRuns.id, run.id));- lastOutputFlushAt = pendingOutputProgress.at;- outputProgressState.pending = null;- };try {const startedAt = run.startedAt ?? new Date();const runningWithSession = await db@@ -3502,100 +3453,8 @@ export function heartbeatService(message: "run started",});- handle = await runLogStore.begin({- companyId: run.companyId,- agentId: run.agentId,- runId,- });-- await db- .update(heartbeatRuns)- .set({- logStore: handle.store,- logRef: handle.logRef,- updatedAt: new Date(),- })- .where(eq(heartbeatRuns.id, runId));-- const currentUserRedactionOptions =- await getCurrentUserRedactionOptions();- const appendIdentityRedactedLog = async (stream: "stdout" | "stderr", chunk: string) => {- const sanitizedChunk = compactRunLogChunk(- redactCurrentUserText(chunk, currentUserRedactionOptions),- );- if (stream === "stdout")- stdoutExcerpt = appendExcerpt(stdoutExcerpt, sanitizedChunk);- if (stream === "stderr")- stderrExcerpt = appendExcerpt(stderrExcerpt, sanitizedChunk);- const ts = new Date().toISOString();-- outputSeq += 1;- const chunkSeq = outputSeq;- let appendedBytes = 0;- if (handle) {- appendedBytes = await runLogStore.append(handle, {- stream,- chunk: sanitizedChunk,- ts,- seq: chunkSeq,- });- persistedLogBytes += appendedBytes;- }- outputProgressState.pending = {- at: new Date(ts),- seq: chunkSeq,- stream,- bytes: persistedLogBytes,- };- await flushOutputProgress();-- // Streamed CLI output is real run activity: keep the in-memory- // runtime status ("Working... / X ago") fresh between structured- // events so sandbox runs with mid-run log streaming never show a- // minutes-stale timestamp. Throttled to avoid churning the live- // event stream on every 250ms tail chunk.- const logActivityAt = new Date(ts);- if (- isHeartbeatRunRuntimeStatusActive(run.status) &&- logActivityAt.getTime() - lastLogRuntimeStatusTouchMs >=- ACTIVE_RUN_LOG_RUNTIME_STATUS_REFRESH_INTERVAL_MS- ) {- lastLogRuntimeStatusTouchMs = logActivityAt.getTime();- const touchedStatus = touchHeartbeatRunRuntimeStatus({- companyId: run.companyId,- issueId,- agentId: run.agentId,- runId: run.id,- at: logActivityAt,- });- if (touchedStatus)- publishHeartbeatRunRuntimeProgress(touchedStatus);- }-- const payloadChunk =- sanitizedChunk.length > MAX_LIVE_LOG_CHUNK_BYTES- ? sanitizedChunk.slice(- sanitizedChunk.length - MAX_LIVE_LOG_CHUNK_BYTES,- )- : sanitizedChunk;-- publishLiveEvent({- companyId: run.companyId,- type: "heartbeat.run.log",- payload: {- runId: run.id,- agentId: run.agentId,- issueId,- ts,- seq: chunkSeq,- stream,- chunk: payloadChunk,- truncated: payloadChunk.length !== sanitizedChunk.length,- },- });- };- const onLog = (stream: "stdout" | "stderr", chunk: string) =>- appendIdentityRedactedLog(stream, identityRedactor.chunk(stream, chunk));+ const { currentUserRedactionOptions, appendIdentityRedactedLog, onLog, onAdapterMeta, onAdapterEvent } =+ await runOutput.begin(currentRun);if (runScopedMentionedSkillKeys.length > 0) {await onLog("stdout",@@ -3683,36 +3542,6 @@ export function heartbeatService();}}- const onAdapterMeta = async (meta: AdapterInvocationMeta) => {- meta = identityRedactor.redact(meta);- if (meta.env && secretKeys.size > 0) {- for (const key of secretKeys) {- if (key in meta.env) meta.env[key] = "***REDACTED***";- }- }- await appendRunEvent(currentRun, {- eventType: "adapter.invoke",- stream: "system",- level: "info",- message: "adapter invocation",- payload: meta as unknown as Record<string, unknown>,- });- };-- const onAdapterEvent = async (event: AdapterRuntimeEvent) => {- event = identityRedactor.redact(event);- const eventType = event.eventType.trim();- if (!eventType) return;- await appendRunEvent(currentRun, {- eventType: eventType.slice(0, 120),- stream: event.stream,- level: event.level,- color: event.color,- message: event.message,- payload: event.payload,- });- };-const adapter = getServerAdapter(agent.adapterType);const durableGoalControlRun =readNonEmptyString(context.goalControlRequestId) !== null ||@@ -4101,11 +3930,7 @@ export function heartbeatService(}await runCompletion.completeRun({run, agent, issueId, issueRef, signal: executionControl.controller.signal,- output: {- handle, outputProgressState, flushOutputProgress,- get stdoutExcerpt() { return stdoutExcerpt; },- get stderrExcerpt() { return stderrExcerpt; },- },+ output: runOutput,session: { runtimeForAdapter, previousSessionParams, taskKey, configuredModel, sessionConfigMetadata },readFailureReportSecrets,adapterResult, sessionCodec, taskSessionForRun, sessionCompaction,@@ -4236,11 +4061,7 @@ export function heartbeatService(}await runCompletion.failRun({run, agent, issueId, issueRef, signal: executionControl.controller.signal,- output: {- handle, outputProgressState, flushOutputProgress,- get stdoutExcerpt() { return stdoutExcerpt; },- get stderrExcerpt() { return stderrExcerpt; },- },+ output: runOutput,session: { runtimeForAdapter, previousSessionParams, taskKey, configuredModel, sessionConfigMetadata },readFailureReportSecrets,runId, err, identityRedactor, requiredWorkspaceRestoreEvidence, legacyAdapterEntered,diff --git a/server/src/services/heartbeat/run-output.ts b/server/src/services/heartbeat/run-output.tsnew file mode 100644index 0000000000..249db52646--- /dev/null+++ b/server/src/services/heartbeat/run-output.ts@@ -0,0 +1,209 @@+import { eq } from "drizzle-orm";+import { heartbeatRuns, type Db } from "@paperclipai/db";+import type { AdapterInvocationMeta, AdapterRuntimeEvent } from "../../adapters/index.js";+import { redactCurrentUserText, type CurrentUserRedactionOptions } from "../../log-redaction.js";+import type { createAgentIdentityRedactor } from "../agent-identity-redaction.js";+import { touchHeartbeatRunRuntimeStatus } from "../heartbeat-run-runtime-status.js";+import { publishLiveEvent } from "../live-events.js";+import type { RunLogHandle, RunLogStore } from "../run-log-store.js";+import { appendExcerpt, compactRunLogChunk } from "./run-log.js";+import { isHeartbeatRunRuntimeStatusActive, publishHeartbeatRunRuntimeProgress, type createHeartbeatLifecycle } from "./run-lifecycle.js";++const MAX_LIVE_LOG_CHUNK_BYTES = 8 * 1024;+export const ACTIVE_RUN_OUTPUT_PROGRESS_FLUSH_INTERVAL_MS = 60 * 1000;+export const ACTIVE_RUN_LOG_RUNTIME_STATUS_REFRESH_INTERVAL_MS = 5 * 1000;++type Run = typeof heartbeatRuns.$inferSelect;++export interface HeartbeatRunOutputInput {+ run: Run;+ runId: string;+ issueId: string | null;+ runLogStore: Pick<RunLogStore, "begin" | "append">;+ identityRedactor: Pick<ReturnType<typeof createAgentIdentityRedactor>, "chunk" | "redact">;+ secretKeys: Set<string>;+ appendRunEvent: ReturnType<typeof createHeartbeatLifecycle>["appendRunEvent"];+ getCurrentUserRedactionOptions: () => Promise<CurrentUserRedactionOptions>;+}++/** One recorder per execution attempt; the log store itself stays service-scoped. */+export function createHeartbeatRunOutput(db: Db, input: HeartbeatRunOutputInput) {+ const { run, runId, issueId, runLogStore, identityRedactor, secretKeys, appendRunEvent, getCurrentUserRedactionOptions } = input;+ let handle: RunLogHandle | null = null;+ let stdoutExcerpt = "";+ let stderrExcerpt = "";+ let outputSeq = Number(run.lastOutputSeq ?? 0);+ let lastOutputFlushAt: Date | null = run.lastOutputAt ?? null;+ let lastLogRuntimeStatusTouchMs = 0;+ const outputProgressState: {+ pending: {+ at: Date;+ seq: number;+ stream: "stdout" | "stderr";+ bytes: number;+ } | null;+ } = { pending: null };+ let persistedLogBytes = Number(run.logBytes ?? 0);+ const flushOutputProgress = async (opts?: { force?: boolean }) => {+ const pendingOutputProgress = outputProgressState.pending;+ if (!pendingOutputProgress) return;+ const shouldFlush =+ opts?.force === true ||+ !lastOutputFlushAt ||+ pendingOutputProgress.at.getTime() - lastOutputFlushAt.getTime() >=+ ACTIVE_RUN_OUTPUT_PROGRESS_FLUSH_INTERVAL_MS;+ if (!shouldFlush) return;+ await db+ .update(heartbeatRuns)+ .set({+ lastOutputAt: pendingOutputProgress.at,+ lastOutputSeq: pendingOutputProgress.seq,+ lastOutputStream: pendingOutputProgress.stream,+ lastOutputBytes: pendingOutputProgress.bytes,+ updatedAt: new Date(),+ })+ .where(eq(heartbeatRuns.id, run.id));+ lastOutputFlushAt = pendingOutputProgress.at;+ outputProgressState.pending = null;+ };+ // Bind handlers to the run row persisted at execution start. Progress writes+ // above use only the immutable run ID from the initial row.+ async function begin(currentRun: Run) {+ const run = currentRun;+ handle = await runLogStore.begin({+ companyId: run.companyId,+ agentId: run.agentId,+ runId,+ });++ await db+ .update(heartbeatRuns)+ .set({+ logStore: handle.store,+ logRef: handle.logRef,+ updatedAt: new Date(),+ })+ .where(eq(heartbeatRuns.id, runId));++ const currentUserRedactionOptions =+ await getCurrentUserRedactionOptions();+ const appendIdentityRedactedLog = async (stream: "stdout" | "stderr", chunk: string) => {+ const sanitizedChunk = compactRunLogChunk(+ redactCurrentUserText(chunk, currentUserRedactionOptions),+ );+ if (stream === "stdout")+ stdoutExcerpt = appendExcerpt(stdoutExcerpt, sanitizedChunk);+ if (stream === "stderr")+ stderrExcerpt = appendExcerpt(stderrExcerpt, sanitizedChunk);+ const ts = new Date().toISOString();++ outputSeq += 1;+ const chunkSeq = outputSeq;+ let appendedBytes = 0;+ if (handle) {+ appendedBytes = await runLogStore.append(handle, {+ stream,+ chunk: sanitizedChunk,+ ts,+ seq: chunkSeq,+ });+ persistedLogBytes += appendedBytes;+ }+ outputProgressState.pending = {+ at: new Date(ts),+ seq: chunkSeq,+ stream,+ bytes: persistedLogBytes,+ };+ await flushOutputProgress();++ // Streamed CLI output is real run activity: keep the in-memory+ // runtime status ("Working... / X ago") fresh between structured+ // events so sandbox runs with mid-run log streaming never show a+ // minutes-stale timestamp. Throttled to avoid churning the live+ // event stream on every 250ms tail chunk.+ const logActivityAt = new Date(ts);+ if (+ isHeartbeatRunRuntimeStatusActive(run.status) &&+ logActivityAt.getTime() - lastLogRuntimeStatusTouchMs >=+ ACTIVE_RUN_LOG_RUNTIME_STATUS_REFRESH_INTERVAL_MS+ ) {+ lastLogRuntimeStatusTouchMs = logActivityAt.getTime();+ const touchedStatus = touchHeartbeatRunRuntimeStatus({+ companyId: run.companyId,+ issueId,+ agentId: run.agentId,+ runId: run.id,+ at: logActivityAt,+ });+ if (touchedStatus)+ publishHeartbeatRunRuntimeProgress(touchedStatus);+ }++ const payloadChunk =+ sanitizedChunk.length > MAX_LIVE_LOG_CHUNK_BYTES+ ? sanitizedChunk.slice(+ sanitizedChunk.length - MAX_LIVE_LOG_CHUNK_BYTES,+ )+ : sanitizedChunk;++ publishLiveEvent({+ companyId: run.companyId,+ type: "heartbeat.run.log",+ payload: {+ runId: run.id,+ agentId: run.agentId,+ issueId,+ ts,+ seq: chunkSeq,+ stream,+ chunk: payloadChunk,+ truncated: payloadChunk.length !== sanitizedChunk.length,+ },+ });+ };+ const onLog = (stream: "stdout" | "stderr", chunk: string) =>+ appendIdentityRedactedLog(stream, identityRedactor.chunk(stream, chunk));+ const onAdapterMeta = async (meta: AdapterInvocationMeta) => {+ meta = identityRedactor.redact(meta);+ if (meta.env && secretKeys.size > 0) {+ for (const key of secretKeys) {+ if (key in meta.env) meta.env[key] = "***REDACTED***";+ }+ }+ await appendRunEvent(currentRun, {+ eventType: "adapter.invoke",+ stream: "system",+ level: "info",+ message: "adapter invocation",+ payload: meta as unknown as Record<string, unknown>,+ });+ };++ const onAdapterEvent = async (event: AdapterRuntimeEvent) => {+ event = identityRedactor.redact(event);+ const eventType = event.eventType.trim();+ if (!eventType) return;+ await appendRunEvent(currentRun, {+ eventType: eventType.slice(0, 120),+ stream: event.stream,+ level: event.level,+ color: event.color,+ message: event.message,+ payload: event.payload,+ });+ };++ return { currentUserRedactionOptions, appendIdentityRedactedLog, onLog, onAdapterMeta, onAdapterEvent };+ }++ return {+ begin,+ get handle() { return handle; },+ outputProgressState,+ flushOutputProgress,+ // Finalization awaits I/O and can receive more output before persisting excerpts.+ get stdoutExcerpt() { return stdoutExcerpt; },+ get stderrExcerpt() { return stderrExcerpt; },+ };+}diff --git a/tests/e2e/workspace-bootstrap/recovery.spec.ts b/tests/e2e/workspace-bootstrap/recovery.spec.tsindex 884a20a8bd..e513615986 100644--- a/tests/e2e/workspace-bootstrap/recovery.spec.ts+++ b/tests/e2e/workspace-bootstrap/recovery.spec.ts@@ -75,6 +75,12 @@ for (const persistent of [false, true]) {// Independently confirm the configured source was never overwritten.expect(sourceCopy).toBeTruthy();expect(completed.scheduledRetryAttempt).toBe(1);+ const completedRun = await api(`/heartbeat-runs/${completed.id}`);+ const completedLog = await api(`/heartbeat-runs/${completed.id}/log`);+ expect(completedRun.stdoutExcerpt).toContain("Workspace recovery verification complete.");+ expect(completedRun.lastOutputSeq).toBeGreaterThan(0);+ expect(completedRun.lastOutputBytes).toBe(completedRun.logBytes);+ expect(completedLog.content).toContain("Workspace recovery verification complete.");expect(await readFile(path.join(fixture.source, "README.md"), "utf8")).toBe("Existing uncommitted work\n");}await page.reload();