From 7bedaa523a039c63f780665a6b1c535d3eb0ca7c Mon Sep 17 00:00:00 2001 From: itai Date: Mon, 23 Nov 2026 11:21:27 +0200 Subject: [PATCH 1/4] fix(workflow): a step that concludes blocked: fails the run An agent step that exited 0 with a `blocked:` conclusion (for example factory-mission --plan refusing on the dependency gate) completed, so the next gate paused with nothing to approve and an approval started execute on a refused mission (adlc-workspace#167, run fa82c68a). The engine now fails such a step with the conclusion as the error, before any question payload is read. The run ends failed without fast_failure, so `workflow run` exits 10 and the lane does not retry. Other conclusions keep today's behaviour. Refs adlc-workspace#167 Co-Authored-By: Claude Opus 5.5 --- README.md | 9 + src/workflow/steps/agent.mjs | 13 ++ tests/workflow-blocked-conclusion.test.mjs | 203 +++++++++++++++++++++ 3 files changed, 225 insertions(+) create mode 100644 tests/workflow-blocked-conclusion.test.mjs diff --git a/README.md b/README.md index 2104c9d8..f3b1cd54 100644 --- a/README.md +++ b/README.md @@ -282,6 +282,15 @@ 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, 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. 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/steps/agent.mjs b/src/workflow/steps/agent.mjs index 05686387..86913f09 100644 --- a/src/workflow/steps/agent.mjs +++ b/src/workflow/steps/agent.mjs @@ -202,6 +202,19 @@ 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. + if (typeof output.conclusion === "string" && /^\s*blocked:/i.test(output.conclusion)) { + return new StepResult({ + status: StepStatus.FAILED, + error: `Agent step ${rid(config)}: ${output.conclusion.trim()}`, + 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. diff --git a/tests/workflow-blocked-conclusion.test.mjs b/tests/workflow-blocked-conclusion.test.mjs new file mode 100644 index 00000000..78f28bfa --- /dev/null +++ b/tests/workflow-blocked-conclusion.test.mjs @@ -0,0 +1,203 @@ +// 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.notEqual(failed.status, "aborted"); // not a reject + assert.match(failed.error ?? "", /blocked: dependency-gate/); +}); From 7835b7bcb7f0caa2b2f75c821820dd7fc42eeef5 Mon Sep 17 00:00:00 2001 From: itai Date: Mon, 23 Nov 2026 11:24:39 +0200 Subject: [PATCH 2/4] fix(workflow): only a gate's boolean aborted ends a run aborted; redact blocked errors Security review of the blocked-conclusion change: a blocked step keeps its merged agent output, so an agent-written "aborted" string would have turned the failure into an abort (exit 1, retried). The engine now compares `aborted === true`, which only the gate sets. The blocked error is passed through redactSecrets with the agent's env and kept on one line. Refs adlc-workspace#167 Co-Authored-By: Claude Opus 5.5 --- src/workflow/engine.mjs | 7 +++++-- src/workflow/steps/agent.mjs | 5 ++++- tests/workflow-blocked-conclusion.test.mjs | 20 ++++++++++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) 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 86913f09..e69cd8d8 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 ?? "?"}'`; @@ -211,7 +212,9 @@ async function runAgentStep({ agentKey, model, mode, prompt, context, config, ti if (typeof output.conclusion === "string" && /^\s*blocked:/i.test(output.conclusion)) { return new StepResult({ status: StepStatus.FAILED, - error: `Agent step ${rid(config)}: ${output.conclusion.trim()}`, + // 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). + error: `Agent step ${rid(config)}: ${redactSecrets(output.conclusion, { ...process.env, ...runEnv }).replace(/[\u0000-\u001f\u007f]+/g, " ").trim()}`, output, }); } diff --git a/tests/workflow-blocked-conclusion.test.mjs b/tests/workflow-blocked-conclusion.test.mjs index 78f28bfa..11c6f646 100644 --- a/tests/workflow-blocked-conclusion.test.mjs +++ b/tests/workflow-blocked-conclusion.test.mjs @@ -201,3 +201,23 @@ test("B2: `adlc-cli workflow run` exits 10 on a blocked plan", { skip: !POSIX }, assert.notEqual(failed.status, "aborted"); // 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/); +}); From 6b38ebf89040662c461214f053971914c47a5ff9 Mon Sep 17 00:00:00 2001 From: itai Date: Mon, 23 Nov 2026 14:30:39 +0200 Subject: [PATCH 3/4] fix(workflow): read a blocked conclusion before output validation (fail closed) factory-review F2 on #118: step output merges all-or-nothing, so a `blocked:` conclusion next to one invalid sibling field (a number, a reserved key, >16 fields, a >2048-char value) or in a file that does not parse was dropped, the step completed, and the run paused at the spec gate with nothing to approve, the #167 failure again. The refusal is now read from the raw file before validation. Also: invisible format characters (U+200B, U+FEFF) before the prefix no longer hide it; C1 controls are collapsed in the error; the CLI test asserts run_failed status "failed"; the README says what the error holds. Refs adlc-workspace#167 Co-Authored-By: Claude Opus 5.5 --- README.md | 13 ++++--- src/workflow/steps/agent.mjs | 45 ++++++++++++++++++++-- tests/workflow-blocked-conclusion.test.mjs | 37 +++++++++++++++++- 3 files changed, 86 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index f3b1cd54..2361b220 100644 --- a/README.md +++ b/README.md @@ -285,11 +285,14 @@ 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, 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. A conclusion that only mentions it later -completes as before. A blocked step never pauses on a question payload. +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 diff --git a/src/workflow/steps/agent.mjs b/src/workflow/steps/agent.mjs index e69cd8d8..84ea359e 100644 --- a/src/workflow/steps/agent.mjs +++ b/src/workflow/steps/agent.mjs @@ -208,13 +208,16 @@ async function runAgentStep({ agentKey, model, mode, prompt, context, config, ti // 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. - if (typeof output.conclusion === "string" && /^\s*blocked:/i.test(output.conclusion)) { + // 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). - error: `Agent step ${rid(config)}: ${redactSecrets(output.conclusion, { ...process.env, ...runEnv }).replace(/[\u0000-\u001f\u007f]+/g, " ").trim()}`, + error: `Agent step ${rid(config)}: ${redactSecrets(blocked, { ...process.env, ...runEnv }).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim()}`, output, }); } @@ -250,6 +253,42 @@ 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 returned text is capped at the output value limit. +const BLOCKED_PREFIX = /^[\s\p{Cf}]*blocked:/iu; +const BLOCKED_IN_RAW = /"conclusion"\s*:\s*"((?:[^"\\]|\\.){0,2048})/; + +function readBlockedConclusion(path) { + if (!path || !existsSync(path)) return null; + let raw; + try { + raw = readFileSync(path, "utf-8"); + } catch { + return null; + } + if (raw.length > MAX_OUTPUT_FILE) raw = raw.slice(0, MAX_OUTPUT_FILE); + let conclusion = null; + try { + const data = JSON.parse(raw); + if (data && typeof data === "object" && !Array.isArray(data) && typeof data.conclusion === "string") { + conclusion = data.conclusion; + } + } catch { + // Not JSON: fall back to the first "conclusion" string in the text. + const m = BLOCKED_IN_RAW.exec(raw); + if (m) { + try { conclusion = JSON.parse(`"${m[1]}"`); } catch { conclusion = m[1]; } + } + } + if (typeof conclusion !== "string" || !BLOCKED_PREFIX.test(conclusion)) return null; + return conclusion.replace(/^[\s\p{Cf}]+/u, "").slice(0, MAX_OUTPUT_VALUE); +} + // ── 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 index 11c6f646..08145baa 100644 --- a/tests/workflow-blocked-conclusion.test.mjs +++ b/tests/workflow-blocked-conclusion.test.mjs @@ -198,7 +198,7 @@ test("B2: `adlc-cli workflow run` exits 10 on a blocked plan", { skip: !POSIX }, 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.notEqual(failed.status, "aborted"); // not a reject + assert.equal(failed.status, "failed"); // a logical failure, not a reject assert.match(failed.error ?? "", /blocked: dependency-gate/); }); @@ -221,3 +221,38 @@ test("B6: the blocked error is redacted and kept on one line", { skip: !POSIX }, 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]/); +}); From a93d2c9a5a4c9de980e38df4dcf7506ee37f0e0b Mon Sep 17 00:00:00 2001 From: itai Date: Mon, 23 Nov 2026 14:33:30 +0200 Subject: [PATCH 4/4] fix(workflow): redact the whole blocked conclusion before capping it Security review of 6b38ebf: - the conclusion is redacted in full, then collapsed and capped, so a secret across the 2048-character cut is never half-kept; - in a file that does not parse, every "conclusion" string is decoded (valid escapes one by one) before the prefix check and redaction, so glpat-... is redacted as glpat-..., and a blocked conclusion after another one still counts. An unreadable or oversized file keeps today's outcome unless a readable, bounded part of it says blocked:, so a run that never refused is unchanged. Refs adlc-workspace#167 Co-Authored-By: Claude Opus 5.5 --- src/workflow/steps/agent.mjs | 35 ++++++++++++++-------- tests/workflow-blocked-conclusion.test.mjs | 27 +++++++++++++++++ 2 files changed, 50 insertions(+), 12 deletions(-) diff --git a/src/workflow/steps/agent.mjs b/src/workflow/steps/agent.mjs index 84ea359e..a008c5df 100644 --- a/src/workflow/steps/agent.mjs +++ b/src/workflow/steps/agent.mjs @@ -217,7 +217,8 @@ async function runAgentStep({ agentKey, model, mode, prompt, context, config, ti 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). - error: `Agent step ${rid(config)}: ${redactSecrets(blocked, { ...process.env, ...runEnv }).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim()}`, + // 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, }); } @@ -259,9 +260,20 @@ async function runAgentStep({ agentKey, model, mode, prompt, context, config, ti // 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 returned text is capped at the output value limit. +// The caller redacts the whole text before it caps it. const BLOCKED_PREFIX = /^[\s\p{Cf}]*blocked:/iu; -const BLOCKED_IN_RAW = /"conclusion"\s*:\s*"((?:[^"\\]|\\.){0,2048})/; +// 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; @@ -269,24 +281,23 @@ function readBlockedConclusion(path) { 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); - let conclusion = null; + const candidates = []; try { const data = JSON.parse(raw); if (data && typeof data === "object" && !Array.isArray(data) && typeof data.conclusion === "string") { - conclusion = data.conclusion; + candidates.push(data.conclusion); } } catch { - // Not JSON: fall back to the first "conclusion" string in the text. - const m = BLOCKED_IN_RAW.exec(raw); - if (m) { - try { conclusion = JSON.parse(`"${m[1]}"`); } catch { conclusion = m[1]; } - } + // Not JSON: every "conclusion" string in the text counts, decoded. + for (const m of raw.matchAll(CONCLUSION_IN_RAW)) candidates.push(decodeJsonStringBody(m[1])); } - if (typeof conclusion !== "string" || !BLOCKED_PREFIX.test(conclusion)) return null; - return conclusion.replace(/^[\s\p{Cf}]+/u, "").slice(0, MAX_OUTPUT_VALUE); + const hit = candidates.find((c) => BLOCKED_PREFIX.test(c)); + return hit === undefined ? null : hit.replace(/^[\s\p{Cf}]+/u, ""); } // ── question payload (adlc-workspace#148) ───────────────────────────────── diff --git a/tests/workflow-blocked-conclusion.test.mjs b/tests/workflow-blocked-conclusion.test.mjs index 08145baa..0dcb266a 100644 --- a/tests/workflow-blocked-conclusion.test.mjs +++ b/tests/workflow-blocked-conclusion.test.mjs @@ -256,3 +256,30 @@ 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); +});