Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ The live SSH transport is the default: `--provider coder` provisions or reuses a
| `workflow run <source>` | Execute a workflow — YAML path, installed ID, or built-in (`factory` = the outer loop) |
| `workflow resume <run_id>` | 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 <run_id> [--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 <source>` | Validate a definition; `--headless` requires gates to declare `verdict_input` |
| `workflow state …` | LLM-executor helpers: `start/advance/pause/fail/show` (ADR-395) |

Expand Down
28 changes: 28 additions & 0 deletions src/commands/workflow.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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":
Expand Down Expand Up @@ -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 <run_id> [--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)) {
Expand Down
1 change: 1 addition & 0 deletions src/dispatch.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down
1 change: 1 addition & 0 deletions src/help.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export function printCliHelp() {
["workflow restore <run_id>", "Restore a parked run from the remote run ref"],
["workflow board [--remote <name>]", "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 <run_id> [--json]", "One end-of-run message: outcome, MR/PR links, gates, steps"],
["workflow validate <src>", "Validate a workflow definition (--headless checks gate verdicts)"],
["workflow search [query]", "Search available workflows in catalog"],
["workflow add <id|url> [--as <name>]", "Install a workflow from catalog or URL into workspace"],
Expand Down
3 changes: 3 additions & 0 deletions src/workflow/base.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions src/workflow/engine.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 };

Expand Down Expand Up @@ -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 };
Expand Down
4 changes: 3 additions & 1 deletion src/workflow/steps/agent.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
15 changes: 15 additions & 0 deletions src/workflow/steps/gate.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -316,6 +320,17 @@ export class GateStep extends StepBase {
);
}
output.choice = choice;
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);
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)) {
Expand Down
222 changes: 222 additions & 0 deletions src/workflow/summary.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
// 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/<run_id>/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
// 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";

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._-][A-Za-z0-9._@-]{0,63}$/;

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 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);
// 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);

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" };
const type = typeof r.type === "string" ? r.type : types[id];
if (type) step.type = type;
steps.push(step);
// 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;
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;
// 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),
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: "…" };

// 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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
.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), ...(g.answered_by ? { answered_by: e(g.answered_by) } : {}) })),
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);
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;
}
Loading
Loading