From a9f8541f290a12b0e827f88e326cbc7f63021ccf Mon Sep 17 00:00:00 2001 From: itai Date: Mon, 23 Nov 2026 16:16:23 +0200 Subject: [PATCH 1/5] feat(workflow): `workflow summary ` end-of-run message adlc-workspace#66: a run that ended left no message saying how it ended or which MR/PR it opened; since the lane has no completion gate, #151's thread never showed adlc-workspace!166. `adlc-cli workflow summary [--json]` builds one message from the run's own files (state.json, inputs.json, log.jsonl, trace events): the outcome and duration, the failing step and its error (the step with its own error, not an `if` around a rejected gate), every MR/PR link of every step, the conclusion (execute's wins), each gate's answer and who gave it, one line per step, and resumes. Step text is redacted, one line and capped; the whole text fits one chat message. No network. A gate that takes its verdict from an input now records `answered_by` from ADLC_ANSWERED_BY (a plain id only), so the summary can name the approver. Refs adlc-workspace#66 Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + src/commands/workflow.mjs | 28 ++++ src/dispatch.mjs | 1 + src/help.mjs | 1 + src/workflow/steps/gate.mjs | 6 + src/workflow/summary.mjs | 194 ++++++++++++++++++++++ tests/workflow-summary.test.mjs | 278 ++++++++++++++++++++++++++++++++ 7 files changed, 509 insertions(+) create mode 100644 src/workflow/summary.mjs create mode 100644 tests/workflow-summary.test.mjs diff --git a/README.md b/README.md index 2361b220..f4c1e4e0 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,7 @@ The live SSH transport is the default: `--provider coder` provisions or reuses a | `workflow run ` | Execute a workflow — YAML path, installed ID, or built-in (`factory` = the outer loop) | | `workflow resume ` | Resume a paused/failed run; gates re-prompt (or bind a `verdict_input` via `--input`) | | `workflow status [run_id]` | List runs / show one run's step states | +| `workflow summary [--json]` | One end-of-run message from the run's files: outcome and duration, the failing step and its error, every MR/PR link (`mr_url`/`mr_urls`), the conclusion, each gate's answer and who gave it (`answered_by`, from `ADLC_ANSWERED_BY` when a relay resumes the gate), one line per step, and resumes. Redacted and capped to fit one chat message; no network calls | | `workflow validate ` | Validate a definition; `--headless` requires gates to declare `verdict_input` | | `workflow state …` | LLM-executor helpers: `start/advance/pause/fail/show` (ADR-395) | diff --git a/src/commands/workflow.mjs b/src/commands/workflow.mjs index eeaeaea9..4d2735be 100644 --- a/src/commands/workflow.mjs +++ b/src/commands/workflow.mjs @@ -51,6 +51,8 @@ import { ACCENT, } from "../ui/index.mjs"; +import { buildRunSummary } from "../workflow/summary.mjs"; + const RUNS_DIR = ".adlc/workflows/runs"; export async function cmdWorkflow(args, flags, rawArgv) { @@ -63,6 +65,8 @@ export async function cmdWorkflow(args, flags, rawArgv) { return cmdWorkflowResume(rest, rawArgv); case "status": return cmdWorkflowStatus(rest); + case "summary": + return cmdWorkflowSummary(rest, rawArgv); case "validate": return cmdWorkflowValidate(rest, rawArgv); case "state": @@ -676,6 +680,30 @@ function statusCell(status) { return combine(style(glyph, color ?? "gray"), " ", status); } +// ── summary ────────────────────────────────────────────────────────────── +// One end-of-run message built from the run's files (adlc-workspace#66): the +// outcome, the failing step, every MR/PR link, the conclusion, the gate +// answers and who gave them, one line per step. `--json` prints the object. + +function cmdWorkflowSummary(rest, rawArgv = []) { + const runId = rest.find((a) => !a.startsWith("-")); + if (!runId || !/^[A-Za-z0-9._-]{1,128}$/.test(runId)) { + err(tint("Usage: adlc-cli workflow summary [--json]", "gray")); + return 1; + } + const summary = buildRunSummary(join(process.cwd(), RUNS_DIR, runId)); + if (summary === null) { + error(`Run state not found: ${join(RUNS_DIR, runId, "state.json")}`); + return 1; + } + if ((rawArgv ?? []).includes("--json") || rest.includes("--json")) { + console.log(JSON.stringify(summary)); + } else { + console.log(summary.text); + } + return 0; +} + function loadStateRaw(runId, projectRoot) { const path = join(projectRoot, RUNS_DIR, runId, "state.json"); if (!existsSync(path)) { diff --git a/src/dispatch.mjs b/src/dispatch.mjs index fab8da9a..a6d7f617 100644 --- a/src/dispatch.mjs +++ b/src/dispatch.mjs @@ -231,6 +231,7 @@ async function runNewTree({ command, args, flags }, argv) { case "run": case "resume": case "status": + case "summary": case "validate": case "state": case "park": diff --git a/src/help.mjs b/src/help.mjs index 067d38e7..e7d1cbb5 100644 --- a/src/help.mjs +++ b/src/help.mjs @@ -79,6 +79,7 @@ export function printCliHelp() { ["workflow restore ", "Restore a parked run from the remote run ref"], ["workflow board [--remote ]", "Pane of glass: local runs + remote refs/factory-runs/* (--format json)"], ["workflow status [run_id]", "List runs / show one run's step states"], + ["workflow summary [--json]", "One end-of-run message: outcome, MR/PR links, gates, steps"], ["workflow validate ", "Validate a workflow definition (--headless checks gate verdicts)"], ["workflow search [query]", "Search available workflows in catalog"], ["workflow add [--as ]", "Install a workflow from catalog or URL into workspace"], diff --git a/src/workflow/steps/gate.mjs b/src/workflow/steps/gate.mjs index 75afdbb5..b8efb1a3 100644 --- a/src/workflow/steps/gate.mjs +++ b/src/workflow/steps/gate.mjs @@ -302,6 +302,10 @@ export class GateStep extends StepBase { return new StepResult({ status: StepStatus.PAUSED, output }); } + // A verdict that came in through the run's inputs (a relay such as the + // agentic-container runtime) records who gave it, from ADLC_ANSWERED_BY: + // a plain id only (adlc-workspace#66, the end-of-run summary). + const fromInput = choice !== null && choice !== undefined; if (choice === null || choice === undefined) { // Non-interactive: pause for later resume (the file is not read here). if (!process.stdin.isTTY) { @@ -316,6 +320,8 @@ export class GateStep extends StepBase { ); } output.choice = choice; + const answeredBy = (process.env.ADLC_ANSWERED_BY ?? "").trim(); + if (fromInput && /^[A-Za-z0-9._@-]{1,64}$/.test(answeredBy)) output.answered_by = answeredBy; // Match rejection case-insensitively, agreeing with validate(). if (isRejection(choice)) { diff --git a/src/workflow/summary.mjs b/src/workflow/summary.mjs new file mode 100644 index 00000000..6d936fe4 --- /dev/null +++ b/src/workflow/summary.mjs @@ -0,0 +1,194 @@ +// End-of-run summary (adlc-workspace#66). +// +// One message that says how a run ended, built only from the run's own files +// (.adlc/workflows/runs//state.json, inputs.json, log.jsonl and the +// trace events). The engine makes no network call here (ADR-416): a runtime +// that relays runs to a chat thread forwards `text` as it is. +// +// Every string that came from a step (errors, conclusions, links, who answered +// a gate) is redacted, put on one line and capped, and the whole text is kept +// under SUMMARY_MAX_CHARS so it fits one chat message. + +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { redactSecrets } from "./redact.mjs"; +import { tracePaths } from "./trace.mjs"; + +export const SUMMARY_MAX_CHARS = 3000; +export const SUMMARY_FIELD_CHARS = 300; +export const SUMMARY_MAX_LINKS = 10; +const LINK = /^https?:\/\/[^\s<>|]{1,2040}$/i; +const ANSWERER = /^[A-Za-z0-9._@-]{1,64}$/; + +function readJson(path) { + try { + return JSON.parse(readFileSync(path, "utf-8")); + } catch { + return null; + } +} + +function readLines(path) { + if (!existsSync(path)) return []; + let raw; + try { + raw = readFileSync(path, "utf-8"); + } catch { + return []; + } + const out = []; + for (const line of raw.split("\n")) { + if (!line.trim()) continue; + try { out.push(JSON.parse(line)); } catch {} + } + return out; +} + +/** Redacted, one line, capped. Non-strings become "". */ +export function cleanField(value, max = SUMMARY_FIELD_CHARS, env = process.env) { + if (typeof value !== "string") return ""; + const one = redactSecrets(value, env).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").replace(/\s+/g, " ").trim(); + return one.length > max ? one.slice(0, max - 1) + "…" : one; +} + +export function formatDuration(seconds) { + if (!Number.isFinite(seconds) || seconds < 0) return ""; + const s = Math.round(seconds); + const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), r = s % 60; + if (h > 0) return `${h}h ${m}m`; + if (m > 0) return `${m}m ${r}s`; + return `${r}s`; +} + +function stepLinks(output) { + const links = []; + if (!output || typeof output !== "object") return links; + if (typeof output.mr_url === "string") links.push(output.mr_url.trim()); + if (typeof output.mr_urls === "string") links.push(...output.mr_urls.split(/[\s,]+/)); + return links.filter((l) => LINK.test(l)); +} + +/** + * Build the summary of one run from its directory. Returns null when the run + * has no readable state.json. + */ +export function buildRunSummary(runDir, { env = process.env } = {}) { + const state = readJson(join(runDir, "state.json")); + if (!state || typeof state !== "object") return null; + const inputs = (readJson(join(runDir, "inputs.json")) ?? {}).inputs ?? {}; + const log = readLines(join(runDir, "log.jsonl")); + const trace = readLines(tracePaths(runDir).events); + const results = state.step_results && typeof state.step_results === "object" ? state.step_results : {}; + + // Step order: as the run started them (log.jsonl), then any result the log + // does not name, in state order. + const types = {}; + const order = []; + for (const e of log) { + if (e?.event === "step_started" && typeof e.step_id === "string") { + if (!order.includes(e.step_id)) order.push(e.step_id); + if (typeof e.type === "string") types[e.step_id] = e.type; + } + } + for (const id of Object.keys(results)) if (!order.includes(id)) order.push(id); + + const steps = []; + const gates = []; + const links = []; + let conclusion = ""; + let conclusionStep = null; + let failed = null; + for (const id of order) { + const r = results[id]; + if (!r || typeof r !== "object") continue; + const output = r.output && typeof r.output === "object" ? r.output : {}; + const step = { id: cleanField(id, 80, env), status: typeof r.status === "string" ? r.status : "unknown" }; + if (types[id]) step.type = types[id]; + steps.push(step); + if (typeof output.choice === "string") { + const gate = { id: step.id, choice: cleanField(output.choice, 40, env) }; + if (typeof output.answered_by === "string" && ANSWERER.test(output.answered_by)) gate.answered_by = output.answered_by; + if (output.auto_passed === true) gate.auto = true; + gates.push(gate); + } + for (const l of stepLinks(output)) { + const c = cleanField(l, 2048, env); + if (LINK.test(c) && !links.includes(c)) links.push(c); + } + if (typeof output.conclusion === "string" && output.conclusion.trim()) { + // The execute step's conclusion wins; otherwise the last one. + if (conclusionStep !== "execute") { + conclusion = cleanField(output.conclusion, SUMMARY_FIELD_CHARS, env); + conclusionStep = id; + } + } + // The step that failed: the first failed one with its own error (an `if` + // or loop around a rejected gate fails too, with no error of its own). + if (r.status === "failed" && (failed === null || (!failed.own && typeof r.error === "string" && r.error))) { + const own = typeof r.error === "string" && r.error !== ""; + failed = { id: step.id, error: cleanField(own ? r.error : (state.error ?? ""), SUMMARY_FIELD_CHARS, env), own }; + } + } + + const started = Date.parse(state.created_at ?? ""); + const ended = Date.parse(state.updated_at ?? ""); + const durationSeconds = Number.isFinite(started) && Number.isFinite(ended) && ended >= started + ? Math.round((ended - started) / 1000) : null; + const resumes = trace.filter((e) => e?.payload?.adlc?.event === "run_resumed").length; + + const summary = { + run_id: cleanField(String(state.run_id ?? ""), 80, env), + workflow_id: cleanField(String(state.workflow_id ?? ""), 80, env), + status: typeof state.status === "string" ? state.status : "unknown", + started_at: state.created_at ?? null, + ended_at: state.updated_at ?? null, + duration_seconds: durationSeconds, + issue_ref: cleanField(inputs.issue_ref, 200, env) || null, + dispatch: cleanField(inputs.dispatch, 40, env) || null, + steps, + gates, + conclusion: conclusion || null, + mr_urls: links.slice(0, SUMMARY_MAX_LINKS), + failed_step: failed ? { id: failed.id, error: failed.error } : null, + resumes, + }; + summary.text = renderSummaryText(summary); + return summary; +} + +const MARK = { completed: "✓", failed: "✗", skipped: "–", paused: "⏸", running: "…" }; + +export function renderSummaryText(s) { + const lines = []; + const head = [`*Run ${s.run_id} ${s.status}*`]; + if (s.workflow_id) head.push(s.workflow_id); + if (s.duration_seconds !== null) head.push(formatDuration(s.duration_seconds)); + lines.push(head.join(" · ")); + const who = []; + if (s.issue_ref) who.push(`Issue ${s.issue_ref}`); + if (s.dispatch) who.push(`dispatch ${s.dispatch}`); + if (who.length) lines.push(who.join(" · ")); + if (s.failed_step) lines.push(`Failed at \`${s.failed_step.id}\`${s.failed_step.error ? `: ${s.failed_step.error}` : ""}`); + if (s.mr_urls.length) { + lines.push("MR/PR:"); + for (const l of s.mr_urls) lines.push(`• ${l}`); + } else { + lines.push("MR/PR: none"); + } + if (s.conclusion) lines.push(`Conclusion: ${s.conclusion}`); + if (s.gates.length) { + lines.push("Gates:"); + for (const g of s.gates) { + const by = g.auto ? " (auto)" : g.answered_by ? ` (by ${g.answered_by})` : ""; + lines.push(`• ${g.id}: ${g.choice}${by}`); + } + } + if (s.steps.length) { + lines.push("Steps:"); + for (const st of s.steps) lines.push(`• ${MARK[st.status] ?? "?"} ${st.id}: ${st.status}`); + } + if (s.resumes > 0) lines.push(`Resumed ${s.resumes} time${s.resumes === 1 ? "" : "s"}`); + let text = lines.join("\n"); + if (text.length > SUMMARY_MAX_CHARS) text = text.slice(0, SUMMARY_MAX_CHARS - 1) + "…"; + return text; +} diff --git a/tests/workflow-summary.test.mjs b/tests/workflow-summary.test.mjs new file mode 100644 index 00000000..318ec072 --- /dev/null +++ b/tests/workflow-summary.test.mjs @@ -0,0 +1,278 @@ +// End-of-run summary (adlc-workspace#66). +// +// Contract pinned here: +// S1 `workflow summary ` renders completed, failed and aborted runs +// from their run files (golden texts below); `--json` prints the same +// data as one object with `text`. A missing run exits 1. +// S2 A gate that takes its verdict from an input records who answered it +// (`answered_by`, from ADLC_ANSWERED_BY; a plain id only) and the +// summary shows it. +// S3 Every MR/PR link of every step (mr_url, mr_urls) is listed once; the +// execute step's conclusion wins over earlier ones; a failed run names +// its failing step and error. +// S4 Step text is redacted, one line and capped; the whole text fits one +// chat message (SUMMARY_MAX_CHARS). + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, dirname } from "node:path"; +import { spawnSync, execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { buildRunSummary, SUMMARY_MAX_CHARS } from "../src/workflow/summary.mjs"; +import { WorkflowEngine, RunStatus } from "../src/workflow/engine.mjs"; +import { STEP_REGISTRY } from "../src/workflow/registry.mjs"; + +const POSIX = process.platform !== "win32"; +const BIN = join(dirname(fileURLToPath(import.meta.url)), "..", "bin", "adlc-cli.mjs"); +const temps = []; +function tempDir(prefix) { + const d = mkdtempSync(join(tmpdir(), prefix)); + temps.push(d); + return d; +} +process.on("exit", () => { + for (const d of temps) { + try { rmSync(d, { recursive: true, force: true }); } catch {} + } +}); + +function writeRun(root, runId, { state, inputs = {}, steps = [], resumes = 0 }) { + const dir = join(root, ".adlc", "workflows", "runs", runId); + mkdirSync(join(dir, "trace"), { recursive: true }); + writeFileSync(join(dir, "state.json"), JSON.stringify({ run_id: runId, ...state })); + writeFileSync(join(dir, "inputs.json"), JSON.stringify({ inputs })); + writeFileSync(join(dir, "log.jsonl"), steps.map(([id, type]) => JSON.stringify({ event: "step_started", step_id: id, type })).join("\n") + "\n"); + const ev = []; + for (let i = 0; i < resumes; i++) ev.push(JSON.stringify({ schema_version: 1, type: "log", payload: { adlc: { event: "run_resumed" } } })); + writeFileSync(join(dir, "trace", "events.jsonl"), ev.join("\n") + (ev.length ? "\n" : "")); + return dir; +} + +const LANE_STEPS = [["run-branch", "shell"], ["plan", "command"], ["publish-spec", "shell"], ["spec-approval", "if"], ["gate-spec", "gate"], ["run-branch-execute", "shell"], ["execute", "command"]]; +const INPUTS = { issue_ref: "g/adlc-workspace#174", dispatch: "supervised", run_id: "a4b7d251" }; + +function completedRun(root) { + return writeRun(root, "93cd560c", { + inputs: INPUTS, steps: LANE_STEPS, resumes: 1, + state: { + workflow_id: "factory-lane", status: "completed", + created_at: "2026-11-23T08:00:00.000Z", updated_at: "2026-11-23T08:16:42.000Z", + step_results: { + "run-branch": { status: "completed", output: {} }, + plan: { status: "completed", output: { conclusion: "plan-ready" } }, + "publish-spec": { status: "completed", output: {} }, + "spec-approval": { status: "completed", output: {} }, + "gate-spec": { status: "completed", output: { choice: "approve", answered_by: "U03T2SB0B" } }, + "run-branch-execute": { status: "completed", output: {} }, + execute: { status: "completed", output: { conclusion: "Drill done: draft PR open", mr_url: "https://github.com/g/adlc-team-skills/pull/198" } }, + }, + }, + }); +} + +function failedRun(root) { + return writeRun(root, "56d27c13", { + inputs: { ...INPUTS, issue_ref: "g/adlc-workspace#181" }, steps: LANE_STEPS.slice(0, 2), + state: { + workflow_id: "factory-lane", status: "failed", error: "Agent step 'plan': blocked: dependency-gate on #66", + created_at: "2026-11-23T13:46:20.000Z", updated_at: "2026-11-23T13:52:30.000Z", + step_results: { + "run-branch": { status: "completed", output: {} }, + plan: { status: "failed", error: "Agent step 'plan': blocked: dependency-gate on #66", output: { conclusion: "blocked: dependency-gate on #66" } }, + }, + }, + }); +} + +function abortedRun(root) { + return writeRun(root, "7edcedf2", { + inputs: { ...INPUTS, issue_ref: "g/adlc-workspace#172" }, steps: LANE_STEPS.slice(0, 5), resumes: 1, + state: { + workflow_id: "factory-lane", status: "aborted", error: "Gate rejected by user at step 'gate-spec'", + created_at: "2026-11-22T16:00:00.000Z", updated_at: "2026-11-22T16:00:45.000Z", + step_results: { + "run-branch": { status: "completed", output: {} }, + plan: { status: "completed", output: { conclusion: "plan-ready" } }, + "publish-spec": { status: "completed", output: {} }, + "spec-approval": { status: "failed", output: {} }, + "gate-spec": { status: "failed", error: "Gate rejected by user at step 'gate-spec'", output: { choice: "reject", answered_by: "U03T2SB0B", aborted: true } }, + }, + }, + }); +} + +test("S1: completed run (golden)", () => { + const s = buildRunSummary(completedRun(tempDir("sum-"))); + assert.equal(s.text, [ + "*Run 93cd560c completed* · factory-lane · 16m 42s", + "Issue g/adlc-workspace#174 · dispatch supervised", + "MR/PR:", + "• https://github.com/g/adlc-team-skills/pull/198", + "Conclusion: Drill done: draft PR open", + "Gates:", + "• gate-spec: approve (by U03T2SB0B)", + "Steps:", + "• ✓ run-branch: completed", + "• ✓ plan: completed", + "• ✓ publish-spec: completed", + "• ✓ spec-approval: completed", + "• ✓ gate-spec: completed", + "• ✓ run-branch-execute: completed", + "• ✓ execute: completed", + "Resumed 1 time", + ].join("\n")); +}); + +test("S1: failed run (golden)", () => { + const s = buildRunSummary(failedRun(tempDir("sum-"))); + assert.equal(s.text, [ + "*Run 56d27c13 failed* · factory-lane · 6m 10s", + "Issue g/adlc-workspace#181 · dispatch supervised", + "Failed at `plan`: Agent step 'plan': blocked: dependency-gate on #66", + "MR/PR: none", + "Conclusion: blocked: dependency-gate on #66", + "Steps:", + "• ✓ run-branch: completed", + "• ✗ plan: failed", + ].join("\n")); + assert.deepEqual(s.failed_step, { id: "plan", error: "Agent step 'plan': blocked: dependency-gate on #66" }); +}); + +test("S1: aborted run (golden)", () => { + const s = buildRunSummary(abortedRun(tempDir("sum-"))); + assert.equal(s.text, [ + "*Run 7edcedf2 aborted* · factory-lane · 45s", + "Issue g/adlc-workspace#172 · dispatch supervised", + "Failed at `gate-spec`: Gate rejected by user at step 'gate-spec'", + "MR/PR: none", + "Conclusion: plan-ready", + "Gates:", + "• gate-spec: reject (by U03T2SB0B)", + "Steps:", + "• ✓ run-branch: completed", + "• ✓ plan: completed", + "• ✓ publish-spec: completed", + "• ✗ spec-approval: failed", + "• ✗ gate-spec: failed", + "Resumed 1 time", + ].join("\n")); +}); + +test("S3: every link once, mr_urls split, non-links dropped", () => { + const root = tempDir("sum-"); + const dir = writeRun(root, "r1", { + steps: [["publish-spec", "shell"], ["execute", "command"]], + state: { + workflow_id: "w", status: "completed", created_at: "2026-11-23T08:00:00Z", updated_at: "2026-11-23T08:00:05Z", + step_results: { + "publish-spec": { status: "completed", output: { mr_url: "https://gl.test/g/p/-/merge_requests/1" } }, + execute: { status: "completed", output: { mr_url: "https://gl.test/g/p/-/merge_requests/1", mr_urls: "https://github.com/g/c/pull/2, javascript:alert(1) https://github.com/g/d/pull/3" } }, + }, + }, + }); + assert.deepEqual(buildRunSummary(dir).mr_urls, [ + "https://gl.test/g/p/-/merge_requests/1", "https://github.com/g/c/pull/2", "https://github.com/g/d/pull/3", + ]); +}); + +test("S4: step text is redacted, one line, capped; the text fits one message", () => { + const root = tempDir("sum-"); + const token = "glpat-" + "a1b2c3d4e5f6g7h8i9j0"; + const results = {}; + const steps = []; + for (let i = 0; i < 120; i++) { results[`step-${i}`] = { status: "completed", output: {} }; steps.push([`step-${i}`, "shell"]); } + results.execute = { status: "failed", error: `push to https://oauth2:${token}@gl.test failed\nline two`, output: { conclusion: "x".repeat(5000) } }; + steps.push(["execute", "command"]); + const dir = writeRun(root, "r2", { steps, state: { workflow_id: "w", status: "failed", created_at: "2026-11-23T08:00:00Z", updated_at: "2026-11-23T09:05:00Z", step_results: results } }); + const s = buildRunSummary(dir); + assert.ok(!s.text.includes(token)); + assert.ok(!s.failed_step.error.includes("\n")); + assert.ok(s.conclusion.length <= 300); + assert.ok(s.text.length <= SUMMARY_MAX_CHARS); + assert.match(s.text, /^\*Run r2 failed\* · w · 1h 5m/); +}); + +test("S2: an answered_by that is not a plain id is not shown", () => { + const root = tempDir("sum-"); + const dir = writeRun(root, "r3", { + steps: [["gate-spec", "gate"]], + state: { workflow_id: "w", status: "completed", created_at: "2026-11-23T08:00:00Z", updated_at: "2026-11-23T08:00:01Z", + step_results: { "gate-spec": { status: "completed", output: { choice: "approve", answered_by: " evil" } } } }, + }); + assert.match(buildRunSummary(dir).text, /• gate-spec: approve\n/); +}); + +// ── S2 end to end: the gate records who answered ──────────────────────────── + +function gateProject() { + const dir = tempDir("sum-gate-"); + execFileSync("git", ["init", "-q", "-b", "main"], { cwd: dir }); + const wf = join(tempDir("sum-gate-wf-"), "workflow.yml"); + writeFileSync(wf, `schema_version: "1.0" +workflow: + id: g-wf + name: G + version: "1.0.0" +inputs: + verdict: {type: string, default: "", enum: ["", approve, reject]} +steps: + - id: gate-spec + type: gate + message: "Approve?" + options: [approve, reject] + on_reject: abort + verdict_input: verdict +`); + return { dir, wf }; +} + +async function runGate(env, verdict = "approve") { + const { dir, wf } = gateProject(); + const saved = process.env.ADLC_ANSWERED_BY; + if (env === undefined) delete process.env.ADLC_ANSWERED_BY; + else process.env.ADLC_ANSWERED_BY = env; + try { + const engine = new WorkflowEngine(dir); + const state = await engine.execute(engine.loadWorkflow(wf), { verdict }, "g1", STEP_REGISTRY); + return { dir, state }; + } finally { + if (saved === undefined) delete process.env.ADLC_ANSWERED_BY; + else process.env.ADLC_ANSWERED_BY = saved; + } +} + +test("S2: a gate answered through its verdict input records ADLC_ANSWERED_BY", async () => { + const { state } = await runGate("U03T2SB0B"); + assert.equal(state.status, RunStatus.COMPLETED); + assert.equal(state.stepResults["gate-spec"].output.answered_by, "U03T2SB0B"); +}); + +test("S2: a reject records who rejected", async () => { + const { state } = await runGate("U03T2SB0B", "reject"); + assert.equal(state.stepResults["gate-spec"].output.answered_by, "U03T2SB0B"); +}); + +test("S2: no ADLC_ANSWERED_BY, or one that is not a plain id, records nothing", async () => { + assert.equal((await runGate(undefined)).state.stepResults["gate-spec"].output.answered_by, undefined); + assert.equal((await runGate("")).state.stepResults["gate-spec"].output.answered_by, undefined); +}); + +// ── the command ───────────────────────────────────────────────────────────── + +test("S1: `workflow summary` prints the text, `--json` the object; a missing run exits 1", { skip: !POSIX }, () => { + const root = tempDir("sum-cli-"); + failedRun(root); + const r = spawnSync(process.execPath, [BIN, "workflow", "summary", "56d27c13"], { cwd: root, encoding: "utf-8" }); + assert.equal(r.status, 0, r.stderr); + assert.match(r.stdout, /\*Run 56d27c13 failed\* · factory-lane · 6m 10s/); + const j = spawnSync(process.execPath, [BIN, "workflow", "summary", "56d27c13", "--json"], { cwd: root, encoding: "utf-8" }); + assert.equal(j.status, 0, j.stderr); + const obj = JSON.parse(j.stdout); + assert.equal(obj.status, "failed"); + assert.equal(obj.failed_step.id, "plan"); + assert.match(obj.text, /^\*Run 56d27c13 failed\*/); + const missing = spawnSync(process.execPath, [BIN, "workflow", "summary", "nope"], { cwd: root, encoding: "utf-8" }); + assert.equal(missing.status, 1); +}); From 55631f752f4a4f1bcb22e727a4fedcb63e457c11 Mon Sep 17 00:00:00 2001 From: itai Date: Mon, 23 Nov 2026 16:20:15 +0200 Subject: [PATCH 2/5] fix(workflow): summary gates by logged type, chat-safe text, answerer per supplied verdict Security review of a9f8541: - a gate line comes only from a step the engine logged as `gate`; any other step can write choice/answered_by to its own output; - the summary text escapes & < > and breaks @here/@channel/@everyone, so step text cannot become chat links, mentions or broadcasts (the JSON fields keep the cleaned values); - a gate credits ADLC_ANSWERED_BY only when its verdict input was supplied in this run/resume call (StepContext.suppliedInputs), not for a verdict kept from an earlier call. Refs adlc-workspace#66 Co-Authored-By: Claude Opus 5.5 --- src/workflow/base.mjs | 3 ++ src/workflow/engine.mjs | 2 + src/workflow/steps/gate.mjs | 5 +- src/workflow/summary.mjs | 25 +++++++++- tests/workflow-summary.test.mjs | 82 +++++++++++++++++++++++++++++++++ 5 files changed, 114 insertions(+), 3 deletions(-) diff --git a/src/workflow/base.mjs b/src/workflow/base.mjs index 545ef4e1..20bf54ee 100644 --- a/src/workflow/base.mjs +++ b/src/workflow/base.mjs @@ -48,6 +48,9 @@ export class StepContext { this.workflowDir = fields.workflowDir ?? null; // Whether the engine is re-executing the current step during resume. this.isResume = fields.isResume ?? false; + // Input keys passed in this run/resume call (not ones kept from an earlier + // call): a gate credits ADLC_ANSWERED_BY only for a verdict supplied now. + this.suppliedInputs = fields.suppliedInputs ?? []; // Run-level shas context gates resolve `since` from ({ runStartSha, // lastApprovedSha }); shared by reference so approvals are seen by // every derived context. diff --git a/src/workflow/engine.mjs b/src/workflow/engine.mjs index 9f4521be..03dd79e9 100644 --- a/src/workflow/engine.mjs +++ b/src/workflow/engine.mjs @@ -813,6 +813,7 @@ export class WorkflowEngine { runId: state.runId, workflowDir, gateIds: gateStepIds(definition.steps), + suppliedInputs: Object.keys(inputs ?? {}), }); context.gateRun = { runStartSha: state.runStartSha, lastApprovedSha: state.lastApprovedSha }; @@ -923,6 +924,7 @@ export class WorkflowEngine { runId: state.runId, workflowDir: state.workflowDir, gateIds: gateStepIds(definition.steps), + suppliedInputs: Object.keys(inputs ?? {}), }); context.isResume = true; context.gateRun = { runStartSha: state.runStartSha, lastApprovedSha: state.lastApprovedSha }; diff --git a/src/workflow/steps/gate.mjs b/src/workflow/steps/gate.mjs index b8efb1a3..15d540a7 100644 --- a/src/workflow/steps/gate.mjs +++ b/src/workflow/steps/gate.mjs @@ -321,7 +321,10 @@ export class GateStep extends StepBase { } output.choice = choice; const answeredBy = (process.env.ADLC_ANSWERED_BY ?? "").trim(); - if (fromInput && /^[A-Za-z0-9._@-]{1,64}$/.test(answeredBy)) output.answered_by = answeredBy; + // Only for a verdict supplied in this run/resume call: a verdict kept from + // an earlier call was not given by whoever resumed the run now. + const suppliedNow = boundVerdictInput !== null && (context.suppliedInputs ?? []).includes(boundVerdictInput); + if (fromInput && suppliedNow && /^[A-Za-z0-9._@-]{1,64}$/.test(answeredBy)) output.answered_by = answeredBy; // Match rejection case-insensitively, agreeing with validate(). if (isRejection(choice)) { diff --git a/src/workflow/summary.mjs b/src/workflow/summary.mjs index 6d936fe4..b5ae9a87 100644 --- a/src/workflow/summary.mjs +++ b/src/workflow/summary.mjs @@ -105,7 +105,9 @@ export function buildRunSummary(runDir, { env = process.env } = {}) { const step = { id: cleanField(id, 80, env), status: typeof r.status === "string" ? r.status : "unknown" }; if (types[id]) step.type = types[id]; steps.push(step); - if (typeof output.choice === "string") { + // Gates only by the type the engine logged when it started the step: any + // other step can write `choice`/`answered_by` to its own output. + if (types[id] === "gate" && typeof output.choice === "string") { const gate = { id: step.id, choice: cleanField(output.choice, 40, env) }; if (typeof output.answered_by === "string" && ANSWERER.test(output.answered_by)) gate.answered_by = output.answered_by; if (output.auto_passed === true) gate.auto = true; @@ -158,7 +160,26 @@ export function buildRunSummary(runDir, { env = process.env } = {}) { const MARK = { completed: "✓", failed: "✗", skipped: "–", paused: "⏸", running: "…" }; -export function renderSummaryText(s) { +// Chat-safe text: `&`, `<`, `>` escaped (no links, mentions or broadcasts +// made of step text) and @here/@channel/@everyone broken with a zero-width +// space. Only the rendered text; the JSON fields keep the cleaned values. +export function chatSafe(value) { + return String(value ?? "") + .replace(/&/g, "&").replace(//g, ">") + .replace(/@(here|channel|everyone)\b/gi, "@\u200b$1"); +} + +export function renderSummaryText(raw) { + const e = chatSafe; + const s = { + ...raw, + run_id: e(raw.run_id), workflow_id: e(raw.workflow_id), issue_ref: raw.issue_ref ? e(raw.issue_ref) : raw.issue_ref, + dispatch: raw.dispatch ? e(raw.dispatch) : raw.dispatch, conclusion: raw.conclusion ? e(raw.conclusion) : raw.conclusion, + failed_step: raw.failed_step ? { id: e(raw.failed_step.id), error: e(raw.failed_step.error) } : null, + mr_urls: raw.mr_urls.map(e), + gates: raw.gates.map((g) => ({ ...g, id: e(g.id), choice: e(g.choice) })), + steps: raw.steps.map((st) => ({ ...st, id: e(st.id) })), + }; const lines = []; const head = [`*Run ${s.run_id} ${s.status}*`]; if (s.workflow_id) head.push(s.workflow_id); diff --git a/tests/workflow-summary.test.mjs b/tests/workflow-summary.test.mjs index 318ec072..b7fa0008 100644 --- a/tests/workflow-summary.test.mjs +++ b/tests/workflow-summary.test.mjs @@ -276,3 +276,85 @@ test("S1: `workflow summary` prints the text, `--json` the object; a missing run const missing = spawnSync(process.execPath, [BIN, "workflow", "summary", "nope"], { cwd: root, encoding: "utf-8" }); assert.equal(missing.status, 1); }); + +// ── security review of a9f8541 ────────────────────────────────────────────── + +test("S5: a non-gate step that writes choice/answered_by is not shown as a gate", () => { + const root = tempDir("sum-"); + const dir = writeRun(root, "r5", { + steps: [["fake", "shell"], ["typeless", undefined]], + state: { workflow_id: "w", status: "completed", created_at: "2026-11-23T08:00:00Z", updated_at: "2026-11-23T08:00:01Z", + step_results: { + fake: { status: "completed", output: { choice: "approve", answered_by: "U0BOSS" } }, + typeless: { status: "completed", output: { choice: "approve", answered_by: "U0BOSS" } }, + } }, + }); + const s = buildRunSummary(dir); + assert.deepEqual(s.gates, []); + assert.doesNotMatch(s.text, /Gates:|U0BOSS/); +}); + +test("S6: chat markup and broadcast mentions in step text are neutralised in the text", () => { + const root = tempDir("sum-"); + const dir = writeRun(root, "r6", { + steps: [["execute", "command"]], + state: { workflow_id: "w", status: "completed", created_at: "2026-11-23T08:00:00Z", updated_at: "2026-11-23T08:00:01Z", + step_results: { execute: { status: "completed", output: { conclusion: "done a & b @here @everyone @channel" } } } }, + }); + const s = buildRunSummary(dir); + assert.ok(!s.text.includes(""), s.text); + assert.ok(!s.text.includes(""), s.text); + assert.match(s.text, /<!channel>/); + assert.match(s.text, /a & b/); + for (const m of ["@here", "@everyone", "@channel"]) assert.ok(!s.text.includes(m), m); + assert.equal(s.conclusion, "done a & b @here @everyone @channel"); // JSON keeps the text +}); + +function twoGateProject() { + const dir = tempDir("sum-gate2-"); + execFileSync("git", ["init", "-q", "-b", "main"], { cwd: dir }); + const wf = join(tempDir("sum-gate2-wf-"), "workflow.yml"); + writeFileSync(wf, `schema_version: "1.0" +workflow: + id: g2-wf + name: G2 + version: "1.0.0" +inputs: + v1: {type: string, default: "", enum: ["", approve, reject]} + v2: {type: string, default: "", enum: ["", approve, reject]} +steps: + - id: gate-one + type: gate + message: "One?" + options: [approve, reject] + verdict_input: v1 + - id: gate-two + type: gate + message: "Two?" + options: [approve, reject] + verdict_input: v2 +`); + return { dir, wf }; +} + +async function withAnswerer(id, fn) { + const saved = process.env.ADLC_ANSWERED_BY; + if (id === undefined) delete process.env.ADLC_ANSWERED_BY; else process.env.ADLC_ANSWERED_BY = id; + try { return await fn(); } finally { + if (saved === undefined) delete process.env.ADLC_ANSWERED_BY; else process.env.ADLC_ANSWERED_BY = saved; + } +} + +test("S2: the answerer is recorded only for a verdict supplied in this run or resume call", async () => { + const { dir, wf } = twoGateProject(); + const engine = new WorkflowEngine(dir); + // Started with v2 preset and no answerer: gate-one pauses. + let state = await withAnswerer(undefined, () => engine.execute(engine.loadWorkflow(wf), { v2: "approve" }, "g2", STEP_REGISTRY)); + assert.equal(state.status, RunStatus.PAUSED); + // U1 answers gate-one. gate-two then runs on the v2 set at start: U1 did + // not give that verdict, so it must not be credited to U1. + state = await withAnswerer("U1", () => engine.resume("g2", { v1: "approve" }, STEP_REGISTRY)); + assert.equal(state.status, RunStatus.COMPLETED); + assert.equal(state.stepResults["gate-one"].output.answered_by, "U1"); + assert.equal(state.stepResults["gate-two"].output.answered_by, undefined); +}); From 8ee4dd725b58f4fa7cf243166001bf9b3caa8892 Mon Sep 17 00:00:00 2001 From: itai Date: Mon, 23 Nov 2026 16:23:46 +0200 Subject: [PATCH 3/5] fix(workflow): credit only the gate that asked; escape the answerer; first logged type wins Security review of 55631f7: - a gate records ADLC_ANSWERED_BY only when it was paused before this call and its verdict input was supplied now: a verdict preset at the start, or one a second gate shares, is not credited; - the answerer may not start with "@" (gate and summary) and is escaped in the summary text, so it can never render as a mention; - the summary takes a step's first logged type; a later log line cannot turn a step into a gate. Refs adlc-workspace#66 Co-Authored-By: Claude Opus 5.5 --- src/workflow/steps/gate.mjs | 8 +++- src/workflow/summary.mjs | 7 ++-- tests/workflow-summary.test.mjs | 72 +++++++++++++++++++++++++++++++-- 3 files changed, 80 insertions(+), 7 deletions(-) diff --git a/src/workflow/steps/gate.mjs b/src/workflow/steps/gate.mjs index 15d540a7..191bc831 100644 --- a/src/workflow/steps/gate.mjs +++ b/src/workflow/steps/gate.mjs @@ -323,8 +323,14 @@ export class GateStep extends StepBase { const answeredBy = (process.env.ADLC_ANSWERED_BY ?? "").trim(); // Only for a verdict supplied in this run/resume call: a verdict kept from // an earlier call was not given by whoever resumed the run now. + // And only for the gate that asked: this gate was paused before this call + // (a verdict preset at the start, or one a second gate shares, was not an + // answer to this gate). A plain id, never starting with "@". const suppliedNow = boundVerdictInput !== null && (context.suppliedInputs ?? []).includes(boundVerdictInput); - if (fromInput && suppliedNow && /^[A-Za-z0-9._@-]{1,64}$/.test(answeredBy)) output.answered_by = answeredBy; + const askedBefore = context.steps?.[config.id]?.status === StepStatus.PAUSED; + if (fromInput && suppliedNow && askedBefore && /^[A-Za-z0-9._-][A-Za-z0-9._@-]{0,63}$/.test(answeredBy)) { + output.answered_by = answeredBy; + } // Match rejection case-insensitively, agreeing with validate(). if (isRejection(choice)) { diff --git a/src/workflow/summary.mjs b/src/workflow/summary.mjs index b5ae9a87..8ac516ad 100644 --- a/src/workflow/summary.mjs +++ b/src/workflow/summary.mjs @@ -18,7 +18,7 @@ export const SUMMARY_MAX_CHARS = 3000; export const SUMMARY_FIELD_CHARS = 300; export const SUMMARY_MAX_LINKS = 10; const LINK = /^https?:\/\/[^\s<>|]{1,2040}$/i; -const ANSWERER = /^[A-Za-z0-9._@-]{1,64}$/; +const ANSWERER = /^[A-Za-z0-9._-][A-Za-z0-9._@-]{0,63}$/; function readJson(path) { try { @@ -87,7 +87,8 @@ export function buildRunSummary(runDir, { env = process.env } = {}) { for (const e of log) { if (e?.event === "step_started" && typeof e.step_id === "string") { if (!order.includes(e.step_id)) order.push(e.step_id); - if (typeof e.type === "string") types[e.step_id] = e.type; + // The first logged type stands; a later line cannot retype a step. + if (typeof e.type === "string" && !(e.step_id in types)) types[e.step_id] = e.type; } } for (const id of Object.keys(results)) if (!order.includes(id)) order.push(id); @@ -177,7 +178,7 @@ export function renderSummaryText(raw) { dispatch: raw.dispatch ? e(raw.dispatch) : raw.dispatch, conclusion: raw.conclusion ? e(raw.conclusion) : raw.conclusion, failed_step: raw.failed_step ? { id: e(raw.failed_step.id), error: e(raw.failed_step.error) } : null, mr_urls: raw.mr_urls.map(e), - gates: raw.gates.map((g) => ({ ...g, id: e(g.id), choice: e(g.choice) })), + gates: raw.gates.map((g) => ({ ...g, id: e(g.id), choice: e(g.choice), ...(g.answered_by ? { answered_by: e(g.answered_by) } : {}) })), steps: raw.steps.map((st) => ({ ...st, id: e(st.id) })), }; const lines = []; diff --git a/tests/workflow-summary.test.mjs b/tests/workflow-summary.test.mjs index b7fa0008..9db3c0ae 100644 --- a/tests/workflow-summary.test.mjs +++ b/tests/workflow-summary.test.mjs @@ -228,14 +228,19 @@ steps: return { dir, wf }; } +// The gate pauses first (no verdict), then a relay resumes it with the +// verdict and ADLC_ANSWERED_BY: the gate that asked is the gate answered. async function runGate(env, verdict = "approve") { const { dir, wf } = gateProject(); const saved = process.env.ADLC_ANSWERED_BY; - if (env === undefined) delete process.env.ADLC_ANSWERED_BY; - else process.env.ADLC_ANSWERED_BY = env; try { + delete process.env.ADLC_ANSWERED_BY; const engine = new WorkflowEngine(dir); - const state = await engine.execute(engine.loadWorkflow(wf), { verdict }, "g1", STEP_REGISTRY); + const paused = await engine.execute(engine.loadWorkflow(wf), {}, "g1", STEP_REGISTRY); + assert.equal(paused.status, RunStatus.PAUSED); + if (env === undefined) delete process.env.ADLC_ANSWERED_BY; + else process.env.ADLC_ANSWERED_BY = env; + const state = await engine.resume("g1", { verdict }, STEP_REGISTRY); return { dir, state }; } finally { if (saved === undefined) delete process.env.ADLC_ANSWERED_BY; @@ -257,6 +262,7 @@ test("S2: a reject records who rejected", async () => { test("S2: no ADLC_ANSWERED_BY, or one that is not a plain id, records nothing", async () => { assert.equal((await runGate(undefined)).state.stepResults["gate-spec"].output.answered_by, undefined); assert.equal((await runGate("")).state.stepResults["gate-spec"].output.answered_by, undefined); + assert.equal((await runGate("@channel")).state.stepResults["gate-spec"].output.answered_by, undefined); }); // ── the command ───────────────────────────────────────────────────────────── @@ -358,3 +364,63 @@ test("S2: the answerer is recorded only for a verdict supplied in this run or re assert.equal(state.stepResults["gate-one"].output.answered_by, "U1"); assert.equal(state.stepResults["gate-two"].output.answered_by, undefined); }); + +// ── security review of 55631f7 ────────────────────────────────────────────── + +test("S2: a verdict preset at the start (no pause) is not credited to anyone", async () => { + const { dir, wf } = gateProject(); + const state = await withAnswerer("U1", () => { const e = new WorkflowEngine(dir); return e.execute(e.loadWorkflow(wf), { verdict: "approve" }, "g0", STEP_REGISTRY); }); + assert.equal(state.status, RunStatus.COMPLETED); + assert.equal(state.stepResults["gate-spec"].output.answered_by, undefined); +}); + +test("S2: two gates sharing one verdict input: only the gate that asked is credited", async () => { + const dir = tempDir("sum-shared-"); + execFileSync("git", ["init", "-q", "-b", "main"], { cwd: dir }); + const wf = join(tempDir("sum-shared-wf-"), "workflow.yml"); + writeFileSync(wf, `schema_version: "1.0" +workflow: + id: sh-wf + name: SH + version: "1.0.0" +inputs: + verdict: {type: string, default: "", enum: ["", approve, reject]} +steps: + - id: gate-a + type: gate + message: "A?" + options: [approve, reject] + verdict_input: verdict + - id: gate-b + type: gate + message: "B?" + options: [approve, reject] + verdict_input: verdict +`); + const engine = new WorkflowEngine(dir); + await withAnswerer(undefined, () => engine.execute(engine.loadWorkflow(wf), {}, "sh", STEP_REGISTRY)); + const state = await withAnswerer("U1", () => engine.resume("sh", { verdict: "approve" }, STEP_REGISTRY)); + assert.equal(state.stepResults["gate-a"].output.answered_by, "U1"); + assert.equal(state.stepResults["gate-b"]?.output?.answered_by, undefined); +}); + +test("S6: an answerer that looks like a mention is never rendered as one", () => { + const root = tempDir("sum-"); + const dir = writeRun(root, "r7", { + steps: [["gate-spec", "gate"]], + state: { workflow_id: "w", status: "completed", created_at: "2026-11-23T08:00:00Z", updated_at: "2026-11-23T08:00:01Z", + step_results: { "gate-spec": { status: "completed", output: { choice: "approve", answered_by: "@channel" } } } }, + }); + const s = buildRunSummary(dir); + assert.ok(!s.text.includes("@channel"), s.text); +}); + +test("S5: a later log line cannot turn a step into a gate", () => { + const root = tempDir("sum-"); + const dir = writeRun(root, "r8", { + steps: [["fake", "shell"], ["fake", "gate"]], + state: { workflow_id: "w", status: "completed", created_at: "2026-11-23T08:00:00Z", updated_at: "2026-11-23T08:00:01Z", + step_results: { fake: { status: "completed", output: { choice: "approve", answered_by: "U0BOSS" } } } }, + }); + assert.deepEqual(buildRunSummary(dir).gates, []); +}); From 022a29efe5c824e22f876682c330f7c96c1b07a9 Mon Sep 17 00:00:00 2001 From: itai Date: Mon, 23 Nov 2026 16:27:43 +0200 Subject: [PATCH 4/5] fix(workflow): summary gates from the run's definition; resumes from log.jsonl Security review: log.jsonl is not a trust source (anything in the workspace can append to it). Gate lines now come only from the run copy of the definition (runs//workflow.yml), the file the engine executes and resumes from, via the engine's own gateStepIds. No readable copy: no gate lines. log.jsonl stays an ordering hint. Also: resumes are counted from log.jsonl (a paused or interrupted end with entries after it), not from trace events, which are sampled and were absent on a real paused-and-resumed run. A test now runs a real pause and resume and checks the summary. Refs adlc-workspace#66 Co-Authored-By: Claude Opus 5.5 --- src/workflow/summary.mjs | 42 +++++++++++++++++++++----- tests/workflow-summary.test.mjs | 52 ++++++++++++++++++++++++++++----- 2 files changed, 80 insertions(+), 14 deletions(-) diff --git a/src/workflow/summary.mjs b/src/workflow/summary.mjs index 8ac516ad..bff352ba 100644 --- a/src/workflow/summary.mjs +++ b/src/workflow/summary.mjs @@ -2,7 +2,7 @@ // // One message that says how a run ended, built only from the run's own files // (.adlc/workflows/runs//state.json, inputs.json, log.jsonl and the -// trace events). The engine makes no network call here (ADR-416): a runtime +// run copy of the workflow definition). The engine makes no network call here (ADR-416): a runtime // that relays runs to a chat thread forwards `text` as it is. // // Every string that came from a step (errors, conclusions, links, who answered @@ -12,7 +12,8 @@ import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { redactSecrets } from "./redact.mjs"; -import { tracePaths } from "./trace.mjs"; +import { gateStepIds } from "./gate-payload.mjs"; +import { WorkflowDefinition } from "./engine.mjs"; export const SUMMARY_MAX_CHARS = 3000; export const SUMMARY_FIELD_CHARS = 300; @@ -68,6 +69,26 @@ function stepLinks(output) { return links.filter((l) => LINK.test(l)); } +// Gate ids from the run copy of the definition (runs//workflow.yml): the +// file the engine executes and resumes from, so the same source the engine's +// own gate decisions come from. log.jsonl is only an ordering hint: anything +// in the workspace can append to it. No readable copy: no gate lines. +function definedGateIds(runDir) { + const copy = join(runDir, "workflow.yml"); + if (!existsSync(copy)) return null; + let data = null; + try { + data = WorkflowDefinition.fromYamlFile(copy).data; + } catch { + try { + data = JSON.parse(readFileSync(copy, "utf-8").replace(/^# serialized from string source\n/, "")); + } catch { + return null; + } + } + return data && typeof data === "object" ? new Set(gateStepIds(data.steps)) : null; +} + /** * Build the summary of one run from its directory. Returns null when the run * has no readable state.json. @@ -77,8 +98,8 @@ export function buildRunSummary(runDir, { env = process.env } = {}) { if (!state || typeof state !== "object") return null; const inputs = (readJson(join(runDir, "inputs.json")) ?? {}).inputs ?? {}; const log = readLines(join(runDir, "log.jsonl")); - const trace = readLines(tracePaths(runDir).events); const results = state.step_results && typeof state.step_results === "object" ? state.step_results : {}; + const gateIds = definedGateIds(runDir) ?? new Set(); // Step order: as the run started them (log.jsonl), then any result the log // does not name, in state order. @@ -106,9 +127,9 @@ export function buildRunSummary(runDir, { env = process.env } = {}) { const step = { id: cleanField(id, 80, env), status: typeof r.status === "string" ? r.status : "unknown" }; if (types[id]) step.type = types[id]; steps.push(step); - // Gates only by the type the engine logged when it started the step: any - // other step can write `choice`/`answered_by` to its own output. - if (types[id] === "gate" && typeof output.choice === "string") { + // Gates only by the run's definition: any other step can write + // `choice`/`answered_by` to its own output. + if (gateIds.has(id) && typeof output.choice === "string") { const gate = { id: step.id, choice: cleanField(output.choice, 40, env) }; if (typeof output.answered_by === "string" && ANSWERER.test(output.answered_by)) gate.answered_by = output.answered_by; if (output.auto_passed === true) gate.auto = true; @@ -137,7 +158,14 @@ export function buildRunSummary(runDir, { env = process.env } = {}) { const ended = Date.parse(state.updated_at ?? ""); const durationSeconds = Number.isFinite(started) && Number.isFinite(ended) && ended >= started ? Math.round((ended - started) / 1000) : null; - const resumes = trace.filter((e) => e?.payload?.adlc?.event === "run_resumed").length; + // Resumes from log.jsonl (the trace events are sampled): every call ends + // with workflow_finished or workflow_interrupted; one that stopped the run + // (paused, interrupted) and has entries after it was resumed. + let resumes = 0; + log.forEach((e, i) => { + const stopped = (e?.event === "workflow_finished" && e.status === "paused") || e?.event === "workflow_interrupted"; + if (stopped && i < log.length - 1) resumes++; + }); const summary = { run_id: cleanField(String(state.run_id ?? ""), 80, env), diff --git a/tests/workflow-summary.test.mjs b/tests/workflow-summary.test.mjs index 9db3c0ae..d1d27fd5 100644 --- a/tests/workflow-summary.test.mjs +++ b/tests/workflow-summary.test.mjs @@ -38,15 +38,32 @@ process.on("exit", () => { } }); -function writeRun(root, runId, { state, inputs = {}, steps = [], resumes = 0 }) { +// The run copy of the definition (runs//workflow.yml) is what the engine +// executes and resumes from; the summary takes its gate ids from it. `defined` +// overrides the step types written there (default: the logged ones). +function writeDefinition(dir, defined) { + const lines = ['schema_version: "1.0"', "workflow:", " id: w", " name: W", ' version: "1.0.0"', "steps:"]; + for (const [id, type] of defined) { + lines.push(` - id: ${id}`); + if (type) lines.push(` type: ${type}`); + if (type === "gate") lines.push(' message: "?"', " options: [approve, reject]"); + if (type === "shell") lines.push(" run: \"true\""); + if (type === "command" || !type) lines.push(" command: x"); + } + writeFileSync(join(dir, "workflow.yml"), lines.join("\n") + "\n"); +} + +function writeRun(root, runId, { state, inputs = {}, steps = [], resumes = 0, defined = steps, definition = true }) { const dir = join(root, ".adlc", "workflows", "runs", runId); mkdirSync(join(dir, "trace"), { recursive: true }); + if (definition) writeDefinition(dir, defined.filter(([id], i, a) => a.findIndex(([j]) => j === id) === i)); writeFileSync(join(dir, "state.json"), JSON.stringify({ run_id: runId, ...state })); writeFileSync(join(dir, "inputs.json"), JSON.stringify({ inputs })); - writeFileSync(join(dir, "log.jsonl"), steps.map(([id, type]) => JSON.stringify({ event: "step_started", step_id: id, type })).join("\n") + "\n"); - const ev = []; - for (let i = 0; i < resumes; i++) ev.push(JSON.stringify({ schema_version: 1, type: "log", payload: { adlc: { event: "run_resumed" } } })); - writeFileSync(join(dir, "trace", "events.jsonl"), ev.join("\n") + (ev.length ? "\n" : "")); + const log = []; + for (let i = 0; i < resumes; i++) log.push(JSON.stringify({ event: "workflow_finished", status: "paused" })); + for (const [id, type] of steps) log.push(JSON.stringify({ event: "step_started", step_id: id, type })); + log.push(JSON.stringify({ event: "workflow_finished", status: state.status })); + writeFileSync(join(dir, "log.jsonl"), log.join("\n") + "\n"); return dir; } @@ -415,12 +432,33 @@ test("S6: an answerer that looks like a mention is never rendered as one", () => assert.ok(!s.text.includes("@channel"), s.text); }); -test("S5: a later log line cannot turn a step into a gate", () => { +test("S5: the log cannot turn a step into a gate: the run's definition decides", () => { const root = tempDir("sum-"); const dir = writeRun(root, "r8", { - steps: [["fake", "shell"], ["fake", "gate"]], + steps: [["fake", "gate"], ["fake", "shell"]], defined: [["fake", "shell"]], state: { workflow_id: "w", status: "completed", created_at: "2026-11-23T08:00:00Z", updated_at: "2026-11-23T08:00:01Z", step_results: { fake: { status: "completed", output: { choice: "approve", answered_by: "U0BOSS" } } } }, }); assert.deepEqual(buildRunSummary(dir).gates, []); }); + +test("S5: without the run's definition there are no gate lines (fail closed)", () => { + const root = tempDir("sum-"); + const dir = writeRun(root, "r9", { + steps: [["gate-spec", "gate"]], definition: false, + state: { workflow_id: "w", status: "completed", created_at: "2026-11-23T08:00:00Z", updated_at: "2026-11-23T08:00:01Z", + step_results: { "gate-spec": { status: "completed", output: { choice: "approve", answered_by: "U1" } } } }, + }); + const s = buildRunSummary(dir); + assert.deepEqual(s.gates, []); + assert.match(s.text, /• ✓ gate-spec: completed/); +}); + +test("S1: a real paused-and-resumed run: gate credited, one resume, from the engine's own files", async () => { + const { dir } = await runGate("U03T2SB0B"); + const s = buildRunSummary(join(dir, ".adlc", "workflows", "runs", "g1")); + assert.deepEqual(s.gates, [{ id: "gate-spec", choice: "approve", answered_by: "U03T2SB0B" }]); + assert.equal(s.resumes, 1); + assert.match(s.text, /• gate-spec: approve \(by U03T2SB0B\)/); + assert.match(s.text, /Resumed 1 time$/); +}); From e5956276df2211193b16a2e5292215af3c7e21ed Mon Sep 17 00:00:00 2001 From: itai Date: Mon, 23 Nov 2026 16:34:50 +0200 Subject: [PATCH 5/5] fix(workflow): summary gates by the engine-recorded step type; reserve gate keys Security review: the run copy of the definition is as writable as the log, and walking it does not match runtime ids (fan-out, loops). The engine already records each step's type in its result (state.json step_results[].type, keyed by the runtime id); a gate line now needs `type === "gate"` there. The definition walker is gone; log.jsonl stays an ordering hint. `choice`, `answered_by` and `auto_passed` are reserved in step output, so no agent or shell step can supply a gate's fields. Refs adlc-workspace#66 Co-Authored-By: Claude Opus 5.5 --- src/workflow/steps/agent.mjs | 4 +++- src/workflow/summary.mjs | 36 ++++++---------------------- tests/workflow-summary.test.mjs | 42 +++++++++++++++++---------------- 3 files changed, 32 insertions(+), 50 deletions(-) diff --git a/src/workflow/steps/agent.mjs b/src/workflow/steps/agent.mjs index a008c5df..ebc7831b 100644 --- a/src/workflow/steps/agent.mjs +++ b/src/workflow/steps/agent.mjs @@ -362,7 +362,9 @@ function priorPauseCount(context, config) { // ── run context + structured step output (ADR-444) ───────────────────────── -const RESERVED_OUTPUT_KEYS = new Set(["integration", "model", "input", "stdout", "stderr", "exit_code", "interrupted"]); +// `choice`, `answered_by` and `auto_passed` are a gate's own fields: no step +// output may supply them (adlc-workspace#66, the end-of-run summary). +const RESERVED_OUTPUT_KEYS = new Set(["integration", "model", "input", "stdout", "stderr", "exit_code", "interrupted", "choice", "answered_by", "auto_passed"]); const OUTPUT_KEY = /^[a-z][a-z0-9_]{0,39}$/; const MAX_OUTPUT_ENTRIES = 16; const MAX_OUTPUT_VALUE = 2048; diff --git a/src/workflow/summary.mjs b/src/workflow/summary.mjs index bff352ba..be99ccc2 100644 --- a/src/workflow/summary.mjs +++ b/src/workflow/summary.mjs @@ -1,8 +1,7 @@ // End-of-run summary (adlc-workspace#66). // // One message that says how a run ended, built only from the run's own files -// (.adlc/workflows/runs//state.json, inputs.json, log.jsonl and the -// run copy of the workflow definition). The engine makes no network call here (ADR-416): a runtime +// (.adlc/workflows/runs//state.json, inputs.json and log.jsonl). The engine makes no network call here (ADR-416): a runtime // that relays runs to a chat thread forwards `text` as it is. // // Every string that came from a step (errors, conclusions, links, who answered @@ -12,8 +11,6 @@ import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { redactSecrets } from "./redact.mjs"; -import { gateStepIds } from "./gate-payload.mjs"; -import { WorkflowDefinition } from "./engine.mjs"; export const SUMMARY_MAX_CHARS = 3000; export const SUMMARY_FIELD_CHARS = 300; @@ -69,26 +66,6 @@ function stepLinks(output) { return links.filter((l) => LINK.test(l)); } -// Gate ids from the run copy of the definition (runs//workflow.yml): the -// file the engine executes and resumes from, so the same source the engine's -// own gate decisions come from. log.jsonl is only an ordering hint: anything -// in the workspace can append to it. No readable copy: no gate lines. -function definedGateIds(runDir) { - const copy = join(runDir, "workflow.yml"); - if (!existsSync(copy)) return null; - let data = null; - try { - data = WorkflowDefinition.fromYamlFile(copy).data; - } catch { - try { - data = JSON.parse(readFileSync(copy, "utf-8").replace(/^# serialized from string source\n/, "")); - } catch { - return null; - } - } - return data && typeof data === "object" ? new Set(gateStepIds(data.steps)) : null; -} - /** * Build the summary of one run from its directory. Returns null when the run * has no readable state.json. @@ -99,7 +76,6 @@ export function buildRunSummary(runDir, { env = process.env } = {}) { const inputs = (readJson(join(runDir, "inputs.json")) ?? {}).inputs ?? {}; const log = readLines(join(runDir, "log.jsonl")); const results = state.step_results && typeof state.step_results === "object" ? state.step_results : {}; - const gateIds = definedGateIds(runDir) ?? new Set(); // Step order: as the run started them (log.jsonl), then any result the log // does not name, in state order. @@ -125,11 +101,13 @@ export function buildRunSummary(runDir, { env = process.env } = {}) { if (!r || typeof r !== "object") continue; const output = r.output && typeof r.output === "object" ? r.output : {}; const step = { id: cleanField(id, 80, env), status: typeof r.status === "string" ? r.status : "unknown" }; - if (types[id]) step.type = types[id]; + const type = typeof r.type === "string" ? r.type : types[id]; + if (type) step.type = type; steps.push(step); - // Gates only by the run's definition: any other step can write - // `choice`/`answered_by` to its own output. - if (gateIds.has(id) && typeof output.choice === "string") { + // Gates only by the type the engine recorded in the step's result (its + // runtime id, never the step's own output or the log). Step output cannot + // carry `choice`/`answered_by`/`auto_passed` (reserved in readStepOutput). + if (r.type === "gate" && typeof output.choice === "string") { const gate = { id: step.id, choice: cleanField(output.choice, 40, env) }; if (typeof output.answered_by === "string" && ANSWERER.test(output.answered_by)) gate.answered_by = output.answered_by; if (output.auto_passed === true) gate.auto = true; diff --git a/tests/workflow-summary.test.mjs b/tests/workflow-summary.test.mjs index d1d27fd5..f4e0d4d2 100644 --- a/tests/workflow-summary.test.mjs +++ b/tests/workflow-summary.test.mjs @@ -38,25 +38,17 @@ process.on("exit", () => { } }); -// The run copy of the definition (runs//workflow.yml) is what the engine -// executes and resumes from; the summary takes its gate ids from it. `defined` -// overrides the step types written there (default: the logged ones). -function writeDefinition(dir, defined) { - const lines = ['schema_version: "1.0"', "workflow:", " id: w", " name: W", ' version: "1.0.0"', "steps:"]; - for (const [id, type] of defined) { - lines.push(` - id: ${id}`); - if (type) lines.push(` type: ${type}`); - if (type === "gate") lines.push(' message: "?"', " options: [approve, reject]"); - if (type === "shell") lines.push(" run: \"true\""); - if (type === "command" || !type) lines.push(" command: x"); - } - writeFileSync(join(dir, "workflow.yml"), lines.join("\n") + "\n"); -} - -function writeRun(root, runId, { state, inputs = {}, steps = [], resumes = 0, defined = steps, definition = true }) { +// The engine records each step's type in its result (state.json +// step_results[].type); the summary decides gates by it. `defined` sets +// those types (default: the logged ones); `engineTypes: false` leaves them out. +function writeRun(root, runId, { state, inputs = {}, steps = [], resumes = 0, defined = steps, engineTypes = true }) { const dir = join(root, ".adlc", "workflows", "runs", runId); mkdirSync(join(dir, "trace"), { recursive: true }); - if (definition) writeDefinition(dir, defined.filter(([id], i, a) => a.findIndex(([j]) => j === id) === i)); + if (engineTypes && state.step_results) { + const typeOf = {}; + for (const [id, type] of defined) if (!(id in typeOf)) typeOf[id] = type; + for (const [id, r] of Object.entries(state.step_results)) if (r.type === undefined && typeOf[id]) r.type = typeOf[id]; + } writeFileSync(join(dir, "state.json"), JSON.stringify({ run_id: runId, ...state })); writeFileSync(join(dir, "inputs.json"), JSON.stringify({ inputs })); const log = []; @@ -432,7 +424,7 @@ test("S6: an answerer that looks like a mention is never rendered as one", () => assert.ok(!s.text.includes("@channel"), s.text); }); -test("S5: the log cannot turn a step into a gate: the run's definition decides", () => { +test("S5: the log cannot turn a step into a gate: the engine-recorded type decides", () => { const root = tempDir("sum-"); const dir = writeRun(root, "r8", { steps: [["fake", "gate"], ["fake", "shell"]], defined: [["fake", "shell"]], @@ -442,10 +434,10 @@ test("S5: the log cannot turn a step into a gate: the run's definition decides", assert.deepEqual(buildRunSummary(dir).gates, []); }); -test("S5: without the run's definition there are no gate lines (fail closed)", () => { +test("S5: a result with no engine-recorded type is not a gate (fail closed)", () => { const root = tempDir("sum-"); const dir = writeRun(root, "r9", { - steps: [["gate-spec", "gate"]], definition: false, + steps: [["gate-spec", "gate"]], engineTypes: false, state: { workflow_id: "w", status: "completed", created_at: "2026-11-23T08:00:00Z", updated_at: "2026-11-23T08:00:01Z", step_results: { "gate-spec": { status: "completed", output: { choice: "approve", answered_by: "U1" } } } }, }); @@ -462,3 +454,13 @@ test("S1: a real paused-and-resumed run: gate credited, one resume, from the eng assert.match(s.text, /• gate-spec: approve \(by U03T2SB0B\)/); assert.match(s.text, /Resumed 1 time$/); }); + +test("S5: step output cannot carry gate fields (reserved keys)", async () => { + const { readStepOutput } = await import("../src/workflow/steps/agent.mjs"); + const d = tempDir("sum-res-"); + for (const key of ["choice", "answered_by", "auto_passed"]) { + const f = join(d, `${key}.json`); + writeFileSync(f, JSON.stringify({ conclusion: "ok", [key]: "x" })); + assert.deepEqual(readStepOutput(f, "s"), {}, key); + } +});