diff --git a/README.md b/README.md index 2104c9d8..2361b220 100644 --- a/README.md +++ b/README.md @@ -282,6 +282,18 @@ later step or gate can read them, for example a rule, the file is ignored with a log line. Stdout is never parsed for results. +**A `conclusion` that starts with `blocked:` fails the step.** An agent +(`command`/`prompt`) step that exits 0 but writes, for example, +`{"conclusion": "blocked: dependency-gate on #164 (open)"}` has refused its +work. The engine fails the step with that text as the error (secrets +redacted, kept on one line), so no later gate pauses with nothing to approve +and no later step runs. The run ends `failed` and `workflow run` exits 10, a +logical failure that a lane does not retry. The prefix is case-insensitive +and may follow whitespace or invisible format characters. The refusal counts +even when the rest of the file breaks the rules above, because it is read +before validation. A conclusion that only mentions it later completes as +before. A blocked step never pauses on a question payload. + **Passing values to a `shell` step: use `env:`, not the script text.** A `{{ … }}` expression inside `run` is pasted into the script as text before the shell reads it, so a value with a quote, a backtick or `$(…)` becomes shell diff --git a/src/workflow/engine.mjs b/src/workflow/engine.mjs index f8cef7c4..9f4521be 100644 --- a/src/workflow/engine.mjs +++ b/src/workflow/engine.mjs @@ -1163,7 +1163,10 @@ export class WorkflowEngine { return; } - if (result.output.aborted) { + // Strict: only a gate's boolean `true` aborts. Agent step output is + // merged as strings and must never select the aborted state + // (adlc-workspace#167 security review). + if (result.output.aborted === true) { state.status = RunStatus.ABORTED; state.error = result.error; await state.appendLog({ event: "workflow_aborted", step_id: stepId }); @@ -1326,7 +1329,7 @@ export class WorkflowEngine { if (rec.status === StepStatus.PAUSED) return RunStatus.PAUSED; if (rec.status === StepStatus.FAILED) { const out = rec.output ?? {}; - if (out.aborted) return RunStatus.ABORTED; + if (out.aborted === true) return RunStatus.ABORTED; if (template.continue_on_error !== true) return RunStatus.FAILED; } return null; diff --git a/src/workflow/steps/agent.mjs b/src/workflow/steps/agent.mjs index 05686387..a008c5df 100644 --- a/src/workflow/steps/agent.mjs +++ b/src/workflow/steps/agent.mjs @@ -13,6 +13,7 @@ import { readAgent } from "../../utils/init-options.mjs"; import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { currentHeadSha } from "../gate-context.mjs"; +import { redactSecrets } from "../redact.mjs"; const rid = (config) => `'${config.id ?? "?"}'`; @@ -202,6 +203,25 @@ async function runAgentStep({ agentKey, model, mode, prompt, context, config, ti }); } Object.assign(output, readStepOutput(runEnv.ADLC_STEP_OUTPUT, rid(config))); + // A refusal ends the run (adlc-workspace#167): a step whose conclusion + // starts with `blocked:` (a dependency gate, no issue, a refused publish) + // FAILS even though the agent exited 0, so no later gate pauses with + // nothing to approve and no later step runs. A logical failure — never + // fast_failure — so `workflow run` exits 10 and the lane does not retry. + // Checked before the question payload: a refused step never asks. Read from + // the raw file, not the validated merge: one invalid sibling field drops + // the whole object, and the refusal must still end the run (fail closed). + const blocked = readBlockedConclusion(runEnv.ADLC_STEP_OUTPUT); + if (blocked !== null) { + return new StepResult({ + status: StepStatus.FAILED, + // Agent-written text: redact secrets with the env the agent ran with, + // and keep it on one line (it reaches run_failed and the runtime log). + // Redact the whole text first, then collapse and cap it. + error: `Agent step ${rid(config)}: ${redactSecrets(blocked, { ...process.env, ...runEnv }).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim().slice(0, MAX_OUTPUT_VALUE)}`, + output, + }); + } // Question payload (adlc-workspace#148): after exit 0, a valid // runs//questions/.json pauses the run with kind=question // instead of completing. Invalid payloads keep COMPLETED with a warning. @@ -234,6 +254,52 @@ async function runAgentStep({ agentKey, model, mode, prompt, context, config, ti return new StepResult({ status: StepStatus.COMPLETED, output }); } +// ── blocked conclusion (adlc-workspace#167) ─────────────────────────────── +// The step's `conclusion` when it starts with `blocked:` (any case, after +// whitespace and invisible format characters such as U+200B), else null. +// Independent of the all-or-nothing output validation: a file the merge +// rejects (a non-string sibling, too many fields, an over-long value, a +// reserved key) or that does not parse as JSON still carries the refusal. +// The caller redacts the whole text before it caps it. +const BLOCKED_PREFIX = /^[\s\p{Cf}]*blocked:/iu; +// Every "conclusion": "" in a file that does not parse, whole (the +// file is already bounded by MAX_OUTPUT_FILE). +const CONCLUSION_IN_RAW = /"conclusion"\s*:\s*"((?:[^"\\]|\\.)*)/g; + +// Decode a JSON string body tolerantly: valid escapes are decoded one by one +// (so `\u0067lpat-…` is redacted as `glpat-…`), invalid ones are left as they +// are, and raw control characters are kept for the caller to collapse. +function decodeJsonStringBody(body) { + const simple = { '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t" }; + return body.replace(/\\(u[0-9a-fA-F]{4}|["\\/bfnrt])/g, (_, e) => + e[0] === "u" ? String.fromCharCode(parseInt(e.slice(1), 16)) : simple[e]); +} + +function readBlockedConclusion(path) { + if (!path || !existsSync(path)) return null; + let raw; + try { + raw = readFileSync(path, "utf-8"); + } catch { + // Unreadable: the merge reads nothing from it either; the step keeps + // today's outcome (only a readable `blocked:` changes it). + return null; + } + if (raw.length > MAX_OUTPUT_FILE) raw = raw.slice(0, MAX_OUTPUT_FILE); + const candidates = []; + try { + const data = JSON.parse(raw); + if (data && typeof data === "object" && !Array.isArray(data) && typeof data.conclusion === "string") { + candidates.push(data.conclusion); + } + } catch { + // Not JSON: every "conclusion" string in the text counts, decoded. + for (const m of raw.matchAll(CONCLUSION_IN_RAW)) candidates.push(decodeJsonStringBody(m[1])); + } + const hit = candidates.find((c) => BLOCKED_PREFIX.test(c)); + return hit === undefined ? null : hit.replace(/^[\s\p{Cf}]+/u, ""); +} + // ── question payload (adlc-workspace#148) ───────────────────────────────── // Caps: max 3 questions per payload, max 3 pauses per step per run. export const MAX_QUESTION_PAUSES = 3; diff --git a/tests/workflow-blocked-conclusion.test.mjs b/tests/workflow-blocked-conclusion.test.mjs new file mode 100644 index 00000000..0dcb266a --- /dev/null +++ b/tests/workflow-blocked-conclusion.test.mjs @@ -0,0 +1,285 @@ +// A step that ends `blocked:` ends the run (adlc-workspace#167). +// +// Evidence: #151 re-send, run fa82c68a (2026-11-22, adlc-cli 2.15.0). The +// `plan` step (factory-mission --plan) hit the dependency hard gate, posted +// its refusal, set the issue back to spec-gated and wrote +// {"conclusion":"blocked: dependency-gate on #164 (open)"} — then exited 0. +// The engine completed the step and paused gate-spec with nothing to +// approve; the approval started `execute` on a refused mission. +// +// Contract pinned here: +// B1 After exit 0, an agent step whose ADLC_STEP_OUTPUT `conclusion` +// starts with `blocked:` (case-insensitive, after leading space) FAILS +// with that conclusion in the error: the run ends failed, no later gate +// pauses and no later step runs. +// B2 It is a logical failure, never the retryable infrastructure one: the +// run state carries no fast_failure, so `workflow run` exits 10 (the +// lane's retryStrategy does not retry 10). +// B3 A conclusion that only mentions "blocked:" later, or no conclusion, +// completes as before; the output object is still merged on B1. +// B4 A blocked conclusion wins over a question payload: a refused step +// never pauses to ask. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync, chmodSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, dirname } from "node:path"; +import { execFileSync, spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { WorkflowEngine, RunStatus } from "../src/workflow/engine.mjs"; +import { STEP_REGISTRY } from "../src/workflow/registry.mjs"; +import { classifyWorkflowStatus } from "../src/exit-codes.mjs"; + +const POSIX = process.platform !== "win32"; +const BIN = join(dirname(fileURLToPath(import.meta.url)), "..", "bin", "adlc-cli.mjs"); +const BLOCKED = "blocked: dependency-gate on #164 (open)"; +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 {} + } +}); + +// A fake `opencode`: for the step named in $FAKE_STEP it writes $FAKE_OUTPUT to +// ADLC_STEP_OUTPUT (and $FAKE_QUESTION to ADLC_STEP_QUESTION); every step +// appends its id to $FAKE_LOG. Always exits 0, like the agent did in fa82c68a. +function installFakeAgent() { + const bin = tempDir("fake-agent-bin-"); + const script = join(bin, "opencode"); + writeFileSync(script, `#!${process.execPath} +const fs = require("node:fs"), path = require("node:path"); +const step = process.env.ADLC_STEP_ID; +if (process.env.FAKE_LOG) fs.appendFileSync(process.env.FAKE_LOG, step + "\\n"); +if (step === process.env.FAKE_STEP) { + if (process.env.FAKE_OUTPUT !== undefined && process.env.ADLC_STEP_OUTPUT) { + fs.mkdirSync(path.dirname(process.env.ADLC_STEP_OUTPUT), { recursive: true }); + fs.writeFileSync(process.env.ADLC_STEP_OUTPUT, process.env.FAKE_OUTPUT); + } + if (process.env.FAKE_QUESTION && process.env.ADLC_STEP_QUESTION) { + fs.mkdirSync(path.dirname(process.env.ADLC_STEP_QUESTION), { recursive: true }); + fs.writeFileSync(process.env.ADLC_STEP_QUESTION, process.env.FAKE_QUESTION); + } +} +console.log(JSON.stringify({ type: "text", text: "ok" })); +process.exit(0); +`); + chmodSync(script, 0o755); + return bin; +} + +function project() { + const dir = tempDir("blocked-"); + execFileSync("git", ["init", "-q", "-b", "main"], { cwd: dir }); + return dir; +} + +// The lane's shape: plan, then the spec gate, then execute. +function laneWorkflow() { + const path = join(tempDir("blocked-wf-"), "workflow.yml"); + writeFileSync(path, `schema_version: "1.0" +workflow: + id: blocked-wf + name: Blocked + version: "1.0.0" + integration: opencode +inputs: + issue_ref: {type: string, default: ""} + verdict: {type: string, default: "", enum: ["", approve, reject]} +steps: + - id: plan + type: command + command: factory-mission + - id: gate-spec + type: gate + message: "Approve the plan?" + options: [approve, reject] + on_reject: abort + verdict_input: verdict + - id: execute + type: command + command: factory-mission +`); + return path; +} + +function withEnv(vars, fn) { + const saved = {}; + for (const k of Object.keys(vars)) saved[k] = process.env[k]; + for (const [k, v] of Object.entries(vars)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + return fn().finally(() => { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + }); +} + +async function runLane({ output, question, step = "plan" } = {}) { + const bin = installFakeAgent(); + const dir = project(); + const log = join(tempDir("log-"), "steps.log"); + return withEnv({ + PATH: `${bin}:${process.env.PATH}`, FAKE_LOG: log, FAKE_STEP: step, + FAKE_OUTPUT: output, FAKE_QUESTION: question, + }, async () => { + const engine = new WorkflowEngine(dir); + const state = await engine.execute(engine.loadWorkflow(laneWorkflow()), { issue_ref: "g/p#151" }, "r167", STEP_REGISTRY); + let ran = []; + try { ran = (await import("node:fs")).readFileSync(log, "utf-8").trim().split("\n").filter(Boolean); } catch {} + return { state, ran }; + }); +} + +test("B1: a plan step that concludes blocked: fails the run before the spec gate", { skip: !POSIX }, async () => { + const { state, ran } = await runLane({ output: JSON.stringify({ conclusion: BLOCKED }) }); + assert.equal(state.status, RunStatus.FAILED); + assert.deepEqual(ran, ["plan"]); // execute never ran + assert.equal(state.stepResults["gate-spec"], undefined); // the gate never paused + const plan = state.stepResults.plan; + assert.equal(plan.status, "failed"); + assert.match(plan.error, /blocked: dependency-gate on #164 \(open\)/); + assert.equal(plan.output.conclusion, BLOCKED); // the output is still merged +}); + +test("B2: it is a logical failure (exit 10), never the retryable one", { skip: !POSIX }, async () => { + const { state } = await runLane({ output: JSON.stringify({ conclusion: BLOCKED }) }); + assert.notEqual(state.fastFailure, true); + assert.equal(classifyWorkflowStatus(state.status, { fastFailure: state.fastFailure === true }).exitCode, 10); +}); + +for (const conclusion of ["Blocked: factory run without an issue", " blocked: pause publish failed (push refused)"]) { + test(`B1: ${JSON.stringify(conclusion)} counts as blocked`, { skip: !POSIX }, async () => { + const { state, ran } = await runLane({ output: JSON.stringify({ conclusion }) }); + assert.equal(state.status, RunStatus.FAILED); + assert.deepEqual(ran, ["plan"]); + }); +} + +for (const [name, output] of [ + ["a normal conclusion", JSON.stringify({ conclusion: "plan-ready" })], + ["a conclusion that mentions blocked: later", JSON.stringify({ conclusion: "plan-ready; was blocked: by #164, now closed" })], + ["no conclusion", JSON.stringify({ mr_url: "https://gl.test/g/p/-/merge_requests/1" })], + ["no output file", undefined], +]) { + test(`B3: ${name} completes plan and pauses at the gate as before`, { skip: !POSIX }, async () => { + const { state, ran } = await runLane({ output }); + assert.equal(state.status, RunStatus.PAUSED); + assert.deepEqual(ran, ["plan"]); + assert.equal(state.stepResults.plan.status, "completed"); + }); +} + +test("B4: a blocked conclusion wins over a question payload", { skip: !POSIX }, async () => { + const { state } = await runLane({ + output: JSON.stringify({ conclusion: BLOCKED }), + question: JSON.stringify({ summary: "s", questions: [{ id: "q1", text: "Which channel?" }] }), + }); + assert.equal(state.status, RunStatus.FAILED); + assert.equal(state.stepResults.plan.status, "failed"); +}); + +test("B2: `adlc-cli workflow run` exits 10 on a blocked plan", { skip: !POSIX }, () => { + const bin = installFakeAgent(); + const dir = project(); + const r = spawnSync(process.execPath, [BIN, "workflow", "run", laneWorkflow(), "--format", "json", "--input", "issue_ref=g/p#151"], { + cwd: dir, encoding: "utf-8", + env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, FAKE_STEP: "plan", FAKE_OUTPUT: JSON.stringify({ conclusion: BLOCKED }) }, + }); + assert.equal(r.status, 10, r.stderr + r.stdout); + const failed = r.stdout.split("\n").filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }) + .find((e) => e && e.type === "run_failed"); + assert.ok(failed, r.stdout); + assert.equal(failed.status, "failed"); // a logical failure, not a reject + assert.match(failed.error ?? "", /blocked: dependency-gate/); +}); + +// B5 (security review of #118): a blocked step keeps its merged output, so +// agent-written fields must not steer the run. `aborted` (a string here; the +// gate sets the boolean true) must not turn the failure into an abort, which +// exits 1 and is retried. +test("B5: an agent-written aborted field cannot turn a blocked step into an abort", { skip: !POSIX }, async () => { + const { state } = await runLane({ output: JSON.stringify({ conclusion: BLOCKED, aborted: "true" }) }); + assert.equal(state.status, RunStatus.FAILED); + assert.equal(classifyWorkflowStatus(state.status, { fastFailure: state.fastFailure === true }).exitCode, 10); +}); + +test("B6: the blocked error is redacted and kept on one line", { skip: !POSIX }, async () => { + const token = "glpat-" + "a1b2c3d4e5f6g7h8i9j0"; + const { state } = await runLane({ output: JSON.stringify({ conclusion: `blocked: push refused for https://oauth2:${token}@gl.test/g/p.git\nsecond line` }) }); + const err = state.stepResults.plan.error; + assert.equal(state.status, RunStatus.FAILED); + assert.ok(!err.includes(token), err); + assert.ok(!err.includes("\n"), err); + assert.match(err, /blocked: push refused/); +}); + +// B7 (factory-review F2 on #118): step output merges all-or-nothing, so one +// invalid sibling field drops the whole object. The refusal must still end +// the run: it is read from the raw file, before validation (fail closed). +for (const [name, output] of [ + ["a non-string sibling field", JSON.stringify({ conclusion: BLOCKED, elapsed: 12 })], + ["a conclusion over 2048 characters", JSON.stringify({ conclusion: BLOCKED + " " + "x".repeat(2100) })], + ["more than 16 fields", JSON.stringify({ conclusion: BLOCKED, ...Object.fromEntries(Array.from({ length: 16 }, (_, i) => [`k${i}`, "v"])) })], + ["a reserved sibling key", JSON.stringify({ conclusion: BLOCKED, stdout: "x" })], + ["JSON that does not parse", `{"conclusion": "${BLOCKED}", oops}`], +]) { + test(`B7: a blocked conclusion with ${name} still fails the run`, { skip: !POSIX }, async () => { + const { state, ran } = await runLane({ output }); + assert.equal(state.status, RunStatus.FAILED); + assert.deepEqual(ran, ["plan"]); + assert.equal(state.stepResults["gate-spec"], undefined); + assert.match(state.stepResults.plan.error, /blocked: dependency-gate on #164/); + assert.ok(state.stepResults.plan.error.length < 2300); + }); +} + +test("B7: an invalid file without a blocked conclusion still completes as before", { skip: !POSIX }, async () => { + const { state } = await runLane({ output: JSON.stringify({ conclusion: "plan-ready", elapsed: 12 }) }); + assert.equal(state.status, RunStatus.PAUSED); +}); + +test("B8: zero-width and format characters before blocked: do not hide the refusal", { skip: !POSIX }, async () => { + const { state } = await runLane({ output: JSON.stringify({ conclusion: "\u200b\ufeffblocked: dependency-gate on #164 (open)" }) }); + assert.equal(state.status, RunStatus.FAILED); +}); + +test("B6: C1 control characters are collapsed too", { skip: !POSIX }, async () => { + const { state } = await runLane({ output: JSON.stringify({ conclusion: "blocked: a\u0085b\u009bc" }) }); + assert.doesNotMatch(state.stepResults.plan.error, /[\u0080-\u009f]/); +}); + +// B9 (security review of 6b38ebf): redact before truncating, decode the +// malformed-JSON fallback before redacting, and check every conclusion in it. +test("B9: a secret across the 2048-character cut is redacted, not half-kept", { skip: !POSIX }, async () => { + const token = "glpat-" + "a1b2c3d4e5f6g7h8i9j0"; + const pad = "x".repeat(2048 - "blocked: ".length - 10); + const { state } = await runLane({ output: JSON.stringify({ conclusion: `blocked: ${pad} ${token}` }) }); + const err = state.stepResults.plan.error; + assert.equal(state.status, RunStatus.FAILED); + assert.ok(!err.includes("glpat-a1b2"), err.slice(-80)); +}); + +test("B9: an escaped secret in JSON that does not parse is decoded and redacted", { skip: !POSIX }, async () => { + // \u0067 = "g"; a raw tab inside the string makes JSON.parse fail. + const raw = `{"conclusion": "blocked: push refused \\u0067lpat-a1b2c3d4e5f6g7h8i9j0\tx", oops}`; + const { state } = await runLane({ output: raw }); + const err = state.stepResults.plan.error; + assert.equal(state.status, RunStatus.FAILED); + assert.ok(!err.includes("a1b2c3d4e5f6g7h8i9j0"), err); + assert.ok(!err.includes("\\u0067"), err); +}); + +test("B9: a blocked conclusion after another conclusion in a broken file still counts", { skip: !POSIX }, async () => { + const raw = `{"conclusion": "plan-ready", "conclusion": "${BLOCKED}", oops}`; + const { state } = await runLane({ output: raw }); + assert.equal(state.status, RunStatus.FAILED); +});