From 14eac711e81207f783256a3a04bae4c85c4ab655 Mon Sep 17 00:00:00 2001 From: "moti.zamir" Date: Thu, 26 Nov 2026 11:07:51 +0200 Subject: [PATCH 1/2] feat(workflow): per-step transcript producer (M25 G1 #175) - recordStepTranscript: stdout + session dump, redacted at capture - 5MB/file + 20MB/ref caps with trimmed retention class - fail-soft: producer never fails the step - 6 new contract tests, 17/17 green --- src/workflow/steps/agent.mjs | 36 ++++++ src/workflow/trace.mjs | 205 +++++++++++++++++++++++++++++++++- tests/workflow-trace.test.mjs | 103 +++++++++++++++++ 3 files changed, 341 insertions(+), 3 deletions(-) diff --git a/src/workflow/steps/agent.mjs b/src/workflow/steps/agent.mjs index ebc7831b..82d76241 100644 --- a/src/workflow/steps/agent.mjs +++ b/src/workflow/steps/agent.mjs @@ -14,6 +14,21 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node import { dirname, join } from "node:path"; import { currentHeadSha } from "../gate-context.mjs"; import { redactSecrets } from "../redact.mjs"; +import { dumpAgentSession, recordStepTranscript } from "../trace.mjs"; + +export async function captureStepTranscript({ projectRoot, runId, stepId, stdout, sessionDump } = {}) { + try { + if (!projectRoot || !runId || !stepId) return { ok: true, skipped: true }; + const runDir = join(projectRoot, ".adlc", "workflows", "runs", runId); + const dump = + typeof sessionDump === "function" + ? sessionDump + : async () => dumpAgentSession(process.env.ADLC_AGENT_SESSION_ID ?? null); + return await recordStepTranscript(runDir, stepId, { stdout: stdout ?? "", sessionDump: dump }); + } catch { + return { ok: true, skipped: true }; + } +} const rid = (config) => `'${config.id ?? "?"}'`; @@ -155,6 +170,7 @@ async function runAgentStep({ agentKey, model, mode, prompt, context, config, ti if (process.listenerCount("SIGINT") > 0 && exit.signal === "SIGINT") { output.interrupted = true; + await emitStepTranscript(context, config, output); return new StepResult({ status: StepStatus.FAILED, error: `Agent step ${rid(config)} interrupted (SIGINT).`, @@ -173,6 +189,7 @@ async function runAgentStep({ agentKey, model, mode, prompt, context, config, ti // elapsed but no fast_failure mark. const agentElapsedSeconds = Number(process.hrtime.bigint() - spawnedAt) / 1e9; output.agent_elapsed_seconds = Math.round(agentElapsedSeconds * 10) / 10; + await emitStepTranscript(context, config, output); return new StepResult({ status: StepStatus.FAILED, error: @@ -192,6 +209,7 @@ async function runAgentStep({ agentKey, model, mode, prompt, context, config, ti const fastFailure = !timedOut && agentElapsedSeconds < fastFailureThresholdSeconds(); output.agent_elapsed_seconds = Math.round(agentElapsedSeconds * 10) / 10; if (fastFailure) output.fast_failure = true; + await emitStepTranscript(context, config, output); return new StepResult({ status: StepStatus.FAILED, error: @@ -213,6 +231,7 @@ async function runAgentStep({ agentKey, model, mode, prompt, context, config, ti // the whole object, and the refusal must still end the run (fail closed). const blocked = readBlockedConclusion(runEnv.ADLC_STEP_OUTPUT); if (blocked !== null) { + await emitStepTranscript(context, config, output); return new StepResult({ status: StepStatus.FAILED, // Agent-written text: redact secrets with the env the agent ran with, @@ -251,6 +270,7 @@ async function runAgentStep({ agentKey, model, mode, prompt, context, config, ti console.error(`[workflow] step ${rid(config)}: question payload ignored (${question.why})`); output.question_warning = `question payload ignored: ${question.why}`; } + await emitStepTranscript(context, config, output); return new StepResult({ status: StepStatus.COMPLETED, output }); } @@ -448,6 +468,22 @@ export function runContextEnv(context, config) { return env; } +// Post-step transcript capture (ADR-548, fail-soft): runs at every agent-step +// exit point after `output` is final. Never throws, never changes the result. +async function emitStepTranscript(context, config, output) { + try { + const stepId = typeof config.id === "string" ? config.id : null; + const runId = typeof context.runId === "string" ? context.runId : null; + if (!stepId || !runId || !context.projectRoot) return; + await captureStepTranscript({ + projectRoot: context.projectRoot, + runId, + stepId, + stdout: output?.stdout ?? "", + }); + } catch {} +} + // The step's structured result: a flat object of short strings, merged only // when every entry is valid — otherwise nothing (and a log line). The values // are untrusted; renderers sanitise them (links: safeMrLink). diff --git a/src/workflow/trace.mjs b/src/workflow/trace.mjs index a16e5605..f8d5e829 100644 --- a/src/workflow/trace.mjs +++ b/src/workflow/trace.mjs @@ -10,18 +10,23 @@ // enters the trace passes through the shared text redactor first. Writes are // fail-soft at the call sites — telemetry never fails a run. -import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; import { isAbsolute, join } from "node:path"; import { createHash } from "node:crypto"; -import { spawnSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; +import { homedir } from "node:os"; import { RunStatus } from "./base.mjs"; import { redactSecrets } from "./redact.mjs"; import { readAgent } from "../utils/init-options.mjs"; +import { extractAssistantTexts } from "../format/audit.mjs"; import { currentHeadSha } from "./gate-context.mjs"; export const TRACE_SCHEMA_VERSION = 1; +export const TRANSCRIPT_MAX_FILE_BYTES = 5 * 1024 * 1024; +export const TRANSCRIPT_MAX_REF_BYTES = 20 * 1024 * 1024; const TRACE_DIR = "trace"; +const STEPS_DIR = "steps"; const DEFAULT_AGENT_ID = "adlc-cli"; // ADR-364 canonical event types, keyed by the run-log event name. @@ -45,6 +50,19 @@ export function tracePaths(runDir) { }; } +// Per-step transcript files (ADR-548): stdout captured on the step seam plus +// the post-step agent-session dump, both inside the run dir so they ship in +// refs/factory-runs/ via the existing ref write path. +export function transcriptPaths(runDir, stepId) { + const safe = String(stepId ?? "step").replace(/[^A-Za-z0-9._-]+/g, "_"); + return { + dir: join(runDir, STEPS_DIR), + stdoutLog: join(runDir, STEPS_DIR, `${safe}.stdout.log`), + sessionJsonl: join(runDir, STEPS_DIR, `${safe}.session.jsonl`), + safeStepId: safe, + }; +} + function nowIso() { return new Date().toISOString(); } @@ -287,6 +305,184 @@ const SHA256_RE = /^[0-9a-f]{64}$/; // Append a content-addressed artifact entry. `path` (relative to the run dir) // hashes a local file; otherwise an explicit content_sha256 is required. // Invalid input throws — callers decide whether that is fatal. +// Fail-hard cap (ADR-548): stop transcript writes past the per-file / per-ref +// budgets, mark `trimmed`, keep the run going. Per-file: any single write +// larger than TRANSCRIPT_MAX_FILE_BYTES is refused. Per-ref: the running +// total of steps/*.log + steps/*.session.jsonl past TRANSCRIPT_MAX_REF_BYTES +// stops further transcript capture. Callers stay fail-soft: always {ok:true}. +function transcriptBytesUsed(runDir) { + let total = 0; + try { + const dir = join(runDir, STEPS_DIR); + for (const name of readdirSync(dir)) { + if (!name.endsWith(".stdout.log") && !name.endsWith(".session.jsonl")) continue; + try { + total += statSync(join(dir, name)).size; + } catch {} + } + } catch {} + return total; +} + +function markTrimmed(runDir) { + try { + const paths = tracePaths(runDir); + const raw = readFileSync(paths.manifest, "utf-8"); + const doc = JSON.parse(raw); + if (doc.retention_class === "trimmed") return; + doc.retention_class = "trimmed"; + doc.trace_pruned = false; + writeFileSync(paths.manifest, JSON.stringify(doc, null, 2) + "\n"); + try { + const arts = JSON.parse(readFileSync(paths.artifacts, "utf-8")); + arts.retention_class = "trimmed"; + writeFileSync(paths.artifacts, JSON.stringify(arts, null, 2) + "\n"); + } catch {} + } catch {} +} + +// Opencode session dump scoped by ADLC_AGENT_SESSION_ID (plan step seam): +// rows come from the session store; only assistant texts are kept, via the +// existing audit.mjs extractor. Fail-soft — any store error yields []. +export async function dumpAgentSession(sessionId, { query = defaultSessionQuery, dbPath } = {}) { + if (!sessionId) return []; + let rows; + try { + rows = await query(dbPath, sessionId); + } catch { + return []; + } + const out = []; + for (const row of rows ?? []) { + for (const text of extractAssistantTexts(row)) out.push({ text }); + } + return out; +} + +// Default opencode sqlite lookup: session_message rows for one session id. +// dbPath defaults to the well-known local store location. +function defaultSessionQuery(dbPath, sessionId) { + const resolved = + dbPath ?? + join(homedir() ?? "~", ".local", "share", "opencode", "opencode.db"); + const sql = `SELECT data FROM session_message WHERE session_id = '${String(sessionId).replace(/'/g, "''")}' AND type = 'assistant' ORDER BY seq ASC LIMIT 4000`; + let raw; + try { + raw = execFileSync("sqlite3", ["-json", resolved, sql], { encoding: "utf-8" }); + } catch { + return []; + } + if (!raw.trim()) return []; + let parsed; + try { + parsed = JSON.parse(raw); + } catch { + return []; + } + return (Array.isArray(parsed) ? parsed : []).map((r) => { + try { + return JSON.parse(r.data); + } catch { + return null; + } + }).filter(Boolean); +} + +// Per-step transcript producer (ADR-548, post-step cadence): capture-time +// redacted stdout + session dump into steps/.{stdout.log,session.jsonl} +// and index both in trace/artifacts.json with git-ref:// URIs. Fail-soft: +// every failure path returns {ok:true} (with capped/skipped flags) so a +// producer failure never fails the step or run. No S3 changes (ref-first). +export async function recordStepTranscript(runDir, stepId, { stdout = "", sessionDump = null } = {}) { + try { + const paths = transcriptPaths(runDir, stepId); + const manifestNow = (() => { + try { + return JSON.parse(readFileSync(tracePaths(runDir).manifest, "utf-8")); + } catch { + return null; + } + })(); + if (manifestNow?.retention_class === "trimmed") return { ok: true, skipped: true }; + if (transcriptBytesUsed(runDir) >= TRANSCRIPT_MAX_REF_BYTES) { + markTrimmed(runDir); + return { ok: true, skipped: true }; + } + const cleanStdout = String(stdout ?? ""); + if (Buffer.byteLength(cleanStdout, "utf-8") > TRANSCRIPT_MAX_FILE_BYTES) { + markTrimmed(runDir); + return { ok: true, skipped: true, capped: true }; + } + mkdirSync(paths.dir, { recursive: true }); + // Capture-time redaction (ADR-478): secrets never enter the ref even + // transiently. A redactor failure stops capture, never the step. + let redStdout; + try { + redStdout = redactDeep(cleanStdout); + } catch { + return { ok: true, skipped: true }; + } + try { + const projected = transcriptBytesUsed(runDir) + Buffer.byteLength(redStdout, "utf-8"); + if (projected > TRANSCRIPT_MAX_REF_BYTES) { + markTrimmed(runDir); + return { ok: true, skipped: true, capped: true }; + } + writeFileSync(paths.stdoutLog, redStdout); + } catch { + return { ok: true, skipped: true }; + } + // Session leg: failures write an empty file, never fail the step. + let rows = []; + if (typeof sessionDump === "function") { + try { + rows = (await sessionDump()) ?? []; + } catch { + rows = []; + } + } + let sessionText = ""; + try { + const lines = []; + for (const row of rows) { + const texts = + row && typeof row === "object" && "text" in row + ? [row.text] + : extractAssistantTexts(row); + for (const t of texts) { + if (typeof t === "string" && t) lines.push(JSON.stringify({ text: redactDeep(t) })); + } + } + sessionText = lines.length ? lines.join("\n") + "\n" : ""; + } catch { + sessionText = ""; + } + try { + if (Buffer.byteLength(sessionText, "utf-8") > TRANSCRIPT_MAX_FILE_BYTES) { + markTrimmed(runDir); + rmSync(paths.stdoutLog, { force: true }); + return { ok: true, skipped: true, capped: true }; + } + const projected = transcriptBytesUsed(runDir) + Buffer.byteLength(sessionText, "utf-8"); + if (projected > TRANSCRIPT_MAX_REF_BYTES) { + markTrimmed(runDir); + return { ok: true, skipped: true, capped: true }; + } + writeFileSync(paths.sessionJsonl, sessionText); + } catch { + return { ok: true, skipped: true }; + } + // Index both files (dedup by path: re-runs overwrite, never duplicate). + try { + recordArtifact(runDir, { path: `steps/${paths.safeStepId}.stdout.log`, media_type: "text/plain", storage_uri: `git-ref://steps/${paths.safeStepId}.stdout.log`, retention_class: "transcript", sensitivity: "redacted", producing_event: "step_completed" }); + recordArtifact(runDir, { path: `steps/${paths.safeStepId}.session.jsonl`, media_type: "application/jsonl", storage_uri: `git-ref://steps/${paths.safeStepId}.session.jsonl`, retention_class: "transcript", sensitivity: "redacted", producing_event: "step_completed" }); + } catch {} + return { ok: true }; + } catch { + return { ok: true, skipped: true }; + } +} + export function recordArtifact(runDir, artifact = {}) { const paths = tracePaths(runDir); mkdirSync(paths.dir, { recursive: true }); @@ -327,7 +523,10 @@ export function recordArtifact(runDir, artifact = {}) { } entry.created_at = nowIso(); - doc.artifacts.push(redactDeep(entry)); + const redacted = redactDeep(entry); + const prior = doc.artifacts.findIndex((a) => a && a.path === redacted.path); + if (prior >= 0) doc.artifacts[prior] = redacted; + else doc.artifacts.push(redacted); writeJson(paths.artifacts, doc); return entry; } diff --git a/tests/workflow-trace.test.mjs b/tests/workflow-trace.test.mjs index 29a19821..8a263103 100644 --- a/tests/workflow-trace.test.mjs +++ b/tests/workflow-trace.test.mjs @@ -450,3 +450,106 @@ test("I-2: finalize refreshes manifest head_sha when steps moved the repo HEAD", assert.equal(after.repository.head_sha, movedSha, "finalize must record the post-step revision"); assert.equal(after.repository.run_start_sha, startSha, "run_start_sha keeps the run-start revision"); }); + +// ── M25 G1 transcript producer contract (RED: producer missing) ────────── + +test("G1: recordStepTranscript writes redacted per-step files + git-ref artifacts", async () => { + const { recordStepTranscript, transcriptPaths } = await import("../src/workflow/trace.mjs"); + const dir = tempDir("g1-transcript-"); + const runDirPath = runDir(dir, "t1"); + mkdirSync(runDirPath, { recursive: true }); + const res = await withEnv("SEEDED_TRANSCRIPT_SECRET", "glpat-SEEDgabriel0011223344", async () => + recordStepTranscript(runDirPath, "stepA", { + stdout: "hello glpat-SEEDgabriel0011223344 world\n", + sessionDump: async () => [{ role: "assistant", content: "echo glpat-SEEDgabriel0011223344 ok" }], + }), + ); + assert.equal(res.ok, true); + const paths = transcriptPaths(runDirPath, "stepA"); + assert.ok(!readFileSync(paths.stdoutLog, "utf-8").includes("glpat-SEEDgabriel0011223344"), "secret redacted from stdout.log"); + assert.ok(!readFileSync(paths.sessionJsonl, "utf-8").includes("glpat-SEEDgabriel0011223344"), "secret redacted from session.jsonl"); + const doc = readJson(tracePaths(runDirPath).artifacts); + assert.ok(doc.artifacts.some((a) => a.path === "steps/stepA.stdout.log" && a.storage_uri.startsWith("git-ref://"))); + assert.ok(doc.artifacts.some((a) => a.path === "steps/stepA.session.jsonl" && a.storage_uri.startsWith("git-ref://"))); +}); + +test("G1: producer is fail-soft — dump failure still writes stdout", async () => { + const { recordStepTranscript, transcriptPaths } = await import("../src/workflow/trace.mjs"); + const dir = tempDir("g1-failsoft-"); + const runDirPath = runDir(dir, "t2"); + mkdirSync(runDirPath, { recursive: true }); + const res = await recordStepTranscript(runDirPath, "stepB", { + stdout: "partial output\n", + sessionDump: async () => { throw new Error("db gone"); }, + }); + assert.equal(res.ok, true); + assert.ok(existsSync(transcriptPaths(runDirPath, "stepB").stdoutLog)); +}); + +test("G1: transcript cap marks trimmed and skips later files without failing run", async () => { + const { initTrace, finalizeTrace, recordStepTranscript, transcriptPaths, TRANSCRIPT_MAX_FILE_BYTES } = + await import("../src/workflow/trace.mjs"); + const dir = tempDir("g1-cap-"); + const runDirPath = runDir(dir, "t3"); + mkdirSync(runDirPath, { recursive: true }); + initTrace(runDirPath, { state: { runId: "t3", workflowId: "w", status: "running", projectRoot: dir } }); + const res = await recordStepTranscript(runDirPath, "stepBig", { stdout: "x".repeat(TRANSCRIPT_MAX_FILE_BYTES + 16) }); + assert.equal(res.ok, true); + assert.equal(res.capped ?? res.skipped, true); + assert.equal(readJson(tracePaths(runDirPath).manifest).retention_class, "trimmed"); + const res2 = await recordStepTranscript(runDirPath, "stepAfter", { stdout: "small\n" }); + assert.equal(res2.ok, true); + assert.equal(res2.skipped, true); + assert.ok(!existsSync(transcriptPaths(runDirPath, "stepAfter").stdoutLog)); +}); + +test("G1: retention keeps full transcripts on failure, manifest-only on unsampled success", async () => { + const { initTrace, finalizeTrace, recordStepTranscript } = await import("../src/workflow/trace.mjs"); + const dir = tempDir("g1-retain-"); + // Failed run: finalize keeps everything. + const failRun = runDir(dir, "t4fail"); + mkdirSync(failRun, { recursive: true }); + initTrace(failRun, { state: { runId: "t4fail", workflowId: "w", status: "running", projectRoot: dir } }); + await recordStepTranscript(failRun, "s1", { stdout: "out\n" }); + finalizeTrace(failRun, { status: "failed", projectRoot: dir }); + assert.ok(existsSync(join(failRun, "steps", "s1.stdout.log")), "failed run keeps full transcripts"); + // Completed unsampled run: events prune, transcripts already captured stay. + const okRun = runDir(dir, "t4ok"); + mkdirSync(okRun, { recursive: true }); + initTrace(okRun, { state: { runId: "t4ok", workflowId: "w", status: "running", projectRoot: dir } }); + await recordStepTranscript(okRun, "s1", { stdout: "out\n" }); + finalizeTrace(okRun, { status: "completed", projectRoot: dir }); + const man = readJson(tracePaths(okRun).manifest); + assert.equal(man.retention_class, "manifest-only"); + assert.ok(!existsSync(tracePaths(okRun).events), "unsampled success prunes events"); + assert.ok(existsSync(join(okRun, "steps", "s1.stdout.log")), "unsampled success keeps captured transcripts"); +}); + +test("G1: dumpAgentSession scopes the sqlite query by ADLC_AGENT_SESSION_ID", async () => { + const { dumpAgentSession } = await import("../src/workflow/trace.mjs"); + const calls = []; + const rows = await dumpAgentSession("sess-9", { + query: async (dbPath, sessionId) => { + calls.push([dbPath, sessionId]); + return [{ type: "assistant", content: [{ type: "text", text: "hi" }] }]; + }, + }); + assert.deepEqual(calls.map((c) => c[1]), ["sess-9"]); + assert.equal(rows.length, 1); + assert.equal(rows[0].text, "hi"); +}); + +test("G1: re-recorded transcript overwrites artifact index entry instead of duplicating", async () => { + const { recordStepTranscript } = await import("../src/workflow/trace.mjs"); + const dir = tempDir("g1-dedup-"); + const runDirPath = runDir(dir, "t5"); + mkdirSync(runDirPath, { recursive: true }); + await recordStepTranscript(runDirPath, "s1", { stdout: "first\n" }); + await recordStepTranscript(runDirPath, "s1", { stdout: "second\n" }); + const paths_for = tracePaths(runDirPath); + const entries = readJson(paths_for.artifacts).artifacts.filter( + (a) => a.path === "steps/s1.stdout.log", + ); + assert.equal(entries.length, 1); + assert.equal(readFileSync(join(runDirPath, "steps", "s1.stdout.log"), "utf-8"), "second\n"); +}); From 668912ff8a0c3a559a35accb8c13a96d8435d852 Mon Sep 17 00:00:00 2001 From: "moti.zamir" Date: Thu, 26 Nov 2026 12:11:16 +0200 Subject: [PATCH 2/2] fix(workflow): keep stdout on session-oversize, use writeJson in markTrimmed --- src/workflow/trace.mjs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/workflow/trace.mjs b/src/workflow/trace.mjs index f8d5e829..7c35ce38 100644 --- a/src/workflow/trace.mjs +++ b/src/workflow/trace.mjs @@ -332,11 +332,11 @@ function markTrimmed(runDir) { if (doc.retention_class === "trimmed") return; doc.retention_class = "trimmed"; doc.trace_pruned = false; - writeFileSync(paths.manifest, JSON.stringify(doc, null, 2) + "\n"); + writeJson(paths.manifest, doc); try { const arts = JSON.parse(readFileSync(paths.artifacts, "utf-8")); arts.retention_class = "trimmed"; - writeFileSync(paths.artifacts, JSON.stringify(arts, null, 2) + "\n"); + writeJson(paths.artifacts, arts); } catch {} } catch {} } @@ -459,8 +459,9 @@ export async function recordStepTranscript(runDir, stepId, { stdout = "", sessio } try { if (Buffer.byteLength(sessionText, "utf-8") > TRANSCRIPT_MAX_FILE_BYTES) { + // Fail-hard per ADR-548: stop capture, mark trimmed. Keep the + // already-written stdout leg — one oversize leg must not nuke both. markTrimmed(runDir); - rmSync(paths.stdoutLog, { force: true }); return { ok: true, skipped: true, capped: true }; } const projected = transcriptBytesUsed(runDir) + Buffer.byteLength(sessionText, "utf-8");