@agimon-ai/po-workflow 0.0.0-alpha.29 → 0.0.0-alpha.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RecoverWorkflowService-BAVHSWqr.cjs.map +1 -1
- package/dist/RecoverWorkflowService-Xo-OZAJ4.mjs.map +1 -1
- package/dist/cli.cjs +2 -2
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/cli.mjs.map +1 -1
- package/dist/extensions/server.cjs +2 -2
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.mjs +1 -1
- package/dist/extensions/server.mjs.map +1 -1
- package/package.json +9 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RecoverWorkflowService-BAVHSWqr.cjs","names":["getOrThrow","resolve","parseYaml","WORKFLOW_DISPATCH_TRIGGER","CUSTOM_RUN_KEY","INTERACTIVE_RUN_KEY","stepLabel","z","BACKGROUND_CONTEXT","getOrThrow","CUSTOM_RUN_KEY","Liquid","resolve","pathExists","getOrThrow","parseYaml","resolve","getOrThrow","performance","spawn","constants","spawn","errorMessage","mkdir","join","writeFile","createRequire","path","fs","RMUX","NativeTerminalService","spawn","serveNativeTerminal","createServer","join","createConnection","connectNativeTerminal","createRequire","join","dirname","NativeTerminalService","serveNativeTerminal","connectNativeTerminal","createInterface","writeFile","link","lock","chmod","spawn","execFileSync","open","constants","createHash","join","nodeHost","createSerialRunner","dirname","getOrThrow","resolve","createHash","relative","FIX_FILENAME","join","randomUUID","getOrThrow","pathExists","writeFileAtomic","getOrThrow","resolve","DEFAULT_WORKSPACE","COMPLETED_STAGE","ERROR_STAGE","RUN_RECORD_FILENAME","FIX_FILENAME","PROCEED_FILENAME","PAUSE_REQUEST_FILENAME","ISSUES_DIRNAME","REPAIR_FILENAME","INTERRUPTED_EXIT_CODE","createSerialRunner","resolve","randomUUID","getOrThrow","writeFileAtomic","RESET","BOLD","DIM","GREEN","RED","BLUE","resolve","pathExists","join","dirname","RESET","BOLD","DIM","GREEN","YELLOW","RED","WORKFLOW_JOB_NAME_ENV_KEY","envFlagEnabled","randomUUID","resolve","pathExists","dirname","z","join","getOrThrow","RESET","DIM","CYAN","GREEN","YELLOW","RED","INTERRUPT_SIGNAL","HANGUP_SIGNAL","TERMINATE_SIGNAL","resolve","join","dirname","pathExists","getOrThrow","randomUUID","_exhaustive","writeFileAtomic","RESET","BOLD","DIM","CYAN","GREEN","RED","BLUE","INTERRUPT_SIGNAL","resolve","getOrThrow","dirname","basename","resolve","getOrThrow","RESET","DIM","YELLOW","resolve","dirname","basename","pathExists","removePath","FIX_FRONTMATTER_DELIMITER","FIX_RESTART_FROM_KEY","FIX_STATUS_KEY","FIX_TERMINAL_TARGET","ERROR_STAGE","REPAIR_TRIAGE_JOB_NAME","resolve","createHash","dirname","relative","basename","extname","getOrThrow","serializeYaml","pathExists"],"sources":["../src/services/workflowDiscovery/index.ts","../src/services/WorkflowCatalogService/index.ts","../src/schemas/workflowEngine.ts","../src/services/workflowRuntime/index.ts","../src/services/workflowShell/index.ts","../src/services/WorkflowParserService/index.ts","../src/services/WorkflowDoctorService/index.ts","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/errors.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/command.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/duration.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/process.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/control.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/expectations.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/compatibility.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/lifecycle.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/locators.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/snapshot.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/streams.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/validation.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/handles/pane.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/handles/window.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/handles/session.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/pane-set.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/builder.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/trace.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/rmux.js","../src/services/workflowHost/nativeTerminal.ts","../src/services/workflowHost/terminalSocket.ts","../src/services/workflowHost/index.ts","../src/services/NativeTerminalService/terminalSocket.ts","../src/services/NativeTerminalService/index.ts","../src/services/RunDirectoryService/index.ts","../src/services/StepDecisionService/index.ts","../src/models/InvalidWorkflowRunRecordError.ts","../src/models/WorkflowRunConflictError.ts","../src/services/WorkflowProgressService/index.ts","../src/services/WorkflowRegistryService/index.ts","../src/models/WorkflowCapacityError.ts","../src/models/WorkflowInterruptedError.ts","../src/services/BackgroundServiceManager/index.ts","../src/services/workflowTelemetry/index.ts","../src/services/JobRunnerService/index.ts","../src/models/WorkflowStepSpawnError.ts","../src/models/WorkflowStepTimeoutConfigError.ts","../src/schemas/workflowStepTimeout.ts","../src/services/CodexQuotaService/index.ts","../src/services/StepRunnerService/index.ts","../src/services/TriggerService/index.ts","../src/services/WorkflowRepairService/index.ts","../src/services/WorktreeService/index.ts","../src/services/RunWorkflowService/index.ts","../src/services/RecoverWorkflowService/index.ts"],"sourcesContent":["import { resolve } from 'node:path';\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\nimport { load as parseYaml } from 'js-yaml';\n\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nconst MAX_DIRECTORY_DEPTH = 4;\nconst WORKFLOW_FILE_PATTERN = /\\.workflow\\.ya?ml$/;\n\nexport interface WorkflowSummary {\n path: string;\n name: string;\n description: string;\n tags: string[];\n}\n\nexport interface WorkflowTagSummary {\n count: number;\n tag: string;\n}\n\nexport interface WorkflowListPagination {\n currentPage: number;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n pageSize: number;\n totalPages: number;\n totalWorkflows: number;\n}\n\nexport interface WorkflowListResult {\n directory: string;\n filter?: string;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n page: number;\n pageSize: number;\n pagination: WorkflowListPagination;\n tagFilter?: string[];\n tags: WorkflowTagSummary[];\n total: number;\n totalPages: number;\n workflows: WorkflowSummary[];\n}\n\ninterface WorkflowMetadata {\n name?: unknown;\n description?: unknown;\n tags?: unknown;\n}\n\ninterface ListWorkflowsOptions {\n page: number;\n pageSize: number;\n filter?: string;\n format: 'json' | 'text';\n tags?: string[];\n}\n\n/** Workflow files under `directory`, relative to it, skipping hidden entries and symlinks. */\nexport async function findWorkflowPaths(\n runtime: WorkflowRuntimeContext,\n directory: string,\n relativeDirectory = '',\n depth = 0,\n): Promise<string[]> {\n const entries = getOrThrow(\n await runtime.fs.listDir(resolve(runtime.cwd, directory, relativeDirectory), runtime.ioContext),\n );\n const paths: string[] = [];\n\n for (const entry of entries) {\n if (entry.kind === 'symlink' || entry.name.startsWith('.')) {\n continue;\n }\n\n const relativePath = relativeDirectory ? `${relativeDirectory}/${entry.name}` : entry.name;\n if (entry.kind === 'file' && WORKFLOW_FILE_PATTERN.test(entry.name)) {\n paths.push(relativePath);\n } else if (entry.kind === 'directory' && depth < MAX_DIRECTORY_DEPTH) {\n paths.push(...(await findWorkflowPaths(runtime, directory, relativePath, depth + 1)));\n }\n }\n\n return paths;\n}\n\nasync function readWorkflowSummary(\n runtime: WorkflowRuntimeContext,\n directory: string,\n path: string,\n): Promise<WorkflowSummary> {\n const parsed = parseYaml(\n getOrThrow(await runtime.fs.readTextFile(resolve(directory, path), runtime.ioContext)),\n ) as WorkflowMetadata | null;\n const tags = Array.isArray(parsed?.tags)\n ? [\n ...new Set(\n parsed.tags\n .filter((tag): tag is string => typeof tag === 'string')\n .map((tag) => tag.trim().toLocaleLowerCase())\n .filter(Boolean),\n ),\n ].sort()\n : [];\n return {\n path,\n name: typeof parsed?.name === 'string' ? parsed.name : '',\n description: typeof parsed?.description === 'string' ? parsed.description : '',\n tags,\n };\n}\n\nexport async function listWorkflows(\n runtime: WorkflowRuntimeContext,\n directory: string,\n options: Pick<ListWorkflowsOptions, 'filter' | 'page' | 'pageSize' | 'tags'>,\n): Promise<WorkflowListResult> {\n const resolvedDirectory = resolve(runtime.cwd, directory);\n const summaries = await Promise.all(\n (await findWorkflowPaths(runtime, resolvedDirectory))\n .sort()\n .map((path) => readWorkflowSummary(runtime, resolvedDirectory, path)),\n );\n const normalizedFilter = options.filter?.trim().toLocaleLowerCase();\n const textFiltered = normalizedFilter\n ? summaries.filter(({ path, name, description, tags }) =>\n `${path}\\n${name}\\n${description}\\n${tags.join('\\n')}`.toLocaleLowerCase().includes(normalizedFilter),\n )\n : summaries;\n const tagFilter = [\n ...new Set(options.tags?.map((tag) => tag.trim().toLocaleLowerCase()).filter(Boolean) ?? []),\n ].sort();\n const filtered =\n tagFilter.length > 0\n ? textFiltered.filter((workflow) => tagFilter.every((tag) => workflow.tags.includes(tag)))\n : textFiltered;\n const tagCounts = new Map<string, number>();\n for (const workflow of filtered) {\n for (const tag of workflow.tags) {\n tagCounts.set(tag, (tagCounts.get(tag) ?? 0) + 1);\n }\n }\n const tags = [...tagCounts.entries()]\n .map(([tag, count]) => ({ count, tag }))\n .sort((left, right) => left.tag.localeCompare(right.tag));\n const start = (options.page - 1) * options.pageSize;\n const total = filtered.length;\n const totalPages = Math.ceil(total / options.pageSize);\n const hasNextPage = options.page < totalPages;\n const hasPreviousPage = options.page > 1 && total > 0;\n\n return {\n directory: resolvedDirectory,\n ...(normalizedFilter ? { filter: options.filter?.trim() } : {}),\n hasNextPage,\n hasPreviousPage,\n page: options.page,\n pageSize: options.pageSize,\n pagination: {\n currentPage: options.page,\n hasNextPage,\n hasPreviousPage,\n pageSize: options.pageSize,\n totalPages,\n totalWorkflows: total,\n },\n ...(tagFilter.length > 0 ? { tagFilter } : {}),\n tags,\n total,\n totalPages,\n workflows: filtered.slice(start, start + options.pageSize),\n };\n}\n","/**\n * WorkflowCatalogService\n *\n * The repository's workflows, and the parsed detail a surface needs to launch\n * one of them.\n *\n * WHY THIS LIVES HERE:\n * Listing workflow files and reading their triggers, inputs, jobs and runner\n * maps is the same work whichever surface asks: a terminal picker, a cockpit\n * drawer, or an agent choosing what to launch. Each of them used to parse the\n * YAML again in its own vocabulary, which is how two surfaces come to disagree\n * about what a workflow requires.\n *\n * DESIGN PATTERNS:\n * - Discovery reuses the list-workflows command, so the catalog and the tool\n * can never find different files\n * - A parse failure is returned as `error`, never thrown: one unparseable file\n * in a repository must not take a whole board down\n * - Parsing is injected, so a caller that already holds a parser reuses it and\n * a test can supply a workflow object directly\n *\n * CODING STANDARDS:\n * - Named exports only\n * - Explicit return types on exported members\n *\n * AVOID:\n * - Paging here: a surface shows a repository's workflows, and repositories\n * have tens of them, not thousands\n */\n\nimport type { Job, Step, Workflow } from '../../schemas/workflowEngine';\nimport { listWorkflows } from '../workflowDiscovery';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport type {\n WorkflowArtifactSummary,\n WorkflowCatalogEntry,\n WorkflowInputSummary,\n WorkflowJobSummary,\n WorkflowSummaryDetail,\n} from './types';\n\n/** One page big enough for any repository, since this surface does not page. */\nconst CATALOG_PAGE_SIZE = 1000;\nconst CATALOG_PAGE = 1;\nconst WORKFLOW_DISPATCH_TRIGGER = 'workflow_dispatch';\nconst INPUTS_KEY = 'inputs';\nconst RUN_KEYS = ['interactiveRun', 'run'] as const;\nconst CUSTOM_RUN_KEY = 'customRun';\nconst INTERACTIVE_RUN_KEY = 'interactiveRun';\n\n/** Parses one workflow file into the engine's own shape. */\nexport type WorkflowFileParser = (workflowPath: string) => Workflow | Promise<Workflow>;\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};\n}\n\nfunction triggerBlock(workflow: Workflow): Record<string, unknown> {\n return asRecord(workflow.on);\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];\n}\n\n/**\n * The `workflow_dispatch` inputs a launch must collect.\n *\n * Read leniently: an input block that does not match the declared shape is\n * skipped rather than failing the whole read, because a surface that cannot\n * show one field is still more useful than one that shows none.\n */\nexport function describeWorkflowDispatch(workflow: Workflow): WorkflowInputSummary[] {\n const dispatch = triggerBlock(workflow)[WORKFLOW_DISPATCH_TRIGGER];\n const declarations = asRecord(asRecord(dispatch)[INPUTS_KEY]);\n const summaries: WorkflowInputSummary[] = [];\n for (const [name, declaration] of Object.entries(declarations)) {\n const definition = asRecord(declaration);\n summaries.push({\n name,\n ...(typeof definition.description === 'string' ? { description: definition.description } : {}),\n ...(typeof definition.required === 'boolean' ? { required: definition.required } : {}),\n ...(typeof definition.default === 'string' ? { default: definition.default } : {}),\n ...(typeof definition.type === 'string' ? { type: definition.type } : {}),\n ...(Array.isArray(definition.options) ? { options: stringArray(definition.options) } : {}),\n });\n }\n return summaries;\n}\n\n/** One step command map: the runner keys it names, and whether its step can run in-process instead. */\ninterface RunnerMap {\n keys: string[];\n custom: boolean;\n}\n\n/** A customRun keyed by runner, rather than one entry any runner runs. */\nfunction isCustomRunMap(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && typeof (value as { prompt?: unknown }).prompt !== 'string';\n}\n\n/** Collects every runner map a workflow's step commands declare. */\nfunction collectRunnerMaps(value: unknown, maps: RunnerMap[]): void {\n if (Array.isArray(value)) {\n for (const item of value) collectRunnerMaps(item, maps);\n return;\n }\n if (!value || typeof value !== 'object') return;\n const custom = CUSTOM_RUN_KEY in value;\n for (const [key, nested] of Object.entries(value)) {\n const isRunKey = (RUN_KEYS as readonly string[]).includes(key);\n if (isRunKey && nested && typeof nested === 'object' && !Array.isArray(nested)) {\n maps.push({ keys: Object.keys(nested), custom });\n } else if (key === CUSTOM_RUN_KEY && isCustomRunMap(nested)) {\n // Its runners are offered too; like any customRun step, it runs on the others as well.\n maps.push({ keys: Object.keys(nested), custom: true });\n } else {\n collectRunnerMaps(nested, maps);\n }\n }\n}\n\n/**\n * The runners every step of a workflow can run on, or undefined when it names\n * neither a runner map nor a custom runner.\n *\n * Undefined and an empty array mean different things: undefined is a workflow\n * whose steps take any runner, an empty array is one whose steps agree on none.\n * A step with a customRun takes any runner, since a runner its map does not name\n * runs it in-process; a named custom runner still needs every other map to name it.\n */\nexport function compatibleRunners(workflow: Workflow): string[] | undefined {\n const maps: RunnerMap[] = [];\n // Runner names are free-form, so a runner called `run` must not read as a step command map.\n collectRunnerMaps({ ...workflow, runners: undefined }, maps);\n const declared = Object.keys(workflow.runners ?? {});\n if (maps.length === 0 && declared.length === 0) return undefined;\n const candidates = new Set([...declared, ...maps.flatMap((map) => map.keys)]);\n return [...candidates].filter((runner) => maps.every((map) => map.custom || map.keys.includes(runner))).sort();\n}\n\n/** Collects the command names each templated interactiveRun offers. */\nfunction collectCommandOffers(value: unknown, offers: string[][]): void {\n if (Array.isArray(value)) {\n for (const item of value) collectCommandOffers(item, offers);\n return;\n }\n if (!value || typeof value !== 'object') return;\n for (const [key, nested] of Object.entries(value)) {\n if (key === INTERACTIVE_RUN_KEY && Array.isArray(nested)) {\n offers.push(nested.map((entry) => asRecord(entry).command).filter((name) => typeof name === 'string'));\n } else {\n collectCommandOffers(nested, offers);\n }\n }\n}\n\n/**\n * The commands every templated step of a workflow offers, in the order the\n * first step lists them, or undefined when no step is templated. These are\n * the values a launch's `--command` accepts.\n */\nexport function compatibleCommands(workflow: Workflow): string[] | undefined {\n const offers: string[][] = [];\n // Command and choice names are free-form, so their declarations are not steps.\n collectCommandOffers({ ...workflow, commands: undefined, choices: undefined }, offers);\n if (offers.length === 0) return undefined;\n return (offers[0] ?? []).filter((name) => offers.every((offer) => offer.includes(name)));\n}\n\n/**\n * A step's label for a summary: its name, else what it uses, else its id, else\n * its position. A `run:` step without a name is identified by position rather\n * than by its command, which would put a shell line into a summary pane.\n */\nfunction stepLabel(step: Step, index: number): string {\n if (step.name) return step.name;\n if (step.uses) return step.uses;\n if (step.id) return step.id;\n return `step ${index + 1}`;\n}\n\nfunction summarizeJobs(workflow: Workflow): WorkflowJobSummary[] {\n return Object.entries(workflow.jobs ?? {}).map(([name, job]: [string, Job]) => ({\n name,\n ...(job['runs-on'] ? { runsOn: job['runs-on'] } : {}),\n steps: (job.steps ?? []).map((step, index) => stepLabel(step, index)),\n }));\n}\n\n/** The run-directory entries a workflow declares, which are its deliverables. */\nfunction summarizeArtifacts(workflow: Workflow): WorkflowArtifactSummary[] {\n return (workflow['run-directory']?.entries ?? []).map((entry) => ({\n path: entry.path,\n kind: entry.kind,\n description: entry.description,\n producedBy: entry['produced-by'] ?? [],\n }));\n}\n\n/** Every workflow file under a directory, nearest name first. */\nexport async function readWorkflowCatalog(\n directory: string,\n runtime: WorkflowRuntimeContext,\n): Promise<WorkflowCatalogEntry[]> {\n const listed = await listWorkflows(runtime, directory, { page: CATALOG_PAGE, pageSize: CATALOG_PAGE_SIZE });\n return listed.workflows.map((workflow) => ({\n path: `${listed.directory}/${workflow.path}`,\n relativePath: workflow.path,\n name: workflow.name,\n description: workflow.description,\n tags: workflow.tags,\n }));\n}\n\n/**\n * One workflow's parsed detail, or the reason it could not be read.\n *\n * The parser is optional so a caller that already holds one reuses it rather\n * than building a second.\n */\nexport async function summarizeWorkflow(\n workflowPath: string,\n parse: WorkflowFileParser,\n): Promise<WorkflowSummaryDetail> {\n try {\n const workflow = await parse(workflowPath);\n const runners = compatibleRunners(workflow);\n const commands = compatibleCommands(workflow);\n const choices = Object.keys(workflow.choices ?? {});\n return {\n triggers: Object.keys(triggerBlock(workflow)),\n inputs: describeWorkflowDispatch(workflow),\n jobs: summarizeJobs(workflow),\n artifacts: summarizeArtifacts(workflow),\n ...(runners ? { runners } : {}),\n ...(commands ? { commands } : {}),\n ...(choices.length > 0 ? { choices } : {}),\n };\n } catch (cause) {\n return {\n triggers: [],\n inputs: [],\n jobs: [],\n artifacts: [],\n error: cause instanceof Error ? cause.message : String(cause),\n };\n }\n}\n","/**\n * Zod Schemas for Workflow YAML Validation\n *\n * DESIGN PATTERNS:\n * - Schema-first development: Zod schemas are the source of truth\n * - Types inferred from schemas via z.infer<>\n * - Runtime validation at YAML parse boundary\n *\n * CODING STANDARDS:\n * - Export all schemas and inferred types from this file\n * - Use descriptive names matching the workflow YAML structure\n *\n * AVOID:\n * - Duplicating type definitions manually (use z.infer<>)\n * - Validating deep inside services (validate at parse boundary)\n */\n\nimport { z } from 'zod';\n\n// ─── Workflow YAML schemas ──────────────────────────────────────────────────\n\nconst CoercedEnvRecord = z.record(z.string(), z.coerce.string());\n\nexport const WorkflowInputSchema = z.object({\n description: z.string().optional(),\n required: z.boolean().optional(),\n default: z.string().optional(),\n type: z.string().optional(),\n options: z.array(z.string()).optional(),\n});\n\nexport const MatrixEntrySchema = z.record(z.string(), z.string());\n\nexport const StepCommandMapSchema = z.record(z.string(), z.string());\n\nexport const StepCommandSchema = z.union([z.string(), StepCommandMapSchema]);\n\nconst WorkflowRelativePathSchema = z\n .string()\n .min(1)\n .describe('Path relative to WORKFLOW_RUN_DIR using forward slashes.')\n .refine(\n (value) =>\n !value.startsWith('/') &&\n !value.includes('\\\\') &&\n !value.split('/').some((segment) => segment === '' || segment === '.' || segment === '..'),\n 'Workflow artifact paths must be safe relative paths without empty, dot, or parent segments.',\n );\n\nconst StepArtifactsSchema = z\n .array(WorkflowRelativePathSchema)\n .min(1)\n .refine((paths) => new Set(paths).size === paths.length, 'Step artifact paths must be unique.')\n .describe('Declared run-directory files that an interactive step must update before stopping.');\n\n/**\n * Execution settings a step shares between its runners.\n *\n * Deliberately generic: the engine never reads a key, it only interpolates\n * them (`${{ runConfig.<key> }}`, lists joined with commas) and hands the map to\n * a host executor, which owns and validates the keys it understands.\n */\nexport const RunConfigSchema = z\n .record(z.string(), z.union([z.string(), z.array(z.string())]))\n .describe('Host execution settings shared by customRun and command runners.');\n\n/** What only an in-process host executor needs, beside the shared `runConfig`. */\nexport const CustomRunEntrySchema = z\n .object({\n prompt: z.string().min(1).describe('Prompt the host executor runs. Interpolated like a command.'),\n systemPrompt: z\n .string()\n .min(1)\n .optional()\n .describe('Text the host appends to the agent system prompt. Interpolated like the prompt.'),\n runConfig: RunConfigSchema.optional().describe(\"Settings laid over the step's shared runConfig.\"),\n })\n .describe('Step executed in-process by a host executor instead of a shell.');\n\n/**\n * One in-process run for any runner, or one per runner keyed like an\n * interactiveRun map, each with its own prompt and settings.\n */\nexport const CustomRunSchema = z.union([CustomRunEntrySchema, z.record(z.string(), CustomRunEntrySchema)]);\n\n/**\n * A named custom runner. Selecting it by name, the way a command map's key is\n * selected, runs every customRun step with this `runConfig` over its own.\n */\nexport const RunnerSchema = z\n .object({\n runConfig: RunConfigSchema.optional().describe('Settings laid over each customRun step runConfig.'),\n })\n .describe('Named custom runner a launch can select.');\n\n/**\n * A command a step can run through, as a Liquid template rendered into its\n * shell command. `inProcess` tells a host that runs agent sessions itself that\n * it may run the step in-process from the structured values instead.\n */\nexport const CommandTemplateSchema = z.union([\n z.string().min(1),\n z\n .object({\n run: z.string().min(1).describe('Liquid template rendered into the shell command.'),\n inProcess: z\n .boolean()\n .optional()\n .describe('A host that runs agent sessions may run this command in-process instead of the shell.'),\n })\n .strict(),\n]);\n\nexport const ChoiceSettingsSchema = z\n .object({\n model: z.string().min(1).optional(),\n thinking: z.string().min(1).optional(),\n subagentModel: z.string().min(1).optional(),\n subagentThinking: z.string().min(1).optional(),\n })\n .strict();\n\n/**\n * A named model composition: independent step and subagent settings, plus overrides\n * keyed by command name for commands whose model ids differ.\n */\nexport const ChoiceSchema = z\n .record(z.string(), z.union([z.string().min(1), ChoiceSettingsSchema]))\n .superRefine((choice, context) => {\n for (const [key, value] of Object.entries(choice)) {\n const setting = Object.hasOwn(ChoiceSettingsSchema.shape, key);\n if (setting !== (typeof value === 'string')) {\n context.addIssue({\n code: 'custom',\n message: setting\n ? `Choice ${key} must be a string.`\n : `Choice override \"${key}\" must be an object of choice settings for that command.`,\n path: [key],\n });\n }\n }\n });\n\n/** One command a step offers, with what it overrides for that command. */\nexport const CommandRefSchema = z\n .object({\n command: z.string().min(1).describe('Name of a command declared under the workflow commands.'),\n choice: z.string().min(1).optional().describe('Choice this command always runs with.'),\n runConfig: RunConfigSchema.optional().describe(\"Settings laid over the step's runConfig for this command.\"),\n prompt: z.string().min(1).optional(),\n systemPrompt: z.string().min(1).optional(),\n })\n .strict();\n\n/** Commands a step offers (the template form), or a legacy command string or runner map. */\nexport const InteractiveRunSchema = z.union([z.array(CommandRefSchema).min(1), StepCommandSchema]);\n\nexport const StrategySchema = z.object({\n 'fail-fast': z.boolean().optional(),\n matrix: z\n .looseObject({\n include: z.array(MatrixEntrySchema).optional(),\n })\n .optional(),\n});\n\nconst StepFieldsSchema = z.object({\n name: z.string().optional(),\n uses: z.string().optional(),\n run: StepCommandSchema.optional(),\n interactiveRun: InteractiveRunSchema.optional(),\n customRun: CustomRunSchema.optional(),\n runConfig: RunConfigSchema.optional(),\n prompt: z.string().min(1).optional().describe('Prompt of a templated interactiveRun, interpolated with ${{ }}.'),\n systemPrompt: z\n .string()\n .min(1)\n .optional()\n .describe('System prompt of a templated interactiveRun, interpolated with ${{ }}.'),\n choice: z.string().min(1).optional().describe('Choice this step runs with, whatever the launch selects.'),\n 'restart-from': z\n .string()\n .min(1)\n .optional()\n .describe('Job a failing run step asks the workflow to restart from, instead of failing the job.'),\n artifacts: StepArtifactsSchema.optional(),\n 'timeout-minutes': z.number().optional(),\n env: CoercedEnvRecord.optional(),\n with: z.record(z.string(), z.string()).optional(),\n 'working-directory': z.string().optional(),\n if: z.string().optional(),\n 'continue-on-error': z.boolean().optional(),\n 'timeout-retries': z.number().optional(),\n 'pause-policy': z.enum(['replay', 'protected']).optional(),\n id: z.string().optional(),\n});\n\nconst GROUP_STEP_KEYS = new Set(['name', 'id', 'parallel']);\n\nfunction refineStep(step: Record<string, unknown> & z.infer<typeof StepFieldsSchema>, context: z.RefinementCtx): void {\n if (step.artifacts && !step.interactiveRun && !step.customRun) {\n context.addIssue({\n code: 'custom',\n message: 'Step artifacts are only supported for interactiveRun and customRun steps.',\n path: ['artifacts'],\n });\n }\n const templated = Array.isArray(step.interactiveRun);\n if (templated) {\n if (step.run !== undefined || step.customRun !== undefined) {\n context.addIssue({\n code: 'custom',\n message: 'A templated interactiveRun cannot be combined with run or customRun.',\n path: ['interactiveRun'],\n });\n }\n const commands = step.interactiveRun as z.infer<typeof CommandRefSchema>[];\n if (step.prompt === undefined && commands.some((entry) => entry.prompt === undefined)) {\n context.addIssue({\n code: 'custom',\n message: 'A templated interactiveRun needs a prompt on the step or on every command.',\n path: ['prompt'],\n });\n }\n } else {\n for (const key of ['prompt', 'systemPrompt', 'choice'] as const) {\n if (step[key] !== undefined) {\n context.addIssue({\n code: 'custom',\n message: `${key} is only supported with a templated interactiveRun.`,\n path: [key],\n });\n }\n }\n }\n if (step['restart-from'] !== undefined && (step.run === undefined || step.interactiveRun || step.customRun)) {\n context.addIssue({\n code: 'custom',\n message: 'restart-from is only supported on run steps.',\n path: ['restart-from'],\n });\n }\n if (step.parallel !== undefined) {\n for (const [key, value] of Object.entries(step)) {\n if (value !== undefined && !GROUP_STEP_KEYS.has(key)) {\n context.addIssue({\n code: 'custom',\n message: `A parallel group only takes name and id; move ${key} onto its steps.`,\n path: [key],\n });\n }\n }\n }\n}\n\nconst ParallelStepSchema = StepFieldsSchema.extend({\n parallel: z.undefined({ error: 'Parallel groups cannot be nested.' }).optional(),\n}).superRefine(refineStep);\n\nexport const StepSchema = StepFieldsSchema.extend({\n parallel: z\n .array(ParallelStepSchema)\n .min(2)\n .optional()\n .describe('Steps run at the same time; their fix requests merge into one repair.'),\n}).superRefine(refineStep);\n\nexport const ServiceDefSchema = z.object({\n name: z.string(),\n run: z.string(),\n env: CoercedEnvRecord.optional(),\n 'working-directory': z.string().optional(),\n 'ready-check': z.union([z.string(), z.boolean()]).optional(),\n 'ready-timeout': z.number().optional(),\n host: z.string().optional(),\n port: z.number().int().min(1).max(65535).optional(),\n 'port-range': z\n .object({\n min: z.number().int().min(1).max(65535),\n max: z.number().int().min(1).max(65535),\n })\n .optional(),\n 'service-type': z.enum(['tool', 'service']).optional(),\n});\n\nexport const PreBlockSchema = z.object({\n services: z.array(ServiceDefSchema).optional(),\n steps: z.array(StepSchema).optional(),\n});\n\nexport const JobHookBlockSchema = z.object({\n steps: z.array(StepSchema).optional(),\n});\n\nexport const JobSchema = z.object({\n 'runs-on': z.string().optional(),\n needs: z.union([z.string(), z.array(z.string())]).optional(),\n extends: z.union([z.string(), z.array(z.string())]).optional(),\n description: z.string().optional(),\n strategy: StrategySchema.optional(),\n steps: z.array(StepSchema),\n preJob: JobHookBlockSchema.optional(),\n postJob: JobHookBlockSchema.optional(),\n env: CoercedEnvRecord.optional(),\n if: z.string().optional(),\n 'system-prompt': z.string().optional(),\n context: z.string().optional(),\n});\n\nexport const RepairTriageSchema = JobSchema.omit({\n extends: true,\n needs: true,\n}).describe('Workflow-defined repair triage that runs before jobs in an active repair.');\n\nexport const AgentDecisionTriggerSchema = z.object({\n steps: z.array(StepSchema),\n});\n\nexport const WorktreeHookSchema = z.object({\n steps: z.array(StepSchema),\n});\n\nexport const WorktreeConfigSchema = z.object({\n beforeCreate: WorktreeHookSchema.optional(),\n afterCreate: WorktreeHookSchema.optional(),\n beforeCompleted: WorktreeHookSchema.optional(),\n afterCompleted: WorktreeHookSchema.optional(),\n});\n\nexport const WorkflowKeybindingsSchema = z.object({\n STOP: z.string().optional(),\n});\n\nconst RUN_DIRECTORY_BUILT_IN_PATHS = new Set([\n 'run.json',\n 'context.md',\n 'changelog.md',\n 'fix.md',\n 'issues',\n 'decisions',\n 'bin',\n 'writes.ndjson',\n]);\n\nexport const RunDirectoryEntrySchema = z\n .object({\n path: WorkflowRelativePathSchema,\n kind: z.enum(['file', 'directory']).describe('Filesystem entry kind.'),\n description: z.string().min(1).describe('Agent-facing purpose of this entry.'),\n 'produced-by': z\n .array(z.string().min(1))\n .optional()\n .describe('Workflow jobs expected to create or update this entry.'),\n 'initial-content': z.string().optional().describe('Initial content used when creating a file.'),\n })\n .superRefine((entry, context) => {\n if (entry.kind === 'directory' && entry['initial-content'] !== undefined) {\n context.addIssue({\n code: 'custom',\n message: 'initial-content is only valid for file entries.',\n path: ['initial-content'],\n });\n }\n });\n\nexport const RunDirectorySchema = z\n .object({\n description: z.string().min(1).describe('Agent-facing purpose of the workflow run directory.'),\n entries: z.array(RunDirectoryEntrySchema).describe('Declared workflow-owned files and directories.'),\n })\n .superRefine((runDirectory, context) => {\n const seen = new Set<string>();\n for (const [index, entry] of runDirectory.entries.entries()) {\n if (RUN_DIRECTORY_BUILT_IN_PATHS.has(entry.path)) {\n context.addIssue({\n code: 'custom',\n message: `Run-directory path is owned by workflow-mcp: ${entry.path}`,\n path: ['entries', index, 'path'],\n });\n }\n if (seen.has(entry.path)) {\n context.addIssue({\n code: 'custom',\n message: `Duplicate run-directory path: ${entry.path}`,\n path: ['entries', index, 'path'],\n });\n }\n seen.add(entry.path);\n }\n });\n\nexport const WorkflowSchema = z\n .object({\n name: z.string().optional(),\n tags: z\n .array(z.string().trim().min(1))\n .optional()\n .describe('Tags used to categorize and filter workflow definitions.'),\n workspace: z.string().optional(),\n runner: z.string().optional().describe('Default runner key for step command maps when no CLI runner is provided.'),\n 'default-runner': z.string().optional().describe('Deprecated alias for runner.'),\n runners: z\n .record(z.string(), RunnerSchema)\n .optional()\n .describe('Named custom runners; selecting one lays its runConfig over every customRun step.'),\n commands: z\n .record(z.string(), CommandTemplateSchema)\n .optional()\n .describe('Command templates a templated interactiveRun selects with --command.'),\n choices: z\n .record(z.string(), ChoiceSchema)\n .optional()\n .describe('Model compositions a launch selects with --choice; \"default\" is used when none is named.'),\n runConfig: RunConfigSchema.optional().describe(\n 'Defaults laid under the runConfig of every interactiveRun and customRun step; a step key wins.',\n ),\n imports: z.array(z.string()).optional(),\n 'system-prompt': z.string().optional(),\n 'max-workflows': z.number().int().positive().optional(),\n 'launch-command': z.string().optional(),\n launcher: z.enum(['cmux', 'tmux']).optional(),\n keybindings: WorkflowKeybindingsSchema.optional(),\n 'run-directory': RunDirectorySchema.optional(),\n on: z\n .looseObject({\n workflow_dispatch: z\n .object({\n inputs: z.record(z.string(), WorkflowInputSchema).optional(),\n })\n .nullable()\n .optional(),\n agent_decision: AgentDecisionTriggerSchema.optional(),\n })\n .optional(),\n env: CoercedEnvRecord.optional(),\n pre: PreBlockSchema.optional(),\n post: PreBlockSchema.optional(),\n repair: RepairTriageSchema.optional(),\n worktree: WorktreeConfigSchema.optional(),\n jobs: z.record(z.string(), JobSchema),\n })\n .superRefine((workflow, context) => {\n const declaredFiles = new Set(\n (workflow['run-directory']?.entries ?? []).filter((entry) => entry.kind === 'file').map((entry) => entry.path),\n );\n for (const [jobName, job] of Object.entries(workflow.jobs)) {\n for (const [stepIndex, step] of job.steps.entries()) {\n const members = step.parallel\n ? step.parallel.map((child, childIndex) => ({ step: child, path: [stepIndex, 'parallel', childIndex] }))\n : [{ step, path: [stepIndex] }];\n for (const member of members) {\n for (const [artifactIndex, artifact] of (member.step.artifacts ?? []).entries()) {\n if (!declaredFiles.has(artifact)) {\n context.addIssue({\n code: 'custom',\n message: `Step artifact must reference a declared run-directory file: ${artifact}`,\n path: ['jobs', jobName, 'steps', ...member.path, 'artifacts', artifactIndex],\n });\n }\n }\n }\n }\n }\n for (const [entryIndex, entry] of (workflow['run-directory']?.entries ?? []).entries()) {\n for (const [producerIndex, producer] of (entry['produced-by'] ?? []).entries()) {\n if (!workflow.jobs[producer] || producer.startsWith('.')) {\n context.addIssue({\n code: 'custom',\n message: `Unknown producing job: ${producer}`,\n path: ['run-directory', 'entries', entryIndex, 'produced-by', producerIndex],\n });\n }\n }\n }\n });\n\n// ─── Runtime schemas ────────────────────────────────────────────────────────\n\nexport const WorkflowStageSchema = z.enum(['running', 'completed', 'error']);\n\nexport const WorkflowOutcomeSchema = z.enum(['success', 'skipped', 'failed', 'interrupted']);\n\n/**\n * One line of the run progress log.\n *\n * Append-only NDJSON in the run directory, because a run is a detached process\n * and anything held in its memory is invisible to every other process and lost\n * on crash. A reader can tail this to know which job and step a run is on,\n * which the run record cannot express: it carries only a stage.\n */\nexport const WorkflowExecutionStateSchema = z\n .enum(['running', 'pause_requested', 'paused', 'resume_requested'])\n .describe('Live execution state within a running workflow.');\n\nexport const WorkflowResumeModeSchema = z\n .enum(['replay-current', 'continue-next'])\n .describe('How a paused workflow resumes at its execution cursor.');\n\nexport const WorkflowExecutionCursorSchema = z.object({\n attempt: z.number().int().positive().optional(),\n executionGeneration: z.number().int().positive(),\n revision: z.number().int().nonnegative().optional(),\n job: z.string().optional(),\n matrixIndex: z.number().int().nonnegative().optional(),\n phase: z.string(),\n requestId: z.string().uuid().optional(),\n resumeMode: WorkflowResumeModeSchema,\n stepIndex: z.number().int().nonnegative().optional(),\n stepName: z.string().optional(),\n});\n\n/** A host-owned handle a reader can follow, such as an agent session or a terminal pane. */\nexport const StepExecutionRefSchema = z.object({\n kind: z.string().min(1).describe('Host-defined handle kind, such as session or pane.'),\n id: z.string().min(1),\n label: z.string().optional(),\n});\n\nexport const WorkflowProgressEventSchema = z.object({\n at: z.string().describe('ISO timestamp the event was recorded.'),\n index: z.number().int().nonnegative().optional().describe('Zero-based position within its parent sequence.'),\n job: z.string().describe('Job the event belongs to.'),\n /** Present on failures and skips, so a reader can show why without opening the log. */\n reason: z.string().optional(),\n status: z\n .enum(['running', 'completed', 'failed', 'pause_requested', 'paused', 'resumed', 'skipped'])\n .describe('State the subject moved into.'),\n step: z.string().optional().describe('Step name, absent for job-level events.'),\n group: z.string().optional().describe('Parallel group a step runs in, beside the other steps of that group.'),\n ref: StepExecutionRefSchema.optional().describe('Where a host executor runs the step, once it started.'),\n total: z.number().int().nonnegative().optional().describe('Length of the parent sequence, when known.'),\n type: z.enum(['job', 'step']),\n});\n\nexport const WorkflowRepairStatusSchema = z.enum(['pending', 'active', 'resolved', 'superseded', 'rejected']);\n\nexport const WorkflowRepairJobStatusSchema = z.enum([\n 'pending',\n 'running',\n 'completed',\n 'failed',\n 'interrupted',\n 'skipped',\n]);\n\nexport const WorkflowRepairJobAttemptSchema = z.object({\n attempt: z.number().int().positive(),\n finishedAt: z.string().optional(),\n startedAt: z.string(),\n status: z.enum(['running', 'completed', 'failed', 'interrupted']),\n workflowRunId: z.string().optional(),\n});\n\nexport const WorkflowRepairJobSchema = z.object({\n attempts: z.array(WorkflowRepairJobAttemptSchema),\n jobName: z.string(),\n status: WorkflowRepairJobStatusSchema,\n});\n\nexport const WorkflowRepairRoutingFallbackSchema = z.object({\n reason: z.enum(['missing', 'unknown']),\n requestedTarget: z.string().optional(),\n resolvedTarget: z.string(),\n});\n\nexport const WorkflowRepairRecordSchema = z.object({\n createdAt: z.string(),\n fixCycle: z.number().int().positive(),\n issueFile: z.string(),\n jobs: z.array(WorkflowRepairJobSchema),\n rejectedAt: z.string().optional(),\n repairId: z.string().regex(/^\\d+$/),\n resolvedAt: z.string().optional(),\n restartFrom: z.string(),\n routingFallback: WorkflowRepairRoutingFallbackSchema.optional(),\n schemaVersion: z.literal(1),\n scopeJobs: z.array(z.string()),\n status: WorkflowRepairStatusSchema,\n supersededAt: z.string().optional(),\n supersededBy: z.string().optional(),\n updatedAt: z.string(),\n verificationJob: z.string(),\n});\n\nconst CmuxWorkflowLauncherMetadataSchema = z.object({\n originSurfaceId: z.string().optional(),\n originWorkspaceId: z.string().optional(),\n surfaceId: z.string().optional(),\n type: z.literal('cmux'),\n workspaceId: z.string(),\n});\n\nconst TmuxWorkflowLauncherMetadataSchema = z.object({\n originPaneId: z.string().optional(),\n originSessionId: z.string().optional(),\n originSurfaceId: z.string().optional(),\n originWorkspaceId: z.string().optional(),\n paneId: z.string().optional(),\n sessionId: z.string().optional(),\n sessionName: z.string(),\n type: z.literal('tmux'),\n windowId: z.string().optional(),\n});\n\n/**\n * Compatibility metadata for the RMUX-backed launcher. The `native` literal is\n * retained for existing run records and cockpit clients; the detached host pid\n * and terminal socket remain the public identity.\n */\nconst NativeWorkflowLauncherMetadataSchema = z.object({\n pid: z.number().int().positive().optional(),\n type: z.literal('native'),\n});\n\nexport const WorkflowLauncherMetadataSchema = z.discriminatedUnion('type', [\n CmuxWorkflowLauncherMetadataSchema,\n TmuxWorkflowLauncherMetadataSchema,\n NativeWorkflowLauncherMetadataSchema,\n]);\n\nexport const WorkflowRunRecordSchema = z.object({\n activeRepairId: z.string().regex(/^\\d+$/).optional(),\n cliAgent: z.string().optional(),\n continueOnError: z.boolean().optional(),\n displayName: z.string(),\n dryRun: z.boolean(),\n env: z.record(z.string(), z.string()).optional(),\n executionCursor: WorkflowExecutionCursorSchema.optional(),\n executionState: WorkflowExecutionStateSchema.optional(),\n errorMessage: z.string().optional(),\n exitCode: z.number().optional(),\n failedJob: z.string().optional(),\n finishedAt: z.string().optional(),\n fixLoopCycle: z.number().int().positive().optional(),\n inputs: z.record(z.string(), z.string()).optional(),\n job: z.string().optional(),\n keepWorktree: z.boolean().optional(),\n launcher: WorkflowLauncherMetadataSchema.optional(),\n originalRepoPath: z.string().optional(),\n outcome: WorkflowOutcomeSchema.optional(),\n pid: z.number().int().positive().optional(),\n prompt: z.string().optional(),\n runner: z.string().optional(),\n command: z.string().optional().describe('Command the launch selected for templated interactiveRun steps.'),\n choice: z.string().optional().describe('Choice the launch selected for steps that do not pin one.'),\n runId: z.string().uuid().optional(),\n runKey: z.string(),\n secretFile: z.string().optional(),\n skipLaunch: z.boolean().optional(),\n stale: z.boolean().optional(),\n staleReason: z.string().optional(),\n stage: WorkflowStageSchema,\n startedAt: z.string(),\n statusFile: z.string().optional(),\n /**\n * Unix socket a natively hosted run answers screen, key and resize requests\n * on, so a reader outside the hosting process can attach to it. Absent for a\n * multiplexer-hosted run, which is addressed through the multiplexer itself.\n */\n terminalSocket: z.string().optional(),\n failureReason: z.string().optional(),\n worktreeBranch: z.string().optional(),\n worktreePath: z.string().optional(),\n workflowPath: z.string(),\n workflowId: z.string().optional(),\n workflowName: z.string().optional(),\n runDirectory: RunDirectorySchema.optional(),\n workspace: z.string(),\n effectiveStage: WorkflowStageSchema.optional(),\n effectiveOutcome: WorkflowOutcomeSchema.optional(),\n});\n\n/** What an agent decided a step's outcome is, through `workflow-mcp step`. */\nexport const StepDecisionSchema = z.discriminatedUnion('decision', [\n z.object({ decision: z.literal('complete'), summary: z.string().optional() }),\n z.object({ decision: z.literal('fix'), restartFrom: z.string().min(1), reason: z.string().min(1) }),\n z.object({ decision: z.literal('fail'), reason: z.string().min(1) }),\n]);\n\n/**\n * The per-attempt file a decision step shares with its agent and stop hooks.\n * The engine creates it, `workflow-mcp step` records the decision in it, and\n * stop hooks count the reminders they sent in `nudges`.\n */\nexport const StepDecisionFileSchema = z.object({\n schemaVersion: z.literal(1),\n job: z.string(),\n step: z.string(),\n restartTargets: z.array(z.string()),\n /** A templated agent step must decide; any other step may, and otherwise ends on its exit code. */\n required: z.boolean(),\n nudges: z.number().int().nonnegative(),\n decidedAt: z.string().optional(),\n decision: StepDecisionSchema.optional(),\n});\n\nexport const WorkflowRunHandleSchema = z.object({\n changelogPath: z.string(),\n contextPath: z.string(),\n displayName: z.string(),\n pauseRequestPath: z.string().optional(),\n recordPath: z.string(),\n runDir: z.string(),\n runId: z.string().uuid(),\n runKey: z.string(),\n stopRequestPath: z.string(),\n workspace: z.string(),\n});\n\n// ─── Inferred types ─────────────────────────────────────────────────────────\n\nexport type WorkflowExecutionCursor = z.infer<typeof WorkflowExecutionCursorSchema>;\nexport type WorkflowExecutionState = z.infer<typeof WorkflowExecutionStateSchema>;\nexport type WorkflowInput = z.infer<typeof WorkflowInputSchema>;\nexport type MatrixEntry = z.infer<typeof MatrixEntrySchema>;\nexport type StepCommandMap = z.infer<typeof StepCommandMapSchema>;\nexport type StepCommand = z.infer<typeof StepCommandSchema>;\nexport type CommandTemplate = z.infer<typeof CommandTemplateSchema>;\nexport type Choice = z.infer<typeof ChoiceSchema>;\nexport type CommandRef = z.infer<typeof CommandRefSchema>;\nexport type StepDecision = z.infer<typeof StepDecisionSchema>;\nexport type StepDecisionFile = z.infer<typeof StepDecisionFileSchema>;\nexport type Strategy = z.infer<typeof StrategySchema>;\nexport type Step = z.infer<typeof StepSchema>;\nexport type RunConfig = z.infer<typeof RunConfigSchema>;\nexport type CustomRun = z.infer<typeof CustomRunSchema>;\nexport type CustomRunEntry = z.infer<typeof CustomRunEntrySchema>;\nexport type Runner = z.infer<typeof RunnerSchema>;\nexport type StepExecutionRef = z.infer<typeof StepExecutionRefSchema>;\nexport type ServiceDef = z.infer<typeof ServiceDefSchema>;\nexport type PreBlock = z.infer<typeof PreBlockSchema>;\nexport type JobHookBlock = z.infer<typeof JobHookBlockSchema>;\nexport type Job = z.infer<typeof JobSchema>;\nexport type RepairTriage = z.infer<typeof RepairTriageSchema>;\nexport type AgentDecisionTrigger = z.infer<typeof AgentDecisionTriggerSchema>;\nexport type WorktreeHook = z.infer<typeof WorktreeHookSchema>;\nexport type WorktreeConfig = z.infer<typeof WorktreeConfigSchema>;\nexport type WorkflowKeybindings = z.infer<typeof WorkflowKeybindingsSchema>;\nexport type RunDirectoryEntry = z.infer<typeof RunDirectoryEntrySchema>;\nexport type RunDirectory = z.infer<typeof RunDirectorySchema>;\nexport type Workflow = z.infer<typeof WorkflowSchema>;\nexport type WorkflowStage = z.infer<typeof WorkflowStageSchema>;\nexport type WorkflowOutcome = z.infer<typeof WorkflowOutcomeSchema>;\nexport type WorkflowRepairStatus = z.infer<typeof WorkflowRepairStatusSchema>;\nexport type WorkflowResumeMode = z.infer<typeof WorkflowResumeModeSchema>;\nexport type WorkflowRepairJobStatus = z.infer<typeof WorkflowRepairJobStatusSchema>;\nexport type WorkflowRepairJobAttempt = z.infer<typeof WorkflowRepairJobAttemptSchema>;\nexport type WorkflowRepairJob = z.infer<typeof WorkflowRepairJobSchema>;\nexport type WorkflowRepairRoutingFallback = z.infer<typeof WorkflowRepairRoutingFallbackSchema>;\nexport type WorkflowProgressEvent = z.infer<typeof WorkflowProgressEventSchema>;\nexport type WorkflowRepairRecord = z.infer<typeof WorkflowRepairRecordSchema>;\nexport type WorkflowLauncherMetadata = z.infer<typeof WorkflowLauncherMetadataSchema>;\nexport type WorkflowLauncherType = WorkflowLauncherMetadata['type'];\nexport type WorkflowRunRecord = z.infer<typeof WorkflowRunRecordSchema>;\nexport type WorkflowRunHandle = z.infer<typeof WorkflowRunHandleSchema>;\n","import { BACKGROUND_CONTEXT, getOrThrow } from '@agimon-ai/po-core/platform';\n\nimport type { WorkflowRuntimeContext } from './type';\n\n/** Freeze the admitted environment too, so concurrent runs cannot mutate each other's facts. */\nexport function createWorkflowRuntime(\n input: Omit<WorkflowRuntimeContext, 'ioContext'> & Partial<Pick<WorkflowRuntimeContext, 'ioContext'>>,\n): WorkflowRuntimeContext {\n return Object.freeze({\n ...input,\n baseEnvironment: Object.freeze({ ...input.baseEnvironment }),\n ioContext: input.ioContext ?? BACKGROUND_CONTEXT,\n });\n}\n\n/** A bounded command on the admitted platform, without inheriting the server process environment. */\nexport async function workflowShellOutput(\n runtime: WorkflowRuntimeContext,\n command: string | readonly string[],\n options: { cwd?: string; environment?: Readonly<Record<string, string | undefined>>; timeoutMs?: number } = {},\n): Promise<string> {\n let output = '';\n const env = Object.fromEntries(\n Object.entries(options.environment ?? runtime.baseEnvironment).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n );\n const result = getOrThrow(\n await runtime.shell.exec(\n typeof command === 'string' ? command : [...command],\n {\n cwd: options.cwd ?? runtime.cwd,\n env,\n inheritEnv: false,\n ...(options.timeoutMs === undefined ? {} : { timeout: options.timeoutMs }),\n onOutput: (text) => {\n output += text;\n },\n },\n runtime.ioContext,\n ),\n );\n if (result.exitCode !== 0)\n throw new Error(\n `Workflow command exited with code ${result.exitCode}: ${typeof command === 'string' ? command : command.join(' ')}\\n${output}`,\n );\n return output;\n}\n","/**\n * Shell-quoting helpers for safely interpolating values into shell command strings.\n *\n * DESIGN PATTERNS:\n * - Pure functions with no side effects\n * - Context-aware escaping driven by the surrounding quote character\n *\n * AVOID:\n * - String.prototype.replace with a value as the replacement string: its replacement\n * patterns ($&, $1, $$, ...) would corrupt any value containing `$`. Build the result\n * with slice/concat or a function replacer instead.\n */\n\n/**\n * Escape a string for safe use as a single-quoted shell argument.\n *\n * Wraps the value in single quotes and neutralises embedded single quotes via the\n * quote-break-escape-requote pattern (`'\\''`).\n */\nexport function escapeShellArg(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/**\n * Escape a value for safe insertion inside a double-quoted shell string (`\"...\"`).\n *\n * Inside double quotes only `\\`, `$`, `` ` `` and `\"` retain special meaning, so each is\n * backslash-escaped in a single pass. A function replacer is used so a `$` in the value is\n * never interpreted as a replacement pattern.\n */\nexport function escapeForDoubleQuotes(value: string): string {\n return value.replace(/[\\\\$`\"]/g, (char) => `\\\\${char}`);\n}\n\n/**\n * Replace every occurrence of `placeholder` in `template` with `value`, escaping the value\n * for the shell-quoting context of the character immediately preceding the placeholder:\n *\n * - preceded by `\"` -> escape for a double-quoted slot (`\\ $ ` ` \" `)\n * - preceded by `'` -> escape embedded single quotes (the template supplies the surrounding quotes)\n * - otherwise (bare) -> wrap the value as a single safe single-quoted token\n *\n * The result is assembled with slice/concat so `value` is never treated as a\n * String.prototype.replace replacement pattern.\n */\nexport function substituteShellPlaceholder(template: string, placeholder: string, value: string): string {\n let result = '';\n let searchFrom = 0;\n for (;;) {\n const index = template.indexOf(placeholder, searchFrom);\n if (index === -1) {\n return result + template.slice(searchFrom);\n }\n result += template.slice(searchFrom, index) + escapeForPrecedingQuote(value, template[index - 1]);\n searchFrom = index + placeholder.length;\n }\n}\n\nfunction escapeForPrecedingQuote(value: string, precedingChar: string | undefined): string {\n if (precedingChar === '\"') {\n return escapeForDoubleQuotes(value);\n }\n if (precedingChar === \"'\") {\n return value.replace(/'/g, \"'\\\\''\");\n }\n return escapeShellArg(value);\n}\n","/**\n * WorkflowParserService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { resolve } from 'node:path';\n\nimport { getOrThrow, pathExists } from '@agimon-ai/po-core/platform';\nimport { load as parseYaml } from 'js-yaml';\nimport { Liquid } from 'liquidjs';\n\nimport { ChoiceSettingsSchema, WorkflowSchema } from '../../schemas/workflowEngine';\nimport type {\n Choice,\n CommandTemplate,\n Job,\n MatrixEntry,\n RunConfig,\n RunDirectory,\n Step,\n Workflow,\n} from '../../schemas/workflowEngine';\nimport type { InterpolationContext } from '../workflowEngine/type';\nimport { workflowShellOutput } from '../workflowRuntime';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport { escapeShellArg } from '../workflowShell';\n\nconst CUSTOM_RUN_KEY = 'customRun';\nconst RUN_CONFIG_KEY = 'runConfig';\nconst PROMPT_VARIABLE = 'prompt';\nconst SYSTEM_PROMPT_VARIABLE = 'systemPrompt';\nconst CHOICE_SETTING_KEYS = new Set(Object.keys(ChoiceSettingsSchema.shape));\n/** A prompt printed raw would be split and expanded by the shell, so templates must quote it. */\nconst UNQUOTED_PROMPT_PATTERN = /\\{\\{-?\\s*(prompt|systemPrompt)\\s*-?\\}\\}/;\nconst LEGACY_INTERPOLATION_MARKER = '${{';\n\n/**\n * Renders command templates. Strict, so a variable a launch does not provide\n * fails the step instead of rendering an empty flag; lenient in `if` and\n * `default`, so optional values such as the system prompt can be tested.\n */\nconst commandTemplates = new Liquid({ strictVariables: true, strictFilters: true, lenientIf: true });\ncommandTemplates.registerFilter('shell', (value: unknown) =>\n // Liquid filters deliberately accept arbitrary values with native string coercion.\n // oxlint-disable-next-line typescript/no-base-to-string\n escapeShellArg(Array.isArray(value) ? value.join(',') : String(value ?? '')),\n);\n\n/** A declared command's template and host options, whichever form it was written in. */\nexport function commandTemplateOf(command: CommandTemplate): { run: string; inProcess: boolean } {\n return typeof command === 'string'\n ? { run: command, inProcess: false }\n : { run: command.run, inProcess: command.inProcess === true };\n}\n\n/** Base step/subagent settings, with an optional command-specific override. */\nexport function choiceSettings(choice: Choice | undefined, command?: string): RunConfig {\n if (!choice) return {};\n const settings: RunConfig = {};\n for (const key of CHOICE_SETTING_KEYS) {\n const value = choice[key];\n if (typeof value === 'string') settings[key] = value;\n }\n const override = command === undefined ? undefined : choice[command];\n if (override && typeof override !== 'string') Object.assign(settings, override);\n return settings;\n}\n\nconst SKIPPED_ACTIONS = [\n 'actions/checkout',\n 'actions/setup-node',\n 'actions/cache',\n 'actions/upload-artifact',\n 'actions/download-artifact',\n 'pnpm/action-setup',\n];\n\nconst ADJECTIVES = [\n 'bold',\n 'calm',\n 'cool',\n 'dark',\n 'deep',\n 'fair',\n 'fast',\n 'free',\n 'gold',\n 'keen',\n 'kind',\n 'loud',\n 'neat',\n 'pure',\n 'rare',\n 'safe',\n 'slim',\n 'soft',\n 'tall',\n 'warm',\n 'wild',\n 'wise',\n 'blue',\n 'gray',\n 'jade',\n 'iron',\n 'zinc',\n 'ruby',\n 'opal',\n 'onyx',\n];\n\nconst NOUNS = [\n 'arch',\n 'beam',\n 'bird',\n 'bolt',\n 'cape',\n 'cove',\n 'dawn',\n 'dove',\n 'echo',\n 'fern',\n 'flux',\n 'gale',\n 'hawk',\n 'haze',\n 'iris',\n 'jade',\n 'kite',\n 'lake',\n 'lynx',\n 'mesa',\n 'moth',\n 'node',\n 'palm',\n 'peak',\n 'pine',\n 'raft',\n 'reef',\n 'sage',\n 'tide',\n 'vale',\n];\n\nexport class WorkflowParserService {\n private githubSha = 'local';\n\n constructor(readonly runtime: WorkflowRuntimeContext) {}\n\n generateHumanReadableId(): string {\n const adj = ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)];\n const noun = NOUNS[Math.floor(Math.random() * NOUNS.length)];\n return `${adj}-${noun}`;\n }\n\n async parseWorkflowFile(workflowPath: string): Promise<Workflow> {\n const resolved = resolve(this.runtime.cwd, workflowPath);\n if (!(await pathExists(this.runtime.fs, resolved, this.runtime.ioContext))) {\n throw new Error(`Workflow file not found: ${resolved}`);\n }\n\n const content = getOrThrow(await this.runtime.fs.readTextFile(resolved, this.runtime.ioContext));\n if (content.includes('github.sha')) {\n try {\n this.githubSha = (await workflowShellOutput(this.runtime, 'git rev-parse HEAD')).trim();\n } catch {\n this.githubSha = 'local';\n }\n }\n const workflow = WorkflowSchema.parse(parseYaml(content)) as Workflow;\n\n if (workflow.imports) {\n await this.resolveImports(workflow, resolved);\n }\n\n if (!workflow.jobs || Object.keys(workflow.jobs).length === 0) {\n throw new Error('No jobs found in workflow file');\n }\n\n this.resolveExtends(workflow);\n\n const parsed = WorkflowSchema.parse(this.applyRunConfigDefaults(workflow)) as Workflow;\n this.validateCommandTemplates(parsed);\n return parsed;\n }\n\n /**\n * Render a command template into the shell command a step runs.\n *\n * Values enter as data and are never rendered again, so `${{ }}` text a\n * prompt already went through, or Liquid syntax a prompt quotes, stays as it\n * is. Use the `shell` filter to quote a value as one shell word.\n */\n renderCommandTemplate(template: string, values: Record<string, unknown>): string {\n return commandTemplates.parseAndRenderSync(template, values).trim();\n }\n\n /** The top-level values a command template reads. */\n templateVariables(template: string): string[] {\n return commandTemplates.globalVariablesSync(template);\n }\n\n /** Whether a template passes the system prompt itself; when not, it is folded into the prompt. */\n templateUsesSystemPrompt(template: string): boolean {\n return commandTemplates.globalVariablesSync(template).includes(SYSTEM_PROMPT_VARIABLE);\n }\n\n /**\n * Check what the schema cannot see once imports and templates are merged:\n * that steps name declared commands and choices, that `parallel` and\n * `restart-from` sit in jobs, and that every command template parses and\n * quotes its prompts.\n */\n validateCommandTemplates(workflow: Workflow): void {\n const problems: string[] = [];\n const commands = workflow.commands ?? {};\n const choices = workflow.choices ?? {};\n const jobNames = new Set(Object.keys(workflow.jobs));\n\n for (const [name, command] of Object.entries(commands)) {\n const { run } = commandTemplateOf(command);\n if (run.includes(LEGACY_INTERPOLATION_MARKER)) {\n problems.push(`Command \"${name}\" uses \\${{ }}; command templates are Liquid, use {{ }} instead.`);\n }\n if (UNQUOTED_PROMPT_PATTERN.test(run)) {\n problems.push(`Command \"${name}\" prints a prompt unquoted; write {{ prompt | shell }}.`);\n }\n try {\n if (!commandTemplates.globalVariablesSync(run).includes(PROMPT_VARIABLE)) {\n problems.push(`Command \"${name}\" never passes {{ prompt | shell }} to the agent.`);\n }\n } catch (error) {\n problems.push(`Command \"${name}\" is not a valid Liquid template: ${(error as Error).message}`);\n }\n }\n for (const [name, choice] of Object.entries(choices)) {\n for (const key of Object.keys(choice)) {\n if (!CHOICE_SETTING_KEYS.has(key) && !(key in commands)) {\n problems.push(`Choice \"${name}\" overrides \"${key}\", which is not a declared command.`);\n }\n }\n }\n\n const checkStep = (step: Step, where: string, inJob: boolean): void => {\n if (Array.isArray(step.interactiveRun)) {\n for (const entry of step.interactiveRun) {\n if (!(entry.command in commands)) {\n problems.push(`${where} runs command \"${entry.command}\", which is not declared under commands.`);\n }\n if (entry.choice !== undefined && !(entry.choice in choices)) {\n problems.push(`${where} names choice \"${entry.choice}\", which is not declared under choices.`);\n }\n }\n }\n if (step.choice !== undefined && !(step.choice in choices)) {\n problems.push(`${where} names choice \"${step.choice}\", which is not declared under choices.`);\n }\n const restartFrom = step['restart-from'];\n if (restartFrom !== undefined) {\n if (!inJob) problems.push(`${where} sets restart-from, which only jobs support.`);\n else if (!jobNames.has(restartFrom)) {\n problems.push(`${where} restarts from \"${restartFrom}\", which is not a job.`);\n }\n }\n if (step.parallel) {\n if (!inJob) problems.push(`${where} is a parallel group, which only jobs support.`);\n const names = step.parallel.map((child) => child.name).filter((name) => name !== undefined);\n if (new Set(names).size !== names.length) problems.push(`${where} has parallel steps with the same name.`);\n for (const [index, child] of step.parallel.entries()) {\n checkStep(child, `${where} parallel ${child.name ?? index + 1}`, inJob);\n }\n }\n };\n const checkSteps = (steps: Step[] | undefined, where: string, inJob: boolean): void => {\n for (const [index, step] of (steps ?? []).entries()) {\n checkStep(step, `${where} step ${step.name ?? index + 1}`, inJob);\n }\n };\n const checkJob = (job: Job, where: string): void => {\n checkSteps(job.steps, where, true);\n checkSteps(job.preJob?.steps, `${where} preJob`, true);\n checkSteps(job.postJob?.steps, `${where} postJob`, true);\n };\n\n for (const [name, job] of Object.entries(workflow.jobs)) checkJob(job, `Job \"${name}\"`);\n if (workflow.repair) checkJob(workflow.repair as Job, 'Repair');\n checkSteps(workflow.pre?.steps, 'pre', false);\n checkSteps(workflow.post?.steps, 'post', false);\n checkSteps(workflow.on?.agent_decision?.steps, 'agent_decision', false);\n for (const [hook, block] of Object.entries(workflow.worktree ?? {})) {\n checkSteps(block?.steps, `worktree ${hook}`, false);\n }\n\n if (problems.length > 0) {\n throw new Error(`Invalid workflow:\\n - ${problems.join('\\n - ')}`);\n }\n }\n\n /**\n * Lay the workflow's `runConfig` under the one of every agent step, a step\n * with an `interactiveRun` or `customRun`, wherever it sits. A key the step\n * sets itself wins, so a step runs on the workflow default unless it says\n * otherwise.\n */\n private applyRunConfigDefaults(workflow: Workflow): Workflow {\n const defaults = workflow.runConfig;\n if (defaults === undefined) return workflow;\n const visit = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(visit);\n if (!value || typeof value !== 'object') return value;\n const copy: Record<string, unknown> = Object.fromEntries(\n Object.entries(value).map(([key, nested]) => [key, visit(nested)]),\n );\n if (copy[CUSTOM_RUN_KEY] !== undefined || copy.interactiveRun !== undefined) {\n copy[RUN_CONFIG_KEY] = { ...defaults, ...(copy[RUN_CONFIG_KEY] as RunConfig | undefined) };\n }\n return copy;\n };\n const { runConfig, ...rest } = workflow;\n return { ...(visit(rest) as Workflow), runConfig };\n }\n\n /**\n * The workflow as it runs on `runner`.\n *\n * A runner declared under `runners` lays its `runConfig` over the one of\n * every step that has a `customRun`, wherever the step sits: jobs, hooks,\n * triage and worktree steps alike. Any other runner, including a command\n * map's key, leaves the workflow as parsed.\n */\n selectRunner(workflow: Workflow, runner: string | undefined): Workflow {\n const overlay = runner === undefined ? undefined : workflow.runners?.[runner]?.runConfig;\n if (overlay === undefined) return workflow;\n const visit = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(visit);\n if (!value || typeof value !== 'object') return value;\n const copy: Record<string, unknown> = Object.fromEntries(\n Object.entries(value).map(([key, nested]) => [key, visit(nested)]),\n );\n if (copy[CUSTOM_RUN_KEY] !== undefined) {\n copy[RUN_CONFIG_KEY] = { ...(copy[RUN_CONFIG_KEY] as RunConfig | undefined), ...overlay };\n }\n return copy;\n };\n const { runners, ...rest } = workflow;\n return { ...(visit(rest) as Workflow), runners };\n }\n\n /**\n * Resolve `imports` references in a workflow.\n * Import paths are resolved relative to the importing workflow file.\n * Imported files provide base sections that the main workflow can override:\n * - env: merged (main overrides imported)\n * - pre.steps: imported steps prepended before main steps\n * - pre.services: imported services prepended before main services\n * - post.steps: imported steps prepended before main steps\n * - post.services: imported services prepended before main services\n * - worktree: imported hooks used as defaults, main overrides per-hook\n * - jobs: imported template jobs (dot-prefixed) merged in, main overrides\n * - system-prompt: concatenated (imported + main)\n * - commands, choices: merged per name (main overrides imported)\n * - runConfig: merged per key (main overrides imported)\n * Imports are processed in order; later imports override earlier ones.\n * Circular imports are detected and throw an error.\n */\n async resolveImports(workflow: Workflow, workflowPath: string, visited = new Set<string>()): Promise<void> {\n const normalizedPath = resolve(workflowPath);\n if (visited.has(normalizedPath)) {\n throw new Error(`Circular import detected: ${normalizedPath}`);\n }\n visited.add(normalizedPath);\n\n const baseDir = normalizedPath.replace(/\\/[^/]+$/, '');\n\n for (const importPath of workflow.imports ?? []) {\n const resolvedImport = resolve(baseDir, importPath);\n if (!(await pathExists(this.runtime.fs, resolvedImport, this.runtime.ioContext))) {\n throw new Error(`Imported workflow file not found: ${resolvedImport} (from ${normalizedPath})`);\n }\n\n const importContent = getOrThrow(await this.runtime.fs.readTextFile(resolvedImport, this.runtime.ioContext));\n const imported = parseYaml(importContent) as Workflow;\n\n // Recursively resolve nested imports\n if (imported.imports) {\n await this.resolveImports(imported, resolvedImport, visited);\n }\n\n // Merge env (main overrides imported)\n if (imported.env) {\n workflow.env = { ...imported.env, ...workflow.env };\n }\n\n // Merge pre block\n if (imported.pre) {\n if (!workflow.pre) {\n workflow.pre = {};\n }\n if (imported.pre.services) {\n workflow.pre.services = [...imported.pre.services, ...(workflow.pre.services ?? [])];\n }\n if (imported.pre.steps) {\n workflow.pre.steps = [...imported.pre.steps, ...(workflow.pre.steps ?? [])];\n }\n }\n\n // Merge post block\n if (imported.post) {\n if (!workflow.post) {\n workflow.post = {};\n }\n if (imported.post.services) {\n workflow.post.services = [...imported.post.services, ...(workflow.post.services ?? [])];\n }\n if (imported.post.steps) {\n workflow.post.steps = [...imported.post.steps, ...(workflow.post.steps ?? [])];\n }\n }\n\n // Merge worktree (main overrides per-hook)\n if (imported.worktree) {\n if (!workflow.worktree) {\n workflow.worktree = {};\n }\n const hooks = ['beforeCreate', 'afterCreate', 'beforeCompleted', 'afterCompleted'] as const;\n for (const hook of hooks) {\n if (imported.worktree[hook] && !workflow.worktree[hook]) {\n workflow.worktree[hook] = imported.worktree[hook];\n }\n }\n }\n\n // Merge max-workflows (main overrides imported)\n if (imported['max-workflows'] && !workflow['max-workflows']) {\n workflow['max-workflows'] = imported['max-workflows'];\n }\n\n // Merge launch-command and launcher (main overrides imported)\n if (imported['launch-command'] && !workflow['launch-command']) {\n workflow['launch-command'] = imported['launch-command'];\n }\n if (imported.launcher && !workflow.launcher) {\n workflow.launcher = imported.launcher;\n }\n\n // Merge keybindings (main overrides imported per action)\n if (imported.keybindings) {\n workflow.keybindings = { ...imported.keybindings, ...workflow.keybindings };\n }\n\n // Merge commands and choices (main overrides imported per name, whole entries)\n if (imported.commands) {\n workflow.commands = { ...imported.commands, ...workflow.commands };\n }\n if (imported.choices) {\n workflow.choices = { ...imported.choices, ...workflow.choices };\n }\n if (imported.runConfig) {\n workflow.runConfig = { ...imported.runConfig, ...workflow.runConfig };\n }\n\n if (imported['run-directory']) {\n workflow['run-directory'] = this.mergeRunDirectories(imported['run-directory'], workflow['run-directory']);\n }\n\n // Merge repair triage (main overrides imported)\n if (imported.repair && !workflow.repair) {\n workflow.repair = imported.repair;\n }\n\n // Merge system-prompt (concatenate)\n if (imported['system-prompt']) {\n if (workflow['system-prompt']) {\n workflow['system-prompt'] = `${imported['system-prompt']}\\n\\n${workflow['system-prompt']}`;\n } else {\n workflow['system-prompt'] = imported['system-prompt'];\n }\n }\n\n // Merge jobs (imported jobs used as base, main overrides)\n if (imported.jobs) {\n for (const [name, job] of Object.entries(imported.jobs)) {\n if (!(name in (workflow.jobs ?? {}))) {\n if (!workflow.jobs) {\n workflow.jobs = {};\n }\n workflow.jobs[name] = job;\n }\n }\n }\n }\n\n // Clean up imports field after resolution\n delete workflow.imports;\n }\n\n private mergeRunDirectories(base: RunDirectory, override?: RunDirectory): RunDirectory {\n if (!override) return base;\n const entries = new Map(base.entries.map((entry) => [entry.path, entry]));\n for (const entry of override.entries) entries.set(entry.path, entry);\n return {\n description: override.description,\n entries: [...entries.values()],\n };\n }\n\n /**\n * Resolve `extends` references in jobs.\n * Dot-prefixed jobs (e.g. `.ios-prebuild`) are shared templates.\n * When a job has `extends: .template-name`, it merges:\n * - steps: template steps prepended before job steps\n * - preJob.steps: template steps prepended before job preJob steps\n * - postJob.steps: template steps prepended before job postJob steps\n * - env: merged (job overrides template)\n * - system-prompt: concatenated (template + job)\n * - all other fields: job overrides template\n * Template jobs are removed from the jobs map after resolution.\n */\n resolveExtends(workflow: Workflow): void {\n const { jobs } = workflow;\n\n // Separate templates (dot-prefixed) from real jobs\n const templates = new Map<string, Job>();\n for (const [name, job] of Object.entries(jobs)) {\n if (name.startsWith('.')) {\n templates.set(name, job);\n }\n }\n\n // Resolve extends for each real job\n for (const [name, job] of Object.entries(jobs)) {\n if (name.startsWith('.')) continue;\n if (!job.extends) continue;\n\n const templateNames = Array.isArray(job.extends) ? job.extends : [job.extends];\n const jobOwnSteps = [...(job.steps ?? [])];\n const jobOwnPreSteps = [...(job.preJob?.steps ?? [])];\n const jobOwnPostSteps = [...(job.postJob?.steps ?? [])];\n const prependedSteps: import('../../schemas/workflowEngine').Step[] = [];\n const prependedPreJobSteps: import('../../schemas/workflowEngine').Step[] = [];\n const prependedPostJobSteps: import('../../schemas/workflowEngine').Step[] = [];\n\n for (const templateName of templateNames) {\n const template = templates.get(templateName);\n if (!template) {\n throw new Error(`Job \"${name}\" extends \"${templateName}\" but template not found`);\n }\n\n prependedSteps.push(...(template.steps ?? []));\n prependedPreJobSteps.push(...(template.preJob?.steps ?? []));\n prependedPostJobSteps.push(...(template.postJob?.steps ?? []));\n this.applyTemplate(job, template);\n }\n\n // Reconstruct steps: all template steps in order, then job's own steps\n job.steps = [...prependedSteps, ...jobOwnSteps];\n this.assignJobHookSteps(job, 'preJob', [...prependedPreJobSteps, ...jobOwnPreSteps]);\n this.assignJobHookSteps(job, 'postJob', [...prependedPostJobSteps, ...jobOwnPostSteps]);\n\n delete job.extends;\n }\n\n // Remove template jobs from the map\n for (const name of templates.keys()) {\n delete jobs[name];\n }\n }\n\n /**\n * Merge a single template into a job.\n * Called once per template when a job extends multiple templates.\n */\n private applyTemplate(job: Job, template: Job): void {\n // Steps: template steps prepended before job steps\n const templateSteps = template.steps ?? [];\n job.steps = [...templateSteps, ...(job.steps ?? [])];\n this.mergeJobHookSteps(job, template, 'preJob');\n this.mergeJobHookSteps(job, template, 'postJob');\n\n // Env: merge (job overrides template)\n if (template.env || job.env) {\n job.env = { ...template.env, ...job.env };\n }\n\n // System prompt: concatenate\n if (template['system-prompt'] && job['system-prompt']) {\n job['system-prompt'] = `${template['system-prompt']}\\n\\n${job['system-prompt']}`;\n } else if (template['system-prompt']) {\n job['system-prompt'] = template['system-prompt'];\n }\n\n // Scalar fields: inherit from template if not set on job\n if (template['runs-on'] && !job['runs-on']) job['runs-on'] = template['runs-on'];\n if (template.strategy && !job.strategy) job.strategy = template.strategy;\n if (template.context && !job.context) job.context = template.context;\n }\n\n private mergeJobHookSteps(job: Job, template: Job, hookKey: 'preJob' | 'postJob'): void {\n const templateSteps = template[hookKey]?.steps ?? [];\n const jobSteps = job[hookKey]?.steps ?? [];\n this.assignJobHookSteps(job, hookKey, [...templateSteps, ...jobSteps]);\n }\n\n private assignJobHookSteps(job: Job, hookKey: 'preJob' | 'postJob', steps: Job['steps']): void {\n if (steps.length > 0) {\n job[hookKey] = { steps };\n return;\n }\n\n delete job[hookKey];\n }\n\n async loadSecrets(secretFile: string): Promise<Map<string, string>> {\n const secrets = new Map<string, string>();\n if (!(await pathExists(this.runtime.fs, secretFile, this.runtime.ioContext))) {\n return secrets;\n }\n\n const content = getOrThrow(await this.runtime.fs.readTextFile(secretFile, this.runtime.ioContext));\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n const eqIdx = trimmed.indexOf('=');\n if (eqIdx === -1) continue;\n secrets.set(trimmed.slice(0, eqIdx), trimmed.slice(eqIdx + 1));\n }\n\n return secrets;\n }\n\n interpolate(template: string, context: InterpolationContext): string {\n return template.replace(/\\$\\{\\{\\s*(.+?)\\s*\\}\\}/g, (_match, expr: string) => {\n const parts = expr.trim().split('.');\n\n if (parts[0] === 'inputs' && parts[1]) {\n return context.inputs.get(parts[1]) || '';\n }\n if (parts[0] === 'matrix' && parts[1]) {\n return context.matrix[parts[1]] || '';\n }\n if (parts[0] === 'secrets' && parts[1]) {\n return context.secrets.get(parts[1]) || this.runtime.baseEnvironment[parts[1]] || '';\n }\n if (parts[0] === 'env' && parts[1]) {\n return context.env[parts[1]] || this.runtime.baseEnvironment[parts[1]] || '';\n }\n if (parts[0] === 'runConfig' && parts[1]) {\n const value = context.runConfig?.[parts[1]];\n return Array.isArray(value) ? value.join(',') : (value ?? '');\n }\n if (parts[0] === 'runner' && parts[1] === 'os') return 'macOS';\n if (parts[0] === 'github' && parts[1] === 'sha') {\n return this.githubSha;\n }\n\n if (expr.includes('hashFiles')) return 'local';\n\n return `\\${{ ${expr} }}`;\n });\n }\n\n isActionSkipped(uses: string): boolean {\n return SKIPPED_ACTIONS.some((prefix) => uses.startsWith(prefix));\n }\n\n resolveJobOrder(jobs: Record<string, Job>, targetJob: string | null): string[] {\n const visited = new Set<string>();\n const order: string[] = [];\n\n const visit = (jobName: string) => {\n if (visited.has(jobName)) return;\n visited.add(jobName);\n\n const job = jobs[jobName];\n if (!job) {\n throw new Error(`Job not found: ${jobName}`);\n }\n\n const deps = job.needs ? (Array.isArray(job.needs) ? job.needs : [job.needs]) : [];\n for (const dep of deps) {\n visit(dep);\n }\n\n order.push(jobName);\n };\n\n if (targetJob) {\n visit(targetJob);\n } else {\n for (const jobName of Object.keys(jobs)) {\n visit(jobName);\n }\n }\n\n return order;\n }\n\n expandMatrix(job: Job): MatrixEntry[] {\n if (!job.strategy?.matrix) return [{}];\n\n const { include, ...rest } = job.strategy.matrix;\n\n if (include && include.length > 0) {\n return include;\n }\n\n const keys = Object.keys(rest).filter((k) => Array.isArray(rest[k]));\n if (keys.length === 0) return [{}];\n\n let combos: MatrixEntry[] = [{}];\n for (const key of keys) {\n const values = rest[key] as string[];\n const newCombos: MatrixEntry[] = [];\n for (const combo of combos) {\n for (const val of values) {\n newCombos.push({ ...combo, [key]: String(val) });\n }\n }\n combos = newCombos;\n }\n\n return combos;\n }\n}\n","import { resolve } from 'node:path';\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\n\nimport type { CommandRef, Step, Workflow } from '../../schemas/workflowEngine';\nimport { compatibleRunners } from '../WorkflowCatalogService';\nimport { findWorkflowPaths } from '../workflowDiscovery';\nimport { commandTemplateOf, WorkflowParserService } from '../WorkflowParserService';\nimport type { WorkflowDiagnostic, WorkflowDoctorOptions, WorkflowDoctorReport } from './types';\n\nconst INVALID_WORKFLOW_PREFIX = 'Invalid workflow:';\nconst PROBLEM_SEPARATOR = /\\n\\s*- /;\nconst INPUT_REFERENCE = /\\$\\{\\{\\s*inputs\\.([A-Za-z0-9_-]+)\\s*\\}\\}/g;\nconst WORKFLOW_DISPATCH_TRIGGER = 'workflow_dispatch';\nconst STEP_SEPARATOR = ' › ';\n\n/** One step and where it sits, as a reader finds it in the file. */\ninterface LocatedStep {\n step: Step;\n location: string;\n}\n\nfunction stepLabel(step: Step, index: number): string {\n return step.name ?? step.id ?? `step ${String(index + 1)}`;\n}\n\n/** Every step a workflow can run, parallel ones included, each with where it is. */\nfunction collectSteps(workflow: Workflow): LocatedStep[] {\n const located: LocatedStep[] = [];\n const walk = (steps: readonly Step[] | undefined, where: string): void => {\n for (const [index, step] of (steps ?? []).entries()) {\n const location = `${where}${STEP_SEPARATOR}${stepLabel(step, index)}`;\n if (step.parallel) {\n walk(step.parallel as Step[], location);\n continue;\n }\n located.push({ step, location });\n }\n };\n walk(workflow.pre?.steps, 'pre');\n walk(workflow.post?.steps, 'post');\n walk(workflow.repair?.steps, 'repair');\n walk(workflow.worktree?.beforeCreate?.steps, 'worktree.beforeCreate');\n walk(workflow.worktree?.afterCreate?.steps, 'worktree.afterCreate');\n for (const [name, job] of Object.entries(workflow.jobs)) {\n walk(job.preJob?.steps, `jobs.${name}.preJob`);\n walk(job.steps, `jobs.${name}`);\n walk(job.postJob?.steps, `jobs.${name}.postJob`);\n }\n return located;\n}\n\nfunction referencesIn(value: unknown, pattern: RegExp): Set<string> {\n const found = new Set<string>();\n for (const match of JSON.stringify(value ?? null).matchAll(pattern)) {\n if (match[1] !== undefined) found.add(match[1]);\n }\n return found;\n}\n\n/** The customRun entries of a step: one entry any runner runs, or one per runner. */\nfunction customRunEntries(customRun: Step['customRun']): { runner?: string; runConfig?: Record<string, unknown> }[] {\n if (!customRun) return [];\n if (typeof (customRun as { prompt?: unknown }).prompt === 'string') {\n const entry = customRun as { runConfig?: Record<string, unknown> };\n return [entry.runConfig === undefined ? {} : { runConfig: entry.runConfig }];\n }\n return Object.entries(customRun as Record<string, { runConfig?: Record<string, unknown> }>).map(\n ([runner, entry]) => ({ runner, ...(entry.runConfig === undefined ? {} : { runConfig: entry.runConfig }) }),\n );\n}\n\n/** The problems the parser reports together, one diagnostic each. */\nfunction parseProblems(message: string): string[] {\n if (!message.startsWith(INVALID_WORKFLOW_PREFIX)) return [message];\n return message\n .slice(INVALID_WORKFLOW_PREFIX.length)\n .split(PROBLEM_SEPARATOR)\n .map((problem) => problem.trim())\n .filter((problem) => problem.length > 0);\n}\n\n/**\n * Check one workflow before anything runs it.\n *\n * Everything the parser refuses comes back as errors, one per problem. On top\n * of that, what only shows up once a step runs:\n * - runConfig keys nothing reads. A key a host does not know, such as a\n * misspelled `majormode`, would otherwise run the step on defaults or fail it\n * mid-run. Which keys are known depends on the host, so they are errors only\n * when `runConfigKeys` names the host's own; without them, keys a templated\n * step's command does not read are warnings.\n * - A job needing one that does not exist.\n * - Runner maps no runner satisfies, customRun steps no terminal can run, and\n * `${{ inputs.X }}` for inputs the workflow does not declare.\n */\nexport async function diagnoseWorkflow(\n workflowPath: string,\n options: WorkflowDoctorOptions,\n): Promise<WorkflowDoctorReport> {\n const path = resolve(workflowPath);\n const parser = options.parser ?? new WorkflowParserService(options.runtime);\n let workflow: Workflow;\n try {\n workflow = await parser.parseWorkflowFile(path);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n path,\n diagnostics: parseProblems(message).map((problem) => ({\n level: 'error',\n code: 'invalid-workflow',\n message: problem,\n })),\n };\n }\n\n const diagnostics: WorkflowDiagnostic[] = [];\n const hostKeys = options.runConfigKeys === undefined ? undefined : new Set(options.runConfigKeys);\n const reads = (command: string): Set<string> | undefined => {\n const declared = workflow.commands?.[command];\n return declared === undefined ? undefined : new Set(parser.templateVariables(commandTemplateOf(declared).run));\n };\n const unknownKeys = (keys: Iterable<string>, known: ReadonlySet<string>): string[] =>\n [...new Set(keys)].filter((key) => !known.has(key));\n\n for (const { step, location } of collectSteps(workflow)) {\n const stepKeys = Object.keys(step.runConfig ?? {});\n // A templated step runs through one of the commands it offers, whose\n // templates read runConfig values; a host running it in-process also reads\n // its own keys. The step's runConfig is shared by every command it offers,\n // while a command's own runConfig is that command's alone.\n if (Array.isArray(step.interactiveRun)) {\n const refs = step.interactiveRun as CommandRef[];\n const offeredReads = refs.map((ref) => reads(ref.command) ?? new Set<string>());\n const report = (key: string, commands: string): void => {\n diagnostics.push({\n level: hostKeys === undefined ? 'warning' : 'error',\n code: 'unknown-run-config-key',\n location,\n message:\n hostKeys === undefined\n ? `runConfig key \"${key}\" is not read by ${commands}; a host may still read it (pass the host's keys to check).`\n : `runConfig key \"${key}\" is neither a host setting nor read by ${commands}.`,\n });\n };\n const anyCommand = new Set([...offeredReads.flatMap((keys) => [...keys]), ...(hostKeys ?? [])]);\n const offeredNames = refs.map((ref) => `\"${ref.command}\"`).join(' or ');\n for (const key of unknownKeys(stepKeys, anyCommand)) report(key, `the ${offeredNames} command`);\n for (const [index, ref] of refs.entries()) {\n const own = new Set([...(offeredReads[index] ?? []), ...(hostKeys ?? [])]);\n for (const key of unknownKeys(Object.keys(ref.runConfig ?? {}), own))\n report(key, `the \"${ref.command}\" command`);\n }\n } else if (step.customRun && hostKeys !== undefined) {\n // A customRun step is the host's alone to run, so its keys are the host's.\n for (const entry of [{ runConfig: step.runConfig }, ...customRunEntries(step.customRun)]) {\n for (const key of unknownKeys(Object.keys(entry.runConfig ?? {}), hostKeys)) {\n diagnostics.push({\n level: 'error',\n code: 'unknown-run-config-key',\n location:\n 'runner' in entry && entry.runner ? `${location}${STEP_SEPARATOR}customRun.${entry.runner}` : location,\n message: `runConfig key \"${key}\" is not a host setting.`,\n });\n }\n }\n }\n if (step.customRun && step.run === undefined && step.interactiveRun === undefined) {\n diagnostics.push({\n level: 'warning',\n code: 'custom-run-only',\n location,\n message:\n 'customRun has no run or interactiveRun fallback, so only a host that runs steps itself can run it; the CLI fails it.',\n });\n }\n }\n\n if (hostKeys !== undefined) {\n for (const [runner, definition] of Object.entries(workflow.runners ?? {})) {\n for (const key of unknownKeys(Object.keys(definition.runConfig ?? {}), hostKeys)) {\n diagnostics.push({\n level: 'error',\n code: 'unknown-run-config-key',\n location: `runners.${runner}`,\n message: `runConfig key \"${key}\" is not a host setting.`,\n });\n }\n }\n }\n\n const jobs = new Set(Object.keys(workflow.jobs));\n for (const [name, job] of Object.entries(workflow.jobs)) {\n const needs = job.needs === undefined ? [] : Array.isArray(job.needs) ? job.needs : [job.needs];\n for (const needed of needs.filter((candidate) => !jobs.has(candidate))) {\n diagnostics.push({\n level: 'error',\n code: 'unknown-job',\n location: `jobs.${name}`,\n message: `needs \"${needed}\", which is not a job.`,\n });\n }\n }\n\n const runners = compatibleRunners(workflow);\n if (runners !== undefined && runners.length === 0) {\n diagnostics.push({\n level: 'warning',\n code: 'no-common-runner',\n message: 'No runner is offered by every step, so any launch that names a runner fails at a step that lacks it.',\n });\n }\n\n const dispatch = (workflow.on as Record<string, { inputs?: Record<string, unknown> } | null> | undefined)?.[\n WORKFLOW_DISPATCH_TRIGGER\n ];\n const declaredInputs = new Set(Object.keys(dispatch?.inputs ?? {}));\n const { on: _triggers, ...rest } = workflow;\n for (const input of referencesIn(rest, INPUT_REFERENCE)) {\n if (declaredInputs.has(input)) continue;\n diagnostics.push({\n level: 'warning',\n code: 'undeclared-input',\n message: `\\${{ inputs.${input} }} names an input workflow_dispatch does not declare, so it is empty unless a launch passes it.`,\n });\n }\n\n return { path, diagnostics };\n}\n\n/**\n * Check every workflow a path names: a workflow file, or each workflow file\n * under a directory. A file that does not even parse is one report, not the\n * end of the listing.\n */\nexport async function diagnoseWorkflows(\n paths: readonly string[],\n options: WorkflowDoctorOptions,\n): Promise<WorkflowDoctorReport[]> {\n const parser = options.parser ?? new WorkflowParserService(options.runtime);\n const reports: WorkflowDoctorReport[] = [];\n for (const target of paths) {\n const resolved = resolve(target);\n let directory = false;\n try {\n directory =\n getOrThrow(await options.runtime.fs.fileInfo(resolved, options.runtime.ioContext)).kind === 'directory';\n } catch {\n // A path that does not exist is a workflow file the parser reports as missing.\n }\n if (!directory) {\n reports.push(await diagnoseWorkflow(resolved, { ...options, parser }));\n continue;\n }\n for (const relativePath of (await findWorkflowPaths(options.runtime, resolved)).sort()) {\n reports.push(await diagnoseWorkflow(resolve(resolved, relativePath), { ...options, parser }));\n }\n }\n return reports;\n}\n","export class RmuxCommandError extends Error {\n run;\n constructor(run) {\n super(commandFailureMessage(run));\n this.name = \"RmuxCommandError\";\n this.run = run;\n }\n}\nexport class RmuxCompatibilityError extends Error {\n constructor(message) {\n super(message);\n this.name = \"RmuxCompatibilityError\";\n }\n}\nfunction commandFailureMessage(run) {\n const command = commandName(run.args);\n const outcome = run.signal === undefined\n ? `status ${run.returnCode}`\n : `signal ${run.signal}`;\n const stderr = run.stderr.trim();\n const suffix = stderr.length > 0 ? `: ${stderr}` : \"\";\n return `rmux command ${JSON.stringify(command)} failed with ${outcome}${suffix}`;\n}\nfunction commandName(args) {\n for (let index = 1; index < args.length; index += 1) {\n const arg = args[index];\n if (arg === \"-S\" || arg === \"-L\") {\n index += 1;\n continue;\n }\n if (arg !== undefined) {\n return arg;\n }\n }\n return args[0] ?? \"rmux\";\n}\n","import { RmuxCommandError } from \"./errors.js\";\nexport class CommandRun {\n args;\n returnCode;\n signal;\n stdout;\n stderr;\n constructor(args, returnCode, stdout, stderr, signal) {\n this.args = [...args];\n this.returnCode = returnCode;\n if (signal !== undefined) {\n this.signal = signal;\n }\n this.stdout = stdout;\n this.stderr = stderr;\n }\n get returncode() {\n return this.returnCode;\n }\n checkReturnCode() {\n if (this.returnCode !== 0) {\n throw new RmuxCommandError(this);\n }\n return this;\n }\n}\n","import { performance } from \"node:perf_hooks\";\nexport function durationMilliseconds(value) {\n const milliseconds = typeof value === \"number\"\n ? value * 1000\n : (value.milliseconds ?? 0) + (value.seconds ?? 0) * 1000;\n if (!Number.isFinite(milliseconds) || milliseconds < 0) {\n throw new RangeError(\"duration must be a non-negative finite value\");\n }\n return milliseconds;\n}\nexport function sleep(milliseconds) {\n return new Promise((resolve) => {\n setTimeout(resolve, milliseconds);\n });\n}\nexport function deadlineFromNow(timeout) {\n return performance.now() + durationMilliseconds(timeout);\n}\nexport function deadlineExpired(deadline) {\n return performance.now() >= deadline;\n}\nexport function remainingMilliseconds(deadline) {\n return Math.max(0, deadline - performance.now());\n}\n","import { spawn } from \"node:child_process\";\nimport { constants } from \"node:os\";\nexport function mergedEnv(env) {\n if (env === undefined) {\n return undefined;\n }\n return { ...process.env, ...env };\n}\nexport function runProcess(argv, options) {\n const command = argv[0];\n if (command === undefined) {\n return Promise.reject(new Error(\"argv must not be empty\"));\n }\n return new Promise((resolve, reject) => {\n const args = argv.slice(1);\n const child = spawn(command, args, {\n cwd: options.cwd,\n env: mergedEnv(options.env),\n stdio: \"pipe\",\n });\n child.stdin.end();\n let stdout = \"\";\n let stderr = \"\";\n child.stdout.setEncoding(\"utf8\");\n child.stderr.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk) => {\n stdout += chunk;\n });\n child.stderr.on(\"data\", (chunk) => {\n stderr += chunk;\n });\n child.on(\"error\", reject);\n child.on(\"close\", (code, signal) => {\n resolve({\n code: processReturnCode(code, signal),\n signal: signal ?? undefined,\n stdout,\n stderr,\n });\n });\n });\n}\nfunction processReturnCode(code, signal) {\n if (code !== null) {\n return code;\n }\n if (signal !== null) {\n const signalNumber = constants.signals[signal];\n if (typeof signalNumber === \"number\") {\n return -signalNumber;\n }\n }\n return 1;\n}\n","import { spawn } from \"node:child_process\";\nimport { deadlineFromNow, remainingMilliseconds, } from \"./duration.js\";\nimport { mergedEnv } from \"./process.js\";\nexport class ControlOutput {\n paneId;\n data;\n constructor(paneId, data) {\n this.paneId = paneId;\n this.data = data;\n }\n get pane_id() {\n return this.paneId;\n }\n}\nexport class ControlExtendedOutput {\n paneId;\n ageMs;\n data;\n constructor(paneId, ageMs, data) {\n this.paneId = paneId;\n this.ageMs = ageMs;\n this.data = data;\n }\n get pane_id() {\n return this.paneId;\n }\n get age_ms() {\n return this.ageMs;\n }\n}\nexport class ControlExit {\n reason;\n constructor(reason) {\n if (reason !== undefined) {\n this.reason = reason;\n }\n }\n}\nexport class ControlNotification {\n prefix;\n line;\n constructor(prefix, line) {\n this.prefix = prefix;\n this.line = line;\n }\n}\nexport class ControlMalformed {\n prefix;\n line;\n reason;\n constructor(prefix, line, reason) {\n this.prefix = prefix;\n this.line = line;\n this.reason = reason;\n }\n}\nexport class ControlModeStreamEndedError extends Error {\n constructor(message) {\n super(message);\n this.name = \"ControlModeStreamEndedError\";\n }\n}\nexport function spawnControlProcess(options) {\n const child = spawn(options.binary, options.args, {\n cwd: options.cwd,\n env: mergedEnv(options.env),\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n return child;\n}\nexport function waitForControlProcessSpawn(process) {\n return new Promise((resolve, reject) => {\n const cleanup = () => {\n process.off(\"error\", onError);\n process.off(\"spawn\", onSpawn);\n };\n const onError = (error) => {\n cleanup();\n reject(error);\n };\n const onSpawn = () => {\n cleanup();\n resolve();\n };\n process.once(\"error\", onError);\n process.once(\"spawn\", onSpawn);\n });\n}\nexport class ControlModeClient {\n process;\n #lines = new AsyncQueue();\n #deferredEvents = [];\n #buffer = \"\";\n #stderr = \"\";\n #closed = false;\n #ended = false;\n #processError;\n #activeReader;\n constructor(process) {\n this.process = process;\n this.process.stdout.setEncoding(\"utf8\");\n this.process.stderr.setEncoding(\"utf8\");\n this.process.stdout.on(\"data\", (chunk) => {\n this.feedStdout(chunk);\n });\n this.process.stdout.on(\"end\", () => {\n if (this.#buffer.length > 0) {\n this.#lines.push({ kind: \"line\", line: this.#buffer });\n this.#buffer = \"\";\n }\n this.finish();\n });\n this.process.stderr.on(\"data\", (chunk) => {\n this.#stderr = (this.#stderr + chunk).slice(-4096);\n });\n this.process.on(\"error\", (error) => {\n this.#processError = error;\n this.finish();\n });\n this.process.on(\"close\", () => {\n this.finish();\n });\n }\n sendCommand(command) {\n if (isChildClosed(this.process)) {\n throw new Error(\"control-mode process has exited\");\n }\n try {\n this.process.stdin.write(command);\n if (!command.endsWith(\"\\n\")) {\n this.process.stdin.write(\"\\n\");\n }\n }\n catch (error) {\n throw new Error(`failed to write control-mode command: ${errorMessage(error)}`);\n }\n }\n async runCommand(command, timeout = 5) {\n const releaseReader = this.acquireReader(\"runCommand\");\n const deadline = deadlineFromNow(timeout);\n try {\n this.sendCommand(command);\n let commandKey;\n for (;;) {\n const event = await this.readEventFromLines({\n milliseconds: remainingMilliseconds(deadline),\n });\n if (event instanceof ControlExit) {\n throw new ControlModeStreamEndedError(`control-mode exited while running ${command}: ${event.reason ?? \"unknown reason\"}`);\n }\n if (!(event instanceof ControlNotification)) {\n this.#deferredEvents.push(event);\n continue;\n }\n if (event.prefix === \"%begin\") {\n commandKey = controlCommandKey(event.line);\n continue;\n }\n if (event.prefix !== \"%end\" && event.prefix !== \"%error\") {\n continue;\n }\n const eventKey = controlCommandKey(event.line);\n if (commandKey !== undefined && eventKey !== undefined && eventKey !== commandKey) {\n continue;\n }\n if (event.prefix === \"%error\") {\n throw new Error(`control-mode command failed: ${command}; event=${JSON.stringify(event.line)}`);\n }\n return;\n }\n }\n finally {\n releaseReader();\n }\n }\n async readEvent(timeout) {\n const releaseReader = this.acquireReader(\"readEvent\");\n try {\n return await this.readEventUnlocked(timeout);\n }\n finally {\n releaseReader();\n }\n }\n async readEventUnlocked(timeout) {\n const deferred = this.#deferredEvents.shift();\n if (deferred !== undefined) {\n return deferred;\n }\n return this.readEventFromLines(timeout);\n }\n async readEventFromLines(timeout) {\n const deadline = timeout === undefined ? undefined : deadlineFromNow(timeout);\n for (;;) {\n if (this.#ended && this.#lines.isEmpty()) {\n throw this.streamEndedError();\n }\n const timeoutMs = deadline === undefined ? undefined : remainingMilliseconds(deadline);\n const item = await this.#lines.shift(timeoutMs);\n if (item.kind === \"end\") {\n throw this.streamEndedError();\n }\n const event = parseControlLine(item.line.replace(/\\n$/, \"\"));\n if (event !== undefined) {\n return event;\n }\n }\n }\n async *events(timeout) {\n const releaseReader = this.acquireReader(\"events\");\n try {\n for (;;) {\n let event;\n try {\n event = await this.readEventUnlocked(timeout);\n }\n catch (error) {\n if (error instanceof ControlModeStreamEndedError) {\n return;\n }\n throw error;\n }\n yield event;\n if (event instanceof ControlExit) {\n return;\n }\n }\n }\n finally {\n releaseReader();\n }\n }\n async waitForExit(timeout) {\n for await (const event of this.events(timeout)) {\n if (event instanceof ControlExit) {\n return event;\n }\n }\n throw new Error(\"control-mode stream ended before %exit\");\n }\n async close() {\n if (this.#closed) {\n return;\n }\n this.#closed = true;\n if (!isChildClosed(this.process)) {\n try {\n this.process.stdin.write(\"\\n\");\n this.process.stdin.end();\n }\n catch {\n // Best-effort close path.\n }\n try {\n await waitForChildClose(this.process, 2000);\n }\n catch {\n this.process.kill(\"SIGKILL\");\n await waitForChildClose(this.process, 2000);\n }\n }\n }\n acquireReader(operation) {\n if (this.#activeReader !== undefined) {\n throw new Error(`control-mode already has an active reader: ${this.#activeReader}`);\n }\n this.#activeReader = operation;\n return () => {\n if (this.#activeReader === operation) {\n this.#activeReader = undefined;\n }\n };\n }\n feedStdout(chunk) {\n this.#buffer += chunk;\n for (;;) {\n const index = this.#buffer.indexOf(\"\\n\");\n if (index < 0) {\n return;\n }\n const line = this.#buffer.slice(0, index + 1);\n this.#buffer = this.#buffer.slice(index + 1);\n this.#lines.push({ kind: \"line\", line });\n }\n }\n finish() {\n if (this.#ended) {\n return;\n }\n this.#ended = true;\n this.#lines.push({ kind: \"end\" });\n }\n streamEndedError() {\n if (this.#processError !== undefined) {\n return this.#processError;\n }\n const stderr = this.#stderr.trim();\n if (stderr.length > 0) {\n return new ControlModeStreamEndedError(`control-mode stream ended: ${stderr}`);\n }\n return new ControlModeStreamEndedError(\"control-mode stream ended\");\n }\n}\nexport function parseControlLine(line) {\n if (!line.startsWith(\"%\")) {\n return undefined;\n }\n if (line.startsWith(\"%output \")) {\n const [paneId, payload] = splitPayload(line.slice(\"%output \".length));\n if (paneId === undefined) {\n return new ControlMalformed(\"%output\", line, \"missing pane id\");\n }\n return new ControlOutput(paneId, decodeTmuxOctal(payload));\n }\n if (line.startsWith(\"%extended-output \")) {\n const [paneId, rest] = splitPayload(line.slice(\"%extended-output \".length));\n if (paneId === undefined) {\n return new ControlMalformed(\"%extended-output\", line, \"missing pane id\");\n }\n const [age, payloadRaw] = splitPayload(rest);\n if (age === undefined) {\n return new ControlMalformed(\"%extended-output\", line, \"missing age\");\n }\n const payload = payloadRaw.startsWith(\": \") ? payloadRaw.slice(2) : payloadRaw;\n const ageMs = parseInteger(age);\n if (ageMs === undefined) {\n return new ControlMalformed(\"%extended-output\", line, \"invalid age\");\n }\n return new ControlExtendedOutput(paneId, ageMs, decodeTmuxOctal(payload));\n }\n const prefix = line.split(\" \", 1)[0] ?? line;\n if (prefix === \"%exit\") {\n const reason = line.slice(\"%exit\".length).trim();\n return new ControlExit(reason || undefined);\n }\n return new ControlNotification(prefix, line);\n}\nexport function decodeTmuxOctal(value) {\n const chunks = [];\n let index = 0;\n while (index < value.length) {\n if (value[index] === \"\\\\\" &&\n index + 3 < value.length &&\n isOctal(value.slice(index + 1, index + 4))) {\n chunks.push(Number.parseInt(value.slice(index + 1, index + 4), 8));\n index += 4;\n continue;\n }\n const codePoint = value.codePointAt(index);\n if (codePoint === undefined) {\n break;\n }\n chunks.push(...Buffer.from(String.fromCodePoint(codePoint), \"utf8\"));\n index += codePoint > 0xffff ? 2 : 1;\n }\n return Buffer.from(chunks);\n}\nfunction splitPayload(value) {\n const separator = value.indexOf(\" \");\n if (separator <= 0) {\n return [undefined, \"\"];\n }\n return [value.slice(0, separator), value.slice(separator + 1)];\n}\nfunction isOctal(value) {\n return /^[0-7]{3}$/.test(value);\n}\nfunction parseInteger(value) {\n if (!/^-?[0-9]+$/.test(value)) {\n return undefined;\n }\n return Number.parseInt(value, 10);\n}\nfunction controlCommandKey(line) {\n const parts = line.trim().split(/\\s+/);\n if (parts.length < 4) {\n return undefined;\n }\n // RMUX control mode correlates command boundaries on time, number, and flags.\n return parts.slice(1, 4).join(\" \");\n}\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : String(error);\n}\nfunction waitForChildClose(child, timeoutMs) {\n if (isChildClosed(child)) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n cleanup();\n reject(new Error(\"timed out waiting for control-mode process\"));\n }, timeoutMs);\n const onClose = () => {\n cleanup();\n resolve();\n };\n const cleanup = () => {\n clearTimeout(timer);\n child.off(\"close\", onClose);\n };\n child.on(\"close\", onClose);\n });\n}\nfunction isChildClosed(child) {\n return child.exitCode !== null || child.signalCode !== null;\n}\nclass AsyncQueue {\n #items = [];\n #waiters = [];\n isEmpty() {\n return this.#items.length === 0;\n }\n push(value) {\n const waiter = this.#waiters.shift();\n if (waiter !== undefined) {\n waiter(value);\n return;\n }\n this.#items.push(value);\n }\n shift(timeoutMs) {\n if (this.#items.length > 0) {\n const item = this.#items.shift();\n if (item !== undefined) {\n return Promise.resolve(item);\n }\n }\n return new Promise((resolve, reject) => {\n let timer;\n const waiter = (value) => {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n resolve(value);\n };\n this.#waiters.push(waiter);\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n const index = this.#waiters.indexOf(waiter);\n if (index >= 0) {\n this.#waiters.splice(index, 1);\n }\n reject(new Error(\"timed out waiting for control-mode event\"));\n }, timeoutMs);\n }\n });\n }\n}\n","import { deadlineExpired, deadlineFromNow, durationMilliseconds, sleep } from \"./duration.js\";\nexport class TextMatch {\n text;\n row;\n column;\n constructor(text, row, column) {\n this.text = text;\n this.row = row;\n this.column = column;\n }\n}\nexport class TextExpectation {\n #pane;\n #mode;\n #expected;\n #interval;\n constructor(pane, options = {}) {\n this.#pane = pane;\n this.#mode = options.mode;\n this.#expected = options.expected;\n this.#interval = options.interval ?? 0.05;\n }\n toContain(text, options = {}) {\n return new TextExpectation(this.#pane, {\n mode: \"contains\",\n expected: text,\n interval: options.interval ?? 0.05,\n });\n }\n toHaveText(text, options = {}) {\n return new TextExpectation(this.#pane, {\n mode: \"equals\",\n expected: text,\n interval: options.interval ?? 0.05,\n });\n }\n async timeout(value) {\n if (this.#mode === undefined || this.#expected === undefined) {\n throw new Error(\"choose an expectation before setting a timeout\");\n }\n if (this.#mode === \"contains\") {\n return this.#pane.waitForText(this.#expected, {\n timeout: value,\n interval: this.#interval,\n });\n }\n return this.#pane.waitForExactText(this.#expected, {\n timeout: value,\n interval: this.#interval,\n });\n }\n}\nexport async function pollUntil(timeout, interval, callback, failure) {\n const deadline = deadlineFromNow(timeout);\n const intervalMs = durationMilliseconds(interval);\n for (;;) {\n const result = await callback();\n if (result !== undefined) {\n return result;\n }\n if (deadlineExpired(deadline)) {\n throw failure();\n }\n await sleep(intervalMs);\n }\n}\nexport function rowColumn(text, index) {\n const before = text.slice(0, index);\n const row = countOccurrences(before, \"\\n\");\n const lineStart = before.lastIndexOf(\"\\n\");\n if (lineStart < 0) {\n return [row, before.length];\n }\n return [row, before.length - lineStart - 1];\n}\nfunction countOccurrences(text, needle) {\n let count = 0;\n let index = text.indexOf(needle);\n while (index >= 0) {\n count += 1;\n index = text.indexOf(needle, index + needle.length);\n }\n return count;\n}\n","export async function ensureServerCompatible(server) {\n if (server.checkCompatibility) {\n await server.capabilities();\n }\n}\n","export class PaneExitState {\n dead;\n status;\n constructor(dead, status) {\n this.dead = dead;\n if (status !== undefined) {\n this.status = status;\n }\n }\n}\n","import { deadlineExpired, deadlineFromNow, durationMilliseconds, sleep } from \"./duration.js\";\nexport class TextLocator {\n pane;\n text;\n index;\n constructor(pane, text, index) {\n this.pane = pane;\n this.text = text;\n if (index !== undefined) {\n this.index = index;\n }\n }\n async all() {\n return (await this.pane.snapshot()).findAllText(this.text);\n }\n async count() {\n return (await this.all()).length;\n }\n first() {\n return new TextLocator(this.pane, this.text, 0);\n }\n last() {\n return new TextLocator(this.pane, this.text, -1);\n }\n nth(index) {\n return new TextLocator(this.pane, this.text, index);\n }\n async isVisible() {\n return this.resolve(await this.all()) !== undefined;\n }\n expect() {\n return new LocatorExpectation(this);\n }\n resolve(matches) {\n if (this.index === undefined) {\n return matches[0];\n }\n const normalized = this.index < 0 ? matches.length + this.index : this.index;\n return matches[normalized];\n }\n}\nexport class LocatorExpectation {\n #locator;\n #mode;\n #expected;\n #interval;\n constructor(locator, options = {}) {\n this.#locator = locator;\n this.#mode = options.mode;\n this.#expected = options.expected;\n this.#interval = options.interval ?? 0.05;\n }\n toBeVisible(options = {}) {\n return new LocatorExpectation(this.#locator, {\n mode: \"visible\",\n interval: options.interval ?? 0.05,\n });\n }\n toHaveText(text, options = {}) {\n return new LocatorExpectation(this.#locator, {\n mode: \"text\",\n expected: text,\n interval: options.interval ?? 0.05,\n });\n }\n toHaveCount(count, options = {}) {\n return new LocatorExpectation(this.#locator, {\n mode: \"count\",\n expected: count,\n interval: options.interval ?? 0.05,\n });\n }\n async timeout(value) {\n if (this.#mode === undefined) {\n throw new Error(\"choose an expectation before setting a timeout\");\n }\n const deadline = deadlineFromNow(value);\n const intervalMs = durationMilliseconds(this.#interval);\n let lastCount = 0;\n for (;;) {\n const matches = await this.#locator.all();\n lastCount = matches.length;\n const match = this.#locator.resolve(matches);\n if (this.#mode === \"visible\" && match !== undefined) {\n return match;\n }\n if (this.#mode === \"text\" && match !== undefined && match.text === this.#expected) {\n return match;\n }\n if (this.#mode === \"count\" && lastCount === this.#expected) {\n return lastCount;\n }\n if (deadlineExpired(deadline)) {\n throw new Error(this.failureMessage(lastCount));\n }\n await sleep(intervalMs);\n }\n }\n failureMessage(lastCount) {\n if (this.#mode === \"visible\") {\n return `text not visible before timeout: ${JSON.stringify(this.#locator.text)}`;\n }\n if (this.#mode === \"text\") {\n return `text locator did not resolve to expected text before timeout: ${JSON.stringify(this.#locator.text)} != ${JSON.stringify(this.#expected)}`;\n }\n if (this.#mode === \"count\") {\n return `text locator count did not match before timeout: ${lastCount} != ${this.#expected}`;\n }\n return \"locator expectation failed before timeout\";\n }\n}\n","import { rowColumn, TextMatch } from \"./expectations.js\";\nexport class PaneSnapshot {\n visibleText;\n constructor(visibleText) {\n this.visibleText = visibleText;\n }\n get visible_text() {\n return this.visibleText;\n }\n get lines() {\n return this.visibleText.split(/\\r?\\n/).filter((line, index, lines) => {\n return index < lines.length - 1 || line.length > 0;\n });\n }\n rowText(row) {\n const line = this.lines[row];\n if (line === undefined) {\n throw new RangeError(`row is outside the snapshot: ${row}`);\n }\n return line;\n }\n findText(text) {\n const index = this.visibleText.indexOf(text);\n if (index < 0) {\n return undefined;\n }\n const [row, column] = rowColumn(this.visibleText, index);\n return new TextMatch(text, row, column);\n }\n findAllText(text) {\n if (text.length === 0) {\n return [];\n }\n const matches = [];\n let start = 0;\n for (;;) {\n const index = this.visibleText.indexOf(text, start);\n if (index < 0) {\n return matches;\n }\n const [row, column] = rowColumn(this.visibleText, index);\n matches.push(new TextMatch(text, row, column));\n start = index + text.length;\n }\n }\n}\n","import { ControlExit, ControlExtendedOutput, ControlModeClient, ControlOutput, } from \"./control.js\";\nimport { deadlineFromNow, remainingMilliseconds } from \"./duration.js\";\nimport { PaneSnapshot } from \"./snapshot.js\";\nexport class PaneOutputChunk {\n paneId;\n data;\n ageMs;\n constructor(paneId, data, ageMs) {\n this.paneId = paneId;\n this.data = data;\n if (ageMs !== undefined) {\n this.ageMs = ageMs;\n }\n }\n get pane_id() {\n return this.paneId;\n }\n get age_ms() {\n return this.ageMs;\n }\n}\nexport class PaneOutputStream {\n #paneId;\n #control;\n constructor(paneId, control) {\n this.#paneId = paneId;\n this.#control = control;\n }\n static async open(pane) {\n const paneId = await pane.id();\n const control = new ControlModeClient(await pane.server.controlMode());\n try {\n await control.runCommand(`attach-session -t ${paneId}`);\n }\n catch (error) {\n await control.close();\n throw error;\n }\n return new PaneOutputStream(paneId, control);\n }\n async close() {\n await this.#control.close();\n }\n async next(timeout) {\n const deadline = timeout === undefined ? undefined : deadlineFromNow(timeout);\n for (;;) {\n const event = await this.#control.readEvent(deadline === undefined ? undefined : { milliseconds: remainingMilliseconds(deadline) });\n if (event instanceof ControlExit) {\n throw new Error(\"control-mode stream exited\");\n }\n if (event instanceof ControlOutput || event instanceof ControlExtendedOutput) {\n if (this.#paneId === undefined || event.paneId === this.#paneId) {\n return new PaneOutputChunk(event.paneId, event.data, event instanceof ControlExtendedOutput ? event.ageMs : undefined);\n }\n }\n }\n }\n}\nexport class PaneLineStream {\n #output;\n #buffer = [];\n #pending = [];\n constructor(output) {\n this.#output = output;\n }\n async close() {\n await this.#output.close();\n }\n async next(timeout) {\n const deadline = timeout === undefined ? undefined : deadlineFromNow(timeout);\n for (;;) {\n const pending = this.#pending.shift();\n if (pending !== undefined) {\n return pending;\n }\n const chunk = await this.#output.next(deadline === undefined ? undefined : { milliseconds: remainingMilliseconds(deadline) });\n this.feed(chunk.data);\n }\n }\n feed(data) {\n for (const byte of data) {\n if (byte === 0x0a) {\n let line = Buffer.from(this.#buffer);\n this.#buffer.length = 0;\n if (line.at(-1) === 0x0d) {\n line = line.subarray(0, -1);\n }\n this.#pending.push(line.toString(\"utf8\"));\n }\n else {\n this.#buffer.push(byte);\n }\n }\n }\n}\nexport class PaneRenderStream {\n #pane;\n #output;\n constructor(pane, output) {\n this.#pane = pane;\n this.#output = output;\n }\n static async open(pane) {\n return new PaneRenderStream(pane, await pane.outputStream());\n }\n async close() {\n await this.#output.close();\n }\n async next(timeout) {\n await this.#output.next(timeout);\n return this.#pane.snapshot();\n }\n}\n","export function requiredString(value, context, field) {\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n throw new TypeError(`${context} is missing non-empty string field ${JSON.stringify(field)}`);\n}\nexport function requiredInteger(value, context, field) {\n if (typeof value === \"number\" && Number.isInteger(value)) {\n return value;\n }\n throw new TypeError(`${context} is missing integer field ${JSON.stringify(field)}`);\n}\nexport function requiredPaneId(value, context) {\n const paneId = requiredString(value, context, \"pane_id\");\n if (/^%[0-9]+$/.test(paneId)) {\n return paneId;\n }\n throw new TypeError(`${context} has invalid pane_id ${JSON.stringify(paneId)}`);\n}\nexport function requiredSessionId(value, context) {\n const sessionId = requiredString(value, context, \"session_id\");\n if (/^\\$[0-9]+$/.test(sessionId)) {\n return sessionId;\n }\n throw new TypeError(`${context} has invalid session_id ${JSON.stringify(sessionId)}`);\n}\nexport function parseRequiredInteger(value, context) {\n if (/^-?[0-9]+$/.test(value)) {\n return Number.parseInt(value, 10);\n }\n throw new TypeError(`${context} is not an integer: ${JSON.stringify(value)}`);\n}\nexport function parsePaneId(value, context) {\n const paneId = value.trim();\n if (/^%[0-9]+$/.test(paneId)) {\n return paneId;\n }\n throw new TypeError(`${context} did not return a pane id: ${JSON.stringify(value)}`);\n}\nexport function parseWindowIndex(value, context) {\n const parsed = parseRequiredInteger(value.trim(), context);\n if (parsed < 0) {\n throw new TypeError(`${context} must be non-negative: ${JSON.stringify(value)}`);\n }\n return parsed;\n}\nexport function isJsonObject(value) {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { ensureServerCompatible } from \"../compatibility.js\";\nimport { deadlineExpired, deadlineFromNow, durationMilliseconds, sleep } from \"../duration.js\";\nimport { rowColumn, TextExpectation, TextMatch } from \"../expectations.js\";\nimport { PaneExitState } from \"../lifecycle.js\";\nimport { TextLocator } from \"../locators.js\";\nimport { PaneSnapshot } from \"../snapshot.js\";\nimport { PaneLineStream, PaneOutputStream, PaneRenderStream } from \"../streams.js\";\nimport { parsePaneId } from \"../validation.js\";\nexport class Pane {\n server;\n target;\n constructor(server, target) {\n this.server = server;\n this.target = target;\n }\n async sendKeys(...keys) {\n return this.server.sendKeys(this.target, ...keys);\n }\n async sendText(text) {\n return this.server.sendText(this.target, text);\n }\n async select() {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"select-pane\", \"-t\", this.target, { check: true });\n }\n async resize(options) {\n await ensureServerCompatible(this.server);\n const args = [\"resize-pane\", \"-t\", this.target];\n if (options.width !== undefined) {\n args.push(\"-x\", options.width);\n }\n if (options.height !== undefined) {\n args.push(\"-y\", options.height);\n }\n return this.server.cmd(...args, { check: true });\n }\n async split(options = {}) {\n await ensureServerCompatible(this.server);\n const direction = options.direction ?? \"vertical\";\n const args = [\n \"split-window\",\n \"-P\",\n \"-F\",\n \"#{pane_id}\",\n \"-t\",\n this.target,\n ];\n if (direction === \"horizontal\" || direction === \"h\") {\n args.push(\"-h\");\n }\n else if (direction === \"vertical\" || direction === \"v\") {\n args.push(\"-v\");\n }\n else {\n throw new Error(\"direction must be 'horizontal' or 'vertical'\");\n }\n if (options.size !== undefined) {\n args.push(\"-l\", options.size);\n }\n if (options.shellCommand !== undefined) {\n args.push(options.shellCommand);\n }\n const run = await this.server.cmd(...args, { check: true });\n return new Pane(this.server, parsePaneId(run.stdout, \"split-window output\"));\n }\n async respawn(options = {}) {\n await ensureServerCompatible(this.server);\n const args = [\"respawn-pane\", \"-t\", this.target];\n if (options.kill) {\n args.push(\"-k\");\n }\n if (options.shellCommand !== undefined) {\n args.push(options.shellCommand);\n }\n return this.server.cmd(...args, { check: true });\n }\n async close() {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"kill-pane\", \"-t\", this.target, { check: true });\n }\n async capture(options = {}) {\n return this.server.capturePane({ target: this.target, ...options });\n }\n async captureText(options = {}) {\n return (await this.snapshot(options)).visibleText;\n }\n async snapshot(options = {}) {\n return new PaneSnapshot(await this.capture(options));\n }\n getByText(text) {\n return new TextLocator(this, text);\n }\n locator(text) {\n return this.getByText(text);\n }\n async id() {\n await ensureServerCompatible(this.server);\n const run = await this.server.cmd(\"display-message\", \"-p\", \"-t\", this.target, \"#{pane_id}\", {\n check: true,\n });\n return parsePaneId(run.stdout, \"display-message #{pane_id}\");\n }\n async outputStream() {\n return PaneOutputStream.open(this);\n }\n async lineStream() {\n return new PaneLineStream(await this.outputStream());\n }\n async renderStream() {\n return PaneRenderStream.open(this);\n }\n async waitForText(text, options = {}) {\n return this.waitForTextInner(text, false, options.timeout ?? 5, options.interval ?? 0.05);\n }\n async waitForExactText(text, options = {}) {\n return this.waitForTextInner(text, true, options.timeout ?? 5, options.interval ?? 0.05);\n }\n expectVisibleText() {\n return new TextExpectation(this);\n }\n async waitForExit(options = {}) {\n const timeout = options.timeout ?? 5;\n const intervalMs = durationMilliseconds(options.interval ?? 0.05);\n const deadline = deadlineFromNow(timeout);\n for (;;) {\n const state = await this.exitState();\n if (state.dead) {\n return state;\n }\n if (deadlineExpired(deadline)) {\n throw new Error(`pane did not exit before timeout: ${this.target}`);\n }\n await sleep(intervalMs);\n }\n }\n async waitForTextInner(text, exact, timeout, interval) {\n const intervalMs = durationMilliseconds(interval);\n const deadline = deadlineFromNow(timeout);\n for (;;) {\n const captured = await this.captureText();\n if (exact) {\n if (captured.replace(/\\n+$/, \"\") === text) {\n const found = captured.indexOf(text);\n const [row, column] = rowColumn(captured, found < 0 ? 0 : found);\n return new TextMatch(text, row, column);\n }\n }\n else {\n const found = captured.indexOf(text);\n if (found >= 0) {\n const [row, column] = rowColumn(captured, found);\n return new TextMatch(text, row, column);\n }\n }\n if (deadlineExpired(deadline)) {\n throw new Error(`text not found before timeout: ${JSON.stringify(text)}`);\n }\n await sleep(intervalMs);\n }\n }\n async exitState() {\n await ensureServerCompatible(this.server);\n const run = await this.server.cmd(\"display-message\", \"-p\", \"-t\", this.target, \"#{pane_dead}:#{pane_dead_status}\", { check: true });\n const output = run.stdout.trim();\n const separator = output.indexOf(\":\");\n const dead = separator < 0 ? output : output.slice(0, separator);\n const status = separator < 0 ? \"\" : output.slice(separator + 1);\n if (dead !== \"1\" && dead !== \"true\") {\n return new PaneExitState(false);\n }\n return new PaneExitState(true, parseExitStatus(status));\n }\n}\nfunction parseExitStatus(value) {\n if (!/^[0-9]+$/.test(value)) {\n return undefined;\n }\n return Number.parseInt(value, 10);\n}\n","import { ensureServerCompatible } from \"../compatibility.js\";\nimport { requiredPaneId } from \"../validation.js\";\nimport { Pane } from \"./pane.js\";\nexport class Window {\n server;\n sessionName;\n sessionTarget;\n index;\n constructor(server, sessionName, sessionTarget, index) {\n this.server = server;\n this.sessionName = sessionName;\n this.sessionTarget = sessionTarget;\n this.index = index;\n }\n get target() {\n return `${this.sessionTarget}:${this.index}`;\n }\n async listPanes() {\n return this.server.listPanes({ target: this.target });\n }\n async panes() {\n const panes = [];\n for (const [index, pane] of (await this.listPanes()).entries()) {\n panes.push(new Pane(this.server, requiredPaneId(pane[\"pane_id\"], `list-panes row ${index}`)));\n }\n return panes;\n }\n pane(index) {\n return new Pane(this.server, `${this.target}.${index}`);\n }\n async select() {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"select-window\", \"-t\", this.target, { check: true });\n }\n async rename(name) {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"rename-window\", \"-t\", this.target, name, { check: true });\n }\n async resize(options) {\n await ensureServerCompatible(this.server);\n const args = [\"resize-window\", \"-t\", this.target];\n if (options.width !== undefined) {\n args.push(\"-x\", options.width);\n }\n if (options.height !== undefined) {\n args.push(\"-y\", options.height);\n }\n return this.server.cmd(...args, { check: true });\n }\n async selectLayout(layout) {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"select-layout\", \"-t\", this.target, layout, { check: true });\n }\n async close() {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"kill-window\", \"-t\", this.target, { check: true });\n }\n}\n","import { ensureServerCompatible } from \"../compatibility.js\";\nimport { parseWindowIndex, requiredInteger } from \"../validation.js\";\nimport { Window } from \"./window.js\";\nexport class Session {\n server;\n name;\n target;\n constructor(server, name, target = name) {\n this.server = server;\n this.name = name;\n this.target = target;\n }\n async listWindows() {\n return this.server.listWindows({ target: this.target });\n }\n async windows() {\n return (await this.listWindows()).map((window) => {\n return new Window(this.server, this.name, this.target, requiredInteger(window[\"window_index\"], \"list-windows row\", \"window_index\"));\n });\n }\n window(index) {\n return new Window(this.server, this.name, this.target, index);\n }\n pane(windowIndex = 0, paneIndex = 0) {\n return this.window(windowIndex).pane(paneIndex);\n }\n async rename(name) {\n await ensureServerCompatible(this.server);\n await this.server.cmd(\"rename-session\", \"-t\", this.target, name, { check: true });\n return new Session(this.server, name, this.target.startsWith(\"$\") ? this.target : name);\n }\n async kill() {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"kill-session\", \"-t\", this.target, { check: true });\n }\n async newWindow(options = {}) {\n await ensureServerCompatible(this.server);\n const args = [\n \"new-window\",\n \"-P\",\n \"-F\",\n \"#{window_index}\",\n \"-t\",\n this.target,\n ];\n if (options.detached ?? true) {\n args.push(\"-d\");\n }\n if (options.name !== undefined) {\n args.push(\"-n\", options.name);\n }\n if (options.shellCommand !== undefined) {\n args.push(options.shellCommand);\n }\n const run = await this.server.cmd(...args, { check: true });\n return new Window(this.server, this.name, this.target, parseWindowIndex(run.stdout, \"new-window output\"));\n }\n}\n","import { deadlineExpired, deadlineFromNow, durationMilliseconds, sleep } from \"./duration.js\";\nexport class PaneSetOutcome {\n matched;\n snapshots;\n constructor(matched, snapshots) {\n this.matched = [...matched];\n this.snapshots = [...snapshots];\n }\n}\nexport class PaneSet {\n panes;\n constructor(panes) {\n this.panes = [...panes];\n }\n get length() {\n return this.panes.length;\n }\n [Symbol.iterator]() {\n return this.panes[Symbol.iterator]();\n }\n isEmpty() {\n return this.panes.length === 0;\n }\n async broadcastText(text) {\n return Promise.all(this.panes.map((pane) => pane.sendText(text)));\n }\n async broadcastKey(key) {\n return Promise.all(this.panes.map((pane) => pane.sendKeys(key)));\n }\n async snapshotAll() {\n const snapshots = [];\n for (const pane of this.panes) {\n snapshots.push(await pane.snapshot());\n }\n return snapshots;\n }\n expectAll() {\n return new PaneSetExpectation(this, \"all\");\n }\n expectAny() {\n return new PaneSetExpectation(this, \"any\");\n }\n waitAll() {\n return this.expectAll();\n }\n waitAny() {\n return this.expectAny();\n }\n}\nexport class PaneSetExpectation {\n #paneSet;\n #mode;\n #text;\n #interval;\n constructor(paneSet, mode, options = {}) {\n this.#paneSet = paneSet;\n this.#mode = mode;\n this.#text = options.text;\n this.#interval = options.interval ?? 0.05;\n }\n visibleTextContains(text, options = {}) {\n return new PaneSetExpectation(this.#paneSet, this.#mode, {\n text,\n interval: options.interval ?? 0.05,\n });\n }\n async timeout(value) {\n if (this.#text === undefined) {\n throw new Error(\"choose an expectation before setting a timeout\");\n }\n const deadline = deadlineFromNow(value);\n const intervalMs = durationMilliseconds(this.#interval);\n for (;;) {\n const matched = [];\n const snapshots = [];\n for (const pane of this.#paneSet) {\n const snapshot = await pane.snapshot();\n if (snapshot.visibleText.includes(this.#text)) {\n matched.push(pane);\n snapshots.push(snapshot);\n }\n }\n if (this.#mode === \"all\" && matched.length === this.#paneSet.length) {\n return new PaneSetOutcome(matched, snapshots);\n }\n if (this.#mode === \"any\" && matched.length > 0) {\n return new PaneSetOutcome(matched, snapshots);\n }\n if (deadlineExpired(deadline)) {\n throw new Error(`pane set did not match visible text before timeout: ${JSON.stringify(this.#text)}`);\n }\n await sleep(intervalMs);\n }\n }\n}\n","import { Rmux } from \"./rmux.js\";\nexport class RmuxBuilder {\n #binary = \"rmux\";\n #socketPath;\n #socketName;\n #checkCompatibility = true;\n #env;\n #cwd;\n binary(value) {\n this.#binary = value;\n return this;\n }\n socketPath(value) {\n this.#socketPath = value;\n this.#socketName = undefined;\n return this;\n }\n socketName(value) {\n this.#socketName = value;\n this.#socketPath = undefined;\n return this;\n }\n checkCompatibility(enabled) {\n this.#checkCompatibility = enabled;\n return this;\n }\n env(value) {\n this.#env = value === undefined ? undefined : { ...value };\n return this;\n }\n cwd(value) {\n this.#cwd = value;\n return this;\n }\n async connectOrStart() {\n const rmux = new Rmux({\n binary: this.#binary,\n socketPath: this.#socketPath,\n socketName: this.#socketName,\n checkCompatibility: this.#checkCompatibility,\n env: this.#env,\n cwd: this.#cwd,\n });\n await rmux.startServer();\n if (this.#checkCompatibility) {\n await rmux.capabilities();\n }\n return rmux;\n }\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nexport class RmuxTraceBuilder {\n #maxEvents = 100_000;\n maxEvents(value) {\n if (!Number.isInteger(value) || value < 0) {\n throw new RangeError(\"maxEvents must be a non-negative integer\");\n }\n this.#maxEvents = value;\n return this;\n }\n start() {\n const trace = new TraceSession(this.#maxEvents);\n trace.record(\"trace.start\", {});\n return trace;\n }\n}\nexport class TraceSession {\n #maxEvents;\n #events = [];\n constructor(maxEvents) {\n this.#maxEvents = maxEvents;\n }\n recordAction(action) {\n this.record(\"action\", { action });\n }\n async recordSnapshot(pane) {\n const snapshot = await pane.snapshot();\n this.record(\"snapshot\", {\n pane: pane.target,\n visible_text: snapshot.visibleText,\n });\n }\n async stop(directory) {\n this.record(\"trace.stop\", {});\n await mkdir(directory, { recursive: true });\n const output = join(directory, \"trace.jsonl\");\n const content = this.#events.length === 0\n ? \"\"\n : this.#events.map((event) => JSON.stringify(event)).join(\"\\n\") + \"\\n\";\n await writeFile(output, content, \"utf8\");\n return output;\n }\n record(kind, payload) {\n const jsonPayload = copyJsonObject(payload, \"payload\");\n if (this.#maxEvents <= 0) {\n return;\n }\n if (this.#events.length === this.#maxEvents) {\n this.#events.shift();\n }\n this.#events.push({\n timestamp_ms: Date.now(),\n kind,\n payload: jsonPayload,\n });\n }\n}\nfunction copyJsonObject(value, path) {\n if (!isPlainObject(value)) {\n throw new TypeError(`${path} must be a JSON object`);\n }\n const copy = {};\n for (const [key, item] of Object.entries(value)) {\n copy[key] = copyJsonValue(item, `${path}.${key}`);\n }\n return copy;\n}\nfunction copyJsonValue(value, path) {\n if (value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new TypeError(`${path} must be a finite JSON number`);\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((item, index) => copyJsonValue(item, `${path}[${index}]`));\n }\n return copyJsonObject(value, path);\n}\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n","import { CommandRun } from \"./command.js\";\nimport { ControlModeClient, spawnControlProcess, waitForControlProcessSpawn, } from \"./control.js\";\nimport { RmuxCompatibilityError } from \"./errors.js\";\nimport { Session } from \"./handles/session.js\";\nimport { PaneSet } from \"./pane-set.js\";\nimport { runProcess } from \"./process.js\";\nimport { RmuxBuilder } from \"./builder.js\";\nimport { RmuxTraceBuilder } from \"./trace.js\";\nimport { isJsonObject, requiredSessionId, requiredString } from \"./validation.js\";\nexport const BINARY_CONTRACT_VERSION = 1;\nexport class Rmux {\n binary;\n socketPath;\n socketName;\n checkCompatibility;\n env;\n cwd;\n #capabilities;\n static builder() {\n return new RmuxBuilder();\n }\n constructor(options = {}) {\n if (options.socketPath !== undefined && options.socketName !== undefined) {\n throw new Error(\"choose only one of socketPath or socketName\");\n }\n this.binary = options.binary ?? \"rmux\";\n this.socketPath = options.socketPath;\n this.socketName = options.socketName;\n this.checkCompatibility = options.checkCompatibility ?? true;\n this.env = options.env === undefined ? undefined : { ...options.env };\n this.cwd = options.cwd;\n }\n async cmd(...argsAndOptions) {\n const { args, options } = splitCommandArguments(argsAndOptions);\n const argv = this.argv(args);\n const completed = await runProcess(argv, {\n cwd: this.cwd,\n env: this.env,\n });\n const run = new CommandRun(argv, completed.code, completed.stdout, completed.stderr, completed.signal);\n if (options.check) {\n run.checkReturnCode();\n }\n return run;\n }\n async capabilities() {\n if (this.#capabilities === undefined) {\n const capabilities = await this.jsonObject(\"capabilities\", \"--json\");\n if (this.checkCompatibility) {\n this.validateCapabilities(capabilities);\n }\n this.#capabilities = capabilities;\n }\n return { ...this.#capabilities };\n }\n async startServer() {\n return this.cmd(\"start-server\", { check: true });\n }\n async killServer(options = {}) {\n return this.cmd(\"kill-server\", { check: options.check ?? false });\n }\n async listSessions() {\n await this.ensureCompatible();\n return this.jsonList(\"list-sessions\", \"--json\");\n }\n async sessions() {\n return (await this.listSessions()).map((session, index) => {\n return this.sessionFromRow(session, `list-sessions row ${index}`);\n });\n }\n session(name) {\n return new Session(this, name);\n }\n async ensureSession(name, options = {}) {\n await this.ensureCompatible();\n const run = await this.cmd(\"has-session\", \"-t\", name);\n if (run.returnCode !== 0) {\n const args = [\"new-session\"];\n if (options.detached ?? true) {\n args.push(\"-d\");\n }\n args.push(\"-s\", name);\n if (options.shellCommand !== undefined) {\n args.push(options.shellCommand);\n }\n await this.cmd(...args, { check: true });\n }\n return this.sessionForTarget(name, name);\n }\n async listWindows(options = {}) {\n await this.ensureCompatible();\n const args = [\"list-windows\"];\n if (options.allSessions) {\n args.push(\"-a\");\n }\n if (options.target !== undefined) {\n args.push(\"-t\", options.target);\n }\n args.push(\"--json\");\n return this.jsonList(...args);\n }\n async listPanes(options = {}) {\n await this.ensureCompatible();\n const args = [\"list-panes\"];\n if (options.allSessions) {\n args.push(\"-a\");\n }\n if (options.target !== undefined) {\n args.push(\"-t\", options.target);\n }\n args.push(\"--json\");\n return this.jsonList(...args);\n }\n async listClients(options = {}) {\n await this.ensureCompatible();\n const args = [\"list-clients\"];\n if (options.targetSession !== undefined) {\n args.push(\"-t\", options.targetSession);\n }\n args.push(\"--json\");\n return this.jsonList(...args);\n }\n async sendKeys(target, ...keys) {\n await this.ensureCompatible();\n return this.cmd(\"send-keys\", \"-t\", target, ...keys, { check: true });\n }\n async sendText(target, text) {\n await this.ensureCompatible();\n return this.cmd(\"send-keys\", \"-t\", target, \"-l\", text, { check: true });\n }\n async displayMessage(message, options = {}) {\n await this.ensureCompatible();\n const args = [\"display-message\", \"--json\"];\n if (options.target !== undefined) {\n args.push(\"-t\", options.target);\n }\n args.push(message);\n return this.jsonObject(...args);\n }\n async capturePane(options = {}) {\n await this.ensureCompatible();\n const args = [\"capture-pane\", \"-p\"];\n if (options.target !== undefined) {\n args.push(\"-t\", options.target);\n }\n if (options.start !== undefined) {\n args.push(\"-S\", options.start);\n }\n if (options.end !== undefined) {\n args.push(\"-E\", options.end);\n }\n if (options.escapeAnsi) {\n args.push(\"-e\");\n }\n if (options.joinWrapped) {\n args.push(\"-J\");\n }\n return (await this.cmd(...args, { check: true })).stdout;\n }\n async controlMode() {\n await this.ensureCompatible();\n const process = spawnControlProcess({\n binary: this.binary,\n args: this.endpointArgs([\"-C\"]),\n cwd: this.cwd,\n env: this.env,\n });\n await waitForControlProcessSpawn(process);\n return process;\n }\n async control() {\n return new ControlModeClient(await this.controlMode());\n }\n paneSet(panes) {\n return new PaneSet(panes);\n }\n async broadcastText(panes, text) {\n return this.paneSet(panes).broadcastText(text);\n }\n async broadcastKey(panes, key) {\n return this.paneSet(panes).broadcastKey(key);\n }\n tracing() {\n return new RmuxTraceBuilder();\n }\n async jsonList(...args) {\n const value = await this.jsonValue(...args);\n if (!Array.isArray(value)) {\n throw new TypeError(\"rmux JSON response is not an array\");\n }\n return value.map((item) => {\n if (!isJsonObject(item)) {\n throw new TypeError(\"rmux JSON array contains a non-object item\");\n }\n return item;\n });\n }\n async jsonObject(...args) {\n const value = await this.jsonValue(...args);\n if (!isJsonObject(value)) {\n throw new TypeError(\"rmux JSON response is not an object\");\n }\n return value;\n }\n async jsonValue(...args) {\n const run = await this.cmd(...args, { check: true });\n try {\n return JSON.parse(run.stdout);\n }\n catch (error) {\n throw new TypeError(`rmux returned invalid JSON for ${args.map(String).join(\" \")}: ${errorMessage(error)}`);\n }\n }\n async ensureCompatible() {\n if (this.checkCompatibility) {\n await this.capabilities();\n }\n }\n async sessionForTarget(target, fallbackName) {\n const idMessage = await this.displayMessage(\"#{session_id}\", { target });\n const sessionId = requiredSessionId(idMessage[\"message\"], `display-message #{session_id} for ${JSON.stringify(target)}`);\n const row = (await this.listSessions()).find((session) => {\n return session[\"session_id\"] === sessionId;\n });\n if (row !== undefined) {\n return this.sessionFromRow(row, `session ${sessionId}`);\n }\n return new Session(this, fallbackName, sessionId);\n }\n sessionFromRow(session, context) {\n return new Session(this, requiredString(session[\"session_name\"], context, \"session_name\"), requiredSessionId(session[\"session_id\"], context));\n }\n validateCapabilities(capabilities) {\n const version = capabilities[\"binary_contract_version\"];\n if (version !== BINARY_CONTRACT_VERSION) {\n throw new RmuxCompatibilityError(`unsupported rmux binary contract version ${JSON.stringify(version)}; expected ${BINARY_CONTRACT_VERSION}`);\n }\n const commands = capabilities[\"json_commands\"];\n const requiredCommands = [\n \"capabilities\",\n \"display-message\",\n \"list-clients\",\n \"list-panes\",\n \"list-sessions\",\n \"list-windows\",\n ];\n if (!Array.isArray(commands) ||\n !requiredCommands.every((command) => commands.includes(command))) {\n throw new RmuxCompatibilityError(\"rmux binary does not advertise required JSON commands\");\n }\n const publicContract = capabilities[\"public_contract\"];\n if (!Array.isArray(publicContract) || !publicContract.includes(\"control-mode\")) {\n throw new RmuxCompatibilityError(\"rmux binary does not advertise control-mode\");\n }\n }\n argv(args) {\n return [this.binary, ...this.endpointArgs(args)];\n }\n endpointArgs(args) {\n const argv = [];\n if (this.socketName !== undefined) {\n argv.push(\"-L\", this.socketName);\n }\n if (this.socketPath !== undefined) {\n argv.push(\"-S\", this.socketPath);\n }\n argv.push(...args.map(String));\n return argv;\n }\n}\nfunction splitCommandArguments(values) {\n const last = values.at(-1);\n if (isCommandOptionsCandidate(last)) {\n return {\n args: values.slice(0, -1),\n options: parseCommandOptions(last),\n };\n }\n return {\n args: values,\n options: {},\n };\n}\nfunction isCommandOptionsCandidate(value) {\n if (!isJsonObject(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\nfunction parseCommandOptions(value) {\n for (const key of Object.keys(value)) {\n if (key !== \"check\") {\n throw new TypeError(`unknown rmux command option: ${key}`);\n }\n }\n if (value[\"check\"] !== undefined && typeof value[\"check\"] !== \"boolean\") {\n throw new TypeError(\"rmux command option check must be a boolean\");\n }\n return value[\"check\"] === undefined ? {} : { check: value[\"check\"] };\n}\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Terminal hosting for workflow runs through RMUX.\n *\n * DESIGN PATTERNS:\n * - RMUX owns the pseudo terminal, screen state, input, and process lifetime\n * - Platform payloads are optional and resolved at runtime, with PATH fallback\n * - The existing NativeTerminalService API remains stable for consumers\n *\n * CODING STANDARDS:\n * - Named exports only\n * - Explicit return types on exported members\n * - No top-level import of a platform payload package\n */\n\nimport { spawn } from 'node:child_process';\nimport fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\n\nimport { CommandRun, RMUX } from '@rmux/sdk';\n\nimport type {\n NativeTerminalDependencies,\n NativeTerminalSpawnInput,\n NativeTerminalViewer,\n RmuxTerminalClient,\n RmuxTerminalPane,\n} from '../NativeTerminalService/types';\nimport type { WorkflowHostOptions } from './type';\n\nconst EXECUTABLE_MODE = 0o755;\nconst EXECUTABLE_BITS = 0o111;\nconst VENDOR_DIRECTORY = 'vendor';\nconst FALLBACK_COLUMNS = 120;\nconst FALLBACK_ROWS = 40;\nconst PANE_PID_FORMAT = '#{pane_pid}';\nconst PANE_STATE_FORMAT = '#{pane_dead}:#{pane_dead_status}';\nconst POLL_MS = 100;\nconst RMUX_BINARY_ENV = 'AGIMON_RMUX_BINARY';\nconst RMUX_SOCKET_NAME = 'agimon-workflow-mcp';\nconst ENV_COMMAND = '/usr/bin/env';\n// Waits for the gate, loads the run's environment and deletes it, then becomes the command.\nconst GATE_SCRIPT = 'while [ ! -e \"$1\" ]; do sleep 0.01; done; . \"$2\"; rm -f \"$2\"; shift 2; exec \"$@\"';\nconst ENVIRONMENT_FILE = 'environment';\nconst PRIVATE_FILE_MODE = 0o600;\n/** Names a POSIX shell can export; any other name stays on the env command line. */\nconst SHELL_VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst TERMINAL_ENV = { TERM: 'xterm-256color', COLORTERM: 'truecolor' } as const;\n\nconst PACKAGE_BY_PLATFORM: Readonly<Record<string, string>> = {\n 'darwin-arm64': '@agimon-ai/rmux-darwin-arm64',\n 'darwin-x64': '@agimon-ai/rmux-darwin-x64',\n 'linux-arm64': '@agimon-ai/rmux-linux-arm64',\n 'linux-x64': '@agimon-ai/rmux-linux-x64',\n};\n\nconst requirePackage = createRequire(import.meta.url);\n\ninterface HostedRun {\n pane: RmuxTerminalPane;\n sessionName: string;\n exited: boolean;\n exitCode?: number;\n viewers: Set<object>;\n ended: Promise<number>;\n}\n\nfunction defaultGeometry(): { columns: number; rows: number } {\n return {\n columns: process.stdout.columns || FALLBACK_COLUMNS,\n rows: process.stdout.rows || FALLBACK_ROWS,\n };\n}\n\nfunction bundledBinary(): string | undefined {\n const packageName = PACKAGE_BY_PLATFORM[`${process.platform}-${process.arch}`];\n if (!packageName) return undefined;\n try {\n const manifest = requirePackage.resolve(`${packageName}/package.json`);\n return path.join(path.dirname(manifest), VENDOR_DIRECTORY, 'bin', 'rmux');\n } catch {\n return undefined;\n }\n}\n\n/**\n * Make the bundled payload runnable before RMUX is asked for anything.\n *\n * The prebuilt packages reach npm with plain 0644 files. Restoring the\n * executable bit on the launcher alone is not enough: rmux execs\n * `bin/rmux-daemon` and `libexec/rmux/rmux` itself and fails on the first with\n * a permission error, so every file the vendor tree ships is restored. A\n * stand-alone override outside a vendor tree only gets itself restored, and a\n * file that is already executable is left alone, since chmod on a binary\n * someone else owns would throw and drop a usable candidate.\n */\nexport function ensureExecutablePayload(binary: string): void {\n const vendor = path.resolve(path.dirname(binary), '..');\n const payload =\n path.basename(vendor) === VENDOR_DIRECTORY\n ? fs\n .readdirSync(vendor, { recursive: true, withFileTypes: true })\n .filter((entry) => entry.isFile())\n .map((entry) => path.join(entry.parentPath, entry.name))\n : [binary];\n for (const file of payload) {\n if ((fs.statSync(file).mode & EXECUTABLE_BITS) === 0) fs.chmodSync(file, EXECUTABLE_MODE);\n }\n}\n\nasync function createDefaultClient(options: WorkflowHostOptions): Promise<RmuxTerminalClient | undefined> {\n const candidates = [options.environment[RMUX_BINARY_ENV], bundledBinary(), 'rmux'].filter(\n (candidate): candidate is string => Boolean(candidate),\n );\n for (const binary of candidates) {\n try {\n if (binary !== 'rmux') ensureExecutablePayload(binary);\n const environment = Object.fromEntries(\n Object.entries(options.environment).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n const client = new RMUX({ binary, socketName: RMUX_SOCKET_NAME, cwd: options.cwd, env: environment });\n // The SDK's default command runner merges process.env. Keep its handles and\n // compatibility checks, but run each command with the admitted environment.\n client.cmd = async (...arguments_) => {\n const last = arguments_.at(-1);\n const check = typeof last === 'object' ? last.check === true : false;\n const args = (typeof last === 'object' ? arguments_.slice(0, -1) : arguments_).map(String);\n const argv = ['-L', RMUX_SOCKET_NAME, ...args];\n const completed = await runRmux(binary, argv, options.cwd, environment);\n const run = new CommandRun([binary, ...argv], completed.code, completed.stdout, completed.stderr);\n return check ? run.checkReturnCode() : run;\n };\n await client.capabilities();\n return client;\n } catch {\n continue;\n }\n }\n return undefined;\n}\n\n/** Single-quotes a value for POSIX sh, which keeps newlines and every other byte literal. */\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\n/**\n * The run's environment, split into a script the pane sources and the few\n * assignments a shell cannot export.\n *\n * Passing the whole environment as arguments to RMUX's new-session breaks once\n * a host adds its own variables: RMUX refuses the command as too long. It also\n * puts every value, secrets included, into the process table. The script is\n * written to the run's private gate directory instead and deleted as soon as\n * the pane has read it.\n */\nfunction environmentScript(env: Record<string, string>): { script: string; unexportable: string[] } {\n const entries = Object.entries({ ...env, ...TERMINAL_ENV }).sort(([left], [right]) => left.localeCompare(right));\n const exported = entries.filter(([name]) => SHELL_VARIABLE_NAME.test(name));\n return {\n script: exported.map(([name, value]) => `export ${name}=${shellQuote(value)}\\n`).join(''),\n unexportable: entries\n .filter(([name]) => !SHELL_VARIABLE_NAME.test(name))\n .map(([name, value]) => `${name}=${value}`),\n };\n}\n\nfunction panePid(stdout: string): number {\n const pid = Number(stdout.trim());\n if (!Number.isInteger(pid) || pid <= 0)\n throw new Error(`RMUX returned an invalid pane pid: ${JSON.stringify(stdout)}`);\n return pid;\n}\n\nfunction delay(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\nasync function waitForRunEnd(client: RmuxTerminalClient, target: string): Promise<number> {\n for (;;) {\n const result = await client.cmd('display-message', '-p', '-t', target, PANE_STATE_FORMAT, { check: true });\n const [dead, status] = result.stdout.trim().split(':', 2);\n if (dead === '1') {\n const code = Number(status || 0);\n return Number.isInteger(code) ? code : 0;\n }\n await delay(POLL_MS);\n }\n}\n\nfunction screenLines(screen: string): string[] {\n const lines = screen.split('\\n');\n while (lines.length > 0 && lines.at(-1)?.trim() === '') lines.pop();\n return lines;\n}\n\n/**\n * Hosts workflow runs in RMUX while preserving the package's existing terminal\n * socket contract for callers in another process.\n */\nexport class NativeTerminalService {\n private readonly runs = new Map<string, HostedRun>();\n private clientPromise?: Promise<RmuxTerminalClient | undefined>;\n\n constructor(\n private readonly options: WorkflowHostOptions,\n private readonly dependencies: NativeTerminalDependencies = {},\n ) {}\n\n private client(): Promise<RmuxTerminalClient | undefined> {\n this.clientPromise ??= this.dependencies.createClient?.() ?? createDefaultClient(this.options);\n return this.clientPromise;\n }\n\n async available(): Promise<boolean> {\n return Boolean(await this.client());\n }\n\n async spawn(input: NativeTerminalSpawnInput): Promise<{ pid: number }> {\n const client = await this.client();\n if (!client) throw new Error('Terminal hosting is unavailable: RMUX did not load.');\n\n const { columns, rows } = defaultGeometry();\n if (!this.options.temporaryDirectory)\n throw new Error('Native workflow terminals require an admitted temporary directory.');\n const gateDirectory = fs.mkdtempSync(path.join(this.options.temporaryDirectory, 'workflow-mcp-rmux-'));\n const gate = path.join(gateDirectory, 'start');\n const environmentFile = path.join(gateDirectory, ENVIRONMENT_FILE);\n const environment = environmentScript(input.env);\n let created = false;\n let released = false;\n try {\n fs.writeFileSync(environmentFile, environment.script, { mode: PRIVATE_FILE_MODE });\n const opened = await client.cmd(\n 'new-session',\n '-d',\n '-P',\n '-F',\n PANE_PID_FORMAT,\n '-s',\n input.runKey,\n '-c',\n input.cwd,\n '-x',\n columns,\n '-y',\n rows,\n '/usr/bin/env',\n '-i',\n '/bin/sh',\n '-c',\n GATE_SCRIPT,\n 'workflow-mcp-gate',\n gate,\n environmentFile,\n ENV_COMMAND,\n ...environment.unexportable,\n input.command,\n ...input.args,\n { check: true },\n );\n created = true;\n const pid = panePid(opened.stdout);\n await client.cmd('set-option', '-t', input.runKey, 'remain-on-exit', 'on', { check: true });\n const pane = client.session(input.runKey).pane(0, 0);\n const hosted: HostedRun = {\n pane,\n sessionName: input.runKey,\n exited: false,\n viewers: new Set(),\n ended: Promise.resolve(0),\n };\n hosted.ended = waitForRunEnd(client, input.runKey)\n .then((code) => {\n hosted.exited = true;\n hosted.exitCode = code;\n return code;\n })\n .finally(() => fs.rmSync(gateDirectory, { recursive: true, force: true }));\n fs.writeFileSync(gate, '', { mode: 0o600 });\n released = true;\n this.runs.set(input.runKey, hosted);\n return { pid };\n } catch (error) {\n if (created)\n await client\n .session(input.runKey)\n .kill()\n .catch(() => undefined);\n throw error;\n } finally {\n if (!released) fs.rmSync(gateDirectory, { recursive: true, force: true });\n }\n }\n\n isHosted(runKey: string): boolean {\n return this.runs.has(runKey);\n }\n\n exitOf(runKey: string): { exited: boolean; exitCode?: number } | undefined {\n const hosted = this.runs.get(runKey);\n if (!hosted) return undefined;\n return { exited: hosted.exited, ...(hosted.exitCode === undefined ? {} : { exitCode: hosted.exitCode }) };\n }\n\n ended(runKey: string): Promise<number> {\n return this.runs.get(runKey)?.ended ?? Promise.resolve(0);\n }\n\n viewerCount(runKey: string): number {\n return this.runs.get(runKey)?.viewers.size ?? 0;\n }\n\n async attach(runKey: string, columns: number, rows: number): Promise<NativeTerminalViewer> {\n const hosted = this.runs.get(runKey);\n if (!hosted) throw new Error(`No RMUX-hosted workflow run matches ${JSON.stringify(runKey)}.`);\n\n const viewer = {};\n hosted.viewers.add(viewer);\n await hosted.pane.resize({ width: columns, height: rows });\n\n return {\n snapshot: async () => screenLines(await hosted.pane.captureText()),\n resize: async (nextColumns, nextRows) => {\n await hosted.pane.resize({ width: nextColumns, height: nextRows });\n },\n write: async (data) => {\n if (!hosted.exited) await hosted.pane.sendText(data);\n },\n detach: () => {\n hosted.viewers.delete(viewer);\n },\n };\n }\n\n async kill(runKey: string): Promise<void> {\n const hosted = this.runs.get(runKey);\n if (!hosted) return;\n const client = await this.client();\n await client?.session(hosted.sessionName).kill();\n hosted.viewers.clear();\n this.runs.delete(runKey);\n }\n\n async disposeAll(): Promise<void> {\n await Promise.all([...this.runs.keys()].map((runKey) => this.kill(runKey)));\n }\n}\n\nasync function runRmux(\n binary: string,\n args: string[],\n cwd: string,\n env: Record<string, string>,\n): Promise<{ code: number; stdout: string; stderr: string }> {\n return await new Promise((resolve, reject) => {\n const child = spawn(binary, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n child.stderr.on('data', (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n child.once('error', reject);\n child.once('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));\n });\n}\n","/**\n * An RMUX-hosted run, reachable through the existing native-launcher socket.\n *\n * WHY A SOCKET:\n * The run record's `native` discriminator predates RMUX and points callers at\n * this transport. Keeping that contract avoids teaching every cockpit process\n * how to discover the private RMUX server and target.\n *\n * DESIGN PATTERNS:\n * - One line of JSON per request and per answer. A screen is a list of strings\n * and a keystroke is a string, so nothing here earns a framing format\n * - One viewer per socket server, shared by its clients. RMUX owns screen state,\n * so requests capture the pane without allocating an emulator\n * - The client connects per request. A unix socket connect costs a fraction of\n * a millisecond, and a stateless client cannot leak a connection or need\n * reconnect logic when a host restarts\n *\n * CODING STANDARDS:\n * - Named exports only\n * - Explicit return types on exported members\n *\n * AVOID:\n * - Putting the socket inside the run directory: a run directory path is\n * already close to the 104 byte limit macOS puts on a unix socket path\n */\n\nimport { createHash } from 'node:crypto';\nimport { mkdirSync, rmSync } from 'node:fs';\nimport { createConnection, createServer, type Server } from 'node:net';\nimport { join } from 'node:path';\n\nimport type { WorkflowNativeTerminal as NativeTerminalService } from '../NativeTerminalService/types';\nimport type { NativeTerminalViewer } from '../NativeTerminalService/types';\n\nconst SOCKET_DIR_NAME = 'workflow-mcp-terminals';\nconst SOCKET_EXTENSION = '.sock';\nconst HASH_LENGTH = 24;\nconst REQUEST_TIMEOUT_MS = 2_000;\n/** Geometry a reader gets before it has said how much room it has. */\nconst DEFAULT_COLUMNS = 120;\nconst DEFAULT_ROWS = 40;\n\nexport type TerminalSocketOp = 'snapshot' | 'write' | 'resize';\n\nexport interface TerminalSocketRequest {\n op: TerminalSocketOp;\n data?: string;\n columns?: number;\n rows?: number;\n}\n\nexport interface TerminalSocketResponse {\n ok: boolean;\n lines?: string[];\n error?: string;\n}\n\n/**\n * Where one run's socket lives.\n *\n * Hashed and under the temp directory because the obvious home, the run's own\n * directory, is far past what a unix socket path may be: a workspace and a run\n * key nested under the registry root routinely exceed 104 bytes, and binding\n * fails with a message that names neither.\n */\nexport function terminalSocketPath(workspace: string, runKey: string, root: string): string {\n const digest = createHash('sha256').update(`${workspace}/${runKey}`).digest('hex').slice(0, HASH_LENGTH);\n return join(root, SOCKET_DIR_NAME, `${digest}${SOCKET_EXTENSION}`);\n}\n\nexport interface ServeTerminalOptions {\n service: NativeTerminalService;\n runKey: string;\n socketPath: string;\n onNotice?: (message: string) => void;\n}\n\nexport interface TerminalSocketServer {\n close(): Promise<void>;\n}\n\n/**\n * Serves one hosted run on a unix socket.\n *\n * The viewer is created on the first request rather than at bind time: a run\n * nobody ever opens should cost a socket file and nothing else.\n */\nexport async function serveNativeTerminal(options: ServeTerminalOptions): Promise<TerminalSocketServer> {\n const notice = options.onNotice ?? ((): void => {});\n let viewer: NativeTerminalViewer | undefined;\n\n const answer = async (request: TerminalSocketRequest): Promise<TerminalSocketResponse> => {\n if (viewer === undefined) {\n viewer = await options.service.attach(\n options.runKey,\n request.columns ?? DEFAULT_COLUMNS,\n request.rows ?? DEFAULT_ROWS,\n );\n }\n if (request.op === 'write') {\n await viewer.write(request.data ?? '');\n return { ok: true };\n }\n if (request.op === 'resize') {\n await viewer.resize(request.columns ?? DEFAULT_COLUMNS, request.rows ?? DEFAULT_ROWS);\n return { ok: true };\n }\n if (request.columns !== undefined && request.rows !== undefined) {\n await viewer.resize(request.columns, request.rows);\n }\n return { ok: true, lines: await viewer.snapshot() };\n };\n\n const server = createServer((socket) => {\n let buffered = '';\n socket.on('data', (chunk: Buffer) => {\n buffered += chunk.toString();\n let newline = buffered.indexOf('\\n');\n while (newline !== -1) {\n const line = buffered.slice(0, newline);\n buffered = buffered.slice(newline + 1);\n void handle(line);\n newline = buffered.indexOf('\\n');\n }\n });\n // A reader that goes away mid-request is ordinary; the run does not care.\n socket.on('error', () => socket.destroy());\n\n const handle = async (line: string): Promise<void> => {\n let response: TerminalSocketResponse;\n try {\n response = await answer(JSON.parse(line) as TerminalSocketRequest);\n } catch (error) {\n response = { ok: false, error: error instanceof Error ? error.message : String(error) };\n }\n if (socket.writable) socket.write(`${JSON.stringify(response)}\\n`);\n };\n });\n\n mkdirSync(join(options.socketPath, '..'), { recursive: true });\n // A socket left by a host that died would refuse the bind; nothing else owns\n // this path, since it is derived from the run's identity.\n rmSync(options.socketPath, { force: true });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(options.socketPath, () => {\n server.removeListener('error', reject);\n resolve();\n });\n });\n server.on('error', (error) => notice(`terminal socket for ${options.runKey}: ${error.message}`));\n\n return {\n close: () =>\n new Promise<void>((resolve) => {\n viewer?.detach();\n viewer = undefined;\n closeServer(server, options.socketPath, resolve);\n }),\n };\n}\n\nfunction closeServer(server: Server, socketPath: string, done: () => void): void {\n server.close(() => {\n rmSync(socketPath, { force: true });\n done();\n });\n}\n\n/** One request over a fresh connection, or a rejection naming what went wrong. */\nfunction request(socketPath: string, body: TerminalSocketRequest): Promise<TerminalSocketResponse> {\n return new Promise((resolve, reject) => {\n const socket = createConnection(socketPath);\n let buffered = '';\n const finish = (error?: Error, response?: TerminalSocketResponse): void => {\n socket.destroy();\n if (error) reject(error);\n else if (response) resolve(response);\n };\n const timer = setTimeout(\n () => finish(new Error(`The run's terminal did not answer within ${REQUEST_TIMEOUT_MS}ms.`)),\n REQUEST_TIMEOUT_MS,\n );\n timer.unref?.();\n socket.on('connect', () => socket.write(`${JSON.stringify(body)}\\n`));\n socket.on('data', (chunk: Buffer) => {\n buffered += chunk.toString();\n const newline = buffered.indexOf('\\n');\n if (newline === -1) return;\n clearTimeout(timer);\n try {\n finish(undefined, JSON.parse(buffered.slice(0, newline)) as TerminalSocketResponse);\n } catch (error) {\n finish(error instanceof Error ? error : new Error(String(error)));\n }\n });\n socket.on('error', (error) => {\n clearTimeout(timer);\n finish(error);\n });\n });\n}\n\n/**\n * The reader's half: a bridge over one run's socket, shaped for the terminal\n * facade so a natively hosted run reads like any other launcher.\n */\nexport function connectNativeTerminal(): {\n snapshot(socketPath: string, options: { lines?: number }): Promise<string[]>;\n write(socketPath: string, data: string): Promise<void>;\n resize(socketPath: string, columns: number, rows: number): Promise<void>;\n} {\n return {\n async snapshot(socketPath, options) {\n const response = await request(socketPath, { op: 'snapshot' });\n if (!response.ok) throw new Error(response.error ?? 'The run refused to answer.');\n const lines = response.lines ?? [];\n return options.lines === undefined ? lines : lines.slice(-options.lines);\n },\n async write(socketPath, data) {\n const response = await request(socketPath, { op: 'write', data });\n if (!response.ok) throw new Error(response.error ?? 'The run refused the keystrokes.');\n },\n async resize(socketPath, columns, rows) {\n const response = await request(socketPath, { op: 'resize', columns, rows });\n if (!response.ok) throw new Error(response.error ?? 'The run refused the resize.');\n },\n };\n}\n","import { execFileSync, spawn } from 'node:child_process';\nimport { constants } from 'node:fs';\nimport { chmod, link, open, writeFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport { createInterface } from 'node:readline';\n\nimport { lock } from 'proper-lockfile';\n\nimport { NativeTerminalService } from './nativeTerminal';\nimport { serveNativeTerminal, connectNativeTerminal } from './terminalSocket';\nimport type { WorkflowArtifactFile, WorkflowHost, WorkflowHostOptions } from './type';\n\nexport { PO_WORKFLOW_HOST_SERVICE, requirePoWorkflowHost } from './contract';\n\nexport function resolveWorkflowCliPath(): string {\n const manifest = createRequire(import.meta.url).resolve('@agimon-ai/po-workflow/package.json');\n return join(dirname(manifest), 'dist', 'cli.cjs');\n}\n\nexport function readWorkflowPackageVersion(): string {\n return (createRequire(import.meta.url)('@agimon-ai/po-workflow/package.json') as { version: string }).version;\n}\n\n/** Node implementation of the exceptional native workflow operations. */\nexport function createWorkflowHost(options: WorkflowHostOptions): WorkflowHost {\n options = { ...options, environment: Object.freeze({ ...options.environment }) };\n return Object.freeze<WorkflowHost>({\n processId: process.pid,\n executablePath: process.execPath,\n platform: process.platform,\n isElectron: Boolean(process.versions.electron),\n writeStdout: (text) => {\n process.stdout.write(text);\n },\n writeStderr: (text) => {\n process.stderr.write(text);\n },\n onSignal: (signal, listener) => {\n process.on(signal, listener);\n return () => {\n process.off(signal, listener);\n };\n },\n cliPath: options.cliPath,\n portRegistry: {\n reservePort: (request) => registryOperation(options, 'reservePort', request),\n releasePort: (request) => registryOperation(options, 'releasePort', request),\n },\n processRegistry: {\n registerProcess: (request) => registryOperation(options, 'registerProcess', request),\n releaseProcess: (request) => registryOperation(options, 'releaseProcess', request),\n },\n createTerminal: (dependencies) => new NativeTerminalService(options, dependencies),\n serveTerminal: serveNativeTerminal,\n connectTerminal: connectNativeTerminal,\n createPrompt: () => createInterface({ input: process.stdin, output: process.stdout }),\n openArtifact,\n writeExclusive: (path: string, content: string | Uint8Array) =>\n writeFile(path, content, { flag: 'wx', mode: 0o600 }),\n publishExclusive: (source: string, destination: string) => link(source, destination),\n acquireRecoveryLock: (path: string, lockOptions: Parameters<typeof lock>[1]) => lock(path, lockOptions),\n setMode: (path: string, mode: number) => chmod(path, mode),\n spawn: (command: string, args: readonly string[], spawnOptions: Parameters<WorkflowHost['spawn']>[2]) =>\n spawn(command, [...args], spawnOptions),\n signal: (processId: number, signal: NodeJS.Signals | 0) => process.kill(processId, signal),\n inspectProcesses: (columns: 'command' | 'parents' | 'groups', processId?: number) => {\n const args =\n columns === 'command'\n ? ['-p', String(processId), '-o', 'command=']\n : ['-axo', columns === 'parents' ? 'pid=,ppid=' : 'pid=,pgid='];\n return execFileSync('ps', args, {\n cwd: options.cwd,\n env: options.environment,\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n },\n readTerminalState: () => {\n try {\n return execFileSync('stty', ['-g'], {\n cwd: options.cwd,\n env: options.environment,\n encoding: 'utf-8',\n stdio: ['inherit', 'pipe', 'ignore'],\n }).trim();\n } catch {\n return undefined;\n }\n },\n restoreTerminalState: (state?: string) => {\n if (state)\n execFileSync('stty', [state], {\n cwd: options.cwd,\n env: options.environment,\n stdio: ['inherit', 'ignore', 'ignore'],\n });\n if (process.stdout.isTTY) process.stdout.write('\\x1b[0m\\x1b[?25h\\x1b[?1049l');\n },\n });\n}\n\nasync function openArtifact(path: string): Promise<WorkflowArtifactFile | undefined> {\n let file: Awaited<ReturnType<typeof open>>;\n try {\n file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n } catch (error) {\n if (\n error instanceof Error &&\n 'code' in error &&\n ['ENOENT', 'ENOTDIR', 'ELOOP', 'EACCES', 'EPERM'].includes(String(error.code))\n )\n return undefined;\n throw error;\n }\n let closed = false;\n const close = async (): Promise<void> => {\n if (closed) return;\n closed = true;\n await file.close();\n };\n try {\n const snapshot = await file.stat();\n if (!snapshot.isFile()) {\n await close();\n return undefined;\n }\n const identity = (stat: typeof snapshot): string =>\n `\"${stat.dev}-${stat.ino}-${stat.size}-${stat.mtimeMs}-${stat.ctimeMs}\"`;\n const version = identity(snapshot);\n const unchanged = async (): Promise<boolean> => !closed && identity(await file.stat()) === version;\n const readRange = async (start: number, end: number): Promise<Uint8Array | undefined> => {\n if (\n !Number.isSafeInteger(start) ||\n !Number.isSafeInteger(end) ||\n start < 0 ||\n end < start ||\n end >= snapshot.size\n )\n return undefined;\n if (!(await unchanged())) return undefined;\n const bytes = new Uint8Array(end - start + 1);\n let offset = 0;\n while (offset < bytes.length) {\n const read = await file.read(bytes, offset, bytes.length - offset, start + offset);\n if (read.bytesRead === 0) return undefined;\n offset += read.bytesRead;\n }\n return (await unchanged()) ? bytes : undefined;\n };\n return {\n size: snapshot.size,\n modifiedAt: snapshot.mtime.toUTCString(),\n version,\n readRange,\n stream: (start, end) => {\n let position = start;\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n if (position > end) {\n if (!(await unchanged())) throw new Error('Workflow artifact changed while streaming.');\n await close();\n controller.close();\n return;\n }\n const next = Math.min(end, position + 65_536 - 1);\n const bytes = await readRange(position, next);\n if (bytes === undefined) throw new Error('Workflow artifact changed while streaming.');\n position = next + 1;\n controller.enqueue(bytes);\n } catch (error) {\n await close();\n controller.error(error);\n }\n },\n cancel: close,\n });\n },\n close,\n };\n } catch (error) {\n await close();\n throw error;\n }\n}\n\n/** Foundation registries admit process environment internally, so isolate that admission per invocation. */\nasync function registryOperation<T>(\n options: WorkflowHostOptions,\n operation: 'reservePort' | 'releasePort' | 'registerProcess' | 'releaseProcess',\n request: unknown,\n): Promise<T> {\n const requirePackage = createRequire(import.meta.url);\n const portModule = requirePackage.resolve('@agimon-ai/foundation-port-registry');\n const processModule = requirePackage.resolve('@agimon-ai/foundation-process-registry');\n const source = `\n const { PortRegistryService } = require(${JSON.stringify(portModule)});\n const { ProcessRegistryService } = require(${JSON.stringify(processModule)});\n let input = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', chunk => { input += chunk; });\n process.stdin.on('end', async () => {\n try {\n const { operation, request, portRegistryPath, processRegistryPath } = JSON.parse(input);\n const ports = new PortRegistryService(portRegistryPath);\n const processes = new ProcessRegistryService(processRegistryPath);\n const registry = operation === 'reservePort' || operation === 'releasePort' ? ports : processes;\n const result = await registry[operation](request);\n process.stdout.write(JSON.stringify(result));\n } catch (error) { console.error(error); process.exitCode = 1; }\n });\n `;\n return await new Promise<T>((resolve, reject) => {\n const child = spawn(process.execPath, ['-e', source], {\n cwd: options.cwd,\n env: {\n ...options.environment,\n HOME: options.homeDirectory,\n ...(options.temporaryDirectory === undefined ? {} : { TMPDIR: options.temporaryDirectory }),\n },\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n let output = '';\n let errors = '';\n const timeout = setTimeout(() => child.kill('SIGKILL'), 15_000);\n child.stdout.on('data', (chunk: Buffer) => {\n output += chunk.toString('utf8');\n if (output.length > 1_048_576) child.kill('SIGKILL');\n });\n child.stderr.on('data', (chunk: Buffer) => {\n errors = (errors + chunk.toString('utf8')).slice(-65_536);\n });\n child.once('error', (error) => {\n clearTimeout(timeout);\n reject(error);\n });\n child.once('close', (code) => {\n clearTimeout(timeout);\n if (code !== 0) {\n reject(new Error(`Workflow ${operation} failed: ${errors}`));\n return;\n }\n try {\n resolve(JSON.parse(output) as T);\n } catch (error) {\n reject(error);\n }\n });\n child.stdin.end(\n JSON.stringify({\n operation,\n request,\n portRegistryPath: options.environment.PORT_REGISTRY_PATH,\n processRegistryPath: options.environment.PROCESS_REGISTRY_PATH,\n }),\n );\n });\n}\n","import { createHash } from 'node:crypto';\nimport { join } from 'node:path';\n\nimport { nodeHost } from '@agimon-ai/po-core/platform';\n\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport type { WorkflowNativeTerminal } from './types';\n\nexport interface ServeTerminalOptions {\n service: WorkflowNativeTerminal;\n runKey: string;\n socketPath: string;\n onNotice?: (message: string) => void;\n}\nexport interface TerminalSocketServer {\n close(): Promise<void>;\n}\nexport type TerminalSocketOp = 'snapshot' | 'write' | 'resize';\nexport interface TerminalSocketRequest {\n op: TerminalSocketOp;\n data?: string;\n columns?: number;\n rows?: number;\n}\nexport interface TerminalSocketResponse {\n ok: boolean;\n lines?: string[];\n error?: string;\n}\n\n/** Unix socket paths are capped at 104 bytes on macOS; a long admitted root falls back to the host temp dir. */\nconst SOCKET_PATH_LIMIT = 100;\n\nexport function terminalSocketPath(workspace: string, runKey: string, root: string): string {\n const digest = createHash('sha256').update(`${workspace}/${runKey}`).digest('hex').slice(0, 24);\n const preferred = join(root, 'workflow-mcp-terminals', `${digest}.sock`);\n if (Buffer.byteLength(preferred) <= SOCKET_PATH_LIMIT) return preferred;\n return join(nodeHost.temporaryDirectory(), `workflow-mcp-${digest}.sock`);\n}\nexport function serveNativeTerminal(\n runtime: WorkflowRuntimeContext,\n options: ServeTerminalOptions,\n): Promise<TerminalSocketServer> {\n return runtime.workflowHost.serveTerminal(options);\n}\nexport function connectNativeTerminal(runtime: WorkflowRuntimeContext) {\n return runtime.workflowHost.connectTerminal();\n}\n","import type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport type { NativeTerminalDependencies, NativeTerminalSpawnInput, WorkflowNativeTerminal } from './types';\n\n/** Portable facade. The injected host owns RMUX and its native process handles. */\nexport class NativeTerminalService implements WorkflowNativeTerminal {\n private readonly terminal: WorkflowNativeTerminal;\n\n constructor(runtime: WorkflowRuntimeContext, dependencies: NativeTerminalDependencies = {}) {\n this.terminal = runtime.workflowHost.createTerminal(dependencies);\n }\n\n available() {\n return this.terminal.available();\n }\n spawn(input: NativeTerminalSpawnInput) {\n return this.terminal.spawn(input);\n }\n isHosted(runKey: string) {\n return this.terminal.isHosted(runKey);\n }\n exitOf(runKey: string) {\n return this.terminal.exitOf(runKey);\n }\n ended(runKey: string) {\n return this.terminal.ended(runKey);\n }\n viewerCount(runKey: string) {\n return this.terminal.viewerCount(runKey);\n }\n attach(runKey: string, columns: number, rows: number) {\n return this.terminal.attach(runKey, columns, rows);\n }\n kill(runKey: string) {\n return this.terminal.kill(runKey);\n }\n disposeAll() {\n return this.terminal.disposeAll();\n }\n}\n","import { createHash } from 'node:crypto';\nimport { dirname, relative, resolve } from 'node:path';\n\nimport { createSerialRunner, type SerialRunner, getOrThrow } from '@agimon-ai/po-core/platform';\n\nimport type { RunDirectory, RunDirectoryEntry } from '../../schemas/workflowEngine';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport type {\n RunDirectoryInspectedEntry,\n RunDirectoryInspection,\n RunDirectoryInspectOptions,\n RunDirectoryEntryState,\n RunDirectorySnapshot,\n RunDirectoryWrite,\n RunDirectoryWriter,\n StepArtifactSnapshot,\n StepArtifactWarning,\n} from './types';\n\n/** Which job and step last wrote each declared entry, one change per line. */\nexport const RUN_DIRECTORY_WRITES_FILENAME = 'writes.ndjson';\nconst MISSING_STATE = 'missing';\n/** Writes to one run's records, in order: steps of a parallel group finish together. */\n\nconst BUILT_IN_ENTRIES: RunDirectoryEntry[] = [\n {\n path: 'run.json',\n kind: 'file',\n description: 'Runner-owned workflow identity, lifecycle, recovery, and resolved run-directory declaration.',\n },\n {\n path: 'context.md',\n kind: 'file',\n description: 'Runner-owned user prompt and durable repair references.',\n },\n {\n path: 'changelog.md',\n kind: 'file',\n description: 'Shared append-only handoff log maintained by workflow jobs.',\n },\n {\n path: 'fix.md',\n kind: 'file',\n description: 'Ephemeral repair request consumed and archived by the runner.',\n },\n {\n path: 'proceed.md',\n kind: 'file',\n description: 'Ephemeral forward-jump request consumed by the runner during an active repair.',\n },\n {\n path: 'issues',\n kind: 'directory',\n description: 'Runner-owned durable issue and repair records.',\n },\n {\n path: 'decisions',\n kind: 'directory',\n description: 'Runner-owned step decisions recorded through workflow-mcp step.',\n },\n {\n path: 'bin',\n kind: 'directory',\n description: 'Runner-owned workflow-mcp launcher that agents call to record step decisions.',\n },\n {\n path: RUN_DIRECTORY_WRITES_FILENAME,\n kind: 'file',\n description: 'Runner-owned record of which job and step last wrote each declared entry.',\n },\n];\n\nconst UNREADABLE_FINGERPRINT = 'inaccessible';\n\nexport class RunDirectoryService {\n constructor(\n readonly runtime: WorkflowRuntimeContext,\n private readonly recording: SerialRunner = createSerialRunner(),\n ) {}\n\n async materialize(runDir: string, declaration: RunDirectory | undefined, dryRun = false): Promise<void> {\n if (!declaration || dryRun) return;\n\n const directories = declaration.entries\n .filter((entry) => entry.kind === 'directory')\n .sort((left, right) => left.path.split('/').length - right.path.split('/').length);\n for (const entry of directories) {\n getOrThrow(\n await this.runtime.fs.createDir(\n this.resolveEntryPath(runDir, entry.path),\n { recursive: true },\n this.runtime.ioContext,\n ),\n );\n }\n\n for (const entry of declaration.entries.filter((candidate) => candidate.kind === 'file')) {\n const targetPath = this.resolveEntryPath(runDir, entry.path);\n getOrThrow(await this.runtime.fs.createDir(dirname(targetPath), { recursive: true }, this.runtime.ioContext));\n try {\n await this.runtime.workflowHost.writeExclusive(targetPath, entry['initial-content'] ?? '');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n }\n }\n\n async inspect(\n runDir: string,\n declaration: RunDirectory | undefined,\n options: RunDirectoryInspectOptions = {},\n ): Promise<RunDirectoryInspection> {\n const declaredEntries = declaration?.entries ?? [];\n const entries = await Promise.all(\n [...BUILT_IN_ENTRIES, ...declaredEntries].map(async (entry) =>\n this.inspectEntry(runDir, entry, declaration, options),\n ),\n );\n return {\n description: declaration?.description ?? 'Workflow run files managed by workflow-mcp.',\n entries,\n jobName: options.jobName,\n runDir,\n };\n }\n\n snapshot(inspection: RunDirectoryInspection): RunDirectorySnapshot {\n return {\n fingerprints: Object.fromEntries(inspection.entries.map((entry) => [entry.path, entry.fingerprint])),\n };\n }\n\n async snapshotStepArtifacts(runDir: string, paths: string[]): Promise<StepArtifactSnapshot[]> {\n return Promise.all(\n paths.map(async (path) => {\n const targetPath = this.resolveEntryPath(runDir, path);\n try {\n const stats = getOrThrow(await this.runtime.fs.fileInfo(targetPath, this.runtime.ioContext));\n if (stats.kind !== 'file') return { path };\n return { fingerprint: await this.fingerprint(targetPath, 'file'), path };\n } catch {\n return { path };\n }\n }),\n );\n }\n\n async findStepArtifactWarnings(runDir: string, snapshots: StepArtifactSnapshot[]): Promise<StepArtifactWarning[]> {\n const warnings = await Promise.all(\n snapshots.map(async (snapshot): Promise<StepArtifactWarning | null> => {\n const status = await this.stepArtifactStatus(runDir, snapshot);\n if (status === undefined) return null;\n return {\n path: snapshot.path,\n status,\n ...(snapshot.description === undefined ? {} : { description: snapshot.description }),\n };\n }),\n );\n return warnings.filter((warning): warning is StepArtifactWarning => warning !== null);\n }\n\n /** What is wrong with one artifact, or undefined once it was written. */\n private async stepArtifactStatus(\n runDir: string,\n snapshot: StepArtifactSnapshot,\n ): Promise<StepArtifactWarning['status'] | undefined> {\n // A job's output is written once anything changed since the job began, removal included.\n if (snapshot.job !== undefined) {\n const state = await this.entryState(runDir, snapshot.path, snapshot.kind ?? 'file');\n if (state.sha === UNREADABLE_FINGERPRINT) return 'inaccessible';\n return state.sha === snapshot.fingerprint && state.mtimeMs === snapshot.mtimeMs ? 'unchanged' : undefined;\n }\n const targetPath = this.resolveEntryPath(runDir, snapshot.path);\n try {\n const stats = getOrThrow(await this.runtime.fs.fileInfo(targetPath, this.runtime.ioContext));\n if (stats.kind !== 'file') return 'inaccessible';\n if (stats.size === 0) return 'empty';\n return (await this.fingerprint(targetPath, 'file')) === snapshot.fingerprint ? 'unchanged' : undefined;\n } catch (error) {\n return ['ENOENT', 'not_found'].includes(String((error as { code?: string }).code)) ? 'missing' : 'inaccessible';\n }\n }\n\n /** What an entry holds now. */\n async entryState(runDir: string, path: string, kind: RunDirectoryEntry['kind']): Promise<RunDirectoryEntryState> {\n const targetPath = this.resolveEntryPath(runDir, path);\n try {\n const stats = getOrThrow(await this.runtime.fs.fileInfo(targetPath, this.runtime.ioContext));\n if (kind === 'directory' ? stats.kind !== 'directory' : stats.kind !== 'file') {\n return { sha: `incompatible:${stats.kind}`, mtimeMs: stats.mtimeMs };\n }\n return { sha: await this.fingerprint(targetPath, kind), mtimeMs: stats.mtimeMs };\n } catch (error) {\n return {\n sha: ['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))\n ? MISSING_STATE\n : UNREADABLE_FINGERPRINT,\n };\n }\n }\n\n /** Every write recorded in a run, oldest first. A line that does not parse is skipped. */\n async readWrites(runDir: string): Promise<RunDirectoryWrite[]> {\n let text: string;\n try {\n text = getOrThrow(\n await this.runtime.fs.readTextFile(resolve(runDir, RUN_DIRECTORY_WRITES_FILENAME), this.runtime.ioContext),\n );\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) return [];\n throw error;\n }\n return text.split('\\n').flatMap((line) => {\n if (line.trim().length === 0) return [];\n try {\n return [JSON.parse(line) as RunDirectoryWrite];\n } catch {\n return [];\n }\n });\n }\n\n /**\n * Record each entry that changed since its last record, as written by\n * `writer`: new content, the same content rewritten, or its removal. Without\n * a writer, the change happened outside any step. Returns every record of\n * the run, oldest first, the new ones last.\n */\n async recordWrites(\n runDir: string,\n entries: readonly Pick<RunDirectoryEntry, 'path' | 'kind'>[],\n writer?: RunDirectoryWriter,\n ): Promise<RunDirectoryWrite[]> {\n const key = resolve(runDir);\n return await this.recording.forKey(key)(() => this.appendWrites(runDir, entries, writer));\n }\n\n private async appendWrites(\n runDir: string,\n entries: readonly Pick<RunDirectoryEntry, 'path' | 'kind'>[],\n writer: RunDirectoryWriter | undefined,\n ): Promise<RunDirectoryWrite[]> {\n const records = await this.readWrites(runDir);\n const latest = new Map(records.map((record) => [record.path, record]));\n const at = new Date().toISOString();\n const changes: RunDirectoryWrite[] = [];\n for (const entry of entries) {\n const state = await this.entryState(runDir, entry.path, entry.kind);\n const last = latest.get(entry.path);\n if (last && last.sha === state.sha && last.mtimeMs === state.mtimeMs) continue;\n changes.push({ path: entry.path, ...state, ...writer, at });\n }\n if (changes.length > 0) {\n getOrThrow(\n await this.runtime.fs.appendFile(\n resolve(runDir, RUN_DIRECTORY_WRITES_FILENAME),\n changes.map((change) => `${JSON.stringify(change)}\\n`).join(''),\n this.runtime.ioContext,\n ),\n );\n }\n return [...records, ...changes];\n }\n\n formatInspection(inspection: RunDirectoryInspection): string {\n const jobSuffix = inspection.jobName ? ` for job ${inspection.jobName}` : '';\n const lines = [`Workflow run directory${jobSuffix}: ${inspection.runDir}`, inspection.description, ''];\n for (const entry of inspection.entries) {\n const producers = entry.producedBy.length > 0 ? `, produced by ${entry.producedBy.join(', ')}` : '';\n lines.push(\n `- [${entry.status}] ${entry.path} (${entry.kind}, ${entry.relation}${producers}): ${entry.description}`,\n );\n }\n lines.push('', 'Refresh this view with: workflow-mcp describe-run --run-dir \"$WORKFLOW_RUN_DIR\"');\n lines.push(\n `Each job must write the entries it produces before it ends (new content, a rewrite, or removal), or the job fails. ${RUN_DIRECTORY_WRITES_FILENAME} records which job and step last wrote each entry.`,\n );\n return lines.join('\\n');\n }\n\n private async inspectEntry(\n runDir: string,\n entry: RunDirectoryEntry,\n declaration: RunDirectory | undefined,\n options: RunDirectoryInspectOptions,\n ): Promise<RunDirectoryInspectedEntry> {\n const builtIn = BUILT_IN_ENTRIES.some((candidate) => candidate.path === entry.path);\n const producedBy = entry['produced-by'] ?? [];\n const relation = builtIn ? 'built-in' : this.resolveRelation(producedBy, options.jobName, options.jobOrder);\n if (options.planned && !builtIn) {\n return {\n description: entry.description,\n kind: entry.kind,\n path: entry.path,\n producedBy,\n relation,\n status: 'missing',\n };\n }\n\n const targetPath = this.resolveEntryPath(runDir, entry.path);\n try {\n getOrThrow(await this.runtime.fs.fileInfo(targetPath, this.runtime.ioContext));\n const stats = getOrThrow(await this.runtime.fs.fileInfo(targetPath, this.runtime.ioContext));\n if (\n (entry.kind === 'file' && stats.kind !== 'file') ||\n (entry.kind === 'directory' && stats.kind !== 'directory')\n ) {\n return {\n description: entry.description,\n fingerprint: `incompatible:${stats.kind}`,\n kind: entry.kind,\n path: entry.path,\n producedBy,\n relation,\n status: 'incompatible',\n };\n }\n const fingerprint = await this.fingerprint(targetPath, entry.kind);\n const status = await this.resolveStatus(targetPath, entry, declaration, builtIn, fingerprint);\n return {\n description: entry.description,\n fingerprint,\n kind: entry.kind,\n path: entry.path,\n producedBy,\n relation,\n status,\n };\n } catch (error) {\n const status = ['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))\n ? 'missing'\n : 'inaccessible';\n return {\n description: entry.description,\n fingerprint: status === 'inaccessible' ? UNREADABLE_FINGERPRINT : undefined,\n kind: entry.kind,\n path: entry.path,\n producedBy,\n relation,\n status,\n };\n }\n }\n\n private resolveRelation(producedBy: string[], jobName?: string, jobOrder?: string[]) {\n if (!jobName || producedBy.length === 0) return 'shared' as const;\n if (producedBy.includes(jobName)) return 'output' as const;\n const currentIndex = jobOrder?.indexOf(jobName) ?? -1;\n const producerIndexes = producedBy.map((producer) => jobOrder?.indexOf(producer) ?? -1);\n return producerIndexes.some((index) => index >= 0 && index < currentIndex)\n ? ('input' as const)\n : ('future' as const);\n }\n\n private async resolveStatus(\n targetPath: string,\n entry: RunDirectoryEntry,\n declaration: RunDirectory | undefined,\n builtIn: boolean,\n fingerprint: string,\n ) {\n if (entry.kind === 'directory') {\n return getOrThrow(await this.runtime.fs.listDir(targetPath, this.runtime.ioContext)).map((entry) => entry.name)\n .length === 0\n ? ('empty' as const)\n : ('populated' as const);\n }\n if (builtIn && !declaration?.entries.some((candidate) => candidate.path === entry.path)) {\n return getOrThrow(await this.runtime.fs.readBinaryFile(targetPath, this.runtime.ioContext)).length === 0\n ? ('empty' as const)\n : ('populated' as const);\n }\n const initialFingerprint = this.hash(entry['initial-content'] ?? '');\n return fingerprint === initialFingerprint ? ('initial' as const) : ('populated' as const);\n }\n\n private async fingerprint(targetPath: string, kind: RunDirectoryEntry['kind']): Promise<string> {\n if (kind === 'file')\n return this.hash(getOrThrow(await this.runtime.fs.readBinaryFile(targetPath, this.runtime.ioContext)));\n const names = getOrThrow(await this.runtime.fs.listDir(targetPath, this.runtime.ioContext)).map(\n (entry) => entry.name,\n );\n return this.hash(names.sort().join('\\n'));\n }\n\n private hash(value: string | Uint8Array): string {\n return createHash('sha256').update(value).digest('hex');\n }\n\n private resolveEntryPath(runDir: string, entryPath: string): string {\n const targetPath = resolve(runDir, entryPath);\n const relativePath = relative(resolve(runDir), targetPath);\n if (relativePath.startsWith('..') || relativePath === '') {\n throw new Error(`Unsafe workflow run-directory path: ${entryPath}`);\n }\n return targetPath;\n }\n}\n","/**\n * StepDecisionService\n *\n * DESIGN PATTERNS:\n * - Single owner of the step decision file and the text agents are steered with\n * - Pure functions over a file path, so the engine, the `step` CLI, stop hooks\n * and host executors all read and write one format\n *\n * CODING STANDARDS:\n * - Write the decision file atomically; a hook and the CLI may touch it in turn\n * - Never throw from the gate: an unreadable file lets the agent stop\n *\n * AVOID:\n * - Deciding workflow routing here; the engine consumes decisions at job end\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { join } from 'node:path';\n\nimport { getOrThrow, pathExists, writeFileAtomic } from '@agimon-ai/po-core/platform';\n\nimport { StepDecisionFileSchema } from '../../schemas/workflowEngine';\nimport type { StepDecision, StepDecisionFile } from '../../schemas/workflowEngine';\nimport { RunDirectoryService } from '../RunDirectoryService';\nimport { type StepArtifactSnapshot } from '../RunDirectoryService/types';\nimport type { StepDecisionReport } from '../workflowEngine/type';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\n/** Per-attempt decision file of the running step. */\nexport const WORKFLOW_DECISION_FILE_ENV = 'WORKFLOW_DECISION_FILE';\n/** What the job tells its agents about recording a decision; set on every job with a run directory. */\nexport const WORKFLOW_DECISION_INSTRUCTIONS_ENV = 'WORKFLOW_DECISION_INSTRUCTIONS';\n/** Comma-separated jobs a fix may restart from; empty when this job cannot request a fix. */\nexport const WORKFLOW_RESTART_TARGETS_ENV = 'WORKFLOW_RESTART_TARGETS';\n/** How many times a stop is refused for a missing decision before the agent may stop anyway. */\nexport const WORKFLOW_DECISION_NUDGE_CAP_ENV = 'WORKFLOW_DECISION_NUDGE_CAP';\n/** Set to `host` in a session whose host steers it itself, so stop hooks inside it stand down. */\nexport const WORKFLOW_DECISION_STEERING_ENV = 'WORKFLOW_DECISION_STEERING';\nexport const WORKFLOW_DECISION_STEERING_HOST = 'host';\n\nconst DECISIONS_DIRECTORY = 'decisions';\nconst FIX_FILENAME = 'fix.md';\nconst FRONTMATTER_RESTART_FROM = /^---\\s*\\n[\\s\\S]*?^restart-from:\\s*(\\S+)\\s*$[\\s\\S]*?^---\\s*$/m;\nconst DECISION_FILE_SUFFIX = '.json';\nconst WORKFLOW_RUN_DIR_ENV = 'WORKFLOW_RUN_DIR';\nconst WORKFLOW_STEP_ARTIFACTS_ENV = 'WORKFLOW_STEP_ARTIFACTS';\nconst DEFAULT_NUDGE_CAP = 3;\n/** Stays below Claude Code's own limit of 8 blocked stops in a row. */\nconst MAX_NUDGE_CAP = 7;\n\nexport type StepDecisionGate = { action: 'allow' } | { action: 'block'; message: string };\n\n/** The command an agent runs, as it can reach it whatever its PATH. */\nexport function workflowCliPath(runDir: string): string {\n return join(runDir, 'bin', 'workflow-mcp');\n}\n\n/** Where a step's decision file will live; decided before the step's prompt is rendered, which names it. */\nexport function newDecisionFilePath(runDir: string): string {\n return join(runDir, DECISIONS_DIRECTORY, `${randomUUID()}${DECISION_FILE_SUFFIX}`);\n}\n\n/** Start a fresh decision file for one attempt of a step. */\nexport async function createDecisionFile(\n runtime: WorkflowRuntimeContext,\n runDir: string,\n step: { job: string; step: string; restartTargets: string[]; required: boolean },\n path: string = newDecisionFilePath(runDir),\n): Promise<string> {\n getOrThrow(await runtime.fs.createDir(join(runDir, DECISIONS_DIRECTORY), { recursive: true }, runtime.ioContext));\n await resetDecisionFile(runtime, path, step);\n return path;\n}\n\n/** Clear a decision file for another attempt, keeping its step identity. */\nexport async function resetDecisionFile(\n runtime: WorkflowRuntimeContext,\n path: string,\n step: { job: string; step: string; restartTargets: string[]; required: boolean },\n): Promise<void> {\n await writeDecisionFile(runtime, path, { schemaVersion: 1, ...step, nudges: 0 });\n}\n\nexport async function readDecisionFile(\n runtime: WorkflowRuntimeContext,\n path: string,\n): Promise<StepDecisionFile | undefined> {\n try {\n return StepDecisionFileSchema.parse(JSON.parse(getOrThrow(await runtime.fs.readTextFile(path, runtime.ioContext))));\n } catch {\n return undefined;\n }\n}\n\nexport async function readStepDecision(\n runtime: WorkflowRuntimeContext,\n path: string,\n): Promise<StepDecision | undefined> {\n return (await readDecisionFile(runtime, path))?.decision;\n}\n\n/**\n * Record what an agent decided, replacing any earlier decision of this attempt.\n * A fix must name a job this step may restart from; the error lists them.\n */\nexport async function recordStepDecision(\n runtime: WorkflowRuntimeContext,\n path: string,\n decision: StepDecision,\n): Promise<StepDecisionFile> {\n if (!(await pathExists(runtime.fs, path, runtime.ioContext))) {\n throw new Error(`No workflow step is waiting for a decision at ${path}.`);\n }\n const file = await readDecisionFile(runtime, path);\n if (!file) {\n throw new Error(`The workflow decision file ${path} is unreadable.`);\n }\n if (decision.decision === 'fix' && !file.restartTargets.includes(decision.restartFrom)) {\n throw new Error(\n file.restartTargets.length === 0\n ? `Job \"${file.job}\" cannot request a fix. Use \"workflow-mcp step fail\" if it cannot finish.`\n : `\"${decision.restartFrom}\" is not a job this step can restart from. Valid targets: ${file.restartTargets.join(', ')}.`,\n );\n }\n const next: StepDecisionFile = { ...file, decision, decidedAt: new Date().toISOString() };\n await writeDecisionFile(runtime, path, next);\n return next;\n}\n\n/**\n * How an agent runs `workflow-mcp step`: through the run's launcher, and with\n * the step's decision file named, so the command works from any shell even\n * when the agent's tools do not carry the step's environment.\n */\nfunction stepCommand(runDir: string | undefined, decisionFile: string | undefined): string {\n const cli = runDir ? `\"${workflowCliPath(runDir)}\"` : 'workflow-mcp';\n return decisionFile ? `${cli} step <decision> --decision-file \"${decisionFile}\"` : `${cli} step <decision>`;\n}\n\n/**\n * What a job's agents are told about ending their step. Text only: the engine\n * adds it to the system prompt of every templated step, naming the step's own\n * decision file when it has one.\n */\nexport function stepDecisionInstructions(\n runDir: string,\n jobName: string,\n restartTargets: string[],\n decisionFile?: string,\n): string {\n const step = (decision: string) => stepCommand(runDir, decisionFile).replace('<decision>', decision);\n const lines = [\n `You are running a step of workflow job \"${jobName}\". Before you stop, record the step's outcome with exactly one of these shell commands:`,\n `- ${step('complete')} --summary \"<one line on what you did>\"`,\n ];\n if (restartTargets.length > 0) {\n lines.push(\n `- ${step('fix')} --restart-from <job> --reason \"<what must be fixed and where>\"`,\n ` Valid restart targets: ${restartTargets.join(', ')}. Use the earliest job that owns the problem; fix minor issues yourself instead.`,\n );\n }\n lines.push(\n `- ${step('fail')} --reason \"<the blocker and its evidence>\"`,\n ' Only for a blocker this workflow cannot fix; it ends the whole run.',\n 'Use --reason-file <path> instead of --reason for a long reason. Stopping without a decision is a failure. A decision can be replaced by running the command again before you stop.',\n );\n return lines.join('\\n');\n}\n\n/** One artifact still to write, with what it should hold when the run directory says. */\nexport function formatArtifactWarning(warning: { path: string; status: string; description?: string }): string {\n return `- ${warning.path}: ${warning.status}${warning.description ? `. It holds: ${warning.description}` : ''}`;\n}\n\n/** What an agent is told when it tries to stop before writing what its step and job must leave. */\nexport function stepArtifactReminder(\n file: Pick<StepDecisionFile, 'step' | 'job'>,\n runDir: string | undefined,\n warnings: readonly { path: string; status: string; description?: string }[],\n): string {\n const where = runDir ? ` in ${runDir}` : '';\n const owner = file.job ? `Step \"${file.step}\" of job \"${file.job}\"` : `Step \"${file.step}\"`;\n return `${owner} is not done: it must write or update each of these files${where} before it stops.\\n${warnings\n .map(formatArtifactWarning)\n .join('\\n')}`;\n}\n\n/** What an agent is told when it tries to stop without a decision. */\nexport function stepDecisionReminder(\n file: StepDecisionFile,\n runDir: string | undefined,\n decisionFile?: string,\n): string {\n const step = (decision: string) => stepCommand(runDir, decisionFile).replace('<decision>', decision);\n const targets =\n file.restartTargets.length > 0\n ? `, \\`${step('fix')} --restart-from <${file.restartTargets.join('|')}> --reason ...\\``\n : '';\n return `Step \"${file.step}\" of job \"${file.job}\" has no recorded outcome yet. Do not stop: finish the work, then run \\`${step('complete')} --summary ...\\`${targets}, or \\`${step('fail')} --reason ...\\` if a blocker makes it impossible.`;\n}\n\n/**\n * Whether an agent may stop now, for stop hooks and hosts that steer their\n * own sessions. A step with a required decision is held until one is\n * recorded, and a step that must leave artifacts, its own or its job's, until\n * they are updated, each at most `WORKFLOW_DECISION_NUDGE_CAP` times so a stuck\n * agent cannot loop forever: past the cap the stop is allowed and the engine\n * fails the step with what is still missing.\n */\nexport async function gateStepDecision(\n runtime: WorkflowRuntimeContext,\n env: Readonly<Record<string, string | undefined>> = runtime.baseEnvironment,\n): Promise<StepDecisionGate> {\n const path = env[WORKFLOW_DECISION_FILE_ENV];\n if (!path) return { action: 'allow' };\n // The host running this session steers it itself; a hook inside it must not nudge too.\n if (env[WORKFLOW_DECISION_STEERING_ENV] === WORKFLOW_DECISION_STEERING_HOST) return { action: 'allow' };\n const file = await readDecisionFile(runtime, path);\n if (!file) return { action: 'allow' };\n const decision = file.decision;\n if (decision && decision.decision !== 'complete') return { action: 'allow' };\n if (file.nudges >= nudgeCap(env)) return { action: 'allow' };\n\n let message: string | undefined;\n if (!decision && file.required) {\n message = stepDecisionReminder(file, env[WORKFLOW_RUN_DIR_ENV], path);\n } else {\n const warnings = await findArtifactWarnings(runtime, env);\n if (warnings.length > 0) {\n message = stepArtifactReminder(file, env[WORKFLOW_RUN_DIR_ENV], warnings);\n }\n }\n if (!message) return { action: 'allow' };\n await writeDecisionFile(runtime, path, { ...file, nudges: file.nudges + 1 });\n return { action: 'block', message };\n}\n\n/**\n * Merge a job's fix requests into the run's fix.md, which the runner turns\n * into one repair after the job. The restart target is the earliest requested\n * in job order, so one loop back covers every request; each reason gets its\n * own section. A fix.md a script or agent wrote during the job is kept in it.\n */\nexport async function writeFixRequest(\n runtime: WorkflowRuntimeContext,\n runDir: string,\n jobOrder: string[],\n jobName: string,\n fixes: Extract<StepDecisionReport, { decision: 'fix' }>[],\n): Promise<string> {\n const path = join(runDir, FIX_FILENAME);\n let existing: string | undefined;\n try {\n existing = getOrThrow(await runtime.fs.readTextFile(path, runtime.ioContext));\n } catch {\n existing = undefined;\n }\n const existingTarget = existing?.match(FRONTMATTER_RESTART_FROM)?.[1];\n const targets = [...fixes.map((fix) => fix.restartFrom), ...(existingTarget ? [existingTarget] : [])];\n const restartFrom = [...targets].sort((left, right) => rank(jobOrder, left) - rank(jobOrder, right))[0] ?? jobName;\n const sections = fixes.map((fix) => `## ${fix.step} (restart-from: ${fix.restartFrom})\\n\\n${fix.reason.trim()}`);\n if (existing?.trim()) {\n sections.push(`## Earlier fix request\\n\\n${existing.replace(/^---\\s*\\n[\\s\\S]*?\\n---\\s*\\n?/, '').trim()}`);\n }\n const content = `---\\nrestart-from: ${restartFrom}\\n---\\n\\n# Fix requests from job \"${jobName}\"\\n\\n${sections.join('\\n\\n')}\\n`;\n getOrThrow(await runtime.fs.writeFile(path, content, runtime.ioContext));\n return restartFrom;\n}\n\nfunction rank(jobOrder: string[], job: string): number {\n const index = jobOrder.indexOf(job);\n return index < 0 ? Number.MAX_SAFE_INTEGER : index;\n}\n\nfunction nudgeCap(env: Readonly<Record<string, string | undefined>>): number {\n const parsed = Number.parseInt(env[WORKFLOW_DECISION_NUDGE_CAP_ENV] ?? '', 10);\n if (!Number.isFinite(parsed) || parsed < 0) return DEFAULT_NUDGE_CAP;\n return Math.min(parsed, MAX_NUDGE_CAP);\n}\n\nasync function findArtifactWarnings(\n runtime: WorkflowRuntimeContext,\n env: Readonly<Record<string, string | undefined>>,\n) {\n const raw = env[WORKFLOW_STEP_ARTIFACTS_ENV];\n const runDir = env[WORKFLOW_RUN_DIR_ENV];\n if (!raw || !runDir) return [];\n try {\n return await new RunDirectoryService(runtime).findStepArtifactWarnings(\n runDir,\n JSON.parse(raw) as StepArtifactSnapshot[],\n );\n } catch {\n return [];\n }\n}\n\nasync function writeDecisionFile(runtime: WorkflowRuntimeContext, path: string, file: StepDecisionFile): Promise<void> {\n await writeFileAtomic(runtime.fs, path, `${JSON.stringify(file, null, 2)}\\n`, runtime.ioContext);\n}\n","/**\n * Structured error raised when a persisted workflow run record is malformed.\n */\nexport class InvalidWorkflowRunRecordError extends Error {\n readonly code = 'INVALID_WORKFLOW_RUN_RECORD';\n\n constructor(\n public readonly recordPath: string,\n reason: string,\n options?: ErrorOptions,\n ) {\n super(`Invalid workflow run record at \"${recordPath}\": ${reason}`, options);\n this.name = 'InvalidWorkflowRunRecordError';\n }\n}\n","/**\n * Structured error raised when a workflow display name is already active in a workspace.\n */\nexport class WorkflowRunConflictError extends Error {\n readonly code = 'WORKFLOW_RUN_CONFLICT';\n\n constructor(\n public readonly workspace: string,\n public readonly runKey: string,\n ) {\n super(`Workflow \"${runKey}\" is already running in workspace \"${workspace}\"`);\n this.name = 'WorkflowRunConflictError';\n }\n}\n","/**\n * Append-only progress log for a workflow run.\n *\n * DESIGN PATTERNS:\n * - NDJSON append per event. A run is a detached process, so anything it holds\n * in memory is invisible to every other process and lost on crash. One line\n * per transition is crash-safe, tailable while the run is live, and readable\n * long after it finishes.\n * - Best-effort writes. Progress is an observability signal, never a\n * correctness one, so a failure to record must not fail the run.\n *\n * CODING STANDARDS:\n * - Named exports only\n * - Explicit return types on exported members\n *\n * AVOID:\n * - Rewriting the file: appending keeps concurrent readers consistent and keeps\n * the cost of an event independent of how many came before it\n * - Throwing: the run is the product, this is the commentary\n */\n\nimport { resolve } from 'node:path';\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\n\nimport { WorkflowProgressEventSchema } from '../../schemas/workflowEngine';\nimport type { StepExecutionRef, WorkflowProgressEvent } from '../../schemas/workflowEngine';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nexport const PROGRESS_FILENAME = 'progress.ndjson';\n\n/**\n * Job names the engine records for the `pre:` and `post:` blocks.\n *\n * Those blocks are not jobs, but they run steps and a reader wants to see them,\n * so they are recorded as pseudo-jobs under these reserved names. Exported so a\n * reader can tell a phase from a real job without hardcoding the strings the\n * writer happens to use. Worktree hooks are deliberately absent: they record no\n * progress at all, so nothing can report them.\n */\nexport const PHASE_JOB_PRE = 'pre';\nexport const PHASE_JOB_POST = 'post';\n\n/** Whether a recorded job is a real job or one of the two phase blocks. */\nexport type WorkflowRunPhase = 'job' | typeof PHASE_JOB_POST | typeof PHASE_JOB_PRE;\n\n/** Classify a recorded job name as a phase block or a real job. */\nexport function workflowRunPhase(job: string): WorkflowRunPhase {\n if (job === PHASE_JOB_PRE) return PHASE_JOB_PRE;\n if (job === PHASE_JOB_POST) return PHASE_JOB_POST;\n return 'job';\n}\n\nexport type WorkflowProgressInput = Omit<WorkflowProgressEvent, 'at'>;\n\n/** Records job and step transitions for one run. */\nexport class WorkflowProgressService {\n constructor(\n readonly runtime: WorkflowRuntimeContext,\n private readonly runDir: string | undefined,\n private readonly now: () => string = () => new Date().toISOString(),\n private readonly append: (path: string, data: string) => Promise<void> = (path, data) =>\n Promise.resolve(runtime.fs.appendFile(path, data, runtime.ioContext)).then(getOrThrow),\n ) {}\n\n private path(): string | undefined {\n return this.runDir ? resolve(this.runDir, PROGRESS_FILENAME) : undefined;\n }\n\n /**\n * Record one transition.\n *\n * Swallows write failures on purpose: a dry run has no run directory, and a\n * full disk should not turn a passing workflow into a failing one.\n */\n async record(event: WorkflowProgressInput): Promise<void> {\n const path = this.path();\n if (!path) return;\n try {\n await this.append(path, `${JSON.stringify({ ...event, at: this.now() })}\\n`);\n } catch {\n // Observability only.\n }\n }\n\n jobStarted(job: string, index: number, total: number): Promise<void> {\n return this.record({ type: 'job', status: 'running', job, index, total });\n }\n\n jobFinished(\n job: string,\n status: 'completed' | 'failed' | 'pause_requested' | 'paused' | 'resumed',\n reason?: string,\n ): Promise<void> {\n return this.record({ type: 'job', status, job, ...(reason ? { reason } : {}) });\n }\n\n /** A job a forward jump passed over: it never ran, so it never started either. */\n jobSkipped(job: string, reason?: string): Promise<void> {\n return this.record({ type: 'job', status: 'skipped', job, ...(reason ? { reason } : {}) });\n }\n\n /** `group` names the parallel group a step runs in, beside the other steps of that group. */\n stepStarted(job: string, step: string, index: number, total: number, group?: string): Promise<void> {\n return this.record({ type: 'step', status: 'running', job, step, index, total, ...(group ? { group } : {}) });\n }\n\n /** A host executor started the step; the ref says where a reader can follow it. */\n stepExecutionStarted(job: string, step: string, ref: StepExecutionRef): Promise<void> {\n return this.record({ type: 'step', status: 'running', job, step, ref });\n }\n\n stepFinished(\n job: string,\n step: string,\n status: 'completed' | 'failed' | 'pause_requested' | 'paused' | 'resumed',\n reason?: string,\n ): Promise<void> {\n return this.record({ type: 'step', status, job, step, ...(reason ? { reason } : {}) });\n }\n}\n\n/**\n * Read a run's progress log.\n *\n * Malformed lines are skipped rather than throwing: a reader may catch the file\n * mid-append, and a torn final line is expected rather than exceptional.\n */\nexport async function readWorkflowProgress(\n runtime: WorkflowRuntimeContext,\n runDir: string,\n read: (path: string) => Promise<string> = async (path) =>\n getOrThrow(await runtime.fs.readTextFile(path, runtime.ioContext)),\n): Promise<WorkflowProgressEvent[]> {\n let raw: string;\n try {\n raw = await read(resolve(runDir, PROGRESS_FILENAME));\n } catch {\n return [];\n }\n\n return parseProgressLines(raw);\n}\n\nfunction parseProgressLines(raw: string): WorkflowProgressEvent[] {\n const events: WorkflowProgressEvent[] = [];\n for (const line of raw.split('\\n')) {\n if (!line.trim()) continue;\n try {\n const parsed = WorkflowProgressEventSchema.safeParse(JSON.parse(line));\n if (parsed.success) events.push(parsed.data);\n } catch {\n // Torn or truncated line, expected while the run is still appending.\n }\n }\n return events;\n}\n\n/** Whatever a run has appended since a given byte offset, and the new offset. */\nexport interface WorkflowProgressTail {\n events: WorkflowProgressEvent[];\n offset: number;\n}\n\n/** Bytes from `offset` to the end of file, and where each end sat. */\nexport type ProgressTailReader = (\n path: string,\n offset: number,\n) => Promise<{ end: number; start: number; text: string } | undefined>;\n\nasync function readProgressTail(\n runtime: WorkflowRuntimeContext,\n path: string,\n offset: number,\n): ReturnType<ProgressTailReader> {\n const handle = getOrThrow(await runtime.fs.openBinaryReader(path, undefined, runtime.ioContext));\n try {\n const { size } = getOrThrow(await handle.info(runtime.ioContext));\n const start = offset > size ? 0 : offset;\n if (start === size) return { end: size, start, text: '' };\n const bytes = getOrThrow(await handle.read(start, size - start, runtime.ioContext));\n return { end: start + bytes.length, start, text: new TextDecoder().decode(bytes) };\n } finally {\n await handle.close(runtime.ioContext);\n }\n}\n\n/**\n * Read only what a run has appended since the last call.\n *\n * The whole-file `readWorkflowProgress` re-parses from byte zero every time,\n * which is fine once and wasteful on a timer: a watcher asking a live run for\n * its latest transition pays for every transition that came before it.\n *\n * Only whole lines are consumed. A reader routinely catches the file\n * mid-append, and the bytes of a torn line have to stay unread so the next call\n * sees the finished line instead of dropping it.\n */\nexport async function readWorkflowProgressFrom(\n runtime: WorkflowRuntimeContext,\n runDir: string,\n offset = 0,\n read: ProgressTailReader = (path, offset) => readProgressTail(runtime, path, offset),\n): Promise<WorkflowProgressTail> {\n let tail: Awaited<ReturnType<ProgressTailReader>>;\n try {\n tail = await read(resolve(runDir, PROGRESS_FILENAME), offset);\n } catch {\n // No log yet, or not readable. Hold the offset so nothing is skipped once\n // the file appears.\n return { events: [], offset };\n }\n if (!tail) return { events: [], offset };\n\n const lastBreak = tail.text.lastIndexOf('\\n');\n if (lastBreak < 0) return { events: [], offset: tail.start };\n\n const complete = tail.text.slice(0, lastBreak + 1);\n return {\n events: parseProgressLines(complete),\n // Byte length, not character count: a multi-byte character in a step name\n // would otherwise leave the offset short and replay part of a line.\n offset: tail.start + Buffer.byteLength(complete, 'utf-8'),\n };\n}\n\n/** Every state a recorded job or step can be in. */\nexport type WorkflowProgressStatus =\n | 'completed'\n | 'failed'\n | 'pause_requested'\n | 'paused'\n | 'resumed'\n | 'running'\n | 'skipped';\n\nexport interface WorkflowProgressStep {\n name: string;\n status: WorkflowProgressStatus;\n reason?: string;\n /** Where a host executor ran the step, kept after it finishes. */\n ref?: StepExecutionRef;\n /** The parallel group the step ran in, when it ran beside others. */\n group?: string;\n}\n\nexport interface WorkflowProgressJob {\n name: string;\n status: WorkflowProgressStatus;\n steps: WorkflowProgressStep[];\n index?: number;\n total?: number;\n reason?: string;\n}\n\n/**\n * Fold the event log into the current job tree.\n *\n * Later events win, so a job that started and later failed reads as failed.\n * This is what a progress view renders: completed jobs collapse, the running\n * one expands.\n */\nexport function summarizeWorkflowProgress(events: WorkflowProgressEvent[]): WorkflowProgressJob[] {\n const jobs = new Map<string, WorkflowProgressJob>();\n\n for (const event of events) {\n const job = jobs.get(event.job) ?? { name: event.job, status: 'running', steps: [] };\n if (event.type === 'job') {\n job.status = event.status;\n if (event.index !== undefined) job.index = event.index;\n if (event.total !== undefined) job.total = event.total;\n if (event.reason) job.reason = event.reason;\n } else if (event.step) {\n const existing = job.steps.find((step) => step.name === event.step);\n if (existing) {\n existing.status = event.status;\n if (event.reason) existing.reason = event.reason;\n if (event.ref) existing.ref = event.ref;\n if (event.group) existing.group = event.group;\n } else {\n job.steps.push({\n name: event.step,\n status: event.status,\n ...(event.reason ? { reason: event.reason } : {}),\n ...(event.ref ? { ref: event.ref } : {}),\n ...(event.group ? { group: event.group } : {}),\n });\n }\n }\n jobs.set(event.job, job);\n }\n\n return [...jobs.values()];\n}\n\n/** The job and step a run is on right now, for a one-line status. */\nexport function currentWorkflowPosition(\n jobs: WorkflowProgressJob[],\n): { job: string; step?: string; index?: number; total?: number } | undefined {\n const running = jobs.find((job) => job.status === 'running');\n if (!running) return undefined;\n const step = running.steps.find((candidate) => candidate.status === 'running');\n return { job: running.name, step: step?.name, index: running.index, total: running.total };\n}\n","import { randomUUID } from 'node:crypto';\nimport { resolve } from 'node:path';\n/**\n * WorkflowRegistryService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { createSerialRunner, getOrThrow, writeFileAtomic } from '@agimon-ai/po-core/platform';\n\nimport { InvalidWorkflowRunRecordError } from '../../models/InvalidWorkflowRunRecordError';\nimport { WorkflowRunConflictError } from '../../models/WorkflowRunConflictError';\nimport { WorkflowRepairRecordSchema, WorkflowRunRecordSchema } from '../../schemas/workflowEngine';\nimport type {\n RunDirectory,\n WorkflowExecutionCursor,\n WorkflowExecutionState,\n WorkflowLauncherMetadata,\n WorkflowOutcome,\n WorkflowRepairRecord,\n WorkflowRunHandle,\n WorkflowRunRecord,\n WorkflowStage,\n} from '../../schemas/workflowEngine';\nimport type { WorkflowHost } from '../workflowHost/type';\nimport { WorkflowProgressService } from '../WorkflowProgressService';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nconst DEFAULT_WORKFLOW_HOME = '.workflow-mcp';\nconst WORKFLOW_HOME_ENV = 'WORKFLOW_MCP_HOME';\nconst DEFAULT_WORKSPACE = 'default';\nconst RUNNING_STAGE: WorkflowStage = 'running';\nconst COMPLETED_STAGE: WorkflowStage = 'completed';\nconst ERROR_STAGE: WorkflowStage = 'error';\nconst WORKSPACES_DIRNAME = 'workspaces';\nconst RUN_RECORD_FILENAME = 'run.json';\nconst CONTEXT_FILENAME = 'context.md';\nconst CHANGELOG_FILENAME = 'changelog.md';\nconst FIX_FILENAME = 'fix.md';\nconst PROCEED_FILENAME = 'proceed.md';\nconst STOP_REQUEST_FILENAME = 'stop-request.json';\nconst PAUSE_REQUEST_FILENAME = 'pause-request.json';\nconst FINALIZING_FILENAME = 'finalizing.json';\nconst ISSUES_DIRNAME = 'issues';\nconst REPAIR_FILENAME = 'repair.json';\nconst RECOVERY_CLAIM_FILENAME = 'recovery-claim.json';\nconst RECOVERY_ADOPTION_FILENAME = 'recovery-adoption.json';\nconst FALLBACK_RUN_KEY = 'workflow-run';\nconst SLUG_SEPARATOR = '-';\nconst INTERRUPTED_EXIT_CODE = 130;\nconst STALE_RUNNING_ERROR_PREFIX = 'Workflow process is no longer running';\nconst DEFAULT_LIST_RUNS_PAGE = 1;\nconst DEFAULT_LIST_RUNS_PAGE_SIZE = 20;\nconst DEFAULT_RECOVERY_CLAIM_TTL_MS = 5 * 60 * 1000;\n\nexport interface WorkflowRegistryCreateRunInput {\n activeRepairId?: string;\n cliAgent?: string;\n continueOnError?: boolean;\n displayName: string;\n dryRun: boolean;\n env?: Record<string, string>;\n job?: string;\n keepWorktree?: boolean;\n inputs?: Record<string, string>;\n launcher?: WorkflowLauncherMetadata;\n prompt?: string;\n pid?: number;\n /** Required capability when promoting a terminal error run for recovery. */\n recoveryClaimId?: string;\n runner?: string;\n command?: string;\n choice?: string;\n runDirectory?: RunDirectory;\n secretFile?: string;\n skipLaunch?: boolean;\n statusFile?: string;\n /** Where a natively hosted run answers screen and key requests, when it does. */\n terminalSocket?: string;\n workflowPath: string;\n workflowId?: string;\n workflowName?: string;\n workflowWorkspace?: string;\n workspace?: string;\n}\n\nexport interface WorkflowRegistryFinalizeRunInput {\n errorMessage?: string;\n exitCode?: number;\n failedJob?: string;\n failureReason?: string;\n fixLoopCycle?: number;\n originalRepoPath?: string;\n outcome?: WorkflowOutcome;\n stage: Exclude<WorkflowStage, 'running'>;\n worktreeBranch?: string;\n worktreePath?: string;\n}\n\nexport interface WorkflowRegistryRepairStateInput {\n activeRepairId?: string | null;\n fixLoopCycle?: number;\n}\n\nexport interface WorkflowRegistryListRunsPageInput {\n page?: number;\n pageSize?: number;\n workspace?: string;\n /**\n * Applied before pagination, so `total`, `totalPages`, and `hasNextPage`\n * describe the filtered set rather than the whole registry.\n */\n filter?: (record: WorkflowRunRecord) => boolean;\n}\n\nexport interface WorkflowRegistryListRunsPage {\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n items: WorkflowRunRecord[];\n page: number;\n pageSize: number;\n total: number;\n totalPages: number;\n}\n\nexport interface WorkflowStopRequest {\n reason?: string;\n requestedAt: string;\n runId: string;\n schemaVersion: 1;\n}\n\nexport interface WorkflowPauseRequest {\n action: 'pause';\n schemaVersion: 1;\n reason?: string;\n requestId: string;\n requestedAt: string;\n revision: number;\n runId: string;\n}\n\nexport interface WorkflowResumeRequest {\n action: 'resume';\n schemaVersion: 1;\n requestId: string;\n requestedAt: string;\n revision: number;\n runId: string;\n}\n\nexport interface WorkflowRecoveryClaim {\n claimId: string;\n claimedAt: string;\n ownerSessionId?: string;\n pid: number;\n}\n\ninterface WorkflowRecoveryAdoption {\n adoptedAt: string;\n claimId: string;\n pid: number;\n}\n\n/**\n * Filesystem-backed registry for workflow runs.\n */\nexport class WorkflowRegistryService {\n readonly writeCoordinator = createSerialRunner();\n private readonly homeDir: string;\n private readonly lockRecoveryClaim: WorkflowHost['acquireRecoveryLock'];\n\n constructor(\n readonly runtime: WorkflowRuntimeContext,\n homeDir?: string,\n private readonly recoveryClaimTtlMs = DEFAULT_RECOVERY_CLAIM_TTL_MS,\n lockRecoveryClaim?: WorkflowHost['acquireRecoveryLock'],\n ) {\n this.homeDir = resolve(\n homeDir ?? runtime.baseEnvironment[WORKFLOW_HOME_ENV] ?? resolve(runtime.homeDirectory, DEFAULT_WORKFLOW_HOME),\n );\n this.lockRecoveryClaim = lockRecoveryClaim ?? runtime.workflowHost.acquireRecoveryLock.bind(runtime.workflowHost);\n }\n\n /**\n * Resolve the effective workspace from CLI/tool input or workflow YAML metadata.\n */\n resolveWorkspace(explicitWorkspace?: string, workflowWorkspace?: string): string {\n return this.slugifySegment(explicitWorkspace || workflowWorkspace || DEFAULT_WORKSPACE, DEFAULT_WORKSPACE);\n }\n\n /**\n * Create or resume a workflow run in the `running` stage for its workspace.\n */\n async createRun(input: WorkflowRegistryCreateRunInput): Promise<WorkflowRunHandle> {\n const workspace = this.resolveWorkspace(input.workspace, input.workflowWorkspace);\n const runKey = this.slugifySegment(input.displayName, FALLBACK_RUN_KEY);\n\n await this.ensureWorkspaceStructure(workspace);\n\n const existingStage = await this.findReusableRunStage(workspace, runKey);\n if (existingStage === RUNNING_STAGE) {\n throw new WorkflowRunConflictError(workspace, runKey);\n }\n\n const runningDir = this.getRunDirectory(workspace, RUNNING_STAGE, runKey);\n if (existingStage) {\n const existingDir = this.getRunDirectory(workspace, existingStage, runKey);\n let releaseRecoveryLock: (() => Promise<void>) | undefined;\n try {\n if (existingStage === ERROR_STAGE) {\n releaseRecoveryLock = await this.acquireRecoveryClaimLock(existingDir);\n await this.assertRecoveryPromotion(existingDir, workspace, runKey, input.recoveryClaimId);\n } else if (input.recoveryClaimId) {\n throw new Error(`Workflow recovery claim does not target a failed run: ${workspace}/${runKey}`);\n }\n getOrThrow(await this.runtime.fs.remove(runningDir, { recursive: true, force: true }, this.runtime.ioContext));\n getOrThrow(await this.runtime.fs.renameFile(existingDir, runningDir, this.runtime.ioContext));\n } finally {\n await releaseRecoveryLock?.();\n }\n await this.removeFileIfExists(resolve(runningDir, FIX_FILENAME));\n await this.removeFileIfExists(resolve(runningDir, PROCEED_FILENAME));\n await this.removeFileIfExists(resolve(runningDir, STOP_REQUEST_FILENAME));\n await this.removeFileIfExists(resolve(runningDir, PAUSE_REQUEST_FILENAME));\n await this.removeFileIfExists(resolve(runningDir, FINALIZING_FILENAME));\n await this.removeFileIfExists(resolve(runningDir, RECOVERY_CLAIM_FILENAME));\n await this.removeFileIfExists(resolve(runningDir, RECOVERY_ADOPTION_FILENAME));\n } else {\n if (input.recoveryClaimId) {\n throw new Error(`Workflow recovery claim target no longer exists: ${workspace}/${runKey}`);\n }\n getOrThrow(await this.runtime.fs.createDir(runningDir, { recursive: true }, this.runtime.ioContext));\n }\n\n const runId = randomUUID();\n const runRecord: WorkflowRunRecord = {\n activeRepairId: input.activeRepairId,\n cliAgent: input.cliAgent,\n continueOnError: input.continueOnError,\n displayName: input.displayName,\n dryRun: input.dryRun,\n env: input.env,\n inputs: input.inputs,\n job: input.job,\n keepWorktree: input.keepWorktree,\n launcher: input.launcher,\n runKey,\n prompt: input.prompt,\n runner: input.runner,\n ...(input.command === undefined ? {} : { command: input.command }),\n ...(input.choice === undefined ? {} : { choice: input.choice }),\n runDirectory: input.runDirectory,\n runId,\n secretFile: input.secretFile,\n skipLaunch: input.skipLaunch,\n statusFile: input.statusFile,\n terminalSocket: input.terminalSocket,\n executionState: 'running',\n executionCursor: {\n executionGeneration: 1,\n phase: 'starting',\n resumeMode: 'continue-next',\n revision: 0,\n },\n stage: RUNNING_STAGE,\n startedAt: new Date().toISOString(),\n pid: input.pid ?? this.runtime.workflowHost.processId,\n workflowPath: input.workflowPath,\n workflowId: input.workflowId,\n workflowName: input.workflowName,\n workspace,\n };\n\n const recordPath = resolve(runningDir, RUN_RECORD_FILENAME);\n await this.writeRunRecord(recordPath, runRecord);\n\n return {\n changelogPath: resolve(runningDir, CHANGELOG_FILENAME),\n contextPath: resolve(runningDir, CONTEXT_FILENAME),\n displayName: input.displayName,\n pauseRequestPath: resolve(runningDir, PAUSE_REQUEST_FILENAME),\n recordPath,\n runDir: runningDir,\n runId,\n runKey,\n stopRequestPath: resolve(runningDir, STOP_REQUEST_FILENAME),\n workspace,\n };\n }\n\n /**\n * Finalize a workflow run by moving it into a terminal stage and updating metadata.\n */\n async finalizeRun(handle: WorkflowRunHandle, input: WorkflowRegistryFinalizeRunInput): Promise<WorkflowRunHandle> {\n await this.ensureWorkspaceStructure(handle.workspace);\n\n const nextDir = this.getRunDirectory(handle.workspace, input.stage, handle.runKey);\n const currentRecord = await this.readRunRecord(handle.recordPath);\n const finalRecord: WorkflowRunRecord = {\n ...currentRecord,\n errorMessage: input.errorMessage,\n executionCursor: undefined,\n executionState: undefined,\n exitCode: input.exitCode,\n failedJob: input.failedJob,\n failureReason: input.failureReason,\n finishedAt: new Date().toISOString(),\n fixLoopCycle: input.fixLoopCycle,\n originalRepoPath: input.originalRepoPath,\n outcome: input.outcome,\n pid: currentRecord.pid,\n stage: input.stage,\n worktreeBranch: input.worktreeBranch,\n worktreePath: input.worktreePath,\n };\n\n await this.removeFileIfExists(resolve(handle.runDir, PAUSE_REQUEST_FILENAME));\n // The terminal record is written before the directory moves. Written after\n // the rename, a failure or kill in between left a `stage: running` record\n // under a terminal directory, where stale detection never looks, so every\n // reader saw a run that stayed running forever.\n await this.writeRunRecord(handle.recordPath, finalRecord);\n await this.removeFileIfExists(resolve(handle.runDir, FINALIZING_FILENAME));\n if (handle.runDir !== nextDir) {\n getOrThrow(await this.runtime.fs.remove(nextDir, { recursive: true, force: true }, this.runtime.ioContext));\n getOrThrow(await this.runtime.fs.renameFile(handle.runDir, nextDir, this.runtime.ioContext));\n }\n\n const nextRecordPath = resolve(nextDir, RUN_RECORD_FILENAME);\n\n return {\n ...handle,\n pauseRequestPath: resolve(nextDir, PAUSE_REQUEST_FILENAME),\n recordPath: nextRecordPath,\n runDir: nextDir,\n stopRequestPath: resolve(nextDir, STOP_REQUEST_FILENAME),\n };\n }\n\n /**\n * Request graceful interruption for a running workflow.\n */\n async requestStop(\n workspace: string | undefined,\n runKey: string,\n reason: string | undefined,\n expectedRunId: string,\n ): Promise<WorkflowStopRequest> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const runningDir = this.getRunDirectory(resolvedWorkspace, RUNNING_STAGE, resolvedRunKey);\n const recordPath = resolve(runningDir, RUN_RECORD_FILENAME);\n\n if (!(await this.pathExists(recordPath))) {\n throw new Error(`Running workflow not found: ${resolvedWorkspace}/${runKey}`);\n }\n\n const record = await this.inspectRunningRecord(resolvedWorkspace, resolvedRunKey);\n if (record.runId !== expectedRunId) {\n throw new Error(`Workflow run ownership changed: ${resolvedWorkspace}/${runKey}`);\n }\n if (record.stale) {\n throw new Error(record.staleReason ?? `Running workflow is stale: ${resolvedWorkspace}/${runKey}`);\n }\n\n if (!record.runId) throw new Error(`Running workflow has no run ID: ${resolvedWorkspace}/${runKey}`);\n const request: WorkflowStopRequest = {\n reason: reason?.trim() ? reason.trim() : undefined,\n requestedAt: new Date().toISOString(),\n runId: record.runId,\n schemaVersion: 1,\n };\n await this.writeControlRequest(\n {\n changelogPath: resolve(runningDir, CHANGELOG_FILENAME),\n contextPath: resolve(runningDir, CONTEXT_FILENAME),\n displayName: record.displayName,\n pauseRequestPath: resolve(runningDir, PAUSE_REQUEST_FILENAME),\n recordPath,\n runDir: runningDir,\n runId: record.runId,\n runKey: resolvedRunKey,\n stopRequestPath: resolve(runningDir, STOP_REQUEST_FILENAME),\n workspace: resolvedWorkspace,\n },\n resolve(runningDir, STOP_REQUEST_FILENAME),\n request,\n );\n return request;\n }\n\n async requestPause(\n workspace: string | undefined,\n runKey: string,\n reason: string | undefined,\n expectedRunId: string,\n ): Promise<WorkflowPauseRequest> {\n const handle = await this.getRunningHandle(workspace, runKey, expectedRunId);\n await this.assertNotFinalizing(handle);\n const record = await this.readRunRecord(handle.recordPath);\n const state = record.executionState ?? 'running';\n const existing = await this.readPauseRequest(handle);\n if (existing?.action === 'pause' && (state === 'pause_requested' || state === 'paused')) return existing;\n if (state === 'resume_requested') {\n throw new Error(`Workflow is resuming: ${handle.workspace}/${handle.runKey}`);\n }\n if (state !== 'running') {\n throw new Error(`Workflow cannot be paused from execution state ${state}: ${handle.workspace}/${handle.runKey}`);\n }\n\n if (existing?.action === 'resume') {\n await this.clearPauseRequest(handle);\n }\n const revision = record.executionCursor?.revision ?? 0;\n const request: WorkflowPauseRequest = {\n action: 'pause',\n schemaVersion: 1,\n reason: reason?.trim() ? reason.trim() : undefined,\n requestId: randomUUID(),\n requestedAt: new Date().toISOString(),\n revision,\n runId: handle.runId,\n };\n await this.assertCurrentRun(handle);\n await this.updateExecutionState(\n handle,\n 'pause_requested',\n {\n ...(record.executionCursor ?? {\n executionGeneration: 1,\n phase: 'unknown',\n resumeMode: 'replay-current',\n }),\n requestId: request.requestId,\n resumeMode: 'replay-current',\n revision: revision + 1,\n },\n revision,\n );\n await this.writeControlRequest(\n handle,\n handle.pauseRequestPath ?? resolve(handle.runDir, PAUSE_REQUEST_FILENAME),\n request,\n );\n const progressJob = record.executionCursor?.job ?? record.job ?? record.executionCursor?.phase ?? 'workflow';\n if (record.executionCursor?.stepName) {\n await new WorkflowProgressService(this.runtime, handle.runDir).stepFinished(\n progressJob,\n record.executionCursor.stepName,\n 'pause_requested',\n request.reason,\n );\n } else {\n await new WorkflowProgressService(this.runtime, handle.runDir).jobFinished(\n progressJob,\n 'pause_requested',\n request.reason,\n );\n }\n return request;\n }\n\n async requestResume(\n workspace: string | undefined,\n runKey: string,\n expectedRunId: string,\n ): Promise<WorkflowResumeRequest> {\n const handle = await this.getRunningHandle(workspace, runKey, expectedRunId);\n await this.assertNotFinalizing(handle);\n const record = await this.readRunRecord(handle.recordPath);\n const state = record.executionState ?? 'running';\n const existing = await this.readPauseRequest(handle);\n if (existing?.action === 'resume' && (state === 'resume_requested' || state === 'running')) return existing;\n if (state !== 'paused' || existing?.action !== 'pause') {\n throw new Error(`Workflow is not paused: ${handle.workspace}/${handle.runKey}`);\n }\n\n const revision = record.executionCursor?.revision ?? existing.revision;\n const request: WorkflowResumeRequest = {\n action: 'resume',\n schemaVersion: 1,\n requestId: randomUUID(),\n requestedAt: new Date().toISOString(),\n revision,\n runId: handle.runId,\n };\n await this.assertCurrentRun(handle);\n await this.updateExecutionState(\n handle,\n 'resume_requested',\n {\n ...(record.executionCursor ?? {\n executionGeneration: 1,\n phase: 'unknown',\n resumeMode: 'replay-current',\n }),\n requestId: request.requestId,\n resumeMode: 'replay-current',\n revision: revision + 1,\n },\n revision,\n );\n await this.writeControlRequest(\n handle,\n handle.pauseRequestPath ?? resolve(handle.runDir, PAUSE_REQUEST_FILENAME),\n request,\n );\n return request;\n }\n\n async readPauseRequest(handle: WorkflowRunHandle): Promise<WorkflowPauseRequest | WorkflowResumeRequest | null> {\n try {\n const value: unknown = JSON.parse(\n getOrThrow(\n await this.runtime.fs.readTextFile(\n handle.pauseRequestPath ?? resolve(handle.runDir, PAUSE_REQUEST_FILENAME),\n this.runtime.ioContext,\n ),\n ),\n );\n if (!value || typeof value !== 'object') return null;\n const candidate = value as Partial<WorkflowPauseRequest> & Partial<WorkflowResumeRequest>;\n if (\n (candidate.action !== 'pause' && candidate.action !== 'resume') ||\n candidate.schemaVersion !== 1 ||\n candidate.runId !== handle.runId ||\n typeof candidate.requestId !== 'string' ||\n typeof candidate.revision !== 'number' ||\n !Number.isInteger(candidate.revision) ||\n candidate.revision < 0 ||\n typeof candidate.requestedAt !== 'string'\n )\n return null;\n return candidate as WorkflowPauseRequest | WorkflowResumeRequest;\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) return null;\n throw error;\n }\n }\n\n async updateExecutionState(\n handle: WorkflowRunHandle,\n executionState: WorkflowExecutionState,\n executionCursor?: WorkflowExecutionCursor,\n expectedRevision?: number,\n ): Promise<WorkflowRunRecord> {\n const current = await this.readRunRecord(handle.recordPath);\n if (current.stage !== RUNNING_STAGE || (current.runId && current.runId !== handle.runId)) {\n throw new Error(`Workflow run is no longer controllable: ${handle.workspace}/${handle.runKey}`);\n }\n const currentRevision = current.executionCursor?.revision ?? 0;\n if (expectedRevision !== undefined && currentRevision !== expectedRevision) {\n throw new Error(`Workflow control revision changed for ${handle.workspace}/${handle.runKey}`);\n }\n const updated: WorkflowRunRecord = {\n ...current,\n executionCursor: executionCursor ?? current.executionCursor,\n executionState,\n };\n await this.writeRunRecord(handle.recordPath, updated);\n return updated;\n }\n\n async updateExecutionCursor(\n handle: WorkflowRunHandle,\n patch: Partial<WorkflowExecutionCursor>,\n ): Promise<WorkflowRunRecord> {\n const current = await this.readRunRecord(handle.recordPath);\n if (current.stage !== RUNNING_STAGE || (current.runId && current.runId !== handle.runId)) {\n throw new Error(`Workflow run is no longer controllable: ${handle.workspace}/${handle.runKey}`);\n }\n const currentCursor =\n current.executionCursor ??\n ({\n executionGeneration: 1,\n phase: 'unknown',\n resumeMode: 'continue-next',\n revision: 0,\n } satisfies WorkflowExecutionCursor);\n const updated: WorkflowRunRecord = {\n ...current,\n executionCursor: {\n ...currentCursor,\n ...patch,\n revision: currentCursor.revision ?? 0,\n },\n };\n await this.writeRunRecord(handle.recordPath, updated);\n return updated;\n }\n\n async clearPauseRequest(handle: WorkflowRunHandle): Promise<void> {\n await this.removeFileIfExists(handle.pauseRequestPath ?? resolve(handle.runDir, PAUSE_REQUEST_FILENAME));\n }\n\n async markFinalizing(handle: WorkflowRunHandle): Promise<void> {\n const current = await this.readRunRecord(handle.recordPath);\n if (current.stage !== RUNNING_STAGE || (current.runId && current.runId !== handle.runId)) {\n throw new Error(`Workflow run is no longer finalizable: ${handle.workspace}/${handle.runKey}`);\n }\n await this.writeAtomic(resolve(handle.runDir, FINALIZING_FILENAME), {\n at: new Date().toISOString(),\n runId: handle.runId,\n });\n }\n\n /**\n * Check whether a workflow run has been asked to stop.\n */\n async hasStopRequest(handle: WorkflowRunHandle): Promise<boolean> {\n try {\n const request = JSON.parse(\n getOrThrow(await this.runtime.fs.readTextFile(handle.stopRequestPath, this.runtime.ioContext)),\n ) as Partial<WorkflowStopRequest>;\n return request.schemaVersion === 1 && request.runId === handle.runId;\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) return false;\n throw error;\n }\n }\n\n private async assertNotFinalizing(handle: WorkflowRunHandle): Promise<void> {\n if (await this.pathExists(resolve(handle.runDir, FINALIZING_FILENAME))) {\n throw new Error(`Workflow is finalizing: ${handle.workspace}/${handle.runKey}`);\n }\n }\n\n private async assertCurrentRun(handle: WorkflowRunHandle): Promise<void> {\n const current = await this.readRunRecord(handle.recordPath);\n if (current.stage !== RUNNING_STAGE || current.runId !== handle.runId) {\n throw new Error(`Workflow run ownership changed: ${handle.workspace}/${handle.runKey}`);\n }\n }\n\n private async getRunningHandle(\n workspace: string | undefined,\n runKey: string,\n expectedRunId: string,\n ): Promise<WorkflowRunHandle> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const runningDir = this.getRunDirectory(resolvedWorkspace, RUNNING_STAGE, resolvedRunKey);\n const recordPath = resolve(runningDir, RUN_RECORD_FILENAME);\n if (!(await this.pathExists(recordPath)))\n throw new Error(`Running workflow not found: ${resolvedWorkspace}/${runKey}`);\n const record = await this.inspectRunningRecord(resolvedWorkspace, resolvedRunKey);\n if (record.stale)\n throw new Error(record.staleReason ?? `Running workflow is stale: ${resolvedWorkspace}/${runKey}`);\n if (!record.runId) throw new Error(`Running workflow has no run ID: ${resolvedWorkspace}/${runKey}`);\n if (record.runId !== expectedRunId) {\n throw new Error(`Workflow run ownership changed: ${resolvedWorkspace}/${runKey}`);\n }\n return {\n changelogPath: resolve(runningDir, CHANGELOG_FILENAME),\n contextPath: resolve(runningDir, CONTEXT_FILENAME),\n displayName: record.displayName,\n pauseRequestPath: resolve(runningDir, PAUSE_REQUEST_FILENAME),\n recordPath,\n runDir: runningDir,\n runId: record.runId,\n runKey: resolvedRunKey,\n stopRequestPath: resolve(runningDir, STOP_REQUEST_FILENAME),\n workspace: resolvedWorkspace,\n };\n }\n\n private async writeAtomic(path: string, value: unknown): Promise<void> {\n await writeFileAtomic(this.runtime.fs, path, `${JSON.stringify(value, null, 2)}\\n`, this.runtime.ioContext);\n }\n\n /** Publish complete JSON without ever exposing a partially written capability. */\n private async writeExclusiveJson(path: string, value: unknown): Promise<void> {\n const tempPath = `${path}.${this.runtime.workflowHost.processId}.${randomUUID()}.tmp`;\n try {\n getOrThrow(\n await this.runtime.fs.writeFile(tempPath, `${JSON.stringify(value, null, 2)}\\n`, this.runtime.ioContext),\n );\n await this.runtime.workflowHost.publishExclusive(tempPath, path);\n } finally {\n await this.removeFileIfExists(tempPath);\n }\n }\n\n private async writeControlRequest(handle: WorkflowRunHandle, path: string, value: unknown): Promise<void> {\n const tempPath = `${path}.${this.runtime.workflowHost.processId}.${randomUUID()}.tmp`;\n try {\n getOrThrow(\n await this.runtime.fs.writeFile(tempPath, `${JSON.stringify(value, null, 2)}\\n`, this.runtime.ioContext),\n );\n await this.assertCurrentRun(handle);\n getOrThrow(await this.runtime.fs.renameFile(tempPath, path, this.runtime.ioContext));\n } catch (error) {\n await this.removeFileIfExists(tempPath);\n throw error;\n }\n }\n\n /**\n * Read a run record from disk.\n */\n async readRunRecord(recordPath: string): Promise<WorkflowRunRecord> {\n try {\n return this.validateRunRecord(\n JSON.parse(getOrThrow(await this.runtime.fs.readTextFile(recordPath, this.runtime.ioContext))),\n recordPath,\n );\n } catch (error) {\n if (error instanceof InvalidWorkflowRunRecordError) {\n throw error;\n }\n\n const reason = error instanceof Error ? error.message : 'Unknown parse failure';\n throw new InvalidWorkflowRunRecordError(recordPath, reason, { cause: error });\n }\n }\n\n /**\n * Claim one terminal failed run for recovery.\n *\n * Exclusive creation is the cross-process compare-and-set: exactly one Pi or\n * CLI process may advance from inspection to replay. The claim file moves\n * with the run directory and is removed when createRun promotes the record.\n */\n async claimRunRecovery(\n workspace: string | undefined,\n runKey: string,\n ownerSessionId?: string,\n ): Promise<WorkflowRecoveryClaim> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const errorDir = this.getRunDirectory(resolvedWorkspace, ERROR_STAGE, resolvedRunKey);\n const recordPath = resolve(errorDir, RUN_RECORD_FILENAME);\n if (!(await this.pathExists(recordPath))) {\n throw new Error(`Workflow run not found: ${resolvedWorkspace}/${ERROR_STAGE}/${runKey}`);\n }\n\n const claim: WorkflowRecoveryClaim = {\n claimId: randomUUID(),\n claimedAt: new Date().toISOString(),\n ownerSessionId: ownerSessionId?.trim() || undefined,\n pid: this.runtime.workflowHost.processId,\n };\n const claimPath = resolve(errorDir, RECOVERY_CLAIM_FILENAME);\n const releaseLock = await this.acquireRecoveryClaimLock(errorDir).catch((error: NodeJS.ErrnoException) => {\n throw new Error(`Workflow recovery is already claimed: ${resolvedWorkspace}/${runKey}`, { cause: error });\n });\n try {\n try {\n await this.writeExclusiveJson(claimPath, claim);\n return claim;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n if (await this.reclaimAbandonedRecoveryClaim(errorDir)) {\n await this.writeExclusiveJson(claimPath, claim);\n return claim;\n }\n throw new Error(`Workflow recovery is already claimed: ${resolvedWorkspace}/${runKey}`, { cause: error });\n }\n } finally {\n await releaseLock();\n }\n }\n\n /**\n * Consume a claim handed from an embedding process to one recovery process.\n *\n * The caller-controlled claim ID is only a capability reference: ownership\n * comes from the pre-existing registry claim. Exclusive adoption prevents\n * replaying the same capability in two launcher processes.\n */\n async adoptRunRecoveryClaim(\n workspace: string | undefined,\n runKey: string,\n claimId: string,\n ): Promise<WorkflowRecoveryClaim> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const errorDir = this.getRunDirectory(resolvedWorkspace, ERROR_STAGE, resolvedRunKey);\n const claimPath = resolve(errorDir, RECOVERY_CLAIM_FILENAME);\n const claim = await this.readRecoveryClaim(claimPath);\n if (claim.claimId !== claimId) {\n throw new Error(`Workflow recovery claim was not authorized: ${resolvedWorkspace}/${runKey}`);\n }\n\n const adoption: WorkflowRecoveryAdoption = {\n adoptedAt: new Date().toISOString(),\n claimId,\n pid: this.runtime.workflowHost.processId,\n };\n const adoptionPath = resolve(errorDir, RECOVERY_ADOPTION_FILENAME);\n const releaseLock = await this.acquireRecoveryClaimLock(errorDir);\n try {\n const current = await this.readRecoveryClaim(claimPath);\n if (current.claimId !== claimId) {\n throw new Error(`Workflow recovery claim changed: ${resolvedWorkspace}/${runKey}`);\n }\n await this.writeExclusiveJson(adoptionPath, adoption);\n return current;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') {\n throw new Error(`Workflow recovery claim is already adopted: ${resolvedWorkspace}/${runKey}`, { cause: error });\n }\n await this.removeFileIfExists(adoptionPath);\n throw error;\n } finally {\n await releaseLock();\n }\n }\n\n /** Release a claim when recovery validation fails before replay starts. */\n async releaseRunRecoveryClaim(workspace: string | undefined, runKey: string, claimId: string): Promise<void> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const claimPath = resolve(\n this.getRunDirectory(resolvedWorkspace, ERROR_STAGE, resolvedRunKey),\n RECOVERY_CLAIM_FILENAME,\n );\n const errorDir = this.getRunDirectory(resolvedWorkspace, ERROR_STAGE, resolvedRunKey);\n const releaseLock = await this.acquireRecoveryClaimLock(errorDir);\n try {\n const current = await this.readRecoveryClaim(claimPath);\n if (current.claimId !== claimId) return;\n const adoptionPath = resolve(errorDir, RECOVERY_ADOPTION_FILENAME);\n try {\n const adoption = JSON.parse(\n getOrThrow(await this.runtime.fs.readTextFile(adoptionPath, this.runtime.ioContext)),\n ) as Partial<WorkflowRecoveryAdoption>;\n if (adoption.claimId === claimId)\n getOrThrow(await this.runtime.fs.remove(adoptionPath, undefined, this.runtime.ioContext));\n } catch (error) {\n if (!['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) throw error;\n }\n getOrThrow(await this.runtime.fs.remove(claimPath, undefined, this.runtime.ioContext));\n } catch (error) {\n if (!['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) throw error;\n } finally {\n await releaseLock();\n }\n }\n\n private async acquireRecoveryClaimLock(errorDir: string): Promise<() => Promise<void>> {\n return await this.lockRecoveryClaim(resolve(errorDir, RUN_RECORD_FILENAME), {\n lockfilePath: `${errorDir}.recovery-claim.lock`,\n realpath: false,\n retries: 0,\n stale: this.recoveryClaimTtlMs,\n });\n }\n\n /** Verify the exact adopted capability before moving error state to running. */\n private async assertRecoveryPromotion(\n errorDir: string,\n workspace: string,\n runKey: string,\n recoveryClaimId?: string,\n ): Promise<void> {\n if (!recoveryClaimId) {\n throw new Error(`Workflow recovery claim is required: ${workspace}/${runKey}`);\n }\n const claim = await this.readRecoveryClaim(resolve(errorDir, RECOVERY_CLAIM_FILENAME));\n if (claim.claimId !== recoveryClaimId) {\n throw new Error(`Workflow recovery claim was not authorized: ${workspace}/${runKey}`);\n }\n let adoption: WorkflowRecoveryAdoption;\n try {\n adoption = await this.readRecoveryAdoption(resolve(errorDir, RECOVERY_ADOPTION_FILENAME));\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) {\n throw new Error(`Workflow recovery claim was not adopted: ${workspace}/${runKey}`, { cause: error });\n }\n throw error;\n }\n if (adoption.claimId !== recoveryClaimId) {\n throw new Error(`Workflow recovery claim was not adopted: ${workspace}/${runKey}`);\n }\n }\n\n /**\n * Reclaim a claim when its launcher lease expired or its claimant died. An\n * adopted claim is protected while its adopting process remains alive.\n */\n private async reclaimAbandonedRecoveryClaim(errorDir: string): Promise<boolean> {\n const adoptionPath = resolve(errorDir, RECOVERY_ADOPTION_FILENAME);\n let deadAdoption: WorkflowRecoveryAdoption | undefined;\n try {\n const adoption = await this.readRecoveryAdoption(adoptionPath);\n if (this.isProcessAlive(adoption.pid)) return false;\n deadAdoption = adoption;\n } catch (error) {\n if (!['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) throw error;\n }\n\n const claimPath = resolve(errorDir, RECOVERY_CLAIM_FILENAME);\n let claim: WorkflowRecoveryClaim;\n try {\n claim = await this.readRecoveryClaim(claimPath);\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) return true;\n throw error;\n }\n if (deadAdoption && deadAdoption.claimId !== claim.claimId) return false;\n\n const claimedAt = Date.parse(claim.claimedAt);\n const expired = !Number.isFinite(claimedAt) || Date.now() - claimedAt >= this.recoveryClaimTtlMs;\n if (!deadAdoption && this.isProcessAlive(claim.pid) && !expired) return false;\n\n try {\n const current = await this.readRecoveryClaim(claimPath);\n if (current.claimId !== claim.claimId) return false;\n getOrThrow(await this.runtime.fs.remove(claimPath, undefined, this.runtime.ioContext));\n if (deadAdoption) await this.removeFileIfExists(adoptionPath);\n return true;\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) return true;\n throw error;\n }\n }\n\n private async readRecoveryClaim(path: string): Promise<WorkflowRecoveryClaim> {\n const value: unknown = JSON.parse(getOrThrow(await this.runtime.fs.readTextFile(path, this.runtime.ioContext)));\n if (!value || typeof value !== 'object') throw new Error(`Invalid workflow recovery claim: ${path}`);\n const claim = value as Partial<WorkflowRecoveryClaim>;\n if (\n typeof claim.claimId !== 'string' ||\n typeof claim.claimedAt !== 'string' ||\n typeof claim.pid !== 'number' ||\n !Number.isInteger(claim.pid) ||\n claim.pid <= 0 ||\n (claim.ownerSessionId !== undefined && typeof claim.ownerSessionId !== 'string')\n ) {\n throw new Error(`Invalid workflow recovery claim: ${path}`);\n }\n return claim as WorkflowRecoveryClaim;\n }\n\n private async readRecoveryAdoption(path: string): Promise<WorkflowRecoveryAdoption> {\n const value: unknown = JSON.parse(getOrThrow(await this.runtime.fs.readTextFile(path, this.runtime.ioContext)));\n if (!value || typeof value !== 'object') throw new Error(`Invalid workflow recovery adoption: ${path}`);\n const adoption = value as Partial<WorkflowRecoveryAdoption>;\n if (\n typeof adoption.claimId !== 'string' ||\n typeof adoption.adoptedAt !== 'string' ||\n typeof adoption.pid !== 'number' ||\n !Number.isInteger(adoption.pid) ||\n adoption.pid <= 0\n ) {\n throw new Error(`Invalid workflow recovery adoption: ${path}`);\n }\n return adoption as WorkflowRecoveryAdoption;\n }\n\n /**\n * Read a workflow run by workspace, stage, and run key.\n */\n async readRunByKey(workspace: string | undefined, stage: WorkflowStage, runKey: string): Promise<WorkflowRunRecord> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const recordPath = resolve(this.getRunDirectory(resolvedWorkspace, stage, resolvedRunKey), RUN_RECORD_FILENAME);\n\n if (!(await this.pathExists(recordPath))) {\n throw new Error(`Workflow run not found: ${resolvedWorkspace}/${stage}/${runKey}`);\n }\n\n return await this.readRunRecord(recordPath);\n }\n\n /**\n * Read a terminal fix.md artifact from a staged run without mutating it.\n */\n async readRunFixContent(workspace: string | undefined, stage: WorkflowStage, runKey: string): Promise<string | null> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const fixPath = resolve(this.getRunDirectory(resolvedWorkspace, stage, resolvedRunKey), FIX_FILENAME);\n\n try {\n return getOrThrow(await this.runtime.fs.readTextFile(fixPath, this.runtime.ioContext));\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Read one durable repair record from a staged workflow run.\n */\n async readRunRepair(\n workspace: string | undefined,\n stage: WorkflowStage,\n runKey: string,\n repairId: string,\n ): Promise<WorkflowRepairRecord> {\n if (!/^\\d+$/.test(repairId)) {\n throw new Error(`Invalid workflow repair ID: ${repairId}`);\n }\n\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const repairPath = resolve(\n this.getRunDirectory(resolvedWorkspace, stage, resolvedRunKey),\n ISSUES_DIRNAME,\n repairId,\n REPAIR_FILENAME,\n );\n const content = getOrThrow(await this.runtime.fs.readTextFile(repairPath, this.runtime.ioContext));\n return WorkflowRepairRecordSchema.parse(JSON.parse(content));\n }\n\n /**\n * Persist the active repair pointer and fix-cycle progress on a running record.\n */\n async updateRepairState(\n handle: WorkflowRunHandle,\n input: WorkflowRegistryRepairStateInput,\n ): Promise<WorkflowRunRecord> {\n const current = await this.readRunRecord(handle.recordPath);\n const updated: WorkflowRunRecord = {\n ...current,\n activeRepairId: input.activeRepairId === null ? undefined : (input.activeRepairId ?? current.activeRepairId),\n fixLoopCycle: input.fixLoopCycle ?? current.fixLoopCycle,\n };\n await this.writeRunRecord(handle.recordPath, updated);\n return updated;\n }\n\n /**\n * List workflow runs across all workspaces or a single workspace.\n */\n async listRuns(workspace?: string): Promise<WorkflowRunRecord[]> {\n const workspaces = workspace ? [this.resolveWorkspace(workspace)] : await this.listWorkspaceNames();\n const records = await Promise.all(workspaces.map(async (workspaceName) => this.listWorkspaceRuns(workspaceName)));\n\n return records.flat().sort((left, right) => this.compareRunRecordsByLatest(left, right));\n }\n\n /**\n * List workflow runs as a stable page sorted by latest activity first.\n */\n async listRunsPage(input: WorkflowRegistryListRunsPageInput = {}): Promise<WorkflowRegistryListRunsPage> {\n const page = input.page ?? DEFAULT_LIST_RUNS_PAGE;\n const pageSize = input.pageSize ?? DEFAULT_LIST_RUNS_PAGE_SIZE;\n const listed = await this.listRuns(input.workspace);\n const runs = input.filter ? listed.filter(input.filter) : listed;\n const total = runs.length;\n const totalPages = Math.ceil(total / pageSize);\n const startIndex = (page - 1) * pageSize;\n const items = runs.slice(startIndex, startIndex + pageSize);\n\n return {\n hasNextPage: page < totalPages,\n hasPreviousPage: page > 1 && total > 0,\n items,\n page,\n pageSize,\n total,\n totalPages,\n };\n }\n\n /**\n * Count live (non-stale) running workflows in a workspace.\n */\n async countRunningWorkflows(workspace: string): Promise<number> {\n const stageDir = this.getRunStageDirectory(workspace, RUNNING_STAGE);\n if (!(await this.pathExists(stageDir))) {\n return 0;\n }\n\n const entries = getOrThrow(await this.runtime.fs.listDir(stageDir, this.runtime.ioContext));\n let alive = 0;\n\n for (const entry of entries) {\n if (entry.kind !== 'directory') {\n continue;\n }\n\n const recordPath = resolve(stageDir, entry.name, RUN_RECORD_FILENAME);\n if (!(await this.pathExists(recordPath))) {\n continue;\n }\n\n try {\n const record = await this.readRunRecord(recordPath);\n if (record.pid && this.isProcessAlive(record.pid)) {\n alive++;\n }\n } catch {\n // Skip unreadable run records.\n }\n }\n\n return alive;\n }\n\n /**\n * Persist every dead running process in a workspace as an interrupted run.\n * The operation is idempotent and is only invoked by an explicit reconcile\n * request or before a new workflow is dispatched.\n */\n async reconcileStaleRuns(workspace?: string): Promise<WorkflowRunRecord[]> {\n const workspaces = workspace ? [this.resolveWorkspace(workspace)] : await this.listWorkspaceNames();\n const reconciled: WorkflowRunRecord[] = [];\n\n for (const workspaceName of workspaces) {\n const stageDir = this.getRunStageDirectory(workspaceName, RUNNING_STAGE);\n if (!(await this.pathExists(stageDir))) {\n continue;\n }\n\n const entries = getOrThrow(await this.runtime.fs.listDir(stageDir, this.runtime.ioContext));\n for (const entry of entries) {\n if (entry.kind !== 'directory') {\n continue;\n }\n\n const recordPath = resolve(stageDir, entry.name, RUN_RECORD_FILENAME);\n if (!(await this.pathExists(recordPath))) {\n continue;\n }\n\n const record = await this.inspectReconcilableRunningRecord(workspaceName, entry.name);\n if (!record) {\n continue;\n }\n const unmovedTerminal = record.stage !== RUNNING_STAGE && !!record.pid && !this.isProcessAlive(record.pid);\n if (record.stale || unmovedTerminal) {\n reconciled.push(await this.reconcileStaleRunningRecord(workspaceName, entry.name));\n }\n }\n }\n\n return reconciled;\n }\n\n /**\n * Ensure the stage directories exist for the workspace.\n */\n private async ensureWorkspaceStructure(workspace: string): Promise<void> {\n getOrThrow(\n await this.runtime.fs.createDir(\n this.getRunStageDirectory(workspace, RUNNING_STAGE),\n { recursive: true },\n this.runtime.ioContext,\n ),\n );\n getOrThrow(\n await this.runtime.fs.createDir(\n this.getRunStageDirectory(workspace, COMPLETED_STAGE),\n { recursive: true },\n this.runtime.ioContext,\n ),\n );\n getOrThrow(\n await this.runtime.fs.createDir(\n this.getRunStageDirectory(workspace, ERROR_STAGE),\n { recursive: true },\n this.runtime.ioContext,\n ),\n );\n }\n\n /**\n * Find the current stage for an existing run key.\n */\n private async findRunStage(workspace: string, runKey: string): Promise<WorkflowStage | null> {\n for (const stage of [RUNNING_STAGE, COMPLETED_STAGE, ERROR_STAGE] as const) {\n if (await this.pathExists(this.getRunDirectory(workspace, stage, runKey))) {\n return stage;\n }\n }\n return null;\n }\n\n /**\n * Read every run record within a workspace's stage directories.\n */\n private async listWorkspaceRuns(workspace: string): Promise<WorkflowRunRecord[]> {\n const records = new Map<string, WorkflowRunRecord>();\n\n for (const stage of [RUNNING_STAGE, COMPLETED_STAGE, ERROR_STAGE] as const) {\n const stageDir = this.getRunStageDirectory(workspace, stage);\n if (!(await this.pathExists(stageDir))) {\n continue;\n }\n\n const entries = getOrThrow(await this.runtime.fs.listDir(stageDir, this.runtime.ioContext));\n for (const entry of entries) {\n if (entry.kind !== 'directory') {\n continue;\n }\n\n const recordPath = resolve(stageDir, entry.name, RUN_RECORD_FILENAME);\n if (!(await this.pathExists(recordPath))) {\n continue;\n }\n\n const record = await this.readListableRunRecord(workspace, stage, entry.name, recordPath);\n if (record) {\n records.set(record.runKey, record);\n }\n }\n }\n\n return [...records.values()];\n }\n\n /**\n * Resolve the run stage, first converting dead running records into\n * interrupted terminal records so reruns are unblocked.\n */\n private async findReusableRunStage(workspace: string, runKey: string): Promise<WorkflowStage | null> {\n const existingStage = await this.findRunStage(workspace, runKey);\n if (existingStage !== RUNNING_STAGE) {\n return existingStage;\n }\n\n await this.reconcileStaleRunningRecord(workspace, runKey);\n return this.findRunStage(workspace, runKey);\n }\n\n /**\n * Read a running record for status displays without mutating it on disk.\n * If the recorded PID is gone, mark the returned record as stale but keep\n * the persisted state untouched so the original failure metadata is not\n * destroyed by a read-only status query.\n */\n private async inspectRunningRecord(workspace: string, runKey: string): Promise<WorkflowRunRecord> {\n const runningRecordPath = resolve(this.getRunDirectory(workspace, RUNNING_STAGE, runKey), RUN_RECORD_FILENAME);\n const currentRecord = await this.readRunRecord(runningRecordPath);\n\n // A terminal stage here means finalization wrote the record but has not\n // moved the directory yet, or died before it could. Either way it is\n // finished, not stale.\n if (currentRecord.stage !== RUNNING_STAGE || !currentRecord.pid || this.isProcessAlive(currentRecord.pid)) {\n return currentRecord;\n }\n\n return {\n ...currentRecord,\n effectiveOutcome: 'interrupted',\n effectiveStage: ERROR_STAGE,\n stale: true,\n staleReason: `${STALE_RUNNING_ERROR_PREFIX}: pid ${currentRecord.pid}`,\n };\n }\n\n /**\n * Read a running record for stale reconciliation. Malformed records cannot\n * be safely converted to terminal records, so they are skipped consistently\n * with list/count operations instead of blocking unrelated workflow runs.\n */\n private async inspectReconcilableRunningRecord(workspace: string, runKey: string): Promise<WorkflowRunRecord | null> {\n try {\n return await this.inspectRunningRecord(workspace, runKey);\n } catch (error) {\n if (error instanceof InvalidWorkflowRunRecordError) {\n return null;\n }\n\n throw error;\n }\n }\n\n /**\n * Read a run record for status listing. Invalid persisted records are\n * skipped explicitly by returning null so callers do not need to suppress\n * exceptions inline.\n */\n private async readListableRunRecord(\n workspace: string,\n stage: WorkflowStage,\n runKey: string,\n recordPath: string,\n ): Promise<WorkflowRunRecord | null> {\n try {\n if (stage === RUNNING_STAGE) return await this.inspectRunningRecord(workspace, runKey);\n const record = await this.readRunRecord(recordPath);\n // Written by versions that renamed before writing the terminal record:\n // the directory is the commit, so its stage wins over the stale field.\n if (record.stage !== RUNNING_STAGE) return record;\n return {\n ...record,\n finishedAt:\n record.finishedAt ??\n new Date(\n getOrThrow(await this.runtime.fs.fileInfo(recordPath, this.runtime.ioContext)).mtimeMs,\n ).toISOString(),\n outcome: record.outcome ?? (stage === COMPLETED_STAGE ? 'success' : 'interrupted'),\n stage,\n };\n } catch (error) {\n if (error instanceof InvalidWorkflowRunRecordError) {\n return null;\n }\n\n throw error;\n }\n }\n\n /**\n * Convert a stale running record into an interrupted error record when its\n * recorded PID is no longer alive.\n */\n private async reconcileStaleRunningRecord(workspace: string, runKey: string): Promise<WorkflowRunRecord> {\n const runningDir = this.getRunDirectory(workspace, RUNNING_STAGE, runKey);\n const runningRecordPath = resolve(runningDir, RUN_RECORD_FILENAME);\n const currentRecord = await this.readRunRecord(runningRecordPath);\n\n if (!currentRecord.pid || this.isProcessAlive(currentRecord.pid)) {\n return currentRecord;\n }\n\n // Finalization already wrote the outcome and died before moving the\n // directory, so finish the move instead of overwriting it as interrupted.\n if (currentRecord.stage !== RUNNING_STAGE) {\n const stageDir = this.getRunDirectory(workspace, currentRecord.stage, runKey);\n await this.removeFileIfExists(resolve(runningDir, FINALIZING_FILENAME));\n getOrThrow(await this.runtime.fs.remove(stageDir, { recursive: true, force: true }, this.runtime.ioContext));\n getOrThrow(await this.runtime.fs.renameFile(runningDir, stageDir, this.runtime.ioContext));\n return currentRecord;\n }\n\n const errorDir = this.getRunDirectory(workspace, ERROR_STAGE, runKey);\n const finalRecord: WorkflowRunRecord = {\n ...currentRecord,\n errorMessage: `${STALE_RUNNING_ERROR_PREFIX}: pid ${currentRecord.pid}`,\n exitCode: INTERRUPTED_EXIT_CODE,\n failedJob: currentRecord.failedJob ?? currentRecord.executionCursor?.job,\n finishedAt: new Date().toISOString(),\n outcome: 'interrupted',\n stage: ERROR_STAGE,\n };\n\n getOrThrow(await this.runtime.fs.remove(errorDir, { recursive: true, force: true }, this.runtime.ioContext));\n getOrThrow(await this.runtime.fs.renameFile(runningDir, errorDir, this.runtime.ioContext));\n await this.writeRunRecord(resolve(errorDir, RUN_RECORD_FILENAME), finalRecord);\n\n return finalRecord;\n }\n\n /**\n * Enumerate known workspace directory names.\n */\n private async listWorkspaceNames(): Promise<string[]> {\n const workspacesDir = resolve(this.homeDir, WORKSPACES_DIRNAME);\n if (!(await this.pathExists(workspacesDir))) {\n return [];\n }\n\n const entries = getOrThrow(await this.runtime.fs.listDir(workspacesDir, this.runtime.ioContext));\n return entries\n .filter((entry) => entry.kind === 'directory')\n .map((entry) => entry.name)\n .sort((left, right) => left.localeCompare(right));\n }\n\n /**\n * Order runs by latest activity across all stages.\n */\n private compareRunRecordsByLatest(left: WorkflowRunRecord, right: WorkflowRunRecord): number {\n const leftTimestamp = left.finishedAt ?? left.startedAt;\n const rightTimestamp = right.finishedAt ?? right.startedAt;\n const timeDifference = rightTimestamp.localeCompare(leftTimestamp);\n if (timeDifference !== 0) {\n return timeDifference;\n }\n\n const workspaceDifference = left.workspace.localeCompare(right.workspace);\n if (workspaceDifference !== 0) {\n return workspaceDifference;\n }\n\n return left.runKey.localeCompare(right.runKey);\n }\n\n /**\n * Persist a run record with stable formatting.\n */\n private async writeRunRecord(recordPath: string, record: WorkflowRunRecord): Promise<void> {\n await this.writeAtomic(recordPath, record);\n }\n\n /**\n * Validate the persisted run record shape before returning it to callers.\n */\n private validateRunRecord(value: unknown, recordPath: string): WorkflowRunRecord {\n const result = WorkflowRunRecordSchema.safeParse(value);\n if (!result.success) {\n throw new InvalidWorkflowRunRecordError(recordPath, result.error.message);\n }\n return result.data;\n }\n\n /**\n * Resolve the directory for a workspace-scoped run stage.\n */\n private getRunStageDirectory(workspace: string, stage: WorkflowStage): string {\n return resolve(this.homeDir, WORKSPACES_DIRNAME, workspace, stage);\n }\n\n /**\n * Resolve the directory for a single run inside a stage.\n */\n private getRunDirectory(workspace: string, stage: WorkflowStage, runKey: string): string {\n return resolve(this.getRunStageDirectory(workspace, stage), runKey);\n }\n\n /**\n * Directory holding a run's artifacts, derived from a listed record.\n *\n * A record carries workspace, stage, and run key but not its own path, so a\n * reader that wants an artifact such as the progress log would otherwise have\n * to reconstruct the layout itself and drift from it.\n */\n runDirectoryFor(record: Pick<WorkflowRunRecord, 'runKey' | 'stage' | 'workspace'>): string {\n return this.getRunDirectory(record.workspace, record.stage, record.runKey);\n }\n\n /**\n * The directory every workspace lives under.\n *\n * Exposed so an observer can watch exactly what this service writes. Deriving\n * it independently would let the two drift, and a watcher pointed at the\n * wrong tree reports nothing rather than failing.\n */\n workspacesDirectory(): string {\n return resolve(this.homeDir, WORKSPACES_DIRNAME);\n }\n\n /**\n * Test whether a path exists while preserving unexpected filesystem errors.\n */\n private async pathExists(path: string): Promise<boolean> {\n try {\n getOrThrow(await this.runtime.fs.fileInfo(path, this.runtime.ioContext));\n return true;\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Remove a file when present without masking other filesystem failures.\n */\n private async removeFileIfExists(path: string): Promise<void> {\n try {\n getOrThrow(await this.runtime.fs.remove(path, undefined, this.runtime.ioContext));\n } catch (error) {\n if (!['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) {\n throw error;\n }\n }\n }\n\n /**\n * Normalize a user-supplied workspace or run name into a safe directory key.\n */\n private slugifySegment(value: string, fallback: string): string {\n const normalized = value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, SLUG_SEPARATOR)\n .replace(/^-+|-+$/g, '');\n\n return normalized || fallback;\n }\n\n /**\n * Check whether a locally tracked process still exists.\n */\n private isProcessAlive(pid: number): boolean {\n try {\n this.runtime.workflowHost.signal(pid, 0);\n return true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ESRCH') {\n return false;\n }\n if (code === 'EPERM') {\n return true;\n }\n throw error;\n }\n }\n}\n","/**\n * Structured error raised when a workspace has reached its maximum concurrent workflow limit.\n */\nexport class WorkflowCapacityError extends Error {\n readonly code = 'WORKFLOW_CAPACITY_EXCEEDED';\n\n constructor(\n public readonly workspace: string,\n public readonly running: number,\n public readonly max: number,\n ) {\n super(\n `Workspace \"${workspace}\" is at capacity: ${running}/${max} workflows running.\\n` +\n ` → Check running workflows: list-workflow-statuses --workspace ${workspace}\\n` +\n ` → Wait for a running workflow to complete, or cancel one before dispatching again.`,\n );\n this.name = 'WorkflowCapacityError';\n }\n}\n","export interface WorkflowInterruptContext {\n phase: string;\n jobName?: string;\n stepName?: string;\n commandPreview?: string;\n source?: string;\n}\n\nexport interface WorkflowInterruptedErrorOptions {\n cause?: unknown;\n context?: WorkflowInterruptContext;\n}\n\n/**\n * Structured interruption error for workflow shutdown paths.\n */\nexport class WorkflowInterruptedError extends Error {\n readonly code = 'WORKFLOW_INTERRUPTED';\n readonly context?: WorkflowInterruptContext;\n\n constructor(\n public readonly signal: NodeJS.Signals,\n options: WorkflowInterruptedErrorOptions = {},\n ) {\n const contextSuffix = options.context ? ` during ${options.context.phase}` : '';\n super(`Workflow interrupted by ${signal}${contextSuffix}`, {\n cause: options.cause ?? options.context,\n });\n this.name = 'WorkflowInterruptedError';\n this.context = options.context;\n }\n}\n","/**\n * BackgroundServiceManager\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { dirname, join, resolve } from 'node:path';\n\nimport { pathExists } from '@agimon-ai/po-core/platform';\n\nimport type { ServiceDef } from '../../schemas/workflowEngine';\nimport type { Logger, RunningService } from '../workflowEngine/type';\nimport { workflowShellOutput } from '../workflowRuntime';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport { escapeShellArg } from '../workflowShell';\n\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\nconst GREEN = '\\x1b[32m';\nconst RED = '\\x1b[31m';\nconst BLUE = '\\x1b[34m';\nconst DEFAULT_HOST = '127.0.0.1';\nconst DEFAULT_ENVIRONMENT = 'development';\nconst WORKSPACE_MARKERS = ['pnpm-workspace.yaml', 'nx.json', '.git'];\n\nasync function resolveWorkspaceRoot(runtime: WorkflowRuntimeContext, startPath: string): Promise<string> {\n let currentDir = resolve(runtime.cwd, startPath);\n\n while (true) {\n for (const marker of WORKSPACE_MARKERS) {\n if (await pathExists(runtime.fs, join(currentDir, marker), runtime.ioContext)) {\n return currentDir;\n }\n }\n\n const parentDir = dirname(currentDir);\n if (parentDir === currentDir) {\n return startPath;\n }\n\n currentDir = parentDir;\n }\n}\n\nexport class BackgroundServiceManager {\n private runningServices: RunningService[] = [];\n constructor(\n private runtime: WorkflowRuntimeContext,\n private logger: Logger,\n ) {}\n\n private resolveWorkingDirectory(service: ServiceDef, workflowDir: string): string {\n return resolve(this.runtime.cwd, workflowDir, service['working-directory'] ?? '');\n }\n\n getRunningServices(): RunningService[] {\n return this.runningServices;\n }\n\n async startService(\n service: ServiceDef,\n baseEnv: Record<string, string>,\n workflowDir: string,\n dryRun: boolean,\n ): Promise<RunningService | null> {\n const command = service.run;\n\n if (dryRun) {\n this.logger.info(` ${BLUE}dry ${RESET} ${service.name}`);\n this.logger.info(` ${DIM}$ ${command}${RESET}`);\n return null;\n }\n\n this.logger.info(` ${BLUE}start${RESET} ${service.name}`);\n this.logger.info(` ${DIM}$ ${command}${RESET}`);\n\n const serviceEnv: Record<string, string> = { ...this.runtime.baseEnvironment, ...baseEnv } as Record<\n string,\n string\n >;\n if (service.env) {\n for (const [key, val] of Object.entries(service.env)) {\n serviceEnv[key] = String(val);\n }\n }\n\n const workDir = this.resolveWorkingDirectory(service, workflowDir);\n const repositoryPath = await resolveWorkspaceRoot(this.runtime, workDir);\n const environment = serviceEnv.NODE_ENV ?? this.runtime.baseEnvironment.NODE_ENV ?? DEFAULT_ENVIRONMENT;\n const host = service.host ?? DEFAULT_HOST;\n let reservedPort: number | undefined;\n\n if (service.port !== undefined || service['port-range']) {\n const portResult = await this.runtime.workflowHost.portRegistry.reservePort({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n preferredPort: service.port,\n portRange: service['port-range'],\n host,\n force: true,\n });\n\n if (!portResult.success || portResult.port === undefined) {\n throw new Error(portResult.error ?? `Failed to reserve port for background service ${service.name}`);\n }\n\n reservedPort = portResult.port;\n serviceEnv.PORT ??= String(reservedPort);\n serviceEnv.SERVICE_PORT ??= String(reservedPort);\n serviceEnv.HOST ??= host;\n serviceEnv.SERVICE_HOST ??= host;\n }\n\n let child: ReturnType<WorkflowRuntimeContext['workflowHost']['spawn']>;\n try {\n child = this.runtime.workflowHost.spawn(command, [], {\n stdio: ['ignore', 'pipe', 'pipe'],\n cwd: workDir,\n env: { ...serviceEnv, FORCE_COLOR: '1' },\n shell: '/bin/zsh',\n detached: true,\n });\n } catch (error) {\n if (reservedPort !== undefined) {\n await this.runtime.workflowHost.portRegistry.releasePort({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n force: true,\n });\n }\n throw error;\n }\n\n if (child.pid === undefined) {\n if (reservedPort !== undefined) {\n await this.runtime.workflowHost.portRegistry.releasePort({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n force: true,\n });\n }\n\n throw new Error(`Failed to spawn background service ${service.name}`);\n }\n\n const prefix = `${BLUE}[${service.name}]${RESET}`;\n child.stdout?.on('data', (data: Buffer) => {\n for (const line of data.toString().split('\\n')) {\n if (line.trim()) this.logger.info(`${prefix} ${line}`);\n }\n });\n child.stderr?.on('data', (data: Buffer) => {\n for (const line of data.toString().split('\\n')) {\n if (line.trim()) this.logger.error(`${prefix} ${line}`);\n }\n });\n\n child.on('error', (err) => {\n this.logger.error(`${prefix} Process error: ${err.message}`);\n });\n\n let release = async () => {\n if (reservedPort !== undefined) {\n await this.runtime.workflowHost.portRegistry.releasePort({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n force: true,\n });\n }\n };\n\n if (child.pid !== undefined) {\n const registerResult = await this.runtime.workflowHost.processRegistry\n .registerProcess({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n pid: child.pid,\n port: reservedPort,\n host: reservedPort !== undefined ? host : undefined,\n command,\n args: [],\n metadata: {\n workingDirectory: workDir,\n readyCheck: service['ready-check'],\n },\n force: true,\n })\n .catch((error: unknown) => ({ success: false, error: error instanceof Error ? error.message : String(error) }));\n\n if (!registerResult.success) {\n try {\n this.runtime.workflowHost.signal(-child.pid, 'SIGTERM');\n } catch {\n child.kill('SIGTERM');\n }\n\n if (reservedPort !== undefined) {\n await this.runtime.workflowHost.portRegistry.releasePort({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n force: true,\n });\n }\n\n throw new Error(registerResult.error ?? `Failed to register process for background service ${service.name}`);\n }\n\n release = async () => {\n const releaseProcessResult = await this.runtime.workflowHost.processRegistry.releaseProcess({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n pid: child.pid,\n kill: true,\n releasePort: true,\n force: true,\n });\n\n if (!releaseProcessResult.success && !releaseProcessResult.error?.includes('No matching process entry')) {\n throw new Error(releaseProcessResult.error ?? `Failed to release ${service.name}`);\n }\n };\n }\n\n const runningSvc: RunningService = { name: service.name, process: child, env: serviceEnv, release };\n this.runningServices.push(runningSvc);\n return runningSvc;\n }\n\n async waitForServiceReady(\n service: ServiceDef,\n workflowDir: string,\n baseEnv: Record<string, string>,\n shouldAbort?: () => boolean,\n ): Promise<boolean> {\n if (!service['ready-check'] || typeof service['ready-check'] !== 'string') return true;\n\n const timeout = (service['ready-timeout'] || 30) * 1000;\n const start = Date.now();\n const checkCmd = service['ready-check'];\n const workDir = this.resolveWorkingDirectory(service, workflowDir);\n const runningService = this.runningServices.find((entry) => entry.name === service.name);\n const readyEnv = runningService?.env ?? ({ ...this.runtime.baseEnvironment, ...baseEnv } as Record<string, string>);\n\n this.logger.info(` ${DIM}wait${RESET} Waiting for ${service.name} to be ready...`);\n\n while (Date.now() - start < timeout) {\n if (shouldAbort?.()) {\n return false;\n }\n\n try {\n await workflowShellOutput(this.runtime, `/bin/zsh -c ${escapeShellArg(checkCmd)}`, {\n cwd: workDir,\n environment: readyEnv,\n timeoutMs: 5000,\n });\n this.logger.info(` ${GREEN}ready${RESET} ${service.name}`);\n return true;\n } catch {\n if (shouldAbort?.()) {\n return false;\n }\n }\n\n await new Promise((resolveDelay) => {\n setTimeout(resolveDelay, 1000);\n });\n }\n\n if (shouldAbort?.()) {\n return false;\n }\n\n this.logger.error(` ${RED}timeout${RESET} ${service.name} not ready after ${service['ready-timeout'] || 30}s`);\n return false;\n }\n\n async stopAll(): Promise<void> {\n if (this.runningServices.length === 0) return;\n\n this.logger.info(`\\n ${BLUE}${BOLD}pre${RESET} ${BOLD}Stopping services${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n for (const svc of this.runningServices) {\n if (!svc.process.killed && svc.process.pid) {\n this.logger.info(` ${DIM}stop${RESET} ${svc.name} (pid ${svc.process.pid})`);\n }\n\n if (svc.release) {\n try {\n await svc.release();\n continue;\n } catch (error) {\n this.logger.warn(\n ` ${RED}warn${RESET} Failed registry cleanup for ${svc.name}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n\n if (!svc.process.killed && svc.process.pid) {\n try {\n this.runtime.workflowHost.signal(-svc.process.pid, 'SIGTERM');\n } catch {\n svc.process.kill('SIGTERM');\n }\n }\n }\n\n this.runningServices = [];\n }\n}\n","import type { PoTraceContext } from '@agimon-ai/po-telemetry';\n\nimport type { Logger } from '../workflowEngine/type';\n\n/** Telemetry belongs to the caller's scope. Exporter failures never change a run's outcome. */\nexport function createWorkflowLogger(baseLogger: Logger): Logger {\n return {\n ...baseLogger,\n async event(...args) {\n try {\n await baseLogger.event?.(...args);\n } catch {\n // The caller owns exporter recovery; workflow execution must continue.\n }\n },\n async flush() {\n try {\n await baseLogger.flush?.();\n } catch {\n // A telemetry outage must not replace the run's result during cleanup.\n }\n },\n };\n}\n\n/** Delegate fallback to PoTelemetry, never retry work after a span error. */\nexport function runWorkflowSpan<T>(\n logger: Logger,\n name: string,\n attributes: Record<string, unknown>,\n work: (context?: PoTraceContext) => Promise<T> | T,\n): Promise<T> {\n return logger.runInSpan ? logger.runInSpan(name, attributes, work) : Promise.resolve().then(() => work());\n}\n","/**\n * JobRunnerService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { dirname, resolve } from 'node:path';\n\nimport { getOrThrow, pathExists } from '@agimon-ai/po-core/platform';\n\nimport type { Job, MatrixEntry, RunDirectory, Step, StepExecutionRef } from '../../schemas/workflowEngine';\nimport { RunDirectoryService } from '../RunDirectoryService';\nimport type { RunDirectoryWrite, StepArtifactSnapshot } from '../RunDirectoryService/types';\nimport {\n stepDecisionInstructions,\n WORKFLOW_DECISION_INSTRUCTIONS_ENV,\n WORKFLOW_RESTART_TARGETS_ENV,\n writeFixRequest,\n} from '../StepDecisionService';\nimport type { StepRunnerService } from '../StepRunnerService';\nimport type { Logger, StepDecisionReport, StepRunOptions } from '../workflowEngine/type';\nimport type { WorkflowParserService } from '../WorkflowParserService';\nimport { WorkflowProgressService } from '../WorkflowProgressService';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport { runWorkflowSpan } from '../workflowTelemetry';\n\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\nconst GREEN = '\\x1b[32m';\nconst YELLOW = '\\x1b[33m';\nconst RED = '\\x1b[31m';\nconst MAGENTA = '\\x1b[35m';\nconst WORKFLOW_JOB_ID_ENV_KEY = 'WORKFLOW_JOB_ID';\nconst WORKFLOW_JOB_NAME_ENV_KEY = 'WORKFLOW_JOB_NAME';\nconst PROCESS_REGISTRY_TAG_ENV_KEY = 'PROCESS_REGISTRY_TAG';\nconst WORKFLOW_FIX_LOOP_DISABLED_ENV_KEY = 'WORKFLOW_FIX_LOOP_DISABLED';\nconst WORKFLOW_ACTIVE_REPAIR_PROMPT_ENV_KEY = 'WORKFLOW_ACTIVE_REPAIR_PROMPT';\n\ntype FixDecision = Extract<StepDecisionReport, { decision: 'fix' }>;\n\n/** Every step a job runs, with parallel groups opened up. */\nfunction jobSteps(job: Job): Step[] {\n return [...(job.preJob?.steps ?? []), ...(job.steps ?? []), ...(job.postJob?.steps ?? [])].flatMap(\n (step) => step.parallel ?? [step],\n );\n}\n\n/**\n * Whether a job's agents still end through fix.md: any job without templated\n * steps, and any with customRun or command-map steps beside them. Only a job\n * whose agents all run templated commands is told to use `workflow-mcp step`\n * alone.\n */\nfunction usesFixFileContract(job: Job): boolean {\n const steps = jobSteps(job);\n const templated = steps.some((step) => Array.isArray(step.interactiveRun));\n const legacyAgent = steps.some(\n (step) =>\n step.customRun !== undefined || (step.interactiveRun !== undefined && !Array.isArray(step.interactiveRun)),\n );\n return !templated || legacyAgent;\n}\n\nfunction envFlagEnabled(value: string | undefined): boolean {\n return ['1', 'true', 'yes', 'on'].includes(\n String(value ?? '')\n .trim()\n .toLowerCase(),\n );\n}\n\n/**\n * The agent step that ends a sequence: the last step, or the last agent step\n * of a parallel group that ends it. A sequence that ends with a script has\n * none, since that script may still write what the job produces.\n */\nfunction finalAgentStep(steps: readonly Step[]): Step | undefined {\n const last = steps.at(-1);\n if (last === undefined) return undefined;\n return ((last.parallel as Step[] | undefined) ?? [last])\n .filter((step) => step.interactiveRun !== undefined || step.customRun !== undefined)\n .at(-1);\n}\n\n/** What one attempt of a job writes: its outputs to hold, and a record after each step. */\ninterface AttemptWrites {\n /** Every entry the job produces. */\n produced: string[];\n /** The outputs this job has yet to write, as they stood when the attempt began. */\n outputs: StepArtifactSnapshot[];\n stepFinished(stepName: string): Promise<void>;\n}\n\n/**\n * Whether this job is the last to have written an entry: its latest record is\n * this job's, from any attempt or earlier run of the job, so nothing else\n * changed it since. A retry, or a job that skips work it already did, keeps\n * its own output; a file another job wrote after it must be written again.\n */\nfunction lastWrittenBy(records: readonly RunDirectoryWrite[], path: string, jobName: string): boolean {\n return records.filter((record) => record.path === path).at(-1)?.job === jobName;\n}\n\n/**\n * The outputs this job is not the last to have written, each with the job and\n * step that wrote it last, as a reason a reader can act on.\n */\nfunction describeUnwritten(\n records: readonly RunDirectoryWrite[],\n jobName: string,\n paths: readonly string[],\n): string | undefined {\n const unwritten = paths.flatMap((path) => {\n if (lastWrittenBy(records, path, jobName)) return [];\n const last = records.filter((record) => record.path === path && record.job !== undefined).at(-1);\n const by = last ? `last written by job \"${last.job}\", step \"${last.step}\"` : 'not written by any step';\n return [`${path} (${by})`];\n });\n return unwritten.length === 0\n ? undefined\n : `job \"${jobName}\" did not write what it produces: ${unwritten.join(', ')}`;\n}\n\nexport class JobRunnerService {\n constructor(\n private runtime: WorkflowRuntimeContext,\n private parser: WorkflowParserService,\n private stepRunner: StepRunnerService,\n private logger: Logger,\n private runDirectoryService = new RunDirectoryService(runtime),\n ) {}\n\n async runJob(\n jobName: string,\n job: Job,\n context: {\n inputs: Map<string, string>;\n secrets: Map<string, string>;\n workflowEnv: Record<string, string>;\n workflowSystemPrompt?: string;\n jobOrder: string[];\n allJobs: Record<string, Job>;\n repairTriage?: boolean;\n activeRepairIssue?: string;\n /** Job that raised the active repair, when this job is inside its scope. */\n activeRepairVerificationJob?: string;\n allowRepairTerminalStop?: boolean;\n /** Fix cycles already raised in this run, and how many the run allows. */\n fixLoop?: { cycle: number; maxCycles: number };\n runDirectory?: RunDirectory;\n /** Why the job failed, when a step decided so; the run reports it instead of a generic reason. */\n onFailed?: (reason: string) => void;\n onPromptAssembled?: (assembly: { jobName: string; matrix: MatrixEntry; prompt: string }) => void;\n },\n options: {\n cliAgent?: string;\n runner?: string;\n dryRun: boolean;\n continueOnError: boolean;\n stopRequestPath?: string;\n workflowDir: string;\n maxRetries: number;\n onStepStarted?: (\n stepName: string,\n index: number,\n total: number,\n matrixIndex?: number,\n attempt?: number,\n ) => Promise<void> | void;\n onExecutionStateChange?: (state: 'paused' | 'resumed', stepName: string) => Promise<void> | void;\n },\n ): Promise<boolean> {\n return runWorkflowSpan(\n this.logger,\n 'workflow.job',\n {\n 'workflow.run.id': context.workflowEnv.WORKFLOW_RUN_ID ?? '',\n 'workflow.job.name': jobName,\n },\n async () => {\n const matrixCombos = this.parser.expandMatrix(job);\n const maxRetries = options.maxRetries;\n\n for (const [matrixIndex, matrix] of matrixCombos.entries()) {\n const jobExecutionId = randomUUID();\n const matrixLabel =\n Object.keys(matrix).length > 0\n ? ` ${DIM}(${Object.entries(matrix)\n .map(([k, v]) => `${k}=${v}`)\n .join(', ')})${RESET}`\n : '';\n\n this.logger.info(`\\n ${MAGENTA}${BOLD}job${RESET} ${BOLD}${jobName}${RESET}${matrixLabel}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n // Merge env: workflow env -> job env\n const jobEnv: Record<string, string> = {\n ...context.workflowEnv,\n [WORKFLOW_JOB_ID_ENV_KEY]: jobExecutionId,\n [WORKFLOW_JOB_NAME_ENV_KEY]: jobName,\n [PROCESS_REGISTRY_TAG_ENV_KEY]: jobExecutionId,\n };\n if (job.env) {\n for (const [key, val] of Object.entries(job.env)) {\n jobEnv[key] = this.parser.interpolate(String(val), {\n inputs: context.inputs,\n matrix,\n secrets: context.secrets,\n env: jobEnv,\n });\n }\n }\n // Run identity belongs to the engine, not job-level overrides.\n for (const key of [\n 'WORKFLOW_RUN_ID',\n 'WORKFLOW_RUN_KEY',\n 'WORKFLOW_RUN_DIR',\n 'WORKFLOW_WORKSPACE',\n 'WORKFLOW_PHASE',\n ]) {\n if (context.workflowEnv[key] !== undefined) jobEnv[key] = context.workflowEnv[key];\n else delete jobEnv[key];\n }\n jobEnv[WORKFLOW_JOB_ID_ENV_KEY] = jobExecutionId;\n jobEnv[WORKFLOW_JOB_NAME_ENV_KEY] = jobName;\n jobEnv[PROCESS_REGISTRY_TAG_ENV_KEY] = jobExecutionId;\n for (const key of [\n 'WORKFLOW_ACTIVE_REPAIR_ID',\n 'WORKFLOW_ACTIVE_REPAIR_DIR',\n 'WORKFLOW_ACTIVE_REPAIR_FILE',\n 'WORKFLOW_ACTIVE_ISSUE_FILE',\n ]) {\n if (context.workflowEnv[key]) {\n jobEnv[key] = context.workflowEnv[key];\n } else {\n delete jobEnv[key];\n }\n }\n if (!context.repairTriage) {\n delete jobEnv[WORKFLOW_ACTIVE_REPAIR_PROMPT_ENV_KEY];\n }\n this.logger.info(` ${DIM}jobid${RESET} ${jobExecutionId}`);\n const fixLoopDisabled = envFlagEnabled(jobEnv[WORKFLOW_FIX_LOOP_DISABLED_ENV_KEY]);\n const fixFileContract = usesFixFileContract(job);\n const currentJobIndex = context.jobOrder.indexOf(jobName);\n const reachedJobs = currentJobIndex >= 0 ? context.jobOrder.slice(0, currentJobIndex + 1) : [jobName];\n if (jobEnv.WORKFLOW_RUN_DIR) {\n // Steps record their outcome with `workflow-mcp step`; these tell them\n // which jobs a fix may restart from, and what to tell their agents.\n const restartTargets = fixLoopDisabled || context.repairTriage ? [] : reachedJobs;\n jobEnv[WORKFLOW_RESTART_TARGETS_ENV] = restartTargets.join(',');\n jobEnv[WORKFLOW_DECISION_INSTRUCTIONS_ENV] = stepDecisionInstructions(\n jobEnv.WORKFLOW_RUN_DIR,\n jobName,\n restartTargets,\n );\n } else {\n delete jobEnv[WORKFLOW_RESTART_TARGETS_ENV];\n delete jobEnv[WORKFLOW_DECISION_INSTRUCTIONS_ENV];\n }\n let runDirectoryGuidance: string | undefined;\n if (jobEnv.WORKFLOW_RUN_DIR) {\n const inspection = await this.runDirectoryService.inspect(jobEnv.WORKFLOW_RUN_DIR, context.runDirectory, {\n jobName,\n jobOrder: context.jobOrder,\n planned: options.dryRun,\n });\n runDirectoryGuidance = this.runDirectoryService.formatInspection(inspection);\n }\n // Which step wrote each declared entry is recorded as each step\n // finishes, so a job that must write an entry is held to its own write,\n // not to one an earlier job made.\n const declaredEntries = context.runDirectory?.entries ?? [];\n const writesRunDir = options.dryRun || declaredEntries.length === 0 ? undefined : jobEnv.WORKFLOW_RUN_DIR;\n const jobStartedAt = Date.now();\n await this.logger.event?.('info', 'workflow.job.started', {\n attributes: this.buildLifecycleAttributes(jobEnv, {\n 'workflow.job.attempt_limit': maxRetries,\n }),\n });\n\n // Inject system-prompt as env var (runner default + workflow-level + job-level)\n const promptParts: string[] = [];\n\n // Runner-level default prompt (fix.md convention + workflow structure)\n if (jobEnv.WORKFLOW_RUN_DIR && !fixLoopDisabled) {\n if (!context.repairTriage && fixFileContract) {\n const jobList = reachedJobs\n .map((name) => {\n const description = context.allJobs[name]?.description ?? 'No description provided.';\n return ` - Job key: ${name}\\n Description: ${description}`;\n })\n .join('\\n');\n\n promptParts.push(\n `You are currently running job \"${jobName}\". Valid repair targets reached so far, including previous jobs and the current job:\\n${jobList}\\n\\nWhen you have completed your task, you MUST either:\\n1. If you find bugs, missing features, or issues that need fixes from a previous job, write to ${jobEnv.WORKFLOW_RUN_DIR}/fix.md with a YAML frontmatter restart-from field specifying which job key listed above should handle the fix, followed by a detailed description. Future jobs that are not listed above are not valid restart targets. Example:\\n---\\nrestart-from: ${jobName}\\n---\\nDescription of what needs to be fixed...\\n\\nThe workflow runner will restart from the specified job. Only create fix.md for issues that require code changes, and fix minor issues yourself.\\n2. Otherwise, stop. Do not continue with unrelated work.`,\n );\n const budget = context.fixLoop\n ? ` This run has raised ${context.fixLoop.cycle} of ${context.fixLoop.maxCycles} allowed fix cycles.`\n : '';\n promptParts.push(\n `fix.md is the only way you can fail this job. Ending your session always counts as success, so a failure written only to a report, a review, or chat is recorded as success.${budget} If this job's result is not acceptable, you MUST write ${jobEnv.WORKFLOW_RUN_DIR}/fix.md, even when you believe the fix budget is exhausted. Do not decide that yourself: the runner counts fix cycles and fails the run with a nonzero exit once the budget is spent. If a failure has no earlier job to repair, use restart-from: ${jobName}.`,\n );\n }\n\n if (\n jobEnv.WORKFLOW_ACTIVE_REPAIR_ID &&\n jobEnv.WORKFLOW_ACTIVE_REPAIR_FILE &&\n jobEnv.WORKFLOW_ACTIVE_ISSUE_FILE\n ) {\n promptParts.push(\n context.repairTriage\n ? `You are triaging pending repair ${jobEnv.WORKFLOW_ACTIVE_REPAIR_ID}. Read the complete repair request from ${jobEnv.WORKFLOW_ACTIVE_ISSUE_FILE} and job tracking from ${jobEnv.WORKFLOW_ACTIVE_REPAIR_FILE}. Use only this repair. Do not scan historical issue folders, and do not edit or delete issue.md or the runner-owned repair.json.`\n : `This job is part of active repair ${jobEnv.WORKFLOW_ACTIVE_REPAIR_ID}. Read the complete repair request from ${jobEnv.WORKFLOW_ACTIVE_ISSUE_FILE} and job tracking from ${jobEnv.WORKFLOW_ACTIVE_REPAIR_FILE} before working. Use only this active repair. Do not scan historical issue folders, and do not edit or delete issue.md or the runner-owned repair.json.`,\n );\n if (context.activeRepairIssue) {\n promptParts.push(`Active repair request:\\n\\n${context.activeRepairIssue}`);\n }\n if (!context.repairTriage && context.activeRepairVerificationJob) {\n const verifierIndex = context.jobOrder.indexOf(context.activeRepairVerificationJob);\n const currentIndex = context.jobOrder.indexOf(jobName);\n const forwardTargets =\n currentIndex >= 0 && verifierIndex > currentIndex\n ? context.jobOrder.slice(currentIndex + 1, verifierIndex + 1)\n : [];\n if (forwardTargets.length > 0) {\n const targetList = forwardTargets\n .map((name) => {\n const description = context.allJobs[name]?.description ?? 'No description provided.';\n return ` - Job key: ${name}\\n Description: ${description}`;\n })\n .join('\\n');\n promptParts.push(\n `This repair replays every job from here to \"${context.activeRepairVerificationJob}\", the job that raised it. If the fix is fully complete and some of those jobs have no work left to do for it, you may skip ahead by writing ${jobEnv.WORKFLOW_RUN_DIR}/proceed.md with this YAML frontmatter:\\n---\\nproceed-to: ${context.activeRepairVerificationJob}\\n---\\nThen explain why the skipped jobs are unnecessary. Valid forward targets:\\n${targetList}\\n\\nUse proceed-to: ${context.activeRepairVerificationJob} to go straight back to the job that raised the fix. Skipped jobs will not run, so their outputs will not be refreshed; skip a job only when you are certain this fix does not change what it would produce. If you are unsure, do not write proceed.md and the workflow continues job by job. If you instead found a new issue, write fix.md — it always takes precedence over proceed.md.`,\n );\n }\n }\n if ((context.repairTriage || context.allowRepairTerminalStop) && fixFileContract) {\n promptParts.push(\n `If this repair cannot proceed because of a proven external blocker, write ${jobEnv.WORKFLOW_RUN_DIR}/fix.md with this YAML frontmatter:\\n---\\nstatus: stop\\n---\\nThen explain the blocker and the evidence. Use status: stop only for a confirmed blocker that cannot be fixed within this workflow run.`,\n );\n }\n if (context.repairTriage && jobEnv.WORKFLOW_ACTIVE_REPAIR_PROMPT) {\n promptParts.push(jobEnv.WORKFLOW_ACTIVE_REPAIR_PROMPT);\n }\n }\n }\n\n if (context.workflowSystemPrompt) {\n promptParts.push(\n this.parser.interpolate(context.workflowSystemPrompt, {\n inputs: context.inputs,\n matrix,\n secrets: context.secrets,\n env: jobEnv,\n }),\n );\n }\n if (runDirectoryGuidance) {\n promptParts.push(runDirectoryGuidance);\n }\n if (job['system-prompt']) {\n promptParts.push(\n this.parser.interpolate(job['system-prompt'], {\n inputs: context.inputs,\n matrix,\n secrets: context.secrets,\n env: jobEnv,\n }),\n );\n }\n if (promptParts.length > 0) {\n const prompt = promptParts.join('\\n\\n');\n jobEnv.JOB_SYSTEM_PROMPT = prompt;\n context.onPromptAssembled?.({ jobName, matrix, prompt });\n this.logger.info(\n ` ${DIM}prompt${RESET} ${prompt.split('\\n')[0].slice(0, 80)}${prompt.includes('\\n') ? '...' : ''}`,\n );\n }\n\n // Load context file content into env var\n const contextPath = job.context\n ? this.parser.interpolate(job.context, {\n inputs: context.inputs,\n matrix,\n secrets: context.secrets,\n env: jobEnv,\n })\n : jobEnv.CONTEXT_FILE;\n\n if (contextPath) {\n const resolvedPath = resolve(this.runtime.cwd, options.workflowDir, contextPath);\n if (await pathExists(this.runtime.fs, resolvedPath, this.runtime.ioContext)) {\n jobEnv.WORKFLOW_CONTEXT = resolvedPath;\n jobEnv.WORKFLOW_CONTEXT_FILE = resolvedPath;\n this.logger.info(` ${DIM}ctx ${RESET} ${contextPath}`);\n } else if (!options.dryRun) {\n this.logger.warn(` ${YELLOW}warn${RESET} context file not found: ${contextPath}`);\n }\n }\n\n // Load or initialize changelog file\n if (jobEnv.CHANGELOG_FILE) {\n const changelogPath = resolve(this.runtime.cwd, options.workflowDir, jobEnv.CHANGELOG_FILE);\n const changelogDir = dirname(changelogPath);\n if (!(await pathExists(this.runtime.fs, changelogDir, this.runtime.ioContext))) {\n getOrThrow(await this.runtime.fs.createDir(changelogDir, { recursive: true }, this.runtime.ioContext));\n }\n if (!(await pathExists(this.runtime.fs, changelogPath, this.runtime.ioContext))) {\n getOrThrow(await this.runtime.fs.writeFile(changelogPath, '# Changelog\\n', this.runtime.ioContext));\n }\n jobEnv.WORKFLOW_CHANGELOG = changelogPath;\n this.logger.info(` ${DIM}log ${RESET} changelog at ${jobEnv.CHANGELOG_FILE}`);\n }\n\n const stepContext = {\n inputs: context.inputs,\n matrix,\n secrets: context.secrets,\n env: jobEnv,\n };\n\n let jobPassed = false;\n const preJobSteps = job.preJob?.steps ?? [];\n const mainSteps = job.steps ?? [];\n const postJobSteps = job.postJob?.steps ?? [];\n\n let decidedFailure: string | undefined;\n let unwrittenOutputs: string | undefined;\n let fixRequested = false;\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n unwrittenOutputs = undefined;\n if (attempt > 1) {\n this.logger.info(\n `\\n ${YELLOW}retry${RESET} ${BOLD}${jobName}${RESET}${matrixLabel} (attempt ${attempt}/${maxRetries})`,\n );\n this.logger.info(` ${'─'.repeat(50)}`);\n }\n\n // A change made outside a step since the last one finished is nobody's write.\n const baseline = writesRunDir\n ? await this.runDirectoryService.recordWrites(writesRunDir, declaredEntries)\n : undefined;\n const writes =\n writesRunDir && baseline\n ? this.attemptWrites(writesRunDir, jobName, jobEnv, baseline, declaredEntries)\n : undefined;\n\n const decisions: StepDecisionReport[] = [];\n let allStepsPassed = true;\n if (preJobSteps.length > 0) {\n allStepsPassed = await this.runStepSequence(\n preJobSteps,\n stepContext,\n options,\n matrixIndex,\n attempt,\n decisions,\n writes && { ...writes, outputs: [] },\n );\n }\n\n if (allStepsPassed && decisions.length === 0) {\n allStepsPassed = await this.runStepSequence(\n mainSteps,\n stepContext,\n options,\n matrixIndex,\n attempt,\n decisions,\n writes,\n );\n }\n\n if (postJobSteps.length > 0) {\n const postJobPassed = await this.runStepSequence(\n postJobSteps,\n stepContext,\n options,\n matrixIndex,\n attempt,\n decisions,\n writes && { ...writes, outputs: [] },\n );\n allStepsPassed = allStepsPassed && postJobPassed;\n }\n\n // The job must be the last to have written every output it produces.\n if (allStepsPassed && decisions.length === 0 && writesRunDir && writes) {\n unwrittenOutputs = describeUnwritten(\n await this.runDirectoryService.readWrites(writesRunDir),\n jobName,\n writes.produced,\n );\n if (unwrittenOutputs) {\n allStepsPassed = false;\n this.logger.error(` ${RED}error${RESET} ${unwrittenOutputs}`);\n await this.logger.event?.('error', 'workflow.job.outputs_unwritten', {\n attributes: this.buildLifecycleAttributes(jobEnv, {\n 'workflow.job.attempt': attempt,\n 'workflow.job.failure_reason': unwrittenOutputs,\n }),\n });\n }\n }\n\n // A step that decided the job cannot finish ends the run: retrying\n // would only repeat the blocker it reported.\n const failure = decisions.find((decision) => decision.decision === 'fail');\n if (failure) {\n decidedFailure = `Step \"${failure.step}\" failed: ${failure.reason}`;\n break;\n }\n\n // Fix requests, from agents and failing restart-from checks alike,\n // become one repair: the job passes and the run loops back once.\n const fixes = decisions.filter((decision): decision is FixDecision => decision.decision === 'fix');\n if (fixes.length > 0) {\n if (!jobEnv.WORKFLOW_RUN_DIR || fixLoopDisabled || options.dryRun) {\n decidedFailure = `Step \"${fixes[0]?.step}\" requested a fix, but this run cannot loop back: ${fixes[0]?.reason}`;\n break;\n }\n const restartFrom = await writeFixRequest(\n this.runtime,\n jobEnv.WORKFLOW_RUN_DIR,\n context.jobOrder,\n jobName,\n fixes,\n );\n this.logger.warn(\n ` ${YELLOW}Job \"${jobName}\" requested ${fixes.length} fix${fixes.length === 1 ? '' : 'es'}; restarting from \"${restartFrom}\"${RESET}`,\n );\n jobPassed = true;\n fixRequested = true;\n break;\n }\n\n if (allStepsPassed) {\n jobPassed = true;\n break;\n }\n\n if (attempt < maxRetries) {\n this.logger.warn(` ${YELLOW}Job \"${jobName}\" failed, retrying...${RESET}`);\n }\n }\n\n if (decidedFailure) {\n context.onFailed?.(decidedFailure);\n this.logger.error(`\\n ${RED}${decidedFailure}${RESET}`);\n }\n\n if (!jobPassed) {\n // The last attempt failed on what it did not write: that is why the job failed.\n if (!decidedFailure && unwrittenOutputs) context.onFailed?.(unwrittenOutputs);\n this.logger.error(`\\n ${RED}Job \"${jobName}\" failed after ${maxRetries} attempts${RESET}`);\n await this.logger.event?.('error', 'workflow.job.finished', {\n attributes: this.buildLifecycleAttributes(jobEnv, {\n 'workflow.job.duration_ms': Date.now() - jobStartedAt,\n 'workflow.job.outcome': 'failed',\n }),\n });\n if (decidedFailure || job.strategy?.['fail-fast'] !== false) {\n return false;\n }\n } else {\n this.logger.info(` ${GREEN}Job \"${jobName}\" completed${RESET}${matrixLabel}`);\n await this.logger.event?.('info', 'workflow.job.finished', {\n attributes: this.buildLifecycleAttributes(jobEnv, {\n 'workflow.job.duration_ms': Date.now() - jobStartedAt,\n 'workflow.job.outcome': fixRequested ? 'fix' : 'success',\n }),\n });\n // The loop back reruns this job, so its remaining matrix entries would\n // only run against the state the fix is about to change.\n if (fixRequested) return true;\n }\n }\n\n return true;\n },\n );\n }\n\n /**\n * An attempt's outputs, taken from the records at its start, and the record\n * each finished step adds. The step that ends the job is reminded only of\n * outputs another job, or no step, wrote last.\n */\n private attemptWrites(\n runDir: string,\n jobName: string,\n env: Record<string, string>,\n baseline: readonly RunDirectoryWrite[],\n entries: RunDirectory['entries'],\n ): AttemptWrites {\n const latest = new Map(baseline.map((record) => [record.path, record]));\n const jobId = env[WORKFLOW_JOB_ID_ENV_KEY];\n const produced = entries.filter((entry) => entry['produced-by']?.includes(jobName));\n return {\n produced: produced.map((entry) => entry.path),\n outputs: produced\n .filter((entry) => !lastWrittenBy(baseline, entry.path, jobName))\n .map((entry) => ({\n path: entry.path,\n kind: entry.kind,\n description: entry.description,\n job: jobName,\n fingerprint: latest.get(entry.path)?.sha,\n mtimeMs: latest.get(entry.path)?.mtimeMs,\n })),\n stepFinished: async (step) => {\n await this.runDirectoryService.recordWrites(runDir, entries, {\n job: jobName,\n step,\n ...(jobId ? { jobId } : {}),\n });\n },\n };\n }\n\n /**\n * Run steps in order, recording each transition.\n *\n * The recorder is built from the environment rather than threaded through the\n * call chain: WORKFLOW_RUN_DIR and the job name are already there for\n * telemetry, and a run without a run directory records nothing.\n */\n private async runStepSequence(\n steps: Job['steps'],\n context: Parameters<StepRunnerService['runStep']>[1],\n options: Parameters<StepRunnerService['runStep']>[2],\n matrixIndex: number,\n attempt: number,\n decisions: StepDecisionReport[],\n writes?: AttemptWrites,\n ): Promise<boolean> {\n const env = context.env ?? {};\n // An agent step that ends the job is reminded of the job's outputs before it\n // stops; a job that ends with a script is only checked once it ends.\n const jobOutputs = writes?.outputs ?? [];\n const outputOwner = jobOutputs.length > 0 ? finalAgentStep(steps) : undefined;\n const optionsFor = (step: Step): StepRunOptions => (step === outputOwner ? { ...options, jobOutputs } : options);\n const progress = new WorkflowProgressService(this.runtime, env.WORKFLOW_RUN_DIR);\n const jobName = env[WORKFLOW_JOB_NAME_ENV_KEY] ?? '';\n const onDecision = (decision: StepDecisionReport) => {\n decisions.push(decision);\n };\n\n for (const [index, step] of steps.entries()) {\n // Unnamed steps are common, so fall back to a stable positional label\n // rather than recording an empty name a reader cannot match up.\n const stepName = step.name ?? `step ${index + 1}`;\n const started = () => options.onStepStarted?.(stepName, index, steps.length, matrixIndex, attempt);\n const ok = step.parallel\n ? await this.runParallelGroup(\n step.parallel,\n stepName,\n started,\n context,\n optionsFor,\n onDecision,\n progress,\n jobName,\n writes?.stepFinished.bind(writes),\n )\n : await this.runTrackedStep(step, stepName, context, optionsFor(step), onDecision, progress, jobName, {\n index,\n total: steps.length,\n started,\n finished: writes?.stepFinished.bind(writes),\n });\n if (!ok) {\n return false;\n }\n // A decided step ends the sequence: a fix reruns these steps after the\n // loop back, and a failure ends the run.\n if (decisions.length > 0) {\n return true;\n }\n }\n\n return true;\n }\n\n /** Run one step, recording its transitions in the run progress log. */\n private async runTrackedStep(\n step: Step,\n stepName: string,\n context: Parameters<StepRunnerService['runStep']>[1],\n options: StepRunOptions,\n onDecision: (decision: StepDecisionReport) => void,\n progress: WorkflowProgressService,\n jobName: string,\n position: {\n index: number;\n total: number;\n group?: string;\n started?: () => Promise<void> | void;\n /** Records what the step wrote, once it ended either way. */\n finished?: (stepName: string) => Promise<void>;\n },\n runner: StepRunnerService = this.stepRunner,\n ): Promise<boolean> {\n await progress.stepStarted(jobName, stepName, position.index, position.total, position.group);\n await position.started?.();\n let failure: string | undefined;\n const stepOptions: StepRunOptions = {\n ...options,\n onDecision,\n onFailure: (reason: string) => {\n failure = reason;\n options.onFailure?.(reason);\n },\n onExecutionStateChange: async (state: 'paused' | 'resumed', pausedStepName: string) => {\n await options.onExecutionStateChange?.(state, pausedStepName);\n await progress.stepFinished(jobName, pausedStepName, state);\n },\n onExecutionStarted: async (ref: StepExecutionRef) => {\n await options.onExecutionStarted?.(ref);\n await progress.stepExecutionStarted(jobName, stepName, ref);\n },\n };\n const ok = await runner.runStep(step, context, stepOptions);\n await position.finished?.(stepName);\n await progress.stepFinished(jobName, stepName, ok ? 'completed' : 'failed', ok ? undefined : failure);\n return ok;\n }\n\n /**\n * Run a parallel group: every step at once, each on a runner of its own.\n *\n * No step is cancelled when another fails, so every fix request of the\n * group is collected and one loop back fixes them all. An interruption is\n * rethrown once every step has settled.\n */\n private async runParallelGroup(\n steps: Step[],\n groupName: string,\n started: () => Promise<void> | void,\n context: Parameters<StepRunnerService['runStep']>[1],\n optionsFor: (step: Step) => StepRunOptions,\n onDecision: (decision: StepDecisionReport) => void,\n progress: WorkflowProgressService,\n jobName: string,\n finished?: (stepName: string) => Promise<void>,\n ): Promise<boolean> {\n // The execution cursor names the group; the progress log names each step.\n await started();\n const results = await Promise.allSettled(\n steps.map(async (step, index) => {\n const stepName = step.name ?? `${groupName} ${index + 1}`;\n const runner = this.stepRunner.fork(stepName);\n try {\n return await this.runTrackedStep(\n { ...step, name: stepName },\n stepName,\n context,\n optionsFor(step),\n onDecision,\n progress,\n jobName,\n { index, total: steps.length, group: groupName, finished },\n runner,\n );\n } finally {\n this.stepRunner.release(runner);\n }\n }),\n );\n const interrupted = results.find((result) => result.status === 'rejected');\n if (interrupted) throw interrupted.reason;\n return results.every((result) => result.status === 'fulfilled' && result.value);\n }\n\n private buildLifecycleAttributes(\n env: Record<string, string>,\n attributes: Record<string, string | number | boolean>,\n ): Record<string, string | number | boolean> {\n return {\n 'workflow.id': env.WORKFLOW_ID ?? '',\n 'workflow.name': env.WORKFLOW_NAME ?? '',\n 'workflow.workspace': env.WORKFLOW_WORKSPACE ?? '',\n 'workflow.run.id': env.WORKFLOW_RUN_ID ?? '',\n 'workflow.run.key': env.WORKFLOW_RUN_KEY ?? '',\n 'workflow.phase': env.WORKFLOW_PHASE ?? 'job',\n 'workflow.job.id': env[WORKFLOW_JOB_ID_ENV_KEY] ?? '',\n 'workflow.job.name': env[WORKFLOW_JOB_NAME_ENV_KEY] ?? '',\n ...(env.WORKFLOW_ACTIVE_REPAIR_ID ? { 'workflow.repair.id': env.WORKFLOW_ACTIVE_REPAIR_ID } : {}),\n ...attributes,\n };\n }\n}\n","export interface WorkflowStepSpawnContext {\n commandPreview: string;\n source: string;\n stepName: string;\n workDir: string;\n}\n\nexport interface WorkflowStepSpawnErrorOptions {\n cause?: unknown;\n}\n\n/**\n * Structured error raised when a workflow step cannot be spawned.\n */\nexport class WorkflowStepSpawnError extends Error {\n readonly code = 'WORKFLOW_STEP_SPAWN_FAILED';\n\n constructor(\n public readonly context: WorkflowStepSpawnContext,\n options: WorkflowStepSpawnErrorOptions = {},\n ) {\n super(`Failed to start workflow step \"${context.stepName}\"`, {\n cause: options.cause ?? context,\n });\n this.name = 'WorkflowStepSpawnError';\n }\n}\n","export interface WorkflowStepTimeoutConfigContext {\n stepName: string;\n configKey: string;\n timeoutValue: unknown;\n}\n\nexport interface WorkflowStepTimeoutConfigErrorOptions {\n cause?: unknown;\n}\n\n/**\n * Structured error raised when a timeout-related config field is malformed for a workflow step.\n */\nexport class WorkflowStepTimeoutConfigError extends Error {\n readonly code = 'WORKFLOW_STEP_TIMEOUT_CONFIG_INVALID';\n\n constructor(\n public readonly context: WorkflowStepTimeoutConfigContext,\n options: WorkflowStepTimeoutConfigErrorOptions = {},\n ) {\n super(`Invalid ${context.configKey} for workflow step \"${context.stepName}\"`, {\n cause: options.cause ?? context,\n });\n this.name = 'WorkflowStepTimeoutConfigError';\n }\n}\n","import { z } from 'zod';\n\nconst STEP_TIMEOUT_MAX_RETRIES = 2;\nconst STEP_TIMEOUT_RETRIES_LIMIT = 10;\nconst MINUTE_IN_MS = 60_000;\nconst MAX_TIMEOUT_DELAY_MS = 2_147_483_647;\nconst MAX_STEP_TIMEOUT_MINUTES = Math.floor(MAX_TIMEOUT_DELAY_MS / MINUTE_IN_MS);\n\nexport const StepTimeoutMinutesSchema = z.number().positive().finite().max(MAX_STEP_TIMEOUT_MINUTES);\nexport const StepTimeoutRetriesSchema = z\n .number()\n .int()\n .min(0)\n .max(STEP_TIMEOUT_RETRIES_LIMIT)\n .default(STEP_TIMEOUT_MAX_RETRIES);\n","/**\n * CodexQuotaService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n * - Document complex logic with comments\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { join } from 'node:path';\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\n\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nconst DEFAULT_CODEX_HOME_DIRNAME = '.codex';\nconst AUTH_FILENAME = 'auth.json';\nconst CONFIG_FILENAME = 'config.toml';\nconst DEFAULT_CHATGPT_BASE_URL = 'https://chatgpt.com/backend-api/';\nconst CHATGPT_HOST = 'https://chatgpt.com';\nconst CHAT_OPENAI_HOST = 'https://chat.openai.com';\nconst BACKEND_API_SEGMENT = '/backend-api';\nconst QUOTA_USER_AGENT = 'codex-cli';\nconst PRIMARY_WINDOW = 'primary' as const;\nconst SECONDARY_WINDOW = 'secondary' as const;\nconst QUOTA_REACHED_PERCENT = 100;\n\ninterface CodexAuthFile {\n tokens?: {\n access_token?: string;\n account_id?: string;\n };\n}\n\ninterface CodexQuotaWindowPayload {\n limit_window_seconds?: number;\n reset_after_seconds?: number;\n reset_at?: number;\n used_percent?: number;\n}\n\ninterface CodexQuotaLimitPayload {\n allowed?: boolean;\n limit_reached?: boolean;\n primary_window?: CodexQuotaWindowPayload;\n secondary_window?: CodexQuotaWindowPayload;\n}\n\ninterface CodexAdditionalQuotaPayload {\n limit_name?: string;\n metered_feature?: string;\n rate_limit?: CodexQuotaLimitPayload;\n}\n\ninterface CodexQuotaResponsePayload {\n additional_rate_limits?: CodexAdditionalQuotaPayload[];\n plan_type?: string;\n rate_limit?: CodexQuotaLimitPayload;\n}\n\ntype CodexQuotaWindowKind = typeof PRIMARY_WINDOW | typeof SECONDARY_WINDOW;\n\nexport interface CodexQuotaBlock {\n limitId: string;\n limitName: string;\n resetAfterSeconds: number | null;\n resetAt: number;\n usedPercent: number;\n window: CodexQuotaWindowKind;\n windowSeconds: number | null;\n}\n\nexport interface CodexQuotaStatus {\n blockingLimit: CodexQuotaBlock | null;\n planType: string | null;\n}\n\nexport interface CodexQuotaServiceDeps {\n codexHome?: string;\n fetchFn?: typeof fetch;\n now?: () => number;\n readTextFile?: (path: string) => Promise<string>;\n}\n\nexport class CodexQuotaService {\n private readonly codexHome: string;\n\n private readonly fetchFn: typeof fetch;\n\n private readonly now: () => number;\n\n private readonly readTextFile: (path: string) => Promise<string>;\n\n constructor(runtime: WorkflowRuntimeContext, deps: CodexQuotaServiceDeps = {}) {\n this.codexHome =\n deps.codexHome ?? runtime.baseEnvironment.CODEX_HOME ?? join(runtime.homeDirectory, DEFAULT_CODEX_HOME_DIRNAME);\n this.fetchFn = deps.fetchFn ?? fetch;\n this.now = deps.now ?? (() => Date.now());\n this.readTextFile =\n deps.readTextFile ?? (async (path: string) => getOrThrow(await runtime.fs.readTextFile(path, runtime.ioContext)));\n }\n\n isCodexCommand(command: string, _sourceAgentKey?: string): boolean {\n const trimmed = command.trim();\n return trimmed === 'codex' || trimmed.startsWith('codex ');\n }\n\n async getQuotaStatus(): Promise<CodexQuotaStatus | null> {\n const auth = await this.readAuthFile();\n const accessToken = auth?.tokens?.access_token?.trim();\n const accountId = auth?.tokens?.account_id?.trim();\n\n if (!accessToken || !accountId) {\n return null;\n }\n\n const baseUrl = await this.readChatgptBaseUrl();\n const response = await this.fetchFn(this.buildUsageUrl(baseUrl), {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'ChatGPT-Account-Id': accountId,\n 'User-Agent': QUOTA_USER_AGENT,\n },\n });\n\n if (!response.ok) {\n throw new Error(`codex quota request failed with HTTP ${response.status}`);\n }\n\n const payload = (await response.json()) as CodexQuotaResponsePayload;\n return {\n blockingLimit: this.findBlockingLimit(payload),\n planType: payload.plan_type ?? null,\n };\n }\n\n private async readAuthFile(): Promise<CodexAuthFile | null> {\n const raw = await this.readOptionalTextFile(join(this.codexHome, AUTH_FILENAME));\n if (!raw) {\n return null;\n }\n\n return JSON.parse(raw) as CodexAuthFile;\n }\n\n private async readChatgptBaseUrl(): Promise<string> {\n const config = await this.readOptionalTextFile(join(this.codexHome, CONFIG_FILENAME));\n const match = config?.match(/^\\s*chatgpt_base_url\\s*=\\s*\"([^\"]+)\"/m);\n return this.normalizeBaseUrl(match?.[1] ?? DEFAULT_CHATGPT_BASE_URL);\n }\n\n private buildUsageUrl(baseUrl: string): string {\n return baseUrl.includes(BACKEND_API_SEGMENT) ? `${baseUrl}/wham/usage` : `${baseUrl}/api/codex/usage`;\n }\n\n private normalizeBaseUrl(baseUrl: string): string {\n let normalized = baseUrl.trim().replace(/\\/+$/, '');\n if (\n (normalized.startsWith(CHATGPT_HOST) || normalized.startsWith(CHAT_OPENAI_HOST)) &&\n !normalized.includes(BACKEND_API_SEGMENT)\n ) {\n normalized = `${normalized}${BACKEND_API_SEGMENT}`;\n }\n\n return normalized;\n }\n\n private async readOptionalTextFile(path: string): Promise<string | null> {\n try {\n return await this.readTextFile(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n\n throw error;\n }\n }\n\n private findBlockingLimit(payload: CodexQuotaResponsePayload): CodexQuotaBlock | null {\n const blocks: CodexQuotaBlock[] = [];\n\n this.collectBlockingLimit(blocks, 'codex', 'codex', payload.rate_limit);\n\n for (const additionalLimit of payload.additional_rate_limits ?? []) {\n this.collectBlockingLimit(\n blocks,\n additionalLimit.metered_feature ?? additionalLimit.limit_name ?? 'codex',\n additionalLimit.limit_name ?? additionalLimit.metered_feature ?? 'codex',\n additionalLimit.rate_limit,\n );\n }\n\n blocks.sort((left, right) => left.resetAt - right.resetAt || right.usedPercent - left.usedPercent);\n return blocks[0] ?? null;\n }\n\n private collectBlockingLimit(\n blocks: CodexQuotaBlock[],\n limitId: string,\n limitName: string,\n limit: CodexQuotaLimitPayload | undefined,\n ): void {\n if (!limit) {\n return;\n }\n\n const windows: Array<{\n payload: CodexQuotaWindowPayload | undefined;\n window: CodexQuotaWindowKind;\n }> = [\n { payload: limit.primary_window, window: PRIMARY_WINDOW },\n { payload: limit.secondary_window, window: SECONDARY_WINDOW },\n ];\n\n for (const { payload, window } of windows) {\n const resetAt = payload?.reset_at;\n const usedPercent = payload?.used_percent ?? 0;\n if (typeof resetAt !== 'number') {\n continue;\n }\n\n const isBlocked =\n usedPercent >= QUOTA_REACHED_PERCENT ||\n (limit.limit_reached === true && resetAt * 1000 > this.now()) ||\n (limit.allowed === false && resetAt * 1000 > this.now());\n\n if (!isBlocked) {\n continue;\n }\n\n blocks.push({\n limitId,\n limitName,\n resetAfterSeconds: payload?.reset_after_seconds ?? null,\n resetAt,\n usedPercent,\n window,\n windowSeconds: payload?.limit_window_seconds ?? null,\n });\n }\n }\n}\n","import type { ChildProcess } from 'node:child_process';\n/**\n * StepRunnerService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\nimport { randomUUID } from 'node:crypto';\nimport { dirname, join, resolve } from 'node:path';\n\nimport { getOrThrow, pathExists, writeFileAtomic } from '@agimon-ai/po-core/platform';\n\nimport { type WorkflowInterruptContext, WorkflowInterruptedError } from '../../models/WorkflowInterruptedError';\nimport { WorkflowStepSpawnError } from '../../models/WorkflowStepSpawnError';\nimport { WorkflowStepTimeoutConfigError } from '../../models/WorkflowStepTimeoutConfigError';\nimport type {\n CommandRef,\n CustomRun,\n CustomRunEntry,\n RunConfig,\n Step,\n StepCommand,\n Workflow,\n} from '../../schemas/workflowEngine';\nimport { StepTimeoutMinutesSchema, StepTimeoutRetriesSchema } from '../../schemas/workflowStepTimeout';\nimport { CodexQuotaService, type CodexQuotaStatus } from '../CodexQuotaService';\nimport { RunDirectoryService } from '../RunDirectoryService';\nimport { type StepArtifactSnapshot } from '../RunDirectoryService/types';\nimport {\n createDecisionFile,\n newDecisionFilePath,\n readStepDecision,\n stepDecisionInstructions,\n resetDecisionFile,\n WORKFLOW_DECISION_FILE_ENV,\n WORKFLOW_DECISION_INSTRUCTIONS_ENV,\n WORKFLOW_RESTART_TARGETS_ENV,\n} from '../StepDecisionService';\nimport type {\n InterpolationContext,\n Logger,\n ResolvedCustomRun,\n StepCommandTemplate,\n StepExecution,\n StepExecutor,\n StepRunOptions,\n} from '../workflowEngine/type';\nimport { choiceSettings, commandTemplateOf, type WorkflowParserService } from '../WorkflowParserService';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport { runWorkflowSpan } from '../workflowTelemetry';\n\nconst RESET = '\\x1b[0m';\nconst DIM = '\\x1b[2m';\nconst CYAN = '\\x1b[36m';\nconst GREEN = '\\x1b[32m';\nconst YELLOW = '\\x1b[33m';\nconst RED = '\\x1b[31m';\nconst INTERRUPT_EXIT_CODE = 130;\nconst TERMINATE_EXIT_CODE = 143;\nconst INTERRUPT_SIGNAL: NodeJS.Signals = 'SIGINT';\nconst HANGUP_SIGNAL: NodeJS.Signals = 'SIGHUP';\nconst TERMINATE_SIGNAL: NodeJS.Signals = 'SIGTERM';\nconst DEFAULT_STEP_NAME = 'unnamed';\nconst DEFAULT_SHELL = '/bin/zsh';\nconst FORCE_COLOR_KEY = 'FORCE_COLOR';\nconst FORCE_COLOR_VALUE = '1';\nconst PROJECT_PATH_ENV_KEY = 'PROJECT_PATH';\nconst UNKNOWN_EXIT_CODE = 1;\nconst STDIO_INHERIT = 'inherit';\nconst STDIO_PIPE = 'pipe';\nconst STDIO_IGNORE = 'ignore';\nconst COMMAND_LINE_BREAK = '\\n';\nconst COMMAND_LOG_INDENT = ' ';\nconst COMMAND_LOG_PROMPT = '$ ';\nconst COMMAND_LOG_CONTINUATION = `${COMMAND_LINE_BREAK}${COMMAND_LOG_INDENT}${COMMAND_LOG_PROMPT}`;\nconst STEP_EXECUTION_PHASE = 'step_execution';\nconst STEP_RUNNER_SOURCE = 'StepRunnerService.runStep';\nconst STEP_RUNNER_EXECUTE_SOURCE = 'StepRunnerService.executeCommand';\nconst STATUS_SKIP = 'skip';\nconst STATUS_WARN = 'warn';\nconst STATUS_DRY = 'dry ';\nconst STATUS_RUN = 'run ';\nconst STATUS_ERROR = 'error';\nconst STATUS_PASS = 'pass';\nconst STATUS_FAIL = 'fail';\nconst STATUS_INTERRUPTED = 'interrupted';\nconst STATUS_WAIT = 'wait ';\nconst NO_ACTIVE_STEP_MESSAGE = 'no active step to stop';\nconst ALREADY_STOPPING_SUFFIX = 'already stopping';\nconst FAILED_TO_SIGNAL_MESSAGE = 'failed to signal';\nconst FAILED_TO_CLEANUP_PROCESS_GROUP_MESSAGE = 'failed to clean up process group for';\nconst UNSUPPORTED_ACTION_PREFIX = 'Unsupported action:';\nconst UNSUPPORTED_ACTION_SUFFIX = '(skipped)';\nconst CONTINUE_ON_ERROR_SUFFIX = '(continue-on-error)';\nconst SPAWN_FAILURE_PREFIX = 'unable to start step';\nconst SPAWN_ERROR_FALLBACK_HINT = 'check shell availability, PATH, and permissions';\nconst SPAWN_ERROR_RECOVERY_HINT = 'verify command, shell, and permissions';\nconst STEP_EXIT_FAILURE_PREFIX = 'step';\nconst STEP_EXIT_FAILURE_MIDDLE = 'exited with code';\nconst STEP_TIMEOUT_FAILURE_PREFIX = 'step timed out after';\nconst STEP_TIMEOUT_FORCE_KILL_SUFFIX = 'forcing SIGKILL';\nconst PLATFORM_WINDOWS = 'win32';\nconst ESRCH_ERROR_CODE = 'ESRCH';\nconst RUN_KEY = 'run';\nconst INTERACTIVE_RUN_KEY = 'interactiveRun';\nconst CUSTOM_RUN_KEY = 'customRun';\nconst CUSTOM_RUN_UNSUPPORTED_MESSAGE =\n 'customRun needs a host step executor and no run or interactiveRun fallback exists for step';\nconst WORKFLOW_RUN_CONFIG_ENV_KEY = 'WORKFLOW_RUN_CONFIG';\nconst DEFAULT_CHOICE = 'default';\nconst OUTPUT_TAIL_LINES = 50;\n\n/** Whether a customRun keyed by runner has an entry of its own for this runner. */\nfunction customRunNames(customRun: CustomRun | undefined, runner: string | undefined): boolean {\n if (customRun === undefined || runner === undefined) return false;\n if (typeof (customRun as { prompt?: unknown }).prompt === 'string') return false;\n return Object.hasOwn(customRun, runner);\n}\n\n/**\n * The customRun entry a runner runs: the one entry of a plain customRun, the\n * runner's own entry of a runner map, or the map's first entry for a runner it\n * does not name, the way a command map falls back to its first command.\n */\n/** Resolves once a child's piped output has ended, or after OUTPUT_DRAIN_TIMEOUT_MS. */\nfunction outputDrained(child: ChildProcess): Promise<void> {\n const ended = (stream: NodeJS.ReadableStream | null): Promise<void> =>\n !stream || (stream as { readableEnded?: boolean }).readableEnded\n ? Promise.resolve()\n : new Promise((resolveEnded) => {\n stream.once('end', () => resolveEnded());\n stream.once('close', () => resolveEnded());\n stream.once('error', () => resolveEnded());\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolveTimeout) => {\n timer = setTimeout(resolveTimeout, OUTPUT_DRAIN_TIMEOUT_MS);\n });\n return Promise.race([Promise.all([ended(child.stdout), ended(child.stderr)]).then(() => {}), timeout]).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/** A logger whose lines name the parallel step they came from. */\nfunction labelledLogger(logger: Logger, label: string): Logger {\n const prefix = `${DIM}[${label}]${RESET} `;\n return {\n info: (message: string) => logger.info(`${prefix}${message}`),\n error: (message: string) => logger.error(`${prefix}${message}`),\n warn: (message: string) => logger.warn(`${prefix}${message}`),\n ...(logger.event ? { event: logger.event.bind(logger) } : {}),\n ...(logger.flush ? { flush: logger.flush.bind(logger) } : {}),\n ...(logger.runInSpan ? { runInSpan: logger.runInSpan.bind(logger) } : {}),\n };\n}\n\nfunction firstLine(text: string): string {\n return text.split(COMMAND_LINE_BREAK)[0] ?? '';\n}\n\n/** A step command in its legacy string or runner-map form; a templated list is resolved elsewhere. */\nfunction legacyCommand(command: StepCommand | CommandRef[] | undefined): StepCommand | undefined {\n return Array.isArray(command) ? undefined : command;\n}\n\nfunction customRunEntry(customRun: CustomRun, runner: string | undefined): CustomRunEntry | undefined {\n if (typeof (customRun as { prompt?: unknown }).prompt === 'string') return customRun as CustomRunEntry;\n const entries = customRun as Record<string, CustomRunEntry>;\n return (runner === undefined ? undefined : entries[runner]) ?? Object.values(entries)[0];\n}\nconst INTERACTIVE_OUTPUT_NOTICE = '(interactive: output renders directly to terminal)';\nconst STEP_TIMEOUT_MINUTES_KEY = 'timeout-minutes';\nconst STEP_TIMEOUT_RETRIES_KEY = 'timeout-retries';\nconst STATUS_RETRY = 'retry';\nconst STEP_TIMEOUT_RETRY_PREFIX = 'retrying step after timeout';\nconst TERMINATE_FORCE_KILL_SIGNAL: NodeJS.Signals = 'SIGKILL';\nconst FORCE_KILL_GRACE_PERIOD_MS = 1_000;\nconst PROCESS_EXIT_POLL_INTERVAL_MS = 50;\nconst PROCESS_EXIT_WAIT_TIMEOUT_MS = 1_000;\n/**\n * How long a finished step's output may still arrive. A child can exit before\n * its piped output is read; a background process that keeps the pipe open\n * must not hold the step past this.\n */\nconst OUTPUT_DRAIN_TIMEOUT_MS = 500;\nconst STEP_COMPLETION_KILL_GRACE_MS_ENV_KEY = 'WORKFLOW_STEP_FORCE_KILL_GRACE_MS';\n// SIGTERM→SIGKILL grace on the completion path (status file signalled `YES`).\n// Deliberately longer than the 1s timeout-path grace so an interactive agent can\n// flush its final telemetry batch (e.g. Claude Code OTEL Stop-hook events) before\n// SIGKILL. A fast graceful exit still settles immediately, so this only adds\n// latency when a child lingers. Operator-tunable via the env key above.\nconst STEP_COMPLETION_KILL_GRACE_MS = 5_000;\n// Interactive teardown re-walks the process tree every round so descendants\n// spawned or re-parented after an earlier snapshot are still reaped. The grace\n// budget per signal phase is operator-tunable but defaults to today's value so\n// ordinary steps see no behaviour change.\nconst INTERACTIVE_REAP_ROUND_INTERVAL_MS = 100;\nconst INTERACTIVE_PROCESS_TRACK_INTERVAL_MS = 1_000;\nconst INTERACTIVE_KILL_GRACE_MS_ENV_KEY = 'WORKFLOW_INTERACTIVE_KILL_GRACE_MS';\nconst WORKFLOW_RUN_DIR_ENV_KEY = 'WORKFLOW_RUN_DIR';\nconst INTERACTIVE_REAP_LOG_FILENAME = 'interactive-reap.json';\nconst PAUSE_REQUEST_FILENAME = 'pause-request.json';\nconst RUN_RECORD_FILENAME = 'run.json';\nconst INTERACTIVE_REAP_LOG_MAX_ENTRIES = 50;\nconst MINUTE_IN_MS = 60_000;\nconst TIMEOUT_UNIT_MILLISECONDS = 'ms';\nconst TIMEOUT_UNIT_MINUTES = 'minute(s)';\nconst STATUS_FILE_ENV_KEY = 'WORKFLOW_STATUS_FILE';\nconst WORKFLOW_JOB_NAME_ENV_KEY = 'WORKFLOW_JOB_NAME';\nconst WORKFLOW_STEP_NAME_ENV_KEY = 'WORKFLOW_STEP_NAME';\nconst WORKFLOW_STEP_DISPLAY_ENV_KEY = 'WORKFLOW_STEP_DISPLAY';\nconst WORKFLOW_STEP_ARTIFACTS_ENV_KEY = 'WORKFLOW_STEP_ARTIFACTS';\nconst WORKFLOW_TERMINAL_TITLE = 'workflow-mcp';\nconst STATUS_FILE_PREFIX = 'workflow-step-';\nconst STATUS_FILE_SUFFIX = '.status';\nconst STATUS_FILE_COMPLETION_VALUE = 'YES';\nconst STATUS_FILE_COMPLETED_RESULT: StepExecutionResult = { status: 'status_completed' };\nconst TRANSIENT_FS_ERROR_CODES = new Set(['ENOENT', 'EBUSY', 'EAGAIN', 'EPERM', 'not_found']);\nconst STATUS_FILE_POLL_INTERVAL_MS = 1_000;\nconst STOP_REQUEST_POLL_INTERVAL_MS = 1_000;\nconst STATUS_DONE = 'done';\nconst STATUS_STOP = 'stop';\nconst EXPLICIT_RUNNER_MISSING_PREFIX = 'runner';\nconst EXPLICIT_RUNNER_MISSING_MIDDLE = 'not found for step';\nconst EXPLICIT_RUNNER_AVAILABLE_PREFIX = 'available runner keys:';\nconst QUOTA_WAIT_POLL_INTERVAL_MS = 30_000;\nconst QUOTA_WAIT_RESET_BUFFER_MS = 1_000;\nconst QUOTA_WAIT_SOURCE = 'StepRunnerService.waitForCodexQuota';\nconst QUOTA_RETRY_REASON = 'codex quota reached after failed step, retrying after reset';\nconst RESULT_STATUS_COMPLETED = 'completed' as const;\nconst RESULT_STATUS_SPAWN_ERROR = 'spawn_error' as const;\nconst RESULT_STATUS_SIGNALED = 'signaled' as const;\nconst RESULT_STATUS_TIMED_OUT = 'timed_out' as const;\nconst RESULT_STATUS_STATUS_COMPLETED = 'status_completed' as const;\nconst RESULT_STATUS_STOP_REQUESTED = 'stop_requested' as const;\nconst RESULT_STATUS_PAUSE_REQUESTED = 'pause_requested' as const;\n\n/**\n * Normalized child-process termination states used by `runStep`.\n */\ntype StepExecutionResult =\n // `failure` is why a host execution failed, when it said so, in place of an exit code.\n | { status: 'completed'; exitCode: number; outputTail?: string; failure?: string }\n | { status: 'pause_requested'; survivors?: InteractiveProcessReport[] }\n | { status: 'spawn_error'; error: WorkflowStepSpawnError }\n | { status: 'signaled'; signal: NodeJS.Signals }\n | { status: 'timed_out'; timeoutMs: number }\n | { status: 'status_completed' }\n | { status: 'stop_requested' };\n\n/** Why the step being run failed, filled in by the step as it fails. */\ninterface StepFailureReport {\n reason?: string;\n}\n\n/** The reason a step failure carries when nothing more specific was recorded. */\nconst STEP_FAILED_REASON = 'The step failed.';\n\n/**\n * Snapshot of the currently running step process for cancellation.\n */\ninterface ActiveStepExecution {\n command: string;\n interactive: boolean;\n lastSignaledProcessIds: number[];\n process: ChildProcess;\n processGroupId: number | null;\n rootProcessId: number | null;\n stepName: string;\n trackedProcessGroupIds: number[];\n trackedProcessIds: number[];\n}\n\n/**\n * A step a host executor owns. `stopSignal` records the first stop request so\n * a later escalation is not sent twice and the outcome reads as a termination.\n */\ninterface ActiveExternalExecution {\n execution: StepExecution;\n stepName: string;\n stopSignal: NodeJS.Signals | null;\n}\n\ninterface ProcessTreeEntry {\n depth: number;\n pid: number;\n}\n\ninterface InteractiveProcessReport {\n pid: number;\n command: string;\n}\n\ninterface InteractiveReapResult {\n survivors: InteractiveProcessReport[];\n sigkillEscalated: boolean;\n}\n\ntype InteractiveCompletionSource =\n | 'status-file'\n | 'stop-request'\n | 'pause-request'\n | 'natural-exit'\n | 'timed-out'\n | 'signaled'\n | 'spawn-error';\n\n/**\n * Forensic record written once per interactive run so a session that fails to\n * exit is self-diagnosing: it captures how completion was signalled and which\n * processes (with their command) survived termination.\n */\ninterface InteractiveCompletionRecord {\n timestamp: string;\n stepName: string;\n statusFilePath: string;\n completionSource: InteractiveCompletionSource;\n statusFileSignaled: boolean;\n sigkillEscalated: boolean;\n survivors: InteractiveProcessReport[];\n}\n\n/**\n * What a launch selected for templated interactiveRun steps: the workflow's\n * command templates and choices, and the `--command` and `--choice` it named.\n */\nexport interface CommandTemplateSelection {\n commands?: Workflow['commands'];\n choices?: Workflow['choices'];\n command?: string;\n choice?: string;\n}\n\ninterface ResolvedStepCommand {\n agentKey?: string;\n command: string;\n /** Set for a templated interactiveRun: the structured values the command was rendered from. */\n template?: StepCommandTemplate;\n /** Why a templated interactiveRun could not be rendered; the step fails with it. */\n templateError?: string;\n /** Set when a host executor runs the step's `customRun`; `command` is then only a label. */\n custom?: ResolvedCustomRun;\n /** Effective settings: step, selected entry, then the applicable choice settings. */\n runConfig?: RunConfig;\n missingRunner?: {\n availableKeys: string[];\n runner: string;\n };\n interactive: boolean;\n}\n\ninterface ActiveQuotaWait {\n controller: AbortController;\n signal: NodeJS.Signals | null;\n stepName: string;\n}\n\n/**\n * Executes workflow steps in child processes and tracks the active process so\n * the workflow runner can interrupt it safely.\n *\n * Runtime configuration:\n * - Environment precedence is `runtime.baseEnvironment` -> workflow/job env -> step env.\n * - Child commands run through `/bin/zsh` to match local workflow execution.\n * - `FORCE_COLOR=1` is injected so tool output keeps ANSI formatting.\n */\nexport class StepRunnerService {\n private activeStep: ActiveStepExecution | null = null;\n private activeExternal: ActiveExternalExecution | null = null;\n private lastInteractiveReap: InteractiveReapResult | null = null;\n private interruptedSignal: NodeJS.Signals | null = null;\n\n private activeQuotaWait: ActiveQuotaWait | null = null;\n private commandSelection: CommandTemplateSelection = {};\n /** Runners of a parallel group's steps, which a stop must reach too. */\n private forks = new Set<StepRunnerService>();\n /** Shared by a runner and its forks: one engine-spawned interactive step owns the terminal at a time. */\n private terminalLock: { tail: Promise<void> } = { tail: Promise.resolve() };\n\n /**\n * Create a step runner bound to the workflow parser and shared logger.\n *\n * `ownsTerminal` is false when the runner is embedded in a host that owns the\n * terminal itself, which is the Pi extension: there stdin is the TUI's\n * keyboard and stdout is its screen. A runner that does not own the terminal\n * must not hand a step's stdin to it, and must not `stty` or reset it\n * afterwards, however cooperative the intent.\n */\n constructor(\n private runtime: WorkflowRuntimeContext,\n private parser: WorkflowParserService,\n private logger: Logger,\n private quotaService: Pick<CodexQuotaService, 'getQuotaStatus' | 'isCodexCommand'> = new CodexQuotaService(runtime),\n private watchStatusFile = runtime.fs.watch.bind(runtime.fs),\n private runDirectoryService = new RunDirectoryService(runtime),\n private ownsTerminal = true,\n private stepExecutor?: StepExecutor,\n ) {}\n\n /**\n * Use a workflow's command templates and choices, and what the launch\n * selected, for the templated interactiveRun steps this runner starts.\n * Called again whenever the workflow file is re-read.\n */\n useCommandTemplates(selection: CommandTemplateSelection): void {\n this.commandSelection = selection;\n }\n\n /**\n * A runner for one step of a parallel group. It shares this runner's\n * collaborators, command selection and terminal, and has its own active\n * step, so group members run side by side and a stop reaches each of them.\n * Release it once its step has finished.\n */\n fork(label: string): StepRunnerService {\n const child = new StepRunnerService(\n this.runtime,\n this.parser,\n labelledLogger(this.logger, label),\n this.quotaService,\n this.watchStatusFile,\n this.runDirectoryService,\n this.ownsTerminal,\n this.stepExecutor,\n );\n child.commandSelection = this.commandSelection;\n child.interruptedSignal = this.interruptedSignal;\n child.terminalLock = this.terminalLock;\n this.forks.add(child);\n return child;\n }\n\n release(child: StepRunnerService): void {\n this.forks.delete(child);\n }\n\n /**\n * Clear a previous workflow's shutdown state before starting a new run.\n */\n resetInterruption(): void {\n this.interruptedSignal = null;\n }\n\n /**\n * Stop the active step process during workflow shutdown.\n */\n stopActiveStep(signal: NodeJS.Signals): void {\n this.interruptedSignal = signal;\n if (this.forks.size > 0) {\n for (const child of this.forks) child.stopActiveStep(signal);\n return;\n }\n if (this.activeQuotaWait) {\n if (this.activeQuotaWait.controller.signal.aborted) {\n this.logger.info(\n ` ${DIM}${STATUS_SKIP}${RESET} ${this.activeQuotaWait.stepName} ${ALREADY_STOPPING_SUFFIX}`,\n );\n return;\n }\n\n this.activeQuotaWait.signal = signal;\n this.activeQuotaWait.controller.abort();\n this.logger.info(\n ` ${YELLOW}${STATUS_INTERRUPTED}${RESET} cancelling quota wait for ${this.activeQuotaWait.stepName}`,\n );\n return;\n }\n\n if (this.activeExternal) {\n if (this.activeExternal.stopSignal) {\n this.logger.info(\n ` ${DIM}${STATUS_SKIP}${RESET} ${this.activeExternal.stepName} ${ALREADY_STOPPING_SUFFIX}`,\n );\n return;\n }\n this.logger.info(\n ` ${YELLOW}${STATUS_INTERRUPTED}${RESET} stopping ${this.activeExternal.stepName} (${signal})`,\n );\n this.stopExternal(this.activeExternal, signal);\n return;\n }\n\n if (!this.activeStep) {\n this.logger.info(` ${DIM}${STATUS_SKIP}${RESET} ${NO_ACTIVE_STEP_MESSAGE}`);\n return;\n }\n\n if (this.activeStep.process.killed) {\n this.logger.info(` ${DIM}${STATUS_SKIP}${RESET} ${this.activeStep.stepName} ${ALREADY_STOPPING_SUFFIX}`);\n return;\n }\n\n this.logger.info(` ${YELLOW}${STATUS_INTERRUPTED}${RESET} sending ${signal} to ${this.activeStep.stepName}`);\n const killRequested = this.killActiveStep(signal);\n if (!killRequested) {\n this.logger.warn(` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_SIGNAL_MESSAGE} ${this.activeStep.stepName}`);\n }\n }\n\n /**\n * Execute a single workflow step and stream its output to the workflow logger.\n *\n * The runner interpolates the final command before execution, resolves the\n * working directory relative to the workflow root, and merges step-scoped\n * environment variables over the inherited process environment.\n */\n async runStep(step: Step, context: InterpolationContext, options: StepRunOptions): Promise<boolean> {\n const report: StepFailureReport = {};\n const ok = await this.executeStep(step, context, options, report);\n if (!ok) options.onFailure?.(report.reason ?? STEP_FAILED_REASON);\n return ok;\n }\n\n /**\n * Run one step. Each cause of a failure is logged through `fail`, which also\n * keeps it on `report`, so the step's failure carries its reason to the job's\n * progress log and telemetry instead of existing only as a log line.\n */\n private async executeStep(\n step: Step,\n context: InterpolationContext,\n options: StepRunOptions,\n report: StepFailureReport,\n ): Promise<boolean> {\n const fail = (reason: string): void => {\n this.logger.error(` ${RED}${STATUS_ERROR}${RESET} ${reason}`);\n report.reason = reason;\n };\n if (step.customRun) step = { ...step, runConfig: this.customRunChoiceConfig(step.runConfig) };\n const stepContext: InterpolationContext = step.runConfig ? { ...context, runConfig: step.runConfig } : context;\n const runner = this.resolveRunner(options);\n // A job step may record its outcome with `workflow-mcp step`, and a\n // templated agent step must. Its decision file is placed first so the\n // step's instructions can name it; outside jobs nothing routes a decision.\n const decisionRunDir = stepContext.env[WORKFLOW_RUN_DIR_ENV_KEY];\n const plannedDecisionFile =\n stepContext.env[WORKFLOW_DECISION_INSTRUCTIONS_ENV] !== undefined && decisionRunDir && !options.dryRun\n ? newDecisionFilePath(decisionRunDir)\n : undefined;\n const resolvedStepCommand = this.resolveStepCommand(step, stepContext, runner, plannedDecisionFile);\n const stepName = step.name\n ? this.parser.interpolate(step.name, stepContext)\n : resolvedStepCommand?.command.slice(0, 60) || step.uses || DEFAULT_STEP_NAME;\n\n if (this.interruptedSignal) {\n throw new WorkflowInterruptedError(this.interruptedSignal, {\n cause: new Error(`Workflow interrupted before step started: ${stepName}`),\n context: this.createInterruptContext(stepName, resolvedStepCommand?.command ?? ''),\n });\n }\n\n if (step.uses) {\n const action = this.parser.interpolate(step.uses, stepContext);\n if (this.parser.isActionSkipped(action)) {\n this.logger.info(` ${DIM}${STATUS_SKIP}${RESET} ${action}`);\n return true;\n }\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${UNSUPPORTED_ACTION_PREFIX} ${action} ${UNSUPPORTED_ACTION_SUFFIX}`,\n );\n return true;\n }\n\n if (!resolvedStepCommand) {\n if (!step.customRun) return true;\n // A step that only a host can run must not pass by doing nothing.\n fail(`${CUSTOM_RUN_UNSUPPORTED_MESSAGE} \"${stepName}\"`);\n if (step['continue-on-error'] || options.continueOnError) {\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n return false;\n }\n\n if (resolvedStepCommand.missingRunner) {\n fail(\n `${EXPLICIT_RUNNER_MISSING_PREFIX} \"${resolvedStepCommand.missingRunner.runner}\" ${EXPLICIT_RUNNER_MISSING_MIDDLE} \"${stepName}\" (${EXPLICIT_RUNNER_AVAILABLE_PREFIX} ${resolvedStepCommand.missingRunner.availableKeys.join(', ')})`,\n );\n if (step['continue-on-error'] || options.continueOnError) {\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n return false;\n }\n\n if (resolvedStepCommand.templateError) {\n fail(`step \"${stepName}\": ${resolvedStepCommand.templateError}`);\n if (step['continue-on-error'] || options.continueOnError) {\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n return false;\n }\n\n const { command, custom, interactive, template } = resolvedStepCommand;\n const isCodexCommand = this.quotaService.isCodexCommand(command, resolvedStepCommand.agentKey);\n const shouldContinue = step['continue-on-error'] || options.continueOnError;\n let timeoutMs: number | null;\n try {\n timeoutMs = this.resolveTimeoutMs(step, stepName);\n } catch (error) {\n if (!(error instanceof WorkflowStepTimeoutConfigError)) {\n throw error;\n }\n\n fail(`invalid ${error.context.configKey} for \"${stepName}\": ${String(error.context.timeoutValue)}`);\n if (shouldContinue) {\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n return false;\n }\n\n const workDir = step['working-directory']\n ? resolve(this.runtime.cwd, options.workflowDir, this.parser.interpolate(step['working-directory'], stepContext))\n : resolve(this.runtime.cwd, options.workflowDir);\n const stepEnv: NodeJS.ProcessEnv = { ...this.runtime.baseEnvironment, ...stepContext.env };\n if (step.env) {\n for (const [key, val] of Object.entries(step.env)) {\n stepEnv[key] = this.parser.interpolate(String(val), stepContext);\n }\n }\n // YAML cannot retarget the run whose capabilities this step receives.\n for (const key of [\n 'WORKFLOW_RUN_ID',\n 'WORKFLOW_RUN_KEY',\n 'WORKFLOW_RUN_DIR',\n 'WORKFLOW_WORKSPACE',\n 'WORKFLOW_PHASE',\n 'WORKFLOW_JOB_ID',\n 'WORKFLOW_JOB_NAME',\n ]) {\n if (stepContext.env[key] !== undefined) stepEnv[key] = stepContext.env[key];\n else delete stepEnv[key];\n }\n // A globally hosted workflow-mcp can execute another checkout. Pin every\n // nested MCP runtime to the checkout containing this step, not the host cwd.\n stepEnv[PROJECT_PATH_ENV_KEY] = workDir;\n stepEnv[WORKFLOW_STEP_NAME_ENV_KEY] = stepName;\n stepEnv[WORKFLOW_STEP_DISPLAY_ENV_KEY] = this.formatStepDisplay(stepEnv[WORKFLOW_JOB_NAME_ENV_KEY], stepName);\n const runConfig = resolvedStepCommand?.runConfig ?? step.runConfig;\n // An explicit empty payload clears stale preferences inherited from the host.\n stepEnv[WORKFLOW_RUN_CONFIG_ENV_KEY] = JSON.stringify(runConfig ?? {});\n if (step.if !== undefined && !options.dryRun) {\n const condition = await this.evaluateStepCondition(step.if, stepContext, workDir, stepEnv, stepName, timeoutMs);\n if (!condition.run) {\n if (condition.error) fail(condition.error);\n return condition.error ? Boolean(shouldContinue) : true;\n }\n }\n // What an agent step is held to before it stops: its own artifacts, updated\n // during the step, and, when it ends its job, the job's outputs, written\n // during the job's attempt.\n let artifactSnapshots: StepArtifactSnapshot[] | undefined;\n const jobOutputs = interactive || custom ? (options.jobOutputs ?? []) : [];\n if ((interactive || custom) && ((step.artifacts?.length ?? 0) > 0 || jobOutputs.length > 0)) {\n const runDir = stepEnv[WORKFLOW_RUN_DIR_ENV_KEY];\n if (!runDir) {\n fail(`step \"${stepName}\" declares artifacts but WORKFLOW_RUN_DIR is unavailable`);\n return false;\n }\n const artifactPaths = (step.artifacts ?? []).map((path) => this.parser.interpolate(path, stepContext));\n const stepSnapshots =\n artifactPaths.length > 0 ? await this.runDirectoryService.snapshotStepArtifacts(runDir, artifactPaths) : [];\n const own = new Set(stepSnapshots.map((snapshot) => snapshot.path));\n const described = stepSnapshots.map((snapshot) => {\n const description = jobOutputs.find((output) => output.path === snapshot.path)?.description;\n return description === undefined ? snapshot : { ...snapshot, description };\n });\n artifactSnapshots = [...described, ...jobOutputs.filter((output) => !own.has(output.path))];\n stepEnv[WORKFLOW_STEP_ARTIFACTS_ENV_KEY] = JSON.stringify(artifactSnapshots);\n }\n // A step that must record a decision gets a decision file, and so does one\n // that must leave artifacts: the gate counts its reminders there, and its\n // presence is what turns on the agents' stop hooks. Steps outside a run\n // get neither, and a stray inherited one is dropped.\n const decisionIdentity =\n plannedDecisionFile !== undefined\n ? {\n job: stepContext.env[WORKFLOW_JOB_NAME_ENV_KEY] ?? '',\n step: stepName,\n restartTargets: (stepContext.env[WORKFLOW_RESTART_TARGETS_ENV] ?? '').split(',').filter(Boolean),\n required: template !== undefined,\n }\n : artifactSnapshots !== undefined && decisionRunDir && !options.dryRun\n ? {\n job: stepContext.env[WORKFLOW_JOB_NAME_ENV_KEY] ?? '',\n step: stepName,\n restartTargets: [],\n required: false,\n }\n : undefined;\n let decisionFilePath: string | undefined;\n if (decisionIdentity && decisionRunDir) {\n decisionFilePath = await createDecisionFile(this.runtime, decisionRunDir, decisionIdentity, plannedDecisionFile);\n stepEnv[WORKFLOW_DECISION_FILE_ENV] = decisionFilePath;\n } else {\n delete stepEnv[WORKFLOW_DECISION_FILE_ENV];\n delete stepEnv[WORKFLOW_DECISION_INSTRUCTIONS_ENV];\n delete stepEnv[WORKFLOW_RESTART_TARGETS_ENV];\n }\n\n const stepStartedAt = Date.now();\n await this.logStepLifecycle('info', 'workflow.step.started', stepEnv, {\n 'workflow.step.interactive': interactive,\n });\n\n // Only provision a status file for interactive steps (Claude Code / Codex agents).\n // Plain run: steps (e.g. pnpm install) must not receive a status file — a Stop\n // hook fired from an unrelated Claude session must not be able to kill them.\n let statusFilePath: string | undefined;\n if (interactive) {\n statusFilePath = await this.createStatusFile();\n stepEnv[STATUS_FILE_ENV_KEY] = statusFilePath;\n this.logger.info(` ${DIM}status-file${RESET} ${statusFilePath}`);\n } else {\n // Drop any status file inherited from a parent runner/agent so a foreign Stop hook\n // cannot signal completion of this plain run: step.\n delete stepEnv[STATUS_FILE_ENV_KEY];\n }\n\n if (options.dryRun) {\n this.logger.info(` ${CYAN}${STATUS_DRY}${RESET} ${stepName}`);\n this.logger.info(\n `${COMMAND_LOG_INDENT}${DIM}${COMMAND_LOG_PROMPT}${command.split(COMMAND_LINE_BREAK).join(COMMAND_LOG_CONTINUATION)}${RESET}`,\n );\n await this.logStepLifecycle('info', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'dry-run',\n });\n return true;\n }\n\n const pausePolicy = step['pause-policy'] ?? 'replay';\n const pauseRequestPath = options.stopRequestPath\n ? join(dirname(options.stopRequestPath), PAUSE_REQUEST_FILENAME)\n : undefined;\n if (pauseRequestPath && (await this.readControlAction(pauseRequestPath)) === 'pause') {\n if (options.stopRequestPath && (await this.hasCurrentStopRequest(options.stopRequestPath))) {\n throw new WorkflowInterruptedError(TERMINATE_SIGNAL, {\n cause: new Error(`Workflow stop requested before pause acknowledgement for \"${stepName}\"`),\n context: this.createInterruptContext(stepName, command),\n });\n }\n await this.markPaused(options.stopRequestPath, stepName, pausePolicy);\n await options.onExecutionStateChange?.('paused', stepName);\n await this.waitForResume(options.stopRequestPath, stepName);\n await options.onExecutionStateChange?.('resumed', stepName);\n }\n\n let maxTimeoutRetries: number;\n try {\n maxTimeoutRetries = this.resolveTimeoutRetries(step, stepName);\n } catch (error) {\n if (!(error instanceof WorkflowStepTimeoutConfigError)) {\n throw error;\n }\n\n fail(`invalid ${error.context.configKey} for \"${stepName}\": ${String(error.context.timeoutValue)}`);\n if (shouldContinue) {\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n return false;\n }\n\n let quotaFailureRetried = false;\n for (let attempt = 0; attempt <= maxTimeoutRetries; attempt++) {\n await this.waitForCodexQuotaAvailability(stepName, command, isCodexCommand);\n if (decisionFilePath && decisionIdentity)\n await resetDecisionFile(this.runtime, decisionFilePath, decisionIdentity);\n\n if (attempt > 0) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_RETRY}${RESET} ${STEP_TIMEOUT_RETRY_PREFIX} \"${stepName}\" (attempt ${attempt + 1}/${maxTimeoutRetries + 1})`,\n );\n } else {\n this.logger.info(` ${CYAN}${STATUS_RUN}${RESET} ${stepName}`);\n }\n this.logger.info(\n `${COMMAND_LOG_INDENT}${DIM}${COMMAND_LOG_PROMPT}${command.split(COMMAND_LINE_BREAK)[0]}${command.includes(COMMAND_LINE_BREAK) ? ' ...' : ''}${RESET}`,\n );\n\n if (options.stopRequestPath && (await this.hasCurrentStopRequest(options.stopRequestPath))) {\n this.logger.info(`\\n ${YELLOW}${STATUS_INTERRUPTED}${RESET} ${stepName} (${STATUS_STOP})`);\n throw new WorkflowInterruptedError(TERMINATE_SIGNAL, {\n cause: new Error(`Workflow stop requested before \"${stepName}\"`),\n context: this.createInterruptContext(stepName, command),\n });\n }\n\n const executionPromise = runWorkflowSpan(\n this.logger,\n 'workflow.step.attempt',\n {\n 'workflow.run.id': stepEnv.WORKFLOW_RUN_ID ?? '',\n 'workflow.job.name': stepEnv.WORKFLOW_JOB_NAME ?? stepEnv.WORKFLOW_PHASE ?? '',\n 'workflow.step.name': stepName,\n 'workflow.step.attempt': attempt + 1,\n },\n (trace) =>\n this.startStepExecution({\n traceparent: trace?.traceparent,\n command,\n custom,\n interactive,\n onExecutionStarted: options.onExecutionStarted,\n runConfig,\n stepEnv,\n stepName,\n jobEnvironment: this.definedEnv({ ...this.runtime.baseEnvironment, ...stepContext.env }),\n attempt: attempt + 1,\n template,\n timeoutMs,\n workDir,\n }),\n );\n\n const executionResult =\n interactive && statusFilePath\n ? await this.raceInteractiveCompletion(\n executionPromise,\n statusFilePath,\n stepName,\n options.stopRequestPath,\n step['pause-policy'] ?? 'replay',\n )\n : options.stopRequestPath\n ? await this.raceStopRequest(\n executionPromise,\n stepName,\n options.stopRequestPath,\n step['pause-policy'] ?? 'replay',\n )\n : await executionPromise;\n\n if (executionResult.status === RESULT_STATUS_PAUSE_REQUESTED) {\n await this.logStepLifecycle('info', 'workflow.step.pause_requested', stepEnv, {\n 'workflow.step.outcome': pausePolicy === 'replay' ? 'cancelled_for_pause' : 'protected_boundary',\n 'workflow.step.pause_policy': pausePolicy,\n });\n await this.markPaused(options.stopRequestPath, stepName, pausePolicy, executionResult.survivors);\n await options.onExecutionStateChange?.('paused', stepName);\n await this.waitForResume(options.stopRequestPath, stepName);\n await options.onExecutionStateChange?.('resumed', stepName);\n if (pausePolicy === 'protected') return true;\n await this.logStepLifecycle('info', 'workflow.step.replay', stepEnv, {\n 'workflow.step.outcome': 'replay-current',\n });\n attempt -= 1;\n continue;\n }\n\n if (executionResult.status === 'stop_requested') {\n this.logger.info(`\\n ${YELLOW}${STATUS_INTERRUPTED}${RESET} ${stepName} (${STATUS_STOP})`);\n throw new WorkflowInterruptedError(TERMINATE_SIGNAL, {\n cause: new Error(`Workflow stop requested during \"${stepName}\"`),\n context: this.createInterruptContext(stepName, command),\n });\n }\n\n if (executionResult.status === 'signaled') {\n this.logger.info(`\\n ${YELLOW}${STATUS_INTERRUPTED}${RESET} ${stepName}`);\n throw new WorkflowInterruptedError(executionResult.signal, {\n cause: new Error(`Step process ended with ${executionResult.signal}`),\n context: this.createInterruptContext(stepName, command),\n });\n }\n\n if (\n executionResult.status === 'completed' &&\n (executionResult.exitCode === INTERRUPT_EXIT_CODE || executionResult.exitCode === TERMINATE_EXIT_CODE)\n ) {\n const interruptSignal = executionResult.exitCode === INTERRUPT_EXIT_CODE ? INTERRUPT_SIGNAL : TERMINATE_SIGNAL;\n this.logger.info(`\\n ${YELLOW}${STATUS_INTERRUPTED}${RESET} ${stepName}`);\n throw new WorkflowInterruptedError(interruptSignal, {\n cause: new Error(`Step process exited with ${executionResult.exitCode}`),\n context: this.createInterruptContext(stepName, command),\n });\n }\n\n if (executionResult.status === 'spawn_error') {\n fail(\n `${SPAWN_FAILURE_PREFIX} \"${stepName}\" in ${executionResult.error.context.workDir} (${this.formatSpawnError(\n executionResult.error,\n )})`,\n );\n if (shouldContinue) {\n await this.logStepLifecycle('warn', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'continued',\n });\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n await this.logStepLifecycle('error', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'failed',\n 'workflow.step.failure_reason': report.reason ?? '',\n });\n return false;\n }\n\n // A recorded decision is the step's outcome however the agent ended:\n // stopped by its hook, exited, or ran out of time after deciding.\n const decision = decisionFilePath ? await readStepDecision(this.runtime, decisionFilePath) : undefined;\n if (decision) {\n if (statusFilePath) await this.cleanupStatusFile(statusFilePath);\n if (decision.decision === 'complete') {\n const artifactProblem = artifactSnapshots\n ? await this.describeArtifactWarnings(stepEnv, artifactSnapshots)\n : undefined;\n if (!artifactProblem) {\n this.logger.info(\n `\\n ${GREEN}${STATUS_PASS}${RESET} ${stepName}${decision.summary ? ` (${decision.summary})` : ''}\\n`,\n );\n await this.logStepLifecycle('info', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'success',\n });\n return true;\n }\n fail(`step \"${stepName}\" ${artifactProblem}`);\n } else if (decision.decision === 'fix' && options.onDecision) {\n this.logger.warn(\n `\\n ${YELLOW}fix${RESET} ${stepName} asks to restart from \"${decision.restartFrom}\": ${firstLine(decision.reason)}\\n`,\n );\n options.onDecision({ ...decision, step: stepName });\n await this.logStepLifecycle('warn', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'fix',\n });\n return true;\n } else if (decision.decision === 'fail') {\n fail(`step \"${stepName}\" failed: ${firstLine(decision.reason)}`);\n if (!shouldContinue) options.onDecision?.({ ...decision, step: stepName });\n } else {\n fail(`step \"${stepName}\" asked for a fix, which only a job can route`);\n }\n return this.failStep(stepName, stepEnv, stepStartedAt, shouldContinue, report);\n }\n\n if (executionResult.status === 'timed_out') {\n fail(\n `${STEP_TIMEOUT_FAILURE_PREFIX} ${this.formatTimeoutMs(\n executionResult.timeoutMs,\n )} \"${stepName}\" (${command.split(COMMAND_LINE_BREAK)[0]})`,\n );\n\n if (attempt < maxTimeoutRetries) {\n // Reset status file for next attempt (clear stale content from timed-out Stop hook)\n if (statusFilePath) {\n try {\n getOrThrow(await this.runtime.fs.writeFile(statusFilePath, '', this.runtime.ioContext));\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} status-file reset failed for ${stepName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n continue;\n }\n\n if (statusFilePath) await this.cleanupStatusFile(statusFilePath);\n if (shouldContinue) {\n await this.logStepLifecycle('warn', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'continued',\n });\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n await this.logStepLifecycle('error', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'timed-out',\n 'workflow.step.failure_reason': report.reason ?? '',\n });\n return false;\n }\n\n // Clean up status file before returning for non-retry exits\n if (statusFilePath) await this.cleanupStatusFile(statusFilePath);\n\n if (\n decisionIdentity?.required &&\n !(executionResult.status === 'completed' && executionResult.failure !== undefined)\n ) {\n fail(`step \"${stepName}\" ended without a workflow decision (workflow-mcp step complete|fix|fail)`);\n return this.failStep(stepName, stepEnv, stepStartedAt, shouldContinue, report);\n }\n\n const restartFrom = step['restart-from'];\n if (\n restartFrom &&\n options.onDecision &&\n executionResult.status === 'completed' &&\n executionResult.exitCode !== 0\n ) {\n const tail = executionResult.outputTail?.trim();\n const ended = executionResult.failure\n ? `failed: ${executionResult.failure}`\n : `exited with code ${executionResult.exitCode}.`;\n const reason = `\\`${command.split(COMMAND_LINE_BREAK)[0]}\\` ${ended}${\n tail ? `\\n\\nLast output:\\n\\n\\`\\`\\`\\n${tail}\\n\\`\\`\\`` : ''\n }`;\n this.logger.warn(`\\n ${YELLOW}fix${RESET} ${stepName} failed; restarting from \"${restartFrom}\"\\n`);\n options.onDecision({ decision: 'fix', restartFrom, reason, step: stepName });\n await this.logStepLifecycle('warn', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'fix',\n });\n return true;\n }\n\n if (executionResult.status === 'status_completed') {\n // An agent's hook lets it stop once its gate runs out of reminders, so\n // the artifacts it still lacks fail the step here.\n const artifactProblem = artifactSnapshots\n ? await this.describeArtifactWarnings(stepEnv, artifactSnapshots)\n : undefined;\n if (artifactProblem) {\n fail(`step \"${stepName}\" ${artifactProblem}`);\n return this.failStep(stepName, stepEnv, stepStartedAt, shouldContinue, report);\n }\n this.logger.info(`\\n ${GREEN}${STATUS_DONE}${RESET} ${stepName} (status-file signaled completion)\\n`);\n await this.logStepLifecycle('info', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'success',\n });\n return true;\n }\n\n if (executionResult.status === 'completed' && executionResult.exitCode === 0) {\n // Whatever held the agent, its hook or its host, it may have stopped past\n // the gate's cap, so the engine checks the artifacts once the step ends.\n const artifactProblem = artifactSnapshots\n ? await this.describeArtifactWarnings(stepEnv, artifactSnapshots)\n : undefined;\n if (!artifactProblem) {\n this.logger.info(`\\n ${GREEN}${STATUS_PASS}${RESET} ${stepName}\\n`);\n await this.logStepLifecycle('info', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'success',\n });\n return true;\n }\n fail(`step \"${stepName}\" ${artifactProblem}`);\n }\n\n if (executionResult.status === 'completed' && executionResult.exitCode !== 0) {\n fail(\n executionResult.failure\n ? `step \"${stepName}\" failed: ${executionResult.failure}`\n : `${STEP_EXIT_FAILURE_PREFIX} \"${stepName}\" ${STEP_EXIT_FAILURE_MIDDLE} ${executionResult.exitCode} (${command.split(COMMAND_LINE_BREAK)[0]})`,\n );\n }\n\n if (!quotaFailureRetried && (await this.shouldRetryForCodexQuota(stepName, isCodexCommand))) {\n quotaFailureRetried = true;\n this.logger.warn(` ${YELLOW}${STATUS_RETRY}${RESET} ${QUOTA_RETRY_REASON}`);\n attempt -= 1;\n continue;\n }\n\n if (shouldContinue) {\n await this.logStepLifecycle('warn', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'continued',\n });\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n await this.logStepLifecycle('error', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'failed',\n 'workflow.step.failure_reason': report.reason ?? '',\n });\n return false;\n }\n\n return false;\n }\n\n /** Report a failed step, which passes under continue-on-error. */\n private async failStep(\n stepName: string,\n stepEnv: NodeJS.ProcessEnv,\n stepStartedAt: number,\n shouldContinue: boolean | undefined,\n report: StepFailureReport,\n ): Promise<boolean> {\n if (shouldContinue) {\n await this.logStepLifecycle('warn', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'continued',\n });\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n await this.logStepLifecycle('error', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'failed',\n 'workflow.step.failure_reason': report.reason ?? '',\n });\n return false;\n }\n\n private async logStepLifecycle(\n level: 'info' | 'warn' | 'error',\n message: string,\n env: NodeJS.ProcessEnv,\n attributes: Record<string, string | number | boolean>,\n ): Promise<void> {\n await this.logger.event?.(level, message, {\n attributes: {\n 'workflow.id': env.WORKFLOW_ID ?? '',\n 'workflow.name': env.WORKFLOW_NAME ?? '',\n 'workflow.workspace': env.WORKFLOW_WORKSPACE ?? '',\n 'workflow.run.id': env.WORKFLOW_RUN_ID ?? '',\n 'workflow.run.key': env.WORKFLOW_RUN_KEY ?? '',\n 'workflow.phase': env.WORKFLOW_PHASE ?? 'job',\n 'workflow.job.id': env.WORKFLOW_JOB_ID ?? '',\n 'workflow.job.name': env.WORKFLOW_JOB_NAME ?? '',\n 'workflow.step.name': env[WORKFLOW_STEP_NAME_ENV_KEY] ?? '',\n ...attributes,\n },\n });\n }\n\n /** A host-shell predicate: exit 0 runs the step, 1 skips it, anything else fails closed. */\n private async evaluateStepCondition(\n expression: string,\n context: InterpolationContext,\n workDir: string,\n stepEnv: NodeJS.ProcessEnv,\n stepName: string,\n timeoutMs: number | null,\n ): Promise<{ run: boolean; error?: string }> {\n const command = this.parser.interpolate(expression, context).trim();\n if (!command) return { run: false, error: `empty condition for step \"${stepName}\"` };\n const env = { ...stepEnv };\n delete env[STATUS_FILE_ENV_KEY];\n delete env[WORKFLOW_DECISION_FILE_ENV];\n delete env[WORKFLOW_DECISION_INSTRUCTIONS_ENV];\n const result = await this.executeCommand(\n command,\n workDir,\n env,\n `${stepName} (condition)`,\n false,\n Math.min(timeoutMs ?? 30_000, 30_000),\n );\n if (result.status === 'signaled' || this.interruptedSignal) {\n const signal = result.status === 'signaled' ? result.signal : (this.interruptedSignal ?? TERMINATE_SIGNAL);\n throw new WorkflowInterruptedError(signal, {\n cause: new Error(`Workflow interrupted during condition for \"${stepName}\"`),\n context: this.createInterruptContext(stepName, command),\n });\n }\n if (result.status === 'completed' && result.exitCode === 0) return { run: true };\n if (result.status === 'completed' && result.exitCode === 1) {\n this.logger.info(` ${DIM}${STATUS_SKIP}${RESET} ${stepName} (condition is false)`);\n await this.logStepLifecycle('info', 'workflow.step.skipped', stepEnv, { 'workflow.step.outcome': 'skipped' });\n return { run: false };\n }\n const reason = result.status === 'completed' ? `exit code ${result.exitCode}` : result.status;\n return { run: false, error: `condition for step \"${stepName}\" failed: ${reason}` };\n }\n\n /**\n * Spawn a child shell for the step command and normalize its termination\n * into a typed result.\n */\n private async executeCommand(\n command: string,\n workDir: string,\n stepEnv: NodeJS.ProcessEnv,\n stepName: string,\n interactive: boolean,\n timeoutMs: number | null,\n ): Promise<StepExecutionResult> {\n if (interactive) {\n this.logger.info(` ${DIM}${INTERACTIVE_OUTPUT_NOTICE}${RESET}`);\n }\n\n return await new Promise<StepExecutionResult>((resolveResult) => {\n const terminalState = interactive ? this.captureTerminalState() : null;\n // Interactive steps inherit all stdio so the child process gets a real\n // TTY — required for TUI tools like Claude Code that detect isTTY to\n // render their interactive UI. The trade-off is that stdout/stderr are\n // null (not piped), so output goes directly to the terminal instead of\n // through this.logger. Step lifecycle events (run/pass/fail/timeout)\n // are still logged normally by the caller.\n //\n // Interactive steps are NOT detached (detached: false) because\n // detaching moves the child into a separate process group, which\n // breaks terminal job control for TTY-attached programs. On\n // timeout/interrupt, killActiveStep falls back to child.kill(signal)\n // which sends SIGTERM to the shell. Descendant ownership is sampled\n // while the step runs so cleanup retains children that re-parent before\n // the interactive shell receives that signal.\n const child = interactive\n ? this.runtime.workflowHost.spawn(command, [], {\n stdio: [STDIO_INHERIT, STDIO_INHERIT, STDIO_INHERIT],\n cwd: workDir,\n detached: false,\n env: { ...stepEnv, [FORCE_COLOR_KEY]: FORCE_COLOR_VALUE },\n shell: DEFAULT_SHELL,\n })\n : this.runtime.workflowHost.spawn(command, [], {\n // Non-interactive steps inherit stdin so a CLI run can still prompt.\n // Embedded, that stdin is the host's keyboard: a `pre:`/`post:` shell\n // step would sit there silently eating the user's keystrokes.\n stdio: [this.ownsTerminal ? STDIO_INHERIT : STDIO_IGNORE, STDIO_PIPE, STDIO_PIPE],\n cwd: workDir,\n detached: this.runtime.workflowHost.platform !== PLATFORM_WINDOWS,\n env: { ...stepEnv, [FORCE_COLOR_KEY]: FORCE_COLOR_VALUE },\n shell: DEFAULT_SHELL,\n });\n\n this.activeStep = {\n command,\n interactive,\n lastSignaledProcessIds: [],\n process: child,\n processGroupId:\n this.runtime.workflowHost.platform !== PLATFORM_WINDOWS && !interactive && typeof child.pid === 'number'\n ? child.pid\n : null,\n rootProcessId: typeof child.pid === 'number' ? child.pid : null,\n stepName,\n trackedProcessGroupIds: [],\n trackedProcessIds: [],\n };\n\n let ownershipTracker: NodeJS.Timeout | null = null;\n if (interactive) {\n this.captureInteractiveProcessOwnership(child);\n ownershipTracker = setInterval(() => {\n this.captureInteractiveProcessOwnership(child);\n }, INTERACTIVE_PROCESS_TRACK_INTERVAL_MS);\n ownershipTracker.unref();\n }\n\n let forceKillTimer: NodeJS.Timeout | null = null;\n let timedOut = false;\n let settled = false;\n const settle = async (result: StepExecutionResult) => {\n if (settled) {\n return;\n }\n\n settled = true;\n if (timeoutTimer) {\n clearTimeout(timeoutTimer);\n }\n if (forceKillTimer) {\n clearTimeout(forceKillTimer);\n }\n if (ownershipTracker) {\n clearInterval(ownershipTracker);\n ownershipTracker = null;\n }\n // Only tear down / clear the active step if it is still THIS invocation's\n // child. The completion race can settle on the status file before an\n // unkillable child exits; by the time that stale child finally emits its\n // exit event a later step may already own `activeStep`, and reaping it\n // here would terminate the wrong process tree.\n const ownsActiveStep = this.activeStep?.process === child;\n if (interactive) {\n if (ownsActiveStep) {\n this.captureInteractiveProcessOwnership(child);\n await this.cleanupInteractiveProcessTree(TERMINATE_SIGNAL);\n }\n this.restoreTerminalState(terminalState);\n }\n if (ownsActiveStep) {\n this.activeStep = null;\n }\n resolveResult(result);\n };\n\n const timeoutTimer =\n timeoutMs === null\n ? null\n : setTimeout(() => {\n timedOut = true;\n const terminateRequested = this.killActiveStep(TERMINATE_SIGNAL);\n if (terminateRequested) {\n forceKillTimer = setTimeout(() => {\n if (!settled) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} ${STEP_TIMEOUT_FORCE_KILL_SUFFIX}`,\n );\n this.killActiveStep(TERMINATE_FORCE_KILL_SIGNAL);\n }\n }, FORCE_KILL_GRACE_PERIOD_MS);\n return;\n }\n\n void settle({ status: 'timed_out', timeoutMs });\n }, timeoutMs);\n\n // The end of the output becomes the reason when a failing\n // `restart-from` step turns into a fix request.\n const outputTail: string[] = [];\n const keep = (line: string) => {\n outputTail.push(line);\n if (outputTail.length > OUTPUT_TAIL_LINES) outputTail.shift();\n };\n\n child.stdout?.on('data', (data: Buffer) => {\n for (const line of data.toString().split('\\n')) {\n if (line) {\n keep(line);\n this.logger.info(line);\n }\n }\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n for (const line of data.toString().split('\\n')) {\n if (line) {\n keep(line);\n this.logger.error(line);\n }\n }\n });\n\n child.on('error', (error) => {\n void settle({\n status: 'spawn_error',\n error: new WorkflowStepSpawnError(\n {\n commandPreview: command.split(COMMAND_LINE_BREAK)[0],\n source: STEP_RUNNER_EXECUTE_SOURCE,\n stepName,\n workDir,\n },\n { cause: error },\n ),\n });\n });\n\n child.on('exit', async (code, signal) => {\n // Kill the process group to clean up any orphaned background processes\n // (e.g. http servers spawned by claude during manual testing)\n if (!interactive) {\n await this.cleanupProcessGroup();\n }\n // The exit event can come before the last output is read, and that\n // output is what the step's log and a restart-from reason report.\n await outputDrained(child);\n\n if (timedOut && timeoutMs !== null) {\n void settle({ status: 'timed_out', timeoutMs });\n return;\n }\n\n if (signal === INTERRUPT_SIGNAL) {\n void settle({ status: 'signaled', signal: INTERRUPT_SIGNAL });\n return;\n }\n\n if (signal === TERMINATE_SIGNAL) {\n void settle({ status: 'signaled', signal: TERMINATE_SIGNAL });\n return;\n }\n\n // A hangup is a termination like the two above. Falling through would\n // report the killed step as completed with an unknown exit code, and\n // the run would carry on as if nothing had gone wrong.\n if (signal === HANGUP_SIGNAL) {\n void settle({ status: 'signaled', signal: HANGUP_SIGNAL });\n return;\n }\n\n void settle({\n status: 'completed',\n exitCode: code ?? UNKNOWN_EXIT_CODE,\n ...(outputTail.length === 0 ? {} : { outputTail: outputTail.join(COMMAND_LINE_BREAK) }),\n });\n });\n });\n }\n\n /**\n * Start a step through the host executor when it offers one, else spawn it.\n */\n private startStepExecution(request: {\n traceparent?: string;\n command: string;\n custom: ResolvedCustomRun | undefined;\n interactive: boolean;\n onExecutionStarted: StepRunOptions['onExecutionStarted'];\n runConfig: RunConfig | undefined;\n stepEnv: NodeJS.ProcessEnv;\n stepName: string;\n jobEnvironment: Readonly<Record<string, string>>;\n attempt: number;\n template: StepCommandTemplate | undefined;\n timeoutMs: number | null;\n workDir: string;\n }): Promise<StepExecutionResult> {\n const { command, custom, interactive, stepEnv, stepName, template, timeoutMs, workDir } = request;\n const executor = this.stepExecutor;\n const base = {\n traceparent: request.traceparent,\n cwd: workDir,\n env: this.definedEnv({ ...stepEnv, [FORCE_COLOR_KEY]: FORCE_COLOR_VALUE }),\n stepName,\n jobEnvironment: request.jobEnvironment,\n attempt: request.attempt,\n ...(request.runConfig ? { runConfig: request.runConfig } : {}),\n };\n const executeCustom = executor?.custom?.bind(executor);\n if (custom && executeCustom) {\n return this.executeExternal(\n () => executeCustom.call(executor, { ...base, customRun: custom }),\n stepName,\n workDir,\n command,\n timeoutMs,\n request.onExecutionStarted,\n );\n }\n\n const executionCommand = interactive ? this.withInteractiveTerminalTitle(command, stepEnv) : command;\n const executeCommand = executor?.command?.bind(executor);\n const spawnHere = () =>\n interactive\n ? this.withTerminal(() =>\n this.interruptedSignal\n ? Promise.resolve<StepExecutionResult>({ status: RESULT_STATUS_SIGNALED, signal: this.interruptedSignal })\n : this.executeCommand(executionCommand, workDir, stepEnv, stepName, interactive, timeoutMs),\n )\n : this.executeCommand(executionCommand, workDir, stepEnv, stepName, interactive, timeoutMs);\n if (!executeCommand) {\n return spawnHere();\n }\n return this.executeExternal(\n () =>\n executeCommand.call(executor, {\n ...base,\n command: executionCommand,\n interactive,\n ...(template === undefined ? {} : { template }),\n }),\n stepName,\n workDir,\n command,\n timeoutMs,\n request.onExecutionStarted,\n spawnHere,\n );\n }\n\n /**\n * Run with the terminal to itself. An interactive step the engine spawns\n * inherits the terminal, so parallel ones take turns instead of fighting\n * over one keyboard; a host places its steps in panes of their own.\n */\n private async withTerminal<T>(run: () => Promise<T>): Promise<T> {\n const previous = this.terminalLock.tail;\n let release: () => void = () => {};\n this.terminalLock.tail = new Promise<void>((resolve) => {\n release = resolve;\n });\n await previous;\n try {\n return await run();\n } finally {\n release();\n }\n }\n\n /**\n * Await a host-owned execution and normalize it like a child process.\n *\n * The engine keeps ownership of the timeout; stop, pause and status-file\n * completion reach the execution through `killActiveStep`, which calls its\n * `stop`. A stopped execution reads as signalled so shutdown still interrupts\n * the workflow, while the completion races report their own outcome.\n */\n private async executeExternal(\n start: () => Promise<StepExecution | undefined>,\n stepName: string,\n workDir: string,\n command: string,\n timeoutMs: number | null,\n onExecutionStarted: StepRunOptions['onExecutionStarted'],\n declined?: () => Promise<StepExecutionResult>,\n ): Promise<StepExecutionResult> {\n let execution: StepExecution | undefined;\n try {\n execution = await start();\n } catch (error) {\n return {\n status: RESULT_STATUS_SPAWN_ERROR,\n error: new WorkflowStepSpawnError(\n {\n commandPreview: command.split(COMMAND_LINE_BREAK)[0],\n source: STEP_RUNNER_EXECUTE_SOURCE,\n stepName,\n workDir,\n },\n { cause: error },\n ),\n };\n }\n\n if (!execution) {\n if (declined) return declined();\n return {\n status: RESULT_STATUS_SPAWN_ERROR,\n error: new WorkflowStepSpawnError({\n commandPreview: command.split(COMMAND_LINE_BREAK)[0],\n source: STEP_RUNNER_EXECUTE_SOURCE,\n stepName,\n workDir,\n }),\n };\n }\n\n const active: ActiveExternalExecution = { execution, stepName, stopSignal: null };\n this.activeExternal = active;\n let timedOut = false;\n const timeoutTimer =\n timeoutMs === null\n ? null\n : setTimeout(() => {\n timedOut = true;\n this.stopExternal(active, TERMINATE_SIGNAL);\n }, timeoutMs);\n try {\n if (execution.ref) {\n this.logger.info(` ${DIM}${execution.ref.kind}${RESET} ${execution.ref.label ?? execution.ref.id}`);\n await onExecutionStarted?.(execution.ref);\n }\n const outcome = await execution.completion.catch((error: unknown) => ({\n error: error instanceof Error ? error : new Error(String(error)),\n }));\n if (timedOut && timeoutMs !== null) return { status: RESULT_STATUS_TIMED_OUT, timeoutMs };\n if (active.stopSignal) return { status: RESULT_STATUS_SIGNALED, signal: active.stopSignal };\n if ('error' in outcome) {\n return { status: RESULT_STATUS_COMPLETED, exitCode: UNKNOWN_EXIT_CODE, failure: outcome.error.message };\n }\n return {\n status: RESULT_STATUS_COMPLETED,\n exitCode: outcome.exitCode,\n ...(outcome.outputTail === undefined ? {} : { outputTail: outcome.outputTail }),\n };\n } finally {\n if (timeoutTimer) clearTimeout(timeoutTimer);\n if (this.activeExternal === active) this.activeExternal = null;\n }\n }\n\n /** Ask a host execution to end, once. A failed request is reported, not thrown. */\n private stopExternal(active: ActiveExternalExecution, signal: NodeJS.Signals): void {\n if (active.stopSignal) return;\n active.stopSignal = signal;\n void active.execution.stop().catch((error: unknown) => {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_SIGNAL_MESSAGE} ${active.stepName} (${error instanceof Error ? error.message : String(error)})`,\n );\n });\n }\n\n private definedEnv(env: NodeJS.ProcessEnv): Record<string, string> {\n const defined: Record<string, string> = {};\n for (const [key, value] of Object.entries(env)) {\n if (value !== undefined) defined[key] = value;\n }\n return defined;\n }\n\n /**\n * Why the step's own artifacts fail it, or undefined when all were updated.\n * The job's outputs it was reminded of are the job's to check once it ends,\n * since a later step may still write them.\n */\n private async describeArtifactWarnings(\n stepEnv: NodeJS.ProcessEnv,\n snapshots: StepArtifactSnapshot[],\n ): Promise<string | undefined> {\n const runDir = stepEnv[WORKFLOW_RUN_DIR_ENV_KEY];\n if (!runDir) return undefined;\n const own = snapshots.filter((snapshot) => snapshot.job === undefined);\n if (own.length === 0) return undefined;\n const warnings = await this.runDirectoryService.findStepArtifactWarnings(runDir, own);\n if (warnings.length === 0) return undefined;\n return `did not update its declared artifacts: ${warnings.map((warning) => `${warning.path} (${warning.status})`).join(', ')}`;\n }\n\n /**\n * Build interruption metadata for downstream workflow error handling.\n */\n private createInterruptContext(stepName: string, command: string): WorkflowInterruptContext {\n return {\n phase: STEP_EXECUTION_PHASE,\n stepName,\n commandPreview: command.split(COMMAND_LINE_BREAK)[0],\n source: STEP_RUNNER_SOURCE,\n };\n }\n\n /**\n * Render a safe summary of the spawn failure cause for operator logs.\n */\n private formatSpawnError(error: WorkflowStepSpawnError): string {\n const cause = error.cause;\n if (!(cause instanceof Error)) {\n return SPAWN_ERROR_FALLBACK_HINT;\n }\n\n // A host executor that could not start the step says why in its message; an\n // OS spawn failure says it in its code.\n if (!('code' in cause) || typeof cause.code !== 'string') return cause.message || SPAWN_ERROR_FALLBACK_HINT;\n const causePath = 'path' in cause && typeof cause.path === 'string' ? ` at ${cause.path}` : '';\n return `${cause.code}${causePath}; ${SPAWN_ERROR_RECOVERY_HINT}`;\n }\n\n /** Only launch/default subagent preferences affect customRun, never runner-name overrides. */\n private customRunChoiceConfig(runConfig: RunConfig | undefined): RunConfig | undefined {\n const selection = this.commandSelection;\n const settings = choiceSettings(selection.choices?.[selection.choice ?? DEFAULT_CHOICE]);\n const { subagentModel, subagentThinking } = settings;\n if (subagentModel === undefined && subagentThinking === undefined) return runConfig;\n return {\n ...runConfig,\n ...(subagentModel === undefined ? {} : { subagentModel }),\n ...(subagentThinking === undefined ? {} : { subagentThinking }),\n };\n }\n\n private resolveStepCommand(\n step: Step,\n context: InterpolationContext,\n runner?: string,\n decisionFile?: string,\n ): ResolvedStepCommand | null {\n if (Array.isArray(step.interactiveRun)) {\n return this.resolveTemplateCommand(step, step.interactiveRun, context, runner, decisionFile);\n }\n const customRun = step[CUSTOM_RUN_KEY];\n // A command mapped to the selected runner is that runner's own way to run the\n // step, so it beats customRun, unless customRun names the runner too: the\n // command is then the runner's terminal fallback for a host with no executor.\n const runnerCommand = runner !== undefined && this.collectMappedRunnerKeys(step).includes(runner);\n const entry = customRun ? customRunEntry(customRun, runner) : undefined;\n if (entry && this.stepExecutor?.custom && (!runnerCommand || customRunNames(customRun, runner))) {\n const runConfig = this.customRunChoiceConfig(\n entry.runConfig ? { ...step.runConfig, ...entry.runConfig } : step.runConfig,\n );\n const entryContext: InterpolationContext = runConfig ? { ...context, runConfig } : context;\n const prompt = this.parser.interpolate(entry.prompt, entryContext);\n const systemPrompt =\n entry.systemPrompt === undefined ? undefined : this.parser.interpolate(entry.systemPrompt, entryContext);\n return {\n command: `${CUSTOM_RUN_KEY}: ${prompt.split(COMMAND_LINE_BREAK)[0]}`,\n custom: { prompt, ...(systemPrompt === undefined ? {} : { systemPrompt }) },\n ...(runConfig === undefined ? {} : { runConfig }),\n interactive: false,\n };\n }\n\n const interactiveRun = legacyCommand(step[INTERACTIVE_RUN_KEY]);\n const hasInteractiveRun = interactiveRun != null;\n const primary = hasInteractiveRun\n ? { command: interactiveRun, interactive: true }\n : { command: step[RUN_KEY], interactive: false };\n const secondary = hasInteractiveRun\n ? { command: step[RUN_KEY], interactive: false }\n : { command: interactiveRun, interactive: true };\n\n const exactPrimary = this.resolveExactAgentCommand(primary.command, context, runner);\n if (exactPrimary) {\n return { ...exactPrimary, interactive: primary.interactive };\n }\n\n const exactSecondary = this.resolveExactAgentCommand(secondary.command, context, runner);\n if (exactSecondary) {\n return { ...exactSecondary, interactive: secondary.interactive };\n }\n\n // A customRun step's commands are its fallback on a host without an executor,\n // so a runner they do not name, such as a named custom runner, is not missing.\n const missingRunner = customRun ? null : this.resolveMissingExplicitRunner(step, runner);\n if (missingRunner) {\n return { command: '', interactive: false, missingRunner };\n }\n\n const stringPrimary = this.resolveStringCommand(primary.command, context);\n if (stringPrimary) {\n return { command: stringPrimary, interactive: primary.interactive };\n }\n\n const stringSecondary = this.resolveStringCommand(secondary.command, context);\n if (stringSecondary) {\n return { command: stringSecondary, interactive: secondary.interactive };\n }\n\n const firstPrimary = this.resolveFirstMappedCommand(primary.command, context);\n if (firstPrimary) {\n return { command: firstPrimary, interactive: primary.interactive };\n }\n\n const firstSecondary = this.resolveFirstMappedCommand(secondary.command, context);\n if (firstSecondary) {\n return { command: firstSecondary, interactive: secondary.interactive };\n }\n\n return null;\n }\n\n /**\n * Render a templated interactiveRun for the selected command and choice.\n *\n * The command is the launch's `--command`, else `--runner` when the step\n * offers a command of that name, else the step's first. The choice is the\n * entry's, else the step's, else the launch's `--choice`, else `default`.\n * Its step/subagent settings, with the command's own override, lay over the\n * step's runConfig; the result feeds both the template and host executors.\n */\n private resolveTemplateCommand(\n step: Step,\n offered: CommandRef[],\n context: InterpolationContext,\n runner: string | undefined,\n decisionFile: string | undefined,\n ): ResolvedStepCommand {\n const selection = this.commandSelection;\n const failed = (templateError: string): ResolvedStepCommand => ({ command: '', interactive: true, templateError });\n const wanted =\n selection.command ??\n (runner !== undefined && offered.some((entry) => entry.command === runner) ? runner : undefined);\n const entry = wanted === undefined ? offered[0] : offered.find((candidate) => candidate.command === wanted);\n if (!entry) {\n return failed(\n `command \"${wanted}\" is not offered by this step (offered: ${offered.map((candidate) => candidate.command).join(', ')})`,\n );\n }\n const declared = selection.commands?.[entry.command];\n if (!declared) return failed(`command \"${entry.command}\" is not declared under commands`);\n\n const choiceName =\n entry.choice ??\n step.choice ??\n selection.choice ??\n (selection.choices?.[DEFAULT_CHOICE] ? DEFAULT_CHOICE : undefined);\n const choice = choiceName === undefined ? undefined : selection.choices?.[choiceName];\n if (choiceName !== undefined && !choice) return failed(`choice \"${choiceName}\" is not declared under choices`);\n\n const runConfig: RunConfig = {\n ...step.runConfig,\n ...entry.runConfig,\n ...choiceSettings(choice, entry.command),\n };\n const promptContext: InterpolationContext = { ...context, runConfig };\n const promptSource = entry.prompt ?? step.prompt ?? '';\n const prompt = this.parser.interpolate(promptSource, promptContext);\n const systemPromptSource = entry.systemPrompt ?? step.systemPrompt;\n const systemPrompt =\n [\n systemPromptSource === undefined ? undefined : this.parser.interpolate(systemPromptSource, promptContext),\n this.decisionInstructions(context, decisionFile),\n ]\n .filter((part): part is string => part !== undefined && part.length > 0)\n .join('\\n\\n') || undefined;\n\n const { run, inProcess } = commandTemplateOf(declared);\n // A command with no system-prompt flag still has to carry the decision\n // instructions, so they lead its prompt instead.\n const passesSystemPrompt = this.parser.templateUsesSystemPrompt(run);\n const values: Record<string, unknown> = {\n ...runConfig,\n command: entry.command,\n prompt: systemPrompt === undefined || passesSystemPrompt ? prompt : `${systemPrompt}\\n\\n${prompt}`,\n ...(choiceName === undefined ? {} : { choice: choiceName }),\n ...(systemPrompt === undefined || !passesSystemPrompt ? {} : { systemPrompt }),\n };\n let command: string;\n try {\n command = this.parser.renderCommandTemplate(run, values);\n } catch (error) {\n return failed(\n `command \"${entry.command}\" did not render: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return {\n agentKey: entry.command,\n command,\n interactive: true,\n runConfig,\n template: {\n name: entry.command,\n inProcess,\n prompt,\n reads: [\n ...new Set(\n offered.flatMap((candidate) => {\n const offeredTemplate = selection.commands?.[candidate.command];\n return offeredTemplate === undefined\n ? []\n : this.parser.templateVariables(commandTemplateOf(offeredTemplate).run);\n }),\n ),\n ],\n ...(choiceName === undefined ? {} : { choice: choiceName }),\n ...(systemPrompt === undefined ? {} : { systemPrompt }),\n },\n };\n }\n\n /** The job's decision instructions, naming this step's own decision file once it has one. */\n private decisionInstructions(context: InterpolationContext, decisionFile: string | undefined): string | undefined {\n const instructions = context.env[WORKFLOW_DECISION_INSTRUCTIONS_ENV];\n const runDir = context.env[WORKFLOW_RUN_DIR_ENV_KEY];\n if (instructions === undefined || decisionFile === undefined || !runDir) return instructions;\n const job = context.env[WORKFLOW_JOB_NAME_ENV_KEY] ?? '';\n const targets = (context.env[WORKFLOW_RESTART_TARGETS_ENV] ?? '').split(',').filter(Boolean);\n return stepDecisionInstructions(runDir, job, targets, decisionFile);\n }\n\n private resolveExactAgentCommand(\n command: StepCommand | undefined,\n context: InterpolationContext,\n runner?: string,\n ): ResolvedStepCommand | null {\n if (!runner || !command || typeof command === 'string') {\n return null;\n }\n const exactCommand = command[runner];\n return exactCommand\n ? {\n agentKey: runner,\n command: this.parser.interpolate(exactCommand, context),\n interactive: false,\n }\n : null;\n }\n\n private resolveStringCommand(command: StepCommand | undefined, context: InterpolationContext): string | null {\n if (!command || typeof command !== 'string') {\n return null;\n }\n return this.parser.interpolate(command, context);\n }\n\n private resolveFirstMappedCommand(command: StepCommand | undefined, context: InterpolationContext): string | null {\n if (!command || typeof command === 'string') {\n return null;\n }\n const [firstCommand] = Object.values(command);\n return firstCommand ? this.parser.interpolate(firstCommand, context) : null;\n }\n\n private resolveMissingExplicitRunner(\n step: Step,\n runner: string | undefined,\n ): { availableKeys: string[]; runner: string } | null {\n if (!runner) {\n return null;\n }\n\n const availableKeys = this.collectMappedRunnerKeys(step);\n if (availableKeys.length === 0) {\n return null;\n }\n\n return availableKeys.includes(runner) ? null : { availableKeys, runner };\n }\n\n private collectMappedRunnerKeys(step: Step): string[] {\n const keys = new Set<string>();\n for (const command of [legacyCommand(step[INTERACTIVE_RUN_KEY]), step[RUN_KEY]]) {\n if (command && typeof command !== 'string') {\n for (const key of Object.keys(command)) {\n keys.add(key);\n }\n }\n }\n return [...keys];\n }\n\n private resolveRunner(options: StepRunOptions): string | undefined {\n return options.runner ?? options.cliAgent;\n }\n\n private formatStepDisplay(jobName: string | undefined, stepName: string): string {\n return jobName ? `${jobName} > ${stepName}` : stepName;\n }\n\n private withInteractiveTerminalTitle(command: string, stepEnv: NodeJS.ProcessEnv): string {\n const stepDisplay =\n stepEnv[WORKFLOW_STEP_DISPLAY_ENV_KEY] ?? command.split(COMMAND_LINE_BREAK)[0] ?? DEFAULT_STEP_NAME;\n const title = `${WORKFLOW_TERMINAL_TITLE}: ${stepDisplay}`;\n const setTitleCommand = `[ -t 1 ] && printf '\\\\033]0;%s\\\\007' ${this.escapeShellArg(title)}`;\n const resetTitleCommand = `[ -t 1 ] && printf '\\\\033]0;%s\\\\007' ${this.escapeShellArg(WORKFLOW_TERMINAL_TITLE)}`;\n return `trap ${this.escapeShellArg(resetTitleCommand)} EXIT${COMMAND_LINE_BREAK}${setTitleCommand}${COMMAND_LINE_BREAK}${command}`;\n }\n\n private escapeShellArg(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n }\n\n private async shouldRetryForCodexQuota(stepName: string, isCodexCommand: boolean): Promise<boolean> {\n if (!isCodexCommand) {\n return false;\n }\n\n const quotaStatus = await this.readCodexQuotaStatus(stepName);\n return quotaStatus?.blockingLimit != null;\n }\n\n private async waitForCodexQuotaAvailability(\n stepName: string,\n command: string,\n isCodexCommand: boolean,\n ): Promise<void> {\n if (!isCodexCommand) {\n return;\n }\n\n while (true) {\n const quotaStatus = await this.readCodexQuotaStatus(stepName);\n const blockingLimit = quotaStatus?.blockingLimit;\n if (!blockingLimit) {\n return;\n }\n\n const waitTargetMs = blockingLimit.resetAt * 1000 + QUOTA_WAIT_RESET_BUFFER_MS;\n const remainingMs = Math.max(waitTargetMs - Date.now(), QUOTA_WAIT_RESET_BUFFER_MS);\n const waitDescription = new Date(waitTargetMs).toLocaleString();\n const planSuffix = quotaStatus?.planType ? ` (${quotaStatus.planType})` : '';\n\n this.logger.warn(\n ` ${YELLOW}${STATUS_WAIT}${RESET} codex quota ${blockingLimit.limitName}/${blockingLimit.window} is at ${blockingLimit.usedPercent}%${planSuffix}; waiting until ${waitDescription}`,\n );\n\n await this.waitForQuotaDelay(stepName, command, remainingMs);\n }\n }\n\n private async readCodexQuotaStatus(stepName: string): Promise<CodexQuotaStatus | null> {\n try {\n return await this.quotaService.getQuotaStatus();\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} unable to read codex quota for \"${stepName}\" (${this.formatQuotaError(error)})`,\n );\n return null;\n }\n }\n\n private async waitForQuotaDelay(stepName: string, command: string, remainingMs: number): Promise<void> {\n const controller = new AbortController();\n this.activeQuotaWait = {\n controller,\n signal: null,\n stepName,\n };\n\n try {\n let timeLeftMs = remainingMs;\n while (timeLeftMs > 0) {\n const sleepMs = Math.min(timeLeftMs, QUOTA_WAIT_POLL_INTERVAL_MS);\n await this.waitForDelay(sleepMs, controller.signal);\n timeLeftMs -= sleepMs;\n }\n } catch (error) {\n if (controller.signal.aborted) {\n const interruptSignal = this.activeQuotaWait?.signal ?? TERMINATE_SIGNAL;\n throw new WorkflowInterruptedError(interruptSignal, {\n cause: new Error(`Interrupted while waiting for Codex quota reset`),\n context: {\n ...this.createInterruptContext(stepName, command),\n phase: QUOTA_WAIT_SOURCE,\n },\n });\n }\n\n throw error;\n } finally {\n this.activeQuotaWait = null;\n }\n }\n\n private async waitForDelay(delayMs: number, signal: AbortSignal): Promise<void> {\n await new Promise<void>((resolveDelay, rejectDelay) => {\n const timeout = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolveDelay();\n }, delayMs);\n\n const onAbort = () => {\n clearTimeout(timeout);\n signal.removeEventListener('abort', onAbort);\n rejectDelay(new Error('aborted'));\n };\n\n signal.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n private formatQuotaError(error: unknown): string {\n if (error instanceof Error && error.message.trim().length > 0) {\n return error.message;\n }\n\n return 'unknown quota error';\n }\n\n /**\n * Resolve the per-step timeout from workflow YAML into milliseconds.\n */\n private resolveTimeoutMs(step: Step, stepName: string): number | null {\n const timeoutMinutes = step[STEP_TIMEOUT_MINUTES_KEY];\n if (timeoutMinutes === undefined) {\n return null;\n }\n\n try {\n const parsedTimeoutMinutes = StepTimeoutMinutesSchema.parse(timeoutMinutes);\n return Math.ceil(parsedTimeoutMinutes * MINUTE_IN_MS);\n } catch (error) {\n throw new WorkflowStepTimeoutConfigError(\n {\n stepName,\n configKey: STEP_TIMEOUT_MINUTES_KEY,\n timeoutValue: timeoutMinutes,\n },\n { cause: error },\n );\n }\n }\n\n /**\n * Resolve the per-step timeout retry count from workflow YAML.\n */\n private resolveTimeoutRetries(step: Step, stepName: string): number {\n const rawValue = step[STEP_TIMEOUT_RETRIES_KEY];\n try {\n return StepTimeoutRetriesSchema.parse(rawValue);\n } catch (error) {\n throw new WorkflowStepTimeoutConfigError(\n {\n stepName,\n configKey: STEP_TIMEOUT_RETRIES_KEY,\n timeoutValue: rawValue,\n },\n { cause: error },\n );\n }\n }\n\n /**\n * Format timeout durations for operator-facing logs.\n */\n private formatTimeoutMs(timeoutMs: number): string {\n return timeoutMs % MINUTE_IN_MS === 0\n ? `${timeoutMs / MINUTE_IN_MS} ${TIMEOUT_UNIT_MINUTES}`\n : `${timeoutMs}${TIMEOUT_UNIT_MILLISECONDS}`;\n }\n\n /**\n * Send SIGTERM to the active step's process group to clean up orphaned\n * background processes (e.g. http servers spawned during manual testing).\n * Silently ignores ESRCH when the group has already exited.\n */\n private async cleanupProcessGroup(): Promise<void> {\n const processGroupId = this.activeStep?.processGroupId;\n const stepName = this.activeStep?.stepName;\n if (processGroupId === null || processGroupId === undefined || !stepName) {\n return;\n }\n try {\n this.runtime.workflowHost.signal(-processGroupId, TERMINATE_SIGNAL);\n } catch (error) {\n const errorCode = (error as NodeJS.ErrnoException).code;\n if (errorCode !== ESRCH_ERROR_CODE) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_CLEANUP_PROCESS_GROUP_MESSAGE} ${stepName} (pgid=${processGroupId}, error=${errorCode})`,\n );\n } else {\n this.logger.info(` ${DIM}cleanup${RESET} process group ${processGroupId} already exited (ESRCH)`);\n }\n return;\n }\n\n await this.waitForProcessGroupToExit(processGroupId, FORCE_KILL_GRACE_PERIOD_MS);\n if (!this.isProcessGroupAlive(processGroupId)) return;\n\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} process group did not exit after SIGTERM, forcing SIGKILL`,\n );\n try {\n this.runtime.workflowHost.signal(-processGroupId, TERMINATE_FORCE_KILL_SIGNAL);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== ESRCH_ERROR_CODE) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_CLEANUP_PROCESS_GROUP_MESSAGE} ${stepName} (pgid=${processGroupId}, error=${(error as NodeJS.ErrnoException).code})`,\n );\n }\n return;\n }\n await this.waitForProcessGroupToExit(processGroupId, PROCESS_EXIT_WAIT_TIMEOUT_MS);\n }\n\n private isProcessGroupAlive(processGroupId: number): boolean {\n try {\n this.runtime.workflowHost.signal(-processGroupId, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== ESRCH_ERROR_CODE;\n }\n }\n\n private async waitForProcessGroupToExit(processGroupId: number, timeoutMs: number): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while (this.isProcessGroupAlive(processGroupId) && Date.now() < deadline) {\n await new Promise((resolveWait) => setTimeout(resolveWait, PROCESS_EXIT_POLL_INTERVAL_MS));\n }\n }\n\n /**\n * Best-effort cleanup for interactive commands that inherit the terminal.\n * These commands are intentionally not detached, so keep an explicit PID\n * snapshot before signaling; once the shell exits, descendants may be\n * re-parented and no longer discoverable from the shell PID.\n */\n private async cleanupInteractiveProcessTree(signal: NodeJS.Signals): Promise<boolean> {\n if (!this.activeStep || !this.activeStep.interactive) {\n return false;\n }\n\n const stepName = this.activeStep.stepName;\n this.captureInteractiveProcessOwnership(this.activeStep.process);\n const initialProcessIds = this.collectInteractiveProcessIds();\n if (initialProcessIds.length === 0) {\n this.lastInteractiveReap = { survivors: [], sigkillEscalated: false };\n return false;\n }\n\n const initialProcessGroupIds = [\n ...new Set([\n ...this.activeStep.trackedProcessGroupIds,\n ...this.collectInteractiveProcessGroupIds(initialProcessIds),\n ]),\n ];\n this.logger.info(\n ` ${DIM}cleanup${RESET} reaping ${stepName} interactive pids [${initialProcessIds.join(', ')}]${initialProcessGroupIds.length > 0 ? ` groups [${initialProcessGroupIds.join(', ')}]` : ''}`,\n );\n\n const graceMs = this.interactiveKillGraceMs();\n if (signal !== TERMINATE_FORCE_KILL_SIGNAL) {\n await this.reapInteractiveTree(signal, graceMs);\n }\n\n const sigkillEscalated = this.collectInteractiveProcessIds().length > 0;\n if (sigkillEscalated) {\n // Anything alive after the SIGTERM grace is force-killed. Re-walking each\n // round catches descendants that re-parented away from the original root\n // after the shell exited and would escape a single snapshot.\n await this.reapInteractiveTree(TERMINATE_FORCE_KILL_SIGNAL, graceMs);\n }\n\n const survivors = this.collectInteractiveProcessIds().map((pid) => ({\n pid,\n command: this.describeProcess(pid),\n }));\n this.lastInteractiveReap = { survivors, sigkillEscalated };\n if (survivors.length > 0) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} interactive processes survived termination: ${survivors\n .map((entry) => `${entry.pid} (${entry.command})`)\n .join(', ')}`,\n );\n }\n\n return true;\n }\n\n /**\n * Re-signal the live interactive descendants until none remain or `budgetMs`\n * elapses, re-walking the process tree each round. An interactive TUI keeps\n * spawning and re-parenting descendants (MCP servers, browser/render helpers)\n * that a single snapshot misses; group-signalling also reaps members spawned\n * after the snapshot. Returns as soon as the tree is empty so the common,\n * already-exited case adds no latency.\n */\n private async reapInteractiveTree(signal: NodeJS.Signals, budgetMs: number): Promise<void> {\n const deadline = Date.now() + budgetMs;\n do {\n this.captureInteractiveProcessOwnership(this.activeStep?.process);\n const liveProcessIds = this.collectInteractiveProcessIds();\n if (liveProcessIds.length === 0) {\n return;\n }\n\n if (this.activeStep) {\n this.activeStep.lastSignaledProcessIds = liveProcessIds;\n }\n this.signalProcessIds(liveProcessIds, signal);\n this.signalProcessGroups(\n [\n ...new Set([\n ...(this.activeStep?.trackedProcessGroupIds ?? []),\n ...this.collectInteractiveProcessGroupIds(liveProcessIds),\n ]),\n ],\n signal,\n );\n await this.waitForProcessIdsToExit(liveProcessIds, INTERACTIVE_REAP_ROUND_INTERVAL_MS);\n } while (Date.now() < deadline);\n }\n\n /**\n * Operator-tunable SIGTERM→SIGKILL grace per teardown phase. Defaults to the\n * process-exit wait so ordinary interactive steps see no behaviour change.\n */\n private interactiveKillGraceMs(): number {\n const raw = this.runtime.baseEnvironment[INTERACTIVE_KILL_GRACE_MS_ENV_KEY];\n if (raw === undefined) {\n return PROCESS_EXIT_WAIT_TIMEOUT_MS;\n }\n\n const parsed = Number(raw);\n return Number.isInteger(parsed) && parsed > 0 ? parsed : PROCESS_EXIT_WAIT_TIMEOUT_MS;\n }\n\n /**\n * SIGTERM→SIGKILL grace on the completion path (status file signalled `YES`).\n * Deliberately longer than the timeout-path `FORCE_KILL_GRACE_PERIOD_MS` so an\n * interactive agent can flush its final telemetry batch (e.g. Claude Code's\n * OTEL Stop-hook events) before SIGKILL. A fast graceful exit still settles\n * immediately, so this only adds latency when a child lingers. Operator-tunable\n * via `WORKFLOW_STEP_FORCE_KILL_GRACE_MS`; defaults to STEP_COMPLETION_KILL_GRACE_MS.\n */\n private stepCompletionKillGraceMs(): number {\n const raw = this.runtime.baseEnvironment[STEP_COMPLETION_KILL_GRACE_MS_ENV_KEY];\n if (raw === undefined) {\n return STEP_COMPLETION_KILL_GRACE_MS;\n }\n\n const parsed = Number(raw);\n return Number.isInteger(parsed) && parsed > 0 ? parsed : STEP_COMPLETION_KILL_GRACE_MS;\n }\n\n /** Resolve a pid to its `ps` command line so survivors are identifiable. */\n private describeProcess(processId: number): string {\n try {\n const command = this.runtime.workflowHost.inspectProcesses('command', processId).trim();\n return command.length > 0 ? command : 'unknown';\n } catch {\n return 'unknown';\n }\n }\n\n /**\n * Append a forensic record for an interactive run to a capped JSON log so a\n * session that does not exit is self-diagnosing (which signal completed it and\n * what survived). Best-effort: logging never affects step control flow.\n */\n private async recordInteractiveCompletion(record: InteractiveCompletionRecord): Promise<void> {\n try {\n const logPath = await this.interactiveReapLogPath();\n const entries = await this.readInteractiveCompletionLog(logPath);\n entries.push(record);\n getOrThrow(await this.runtime.fs.createDir(dirname(logPath), { recursive: true }, this.runtime.ioContext));\n getOrThrow(\n await this.runtime.fs.writeFile(\n logPath,\n `${JSON.stringify(entries.slice(-INTERACTIVE_REAP_LOG_MAX_ENTRIES), null, 2)}\\n`,\n this.runtime.ioContext,\n ),\n );\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} interactive-reap log write failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n private async interactiveReapLogPath(): Promise<string> {\n const runDir = this.runtime.baseEnvironment[WORKFLOW_RUN_DIR_ENV_KEY];\n const baseDir =\n runDir && (await pathExists(this.runtime.fs, runDir, this.runtime.ioContext))\n ? runDir\n : join(this.runtime.cwd, 'tmp');\n return join(baseDir, INTERACTIVE_REAP_LOG_FILENAME);\n }\n\n private async readInteractiveCompletionLog(logPath: string): Promise<InteractiveCompletionRecord[]> {\n try {\n const parsed = JSON.parse(\n getOrThrow(await this.runtime.fs.readTextFile(logPath, this.runtime.ioContext)),\n ) as unknown;\n return Array.isArray(parsed) ? (parsed as InteractiveCompletionRecord[]) : [];\n } catch {\n return [];\n }\n }\n\n private captureInteractiveProcessOwnership(expectedProcess?: ChildProcess): void {\n const activeStep = this.activeStep;\n if (\n !activeStep?.interactive ||\n activeStep.rootProcessId === null ||\n (expectedProcess !== undefined && activeStep.process !== expectedProcess)\n ) {\n return;\n }\n\n const treeRoots = this.uniqueLiveProcessIds([\n activeStep.rootProcessId,\n ...activeStep.trackedProcessIds,\n ...activeStep.lastSignaledProcessIds,\n ]);\n const treeProcessIds = this.snapshotProcessTree(treeRoots).map((entry) => entry.pid);\n activeStep.trackedProcessIds = this.uniqueLiveProcessIds([\n ...activeStep.trackedProcessIds,\n ...activeStep.lastSignaledProcessIds,\n ...treeProcessIds,\n activeStep.rootProcessId,\n ]);\n activeStep.trackedProcessGroupIds = this.collectInteractiveProcessGroupIds(activeStep.trackedProcessIds);\n }\n\n private collectInteractiveProcessIds(): number[] {\n if (!this.activeStep?.interactive || this.activeStep.rootProcessId === null) {\n return [];\n }\n\n const rootProcessId = this.activeStep.rootProcessId;\n // Walk from every process observed while it was still owned by the\n // interactive root. A descendant can re-parent before teardown begins, so\n // final cleanup must not depend on current PPID ancestry alone.\n const treeRoots = this.uniqueLiveProcessIds([\n rootProcessId,\n ...this.activeStep.trackedProcessIds,\n ...this.activeStep.lastSignaledProcessIds,\n ]);\n const treeProcessIds = this.snapshotProcessTree(treeRoots).map((entry) => entry.pid);\n const processIds = [\n ...treeProcessIds,\n ...this.activeStep.trackedProcessIds,\n ...this.activeStep.lastSignaledProcessIds,\n rootProcessId,\n ];\n return this.uniqueLiveProcessIds(processIds);\n }\n\n private snapshotProcessTree(rootProcessIds: number[]): ProcessTreeEntry[] {\n if (rootProcessIds.length === 0) {\n return [];\n }\n\n let processRows: string;\n try {\n processRows = this.runtime.workflowHost.inspectProcesses('parents');\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} unable to inspect process tree for [${rootProcessIds.join(', ')}] (${error instanceof Error ? error.message : String(error)})`,\n );\n return rootProcessIds.filter((pid) => this.isProcessAlive(pid)).map((pid) => ({ depth: 0, pid }));\n }\n\n const childrenByParent = new Map<number, number[]>();\n for (const line of processRows.split(COMMAND_LINE_BREAK)) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n\n const [pidRaw, parentPidRaw] = trimmed.split(/\\s+/);\n const pid = Number(pidRaw);\n const parentPid = Number(parentPidRaw);\n if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) {\n continue;\n }\n\n const children = childrenByParent.get(parentPid) ?? [];\n children.push(pid);\n childrenByParent.set(parentPid, children);\n }\n\n const entries: ProcessTreeEntry[] = [];\n const visited = new Set<number>();\n const walk = (pid: number, depth: number) => {\n if (visited.has(pid)) {\n return;\n }\n visited.add(pid);\n if (pid !== this.runtime.workflowHost.processId) {\n entries.push({ depth, pid });\n }\n\n for (const childPid of childrenByParent.get(pid) ?? []) {\n walk(childPid, depth + 1);\n }\n };\n\n for (const rootProcessId of rootProcessIds) {\n walk(rootProcessId, 0);\n }\n return entries.sort((left, right) => right.depth - left.depth);\n }\n\n private signalProcessIds(processIds: number[], signal: NodeJS.Signals): boolean {\n let signaled = false;\n for (const processId of processIds) {\n if (processId === this.runtime.workflowHost.processId) {\n continue;\n }\n\n try {\n this.runtime.workflowHost.signal(processId, signal);\n signaled = true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== ESRCH_ERROR_CODE) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_SIGNAL_MESSAGE} pid ${processId} (${code ?? (error as Error).message})`,\n );\n }\n }\n }\n\n return signaled;\n }\n\n /**\n * Resolve the distinct process-group ids owned by the given pids, excluding\n * the runner's own group so a `kill(-pgid)` can never terminate this process.\n *\n * Interactive TUIs such as Claude Code make themselves process-group leaders\n * (pid === pgid) and spawn descendants into that group. Reaping by pid alone\n * leaves anything spawned after the one-shot tree snapshot alive, which keeps\n * the interactive session running after the Stop hook signalled completion.\n */\n private collectInteractiveProcessGroupIds(processIds: number[]): number[] {\n if (processIds.length === 0) {\n return [];\n }\n\n let processRows: string;\n try {\n processRows = this.runtime.workflowHost.inspectProcesses('groups');\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} unable to inspect process groups (${error instanceof Error ? error.message : String(error)})`,\n );\n return [];\n }\n\n const processGroupByPid = new Map<number, number>();\n for (const line of processRows.split(COMMAND_LINE_BREAK)) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n\n const [pidRaw, processGroupRaw] = trimmed.split(/\\s+/);\n const pid = Number(pidRaw);\n const processGroupId = Number(processGroupRaw);\n if (Number.isInteger(pid) && Number.isInteger(processGroupId)) {\n processGroupByPid.set(pid, processGroupId);\n }\n }\n\n const runnerProcessGroupId = processGroupByPid.get(this.runtime.workflowHost.processId);\n const processGroupIds = new Set<number>();\n for (const pid of processIds) {\n const processGroupId = processGroupByPid.get(pid);\n if (processGroupId === undefined || processGroupId <= 1 || processGroupId === runnerProcessGroupId) {\n continue;\n }\n processGroupIds.add(processGroupId);\n }\n\n return [...processGroupIds];\n }\n\n private signalProcessGroups(processGroupIds: number[], signal: NodeJS.Signals): boolean {\n let signaled = false;\n for (const processGroupId of processGroupIds) {\n try {\n this.runtime.workflowHost.signal(-processGroupId, signal);\n signaled = true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== ESRCH_ERROR_CODE) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_SIGNAL_MESSAGE} process group ${processGroupId} (${code ?? (error as Error).message})`,\n );\n }\n }\n }\n\n return signaled;\n }\n\n private uniqueLiveProcessIds(processIds: number[]): number[] {\n const seen = new Set<number>();\n const liveProcessIds: number[] = [];\n for (const processId of processIds) {\n if (\n !Number.isInteger(processId) ||\n processId <= 0 ||\n processId === this.runtime.workflowHost.processId ||\n seen.has(processId)\n ) {\n continue;\n }\n\n seen.add(processId);\n if (this.isProcessAlive(processId)) {\n liveProcessIds.push(processId);\n }\n }\n\n return liveProcessIds;\n }\n\n private isProcessAlive(processId: number): boolean {\n try {\n this.runtime.workflowHost.signal(processId, 0);\n return true;\n } catch {\n return false;\n }\n }\n\n private async waitForProcessIdsToExit(processIds: number[], timeoutMs: number): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (processIds.every((processId) => !this.isProcessAlive(processId))) {\n return;\n }\n\n await new Promise((resolveWait) => setTimeout(resolveWait, PROCESS_EXIT_POLL_INTERVAL_MS));\n }\n }\n\n /**\n * Signal the active step, preferring the detached process group so shell\n * pipelines shut down as a unit before falling back to the shell process.\n *\n * @param signal POSIX signal used to interrupt the running step.\n * @returns `true` when a signal was dispatched successfully, otherwise `false`.\n */\n private killActiveStep(signal: NodeJS.Signals): boolean {\n if (this.activeExternal) {\n this.stopExternal(this.activeExternal, signal);\n return true;\n }\n\n if (!this.activeStep) {\n return false;\n }\n\n if (this.activeStep.interactive) {\n this.captureInteractiveProcessOwnership(this.activeStep.process);\n const processIds = this.collectInteractiveProcessIds();\n if (processIds.length > 0) {\n this.activeStep.lastSignaledProcessIds = processIds;\n const signaledPids = this.signalProcessIds(processIds, signal);\n // Also reap the session's process group(s): an interactive TUI makes\n // itself a group leader and spawns descendants that escape a one-shot\n // pid snapshot, so a per-pid signal alone can leave the session alive.\n const signaledGroups = this.signalProcessGroups(\n [\n ...new Set([\n ...this.activeStep.trackedProcessGroupIds,\n ...this.collectInteractiveProcessGroupIds(processIds),\n ]),\n ],\n signal,\n );\n return signaledPids || signaledGroups;\n }\n }\n\n const { process: child, processGroupId } = this.activeStep;\n if (processGroupId !== null) {\n try {\n this.runtime.workflowHost.signal(-processGroupId, signal);\n return true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== ESRCH_ERROR_CODE) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_SIGNAL_MESSAGE} process group for ${this.activeStep.stepName}`,\n );\n } else {\n this.logger.info(\n ` ${DIM}signal${RESET} process group for ${this.activeStep.stepName} already exited (ESRCH)`,\n );\n }\n }\n }\n\n try {\n return child.kill(signal);\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_SIGNAL_MESSAGE} ${this.activeStep.stepName} (${(error as Error).message})`,\n );\n return false;\n }\n }\n\n /**\n * Create an empty temp file that the Claude Code Stop hook will write\n * YES to when the agent finishes its turn. The path is injected into\n * WORKFLOW_STATUS_FILE so the hook can locate it directly — no fallback\n * marker file is used.\n */\n private async createStatusFile(): Promise<string> {\n if (!this.runtime.temporaryDirectory)\n throw new Error('Workflow interactive status files require an admitted temporaryDirectory');\n const filePath = join(this.runtime.temporaryDirectory, `${STATUS_FILE_PREFIX}${randomUUID()}${STATUS_FILE_SUFFIX}`);\n getOrThrow(await this.runtime.fs.writeFile(filePath, '', this.runtime.ioContext));\n return filePath;\n }\n\n /**\n * Race interactive step execution against agent completion and workflow stop files.\n * When the file contains YES, SIGTERM the step process and wait for\n * it to exit before returning `status_completed`. Escalates to SIGKILL\n * if the process ignores SIGTERM. The next job must not start until\n * the child process tree has fully exited.\n */\n private async raceInteractiveCompletion(\n executionPromise: Promise<StepExecutionResult>,\n statusFilePath: string,\n stepName: string,\n stopRequestPath: string | undefined,\n pausePolicy: 'replay' | 'protected',\n ): Promise<StepExecutionResult> {\n return new Promise<StepExecutionResult>((resolveRace) => {\n let settled = false;\n let statusFileTriggered = false;\n let stopRequestTriggered = false;\n let pauseRequestTriggered = false;\n const pauseRequestPath = stopRequestPath ? join(dirname(stopRequestPath), PAUSE_REQUEST_FILENAME) : undefined;\n let forceKillTimer: NodeJS.Timeout | null = null;\n let completionSettleTimer: NodeJS.Timeout | null = null;\n let watcher: { close(context: WorkflowRuntimeContext['ioContext']): Promise<void> } | null = null;\n let stopWatcher: { close(context: WorkflowRuntimeContext['ioContext']): Promise<void> } | null = null;\n let pauseWatcher: { close(context: WorkflowRuntimeContext['ioContext']): Promise<void> } | null = null;\n let pollTimer: NodeJS.Timeout | null = null;\n let stopPollTimer: NodeJS.Timeout | null = null;\n let pausePollTimer: NodeJS.Timeout | null = null;\n // Tracks whether SIGTERM was actually delivered to the child\n let signalDelivered = false;\n // Tracks whether escalation to SIGKILL was required\n let sigkillEscalated = false;\n\n const resolveCompletionSource = (result: StepExecutionResult): InteractiveCompletionSource => {\n if (stopRequestTriggered) {\n return 'stop-request';\n }\n if (pauseRequestTriggered) {\n return 'pause-request';\n }\n if (statusFileTriggered) {\n return 'status-file';\n }\n switch (result.status) {\n case RESULT_STATUS_TIMED_OUT:\n return 'timed-out';\n case RESULT_STATUS_SPAWN_ERROR:\n return 'spawn-error';\n case RESULT_STATUS_SIGNALED:\n return 'signaled';\n default:\n return 'natural-exit';\n }\n };\n\n const settle = async (result: StepExecutionResult) => {\n if (settled) return;\n settled = true;\n if (watcher) {\n await watcher\n .close(this.runtime.ioContext)\n .catch((error: unknown) => this.logger.warn(`Workflow watcher cleanup failed: ${String(error)}`));\n watcher = null;\n }\n if (stopWatcher) {\n await stopWatcher\n .close(this.runtime.ioContext)\n .catch((error: unknown) => this.logger.warn(`Workflow watcher cleanup failed: ${String(error)}`));\n stopWatcher = null;\n }\n if (pauseWatcher) {\n await pauseWatcher\n .close(this.runtime.ioContext)\n .catch((error: unknown) => this.logger.warn(`Workflow watcher cleanup failed: ${String(error)}`));\n pauseWatcher = null;\n }\n if (pollTimer) {\n clearInterval(pollTimer);\n pollTimer = null;\n }\n if (stopPollTimer) {\n clearInterval(stopPollTimer);\n stopPollTimer = null;\n }\n if (pausePollTimer) {\n clearInterval(pausePollTimer);\n pausePollTimer = null;\n }\n if (forceKillTimer) {\n clearTimeout(forceKillTimer);\n forceKillTimer = null;\n }\n if (completionSettleTimer) {\n clearTimeout(completionSettleTimer);\n completionSettleTimer = null;\n }\n const settledResult =\n result.status === RESULT_STATUS_PAUSE_REQUESTED && this.lastInteractiveReap?.survivors.length\n ? { ...result, survivors: this.lastInteractiveReap.survivors }\n : result;\n await this.recordInteractiveCompletion({\n timestamp: new Date().toISOString(),\n stepName,\n statusFilePath,\n completionSource: resolveCompletionSource(settledResult),\n statusFileSignaled: statusFileTriggered,\n sigkillEscalated: sigkillEscalated || (this.lastInteractiveReap?.sigkillEscalated ?? false),\n survivors: this.lastInteractiveReap?.survivors ?? [],\n });\n this.lastInteractiveReap = null;\n resolveRace(settledResult);\n };\n\n const statusFileHasCompletionValue = async () => {\n try {\n return (\n (await pathExists(this.runtime.fs, statusFilePath, this.runtime.ioContext)) &&\n getOrThrow(await this.runtime.fs.readTextFile(statusFilePath, this.runtime.ioContext)).trim() ===\n STATUS_FILE_COMPLETION_VALUE\n );\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (!code || !TRANSIENT_FS_ERROR_CODES.has(code)) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} status-file read failed for ${stepName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n } else {\n this.logger.info(` ${DIM}status-file${RESET} transient FS error (${code}) polling ${stepName}`);\n }\n return false;\n }\n };\n\n // Absolute backstop: the status file is the source of truth for completion.\n // If a child ignores SIGTERM *and* SIGKILL its exit event never fires, so\n // `executionPromise` never resolves. Rather than hang the workflow until\n // `timeout-minutes`, settle on the verified completion once the kill grace\n // has elapsed, recording any survivors for the forensic reap log.\n const scheduleAbsoluteSettle = (result: StepExecutionResult, delayMs: number) => {\n if (settled || completionSettleTimer) {\n return;\n }\n completionSettleTimer = setTimeout(() => {\n if (settled) return;\n const survivors = this.collectInteractiveProcessIds().map((pid) => ({\n pid,\n command: this.describeProcess(pid),\n }));\n if (survivors.length > 0) {\n this.lastInteractiveReap = { survivors, sigkillEscalated: true };\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} signalled completion but ${survivors.length} process(es) survived termination; proceeding to the next step: ${survivors\n .map((entry) => `${entry.pid} (${entry.command})`)\n .join(', ')}`,\n );\n }\n void settle(result);\n }, delayMs);\n };\n\n const checkFileContent = async () => {\n if (!(await statusFileHasCompletionValue()) || settled || statusFileTriggered) {\n return;\n }\n\n statusFileTriggered = true;\n const graceMs = this.stepCompletionKillGraceMs();\n signalDelivered = this.killActiveStep(TERMINATE_SIGNAL);\n if (!signalDelivered) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} status-file: SIGTERM could not be delivered, process may have already exited`,\n );\n // The process appears gone; its exit should resolve the race shortly.\n // Still arm the backstop in case the awaited child is not the live agent.\n scheduleAbsoluteSettle(STATUS_FILE_COMPLETED_RESULT, PROCESS_EXIT_WAIT_TIMEOUT_MS);\n return;\n }\n // Give the agent the grace window to flush telemetry and exit before the\n // next job starts; escalate to SIGKILL if SIGTERM is ignored.\n forceKillTimer = setTimeout(() => {\n if (settled) return;\n sigkillEscalated = true;\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} did not exit after status-file SIGTERM, forcing SIGKILL`,\n );\n this.killActiveStep(TERMINATE_FORCE_KILL_SIGNAL);\n }, graceMs);\n // Backstop the child's exit event so a process that survives SIGKILL\n // cannot stall the workflow past the kill grace.\n scheduleAbsoluteSettle(STATUS_FILE_COMPLETED_RESULT, graceMs + PROCESS_EXIT_WAIT_TIMEOUT_MS);\n };\n\n const stopRequestExists = async () =>\n Boolean(stopRequestPath && (await this.hasCurrentStopRequest(stopRequestPath)));\n const pauseRequestExists = async () =>\n Boolean(\n pauseRequestPath &&\n (await pathExists(this.runtime.fs, pauseRequestPath, this.runtime.ioContext)) &&\n (await this.readControlAction(pauseRequestPath)) === 'pause',\n );\n\n const checkStopRequest = async () => {\n if (!(await stopRequestExists()) || settled || stopRequestTriggered) {\n return;\n }\n\n stopRequestTriggered = true;\n const graceMs = this.stepCompletionKillGraceMs();\n signalDelivered = this.killActiveStep(TERMINATE_SIGNAL);\n if (!signalDelivered) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} stop request: SIGTERM could not be delivered, process may have already exited`,\n );\n scheduleAbsoluteSettle({ status: RESULT_STATUS_STOP_REQUESTED }, PROCESS_EXIT_WAIT_TIMEOUT_MS);\n return;\n }\n\n forceKillTimer = setTimeout(() => {\n if (settled) return;\n sigkillEscalated = true;\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} did not exit after stop-request SIGTERM, forcing SIGKILL`,\n );\n this.killActiveStep(TERMINATE_FORCE_KILL_SIGNAL);\n }, graceMs);\n scheduleAbsoluteSettle({ status: RESULT_STATUS_STOP_REQUESTED }, graceMs + PROCESS_EXIT_WAIT_TIMEOUT_MS);\n };\n\n const checkPauseRequest = async () => {\n if (!(await pauseRequestExists()) || settled || stopRequestTriggered || pauseRequestTriggered) {\n return;\n }\n pauseRequestTriggered = true;\n if (pausePolicy === 'protected') return;\n\n const graceMs = this.stepCompletionKillGraceMs();\n signalDelivered = this.killActiveStep(TERMINATE_SIGNAL);\n if (!signalDelivered) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} pause request: SIGTERM could not be delivered, process may have already exited`,\n );\n scheduleAbsoluteSettle({ status: RESULT_STATUS_PAUSE_REQUESTED }, PROCESS_EXIT_WAIT_TIMEOUT_MS);\n return;\n }\n\n forceKillTimer = setTimeout(() => {\n if (settled) return;\n sigkillEscalated = true;\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} did not exit after pause-request SIGTERM, forcing SIGKILL`,\n );\n this.killActiveStep(TERMINATE_FORCE_KILL_SIGNAL);\n }, graceMs);\n scheduleAbsoluteSettle({ status: RESULT_STATUS_PAUSE_REQUESTED }, graceMs + PROCESS_EXIT_WAIT_TIMEOUT_MS);\n };\n\n // fs.watch for instant notification, poll as fallback for edge cases\n try {\n void this.watchStatusFile(\n [{ path: statusFilePath }],\n () => {\n void checkFileContent().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n },\n this.runtime.ioContext,\n )\n .then(async (result) => {\n const admitted = getOrThrow(result);\n if (settled) await admitted.close(this.runtime.ioContext);\n else watcher = admitted;\n })\n .catch((error: unknown) =>\n this.logger.warn(`Workflow status-file watcher unavailable, polling instead: ${String(error)}`),\n );\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} status-file watcher setup failed for ${stepName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n pollTimer = setInterval(() => {\n void checkFileContent().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n }, STATUS_FILE_POLL_INTERVAL_MS);\n if (stopRequestPath) {\n try {\n void this.watchStatusFile(\n [{ path: stopRequestPath }],\n () => {\n void checkStopRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n },\n this.runtime.ioContext,\n )\n .then(async (result) => {\n const admitted = getOrThrow(result);\n if (settled) await admitted.close(this.runtime.ioContext);\n else stopWatcher = admitted;\n })\n .catch((error: unknown) =>\n this.logger.warn(`Workflow stop-request watcher unavailable, polling instead: ${String(error)}`),\n );\n } catch (error) {\n const errorCode = (error as NodeJS.ErrnoException).code;\n if (errorCode !== 'ENOENT') {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} stop-request watcher setup failed for ${stepName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n stopPollTimer = setInterval(() => {\n void checkStopRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n }, STOP_REQUEST_POLL_INTERVAL_MS);\n }\n if (pauseRequestPath) {\n try {\n void this.watchStatusFile(\n [{ path: pauseRequestPath }],\n () => {\n void checkPauseRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n },\n this.runtime.ioContext,\n )\n .then(async (result) => {\n const admitted = getOrThrow(result);\n if (settled) await admitted.close(this.runtime.ioContext);\n else pauseWatcher = admitted;\n })\n .catch((error: unknown) =>\n this.logger.warn(`Workflow pause-request watcher unavailable, polling instead: ${String(error)}`),\n );\n } catch (error) {\n const errorCode = (error as NodeJS.ErrnoException).code;\n if (errorCode !== 'ENOENT') {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} pause-request watcher setup failed for ${stepName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n pausePollTimer = setInterval(() => {\n void checkPauseRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n }, STOP_REQUEST_POLL_INTERVAL_MS);\n }\n\n // Immediate check in case the file was written before watcher setup\n void checkFileContent().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n void checkStopRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n void checkPauseRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n\n void executionPromise.then(async (result) => {\n if (stopRequestTriggered) {\n if (sigkillEscalated) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} required SIGKILL escalation after stop request`,\n );\n }\n void settle({ status: RESULT_STATUS_STOP_REQUESTED });\n return;\n }\n\n const completedViaStatusFile = statusFileTriggered || (await statusFileHasCompletionValue());\n const protectedPauseEligible =\n result.status === RESULT_STATUS_STATUS_COMPLETED ||\n (result.status === RESULT_STATUS_COMPLETED && result.exitCode === 0);\n if (\n pauseRequestTriggered &&\n (pausePolicy !== 'protected' || protectedPauseEligible) &&\n (pausePolicy === 'protected' || !statusFileTriggered)\n ) {\n void settle({ status: RESULT_STATUS_PAUSE_REQUESTED });\n return;\n }\n if (!completedViaStatusFile) {\n void settle(result);\n return;\n }\n\n if (!statusFileTriggered) {\n statusFileTriggered = true;\n this.logger.info(\n ` ${GREEN}${STATUS_DONE}${RESET} ${stepName} status-file observed during process exit handling`,\n );\n }\n\n // The status file is the source of truth for work completion, even\n // when the hook write lands immediately before the process exits and\n // the watcher/poller does not observe it in time.\n switch (result.status) {\n case RESULT_STATUS_SPAWN_ERROR:\n case RESULT_STATUS_TIMED_OUT:\n // Preserve infrastructure failures unchanged.\n void settle(result);\n return;\n case RESULT_STATUS_SIGNALED:\n // Process was killed by a signal, or exited as the Stop hook fired.\n if (sigkillEscalated) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} required SIGKILL escalation (work completed via status-file)`,\n );\n }\n void settle(STATUS_FILE_COMPLETED_RESULT);\n return;\n case RESULT_STATUS_COMPLETED: {\n // Once the stop hook has marked the status file, it is the source\n // of truth for the workflow step. Some CLIs convert SIGTERM into a\n // plain non-zero exit code after their own cleanup; that should not\n // turn verified completion into a failed step.\n if (sigkillEscalated) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} required SIGKILL escalation (work completed via status-file, exit code ${result.exitCode})`,\n );\n }\n void settle(STATUS_FILE_COMPLETED_RESULT);\n return;\n }\n case RESULT_STATUS_STATUS_COMPLETED:\n // Should not happen (would mean double status-file trigger),\n // but pass through as-is.\n void settle(result);\n return;\n case RESULT_STATUS_STOP_REQUESTED:\n case RESULT_STATUS_PAUSE_REQUESTED:\n void settle(result);\n return;\n default: {\n const _exhaustive: never = result;\n void settle(_exhaustive);\n }\n }\n });\n });\n }\n\n private async raceStopRequest(\n executionPromise: Promise<StepExecutionResult>,\n stepName: string,\n stopRequestPath: string,\n pausePolicy: 'replay' | 'protected',\n ): Promise<StepExecutionResult> {\n return new Promise<StepExecutionResult>((resolveRace) => {\n let settled = false;\n let stopRequestTriggered = false;\n let pauseRequestTriggered = false;\n const pauseRequestPath = join(dirname(stopRequestPath), PAUSE_REQUEST_FILENAME);\n let forceKillTimer: NodeJS.Timeout | null = null;\n let pollTimer: NodeJS.Timeout | null = null;\n let watcher: { close(context: WorkflowRuntimeContext['ioContext']): Promise<void> } | null = null;\n\n const settle = async (result: StepExecutionResult) => {\n if (settled) return;\n settled = true;\n if (watcher) {\n await watcher\n .close(this.runtime.ioContext)\n .catch((error: unknown) => this.logger.warn(`Workflow watcher cleanup failed: ${String(error)}`));\n watcher = null;\n }\n if (pollTimer) {\n clearInterval(pollTimer);\n pollTimer = null;\n }\n if (forceKillTimer) {\n clearTimeout(forceKillTimer);\n forceKillTimer = null;\n }\n resolveRace(result);\n };\n\n const checkStopRequest = async () => {\n if ((await this.hasCurrentStopRequest(stopRequestPath)) && !settled && !stopRequestTriggered) {\n stopRequestTriggered = true;\n this.killActiveStep(TERMINATE_SIGNAL);\n forceKillTimer ??= setTimeout(() => {\n if (!settled) this.killActiveStep(TERMINATE_FORCE_KILL_SIGNAL);\n }, FORCE_KILL_GRACE_PERIOD_MS);\n return;\n }\n if (\n stopRequestTriggered ||\n pauseRequestTriggered ||\n !(await pathExists(this.runtime.fs, pauseRequestPath, this.runtime.ioContext))\n )\n return;\n if (\n (await this.readControlAction(pauseRequestPath)) !== 'pause' ||\n settled ||\n stopRequestTriggered ||\n pauseRequestTriggered\n )\n return;\n pauseRequestTriggered = true;\n if (pausePolicy === 'protected') return;\n this.killActiveStep(TERMINATE_SIGNAL);\n forceKillTimer ??= setTimeout(() => {\n if (!settled) this.killActiveStep(TERMINATE_FORCE_KILL_SIGNAL);\n }, FORCE_KILL_GRACE_PERIOD_MS);\n };\n\n try {\n void this.watchStatusFile(\n [{ path: stopRequestPath }],\n () => {\n void checkStopRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n },\n this.runtime.ioContext,\n )\n .then(async (result) => {\n const admitted = getOrThrow(result);\n if (settled) await admitted.close(this.runtime.ioContext);\n else watcher = admitted;\n })\n .catch((error: unknown) =>\n this.logger.warn(`Workflow stop-request watcher unavailable, polling instead: ${String(error)}`),\n );\n } catch (error) {\n const errorCode = (error as NodeJS.ErrnoException).code;\n if (errorCode !== 'ENOENT') {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} stop-request watcher setup failed for ${stepName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n pollTimer = setInterval(() => {\n void checkStopRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n }, STOP_REQUEST_POLL_INTERVAL_MS);\n void checkStopRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n\n void executionPromise.then(async (result) => {\n const protectedPauseEligible =\n result.status === RESULT_STATUS_STATUS_COMPLETED ||\n (result.status === RESULT_STATUS_COMPLETED && result.exitCode === 0);\n if (stopRequestTriggered) void settle({ status: RESULT_STATUS_STOP_REQUESTED });\n else if (pauseRequestTriggered && (pausePolicy !== 'protected' || protectedPauseEligible)) {\n void settle({ status: RESULT_STATUS_PAUSE_REQUESTED });\n } else void settle(result);\n });\n });\n }\n\n private async hasCurrentStopRequest(path: string): Promise<boolean> {\n try {\n const value: unknown = JSON.parse(getOrThrow(await this.runtime.fs.readTextFile(path, this.runtime.ioContext)));\n if (!value || typeof value !== 'object') return false;\n const request = value as { runId?: unknown; schemaVersion?: unknown };\n if (request.schemaVersion !== 1 || typeof request.runId !== 'string') return false;\n const record = JSON.parse(\n getOrThrow(\n await this.runtime.fs.readTextFile(join(dirname(path), RUN_RECORD_FILENAME), this.runtime.ioContext),\n ),\n ) as {\n runId?: unknown;\n };\n return request.runId === record.runId;\n } catch {\n return false;\n }\n }\n\n private async readControlAction(path: string): Promise<'pause' | 'resume' | undefined> {\n try {\n const value: unknown = JSON.parse(getOrThrow(await this.runtime.fs.readTextFile(path, this.runtime.ioContext)));\n if (!value || typeof value !== 'object') return undefined;\n const request = value as { action?: unknown; runId?: unknown; schemaVersion?: unknown };\n if (\n (request.action !== 'pause' && request.action !== 'resume') ||\n request.schemaVersion !== 1 ||\n typeof request.runId !== 'string'\n ) {\n return undefined;\n }\n const record = JSON.parse(\n getOrThrow(\n await this.runtime.fs.readTextFile(join(dirname(path), RUN_RECORD_FILENAME), this.runtime.ioContext),\n ),\n ) as {\n runId?: unknown;\n };\n return request.runId === record.runId ? request.action : undefined;\n } catch {\n return undefined;\n }\n }\n\n private async markPaused(\n stopRequestPath: string | undefined,\n stepName: string,\n pausePolicy: 'replay' | 'protected',\n survivors: InteractiveProcessReport[] = [],\n resumeMode: 'replay-current' | 'continue-next' = pausePolicy === 'protected' ? 'continue-next' : 'replay-current',\n ): Promise<void> {\n if (!stopRequestPath) return;\n if (await this.hasCurrentStopRequest(stopRequestPath)) {\n throw new WorkflowInterruptedError(TERMINATE_SIGNAL, {\n cause: new Error(`Workflow stop requested before pause acknowledgement for \"${stepName}\"`),\n context: this.createInterruptContext(stepName, ''),\n });\n }\n if (survivors.length > 0) {\n throw new Error(\n `Cannot acknowledge pause for \"${stepName}\" because ${survivors.length} child process(es) survived termination: ${survivors\n .map((entry) => `${entry.pid} (${entry.command})`)\n .join(', ')}`,\n );\n }\n const recordPath = join(dirname(stopRequestPath), RUN_RECORD_FILENAME);\n try {\n const record = JSON.parse(\n getOrThrow(await this.runtime.fs.readTextFile(recordPath, this.runtime.ioContext)),\n ) as Record<string, unknown>;\n const cursor =\n record.executionCursor && typeof record.executionCursor === 'object'\n ? (record.executionCursor as Record<string, unknown>)\n : { executionGeneration: 1, phase: 'step', resumeMode: 'replay-current' };\n const request = (await pathExists(\n this.runtime.fs,\n join(dirname(stopRequestPath), PAUSE_REQUEST_FILENAME),\n this.runtime.ioContext,\n ))\n ? (JSON.parse(\n getOrThrow(\n await this.runtime.fs.readTextFile(\n join(dirname(stopRequestPath), PAUSE_REQUEST_FILENAME),\n this.runtime.ioContext,\n ),\n ),\n ) as Record<string, unknown>)\n : undefined;\n record.executionState = 'paused';\n record.executionCursor = {\n ...cursor,\n phase: 'step',\n requestId: typeof request?.requestId === 'string' ? request.requestId : cursor.requestId,\n revision: typeof cursor.revision === 'number' ? cursor.revision + 1 : 1,\n stepName,\n resumeMode,\n };\n await this.writeControlRecord(recordPath, record);\n } catch (error) {\n this.logger.warn(` ${YELLOW}${STATUS_WARN}${RESET} could not persist paused state: ${String(error)}`);\n throw error;\n }\n }\n\n private async waitForResume(stopRequestPath: string | undefined, stepName: string): Promise<void> {\n if (!stopRequestPath) return;\n const pauseRequestPath = join(dirname(stopRequestPath), PAUSE_REQUEST_FILENAME);\n const recordPath = join(dirname(stopRequestPath), RUN_RECORD_FILENAME);\n this.logger.info(` ${YELLOW}${STATUS_WAIT}${RESET} ${stepName} paused; waiting for resume`);\n while (true) {\n if (this.interruptedSignal) {\n throw new WorkflowInterruptedError(this.interruptedSignal, {\n cause: new Error(`Workflow interrupted while paused: ${stepName}`),\n context: this.createInterruptContext(stepName, ''),\n });\n }\n if (await this.hasCurrentStopRequest(stopRequestPath))\n throw new WorkflowInterruptedError(TERMINATE_SIGNAL, {\n cause: new Error(`Workflow stop requested while paused: ${stepName}`),\n context: this.createInterruptContext(stepName, ''),\n });\n if (\n (await pathExists(this.runtime.fs, pauseRequestPath, this.runtime.ioContext)) &&\n (await this.readControlAction(pauseRequestPath)) === 'resume'\n ) {\n const record = JSON.parse(\n getOrThrow(await this.runtime.fs.readTextFile(recordPath, this.runtime.ioContext)),\n ) as Record<string, unknown>;\n record.executionState = 'running';\n const cursor =\n record.executionCursor && typeof record.executionCursor === 'object'\n ? (record.executionCursor as Record<string, unknown>)\n : {};\n const request = JSON.parse(\n getOrThrow(await this.runtime.fs.readTextFile(pauseRequestPath, this.runtime.ioContext)),\n ) as Record<string, unknown>;\n const resumeMode = cursor.resumeMode === 'continue-next' ? 'continue-next' : 'replay-current';\n record.executionCursor = {\n ...cursor,\n executionGeneration:\n resumeMode === 'replay-current' && typeof cursor.executionGeneration === 'number'\n ? cursor.executionGeneration + 1\n : typeof cursor.executionGeneration === 'number'\n ? cursor.executionGeneration\n : 1,\n requestId: typeof request.requestId === 'string' ? request.requestId : cursor.requestId,\n revision: typeof cursor.revision === 'number' ? cursor.revision + 1 : 1,\n resumeMode,\n };\n await this.writeControlRecord(recordPath, record);\n return;\n }\n await new Promise((resolvePromise) => setTimeout(resolvePromise, STOP_REQUEST_POLL_INTERVAL_MS));\n }\n }\n\n private async writeControlRecord(recordPath: string, record: Record<string, unknown>): Promise<void> {\n await writeFileAtomic(this.runtime.fs, recordPath, `${JSON.stringify(record, null, 2)}\\n`, this.runtime.ioContext);\n }\n\n private captureTerminalState(): string | null {\n // Not ours to save or put back. The host that owns this terminal is the one\n // that knows what state it wants, and it is still using it while we run.\n if (!this.ownsTerminal) {\n return null;\n }\n\n return this.runtime.workflowHost.readTerminalState() ?? null;\n }\n\n private restoreTerminalState(terminalState: string | null): void {\n if (!this.ownsTerminal) return;\n try {\n this.runtime.workflowHost.restoreTerminalState(terminalState ?? undefined);\n } catch (error) {\n this.logger.warn(` ${YELLOW}${STATUS_WARN}${RESET} failed to restore terminal state: ${String(error)}`);\n }\n }\n\n /**\n * Remove the temp status file and the well-known marker file after step completion.\n */\n private async cleanupStatusFile(statusFilePath: string): Promise<void> {\n try {\n if (await pathExists(this.runtime.fs, statusFilePath, this.runtime.ioContext)) {\n getOrThrow(await this.runtime.fs.remove(statusFilePath, { force: true }, this.runtime.ioContext));\n }\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} status-file cleanup failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n}\n","import { dirname, resolve } from 'node:path';\nimport type { Interface } from 'node:readline';\n/**\n * TriggerService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\n\nimport { WorkflowInterruptedError } from '../../models/WorkflowInterruptedError';\nimport type { AgentDecisionTrigger, MatrixEntry, Workflow } from '../../schemas/workflowEngine';\nimport type { StepRunnerService } from '../StepRunnerService';\nimport type { Logger, StepRunOptions } from '../workflowEngine/type';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\nconst CYAN = '\\x1b[36m';\nconst GREEN = '\\x1b[32m';\nconst RED = '\\x1b[31m';\nconst BLUE = '\\x1b[34m';\nconst INTERRUPT_SIGNAL: NodeJS.Signals = 'SIGINT';\nconst USER_PROMPT_EVENT = 'user_prompt';\nconst AGENT_DECISION_EVENT = 'agent_decision';\nconst SEPARATOR_WIDTH = 50;\nconst PROMPT_PREVIEW_MAX_CHARS = 80;\nconst DRY_RUN_PROMPT_TEXT = '(dry-run: no prompt collected)';\n\n/**\n * Handles trigger-specific setup before the workflow job graph starts.\n */\nexport class TriggerService {\n private activePrompt: Interface | null = null;\n private activePromptSignal: NodeJS.Signals | null = null;\n\n /**\n * Create a trigger handler bound to the step runner used for trigger steps\n * and the workflow logger used for user-facing output.\n */\n constructor(\n readonly runtime: WorkflowRuntimeContext,\n private stepRunner: StepRunnerService,\n private logger: Logger,\n ) {}\n\n /**\n * Check whether a path exists without throwing when it is absent.\n */\n private async pathExists(path: string): Promise<boolean> {\n try {\n getOrThrow(await this.runtime.fs.fileInfo(path, this.runtime.ioContext));\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Clear the cancellation state retained from a previous workflow run.\n */\n resetInterruption(): void {\n this.activePromptSignal = null;\n }\n\n /**\n * Abort an active interactive prompt so the workflow can unwind quickly.\n */\n abortActivePrompt(signal: NodeJS.Signals): void {\n this.activePromptSignal = signal;\n this.activePrompt?.close();\n }\n\n /**\n * Collect prompt context for workflows triggered by `user_prompt`.\n *\n * Uses `workflowEnv.CONTEXT_FILE` when present to read or persist the prompt,\n * and writes the final prompt to `workflowEnv.USER_PROMPT` for downstream\n * job execution.\n */\n async handleUserPrompt(\n workflow: Workflow,\n cliPrompt: string | null,\n workflowEnv: Record<string, string>,\n workflowDir: string,\n dryRun: boolean,\n ): Promise<boolean> {\n if (!workflow.on || !(USER_PROMPT_EVENT in workflow.on)) return true;\n\n this.logger.info(`\\n ${BLUE}${BOLD}trigger${RESET} ${BOLD}user_prompt${RESET}`);\n this.logger.info(` ${'─'.repeat(SEPARATOR_WIDTH)}`);\n\n let userInput = cliPrompt;\n\n // If context file already exists, read from it instead of prompting\n const contextFile = workflowEnv.CONTEXT_FILE;\n if (!userInput && contextFile) {\n const contextPath = resolve(workflowDir, contextFile);\n if (await this.pathExists(contextPath)) {\n userInput = getOrThrow(await this.runtime.fs.readTextFile(contextPath, this.runtime.ioContext)).trim();\n if (userInput) {\n this.logger.info(` ${GREEN}found${RESET} Existing context.md -> ${contextFile}`);\n }\n }\n }\n\n if (!userInput) {\n if (dryRun) {\n this.logger.info(` ${CYAN}dry ${RESET} Would prompt user for input`);\n userInput = DRY_RUN_PROMPT_TEXT;\n } else {\n this.logger.info(` ${CYAN}input${RESET} Enter your prompt (press Enter twice to finish):\\n`);\n const lines: string[] = [];\n const rl = this.runtime.workflowHost.createPrompt();\n const promptResult = new Promise<string>((res, rej) => {\n let settled = false;\n const finish = (callback: () => void) => {\n if (settled) {\n return;\n }\n settled = true;\n this.activePrompt = null;\n callback();\n };\n\n rl.on('line', (line) => {\n if (line === '' && lines.length > 0 && lines[lines.length - 1] === '') {\n rl.close();\n } else {\n lines.push(line);\n }\n });\n\n rl.on('SIGINT', () => {\n this.activePromptSignal = INTERRUPT_SIGNAL;\n rl.close();\n });\n\n rl.on('close', () =>\n finish(() => {\n const signal = this.activePromptSignal;\n this.activePromptSignal = null;\n if (signal) {\n rej(new WorkflowInterruptedError(signal));\n return;\n }\n\n if (lines.length > 0 && lines[lines.length - 1] === '') {\n lines.pop();\n }\n res(lines.join('\\n'));\n }),\n );\n });\n this.activePrompt = rl;\n if (this.activePromptSignal) {\n rl.close();\n }\n userInput = await promptResult;\n }\n }\n\n if (!userInput) {\n this.logger.error(` ${RED}fail${RESET} No prompt provided. Aborting.`);\n return false;\n }\n\n // Write prompt to context file\n if (contextFile) {\n const contextPath = resolve(workflowDir, contextFile);\n const contextDir = dirname(contextPath);\n getOrThrow(await this.runtime.fs.createDir(contextDir, { recursive: true }, this.runtime.ioContext));\n getOrThrow(await this.runtime.fs.writeFile(contextPath, userInput, this.runtime.ioContext));\n this.logger.info(` ${GREEN}saved${RESET} ${userInput.split('\\n').length} line(s) -> ${contextFile}`);\n }\n\n workflowEnv.USER_PROMPT = userInput;\n\n this.logger.info(\n ` ${DIM}prompt${RESET} ${userInput.split('\\n')[0].slice(0, PROMPT_PREVIEW_MAX_CHARS)}${userInput.includes('\\n') ? '...' : ''}`,\n );\n return true;\n }\n\n /**\n * Execute `agent_decision` steps that decide whether the workflow should proceed.\n *\n * Reads and writes workflow context via `workflowEnv.CONTEXT_FILE`, and\n * copies CLI prompt content into `workflowEnv.HEARTBEAT_PROMPT` when supplied.\n */\n async handleAgentDecision(\n workflow: Workflow,\n workflowEnv: Record<string, string>,\n inputs: Map<string, string>,\n secrets: Map<string, string>,\n options: StepRunOptions,\n prompt: string | null,\n ): Promise<boolean> {\n const trigger = workflow.on?.[AGENT_DECISION_EVENT] as AgentDecisionTrigger | undefined;\n if (!trigger?.steps) return true;\n\n this.logger.info(`\\n ${BLUE}${BOLD}trigger${RESET} ${BOLD}agent_decision${RESET}`);\n this.logger.info(` ${'─'.repeat(SEPARATOR_WIDTH)}`);\n\n if (prompt) {\n workflowEnv.HEARTBEAT_PROMPT = prompt;\n this.logger.info(\n ` ${DIM}prompt${RESET} ${prompt.split('\\n')[0].slice(0, PROMPT_PREVIEW_MAX_CHARS)}${prompt.includes('\\n') ? '...' : ''}`,\n );\n }\n\n // Ensure context dir exists\n const contextFile = workflowEnv.CONTEXT_FILE;\n if (contextFile) {\n const contextDir = dirname(resolve(options.workflowDir, contextFile));\n getOrThrow(await this.runtime.fs.createDir(contextDir, { recursive: true }, this.runtime.ioContext));\n }\n\n const stepContext = {\n inputs,\n matrix: {} as MatrixEntry,\n secrets,\n env: workflowEnv,\n };\n\n for (const [index, step] of trigger.steps.entries()) {\n const stepName = step.name ?? `step ${index + 1}`;\n await options.onStepStarted?.(stepName, index, trigger.steps.length);\n const ok = await this.stepRunner.runStep(step, stepContext, options);\n if (!ok) {\n this.logger.error(`\\n ${RED}Agent decision aborted workflow${RESET}`);\n return false;\n }\n }\n\n // Verify context file has content\n if (contextFile && !options.dryRun) {\n const contextPath = resolve(options.workflowDir, contextFile);\n if (!(await this.pathExists(contextPath))) {\n this.logger.error(` ${RED}fail${RESET} Context file not created: ${contextFile}`);\n return false;\n }\n const content = getOrThrow(await this.runtime.fs.readTextFile(contextPath, this.runtime.ioContext)).trim();\n if (!content) {\n this.logger.error(` ${RED}fail${RESET} Context file is empty: ${contextFile}`);\n return false;\n }\n this.logger.info(` ${GREEN}ready${RESET} context has ${content.split('\\n').length} line(s)`);\n }\n\n return true;\n }\n}\n","import { basename, resolve } from 'node:path';\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\n/**\n * WorkflowRepairService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n * - Document complex logic with comments\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { WorkflowRepairRecordSchema } from '../../schemas/workflowEngine';\nimport type {\n WorkflowRepairJobStatus,\n WorkflowRepairRecord,\n WorkflowRepairRoutingFallback,\n} from '../../schemas/workflowEngine';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nconst ISSUES_DIRNAME = 'issues';\nconst ISSUE_FILENAME = 'issue.md';\nconst REPAIR_FILENAME = 'repair.json';\nconst MINIMUM_REPAIR_ID_WIDTH = 3;\nconst DEVELOPMENT_JOB_NAME = 'development';\nconst FALLBACK_RESTART_JOB_INDEX = 1;\n\nexport interface CreateWorkflowRepairInput {\n emittingJob: string;\n fixContent: string;\n fixCycle: number;\n invalidTarget?: string;\n jobOrder: string[];\n restartFrom?: string;\n runDir: string;\n}\n\nexport interface ResolveRepairRouteResult {\n rejected: boolean;\n restartFrom: string;\n routingFallback?: WorkflowRepairRoutingFallback;\n scopeJobs: string[];\n}\n\nexport class WorkflowRepairService {\n constructor(readonly runtime: WorkflowRuntimeContext) {}\n\n async createRepair(input: CreateWorkflowRepairInput): Promise<WorkflowRepairRecord> {\n const issueDir = await this.allocateIssueDirectory(input.runDir);\n const repairId = basename(issueDir);\n if (!repairId) {\n throw new Error(`Unable to resolve repair ID from issue directory: ${issueDir}`);\n }\n\n const issuePath = resolve(issueDir, ISSUE_FILENAME);\n const route = this.resolveRoute(input);\n const now = new Date().toISOString();\n const repair: WorkflowRepairRecord = {\n createdAt: now,\n fixCycle: input.fixCycle,\n issueFile: `${ISSUES_DIRNAME}/${repairId}/${ISSUE_FILENAME}`,\n jobs: route.scopeJobs.map((jobName) => ({ attempts: [], jobName, status: 'pending' })),\n rejectedAt: route.rejected ? now : undefined,\n repairId,\n restartFrom: route.restartFrom,\n routingFallback: route.routingFallback,\n schemaVersion: 1,\n scopeJobs: route.scopeJobs,\n status: route.rejected ? 'rejected' : 'pending',\n updatedAt: now,\n verificationJob: input.emittingJob,\n };\n\n try {\n getOrThrow(await this.runtime.fs.writeFile(issuePath, input.fixContent, this.runtime.ioContext));\n await this.writeRepair(input.runDir, repair);\n return repair;\n } catch (error) {\n getOrThrow(await this.runtime.fs.remove(issueDir, { force: true, recursive: true }, this.runtime.ioContext));\n throw error;\n }\n }\n\n async readRepair(runDir: string, repairId: string): Promise<WorkflowRepairRecord> {\n const content = getOrThrow(\n await this.runtime.fs.readTextFile(this.repairPath(runDir, repairId), this.runtime.ioContext),\n );\n return WorkflowRepairRecordSchema.parse(JSON.parse(content));\n }\n\n async activateRepair(runDir: string, repair: WorkflowRepairRecord): Promise<WorkflowRepairRecord> {\n if (repair.status !== 'pending') {\n return repair;\n }\n return await this.writeStatus(runDir, repair, 'active');\n }\n\n async resolveRepair(runDir: string, repair: WorkflowRepairRecord): Promise<WorkflowRepairRecord> {\n const now = new Date().toISOString();\n return await this.writeRepair(runDir, {\n ...repair,\n resolvedAt: now,\n status: 'resolved',\n updatedAt: now,\n });\n }\n\n async supersedeRepair(\n runDir: string,\n repair: WorkflowRepairRecord,\n supersededBy: string,\n ): Promise<WorkflowRepairRecord> {\n const now = new Date().toISOString();\n return await this.writeRepair(runDir, {\n ...repair,\n status: 'superseded',\n supersededAt: now,\n supersededBy,\n updatedAt: now,\n });\n }\n\n async startJob(\n runDir: string,\n repair: WorkflowRepairRecord,\n jobName: string,\n workflowRunId?: string,\n ): Promise<WorkflowRepairRecord> {\n const jobIndex = repair.jobs.findIndex((job) => job.jobName === jobName);\n if (jobIndex < 0) {\n throw new Error(`Job \"${jobName}\" is outside repair ${repair.repairId} scope`);\n }\n\n const now = new Date().toISOString();\n const jobs = repair.jobs.map((job, index) => {\n if (index !== jobIndex) {\n return job;\n }\n return {\n ...job,\n attempts: [\n ...job.attempts,\n {\n attempt: job.attempts.length + 1,\n startedAt: now,\n status: 'running' as const,\n workflowRunId,\n },\n ],\n status: 'running' as const,\n };\n });\n\n return await this.writeRepair(runDir, { ...repair, jobs, status: 'active', updatedAt: now });\n }\n\n async finishJob(\n runDir: string,\n repair: WorkflowRepairRecord,\n jobName: string,\n status: Exclude<WorkflowRepairJobStatus, 'pending' | 'running' | 'skipped'>,\n ): Promise<WorkflowRepairRecord> {\n const now = new Date().toISOString();\n const jobs = repair.jobs.map((job) => {\n if (job.jobName !== jobName) {\n return job;\n }\n const attempts = [...job.attempts];\n const latest = attempts.at(-1);\n if (!latest) {\n throw new Error(`Repair ${repair.repairId} job \"${jobName}\" has no running attempt`);\n }\n attempts[attempts.length - 1] = { ...latest, finishedAt: now, status };\n return { ...job, attempts, status };\n });\n\n return await this.writeRepair(runDir, { ...repair, jobs, updatedAt: now });\n }\n\n /**\n * Mark scope jobs the run jumped over as skipped.\n *\n * A forward jump inside an active repair leaves jobs that never ran and never\n * will for this repair. They carry no attempt: an attempt records an\n * execution, and none happened. Recording the decision keeps recovery honest —\n * `resolveRecoveryStart` would otherwise resume at a job the repair\n * deliberately passed by.\n */\n async skipJobs(runDir: string, repair: WorkflowRepairRecord, jobNames: string[]): Promise<WorkflowRepairRecord> {\n const skipped = new Set(jobNames);\n for (const jobName of skipped) {\n if (!repair.jobs.some((job) => job.jobName === jobName)) {\n throw new Error(`Job \"${jobName}\" is outside repair ${repair.repairId} scope`);\n }\n }\n\n const now = new Date().toISOString();\n const jobs = repair.jobs.map((job) => (skipped.has(job.jobName) ? { ...job, status: 'skipped' as const } : job));\n\n return await this.writeRepair(runDir, { ...repair, jobs, updatedAt: now });\n }\n\n resolveRecoveryStart(repair: WorkflowRepairRecord): string {\n if (repair.status === 'pending') {\n return repair.restartFrom;\n }\n\n for (const jobName of repair.scopeJobs) {\n const job = repair.jobs.find((candidate) => candidate.jobName === jobName);\n // A skipped job is as done as a completed one: the repair chose to pass\n // over it, so resuming there would undo that decision.\n if (!job || (job.status !== 'completed' && job.status !== 'skipped')) {\n return jobName;\n }\n }\n\n return repair.verificationJob;\n }\n\n private resolveRoute(input: CreateWorkflowRepairInput): ResolveRepairRouteResult {\n if (input.jobOrder.length === 0) {\n throw new Error('Cannot create a workflow repair without jobs');\n }\n\n const emittingIndex = input.jobOrder.indexOf(input.emittingJob);\n if (emittingIndex < 0) {\n throw new Error(`Repair emitter \"${input.emittingJob}\" is not in the workflow job order`);\n }\n\n let restartFrom = input.restartFrom;\n let routingFallback: WorkflowRepairRoutingFallback | undefined;\n if (!restartFrom) {\n const fallbackIndex = this.fallbackRestartIndex(input.jobOrder);\n restartFrom = input.jobOrder[fallbackIndex];\n routingFallback = {\n reason: input.invalidTarget ? 'unknown' : 'missing',\n requestedTarget: input.invalidTarget,\n resolvedTarget: restartFrom,\n };\n }\n\n const restartIndex = input.jobOrder.indexOf(restartFrom);\n if (restartIndex < 0) {\n throw new Error(`Resolved repair target \"${restartFrom}\" is not in the workflow job order`);\n }\n\n const rejected = Boolean(input.invalidTarget) || restartIndex > emittingIndex;\n return {\n rejected,\n restartFrom,\n routingFallback,\n scopeJobs: rejected ? [] : input.jobOrder.slice(restartIndex, emittingIndex + 1),\n };\n }\n\n private fallbackRestartIndex(jobOrder: string[]): number {\n const developmentIndex = jobOrder.indexOf(DEVELOPMENT_JOB_NAME);\n if (developmentIndex >= 0) {\n return developmentIndex;\n }\n return Math.min(FALLBACK_RESTART_JOB_INDEX, jobOrder.length - 1);\n }\n\n private async allocateIssueDirectory(runDir: string): Promise<string> {\n const issuesDir = resolve(runDir, ISSUES_DIRNAME);\n getOrThrow(await this.runtime.fs.createDir(issuesDir, { recursive: true }, this.runtime.ioContext));\n const entries = getOrThrow(await this.runtime.fs.listDir(issuesDir, this.runtime.ioContext));\n const highest = entries.reduce((max, entry) => {\n if (entry.kind !== 'directory' || !/^\\d+$/.test(entry.name)) {\n return max;\n }\n return Math.max(max, Number(entry.name));\n }, 0);\n\n for (let next = highest + 1; ; next++) {\n const repairId = String(next).padStart(MINIMUM_REPAIR_ID_WIDTH, '0');\n const issueDir = resolve(issuesDir, repairId);\n try {\n getOrThrow(await this.runtime.fs.createDir(issueDir, undefined, this.runtime.ioContext));\n return issueDir;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error;\n }\n }\n }\n }\n\n private async writeStatus(\n runDir: string,\n repair: WorkflowRepairRecord,\n status: WorkflowRepairRecord['status'],\n ): Promise<WorkflowRepairRecord> {\n const updated = { ...repair, status, updatedAt: new Date().toISOString() };\n return await this.writeRepair(runDir, updated);\n }\n\n private async writeRepair(runDir: string, repair: WorkflowRepairRecord): Promise<WorkflowRepairRecord> {\n const validated = WorkflowRepairRecordSchema.parse(repair);\n const targetPath = this.repairPath(runDir, repair.repairId);\n const tempPath = `${targetPath}.${this.runtime.workflowHost.processId}.${Date.now()}.tmp`;\n try {\n getOrThrow(\n await this.runtime.fs.writeFile(tempPath, `${JSON.stringify(validated, null, 2)}\\n`, this.runtime.ioContext),\n );\n getOrThrow(await this.runtime.fs.renameFile(tempPath, targetPath, this.runtime.ioContext));\n return validated;\n } catch (error) {\n try {\n getOrThrow(await this.runtime.fs.remove(tempPath, undefined, this.runtime.ioContext));\n } catch (cleanupError) {\n if ((cleanupError as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw cleanupError;\n }\n }\n throw error;\n }\n }\n\n private repairPath(runDir: string, repairId: string): string {\n return resolve(runDir, ISSUES_DIRNAME, repairId, REPAIR_FILENAME);\n }\n}\n","/**\n * WorktreeService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { basename, dirname, resolve } from 'node:path';\n\nimport { getOrThrow, pathExists, removePath } from '@agimon-ai/po-core/platform';\n\nimport type { MatrixEntry, WorktreeHook } from '../../schemas/workflowEngine';\nimport type { StepRunnerService } from '../StepRunnerService';\nimport type { Logger } from '../workflowEngine/type';\nimport { workflowShellOutput } from '../workflowRuntime';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nconst RESET = '\\x1b[0m';\nconst DIM = '\\x1b[2m';\nconst CYAN = '\\x1b[36m';\nconst YELLOW = '\\x1b[33m';\n\nexport class WorktreeService {\n constructor(\n private runtime: WorkflowRuntimeContext,\n private stepRunner: StepRunnerService,\n private logger: Logger,\n ) {}\n\n getWorktreeBranchName(workflowName: string): string {\n const safeName = workflowName\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-|-$/g, '');\n\n return `worktree/${safeName}`;\n }\n\n async createWorktree(repoRoot: string, workflowName: string): Promise<string> {\n repoRoot = resolve(this.runtime.cwd, repoRoot);\n const branchName = this.getWorktreeBranchName(workflowName);\n const safeName = branchName.slice('worktree/'.length);\n const parentDir = dirname(repoRoot);\n const folderName = basename(repoRoot);\n const worktreeBase = resolve(parentDir, `${folderName}-worktree`);\n const worktreePath = resolve(worktreeBase, safeName);\n\n if (!(await pathExists(this.runtime.fs, worktreeBase, this.runtime.ioContext))) {\n getOrThrow(await this.runtime.fs.createDir(worktreeBase, { recursive: true }, this.runtime.ioContext));\n }\n\n // Remove stale worktree if it exists\n if (await pathExists(this.runtime.fs, worktreePath, this.runtime.ioContext)) {\n this.logger.info(` ${DIM}clean${RESET} Removing stale worktree at ${worktreePath}`);\n await this.cleanupWorktreePath(repoRoot, worktreePath);\n }\n\n // Delete existing branch if it exists (from a previous run)\n try {\n await workflowShellOutput(this.runtime, `git branch -D \"${branchName}\"`, { cwd: repoRoot });\n } catch {\n // Branch doesn't exist, that's fine\n }\n\n this.logger.info(` ${CYAN}create${RESET} Worktree at ${worktreePath} (branch: ${branchName})`);\n await workflowShellOutput(this.runtime, `git worktree add -b \"${branchName}\" \"${worktreePath}\" HEAD`, {\n cwd: repoRoot,\n });\n\n return worktreePath;\n }\n\n async removeWorktree(repoRoot: string, worktreePath: string): Promise<void> {\n repoRoot = resolve(this.runtime.cwd, repoRoot);\n worktreePath = resolve(this.runtime.cwd, worktreePath);\n if (!(await pathExists(this.runtime.fs, worktreePath, this.runtime.ioContext))) return;\n\n this.logger.info(` ${DIM}remove${RESET} Worktree at ${worktreePath}`);\n try {\n await this.cleanupWorktreePath(repoRoot, worktreePath);\n } catch {\n this.logger.warn(` ${YELLOW}warn${RESET} Failed to remove worktree (may need manual cleanup)`);\n }\n }\n\n private async cleanupWorktreePath(repoRoot: string, worktreePath: string): Promise<void> {\n if (await this.isRegisteredWorktree(repoRoot, worktreePath)) {\n await workflowShellOutput(this.runtime, `git worktree remove --force \"${worktreePath}\"`, { cwd: repoRoot });\n return;\n }\n\n await removePath(this.runtime.fs, worktreePath, this.runtime.ioContext);\n }\n\n private async isRegisteredWorktree(repoRoot: string, worktreePath: string): Promise<boolean> {\n try {\n const output = await workflowShellOutput(this.runtime, 'git worktree list --porcelain', { cwd: repoRoot });\n\n return output\n .split('\\n')\n .some(\n (line) =>\n line.startsWith('worktree ') && resolve(this.runtime.cwd, line.slice('worktree '.length)) === worktreePath,\n );\n } catch {\n return false;\n }\n }\n\n async runHook(\n hook: WorktreeHook,\n cwd: string,\n baseEnv: Record<string, string>,\n inputs: Map<string, string>,\n secrets: Map<string, string>,\n options: {\n cliAgent?: string;\n runner?: string;\n dryRun: boolean;\n continueOnError: boolean;\n stopRequestPath?: string;\n onStepStarted?: (\n stepName: string,\n index: number,\n total: number,\n matrixIndex?: number,\n attempt?: number,\n ) => Promise<void> | void;\n onExecutionStateChange?: (state: 'paused' | 'resumed', stepName: string) => Promise<void> | void;\n },\n ): Promise<boolean> {\n const stepContext = {\n inputs,\n matrix: {} as MatrixEntry,\n secrets,\n env: baseEnv,\n };\n\n for (const [index, step] of hook.steps.entries()) {\n const stepName = step.name ?? `step ${index + 1}`;\n await options.onStepStarted?.(stepName, index, hook.steps.length);\n const ok = await this.stepRunner.runStep(step, stepContext, { ...options, workflowDir: cwd });\n if (!ok) return false;\n }\n return true;\n }\n}\n","import { createHash } from 'node:crypto';\nimport { basename, dirname, extname, relative, resolve } from 'node:path';\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\nimport { dump as serializeYaml } from 'js-yaml';\n/**\n * RunWorkflowService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Orchestrator pattern coordinating sub-services\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { WorkflowCapacityError } from '../../models/WorkflowCapacityError';\nimport { type WorkflowInterruptContext, WorkflowInterruptedError } from '../../models/WorkflowInterruptedError';\nimport type {\n MatrixEntry,\n StepExecutionRef,\n Workflow,\n WorkflowExecutionCursor,\n WorkflowLauncherMetadata,\n WorkflowLauncherType,\n WorkflowOutcome,\n WorkflowRepairRecord,\n WorkflowRunHandle,\n WorkflowRunRecord,\n} from '../../schemas/workflowEngine';\nimport { BackgroundServiceManager } from '../BackgroundServiceManager';\nimport { JobRunnerService } from '../JobRunnerService';\nimport { RunDirectoryService } from '../RunDirectoryService';\nimport { StepRunnerService } from '../StepRunnerService';\nimport { TriggerService } from '../TriggerService';\nimport { compatibleCommands } from '../WorkflowCatalogService';\nimport type { Logger, StepExecutor } from '../workflowEngine/type';\nimport { WorkflowParserService } from '../WorkflowParserService';\nimport { PHASE_JOB_POST, PHASE_JOB_PRE, WorkflowProgressService } from '../WorkflowProgressService';\nimport { WorkflowRegistryService } from '../WorkflowRegistryService';\nimport { WorkflowRepairService } from '../WorkflowRepairService';\nimport { workflowShellOutput } from '../workflowRuntime';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport { escapeShellArg, substituteShellPlaceholder } from '../workflowShell';\nimport { createWorkflowLogger, runWorkflowSpan } from '../workflowTelemetry';\nimport { WorktreeService } from '../WorktreeService';\n\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\nconst GREEN = '\\x1b[32m';\nconst YELLOW = '\\x1b[33m';\nconst RED = '\\x1b[31m';\nconst BLUE = '\\x1b[34m';\nconst INTERRUPT_SIGNAL: NodeJS.Signals = 'SIGINT';\nconst TERMINATE_SIGNAL: NodeJS.Signals = 'SIGTERM';\n// A run hosted in a terminal pane is hung up, not interrupted, when that pane\n// goes away. Without a handler Node takes the default action and dies on the\n// spot, so the active step's descendants are never reaped and survive as\n// orphans holding the worktree open.\nconst HANGUP_SIGNAL: NodeJS.Signals = 'SIGHUP';\nconst INTERRUPTED_EXIT_CODE = 130;\nconst WORKFLOW_FAILED_EXIT_CODE = 1;\nconst WORKFLOW_SKIPPED_EXIT_CODE = 2;\nconst WORKFLOW_PHASE = 'workflow_execution';\nconst GIT_DIRNAME = '.git';\nconst FIX_FILENAME = 'fix.md';\nconst FIX_FRONTMATTER_DELIMITER = '---';\nconst FIX_RESTART_FROM_KEY = 'restart-from';\nconst FIX_STATUS_KEY = 'status';\nconst FIX_TERMINAL_TARGET = 'stop';\nconst PROCEED_FILENAME = 'proceed.md';\nconst PROCEED_TO_KEY = 'proceed-to';\nconst DRY_RUN_ARTIFACT_PREFIX = 'workflow-mcp-dry-run-';\nconst DRY_RUN_ARTIFACT_FILENAME = 'assembled-workflow.yml';\nconst TRIGGER_USER_PROMPT = 'user_prompt';\nconst TRIGGER_AGENT_DECISION = 'agent_decision';\nconst TRIGGER_WORKFLOW_DISPATCH = 'workflow_dispatch';\nconst WORKTREE_DRY_RUN_MESSAGE = 'Would create at';\nconst SERVICE_STARTUP_DELAY_MS = 2_000;\nconst DEFAULT_WORKSPACE = 'default';\nconst WORKFLOW_SUCCESS_TEXT = 'Workflow completed successfully';\nconst WORKFLOW_SKIPPED_TEXT = 'Workflow skipped: agent decided nothing to do';\nconst WORKFLOW_ABORTED_PROMPT_TEXT = 'Workflow aborted: no prompt provided';\nconst WORKFLOW_ABORTED_PRECONDITIONS_TEXT = 'Workflow aborted: pre-conditions failed';\nconst WORKFLOW_POST_FAILED_TEXT = 'Workflow post-cleanup failed';\nconst WORKFLOW_ABORTED_WORKTREE_BEFORE_CREATE_TEXT = 'Workflow aborted: worktree beforeCreate hook failed';\nconst WORKFLOW_ABORTED_WORKTREE_AFTER_CREATE_TEXT = 'Workflow aborted: worktree afterCreate hook failed';\nconst WORKFLOW_FAILED_AT_JOB_PREFIX = 'Workflow failed at job';\nconst COMPLETED_STAGE = 'completed';\nconst ERROR_STAGE = 'error';\nconst OUTCOME_SUCCESS: WorkflowOutcome = 'success';\nconst OUTCOME_SKIPPED: WorkflowOutcome = 'skipped';\nconst OUTCOME_FAILED: WorkflowOutcome = 'failed';\nconst OUTCOME_INTERRUPTED: WorkflowOutcome = 'interrupted';\n\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_MAX_FIX_CYCLES = 3;\nconst MAX_OUTPUT_LINES = 5_000;\nconst LAUNCH_COMMAND_PLACEHOLDER = '{command}';\nconst LAUNCH_NAME_PLACEHOLDER = '{name}';\nconst CMUX_SURFACE_ID_ENV = 'CMUX_SURFACE_ID';\nconst CMUX_WORKSPACE_ID_ENV = 'CMUX_WORKSPACE_ID';\nconst TMUX_PANE_ENV = 'TMUX_PANE';\nconst WORKFLOW_LAUNCHER_ENV = 'WORKFLOW_LAUNCHER';\nconst WORKFLOW_LAUNCHER_TYPE_ENV = 'WORKFLOW_LAUNCHER_TYPE';\n/** Set by `host-run`, naming where this run's own terminal is answering. */\nconst WORKFLOW_TERMINAL_SOCKET_ENV = 'WORKFLOW_TERMINAL_SOCKET';\nconst NATIVE_LAUNCHER_TYPE = 'native';\nconst WORKFLOW_TMUX_SESSION_NAME_ENV = 'WORKFLOW_TMUX_SESSION_NAME';\nconst WORKFLOW_LAUNCHER_ORIGIN_PANE_ID_ENV = 'WORKFLOW_LAUNCHER_ORIGIN_PANE_ID';\nconst WORKFLOW_LAUNCHER_ORIGIN_SESSION_ID_ENV = 'WORKFLOW_LAUNCHER_ORIGIN_SESSION_ID';\nconst WORKFLOW_LAUNCHER_ORIGIN_SURFACE_ID_ENV = 'WORKFLOW_LAUNCHER_ORIGIN_SURFACE_ID';\nconst WORKFLOW_LAUNCHER_ORIGIN_WORKSPACE_ID_ENV = 'WORKFLOW_LAUNCHER_ORIGIN_WORKSPACE_ID';\nconst WORKFLOW_STATUS_FILE_ENV = 'WORKFLOW_STATUS_FILE';\nconst WORKFLOW_FIX_LOOP_DISABLED_ENV = 'WORKFLOW_FIX_LOOP_DISABLED';\nconst WORKFLOW_PHASE_ENV = 'WORKFLOW_PHASE';\n/**\n * Progress-log names for the two phases that are not jobs.\n *\n * A reader renders these beside real jobs the way GitHub Actions shows \"Set up\n * job\" and \"Post job cleanup\" around the jobs between them. Named for what the\n * console already prints for these phases, so the log and the terminal agree.\n *\n * A workflow whose own job is literally named `pre` would merge into this entry.\n * That is cosmetic rather than corrupting, and is not worth an escaping scheme.\n */\n// Taken from the progress module rather than restated here: these names are the\n// log's format, and a reader classifying phases has to agree with this writer.\nconst PRE_PHASE_JOB = PHASE_JOB_PRE;\nconst POST_PHASE_JOB = PHASE_JOB_POST;\nconst WORKFLOW_EXIT_CODE_ENV = 'WORKFLOW_EXIT_CODE';\nconst WORKFLOW_OUTCOME_ENV = 'WORKFLOW_OUTCOME';\nconst WORKFLOW_FAILED_JOB_ENV = 'WORKFLOW_FAILED_JOB';\nconst WORKFLOW_ACTIVE_REPAIR_ID_ENV = 'WORKFLOW_ACTIVE_REPAIR_ID';\nconst WORKFLOW_ACTIVE_REPAIR_DIR_ENV = 'WORKFLOW_ACTIVE_REPAIR_DIR';\nconst WORKFLOW_ACTIVE_REPAIR_FILE_ENV = 'WORKFLOW_ACTIVE_REPAIR_FILE';\nconst WORKFLOW_ACTIVE_ISSUE_FILE_ENV = 'WORKFLOW_ACTIVE_ISSUE_FILE';\nconst REPAIR_TRIAGE_JOB_NAME = 'repair-triage';\n\nfunction parsePositiveIntegerEnv(value: string | undefined, defaultValue: number): number {\n const parsed = Number(value);\n return Number.isInteger(parsed) && parsed > 0 ? parsed : defaultValue;\n}\n\nconst STEP_CLI_DIRECTORY = 'bin';\nconst STEP_CLI_NAME = 'workflow-mcp';\n\nfunction envFlagEnabled(value: string | undefined): boolean {\n return ['1', 'true', 'yes', 'on'].includes(\n String(value ?? '')\n .trim()\n .toLowerCase(),\n );\n}\n\nexport interface RunWorkflowInput {\n cliAgent?: string;\n runner?: string;\n /** Command templated interactiveRun steps run through; defaults to each step's first. */\n command?: string;\n /** Choice for steps that do not pin one; defaults to the choice named `default`. */\n choice?: string;\n workflowPath: string;\n job?: string;\n inputs?: Record<string, string>;\n env?: Record<string, string>;\n secretFile?: string;\n dryRun?: boolean;\n continueOnError?: boolean;\n keepWorktree?: boolean;\n launcher?: WorkflowLauncherType;\n prompt?: string;\n name?: string;\n workspace?: string;\n skipLaunch?: boolean;\n statusFile?: string;\n /**\n * The run is registered and its directory is ready: the earliest point a\n * host can follow it, identified exactly rather than guessed from the registry.\n */\n onRegistered?: (run: WorkflowRunRegistration) => void;\n /** The engine reloaded its definition for the next job or repair cycle. */\n onConfigChanged?: (run: WorkflowRunRegistration) => void;\n recovery?: {\n activeRepairId?: string;\n /** Omitted only for a read-only recovery dry run. */\n claimId?: string;\n originalJob?: string;\n originalRepoPath?: string;\n runKey: string;\n startJob?: string;\n worktreeBranch?: string;\n worktreePath?: string;\n };\n}\n\nexport interface RunWorkflowResult {\n exitCode: number;\n output: string;\n}\n\n/** Where a registered run lives, as `RunWorkflowInput.onRegistered` reports it. */\nexport interface WorkflowRunRegistration {\n runKey: string;\n runId: string;\n workspace: string;\n runDir: string;\n displayName: string;\n /** The resolved parsed definition used by this execution, never a later disk read. */\n workflow: Workflow;\n revision: string;\n}\n\n/**\n * Optional collaborators for `RunWorkflowService`.\n *\n * Supplying these allows tests and higher-level callers to replace concrete\n * orchestration services without changing the public command API.\n */\nexport interface RunWorkflowDependencies {\n runtime: WorkflowRuntimeContext;\n /**\n * Stdio handed to `launch-command` delegation.\n *\n * The CLI owns its terminal, so it inherits and lets the launcher paint on\n * it. An embedded host does not: inside the Pi extension stdout is the TUI's\n * screen and stdin is its keyboard, and inside the stdio MCP server stdout is\n * the JSON-RPC stream. Those hosts pass `pipe` so the child gets neither.\n */\n launchStdio?: 'inherit' | 'pipe';\n /**\n * Launcher identity to persist instead of inferring one from this process.\n *\n * An embedded host can itself run inside cmux or tmux without that host\n * terminal being the workflow's launcher. It supplies `native` so readers do\n * not later scrape or foreground the host application's own terminal.\n */\n launcherMetadata?: WorkflowLauncherMetadata;\n /**\n * Whether this process owns the terminal its steps would write to.\n *\n * The same distinction `launchStdio` draws, applied to the steps themselves.\n * `launchStdio` only covers the `launch-command` child; a step spawned by\n * `StepRunnerService` still reaches the terminal, and an interactive one also\n * runs `stty` over it. An embedded host passes false to keep both away.\n */\n ownsTerminal?: boolean;\n /**\n * Host execution for `customRun` steps, and optionally for commands.\n *\n * Only an embedding host can supply one: it runs inside the host process. A\n * run delegated through `launch-command` executes elsewhere and never sees it,\n * so a host that wants its executor used launches with `skipLaunch`.\n */\n stepExecutor?: StepExecutor;\n parser?: WorkflowParserService;\n serviceManager?: BackgroundServiceManager;\n stepRunner?: StepRunnerService;\n jobRunner?: JobRunnerService;\n triggerService?: TriggerService;\n worktreeService?: WorktreeService;\n registry?: WorkflowRegistryService;\n repairService?: WorkflowRepairService;\n runDirectoryService?: RunDirectoryService;\n}\n\ninterface DryRunPromptAssembly {\n jobName: string;\n matrix: MatrixEntry;\n prompt: string;\n}\n\n/**\n * Orchestrates local workflow execution, including triggers, jobs, services,\n * worktree lifecycle, and graceful interruption handling.\n */\nexport class RunWorkflowService {\n readonly runtime: WorkflowRuntimeContext;\n private readonly ownsProcessSignals: boolean;\n private logger: Logger;\n private parser: WorkflowParserService;\n private serviceManager: BackgroundServiceManager;\n private stepRunner: StepRunnerService;\n private jobRunner: JobRunnerService;\n private triggerService: TriggerService;\n private worktreeService: WorktreeService;\n private registry: WorkflowRegistryService;\n private repairService: WorkflowRepairService;\n private runDirectoryService: RunDirectoryService;\n private outputLines: string[] = [];\n private interruptedSignal: NodeJS.Signals | null = null;\n private launchStdio: 'inherit' | 'pipe';\n private launcherMetadata: WorkflowLauncherMetadata | undefined;\n\n /**\n * Create a workflow runner with an optional logger and overridable\n * collaborators for tests or alternate orchestration behavior.\n */\n constructor(logger: Logger | undefined, dependencies: RunWorkflowDependencies) {\n this.runtime = dependencies.runtime;\n this.ownsProcessSignals = dependencies.ownsTerminal !== false;\n const baseLogger = createWorkflowLogger(\n logger ?? {\n info: (message: string) => this.runtime.workflowHost.writeStdout(`${message}\\n`),\n error: (message: string) => this.runtime.workflowHost.writeStderr(`${message}\\n`),\n warn: (message: string) => this.runtime.workflowHost.writeStderr(`${message}\\n`),\n },\n );\n\n const pushLine = (message: string) => {\n this.outputLines.push(message);\n if (this.outputLines.length > MAX_OUTPUT_LINES) {\n this.outputLines.shift();\n }\n };\n\n this.logger = {\n info: (message: string) => {\n pushLine(message);\n baseLogger.info(message);\n },\n error: (message: string) => {\n pushLine(message);\n baseLogger.error(message);\n },\n warn: (message: string) => {\n pushLine(message);\n baseLogger.warn(message);\n },\n runInSpan: baseLogger.runInSpan?.bind(baseLogger),\n event: baseLogger.event?.bind(baseLogger),\n flush: baseLogger.flush?.bind(baseLogger),\n };\n\n this.launchStdio = dependencies.launchStdio ?? 'inherit';\n this.launcherMetadata = dependencies.launcherMetadata;\n this.parser = dependencies.parser ?? new WorkflowParserService(this.runtime);\n this.serviceManager = dependencies.serviceManager ?? new BackgroundServiceManager(this.runtime, this.logger);\n // The three `undefined`s keep the quota service, status-file watcher and\n // run-directory service on their own defaults; only terminal ownership and\n // the host executor are being set here.\n this.stepRunner =\n dependencies.stepRunner ??\n new StepRunnerService(\n this.runtime,\n this.parser,\n this.logger,\n undefined,\n undefined,\n undefined,\n dependencies.ownsTerminal,\n dependencies.stepExecutor,\n );\n this.registry = dependencies.registry ?? new WorkflowRegistryService(this.runtime);\n this.runDirectoryService =\n dependencies.runDirectoryService ?? new RunDirectoryService(this.runtime, this.registry.writeCoordinator);\n this.jobRunner =\n dependencies.jobRunner ??\n new JobRunnerService(this.runtime, this.parser, this.stepRunner, this.logger, this.runDirectoryService);\n this.triggerService = dependencies.triggerService ?? new TriggerService(this.runtime, this.stepRunner, this.logger);\n this.worktreeService =\n dependencies.worktreeService ?? new WorktreeService(this.runtime, this.stepRunner, this.logger);\n this.repairService = dependencies.repairService ?? new WorkflowRepairService(this.runtime);\n }\n\n /**\n * Run the workflow from trigger preparation through cleanup.\n */\n async run(input: RunWorkflowInput): Promise<RunWorkflowResult> {\n this.stepRunner.resetInterruption();\n this.triggerService.resetInterruption();\n this.outputLines = [];\n this.interruptedSignal = null;\n const dryRun = input.dryRun ?? false;\n const continueOnError = input.continueOnError ?? false;\n let isCleaningUp = false;\n\n const cleanup = (signal: NodeJS.Signals) => {\n if (isCleaningUp) {\n return;\n }\n isCleaningUp = true;\n this.interrupt(signal);\n };\n const handleSigint = () => cleanup(INTERRUPT_SIGNAL);\n const handleSigterm = () => cleanup(TERMINATE_SIGNAL);\n const handleSighup = () => cleanup(HANGUP_SIGNAL);\n const unsubscribe = this.ownsProcessSignals\n ? [\n this.runtime.workflowHost.onSignal(INTERRUPT_SIGNAL, handleSigint),\n this.runtime.workflowHost.onSignal(TERMINATE_SIGNAL, handleSigterm),\n this.runtime.workflowHost.onSignal(HANGUP_SIGNAL, handleSighup),\n ]\n : [];\n\n try {\n return await runWorkflowSpan(this.logger, 'workflow.run', {}, () =>\n this.executeWorkflow(input, dryRun, continueOnError, input.keepWorktree ?? false),\n );\n } catch (error) {\n if (error instanceof WorkflowInterruptedError || this.isInterrupted()) {\n await this.serviceManager.stopAll();\n return this.createInterruptedResult();\n }\n throw error;\n } finally {\n await this.logger.flush?.();\n for (const off of unsubscribe) off();\n await this.serviceManager.stopAll();\n }\n }\n\n /**\n * Trigger the same interruption cleanup path used by process signal handlers.\n *\n * The optional context records where shutdown started so subsequent\n * `WorkflowInterruptedError` instances carry structured diagnostics.\n */\n interrupt(signal: NodeJS.Signals, context: WorkflowInterruptContext = { phase: WORKFLOW_PHASE }): void {\n if (this.interruptedSignal) {\n return;\n }\n\n this.interruptedSignal = signal;\n const contextSuffix = context.phase === WORKFLOW_PHASE ? '' : ` (${context.phase})`;\n this.logger.info(`\\n\\n${YELLOW}${BOLD}Interrupted, shutting down...${RESET}${contextSuffix}`);\n // SIGHUP can be ignored by non-interactive shells. Record the original signal,\n // but use SIGTERM so the active process tree shuts down reliably.\n const shutdownSignal = signal === HANGUP_SIGNAL ? TERMINATE_SIGNAL : signal;\n this.triggerService.abortActivePrompt(shutdownSignal);\n this.stepRunner.stopActiveStep(shutdownSignal);\n\n void this.serviceManager.stopAll();\n }\n\n /**\n * Check whether workflow shutdown has been requested.\n */\n private isInterrupted(): boolean {\n return (\n this.interruptedSignal === INTERRUPT_SIGNAL ||\n this.interruptedSignal === TERMINATE_SIGNAL ||\n this.interruptedSignal === HANGUP_SIGNAL\n );\n }\n\n /**\n * Build the standard process-style result for an interrupted workflow run.\n */\n private createInterruptedResult(): RunWorkflowResult {\n return { exitCode: INTERRUPTED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n\n /**\n * Extract the restart-from job name from fix.md YAML frontmatter.\n * Returns the parsed target and any invalid target for caller logging.\n */\n private parseFixRestartFrom(\n fixContent: string,\n jobOrder: string[],\n allowTerminalStop: boolean,\n ): {\n restartFrom?: string;\n invalidTarget?: string;\n terminal?: boolean;\n terminalRequested?: boolean;\n } {\n let requestedTarget: string | undefined;\n let requestedStatus: string | undefined;\n if (fixContent.startsWith(FIX_FRONTMATTER_DELIMITER)) {\n const endIndex = fixContent.indexOf(FIX_FRONTMATTER_DELIMITER, FIX_FRONTMATTER_DELIMITER.length);\n if (endIndex >= 0) {\n const frontmatter = fixContent.slice(FIX_FRONTMATTER_DELIMITER.length, endIndex);\n for (const line of frontmatter.split('\\n')) {\n const separatorIndex = line.indexOf(':');\n if (separatorIndex < 0) {\n continue;\n }\n const key = line.slice(0, separatorIndex).trim().toLowerCase();\n if (key === FIX_RESTART_FROM_KEY) {\n requestedTarget = line.slice(separatorIndex + 1).trim();\n }\n if (key === FIX_STATUS_KEY) {\n requestedStatus = line.slice(separatorIndex + 1).trim();\n }\n }\n }\n }\n\n const normalizedTarget = requestedTarget?.toLowerCase();\n const terminalRequested =\n requestedStatus?.toLowerCase() === FIX_TERMINAL_TARGET || normalizedTarget === FIX_TERMINAL_TARGET;\n if (terminalRequested && allowTerminalStop) {\n return { terminal: true, terminalRequested: true };\n }\n\n if (normalizedTarget && normalizedTarget !== FIX_TERMINAL_TARGET) {\n const exactMatch = jobOrder.find((jobName) => jobName.toLowerCase() === normalizedTarget);\n if (exactMatch) {\n return { restartFrom: exactMatch, terminalRequested };\n }\n }\n\n const normalizedFixContent = fixContent.toLowerCase();\n const contentMatch = jobOrder\n .map((jobName, order) => ({\n index: normalizedFixContent.indexOf(jobName.toLowerCase()),\n jobName,\n order,\n }))\n .filter((candidate) => candidate.index >= 0)\n .sort(\n (left, right) =>\n left.index - right.index || right.jobName.length - left.jobName.length || left.order - right.order,\n )[0];\n\n if (contentMatch) {\n return { restartFrom: contentMatch.jobName, terminalRequested };\n }\n\n if (requestedTarget && normalizedTarget !== FIX_TERMINAL_TARGET) {\n return { invalidTarget: requestedTarget, terminalRequested };\n }\n\n return { terminalRequested };\n }\n\n /**\n * Extract the proceed-to job name from proceed.md YAML frontmatter.\n *\n * Frontmatter only, with no fall back to job names mentioned in the body the\n * way fix.md routing does. A mis-routed restart costs re-run time; a\n * mis-routed forward jump silently drops jobs that were supposed to run, so a\n * request this parser cannot read exactly is one the caller should ignore.\n */\n private parseProceedTo(proceedContent: string, jobOrder: string[]): { target?: string; invalidTarget?: string } {\n let requestedTarget: string | undefined;\n if (proceedContent.startsWith(FIX_FRONTMATTER_DELIMITER)) {\n const endIndex = proceedContent.indexOf(FIX_FRONTMATTER_DELIMITER, FIX_FRONTMATTER_DELIMITER.length);\n if (endIndex >= 0) {\n const frontmatter = proceedContent.slice(FIX_FRONTMATTER_DELIMITER.length, endIndex);\n for (const line of frontmatter.split('\\n')) {\n const separatorIndex = line.indexOf(':');\n if (separatorIndex < 0) {\n continue;\n }\n if (line.slice(0, separatorIndex).trim().toLowerCase() === PROCEED_TO_KEY) {\n requestedTarget = line.slice(separatorIndex + 1).trim();\n }\n }\n }\n }\n\n if (!requestedTarget) {\n return {};\n }\n\n const normalizedTarget = requestedTarget.toLowerCase();\n const exactMatch = jobOrder.find((jobName) => jobName.toLowerCase() === normalizedTarget);\n return exactMatch ? { target: exactMatch } : { invalidTarget: requestedTarget };\n }\n\n /**\n * Check whether a file-system path exists while preserving non-ENOENT errors.\n */\n private async pathExists(path: string): Promise<boolean> {\n try {\n getOrThrow(await this.runtime.fs.fileInfo(path, this.runtime.ioContext));\n return true;\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Give background services a short async window to finish booting.\n */\n private async waitForServiceStartup(): Promise<void> {\n await new Promise<void>((resolveDelay) => {\n setTimeout(resolveDelay, SERVICE_STARTUP_DELAY_MS);\n });\n }\n\n private resolveWorkflowRunner(workflow: Workflow): string | undefined {\n if (workflow.runner && workflow['default-runner'] && workflow.runner !== workflow['default-runner']) {\n throw new Error(\n `Conflicting workflow runner selectors: runner=\"${workflow.runner}\" default-runner=\"${workflow['default-runner']}\"`,\n );\n }\n\n return workflow.runner ?? workflow['default-runner'];\n }\n\n /**\n * Hand the step runner the workflow's command templates and what the launch\n * selected, refusing a `--command` some templated step does not offer or a\n * `--choice` the workflow does not declare before anything runs.\n */\n private useCommandSelection(workflow: Workflow, input: RunWorkflowInput): void {\n if (input.command !== undefined) {\n const offered = compatibleCommands(workflow);\n if (!offered?.includes(input.command)) {\n throw new Error(\n offered\n ? `Command \"${input.command}\" is not offered by every templated step (offered: ${offered.join(', ') || 'none in common'}).`\n : `Command \"${input.command}\" was selected, but no step of this workflow is templated.`,\n );\n }\n }\n if (input.choice !== undefined && !workflow.choices?.[input.choice]) {\n const declared = Object.keys(workflow.choices ?? {});\n throw new Error(`Choice \"${input.choice}\" is not declared (declared: ${declared.join(', ') || 'none'}).`);\n }\n this.stepRunner.useCommandTemplates({\n commands: workflow.commands,\n choices: workflow.choices,\n command: input.command,\n choice: input.choice,\n });\n }\n\n private resolveRunner(input: RunWorkflowInput, workflow?: Workflow): string | undefined {\n if (input.runner && input.cliAgent && input.runner !== input.cliAgent) {\n throw new Error(`Conflicting runner selectors: runner=\"${input.runner}\" cliAgent=\"${input.cliAgent}\"`);\n }\n\n return input.runner ?? input.cliAgent ?? (workflow ? this.resolveWorkflowRunner(workflow) : undefined);\n }\n\n /**\n * Execute the workflow after signal handlers are installed.\n */\n private async executeWorkflow(\n input: RunWorkflowInput,\n dryRun: boolean,\n continueOnError: boolean,\n keepWorktree = false,\n ): Promise<RunWorkflowResult> {\n if (input.statusFile) {\n input = { ...input, statusFile: resolve(input.statusFile) };\n }\n\n const workflowPath = resolve(this.runtime.cwd, input.workflowPath);\n const parsedWorkflow = await this.parser.parseWorkflowFile(workflowPath);\n const runner = this.resolveRunner(input, parsedWorkflow);\n let workflow = this.parser.selectRunner(parsedWorkflow, runner);\n this.useCommandSelection(workflow, input);\n let registryRun: WorkflowRunHandle | null = null;\n const configuration = () => ({\n workflow: structuredClone(workflow),\n revision: createHash('sha256').update(JSON.stringify(workflow)).digest('hex'),\n });\n /**\n * Whether this process handed the run to a launcher instead of running it.\n *\n * The delegating process returns from inside the `try`, so the `finally`\n * still fires for it. Most of that block is already inert here, keyed off\n * state delegation never creates: no run record, no worktree, no completion\n * hooks. `post:` is the exception, and it is not a harmless one.\n */\n let delegated = false;\n // Declared out here because post cleanup runs in the `finally` below, and it\n // is a phase readers care about: it is where a dispatch run releases its lock.\n let progress: WorkflowProgressService | undefined;\n let result: RunWorkflowResult | null = null;\n let runError: unknown = null;\n let workflowDir = dirname(workflowPath);\n let originalDir = workflowDir;\n let worktreePath: string | null = null;\n let worktreeBranch: string | null = null;\n let shouldRunSuccessCompletionHooks = false;\n let shouldRemoveWorktreeOnExit = false;\n let failedJob: string | undefined;\n let failureReason: string | undefined;\n let persistedFixLoopCycle: number | undefined;\n let activeJob: string | undefined;\n let activeRepair: WorkflowRepairRecord | null = null;\n const dryRunPromptAssemblies: DryRunPromptAssembly[] = [];\n const useWorktree = !!workflow.worktree;\n const inputs = new Map<string, string>();\n const secrets = input.secretFile ? await this.parser.loadSecrets(input.secretFile) : new Map<string, string>();\n const workflowEnv: Record<string, string> = {};\n const persistExecutionCursor = async (patch: Partial<WorkflowExecutionCursor>): Promise<void> => {\n if (!registryRun) return;\n try {\n await this.registry.updateExecutionCursor(registryRun, patch);\n } catch (error) {\n this.logger.warn(\n `${YELLOW}${BOLD}Workflow cursor update skipped${RESET}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n };\n const onStepStarted = async (\n stepName: string,\n index: number,\n total: number,\n matrixIndex?: number,\n attempt?: number,\n ): Promise<void> => {\n await persistExecutionCursor({\n attempt,\n job: activeJob,\n matrixIndex,\n phase: activeJob ? 'step' : (workflowEnv[WORKFLOW_PHASE_ENV] ?? 'step'),\n resumeMode: 'continue-next',\n stepIndex: index,\n stepName,\n });\n void total;\n };\n const onExecutionStateChange = async (state: 'paused' | 'resumed', stepName: string): Promise<void> => {\n await persistExecutionCursor({\n job: activeJob,\n phase: activeJob ? 'step' : (workflowEnv[WORKFLOW_PHASE_ENV] ?? 'step'),\n stepName,\n });\n await this.logger.event?.('info', `workflow.run.${state}`, {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.step.name': stepName,\n }),\n });\n };\n\n try {\n // Resolve inputs with defaults\n const inputDefs = workflow.on?.[TRIGGER_WORKFLOW_DISPATCH]?.inputs || {};\n for (const [key, def] of Object.entries(inputDefs)) {\n if (def.default) inputs.set(key, def.default);\n }\n if (input.inputs) {\n for (const [key, val] of Object.entries(input.inputs)) {\n inputs.set(key, val);\n }\n }\n\n // Build workflow env\n if (workflow.env) {\n for (const [key, val] of Object.entries(workflow.env)) {\n workflowEnv[key] = String(val);\n }\n }\n if (input.env) {\n for (const [key, val] of Object.entries(input.env)) {\n workflowEnv[key] = val;\n }\n }\n if (runner) {\n workflowEnv.WORKFLOW_RUNNER = runner;\n workflowEnv.WORKFLOW_CLI_AGENT = runner;\n }\n if (input.command) workflowEnv.WORKFLOW_COMMAND = input.command;\n if (input.choice) workflowEnv.WORKFLOW_CHOICE = input.choice;\n\n // Resolve the repo root from workflow path\n let candidate = workflowDir;\n while (candidate !== '/') {\n if (await this.pathExists(resolve(candidate, GIT_DIRNAME))) {\n workflowDir = candidate;\n break;\n }\n candidate = dirname(candidate);\n }\n const workflowPathFromRoot = relative(workflowDir, workflowPath);\n const currentWorkflowPath = async () => {\n const workflowPathInCurrentDir = resolve(workflowDir, workflowPathFromRoot);\n return (await this.pathExists(workflowPathInCurrentDir)) ? workflowPathInCurrentDir : workflowPath;\n };\n\n const resolvedWorkspace = this.registry.resolveWorkspace(input.workspace, workflow.workspace);\n await this.registry.reconcileStaleRuns(resolvedWorkspace);\n\n // Capacity check: enforce max-workflows before creating a run\n const maxWorkflows = workflow['max-workflows'];\n if (maxWorkflows) {\n const running = await this.registry.countRunningWorkflows(resolvedWorkspace);\n if (running >= maxWorkflows) {\n throw new WorkflowCapacityError(resolvedWorkspace, running, maxWorkflows);\n }\n }\n\n // Launch-command delegation: re-invoke via configured launcher (e.g. cmux)\n const launchCommand = workflow['launch-command'];\n if (launchCommand && !input.skipLaunch) {\n const innerCommand = await this.createLaunchScriptCommand(input, workflowPath, workflow);\n const launchBaseName = input.name || workflow.name || basename(workflowPath);\n const launchDisplayName = input.name\n ? launchBaseName\n : `${launchBaseName}-${this.parser.generateHumanReadableId()}`;\n const namedLaunchCommand = substituteShellPlaceholder(\n launchCommand,\n LAUNCH_NAME_PLACEHOLDER,\n launchDisplayName,\n );\n const shell = substituteShellPlaceholder(namedLaunchCommand, LAUNCH_COMMAND_PLACEHOLDER, innerCommand);\n this.logger.info(`${DIM}Delegating via launch-command: ${shell}${RESET}`);\n delegated = true;\n const launched = await this.spawnLaunchCommand(shell, {\n cwd: workflowDir,\n env: this.buildLaunchEnvironment(input.launcher ?? workflow.launcher),\n });\n // Piped output would otherwise be dropped on the floor; routing it\n // through the logger puts it in `outputLines` where the caller reads it.\n if (launched.stdout) this.logger.info(launched.stdout);\n // With piped stdio the launcher's diagnosis is on stderr, and a failed\n // launch leaves no run behind, so this is its only explanation.\n if (launched.stderr && launched.exitCode !== 0) this.logger.error(launched.stderr);\n return { exitCode: launched.exitCode, output: this.outputLines.join('\\n') };\n }\n\n const baseName = input.name || workflow.name || basename(workflowPath);\n const workflowName = input.name ? baseName : `${baseName}-${this.parser.generateHumanReadableId()}`;\n const workflowId = basename(workflowPath, extname(workflowPath));\n if (dryRun && input.recovery) {\n registryRun = await this.createRecoveryDryRunHandle(input, resolvedWorkspace);\n } else {\n registryRun = await this.registry.createRun({\n activeRepairId: input.recovery?.activeRepairId,\n cliAgent: input.cliAgent,\n continueOnError: input.continueOnError,\n displayName: workflowName,\n dryRun,\n env: input.env,\n inputs: input.inputs,\n job: input.recovery ? input.recovery.originalJob : input.job,\n keepWorktree: input.keepWorktree,\n launcher: this.launcherMetadata ?? (await this.resolveLauncherMetadata()),\n prompt: input.prompt,\n recoveryClaimId: input.recovery?.claimId,\n runner,\n command: input.command,\n choice: input.choice,\n runDirectory: workflow['run-directory'],\n secretFile: input.secretFile,\n skipLaunch: input.skipLaunch,\n statusFile: input.statusFile,\n terminalSocket: this.runtime.baseEnvironment[WORKFLOW_TERMINAL_SOCKET_ENV],\n workflowPath,\n workflowId,\n workflowName: workflow.name ?? workflowId,\n workflowWorkspace: workflow.workspace,\n workspace: input.workspace,\n });\n }\n\n if (input.recovery?.activeRepairId && !dryRun) {\n activeRepair = await this.repairService.readRepair(registryRun.runDir, input.recovery.activeRepairId);\n }\n\n workflowEnv.WORKFLOW_RUN_DIR = registryRun.runDir;\n workflowEnv.WORKFLOW_RUN_ID = registryRun.runId;\n workflowEnv.WORKFLOW_RUN_KEY = registryRun.runKey;\n workflowEnv.WORKFLOW_ID = workflowId;\n workflowEnv.WORKFLOW_NAME = workflow.name ?? workflowId;\n workflowEnv.WORKFLOW_WORKSPACE = registryRun.workspace;\n workflowEnv[WORKFLOW_PHASE_ENV] = 'trigger';\n await this.runDirectoryService.materialize(registryRun.runDir, workflow['run-directory'], dryRun);\n if (!dryRun) await this.installStepCli(registryRun.runDir, workflowEnv);\n if (!dryRun) {\n input.onRegistered?.({\n runKey: registryRun.runKey,\n runId: registryRun.runId,\n workspace: registryRun.workspace,\n runDir: registryRun.runDir,\n displayName: registryRun.displayName,\n ...configuration(),\n });\n }\n await this.logger.event?.('info', 'workflow.run.started', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.display_name': registryRun.displayName,\n 'workflow.runner': runner ?? 'default',\n }),\n });\n if (workflowEnv.CONTEXT_FILE) {\n workflowEnv.CONTEXT_FILE = registryRun.contextPath;\n workflowEnv.CHANGELOG_FILE = registryRun.changelogPath;\n }\n\n // Print header\n this.logger.info(`${BOLD}${'═'.repeat(60)}${RESET}`);\n this.logger.info(` ${BOLD}run-workflow${RESET} - ${registryRun.displayName}`);\n this.logger.info(`${BOLD}${'═'.repeat(60)}${RESET}`);\n this.logger.info(` File: ${workflowPath}`);\n this.logger.info(` Workspace: ${registryRun.workspace || DEFAULT_WORKSPACE}`);\n this.logger.info(` Run Dir: ${registryRun.runDir}`);\n if (workflow['run-directory']) {\n this.logger.info(` Run Files: ${workflow['run-directory'].entries.length} declared entries`);\n }\n this.logger.info(` CWD: ${workflowDir}`);\n if (inputs.size > 0) {\n this.logger.info(` Inputs: ${[...inputs.entries()].map(([k, v]) => `${k}=${v}`).join(', ')}`);\n }\n if (secrets.size > 0) {\n this.logger.info(` Secrets: ${[...secrets.keys()].join(', ')}`);\n }\n if (input.job) {\n this.logger.info(` Target: ${input.job}`);\n }\n if (runner) {\n this.logger.info(` Runner: ${runner}`);\n }\n if (workflow.pre) {\n const svcCount = workflow.pre.services?.length || 0;\n const stepCount = workflow.pre.steps?.length || 0;\n this.logger.info(` Pre: ${svcCount} service(s), ${stepCount} setup step(s)`);\n }\n if (workflow.post) {\n const svcCount = workflow.post.services?.length || 0;\n const stepCount = workflow.post.steps?.length || 0;\n this.logger.info(` Post: ${svcCount} service(s), ${stepCount} cleanup step(s)`);\n }\n if (useWorktree) {\n this.logger.info(` Worktree: enabled${keepWorktree ? ' (keep on completion)' : ''}`);\n }\n const triggerType =\n workflow.on && TRIGGER_USER_PROMPT in workflow.on\n ? TRIGGER_USER_PROMPT\n : workflow.on?.[TRIGGER_AGENT_DECISION]\n ? TRIGGER_AGENT_DECISION\n : TRIGGER_WORKFLOW_DISPATCH;\n this.logger.info(` Trigger: ${triggerType}`);\n this.logger.info(` Mode: ${dryRun ? 'dry-run' : 'execute'}`);\n this.logger.info(`${BOLD}${'═'.repeat(60)}${RESET}`);\n\n // Handle user_prompt trigger\n const promptOk = await this.triggerService.handleUserPrompt(\n workflow,\n input.prompt || null,\n workflowEnv,\n workflowDir,\n dryRun,\n );\n if (!promptOk) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n return result;\n }\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_ABORTED_PROMPT_TEXT}${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n return result;\n }\n\n // Handle agent_decision trigger\n const decisionOk = await this.triggerService.handleAgentDecision(\n workflow,\n workflowEnv,\n inputs,\n secrets,\n {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n stopRequestPath: registryRun.stopRequestPath,\n workflowDir,\n onStepStarted,\n onExecutionStateChange,\n },\n input.prompt || null,\n );\n if (!decisionOk) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n return result;\n }\n this.logger.info(`\\n${YELLOW}${BOLD}${WORKFLOW_SKIPPED_TEXT}${RESET}`);\n result = { exitCode: WORKFLOW_SKIPPED_EXIT_CODE, output: this.outputLines.join('\\n') };\n return result;\n }\n\n // Worktree creation\n originalDir = workflowDir;\n\n if (useWorktree && input.recovery) {\n if (!input.recovery.worktreePath || !(await this.pathExists(input.recovery.worktreePath))) {\n throw new Error(`Recoverable worktree not found: ${input.recovery.worktreePath ?? '(missing)'}`);\n }\n\n originalDir = input.recovery.originalRepoPath ?? originalDir;\n worktreePath = input.recovery.worktreePath;\n worktreeBranch =\n input.recovery.worktreeBranch ?? this.worktreeService.getWorktreeBranchName(registryRun.displayName);\n workflowDir = worktreePath;\n\n workflowEnv.WORKTREE_PATH = worktreePath;\n workflowEnv.WORKTREE_BRANCH = worktreeBranch;\n workflowEnv.ORIGINAL_REPO_PATH = originalDir;\n\n this.logger.info(`\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}Reusing worktree${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n this.logger.info(` ${DIM}path ${RESET} ${worktreePath}`);\n } else if (useWorktree && !dryRun) {\n if (workflow.worktree?.beforeCreate) {\n workflowEnv[WORKFLOW_PHASE_ENV] = 'worktree-before-create';\n this.logger.info(`\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}beforeCreate${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n const hookOk = await this.worktreeService.runHook(\n workflow.worktree.beforeCreate,\n workflowDir,\n workflowEnv,\n inputs,\n secrets,\n {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n stopRequestPath: registryRun.stopRequestPath,\n onStepStarted,\n onExecutionStateChange,\n },\n );\n\n if (!hookOk) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n } else {\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_ABORTED_WORKTREE_BEFORE_CREATE_TEXT}${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n }\n }\n if (!result) {\n this.logger.info(`\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}Creating worktree${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n worktreeBranch = this.worktreeService.getWorktreeBranchName(registryRun.displayName);\n worktreePath = await this.worktreeService.createWorktree(workflowDir, registryRun.displayName);\n workflowDir = worktreePath;\n\n workflowEnv.WORKTREE_PATH = worktreePath;\n workflowEnv.WORKTREE_BRANCH = worktreeBranch;\n workflowEnv.ORIGINAL_REPO_PATH = originalDir;\n\n if (workflow.worktree?.afterCreate) {\n workflowEnv[WORKFLOW_PHASE_ENV] = 'worktree-after-create';\n this.logger.info(`\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}afterCreate${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n const hookOk = await this.worktreeService.runHook(\n workflow.worktree.afterCreate,\n worktreePath,\n workflowEnv,\n inputs,\n secrets,\n {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n stopRequestPath: registryRun.stopRequestPath,\n onStepStarted,\n onExecutionStateChange,\n },\n );\n\n if (!hookOk) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n } else {\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_ABORTED_WORKTREE_AFTER_CREATE_TEXT}${RESET}`);\n result = {\n exitCode: WORKFLOW_FAILED_EXIT_CODE,\n output: this.outputLines.join('\\n'),\n };\n }\n shouldRemoveWorktreeOnExit = !keepWorktree;\n }\n }\n }\n } else if (useWorktree && dryRun) {\n const parentDir = dirname(workflowDir);\n const folderName = basename(workflowDir);\n const safeName = registryRun.displayName\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-|-$/g, '');\n const dryWorktreePath = resolve(parentDir, `${folderName}-worktree`, safeName);\n this.logger.info(\n `\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}(dry-run)${RESET} ${WORKTREE_DRY_RUN_MESSAGE} ${dryWorktreePath}`,\n );\n }\n\n // Records job transitions where another process can read them.\n //\n // Created before the pre block, not at the job loop: a dispatch workflow\n // spends its opening minutes in `pre:` claiming its job, and a progress\n // log that only starts at the first job leaves every reader staring at an\n // empty tree for exactly the stretch where it most wants to know what is\n // happening. Dry runs record too; they have a run directory like any other\n // run, and a log with steps but no job transitions folds into a job that\n // never finishes.\n progress = new WorkflowProgressService(this.runtime, registryRun.runDir);\n\n // Run pre-conditions (after worktree so pre steps run in worktree dir)\n if (!result && workflow.pre) {\n workflowEnv[WORKFLOW_PHASE_ENV] = 'pre';\n const preBlock = workflow.pre;\n const preStopRequestPath = registryRun.stopRequestPath;\n const preResult = await this.recordPhase(progress, PRE_PHASE_JOB, () =>\n this.runPreBlock(preBlock, workflowEnv, inputs, secrets, {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n progress,\n stopRequestPath: preStopRequestPath,\n workflowDir,\n onStepStarted,\n onExecutionStateChange,\n }),\n );\n\n if (!preResult) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n } else {\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_ABORTED_PRECONDITIONS_TEXT}${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n shouldRemoveWorktreeOnExit = Boolean(worktreePath && !keepWorktree);\n }\n }\n\n const maxRetries = parsePositiveIntegerEnv(workflowEnv.MAX_RETRIES, DEFAULT_MAX_RETRIES);\n const maxFixCycles = parsePositiveIntegerEnv(workflowEnv.FIX_LOOP_MAX_CYCLES, DEFAULT_MAX_FIX_CYCLES);\n const fixLoopDisabled = envFlagEnabled(workflowEnv[WORKFLOW_FIX_LOOP_DISABLED_ENV]);\n\n // Run jobs with fix-loop support\n const jobOrderTarget = input.recovery ? input.recovery.originalJob || null : input.job || null;\n let jobOrder = this.parser.resolveJobOrder(workflow.jobs, jobOrderTarget);\n let loggedJobOrder = jobOrder.join(' -> ');\n this.logger.info(`\\n ${DIM}Job order: ${loggedJobOrder} (max retries: ${maxRetries})${RESET}`);\n\n const completedJobs = new Set<string>();\n const fixFile =\n !fixLoopDisabled && workflowEnv.WORKFLOW_RUN_DIR ? resolve(workflowEnv.WORKFLOW_RUN_DIR, FIX_FILENAME) : null;\n // Forward jumps only exist inside a repair, and repairs only exist while\n // the fix loop is on, so this file is inert under the same conditions.\n const proceedFile =\n !fixLoopDisabled && workflowEnv.WORKFLOW_RUN_DIR\n ? resolve(workflowEnv.WORKFLOW_RUN_DIR, PROCEED_FILENAME)\n : null;\n if (fixLoopDisabled) {\n this.logger.info(` ${DIM}fix-loop disabled by ${WORKFLOW_FIX_LOOP_DISABLED_ENV}${RESET}`);\n }\n let fixCycle = 0;\n\n let jobIndex = 0;\n let pendingStartJob = input.recovery?.startJob;\n let lastCompletedJob: string | undefined;\n while (!result) {\n workflow = this.parser.selectRunner(await this.parser.parseWorkflowFile(await currentWorkflowPath()), runner);\n this.useCommandSelection(workflow, input);\n input.onConfigChanged?.({\n runKey: registryRun.runKey,\n runId: registryRun.runId,\n workspace: registryRun.workspace,\n runDir: registryRun.runDir,\n displayName: registryRun.displayName,\n ...configuration(),\n });\n jobOrder = this.parser.resolveJobOrder(workflow.jobs, jobOrderTarget);\n const currentJobOrder = jobOrder.join(' -> ');\n if (currentJobOrder !== loggedJobOrder) {\n loggedJobOrder = currentJobOrder;\n this.logger.info(` ${DIM}Workflow file reloaded; job order: ${loggedJobOrder}${RESET}`);\n }\n\n if (activeRepair?.status === 'pending' && workflow.repair) {\n activeJob = REPAIR_TRIAGE_JOB_NAME;\n workflowEnv[WORKFLOW_PHASE_ENV] = REPAIR_TRIAGE_JOB_NAME;\n this.setRepairEnvironment(workflowEnv, registryRun.runDir, activeRepair);\n const repairIssueContent = getOrThrow(\n await this.runtime.fs.readTextFile(\n resolve(registryRun.runDir, activeRepair.issueFile),\n this.runtime.ioContext,\n ),\n );\n\n let triageFailureReason: string | undefined;\n const repair = workflow.repair;\n const stopRequestPath = registryRun.stopRequestPath;\n // Recorded like pre and post: triage is not in the job order, and a\n // triage the progress log never saw start or finish reads as running.\n const triageOk = await this.recordPhase(progress, REPAIR_TRIAGE_JOB_NAME, () =>\n this.jobRunner.runJob(\n REPAIR_TRIAGE_JOB_NAME,\n repair,\n {\n onFailed: (reason) => {\n triageFailureReason = reason;\n },\n inputs,\n secrets,\n workflowEnv,\n workflowSystemPrompt: workflow['system-prompt'],\n jobOrder,\n allJobs: {\n ...workflow.jobs,\n [REPAIR_TRIAGE_JOB_NAME]: repair,\n },\n repairTriage: true,\n activeRepairIssue: repairIssueContent,\n runDirectory: workflow['run-directory'],\n },\n {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n stopRequestPath,\n workflowDir,\n maxRetries,\n onStepStarted,\n onExecutionStateChange,\n },\n ),\n );\n\n if (this.isInterrupted()) {\n failedJob ??= REPAIR_TRIAGE_JOB_NAME;\n failureReason ??= `Workflow interrupted at job \"${REPAIR_TRIAGE_JOB_NAME}\"`;\n result = this.createInterruptedResult();\n } else if (!triageOk) {\n failedJob = REPAIR_TRIAGE_JOB_NAME;\n failureReason = triageFailureReason ?? `${WORKFLOW_FAILED_AT_JOB_PREFIX} \"${REPAIR_TRIAGE_JOB_NAME}\"`;\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_FAILED_AT_JOB_PREFIX} \"${REPAIR_TRIAGE_JOB_NAME}\"${RESET}`);\n await this.serviceManager.stopAll();\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n\n if (result) {\n continue;\n }\n\n if (fixFile && (await this.pathExists(fixFile)) && !dryRun) {\n const triageFixContent = getOrThrow(await this.runtime.fs.readTextFile(fixFile, this.runtime.ioContext));\n const { terminal } = this.parseFixRestartFrom(triageFixContent, jobOrder, true);\n failedJob = REPAIR_TRIAGE_JOB_NAME;\n failureReason = terminal\n ? `Terminal fix requested after \"${REPAIR_TRIAGE_JOB_NAME}\" with status \"${FIX_TERMINAL_TARGET}\".`\n : `Repair triage wrote fix.md without terminal status \"${FIX_TERMINAL_TARGET}\".`;\n this.logger.error(`\\n${RED}${BOLD}${failureReason}${RESET}`);\n await this.serviceManager.stopAll();\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n continue;\n }\n\n // Triage decides whether a repair runs at all; it is not inside the\n // repair scope, so it has nothing to jump forward past. Consume any\n // proceed.md it wrote so a scope job later does not inherit it.\n if (proceedFile && (await this.pathExists(proceedFile)) && !dryRun) {\n getOrThrow(await this.runtime.fs.remove(proceedFile, undefined, this.runtime.ioContext));\n this.logger.warn(`${YELLOW}Ignored ${PROCEED_FILENAME} written during repair triage.${RESET}`);\n }\n\n if (!dryRun) {\n activeRepair = await this.repairService.activateRepair(registryRun.runDir, activeRepair);\n if (workflowEnv.CONTEXT_FILE && (await this.pathExists(workflowEnv.CONTEXT_FILE))) {\n await this.updateRepairReferenceStatus(\n workflowEnv.CONTEXT_FILE,\n activeRepair.repairId,\n activeRepair.status,\n );\n }\n await this.logger.event?.('info', 'workflow.repair.triaged', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.repair.id': activeRepair.repairId,\n 'workflow.repair.status': activeRepair.status,\n }),\n });\n }\n activeJob = undefined;\n }\n\n if (pendingStartJob) {\n jobIndex = jobOrder.indexOf(pendingStartJob);\n if (jobIndex < 0) {\n throw new Error(`Start job not found in workflow order: ${pendingStartJob}`);\n }\n pendingStartJob = undefined;\n lastCompletedJob = undefined;\n } else if (lastCompletedJob) {\n const lastCompletedIndex = jobOrder.indexOf(lastCompletedJob);\n if (lastCompletedIndex >= 0) {\n jobIndex = lastCompletedIndex + 1;\n }\n }\n\n if (jobIndex >= jobOrder.length) {\n break;\n }\n\n const jobName = jobOrder[jobIndex];\n const job = workflow.jobs[jobName];\n activeJob = jobName;\n workflowEnv[WORKFLOW_PHASE_ENV] = 'job';\n await progress.jobStarted(jobName, jobIndex, jobOrder.length);\n await persistExecutionCursor({\n job: jobName,\n phase: 'job',\n stepIndex: undefined,\n stepName: undefined,\n });\n const jobUsesRepair = activeRepair?.scopeJobs.includes(jobName) ?? false;\n if (jobUsesRepair && activeRepair) {\n const repairWasPending = activeRepair.status === 'pending';\n if (!dryRun) {\n activeRepair = await this.repairService.activateRepair(registryRun.runDir, activeRepair);\n if (repairWasPending && workflowEnv.CONTEXT_FILE && (await this.pathExists(workflowEnv.CONTEXT_FILE))) {\n await this.updateRepairReferenceStatus(\n workflowEnv.CONTEXT_FILE,\n activeRepair.repairId,\n activeRepair.status,\n );\n }\n }\n this.setRepairEnvironment(workflowEnv, registryRun.runDir, activeRepair);\n if (!dryRun) {\n activeRepair = await this.repairService.startJob(\n registryRun.runDir,\n activeRepair,\n jobName,\n registryRun.runId,\n );\n }\n } else {\n this.clearRepairEnvironment(workflowEnv);\n }\n const repairIssueContent =\n jobUsesRepair && activeRepair\n ? getOrThrow(\n await this.runtime.fs.readTextFile(\n resolve(registryRun.runDir, activeRepair.issueFile),\n this.runtime.ioContext,\n ),\n )\n : undefined;\n\n let jobFailureReason: string | undefined;\n const ok = await this.jobRunner.runJob(\n jobName,\n job,\n {\n onFailed: (reason) => {\n jobFailureReason = reason;\n },\n inputs,\n secrets,\n workflowEnv,\n workflowSystemPrompt: workflow['system-prompt'],\n jobOrder,\n allJobs: workflow.jobs,\n activeRepairIssue: repairIssueContent,\n activeRepairVerificationJob: jobUsesRepair && activeRepair ? activeRepair.verificationJob : undefined,\n allowRepairTerminalStop: jobUsesRepair && !workflow.repair,\n fixLoop: { cycle: fixCycle, maxCycles: maxFixCycles },\n runDirectory: workflow['run-directory'],\n onPromptAssembled: dryRun\n ? (assembly) => {\n dryRunPromptAssemblies.push(assembly);\n }\n : undefined,\n },\n {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n stopRequestPath: registryRun.stopRequestPath,\n workflowDir,\n maxRetries,\n onStepStarted,\n onExecutionStateChange,\n },\n );\n if (this.isInterrupted()) {\n if (jobUsesRepair && activeRepair && !dryRun) {\n activeRepair = await this.repairService.finishJob(registryRun.runDir, activeRepair, jobName, 'interrupted');\n }\n failedJob ??= jobName;\n failureReason ??= `Workflow interrupted at job \"${jobName}\"`;\n result = this.createInterruptedResult();\n }\n\n if (!result && !ok) {\n if (jobUsesRepair && activeRepair && !dryRun) {\n activeRepair = await this.repairService.finishJob(registryRun.runDir, activeRepair, jobName, 'failed');\n }\n failedJob = jobName;\n failureReason = jobFailureReason ?? `${WORKFLOW_FAILED_AT_JOB_PREFIX} \"${jobName}\"`;\n await progress.jobFinished(jobName, 'failed', failureReason);\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_FAILED_AT_JOB_PREFIX} \"${jobName}\"${RESET}`);\n await this.serviceManager.stopAll();\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n\n if (result) {\n continue;\n }\n if (jobUsesRepair && activeRepair && !dryRun) {\n activeRepair = await this.repairService.finishJob(registryRun.runDir, activeRepair, jobName, 'completed');\n }\n completedJobs.add(jobName);\n await progress.jobFinished(jobName, 'completed');\n\n // Archive a transient fix.md as a durable, job-scoped repair before recycling.\n if (fixFile && (await this.pathExists(fixFile)) && !dryRun) {\n const fixContent = getOrThrow(await this.runtime.fs.readTextFile(fixFile, this.runtime.ioContext));\n const { restartFrom, invalidTarget, terminal, terminalRequested } = this.parseFixRestartFrom(\n fixContent,\n jobOrder,\n jobUsesRepair && !workflow.repair,\n );\n if (terminal) {\n failedJob = jobName;\n failureReason = `Terminal fix requested after \"${jobName}\" with status \"${FIX_TERMINAL_TARGET}\".`;\n this.logger.error(`\\n${RED}${BOLD}${failureReason}${RESET}`);\n await this.serviceManager.stopAll();\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n continue;\n }\n if (terminalRequested) {\n this.logger.warn(\n `${YELLOW}Ignored unauthorized terminal stop after \"${jobName}\"; processing fix.md as a repair.${RESET}`,\n );\n }\n fixCycle++;\n persistedFixLoopCycle = fixCycle;\n const nextRepair = await this.repairService.createRepair({\n emittingJob: jobName,\n fixContent,\n fixCycle,\n invalidTarget,\n jobOrder,\n restartFrom,\n runDir: registryRun.runDir,\n });\n getOrThrow(await this.runtime.fs.remove(fixFile, undefined, this.runtime.ioContext));\n // A job that reports a new defect and asks to skip ahead is asking for\n // two contradictory things. The defect wins: skipping ahead would\n // leave it unaddressed.\n if (proceedFile && (await this.pathExists(proceedFile))) {\n getOrThrow(await this.runtime.fs.remove(proceedFile, undefined, this.runtime.ioContext));\n this.logger.warn(\n `${YELLOW}Ignored ${PROCEED_FILENAME} after \"${jobName}\": ${FIX_FILENAME} takes precedence.${RESET}`,\n );\n }\n\n this.logger.info(\n `\\n${YELLOW}${BOLD}fix.md detected after \"${jobName}\" (cycle ${fixCycle}/${maxFixCycles})${RESET}`,\n );\n this.logger.info(`${DIM}Archived as ${nextRepair.issueFile} (repair ${nextRepair.repairId})${RESET}`);\n\n if (nextRepair.routingFallback) {\n this.logger.warn(\n `${YELLOW}fix.md routing used ${nextRepair.routingFallback.reason} fallback to \"${nextRepair.restartFrom}\"${RESET}`,\n );\n }\n\n if (workflowEnv.CONTEXT_FILE && (await this.pathExists(workflowEnv.CONTEXT_FILE))) {\n await this.appendRepairReferenceToContext(workflowEnv.CONTEXT_FILE, nextRepair);\n }\n\n await this.logger.event?.(nextRepair.status === 'rejected' ? 'error' : 'info', 'workflow.repair.created', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.repair.id': nextRepair.repairId,\n 'workflow.repair.requested_target': nextRepair.routingFallback?.requestedTarget ?? nextRepair.restartFrom,\n 'workflow.repair.resolved_target': nextRepair.routingFallback?.resolvedTarget ?? nextRepair.restartFrom,\n 'workflow.repair.restart_from': nextRepair.restartFrom,\n 'workflow.repair.routing_fallback_reason': nextRepair.routingFallback?.reason ?? 'none',\n 'workflow.repair.status': nextRepair.status,\n 'workflow.repair.verifier': nextRepair.verificationJob,\n }),\n });\n\n if (nextRepair.status === 'rejected') {\n await this.registry.updateRepairState(registryRun, { fixLoopCycle: fixCycle });\n failedJob = jobName;\n const requestedTarget = nextRepair.routingFallback?.requestedTarget;\n failureReason =\n nextRepair.routingFallback?.reason === 'unknown' && requestedTarget\n ? `Repair ${nextRepair.repairId} restart target \"${requestedTarget}\" is not in the workflow job order.`\n : `Repair ${nextRepair.repairId} restart target \"${nextRepair.restartFrom}\" occurs after verifier \"${jobName}\".`;\n this.logger.error(`\\n${RED}${BOLD}${failureReason}${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n continue;\n }\n\n if (activeRepair) {\n const supersededRepair = await this.repairService.supersedeRepair(\n registryRun.runDir,\n activeRepair,\n nextRepair.repairId,\n );\n if (workflowEnv.CONTEXT_FILE && (await this.pathExists(workflowEnv.CONTEXT_FILE))) {\n await this.updateRepairReferenceStatus(\n workflowEnv.CONTEXT_FILE,\n supersededRepair.repairId,\n supersededRepair.status,\n );\n }\n await this.logger.event?.('info', 'workflow.repair.superseded', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.repair.id': supersededRepair.repairId,\n 'workflow.repair.status': supersededRepair.status,\n 'workflow.repair.superseded_by': nextRepair.repairId,\n }),\n });\n }\n\n activeRepair = nextRepair;\n await this.registry.updateRepairState(registryRun, {\n activeRepairId: activeRepair.repairId,\n fixLoopCycle: fixCycle,\n });\n\n if (fixCycle > maxFixCycles) {\n failedJob = jobName;\n failureReason = `Fix loop limit reached (${maxFixCycles} cycles).`;\n this.logger.error(`\\n${RED}${BOLD}Fix loop limit reached (${maxFixCycles} cycles). Aborting.${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n continue;\n }\n\n pendingStartJob = activeRepair.restartFrom;\n lastCompletedJob = undefined;\n this.logger.info(`${YELLOW}Restarting from job \"${pendingStartJob}\"${RESET}\\n`);\n continue;\n }\n\n // A repair replays its whole scope by default, which re-runs jobs whose\n // work the fix did not invalidate. A scope job that knows the fix is\n // complete can jump ahead — at most as far as the job that raised the\n // fix, so the verifier always gets to judge the result.\n if (proceedFile && (await this.pathExists(proceedFile)) && !dryRun) {\n const proceedContent = getOrThrow(await this.runtime.fs.readTextFile(proceedFile, this.runtime.ioContext));\n // Consumed whether or not it is honored: a request left on disk would\n // fire again after an unrelated job.\n getOrThrow(await this.runtime.fs.remove(proceedFile, undefined, this.runtime.ioContext));\n\n const { target, invalidTarget } = this.parseProceedTo(proceedContent, jobOrder);\n const verifierIndex = activeRepair ? jobOrder.indexOf(activeRepair.verificationJob) : -1;\n const targetIndex = target ? jobOrder.indexOf(target) : -1;\n const ignoredReason = this.proceedRejectionReason({\n activeRepair,\n invalidTarget,\n jobName,\n jobUsesRepair,\n target,\n targetIndex,\n currentIndex: jobIndex,\n verifierIndex,\n });\n\n if (ignoredReason) {\n this.logger.warn(\n `${YELLOW}Ignored ${PROCEED_FILENAME} after \"${jobName}\": ${ignoredReason}. Continuing in job order.${RESET}`,\n );\n await this.logger.event?.('warn', 'workflow.repair.proceed_ignored', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.repair.id': activeRepair?.repairId ?? 'none',\n 'workflow.repair.proceed_from': jobName,\n 'workflow.repair.proceed_reason': ignoredReason,\n 'workflow.repair.proceed_requested_target': target ?? invalidTarget ?? 'none',\n }),\n });\n } else if (target && activeRepair) {\n const skippedJobs = jobOrder.slice(jobIndex + 1, targetIndex);\n if (skippedJobs.length > 0) {\n activeRepair = await this.repairService.skipJobs(registryRun.runDir, activeRepair, skippedJobs);\n for (const skippedJob of skippedJobs) {\n await progress.jobSkipped(skippedJob, `Skipped by ${PROCEED_FILENAME} from \"${jobName}\"`);\n }\n }\n if (workflowEnv.CONTEXT_FILE && (await this.pathExists(workflowEnv.CONTEXT_FILE))) {\n await this.appendProceedNoteToContext(\n workflowEnv.CONTEXT_FILE,\n activeRepair.repairId,\n jobName,\n target,\n skippedJobs,\n );\n }\n await this.logger.event?.('info', 'workflow.repair.proceeded', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.repair.id': activeRepair.repairId,\n 'workflow.repair.proceed_from': jobName,\n 'workflow.repair.proceed_skipped_count': skippedJobs.length,\n 'workflow.repair.proceed_to': target,\n }),\n });\n this.logger.info(\n `${YELLOW}Proceeding to job \"${target}\" (skipped: ${skippedJobs.join(', ') || 'none'})${RESET}\\n`,\n );\n pendingStartJob = target;\n lastCompletedJob = undefined;\n continue;\n }\n }\n\n if (jobUsesRepair && activeRepair?.verificationJob === jobName && !dryRun) {\n activeRepair = await this.repairService.resolveRepair(registryRun.runDir, activeRepair);\n if (workflowEnv.CONTEXT_FILE && (await this.pathExists(workflowEnv.CONTEXT_FILE))) {\n await this.updateRepairReferenceStatus(\n workflowEnv.CONTEXT_FILE,\n activeRepair.repairId,\n activeRepair.status,\n );\n }\n await this.registry.updateRepairState(registryRun, { activeRepairId: null });\n await this.logger.event?.('info', 'workflow.repair.resolved', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.repair.id': activeRepair.repairId,\n 'workflow.repair.status': activeRepair.status,\n 'workflow.repair.verifier': activeRepair.verificationJob,\n }),\n });\n this.clearRepairEnvironment(workflowEnv);\n activeRepair = null;\n }\n\n lastCompletedJob = jobName;\n jobIndex++;\n activeJob = undefined;\n }\n\n if (!result && this.isInterrupted()) {\n result = this.createInterruptedResult();\n }\n\n if (!result) {\n if (dryRun) {\n const artifactPath = await this.writeDryRunWorkflowArtifact(workflow, jobOrder, dryRunPromptAssemblies);\n this.logger.info(`\\n ${DIM}Assembled workflow: ${artifactPath}${RESET}`);\n }\n shouldRunSuccessCompletionHooks = true;\n this.logger.info(`\\n${BOLD}${'═'.repeat(60)}${RESET}`);\n this.logger.info(` ${GREEN}${BOLD}${WORKFLOW_SUCCESS_TEXT}${RESET}`);\n this.logger.info(` Jobs run: ${[...completedJobs].join(', ')}`);\n if (worktreePath) {\n this.logger.info(` Worktree: ${worktreePath}`);\n }\n this.logger.info(`${BOLD}${'═'.repeat(60)}${RESET}\\n`);\n\n result = { exitCode: 0, output: this.outputLines.join('\\n') };\n }\n } catch (error) {\n runError = error;\n const activeRepairJob = activeRepair?.jobs.find((job) => job.jobName === activeJob);\n if (registryRun && activeRepair && activeJob && activeRepairJob?.status === 'running' && !dryRun) {\n await this.repairService.finishJob(\n registryRun.runDir,\n activeRepair,\n activeJob,\n error instanceof WorkflowInterruptedError || this.isInterrupted() ? 'interrupted' : 'failed',\n );\n }\n if (error instanceof WorkflowInterruptedError || this.isInterrupted()) {\n if (activeJob) {\n failedJob ??= activeJob;\n failureReason ??= `Workflow interrupted at job \"${activeJob}\"`;\n }\n result = this.createInterruptedResult();\n } else {\n throw error;\n }\n } finally {\n if (registryRun && !(dryRun && input.recovery)) {\n await this.registry.markFinalizing(registryRun);\n }\n\n if (\n shouldRunSuccessCompletionHooks &&\n result?.exitCode === 0 &&\n useWorktree &&\n workflow.worktree?.beforeCompleted &&\n !dryRun &&\n worktreePath\n ) {\n workflowEnv[WORKFLOW_PHASE_ENV] = 'worktree-before-completed';\n this.logger.info(`\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}beforeCompleted${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n const hookOk = await this.worktreeService.runHook(\n workflow.worktree.beforeCompleted,\n worktreePath,\n workflowEnv,\n inputs,\n secrets,\n { runner, cliAgent: input.cliAgent, dryRun, continueOnError },\n );\n\n if (!hookOk) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n } else {\n this.logger.error(`\\n${RED}${BOLD}worktree beforeCompleted hook failed${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n }\n }\n\n // Not for a delegating process. It started nothing: the run it handed to\n // the launcher registers, works and cleans up on its own, in its own\n // terminal. Running cleanup here fires every `post:` step against a run\n // that has barely begun, seconds after launch, on whatever stdio this\n // process happens to own -- which for the Pi extension is the user's TUI.\n if (workflow.post && !delegated) {\n // The workflow-level interruption remains authoritative for the final\n // outcome, but cleanup steps are a new execution phase and must not\n // inherit the cancelled job's StepRunner state.\n this.stepRunner.resetInterruption();\n // Post cleanup runs in `finally`, so it must be told how the run settled.\n // run.json is not finalized until after this block, so env is the only source.\n const settled = this.resolveRunOutcome(result, runError);\n workflowEnv[WORKFLOW_PHASE_ENV] = 'post';\n workflowEnv[WORKFLOW_EXIT_CODE_ENV] = String(settled.exitCode);\n workflowEnv[WORKFLOW_OUTCOME_ENV] = settled.outcome;\n workflowEnv[WORKFLOW_FAILED_JOB_ENV] = failedJob ?? '';\n const postBlock = workflow.post;\n try {\n const postResult = await this.recordPhase(progress, POST_PHASE_JOB, () =>\n this.runPostBlock(postBlock, workflowEnv, inputs, secrets, {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n progress,\n workflowDir,\n }),\n );\n\n if (!postResult) {\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_POST_FAILED_TEXT}${RESET}`);\n if (!result || result.exitCode === 0 || result.exitCode === WORKFLOW_SKIPPED_EXIT_CODE) {\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n }\n } catch (postError) {\n runError ??= postError;\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_POST_FAILED_TEXT}${RESET}`);\n if (!result || result.exitCode === 0 || result.exitCode === WORKFLOW_SKIPPED_EXIT_CODE) {\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n }\n }\n\n if (\n shouldRunSuccessCompletionHooks &&\n result?.exitCode === 0 &&\n useWorktree &&\n workflow.worktree?.afterCompleted &&\n !dryRun &&\n !keepWorktree\n ) {\n workflowEnv[WORKFLOW_PHASE_ENV] = 'worktree-after-completed';\n this.logger.info(`\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}afterCompleted${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n const hookOk = await this.worktreeService.runHook(\n workflow.worktree.afterCompleted,\n originalDir,\n workflowEnv,\n inputs,\n secrets,\n { runner, cliAgent: input.cliAgent, dryRun, continueOnError },\n );\n\n if (!hookOk) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n } else {\n this.logger.error(`\\n${RED}${BOLD}worktree afterCompleted hook failed${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n }\n }\n\n if (shouldRemoveWorktreeOnExit && worktreePath) {\n await this.worktreeService.removeWorktree(originalDir, worktreePath);\n }\n\n if (result) {\n result = { ...result, output: this.outputLines.join('\\n') };\n }\n\n if (registryRun && !(dryRun && input.recovery)) {\n const finalizedRecord = await this.finalizeRegistryRun(registryRun, result, runError, {\n failedJob,\n failureReason,\n fixLoopCycle: persistedFixLoopCycle,\n originalRepoPath: worktreePath ? originalDir : undefined,\n worktreeBranch: worktreeBranch ?? undefined,\n worktreePath: worktreePath ?? undefined,\n });\n workflowEnv[WORKFLOW_PHASE_ENV] = 'terminal';\n await this.logger.event?.(finalizedRecord.stage === ERROR_STAGE ? 'error' : 'info', 'workflow.run.finished', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.duration_ms': Math.max(\n 0,\n Date.parse(finalizedRecord.finishedAt ?? finalizedRecord.startedAt) -\n Date.parse(finalizedRecord.startedAt),\n ),\n 'workflow.exit_code': finalizedRecord.exitCode ?? WORKFLOW_FAILED_EXIT_CODE,\n 'workflow.outcome': finalizedRecord.outcome ?? OUTCOME_FAILED,\n }),\n exception: runError instanceof Error ? runError : undefined,\n });\n\n if (input.statusFile) {\n try {\n await this.writeWorkflowStatusFile(input.statusFile, finalizedRecord);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger.error(`\\n${RED}${BOLD}Workflow status-file write failed${RESET}: ${message}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n }\n }\n }\n\n return result ?? { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n\n /**\n * Ephemeral paths let recovery dry runs assemble prompts against copied\n * evidence without moving or writing the terminal registry directory.\n */\n private async createRecoveryDryRunHandle(input: RunWorkflowInput, workspace: string): Promise<WorkflowRunHandle> {\n if (!input.recovery) throw new Error('Recovery dry-run state is missing.');\n const runDir = getOrThrow(await this.runtime.fs.createTempDir(DRY_RUN_ARTIFACT_PREFIX, this.runtime.ioContext));\n return {\n changelogPath: resolve(runDir, 'changelog.md'),\n contextPath: resolve(runDir, 'context.md'),\n displayName: input.name ?? input.recovery.runKey,\n pauseRequestPath: resolve(runDir, 'pause-request.json'),\n recordPath: resolve(runDir, 'run.json'),\n runDir,\n runId: `dry-run-${input.recovery.runKey}`,\n runKey: input.recovery.runKey,\n stopRequestPath: resolve(runDir, 'stop-request.json'),\n workspace,\n };\n }\n\n private async writeDryRunWorkflowArtifact(\n workflow: Workflow,\n jobOrder: string[],\n promptAssemblies: DryRunPromptAssembly[],\n ): Promise<string> {\n const promptsByJob = new Map<string, DryRunPromptAssembly[]>();\n for (const assembly of promptAssemblies) {\n const existing = promptsByJob.get(assembly.jobName) ?? [];\n existing.push(assembly);\n promptsByJob.set(assembly.jobName, existing);\n }\n\n const jobs = Object.fromEntries(\n Object.entries(workflow.jobs).map(([jobName, job]) => {\n const assemblies = promptsByJob.get(jobName);\n if (!assemblies?.length) {\n return [jobName, job];\n }\n\n return [\n jobName,\n {\n ...job,\n 'system-prompt': assemblies[0].prompt,\n 'x-dry-run-prompt-variants': assemblies.map(({ matrix, prompt }) => ({ matrix, prompt })),\n },\n ];\n }),\n );\n const artifact = {\n ...workflow,\n 'x-dry-run': {\n 'selected-job-order': jobOrder,\n },\n jobs,\n };\n const artifactDir = getOrThrow(\n await this.runtime.fs.createTempDir(DRY_RUN_ARTIFACT_PREFIX, this.runtime.ioContext),\n );\n const artifactPath = resolve(artifactDir, DRY_RUN_ARTIFACT_FILENAME);\n getOrThrow(\n await this.runtime.fs.writeFile(\n artifactPath,\n serializeYaml(artifact, { lineWidth: -1, noRefs: true }),\n this.runtime.ioContext,\n ),\n );\n await this.runtime.workflowHost.setMode(artifactPath, 0o600);\n return artifactPath;\n }\n\n /**\n * Resolve the effective exit code and outcome for a settled run.\n * Shared by the post block env and registry finalization so they cannot drift.\n */\n private resolveRunOutcome(\n result: RunWorkflowResult | null,\n runError: unknown,\n ): { exitCode: number; outcome: WorkflowOutcome } {\n const interrupted = result?.exitCode === INTERRUPTED_EXIT_CODE || runError instanceof WorkflowInterruptedError;\n const exitCode = result?.exitCode ?? (interrupted ? INTERRUPTED_EXIT_CODE : WORKFLOW_FAILED_EXIT_CODE);\n const outcome =\n exitCode === 0\n ? OUTCOME_SUCCESS\n : exitCode === WORKFLOW_SKIPPED_EXIT_CODE\n ? OUTCOME_SKIPPED\n : interrupted || this.isInterrupted()\n ? OUTCOME_INTERRUPTED\n : OUTCOME_FAILED;\n return { exitCode, outcome };\n }\n\n /**\n * Persist the terminal stage for a workflow run after execution completes.\n */\n private async finalizeRegistryRun(\n registryRun: WorkflowRunHandle,\n result: RunWorkflowResult | null,\n runError: unknown,\n recoveryMetadata: {\n failedJob?: string;\n failureReason?: string;\n fixLoopCycle?: number;\n originalRepoPath?: string;\n worktreeBranch?: string;\n worktreePath?: string;\n } = {},\n ): Promise<WorkflowRunRecord> {\n const { exitCode, outcome } = this.resolveRunOutcome(result, runError);\n const stage = exitCode === 0 || exitCode === WORKFLOW_SKIPPED_EXIT_CODE ? COMPLETED_STAGE : ERROR_STAGE;\n // A failed run says why when it knows, such as the outputs a job did not\n // write; its last output line only names the job.\n const errorMessage =\n runError instanceof Error\n ? runError.message\n : exitCode === WORKFLOW_FAILED_EXIT_CODE\n ? (recoveryMetadata.failureReason ?? this.lastMeaningfulOutputLine())\n : undefined;\n\n const finalizedRun = await this.registry.finalizeRun(registryRun, {\n errorMessage,\n exitCode,\n ...recoveryMetadata,\n outcome,\n stage,\n });\n\n return await this.registry.readRunRecord(finalizedRun.recordPath);\n }\n\n private buildLifecycleAttributes(\n workflowEnv: Record<string, string>,\n attributes: Record<string, string | number | boolean> = {},\n ): Record<string, string | number | boolean> {\n return {\n 'workflow.id': workflowEnv.WORKFLOW_ID ?? '',\n 'workflow.name': workflowEnv.WORKFLOW_NAME ?? '',\n 'workflow.workspace': workflowEnv.WORKFLOW_WORKSPACE ?? DEFAULT_WORKSPACE,\n 'workflow.run.id': workflowEnv.WORKFLOW_RUN_ID ?? '',\n 'workflow.run.key': workflowEnv.WORKFLOW_RUN_KEY ?? '',\n 'workflow.phase': workflowEnv[WORKFLOW_PHASE_ENV] ?? WORKFLOW_PHASE,\n ...attributes,\n };\n }\n\n /**\n * Write a terminal workflow record to a caller-provided completion file.\n */\n private async writeWorkflowStatusFile(statusFile: string, record: WorkflowRunRecord): Promise<void> {\n const targetPath = resolve(statusFile);\n const tempPath = `${targetPath}.${this.runtime.workflowHost.processId}.${Date.now()}.tmp`;\n\n try {\n getOrThrow(await this.runtime.fs.createDir(dirname(targetPath), { recursive: true }, this.runtime.ioContext));\n getOrThrow(\n await this.runtime.fs.writeFile(tempPath, `${JSON.stringify(record, null, 2)}\\n`, this.runtime.ioContext),\n );\n getOrThrow(await this.runtime.fs.renameFile(tempPath, targetPath, this.runtime.ioContext));\n } catch (error) {\n try {\n getOrThrow(await this.runtime.fs.remove(tempPath, undefined, this.runtime.ioContext));\n } catch (cleanupError) {\n this.logger.warn(\n `${YELLOW}warn${RESET} status-file temp cleanup failed: ${\n cleanupError instanceof Error ? cleanupError.message : String(cleanupError)\n }`,\n );\n }\n throw error;\n }\n }\n\n private async appendRepairReferenceToContext(contextPath: string, repair: WorkflowRepairRecord): Promise<void> {\n const existing = getOrThrow(await this.runtime.fs.readTextFile(contextPath, this.runtime.ioContext));\n const scope = repair.scopeJobs.length > 0 ? repair.scopeJobs.join(' -> ') : '(none)';\n const repairBlock = [\n '---',\n `## Repair ${repair.repairId} (cycle ${repair.fixCycle})`,\n `- Issue: ${repair.issueFile}`,\n `- Repair: issues/${repair.repairId}/repair.json`,\n `- Status: ${repair.status}`,\n `- Restart from: ${repair.restartFrom}`,\n `- Verifier: ${repair.verificationJob}`,\n `- Scope: ${scope}`,\n ].join('\\n');\n getOrThrow(await this.runtime.fs.writeFile(contextPath, `${existing}\\n\\n${repairBlock}`, this.runtime.ioContext));\n }\n\n /**\n * Why a proceed.md request cannot be honored, or undefined when it can.\n *\n * Every rejection is advisory: the run falls back to plain job order, which is\n * always a correct way to finish a repair. Failing the run over a bad forward\n * jump would turn an optimization into a hazard.\n */\n private proceedRejectionReason(request: {\n activeRepair: WorkflowRepairRecord | null;\n currentIndex: number;\n invalidTarget?: string;\n jobName: string;\n jobUsesRepair: boolean;\n target?: string;\n targetIndex: number;\n verifierIndex: number;\n }): string | undefined {\n if (!request.jobUsesRepair || !request.activeRepair) {\n return 'no repair is active for this job';\n }\n if (request.jobName === request.activeRepair.verificationJob) {\n return 'the verifying job has no forward targets';\n }\n if (request.invalidTarget) {\n return `\"${request.invalidTarget}\" is not in the workflow job order`;\n }\n if (!request.target) {\n return `no \"${PROCEED_TO_KEY}\" frontmatter field`;\n }\n if (request.targetIndex <= request.currentIndex) {\n return `\"${request.target}\" does not come after \"${request.jobName}\"`;\n }\n if (request.targetIndex > request.verifierIndex) {\n return `\"${request.target}\" comes after the verifying job \"${request.activeRepair.verificationJob}\"`;\n }\n return undefined;\n }\n\n private async appendProceedNoteToContext(\n contextPath: string,\n repairId: string,\n fromJob: string,\n toJob: string,\n skippedJobs: string[],\n ): Promise<void> {\n const existing = getOrThrow(await this.runtime.fs.readTextFile(contextPath, this.runtime.ioContext));\n const skipped = skippedJobs.length > 0 ? skippedJobs.join(', ') : '(none)';\n const note = `- Proceeded: \"${fromJob}\" -> \"${toJob}\" (repair ${repairId}, skipped: ${skipped})`;\n getOrThrow(await this.runtime.fs.writeFile(contextPath, `${existing}\\n${note}`, this.runtime.ioContext));\n }\n\n private setRepairEnvironment(\n workflowEnv: Record<string, string>,\n runDir: string,\n repair: WorkflowRepairRecord,\n ): void {\n const repairDir = resolve(runDir, 'issues', repair.repairId);\n workflowEnv[WORKFLOW_ACTIVE_REPAIR_ID_ENV] = repair.repairId;\n workflowEnv[WORKFLOW_ACTIVE_REPAIR_DIR_ENV] = repairDir;\n workflowEnv[WORKFLOW_ACTIVE_REPAIR_FILE_ENV] = resolve(repairDir, 'repair.json');\n workflowEnv[WORKFLOW_ACTIVE_ISSUE_FILE_ENV] = resolve(runDir, repair.issueFile);\n }\n\n private clearRepairEnvironment(workflowEnv: Record<string, string>): void {\n delete workflowEnv[WORKFLOW_ACTIVE_REPAIR_ID_ENV];\n delete workflowEnv[WORKFLOW_ACTIVE_REPAIR_DIR_ENV];\n delete workflowEnv[WORKFLOW_ACTIVE_REPAIR_FILE_ENV];\n delete workflowEnv[WORKFLOW_ACTIVE_ISSUE_FILE_ENV];\n }\n\n private async updateRepairReferenceStatus(\n contextPath: string,\n repairId: string,\n status: WorkflowRepairRecord['status'],\n ): Promise<void> {\n const content = getOrThrow(await this.runtime.fs.readTextFile(contextPath, this.runtime.ioContext));\n const heading = `## Repair ${repairId} `;\n const start = content.indexOf(heading);\n if (start < 0) {\n return;\n }\n const nextBlock = content.indexOf('\\n---\\n', start);\n const end = nextBlock < 0 ? content.length : nextBlock;\n const block = content.slice(start, end);\n const updatedBlock = block.replace(/^- Status: .*$/m, `- Status: ${status}`);\n if (block !== updatedBlock) {\n getOrThrow(\n await this.runtime.fs.writeFile(\n contextPath,\n `${content.slice(0, start)}${updatedBlock}${content.slice(end)}`,\n this.runtime.ioContext,\n ),\n );\n }\n }\n\n /**\n * Put a `workflow-mcp` launcher in the run directory, first on the run's\n * PATH, so agents record step decisions with this engine whatever their\n * shell's PATH and wherever the engine is installed. The decision\n * instructions also name it by path, for harnesses that reset PATH.\n */\n private async installStepCli(runDir: string, workflowEnv: Record<string, string>): Promise<void> {\n let cliPath: string;\n try {\n cliPath = this.resolveCliPath();\n } catch (error) {\n this.logger.warn(\n `${YELLOW}workflow-mcp step launcher not installed${RESET}: ${error instanceof Error ? error.message : String(error)}`,\n );\n return;\n }\n const binDir = resolve(runDir, STEP_CLI_DIRECTORY);\n const launcher = resolve(binDir, STEP_CLI_NAME);\n const runAsNode = this.runtime.workflowHost.isElectron ? 'ELECTRON_RUN_AS_NODE=1 ' : '';\n getOrThrow(await this.runtime.fs.createDir(binDir, { recursive: true }, this.runtime.ioContext));\n getOrThrow(\n await this.runtime.fs.writeFile(\n launcher,\n `#!/bin/sh\\n${runAsNode}exec ${escapeShellArg(this.runtime.workflowHost.executablePath)} ${escapeShellArg(cliPath)} \"$@\"\\n`,\n this.runtime.ioContext,\n ),\n );\n await this.runtime.workflowHost.setMode(launcher, 0o755);\n workflowEnv.PATH = `${binDir}:${workflowEnv.PATH ?? this.runtime.baseEnvironment.PATH ?? ''}`;\n }\n\n private resolveCliPath(): string {\n const cliPath = this.runtime.workflowHost.cliPath;\n if (!cliPath) throw new Error('The workflow CLI entry was not admitted by this host.');\n return cliPath;\n }\n\n private buildLaunchEnvironment(launcher?: WorkflowLauncherType): NodeJS.ProcessEnv {\n const env = { ...this.runtime.baseEnvironment };\n delete env[CMUX_SURFACE_ID_ENV];\n delete env[CMUX_WORKSPACE_ID_ENV];\n delete env[TMUX_PANE_ENV];\n delete env[WORKFLOW_LAUNCHER_TYPE_ENV];\n delete env[WORKFLOW_TMUX_SESSION_NAME_ENV];\n if (launcher) env[WORKFLOW_LAUNCHER_ENV] = launcher;\n // A delegated runner re-issues its own per-step status files; never pass a parent's through.\n delete env[WORKFLOW_STATUS_FILE_ENV];\n return env;\n }\n\n /**\n * Create a short command for launcher integrations such as cmux.\n *\n * The real invocation is written to a temp script so user-controlled values\n * like prompts are parsed by only the script shell, not by every launch layer.\n */\n private async createLaunchScriptCommand(\n input: RunWorkflowInput,\n workflowPath: string,\n workflow: Workflow,\n ): Promise<string> {\n const launchDir = getOrThrow(await this.runtime.fs.createTempDir('workflow-mcp-launch-', this.runtime.ioContext));\n const scriptPath = resolve(launchDir, 'run-workflow.sh');\n const innerCommand = this.buildLaunchCliCommand(input, workflowPath, workflow);\n const script = [\n '#!/bin/sh',\n ...(await this.buildLauncherOriginExports()),\n 'script_path=$0',\n 'rm -f \"$script_path\"',\n 'rmdir \"$(dirname \"$script_path\")\" 2>/dev/null || true',\n `exec ${innerCommand}`,\n '',\n ].join('\\n');\n\n await this.runtime.workflowHost.writeExclusive(scriptPath, script);\n return `sh ${escapeShellArg(scriptPath)}`;\n }\n\n private async buildLauncherOriginExports(): Promise<string[]> {\n const exports: string[] = [];\n if (this.runtime.baseEnvironment[CMUX_WORKSPACE_ID_ENV]) {\n exports.push(\n `export ${WORKFLOW_LAUNCHER_ORIGIN_WORKSPACE_ID_ENV}=${escapeShellArg(this.runtime.baseEnvironment[CMUX_WORKSPACE_ID_ENV])}`,\n );\n }\n if (this.runtime.baseEnvironment[CMUX_SURFACE_ID_ENV]) {\n exports.push(\n `export ${WORKFLOW_LAUNCHER_ORIGIN_SURFACE_ID_ENV}=${escapeShellArg(this.runtime.baseEnvironment[CMUX_SURFACE_ID_ENV])}`,\n );\n }\n const paneId = this.runtime.baseEnvironment[TMUX_PANE_ENV];\n if (paneId) {\n exports.push(`export ${WORKFLOW_LAUNCHER_ORIGIN_PANE_ID_ENV}=${escapeShellArg(paneId)}`);\n const identity = await this.readTmuxIdentity(paneId);\n if (identity?.sessionId) {\n exports.push(`export ${WORKFLOW_LAUNCHER_ORIGIN_SESSION_ID_ENV}=${escapeShellArg(identity.sessionId)}`);\n }\n }\n return exports;\n }\n\n private async resolveLauncherMetadata(): Promise<WorkflowLauncherMetadata | undefined> {\n // RMUX hosting keeps the legacy native discriminator and socket contract,\n // so the run records its detached host pid rather than an internal RMUX target.\n if (this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_TYPE_ENV] === NATIVE_LAUNCHER_TYPE) {\n return { pid: this.runtime.workflowHost.processId, type: NATIVE_LAUNCHER_TYPE };\n }\n if (this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_TYPE_ENV] === 'tmux') {\n const paneId = this.runtime.baseEnvironment[TMUX_PANE_ENV];\n const identity = paneId ? await this.readTmuxIdentity(paneId) : undefined;\n const sessionName = identity?.sessionName ?? this.runtime.baseEnvironment[WORKFLOW_TMUX_SESSION_NAME_ENV];\n if (!sessionName) return undefined;\n return {\n originPaneId: this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_ORIGIN_PANE_ID_ENV],\n originSessionId: this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_ORIGIN_SESSION_ID_ENV],\n originSurfaceId: this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_ORIGIN_SURFACE_ID_ENV],\n originWorkspaceId: this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_ORIGIN_WORKSPACE_ID_ENV],\n paneId: identity?.paneId ?? paneId,\n sessionId: identity?.sessionId,\n sessionName,\n type: 'tmux',\n windowId: identity?.windowId,\n };\n }\n\n const workspaceId = this.runtime.baseEnvironment[CMUX_WORKSPACE_ID_ENV];\n if (!workspaceId) return undefined;\n return {\n originSurfaceId: this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_ORIGIN_SURFACE_ID_ENV],\n originWorkspaceId: this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_ORIGIN_WORKSPACE_ID_ENV],\n surfaceId: this.runtime.baseEnvironment[CMUX_SURFACE_ID_ENV],\n type: 'cmux',\n workspaceId,\n };\n }\n\n private async readTmuxIdentity(\n paneId: string,\n ): Promise<{ paneId: string; sessionId: string; sessionName: string; windowId: string } | undefined> {\n try {\n const output = (\n await workflowShellOutput(\n this.runtime,\n `tmux display-message -p -t ${escapeShellArg(paneId)} ${escapeShellArg('#{session_id}\\t#{session_name}\\t#{window_id}\\t#{pane_id}')}`,\n )\n ).trim();\n const [sessionId, sessionName, windowId, resolvedPaneId] = output.split('\\t');\n if (!sessionId || !sessionName || !windowId || !resolvedPaneId) return undefined;\n return { paneId: resolvedPaneId, sessionId, sessionName, windowId };\n } catch (error) {\n this.logger.warn(`Unable to resolve tmux identity for ${paneId}: ${String(error)}`);\n return undefined;\n }\n }\n\n /**\n * Reconstruct the CLI command string for launch-command delegation,\n * adding --skip-launch to prevent infinite recursion.\n */\n private buildLaunchCliCommand(input: RunWorkflowInput, workflowPath: string, workflow: Workflow): string {\n const cliPath = this.resolveCliPath();\n const parts = ['node', escapeShellArg(cliPath), 'run-workflow', escapeShellArg(workflowPath), '--skip-launch'];\n const runner = this.resolveRunner(input, workflow);\n if (input.job) parts.push('--job', escapeShellArg(input.job));\n if (runner) parts.push('--runner', escapeShellArg(runner));\n if (input.command) parts.push('--command', escapeShellArg(input.command));\n if (input.choice) parts.push('--choice', escapeShellArg(input.choice));\n if (input.dryRun) parts.push('--dry-run');\n if (input.continueOnError) parts.push('--continue-on-error');\n if (input.keepWorktree) parts.push('--keep-worktree');\n if (input.prompt) parts.push('--prompt', escapeShellArg(input.prompt));\n if (input.name) parts.push('--name', escapeShellArg(input.name));\n if (input.workspace) parts.push('--workspace', escapeShellArg(input.workspace));\n if (input.secretFile) parts.push('--secret-file', escapeShellArg(input.secretFile));\n if (input.statusFile) parts.push('--status-file', escapeShellArg(input.statusFile));\n if (input.inputs) {\n for (const [key, val] of Object.entries(input.inputs)) {\n parts.push('--input', escapeShellArg(`${key}=${val}`));\n }\n }\n if (input.env) {\n for (const [key, val] of Object.entries(input.env)) {\n parts.push('--env', escapeShellArg(`${key}=${val}`));\n }\n }\n return parts.join(' ');\n }\n\n /**\n * Return the last non-empty log line for failed run metadata.\n */\n private lastMeaningfulOutputLine(): string | undefined {\n return [...this.outputLines].reverse().find((line) => line.trim().length > 0);\n }\n\n /**\n * Run pre-services and setup steps before job execution begins.\n */\n /**\n * Run the `launch-command` delegation and wait for it to settle.\n *\n * Asynchronous rather than `execSync` because this is not always the CLI. In\n * the Pi extension the workflow engine runs inside the TUI's own process, and\n * a synchronous spawn freezes its event loop for the whole launch: measured at\n * roughly a second, most of it `pnpm exec` resolution, during which nothing\n * repaints and no keystroke is read. `run()` is already async, so blocking\n * bought nothing to begin with.\n */\n private spawnLaunchCommand(\n shell: string,\n options: { cwd: string; env: NodeJS.ProcessEnv },\n ): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n return new Promise((settle) => {\n // `shell: true` keeps `execSync`'s contract: the launch-command is a shell\n // string with its own quoting and substitutions, not an argv vector.\n const child = this.runtime.workflowHost.spawn(shell, [], {\n shell: true,\n cwd: options.cwd,\n env: options.env,\n stdio: this.launchStdio,\n });\n let stdout = '';\n let stderr = '';\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n child.on('error', (error) => {\n settle({ exitCode: WORKFLOW_FAILED_EXIT_CODE, stdout: stdout.trim(), stderr: error.message });\n });\n child.on('close', (code, signal) => {\n // A signalled launcher has no exit code; treat it as a failed launch\n // rather than reporting the success that `code ?? 0` would imply.\n const exitCode = code ?? (signal ? WORKFLOW_FAILED_EXIT_CODE : 0);\n settle({ exitCode, stdout: stdout.trim(), stderr: stderr.trim() });\n });\n });\n }\n\n /**\n * Run a phase block, recording its start and however it settles.\n *\n * Wraps rather than annotating each exit: between them the two blocks return\n * from six places and can also throw, and a phase that starts without ever\n * finishing reads as permanently running to everything downstream.\n */\n private async recordPhase(\n progress: WorkflowProgressService | undefined,\n name: string,\n run: () => Promise<boolean>,\n ): Promise<boolean> {\n // `record` rather than `jobStarted`: a phase has no position in the job\n // order, and passing 0-of-1 would render a counter that means nothing.\n await progress?.record({ type: 'job', status: 'running', job: name });\n try {\n const ok = await run();\n await progress?.jobFinished(name, ok ? 'completed' : 'failed');\n return ok;\n } catch (error) {\n await progress?.jobFinished(name, 'failed', error instanceof Error ? error.message : String(error));\n throw error;\n }\n }\n\n private async runPreBlock(\n pre: import('../../schemas/workflowEngine').PreBlock,\n baseEnv: Record<string, string>,\n inputs: Map<string, string>,\n secrets: Map<string, string>,\n options: {\n cliAgent?: string;\n runner?: string;\n dryRun: boolean;\n continueOnError: boolean;\n progress?: WorkflowProgressService;\n stopRequestPath?: string;\n workflowDir: string;\n onStepStarted?: (stepName: string, index: number, total: number) => Promise<void> | void;\n onExecutionStateChange?: (state: 'paused' | 'resumed', stepName: string) => Promise<void> | void;\n },\n ): Promise<boolean> {\n this.logger.info(`\\n ${BLUE}${BOLD}pre${RESET} ${BOLD}Pre-conditions${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n // Ensure context dir exists\n if (baseEnv.CONTEXT_FILE) {\n const contextDir = dirname(resolve(options.workflowDir, baseEnv.CONTEXT_FILE));\n getOrThrow(await this.runtime.fs.createDir(contextDir, { recursive: true }, this.runtime.ioContext));\n }\n\n // Start background services\n if (pre.services && pre.services.length > 0) {\n this.logger.info(`\\n ${BLUE}${BOLD}services${RESET}`);\n\n for (const service of pre.services) {\n const svc = await this.serviceManager.startService(service, baseEnv, options.workflowDir, options.dryRun);\n if (svc) {\n if (service['ready-check'] && !options.dryRun) {\n const ready = await this.serviceManager.waitForServiceReady(\n service,\n options.workflowDir,\n baseEnv,\n () => this.interruptedSignal !== null,\n );\n if (this.isInterrupted()) {\n return false;\n }\n if (!ready && !options.continueOnError) {\n await this.serviceManager.stopAll();\n return false;\n }\n }\n }\n }\n\n // Brief pause to let services initialize\n if (!options.dryRun && this.serviceManager.getRunningServices().length > 0) {\n await this.waitForServiceStartup();\n }\n }\n\n // Run setup steps\n if (pre.steps && pre.steps.length > 0) {\n this.logger.info(`\\n ${BLUE}${BOLD}setup${RESET}`);\n\n const stepContext = {\n inputs,\n matrix: {} as import('../../schemas/workflowEngine').MatrixEntry,\n secrets,\n env: baseEnv,\n };\n\n for (const [index, step] of pre.steps.entries()) {\n const stepName = step.name ?? `step ${index + 1}`;\n await options.onStepStarted?.(stepName, index, pre.steps.length);\n await options.progress?.stepStarted(PRE_PHASE_JOB, stepName, index, pre.steps.length);\n let failure: string | undefined;\n const stepOptions = {\n ...options,\n onExecutionStateChange: async (state: 'paused' | 'resumed', pausedStepName: string) => {\n await options.onExecutionStateChange?.(state, pausedStepName);\n await options.progress?.stepFinished(PRE_PHASE_JOB, pausedStepName, state);\n },\n onFailure: (reason: string) => {\n failure = reason;\n },\n onExecutionStarted: (ref: StepExecutionRef) =>\n options.progress?.stepExecutionStarted(PRE_PHASE_JOB, stepName, ref),\n };\n const ok = await this.stepRunner.runStep(step, stepContext, stepOptions);\n await options.progress?.stepFinished(\n PRE_PHASE_JOB,\n stepName,\n ok ? 'completed' : 'failed',\n ok ? undefined : failure,\n );\n if (!ok) {\n this.logger.error(`\\n ${RED}Pre-condition step failed${RESET}`);\n await this.serviceManager.stopAll();\n return false;\n }\n }\n }\n\n this.logger.info(`\\n ${GREEN}Pre-conditions ready${RESET}`);\n return true;\n }\n\n /**\n * Run post-cleanup services and steps after the main workflow path settles.\n */\n private async runPostBlock(\n post: import('../../schemas/workflowEngine').PreBlock,\n baseEnv: Record<string, string>,\n inputs: Map<string, string>,\n secrets: Map<string, string>,\n options: {\n cliAgent?: string;\n runner?: string;\n dryRun: boolean;\n continueOnError: boolean;\n progress?: WorkflowProgressService;\n workflowDir: string;\n },\n ): Promise<boolean> {\n this.logger.info(`\\n ${BLUE}${BOLD}post${RESET} ${BOLD}Cleanup${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n await this.serviceManager.stopAll();\n\n try {\n if (post.services && post.services.length > 0) {\n this.logger.info(`\\n ${BLUE}${BOLD}services${RESET}`);\n\n for (const service of post.services) {\n const svc = await this.serviceManager.startService(service, baseEnv, options.workflowDir, options.dryRun);\n if (svc && service['ready-check'] && !options.dryRun) {\n const ready = await this.serviceManager.waitForServiceReady(\n service,\n options.workflowDir,\n baseEnv,\n () => false,\n );\n if (!ready && !options.continueOnError) {\n return false;\n }\n }\n }\n\n if (!options.dryRun && this.serviceManager.getRunningServices().length > 0) {\n await this.waitForServiceStartup();\n }\n }\n\n if (post.steps && post.steps.length > 0) {\n this.logger.info(`\\n ${BLUE}${BOLD}cleanup${RESET}`);\n\n const stepContext = {\n inputs,\n matrix: {} as import('../../schemas/workflowEngine').MatrixEntry,\n secrets,\n env: baseEnv,\n };\n\n for (const [index, step] of post.steps.entries()) {\n const stepName = step.name ?? `step ${index + 1}`;\n await options.progress?.stepStarted(POST_PHASE_JOB, stepName, index, post.steps.length);\n let failure: string | undefined;\n const ok = await this.stepRunner.runStep(step, stepContext, {\n ...options,\n onFailure: (reason: string) => {\n failure = reason;\n },\n onExecutionStarted: (ref: StepExecutionRef) =>\n options.progress?.stepExecutionStarted(POST_PHASE_JOB, stepName, ref),\n });\n await options.progress?.stepFinished(\n POST_PHASE_JOB,\n stepName,\n ok ? 'completed' : 'failed',\n ok ? undefined : failure,\n );\n if (!ok) {\n this.logger.error(`\\n ${RED}Post-cleanup step failed${RESET}`);\n return false;\n }\n }\n }\n\n this.logger.info(`\\n ${GREEN}Cleanup complete${RESET}`);\n return true;\n } finally {\n await this.serviceManager.stopAll();\n }\n }\n}\n\n/**\n * Build a runner safe to embed in a process whose stdout belongs to something\n * else: the Pi extension, where stdout is the TUI's screen and stdin its\n * keyboard, or the stdio MCP server, where stdout is the JSON-RPC stream.\n *\n * Silencing the console costs nothing. Every line still reaches `outputLines`,\n * which is what `RunWorkflowResult.output` returns, so the caller sees the same\n * text it always did; it just arrives as a value instead of as a side effect on\n * a shared terminal.\n *\n * A host that keeps its own record of the run passes `logger`, and gets every\n * line as it is written, including why a step failed. Its telemetry events\n * still reach the engine's own telemetry unless the host logger records them.\n */\nexport function createEmbeddedRunWorkflowService(\n dependencies: RunWorkflowDependencies,\n logger?: Logger,\n): RunWorkflowService {\n const silent = createWorkflowLogger({\n info: () => {},\n error: () => {},\n warn: () => {},\n });\n const host: Logger = logger\n ? {\n ...logger,\n ...(logger.event ? {} : silent.event ? { event: silent.event } : {}),\n ...(logger.flush ? {} : silent.flush ? { flush: silent.flush } : {}),\n }\n : silent;\n return new RunWorkflowService(host, {\n ...dependencies,\n launcherMetadata: dependencies.launcherMetadata ?? {\n pid: dependencies.runtime.workflowHost.processId,\n type: 'native',\n },\n launchStdio: 'pipe',\n ownsTerminal: false,\n });\n}\n","/**\n * RecoverWorkflowService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n * - Document complex logic with comments\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { pathExists } from '@agimon-ai/po-core/platform';\n\nimport { RunWorkflowService } from '../RunWorkflowService';\nimport { WorkflowParserService } from '../WorkflowParserService';\nimport { WorkflowRegistryService } from '../WorkflowRegistryService';\nimport { WorkflowRepairService } from '../WorkflowRepairService';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport type { RecoverWorkflowInput, RecoverWorkflowResult } from './types';\n\nconst ERROR_STAGE = 'error';\nconst FIX_FRONTMATTER_DELIMITER = '---';\nconst FIX_RESTART_FROM_KEY = 'restart-from';\nconst FIX_STATUS_KEY = 'status';\nconst FIX_TERMINAL_TARGET = 'stop';\nconst REPAIR_TRIAGE_JOB_NAME = 'repair-triage';\nconst PI_SESSION_ENV = 'PI_SESSION_ID';\n\n/**\n * RecoverWorkflowService reconstructs and replays failed workflow runs.\n */\nexport class RecoverWorkflowService {\n /**\n * Creates a new RecoverWorkflowService instance.\n *\n * A delegated replay gets the owner from its registry-issued recovery claim,\n * so a CLI caller cannot choose another Pi session's identity.\n */\n constructor(\n readonly runtime: WorkflowRuntimeContext,\n private registry = new WorkflowRegistryService(runtime),\n private runner = new RunWorkflowService(undefined, { registry, runtime }),\n private parser = new WorkflowParserService(runtime),\n private repairService = new WorkflowRepairService(runtime),\n ) {}\n\n /**\n * Recover a failed workflow run from registry metadata.\n */\n async recover(input: RecoverWorkflowInput): Promise<RecoverWorkflowResult> {\n return await this.recoverWithOwner(input);\n }\n\n /** Trusted embedding entry point; owner identity is never part of MCP/CLI input. */\n async recoverForSession(input: RecoverWorkflowInput, ownerSessionId: string): Promise<RecoverWorkflowResult> {\n return await this.recoverWithOwner(input, ownerSessionId);\n }\n\n private async recoverWithOwner(input: RecoverWorkflowInput, ownerSessionId?: string): Promise<RecoverWorkflowResult> {\n const record = await this.registry.readRunByKey(input.workspace, ERROR_STAGE, input.runKey);\n if (input.dryRun || record.dryRun) return await this.recoverClaimed(input, undefined, undefined, record);\n\n const claim = input.recoveryClaimId\n ? await this.registry.adoptRunRecoveryClaim(record.workspace, record.runKey, input.recoveryClaimId)\n : await this.registry.claimRunRecovery(record.workspace, record.runKey, ownerSessionId);\n try {\n if (!input.recoveryClaimId) {\n await this.registry.adoptRunRecoveryClaim(record.workspace, record.runKey, claim.claimId);\n }\n return await this.recoverClaimed(input, claim.claimId, claim.ownerSessionId, record);\n } catch (error) {\n await this.registry.releaseRunRecoveryClaim(record.workspace, record.runKey, claim.claimId);\n throw error;\n }\n }\n\n private async recoverClaimed(\n input: RecoverWorkflowInput,\n recoveryClaimId?: string,\n claimedOwnerSessionId?: string,\n failedRecord?: Awaited<ReturnType<WorkflowRegistryService['readRunByKey']>>,\n ): Promise<RecoverWorkflowResult> {\n const record = failedRecord ?? (await this.registry.readRunByKey(input.workspace, ERROR_STAGE, input.runKey));\n const activeRepair = record.activeRepairId\n ? await this.registry.readRunRepair(record.workspace, ERROR_STAGE, record.runKey, record.activeRepairId)\n : undefined;\n if (activeRepair && !['pending', 'active'].includes(activeRepair.status)) {\n throw new Error(\n `Workflow run \"${record.workspace}/${record.runKey}\" points to non-active repair ${activeRepair.repairId} (${activeRepair.status})`,\n );\n }\n\n const workflow = await this.parser.parseWorkflowFile(record.workflowPath);\n const repairTriageFailed = record.failedJob === REPAIR_TRIAGE_JOB_NAME && Boolean(workflow.repair);\n const fallbackRepairFailed = Boolean(\n activeRepair && !workflow.repair && record.failedJob && activeRepair.scopeJobs.includes(record.failedJob),\n );\n const terminalStopAuthorized = repairTriageFailed || fallbackRepairFailed;\n const terminalFixContent =\n activeRepair && !terminalStopAuthorized\n ? null\n : await this.registry.readRunFixContent(record.workspace, ERROR_STAGE, record.runKey);\n const terminalFix = terminalFixContent ? this.parseTerminalFix(terminalFixContent, terminalStopAuthorized) : {};\n if (terminalFix.terminal) {\n throw new Error(\n `Workflow run \"${record.workspace}/${record.runKey}\" has a terminal fix request and cannot be recovered`,\n );\n }\n const fixRestartFrom = terminalFix.restartFrom;\n const recoveredJob = activeRepair\n ? this.repairService.resolveRecoveryStart(activeRepair)\n : (fixRestartFrom ?? record.failedJob);\n\n if (!recoveredJob) {\n throw new Error(`Workflow run \"${record.workspace}/${record.runKey}\" does not include a recoverable failed job`);\n }\n\n if (record.worktreePath && !(await pathExists(this.runtime.fs, record.worktreePath, this.runtime.ioContext))) {\n throw new Error(`Recoverable worktree not found: ${record.worktreePath}`);\n }\n\n const runner = input.runner ?? record.runner ?? record.cliAgent;\n const cliAgent = runner === record.cliAgent ? record.cliAgent : undefined;\n const originalJob = fixRestartFrom && !activeRepair ? undefined : record.job;\n const jobOrder = this.parser.resolveJobOrder(workflow.jobs, originalJob ?? null);\n if (!jobOrder.includes(recoveredJob)) {\n throw new Error(\n `Workflow run \"${record.workspace}/${record.runKey}\" recovery target \"${recoveredJob}\" is not in the workflow job order`,\n );\n }\n\n const ownerSessionId = claimedOwnerSessionId?.trim();\n const envOverrides = ownerSessionId ? { [PI_SESSION_ENV]: ownerSessionId } : undefined;\n return await this.runner.run({\n cliAgent,\n runner,\n command: record.command,\n choice: record.choice,\n workflowPath: record.workflowPath,\n job: recoveredJob,\n inputs: record.inputs,\n env: envOverrides ? { ...record.env, ...envOverrides } : record.env,\n secretFile: record.secretFile,\n dryRun: input.dryRun ?? record.dryRun,\n continueOnError: record.continueOnError,\n keepWorktree: record.keepWorktree,\n prompt: record.prompt,\n name: record.displayName,\n workspace: record.workspace,\n skipLaunch: true,\n recovery: {\n activeRepairId: activeRepair?.repairId,\n claimId: recoveryClaimId,\n originalJob,\n originalRepoPath: record.originalRepoPath,\n runKey: record.runKey,\n startJob: recoveredJob,\n worktreeBranch: record.worktreeBranch,\n worktreePath: record.worktreePath,\n },\n });\n }\n\n private parseTerminalFix(\n fixContent: string,\n allowTerminalStop: boolean,\n ): { restartFrom?: string; terminal?: boolean } {\n if (!fixContent.startsWith(FIX_FRONTMATTER_DELIMITER)) {\n return {};\n }\n\n const endIndex = fixContent.indexOf(FIX_FRONTMATTER_DELIMITER, FIX_FRONTMATTER_DELIMITER.length);\n if (endIndex < 0) {\n return {};\n }\n\n const frontmatter = fixContent.slice(FIX_FRONTMATTER_DELIMITER.length, endIndex);\n let restartFrom: string | undefined;\n let terminalRequested = false;\n for (const line of frontmatter.split('\\n')) {\n const separatorIndex = line.indexOf(':');\n if (separatorIndex < 0) {\n continue;\n }\n const key = line.slice(0, separatorIndex).trim().toLowerCase();\n const value = line.slice(separatorIndex + 1).trim();\n if (key === FIX_STATUS_KEY && value.toLowerCase() === FIX_TERMINAL_TARGET) {\n terminalRequested = true;\n }\n if (key === FIX_RESTART_FROM_KEY) {\n if (value.toLowerCase() === FIX_TERMINAL_TARGET) {\n terminalRequested = true;\n continue;\n }\n restartFrom = value || undefined;\n }\n }\n\n return terminalRequested && allowTerminalStop ? { terminal: true } : { restartFrom };\n }\n}\n"],"ignoreList":[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25],"mappings":";;;;;;;;;;;;;;;;;;;AAOA,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;;AAqD9B,eAAsB,kBACpB,SACA,WACA,oBAAoB,IACpB,QAAQ,GACW;CACnB,MAAM,WAAA,GAAUA,4BAAAA,WAAAA,CACd,MAAM,QAAQ,GAAG,SAAA,GAAQC,UAAAA,QAAAA,CAAQ,QAAQ,KAAK,WAAW,iBAAiB,GAAG,QAAQ,SAAS,CAChG;CACA,MAAM,QAAkB,CAAC;CAEzB,KAAK,MAAM,SAAS,SAAS;EAC3B,IAAI,MAAM,SAAS,aAAa,MAAM,KAAK,WAAW,GAAG,GACvD;EAGF,MAAM,eAAe,oBAAoB,GAAG,kBAAkB,GAAG,MAAM,SAAS,MAAM;EACtF,IAAI,MAAM,SAAS,UAAU,sBAAsB,KAAK,MAAM,IAAI,GAChE,MAAM,KAAK,YAAY;OAClB,IAAI,MAAM,SAAS,eAAe,QAAQ,qBAC/C,MAAM,KAAK,GAAI,MAAM,kBAAkB,SAAS,WAAW,cAAc,QAAQ,CAAC,CAAE;CAExF;CAEA,OAAO;AACT;AAEA,eAAe,o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aml","WORKFLOW_DISPATCH_TRIGGER","CUSTOM_RUN_KEY","INTERACTIVE_RUN_KEY","stepLabel","z","BACKGROUND_CONTEXT","getOrThrow","CUSTOM_RUN_KEY","Liquid","resolve","pathExists","getOrThrow","parseYaml","resolve","getOrThrow","performance","spawn","constants","spawn","errorMessage","mkdir","join","writeFile","createRequire","path","fs","RMUX","NativeTerminalService","spawn","serveNativeTerminal","createServer","join","createConnection","connectNativeTerminal","createRequire","join","dirname","NativeTerminalService","serveNativeTerminal","connectNativeTerminal","createInterface","writeFile","link","lock","chmod","spawn","execFileSync","open","constants","createHash","join","nodeHost","createSerialRunner","dirname","getOrThrow","resolve","createHash","relative","FIX_FILENAME","join","randomUUID","getOrThrow","pathExists","writeFileAtomic","getOrThrow","resolve","DEFAULT_WORKSPACE","COMPLETED_STAGE","ERROR_STAGE","RUN_RECORD_FILENAME","FIX_FILENAME","PROCEED_FILENAME","PAUSE_REQUEST_FILENAME","ISSUES_DIRNAME","REPAIR_FILENAME","INTERRUPTED_EXIT_CODE","createSerialRunner","resolve","randomUUID","getOrThrow","writeFileAtomic","RESET","BOLD","DIM","GREEN","RED","BLUE","resolve","pathExists","join","dirname","RESET","BOLD","DIM","GREEN","YELLOW","RED","WORKFLOW_JOB_NAME_ENV_KEY","envFlagEnabled","randomUUID","resolve","pathExists","dirname","z","join","getOrThrow","RESET","DIM","CYAN","GREEN","YELLOW","RED","INTERRUPT_SIGNAL","HANGUP_SIGNAL","TERMINATE_SIGNAL","resolve","join","dirname","pathExists","getOrThrow","randomUUID","_exhaustive","writeFileAtomic","RESET","BOLD","DIM","CYAN","GREEN","RED","BLUE","INTERRUPT_SIGNAL","resolve","getOrThrow","dirname","basename","resolve","getOrThrow","RESET","DIM","YELLOW","resolve","dirname","basename","pathExists","removePath","FIX_FRONTMATTER_DELIMITER","FIX_RESTART_FROM_KEY","FIX_STATUS_KEY","FIX_TERMINAL_TARGET","ERROR_STAGE","REPAIR_TRIAGE_JOB_NAME","resolve","createHash","dirname","relative","basename","extname","getOrThrow","serializeYaml","pathExists"],"sources":["../src/services/workflowDiscovery/index.ts","../src/services/WorkflowCatalogService/index.ts","../src/schemas/workflowEngine.ts","../src/services/workflowRuntime/index.ts","../src/services/workflowShell/index.ts","../src/services/WorkflowParserService/index.ts","../src/services/WorkflowDoctorService/index.ts","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/errors.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/command.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/duration.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/process.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/control.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/expectations.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/compatibility.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/lifecycle.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/locators.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/snapshot.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/streams.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/validation.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/handles/pane.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/handles/window.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/handles/session.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/pane-set.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/builder.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/trace.js","../../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/rmux.js","../src/services/workflowHost/nativeTerminal.ts","../src/services/workflowHost/terminalSocket.ts","../src/services/workflowHost/index.ts","../src/services/NativeTerminalService/terminalSocket.ts","../src/services/NativeTerminalService/index.ts","../src/services/RunDirectoryService/index.ts","../src/services/StepDecisionService/index.ts","../src/models/InvalidWorkflowRunRecordError.ts","../src/models/WorkflowRunConflictError.ts","../src/services/WorkflowProgressService/index.ts","../src/services/WorkflowRegistryService/index.ts","../src/models/WorkflowCapacityError.ts","../src/models/WorkflowInterruptedError.ts","../src/services/BackgroundServiceManager/index.ts","../src/services/workflowTelemetry/index.ts","../src/services/JobRunnerService/index.ts","../src/models/WorkflowStepSpawnError.ts","../src/models/WorkflowStepTimeoutConfigError.ts","../src/schemas/workflowStepTimeout.ts","../src/services/CodexQuotaService/index.ts","../src/services/StepRunnerService/index.ts","../src/services/TriggerService/index.ts","../src/services/WorkflowRepairService/index.ts","../src/services/WorktreeService/index.ts","../src/services/RunWorkflowService/index.ts","../src/services/RecoverWorkflowService/index.ts"],"sourcesContent":["import { resolve } from 'node:path';\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\nimport { load as parseYaml } from 'js-yaml';\n\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nconst MAX_DIRECTORY_DEPTH = 4;\nconst WORKFLOW_FILE_PATTERN = /\\.workflow\\.ya?ml$/;\n\nexport interface WorkflowSummary {\n path: string;\n name: string;\n description: string;\n tags: string[];\n}\n\nexport interface WorkflowTagSummary {\n count: number;\n tag: string;\n}\n\nexport interface WorkflowListPagination {\n currentPage: number;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n pageSize: number;\n totalPages: number;\n totalWorkflows: number;\n}\n\nexport interface WorkflowListResult {\n directory: string;\n filter?: string;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n page: number;\n pageSize: number;\n pagination: WorkflowListPagination;\n tagFilter?: string[];\n tags: WorkflowTagSummary[];\n total: number;\n totalPages: number;\n workflows: WorkflowSummary[];\n}\n\ninterface WorkflowMetadata {\n name?: unknown;\n description?: unknown;\n tags?: unknown;\n}\n\ninterface ListWorkflowsOptions {\n page: number;\n pageSize: number;\n filter?: string;\n format: 'json' | 'text';\n tags?: string[];\n}\n\n/** Workflow files under `directory`, relative to it, skipping hidden entries and symlinks. */\nexport async function findWorkflowPaths(\n runtime: WorkflowRuntimeContext,\n directory: string,\n relativeDirectory = '',\n depth = 0,\n): Promise<string[]> {\n const entries = getOrThrow(\n await runtime.fs.listDir(resolve(runtime.cwd, directory, relativeDirectory), runtime.ioContext),\n );\n const paths: string[] = [];\n\n for (const entry of entries) {\n if (entry.kind === 'symlink' || entry.name.startsWith('.')) {\n continue;\n }\n\n const relativePath = relativeDirectory ? `${relativeDirectory}/${entry.name}` : entry.name;\n if (entry.kind === 'file' && WORKFLOW_FILE_PATTERN.test(entry.name)) {\n paths.push(relativePath);\n } else if (entry.kind === 'directory' && depth < MAX_DIRECTORY_DEPTH) {\n paths.push(...(await findWorkflowPaths(runtime, directory, relativePath, depth + 1)));\n }\n }\n\n return paths;\n}\n\nasync function readWorkflowSummary(\n runtime: WorkflowRuntimeContext,\n directory: string,\n path: string,\n): Promise<WorkflowSummary> {\n const parsed = parseYaml(\n getOrThrow(await runtime.fs.readTextFile(resolve(directory, path), runtime.ioContext)),\n ) as WorkflowMetadata | null;\n const tags = Array.isArray(parsed?.tags)\n ? [\n ...new Set(\n parsed.tags\n .filter((tag): tag is string => typeof tag === 'string')\n .map((tag) => tag.trim().toLocaleLowerCase())\n .filter(Boolean),\n ),\n ].sort()\n : [];\n return {\n path,\n name: typeof parsed?.name === 'string' ? parsed.name : '',\n description: typeof parsed?.description === 'string' ? parsed.description : '',\n tags,\n };\n}\n\nexport async function listWorkflows(\n runtime: WorkflowRuntimeContext,\n directory: string,\n options: Pick<ListWorkflowsOptions, 'filter' | 'page' | 'pageSize' | 'tags'>,\n): Promise<WorkflowListResult> {\n const resolvedDirectory = resolve(runtime.cwd, directory);\n const summaries = await Promise.all(\n (await findWorkflowPaths(runtime, resolvedDirectory))\n .sort()\n .map((path) => readWorkflowSummary(runtime, resolvedDirectory, path)),\n );\n const normalizedFilter = options.filter?.trim().toLocaleLowerCase();\n const textFiltered = normalizedFilter\n ? summaries.filter(({ path, name, description, tags }) =>\n `${path}\\n${name}\\n${description}\\n${tags.join('\\n')}`.toLocaleLowerCase().includes(normalizedFilter),\n )\n : summaries;\n const tagFilter = [\n ...new Set(options.tags?.map((tag) => tag.trim().toLocaleLowerCase()).filter(Boolean) ?? []),\n ].sort();\n const filtered =\n tagFilter.length > 0\n ? textFiltered.filter((workflow) => tagFilter.every((tag) => workflow.tags.includes(tag)))\n : textFiltered;\n const tagCounts = new Map<string, number>();\n for (const workflow of filtered) {\n for (const tag of workflow.tags) {\n tagCounts.set(tag, (tagCounts.get(tag) ?? 0) + 1);\n }\n }\n const tags = [...tagCounts.entries()]\n .map(([tag, count]) => ({ count, tag }))\n .sort((left, right) => left.tag.localeCompare(right.tag));\n const start = (options.page - 1) * options.pageSize;\n const total = filtered.length;\n const totalPages = Math.ceil(total / options.pageSize);\n const hasNextPage = options.page < totalPages;\n const hasPreviousPage = options.page > 1 && total > 0;\n\n return {\n directory: resolvedDirectory,\n ...(normalizedFilter ? { filter: options.filter?.trim() } : {}),\n hasNextPage,\n hasPreviousPage,\n page: options.page,\n pageSize: options.pageSize,\n pagination: {\n currentPage: options.page,\n hasNextPage,\n hasPreviousPage,\n pageSize: options.pageSize,\n totalPages,\n totalWorkflows: total,\n },\n ...(tagFilter.length > 0 ? { tagFilter } : {}),\n tags,\n total,\n totalPages,\n workflows: filtered.slice(start, start + options.pageSize),\n };\n}\n","/**\n * WorkflowCatalogService\n *\n * The repository's workflows, and the parsed detail a surface needs to launch\n * one of them.\n *\n * WHY THIS LIVES HERE:\n * Listing workflow files and reading their triggers, inputs, jobs and runner\n * maps is the same work whichever surface asks: a terminal picker, a cockpit\n * drawer, or an agent choosing what to launch. Each of them used to parse the\n * YAML again in its own vocabulary, which is how two surfaces come to disagree\n * about what a workflow requires.\n *\n * DESIGN PATTERNS:\n * - Discovery reuses the list-workflows command, so the catalog and the tool\n * can never find different files\n * - A parse failure is returned as `error`, never thrown: one unparseable file\n * in a repository must not take a whole board down\n * - Parsing is injected, so a caller that already holds a parser reuses it and\n * a test can supply a workflow object directly\n *\n * CODING STANDARDS:\n * - Named exports only\n * - Explicit return types on exported members\n *\n * AVOID:\n * - Paging here: a surface shows a repository's workflows, and repositories\n * have tens of them, not thousands\n */\n\nimport type { Job, Step, Workflow } from '../../schemas/workflowEngine';\nimport { listWorkflows } from '../workflowDiscovery';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport type {\n WorkflowArtifactSummary,\n WorkflowCatalogEntry,\n WorkflowInputSummary,\n WorkflowJobSummary,\n WorkflowSummaryDetail,\n} from './types';\n\n/** One page big enough for any repository, since this surface does not page. */\nconst CATALOG_PAGE_SIZE = 1000;\nconst CATALOG_PAGE = 1;\nconst WORKFLOW_DISPATCH_TRIGGER = 'workflow_dispatch';\nconst INPUTS_KEY = 'inputs';\nconst RUN_KEYS = ['interactiveRun', 'run'] as const;\nconst CUSTOM_RUN_KEY = 'customRun';\nconst INTERACTIVE_RUN_KEY = 'interactiveRun';\n\n/** Parses one workflow file into the engine's own shape. */\nexport type WorkflowFileParser = (workflowPath: string) => Workflow | Promise<Workflow>;\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};\n}\n\nfunction triggerBlock(workflow: Workflow): Record<string, unknown> {\n return asRecord(workflow.on);\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];\n}\n\n/**\n * The `workflow_dispatch` inputs a launch must collect.\n *\n * Read leniently: an input block that does not match the declared shape is\n * skipped rather than failing the whole read, because a surface that cannot\n * show one field is still more useful than one that shows none.\n */\nexport function describeWorkflowDispatch(workflow: Workflow): WorkflowInputSummary[] {\n const dispatch = triggerBlock(workflow)[WORKFLOW_DISPATCH_TRIGGER];\n const declarations = asRecord(asRecord(dispatch)[INPUTS_KEY]);\n const summaries: WorkflowInputSummary[] = [];\n for (const [name, declaration] of Object.entries(declarations)) {\n const definition = asRecord(declaration);\n summaries.push({\n name,\n ...(typeof definition.description === 'string' ? { description: definition.description } : {}),\n ...(typeof definition.required === 'boolean' ? { required: definition.required } : {}),\n ...(typeof definition.default === 'string' ? { default: definition.default } : {}),\n ...(typeof definition.type === 'string' ? { type: definition.type } : {}),\n ...(Array.isArray(definition.options) ? { options: stringArray(definition.options) } : {}),\n });\n }\n return summaries;\n}\n\n/** One step command map: the runner keys it names, and whether its step can run in-process instead. */\ninterface RunnerMap {\n keys: string[];\n custom: boolean;\n}\n\n/** A customRun keyed by runner, rather than one entry any runner runs. */\nfunction isCustomRunMap(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && typeof (value as { prompt?: unknown }).prompt !== 'string';\n}\n\n/** Collects every runner map a workflow's step commands declare. */\nfunction collectRunnerMaps(value: unknown, maps: RunnerMap[]): void {\n if (Array.isArray(value)) {\n for (const item of value) collectRunnerMaps(item, maps);\n return;\n }\n if (!value || typeof value !== 'object') return;\n const custom = CUSTOM_RUN_KEY in value;\n for (const [key, nested] of Object.entries(value)) {\n const isRunKey = (RUN_KEYS as readonly string[]).includes(key);\n if (isRunKey && nested && typeof nested === 'object' && !Array.isArray(nested)) {\n maps.push({ keys: Object.keys(nested), custom });\n } else if (key === CUSTOM_RUN_KEY && isCustomRunMap(nested)) {\n // Its runners are offered too; like any customRun step, it runs on the others as well.\n maps.push({ keys: Object.keys(nested), custom: true });\n } else {\n collectRunnerMaps(nested, maps);\n }\n }\n}\n\n/**\n * The runners every step of a workflow can run on, or undefined when it names\n * neither a runner map nor a custom runner.\n *\n * Undefined and an empty array mean different things: undefined is a workflow\n * whose steps take any runner, an empty array is one whose steps agree on none.\n * A step with a customRun takes any runner, since a runner its map does not name\n * runs it in-process; a named custom runner still needs every other map to name it.\n */\nexport function compatibleRunners(workflow: Workflow): string[] | undefined {\n const maps: RunnerMap[] = [];\n // Runner names are free-form, so a runner called `run` must not read as a step command map.\n collectRunnerMaps({ ...workflow, runners: undefined }, maps);\n const declared = Object.keys(workflow.runners ?? {});\n if (maps.length === 0 && declared.length === 0) return undefined;\n const candidates = new Set([...declared, ...maps.flatMap((map) => map.keys)]);\n return [...candidates].filter((runner) => maps.every((map) => map.custom || map.keys.includes(runner))).sort();\n}\n\n/** Collects the command names each templated interactiveRun offers. */\nfunction collectCommandOffers(value: unknown, offers: string[][]): void {\n if (Array.isArray(value)) {\n for (const item of value) collectCommandOffers(item, offers);\n return;\n }\n if (!value || typeof value !== 'object') return;\n for (const [key, nested] of Object.entries(value)) {\n if (key === INTERACTIVE_RUN_KEY && Array.isArray(nested)) {\n offers.push(nested.map((entry) => asRecord(entry).command).filter((name) => typeof name === 'string'));\n } else {\n collectCommandOffers(nested, offers);\n }\n }\n}\n\n/**\n * The commands every templated step of a workflow offers, in the order the\n * first step lists them, or undefined when no step is templated. These are\n * the values a launch's `--command` accepts.\n */\nexport function compatibleCommands(workflow: Workflow): string[] | undefined {\n const offers: string[][] = [];\n // Command and choice names are free-form, so their declarations are not steps.\n collectCommandOffers({ ...workflow, commands: undefined, choices: undefined }, offers);\n if (offers.length === 0) return undefined;\n return (offers[0] ?? []).filter((name) => offers.every((offer) => offer.includes(name)));\n}\n\n/**\n * A step's label for a summary: its name, else what it uses, else its id, else\n * its position. A `run:` step without a name is identified by position rather\n * than by its command, which would put a shell line into a summary pane.\n */\nfunction stepLabel(step: Step, index: number): string {\n if (step.name) return step.name;\n if (step.uses) return step.uses;\n if (step.id) return step.id;\n return `step ${index + 1}`;\n}\n\nfunction summarizeJobs(workflow: Workflow): WorkflowJobSummary[] {\n return Object.entries(workflow.jobs ?? {}).map(([name, job]: [string, Job]) => ({\n name,\n ...(job['runs-on'] ? { runsOn: job['runs-on'] } : {}),\n steps: (job.steps ?? []).map((step, index) => stepLabel(step, index)),\n }));\n}\n\n/** The run-directory entries a workflow declares, which are its deliverables. */\nfunction summarizeArtifacts(workflow: Workflow): WorkflowArtifactSummary[] {\n return (workflow['run-directory']?.entries ?? []).map((entry) => ({\n path: entry.path,\n kind: entry.kind,\n description: entry.description,\n producedBy: entry['produced-by'] ?? [],\n }));\n}\n\n/** Every workflow file under a directory, nearest name first. */\nexport async function readWorkflowCatalog(\n directory: string,\n runtime: WorkflowRuntimeContext,\n): Promise<WorkflowCatalogEntry[]> {\n const listed = await listWorkflows(runtime, directory, { page: CATALOG_PAGE, pageSize: CATALOG_PAGE_SIZE });\n return listed.workflows.map((workflow) => ({\n path: `${listed.directory}/${workflow.path}`,\n relativePath: workflow.path,\n name: workflow.name,\n description: workflow.description,\n tags: workflow.tags,\n }));\n}\n\n/**\n * One workflow's parsed detail, or the reason it could not be read.\n *\n * The parser is optional so a caller that already holds one reuses it rather\n * than building a second.\n */\nexport async function summarizeWorkflow(\n workflowPath: string,\n parse: WorkflowFileParser,\n): Promise<WorkflowSummaryDetail> {\n try {\n const workflow = await parse(workflowPath);\n const runners = compatibleRunners(workflow);\n const commands = compatibleCommands(workflow);\n const choices = Object.keys(workflow.choices ?? {});\n return {\n triggers: Object.keys(triggerBlock(workflow)),\n inputs: describeWorkflowDispatch(workflow),\n jobs: summarizeJobs(workflow),\n artifacts: summarizeArtifacts(workflow),\n ...(runners ? { runners } : {}),\n ...(commands ? { commands } : {}),\n ...(choices.length > 0 ? { choices } : {}),\n };\n } catch (cause) {\n return {\n triggers: [],\n inputs: [],\n jobs: [],\n artifacts: [],\n error: cause instanceof Error ? cause.message : String(cause),\n };\n }\n}\n","/**\n * Zod Schemas for Workflow YAML Validation\n *\n * DESIGN PATTERNS:\n * - Schema-first development: Zod schemas are the source of truth\n * - Types inferred from schemas via z.infer<>\n * - Runtime validation at YAML parse boundary\n *\n * CODING STANDARDS:\n * - Export all schemas and inferred types from this file\n * - Use descriptive names matching the workflow YAML structure\n *\n * AVOID:\n * - Duplicating type definitions manually (use z.infer<>)\n * - Validating deep inside services (validate at parse boundary)\n */\n\nimport { z } from 'zod';\n\n// ─── Workflow YAML schemas ──────────────────────────────────────────────────\n\nconst CoercedEnvRecord = z.record(z.string(), z.coerce.string());\n\nexport const WorkflowInputSchema = z.object({\n description: z.string().optional(),\n required: z.boolean().optional(),\n default: z.string().optional(),\n type: z.string().optional(),\n options: z.array(z.string()).optional(),\n});\n\nexport const MatrixEntrySchema = z.record(z.string(), z.string());\n\nexport const StepCommandMapSchema = z.record(z.string(), z.string());\n\nexport const StepCommandSchema = z.union([z.string(), StepCommandMapSchema]);\n\nconst WorkflowRelativePathSchema = z\n .string()\n .min(1)\n .describe('Path relative to WORKFLOW_RUN_DIR using forward slashes.')\n .refine(\n (value) =>\n !value.startsWith('/') &&\n !value.includes('\\\\') &&\n !value.split('/').some((segment) => segment === '' || segment === '.' || segment === '..'),\n 'Workflow artifact paths must be safe relative paths without empty, dot, or parent segments.',\n );\n\nconst StepArtifactsSchema = z\n .array(WorkflowRelativePathSchema)\n .min(1)\n .refine((paths) => new Set(paths).size === paths.length, 'Step artifact paths must be unique.')\n .describe('Declared run-directory files that an interactive step must update before stopping.');\n\n/**\n * Execution settings a step shares between its runners.\n *\n * Deliberately generic: the engine never reads a key, it only interpolates\n * them (`${{ runConfig.<key> }}`, lists joined with commas) and hands the map to\n * a host executor, which owns and validates the keys it understands.\n */\nexport const RunConfigSchema = z\n .record(z.string(), z.union([z.string(), z.array(z.string())]))\n .describe('Host execution settings shared by customRun and command runners.');\n\n/** What only an in-process host executor needs, beside the shared `runConfig`. */\nexport const CustomRunEntrySchema = z\n .object({\n prompt: z.string().min(1).describe('Prompt the host executor runs. Interpolated like a command.'),\n systemPrompt: z\n .string()\n .min(1)\n .optional()\n .describe('Text the host appends to the agent system prompt. Interpolated like the prompt.'),\n runConfig: RunConfigSchema.optional().describe(\"Settings laid over the step's shared runConfig.\"),\n })\n .describe('Step executed in-process by a host executor instead of a shell.');\n\n/**\n * One in-process run for any runner, or one per runner keyed like an\n * interactiveRun map, each with its own prompt and settings.\n */\nexport const CustomRunSchema = z.union([CustomRunEntrySchema, z.record(z.string(), CustomRunEntrySchema)]);\n\n/**\n * A named custom runner. Selecting it by name, the way a command map's key is\n * selected, runs every customRun step with this `runConfig` over its own.\n */\nexport const RunnerSchema = z\n .object({\n runConfig: RunConfigSchema.optional().describe('Settings laid over each customRun step runConfig.'),\n })\n .describe('Named custom runner a launch can select.');\n\n/**\n * A command a step can run through, as a Liquid template rendered into its\n * shell command. `inProcess` tells a host that runs agent sessions itself that\n * it may run the step in-process from the structured values instead.\n */\nexport const CommandTemplateSchema = z.union([\n z.string().min(1),\n z\n .object({\n run: z.string().min(1).describe('Liquid template rendered into the shell command.'),\n inProcess: z\n .boolean()\n .optional()\n .describe('A host that runs agent sessions may run this command in-process instead of the shell.'),\n })\n .strict(),\n]);\n\nexport const ChoiceSettingsSchema = z\n .object({\n model: z.string().min(1).optional(),\n thinking: z.string().min(1).optional(),\n subagentModel: z.string().min(1).optional(),\n subagentThinking: z.string().min(1).optional(),\n })\n .strict();\n\n/**\n * A named model composition: independent step and subagent settings, plus overrides\n * keyed by command name for commands whose model ids differ.\n */\nexport const ChoiceSchema = z\n .record(z.string(), z.union([z.string().min(1), ChoiceSettingsSchema]))\n .superRefine((choice, context) => {\n for (const [key, value] of Object.entries(choice)) {\n const setting = Object.hasOwn(ChoiceSettingsSchema.shape, key);\n if (setting !== (typeof value === 'string')) {\n context.addIssue({\n code: 'custom',\n message: setting\n ? `Choice ${key} must be a string.`\n : `Choice override \"${key}\" must be an object of choice settings for that command.`,\n path: [key],\n });\n }\n }\n });\n\n/** One command a step offers, with what it overrides for that command. */\nexport const CommandRefSchema = z\n .object({\n command: z.string().min(1).describe('Name of a command declared under the workflow commands.'),\n choice: z.string().min(1).optional().describe('Choice this command always runs with.'),\n runConfig: RunConfigSchema.optional().describe(\"Settings laid over the step's runConfig for this command.\"),\n prompt: z.string().min(1).optional(),\n systemPrompt: z.string().min(1).optional(),\n })\n .strict();\n\n/** Commands a step offers (the template form), or a legacy command string or runner map. */\nexport const InteractiveRunSchema = z.union([z.array(CommandRefSchema).min(1), StepCommandSchema]);\n\nexport const StrategySchema = z.object({\n 'fail-fast': z.boolean().optional(),\n matrix: z\n .looseObject({\n include: z.array(MatrixEntrySchema).optional(),\n })\n .optional(),\n});\n\nconst StepFieldsSchema = z.object({\n name: z.string().optional(),\n uses: z.string().optional(),\n run: StepCommandSchema.optional(),\n interactiveRun: InteractiveRunSchema.optional(),\n customRun: CustomRunSchema.optional(),\n runConfig: RunConfigSchema.optional(),\n prompt: z.string().min(1).optional().describe('Prompt of a templated interactiveRun, interpolated with ${{ }}.'),\n systemPrompt: z\n .string()\n .min(1)\n .optional()\n .describe('System prompt of a templated interactiveRun, interpolated with ${{ }}.'),\n choice: z.string().min(1).optional().describe('Choice this step runs with, whatever the launch selects.'),\n 'restart-from': z\n .string()\n .min(1)\n .optional()\n .describe('Job a failing run step asks the workflow to restart from, instead of failing the job.'),\n artifacts: StepArtifactsSchema.optional(),\n 'timeout-minutes': z.number().optional(),\n env: CoercedEnvRecord.optional(),\n with: z.record(z.string(), z.string()).optional(),\n 'working-directory': z.string().optional(),\n if: z.string().optional(),\n 'continue-on-error': z.boolean().optional(),\n 'timeout-retries': z.number().optional(),\n 'pause-policy': z.enum(['replay', 'protected']).optional(),\n id: z.string().optional(),\n});\n\nconst GROUP_STEP_KEYS = new Set(['name', 'id', 'parallel']);\n\nfunction refineStep(step: Record<string, unknown> & z.infer<typeof StepFieldsSchema>, context: z.RefinementCtx): void {\n if (step.artifacts && !step.interactiveRun && !step.customRun) {\n context.addIssue({\n code: 'custom',\n message: 'Step artifacts are only supported for interactiveRun and customRun steps.',\n path: ['artifacts'],\n });\n }\n const templated = Array.isArray(step.interactiveRun);\n if (templated) {\n if (step.run !== undefined || step.customRun !== undefined) {\n context.addIssue({\n code: 'custom',\n message: 'A templated interactiveRun cannot be combined with run or customRun.',\n path: ['interactiveRun'],\n });\n }\n const commands = step.interactiveRun as z.infer<typeof CommandRefSchema>[];\n if (step.prompt === undefined && commands.some((entry) => entry.prompt === undefined)) {\n context.addIssue({\n code: 'custom',\n message: 'A templated interactiveRun needs a prompt on the step or on every command.',\n path: ['prompt'],\n });\n }\n } else {\n for (const key of ['prompt', 'systemPrompt', 'choice'] as const) {\n if (step[key] !== undefined) {\n context.addIssue({\n code: 'custom',\n message: `${key} is only supported with a templated interactiveRun.`,\n path: [key],\n });\n }\n }\n }\n if (step['restart-from'] !== undefined && (step.run === undefined || step.interactiveRun || step.customRun)) {\n context.addIssue({\n code: 'custom',\n message: 'restart-from is only supported on run steps.',\n path: ['restart-from'],\n });\n }\n if (step.parallel !== undefined) {\n for (const [key, value] of Object.entries(step)) {\n if (value !== undefined && !GROUP_STEP_KEYS.has(key)) {\n context.addIssue({\n code: 'custom',\n message: `A parallel group only takes name and id; move ${key} onto its steps.`,\n path: [key],\n });\n }\n }\n }\n}\n\nconst ParallelStepSchema = StepFieldsSchema.extend({\n parallel: z.undefined({ error: 'Parallel groups cannot be nested.' }).optional(),\n}).superRefine(refineStep);\n\nexport const StepSchema = StepFieldsSchema.extend({\n parallel: z\n .array(ParallelStepSchema)\n .min(2)\n .optional()\n .describe('Steps run at the same time; their fix requests merge into one repair.'),\n}).superRefine(refineStep);\n\nexport const ServiceDefSchema = z.object({\n name: z.string(),\n run: z.string(),\n env: CoercedEnvRecord.optional(),\n 'working-directory': z.string().optional(),\n 'ready-check': z.union([z.string(), z.boolean()]).optional(),\n 'ready-timeout': z.number().optional(),\n host: z.string().optional(),\n port: z.number().int().min(1).max(65535).optional(),\n 'port-range': z\n .object({\n min: z.number().int().min(1).max(65535),\n max: z.number().int().min(1).max(65535),\n })\n .optional(),\n 'service-type': z.enum(['tool', 'service']).optional(),\n});\n\nexport const PreBlockSchema = z.object({\n services: z.array(ServiceDefSchema).optional(),\n steps: z.array(StepSchema).optional(),\n});\n\nexport const JobHookBlockSchema = z.object({\n steps: z.array(StepSchema).optional(),\n});\n\nexport const JobSchema = z.object({\n 'runs-on': z.string().optional(),\n needs: z.union([z.string(), z.array(z.string())]).optional(),\n extends: z.union([z.string(), z.array(z.string())]).optional(),\n description: z.string().optional(),\n strategy: StrategySchema.optional(),\n steps: z.array(StepSchema),\n preJob: JobHookBlockSchema.optional(),\n postJob: JobHookBlockSchema.optional(),\n env: CoercedEnvRecord.optional(),\n if: z.string().optional(),\n 'system-prompt': z.string().optional(),\n context: z.string().optional(),\n});\n\nexport const RepairTriageSchema = JobSchema.omit({\n extends: true,\n needs: true,\n}).describe('Workflow-defined repair triage that runs before jobs in an active repair.');\n\nexport const AgentDecisionTriggerSchema = z.object({\n steps: z.array(StepSchema),\n});\n\nexport const WorktreeHookSchema = z.object({\n steps: z.array(StepSchema),\n});\n\nexport const WorktreeConfigSchema = z.object({\n beforeCreate: WorktreeHookSchema.optional(),\n afterCreate: WorktreeHookSchema.optional(),\n beforeCompleted: WorktreeHookSchema.optional(),\n afterCompleted: WorktreeHookSchema.optional(),\n});\n\nexport const WorkflowKeybindingsSchema = z.object({\n STOP: z.string().optional(),\n});\n\nconst RUN_DIRECTORY_BUILT_IN_PATHS = new Set([\n 'run.json',\n 'context.md',\n 'changelog.md',\n 'fix.md',\n 'issues',\n 'decisions',\n 'bin',\n 'writes.ndjson',\n]);\n\nexport const RunDirectoryEntrySchema = z\n .object({\n path: WorkflowRelativePathSchema,\n kind: z.enum(['file', 'directory']).describe('Filesystem entry kind.'),\n description: z.string().min(1).describe('Agent-facing purpose of this entry.'),\n 'produced-by': z\n .array(z.string().min(1))\n .optional()\n .describe('Workflow jobs expected to create or update this entry.'),\n 'initial-content': z.string().optional().describe('Initial content used when creating a file.'),\n })\n .superRefine((entry, context) => {\n if (entry.kind === 'directory' && entry['initial-content'] !== undefined) {\n context.addIssue({\n code: 'custom',\n message: 'initial-content is only valid for file entries.',\n path: ['initial-content'],\n });\n }\n });\n\nexport const RunDirectorySchema = z\n .object({\n description: z.string().min(1).describe('Agent-facing purpose of the workflow run directory.'),\n entries: z.array(RunDirectoryEntrySchema).describe('Declared workflow-owned files and directories.'),\n })\n .superRefine((runDirectory, context) => {\n const seen = new Set<string>();\n for (const [index, entry] of runDirectory.entries.entries()) {\n if (RUN_DIRECTORY_BUILT_IN_PATHS.has(entry.path)) {\n context.addIssue({\n code: 'custom',\n message: `Run-directory path is owned by workflow-mcp: ${entry.path}`,\n path: ['entries', index, 'path'],\n });\n }\n if (seen.has(entry.path)) {\n context.addIssue({\n code: 'custom',\n message: `Duplicate run-directory path: ${entry.path}`,\n path: ['entries', index, 'path'],\n });\n }\n seen.add(entry.path);\n }\n });\n\nexport const WorkflowSchema = z\n .object({\n name: z.string().optional(),\n tags: z\n .array(z.string().trim().min(1))\n .optional()\n .describe('Tags used to categorize and filter workflow definitions.'),\n workspace: z.string().optional(),\n runner: z.string().optional().describe('Default runner key for step command maps when no CLI runner is provided.'),\n 'default-runner': z.string().optional().describe('Deprecated alias for runner.'),\n runners: z\n .record(z.string(), RunnerSchema)\n .optional()\n .describe('Named custom runners; selecting one lays its runConfig over every customRun step.'),\n commands: z\n .record(z.string(), CommandTemplateSchema)\n .optional()\n .describe('Command templates a templated interactiveRun selects with --command.'),\n choices: z\n .record(z.string(), ChoiceSchema)\n .optional()\n .describe('Model compositions a launch selects with --choice; \"default\" is used when none is named.'),\n runConfig: RunConfigSchema.optional().describe(\n 'Defaults laid under the runConfig of every interactiveRun and customRun step; a step key wins.',\n ),\n imports: z.array(z.string()).optional(),\n 'system-prompt': z.string().optional(),\n 'max-workflows': z.number().int().positive().optional(),\n 'launch-command': z.string().optional(),\n launcher: z.enum(['cmux', 'tmux']).optional(),\n keybindings: WorkflowKeybindingsSchema.optional(),\n 'run-directory': RunDirectorySchema.optional(),\n on: z\n .looseObject({\n workflow_dispatch: z\n .object({\n inputs: z.record(z.string(), WorkflowInputSchema).optional(),\n })\n .nullable()\n .optional(),\n agent_decision: AgentDecisionTriggerSchema.optional(),\n })\n .optional(),\n env: CoercedEnvRecord.optional(),\n pre: PreBlockSchema.optional(),\n post: PreBlockSchema.optional(),\n repair: RepairTriageSchema.optional(),\n worktree: WorktreeConfigSchema.optional(),\n jobs: z.record(z.string(), JobSchema),\n })\n .superRefine((workflow, context) => {\n const declaredFiles = new Set(\n (workflow['run-directory']?.entries ?? []).filter((entry) => entry.kind === 'file').map((entry) => entry.path),\n );\n for (const [jobName, job] of Object.entries(workflow.jobs)) {\n for (const [stepIndex, step] of job.steps.entries()) {\n const members = step.parallel\n ? step.parallel.map((child, childIndex) => ({ step: child, path: [stepIndex, 'parallel', childIndex] }))\n : [{ step, path: [stepIndex] }];\n for (const member of members) {\n for (const [artifactIndex, artifact] of (member.step.artifacts ?? []).entries()) {\n if (!declaredFiles.has(artifact)) {\n context.addIssue({\n code: 'custom',\n message: `Step artifact must reference a declared run-directory file: ${artifact}`,\n path: ['jobs', jobName, 'steps', ...member.path, 'artifacts', artifactIndex],\n });\n }\n }\n }\n }\n }\n for (const [entryIndex, entry] of (workflow['run-directory']?.entries ?? []).entries()) {\n for (const [producerIndex, producer] of (entry['produced-by'] ?? []).entries()) {\n if (!workflow.jobs[producer] || producer.startsWith('.')) {\n context.addIssue({\n code: 'custom',\n message: `Unknown producing job: ${producer}`,\n path: ['run-directory', 'entries', entryIndex, 'produced-by', producerIndex],\n });\n }\n }\n }\n });\n\n// ─── Runtime schemas ────────────────────────────────────────────────────────\n\nexport const WorkflowStageSchema = z.enum(['running', 'completed', 'error']);\n\nexport const WorkflowOutcomeSchema = z.enum(['success', 'skipped', 'failed', 'interrupted']);\n\n/**\n * One line of the run progress log.\n *\n * Append-only NDJSON in the run directory, because a run is a detached process\n * and anything held in its memory is invisible to every other process and lost\n * on crash. A reader can tail this to know which job and step a run is on,\n * which the run record cannot express: it carries only a stage.\n */\nexport const WorkflowExecutionStateSchema = z\n .enum(['running', 'pause_requested', 'paused', 'resume_requested'])\n .describe('Live execution state within a running workflow.');\n\nexport const WorkflowResumeModeSchema = z\n .enum(['replay-current', 'continue-next'])\n .describe('How a paused workflow resumes at its execution cursor.');\n\nexport const WorkflowExecutionCursorSchema = z.object({\n attempt: z.number().int().positive().optional(),\n executionGeneration: z.number().int().positive(),\n revision: z.number().int().nonnegative().optional(),\n job: z.string().optional(),\n matrixIndex: z.number().int().nonnegative().optional(),\n phase: z.string(),\n requestId: z.string().uuid().optional(),\n resumeMode: WorkflowResumeModeSchema,\n stepIndex: z.number().int().nonnegative().optional(),\n stepName: z.string().optional(),\n});\n\n/** A host-owned handle a reader can follow, such as an agent session or a terminal pane. */\nexport const StepExecutionRefSchema = z.object({\n kind: z.string().min(1).describe('Host-defined handle kind, such as session or pane.'),\n id: z.string().min(1),\n label: z.string().optional(),\n});\n\nexport const WorkflowProgressEventSchema = z.object({\n at: z.string().describe('ISO timestamp the event was recorded.'),\n index: z.number().int().nonnegative().optional().describe('Zero-based position within its parent sequence.'),\n job: z.string().describe('Job the event belongs to.'),\n /** Present on failures and skips, so a reader can show why without opening the log. */\n reason: z.string().optional(),\n status: z\n .enum(['running', 'completed', 'failed', 'pause_requested', 'paused', 'resumed', 'skipped'])\n .describe('State the subject moved into.'),\n step: z.string().optional().describe('Step name, absent for job-level events.'),\n group: z.string().optional().describe('Parallel group a step runs in, beside the other steps of that group.'),\n ref: StepExecutionRefSchema.optional().describe('Where a host executor runs the step, once it started.'),\n total: z.number().int().nonnegative().optional().describe('Length of the parent sequence, when known.'),\n type: z.enum(['job', 'step']),\n});\n\nexport const WorkflowRepairStatusSchema = z.enum(['pending', 'active', 'resolved', 'superseded', 'rejected']);\n\nexport const WorkflowRepairJobStatusSchema = z.enum([\n 'pending',\n 'running',\n 'completed',\n 'failed',\n 'interrupted',\n 'skipped',\n]);\n\nexport const WorkflowRepairJobAttemptSchema = z.object({\n attempt: z.number().int().positive(),\n finishedAt: z.string().optional(),\n startedAt: z.string(),\n status: z.enum(['running', 'completed', 'failed', 'interrupted']),\n workflowRunId: z.string().optional(),\n});\n\nexport const WorkflowRepairJobSchema = z.object({\n attempts: z.array(WorkflowRepairJobAttemptSchema),\n jobName: z.string(),\n status: WorkflowRepairJobStatusSchema,\n});\n\nexport const WorkflowRepairRoutingFallbackSchema = z.object({\n reason: z.enum(['missing', 'unknown']),\n requestedTarget: z.string().optional(),\n resolvedTarget: z.string(),\n});\n\nexport const WorkflowRepairRecordSchema = z.object({\n createdAt: z.string(),\n fixCycle: z.number().int().positive(),\n issueFile: z.string(),\n jobs: z.array(WorkflowRepairJobSchema),\n rejectedAt: z.string().optional(),\n repairId: z.string().regex(/^\\d+$/),\n resolvedAt: z.string().optional(),\n restartFrom: z.string(),\n routingFallback: WorkflowRepairRoutingFallbackSchema.optional(),\n schemaVersion: z.literal(1),\n scopeJobs: z.array(z.string()),\n status: WorkflowRepairStatusSchema,\n supersededAt: z.string().optional(),\n supersededBy: z.string().optional(),\n updatedAt: z.string(),\n verificationJob: z.string(),\n});\n\nconst CmuxWorkflowLauncherMetadataSchema = z.object({\n originSurfaceId: z.string().optional(),\n originWorkspaceId: z.string().optional(),\n surfaceId: z.string().optional(),\n type: z.literal('cmux'),\n workspaceId: z.string(),\n});\n\nconst TmuxWorkflowLauncherMetadataSchema = z.object({\n originPaneId: z.string().optional(),\n originSessionId: z.string().optional(),\n originSurfaceId: z.string().optional(),\n originWorkspaceId: z.string().optional(),\n paneId: z.string().optional(),\n sessionId: z.string().optional(),\n sessionName: z.string(),\n type: z.literal('tmux'),\n windowId: z.string().optional(),\n});\n\n/**\n * Compatibility metadata for the RMUX-backed launcher. The `native` literal is\n * retained for existing run records and cockpit clients; the detached host pid\n * and terminal socket remain the public identity.\n */\nconst NativeWorkflowLauncherMetadataSchema = z.object({\n pid: z.number().int().positive().optional(),\n type: z.literal('native'),\n});\n\nexport const WorkflowLauncherMetadataSchema = z.discriminatedUnion('type', [\n CmuxWorkflowLauncherMetadataSchema,\n TmuxWorkflowLauncherMetadataSchema,\n NativeWorkflowLauncherMetadataSchema,\n]);\n\nexport const WorkflowRunRecordSchema = z.object({\n activeRepairId: z.string().regex(/^\\d+$/).optional(),\n cliAgent: z.string().optional(),\n continueOnError: z.boolean().optional(),\n displayName: z.string(),\n dryRun: z.boolean(),\n env: z.record(z.string(), z.string()).optional(),\n executionCursor: WorkflowExecutionCursorSchema.optional(),\n executionState: WorkflowExecutionStateSchema.optional(),\n errorMessage: z.string().optional(),\n exitCode: z.number().optional(),\n failedJob: z.string().optional(),\n finishedAt: z.string().optional(),\n fixLoopCycle: z.number().int().positive().optional(),\n inputs: z.record(z.string(), z.string()).optional(),\n job: z.string().optional(),\n keepWorktree: z.boolean().optional(),\n launcher: WorkflowLauncherMetadataSchema.optional(),\n originalRepoPath: z.string().optional(),\n outcome: WorkflowOutcomeSchema.optional(),\n pid: z.number().int().positive().optional(),\n prompt: z.string().optional(),\n runner: z.string().optional(),\n command: z.string().optional().describe('Command the launch selected for templated interactiveRun steps.'),\n choice: z.string().optional().describe('Choice the launch selected for steps that do not pin one.'),\n runId: z.string().uuid().optional(),\n runKey: z.string(),\n secretFile: z.string().optional(),\n skipLaunch: z.boolean().optional(),\n stale: z.boolean().optional(),\n staleReason: z.string().optional(),\n stage: WorkflowStageSchema,\n startedAt: z.string(),\n statusFile: z.string().optional(),\n /**\n * Unix socket a natively hosted run answers screen, key and resize requests\n * on, so a reader outside the hosting process can attach to it. Absent for a\n * multiplexer-hosted run, which is addressed through the multiplexer itself.\n */\n terminalSocket: z.string().optional(),\n failureReason: z.string().optional(),\n worktreeBranch: z.string().optional(),\n worktreePath: z.string().optional(),\n workflowPath: z.string(),\n workflowId: z.string().optional(),\n workflowName: z.string().optional(),\n runDirectory: RunDirectorySchema.optional(),\n workspace: z.string(),\n effectiveStage: WorkflowStageSchema.optional(),\n effectiveOutcome: WorkflowOutcomeSchema.optional(),\n});\n\n/** What an agent decided a step's outcome is, through `workflow-mcp step`. */\nexport const StepDecisionSchema = z.discriminatedUnion('decision', [\n z.object({ decision: z.literal('complete'), summary: z.string().optional() }),\n z.object({ decision: z.literal('fix'), restartFrom: z.string().min(1), reason: z.string().min(1) }),\n z.object({ decision: z.literal('fail'), reason: z.string().min(1) }),\n]);\n\n/**\n * The per-attempt file a decision step shares with its agent and stop hooks.\n * The engine creates it, `workflow-mcp step` records the decision in it, and\n * stop hooks count the reminders they sent in `nudges`.\n */\nexport const StepDecisionFileSchema = z.object({\n schemaVersion: z.literal(1),\n job: z.string(),\n step: z.string(),\n restartTargets: z.array(z.string()),\n /** A templated agent step must decide; any other step may, and otherwise ends on its exit code. */\n required: z.boolean(),\n nudges: z.number().int().nonnegative(),\n decidedAt: z.string().optional(),\n decision: StepDecisionSchema.optional(),\n});\n\nexport const WorkflowRunHandleSchema = z.object({\n changelogPath: z.string(),\n contextPath: z.string(),\n displayName: z.string(),\n pauseRequestPath: z.string().optional(),\n recordPath: z.string(),\n runDir: z.string(),\n runId: z.string().uuid(),\n runKey: z.string(),\n stopRequestPath: z.string(),\n workspace: z.string(),\n});\n\n// ─── Inferred types ─────────────────────────────────────────────────────────\n\nexport type WorkflowExecutionCursor = z.infer<typeof WorkflowExecutionCursorSchema>;\nexport type WorkflowExecutionState = z.infer<typeof WorkflowExecutionStateSchema>;\nexport type WorkflowInput = z.infer<typeof WorkflowInputSchema>;\nexport type MatrixEntry = z.infer<typeof MatrixEntrySchema>;\nexport type StepCommandMap = z.infer<typeof StepCommandMapSchema>;\nexport type StepCommand = z.infer<typeof StepCommandSchema>;\nexport type CommandTemplate = z.infer<typeof CommandTemplateSchema>;\nexport type Choice = z.infer<typeof ChoiceSchema>;\nexport type CommandRef = z.infer<typeof CommandRefSchema>;\nexport type StepDecision = z.infer<typeof StepDecisionSchema>;\nexport type StepDecisionFile = z.infer<typeof StepDecisionFileSchema>;\nexport type Strategy = z.infer<typeof StrategySchema>;\nexport type Step = z.infer<typeof StepSchema>;\nexport type RunConfig = z.infer<typeof RunConfigSchema>;\nexport type CustomRun = z.infer<typeof CustomRunSchema>;\nexport type CustomRunEntry = z.infer<typeof CustomRunEntrySchema>;\nexport type Runner = z.infer<typeof RunnerSchema>;\nexport type StepExecutionRef = z.infer<typeof StepExecutionRefSchema>;\nexport type ServiceDef = z.infer<typeof ServiceDefSchema>;\nexport type PreBlock = z.infer<typeof PreBlockSchema>;\nexport type JobHookBlock = z.infer<typeof JobHookBlockSchema>;\nexport type Job = z.infer<typeof JobSchema>;\nexport type RepairTriage = z.infer<typeof RepairTriageSchema>;\nexport type AgentDecisionTrigger = z.infer<typeof AgentDecisionTriggerSchema>;\nexport type WorktreeHook = z.infer<typeof WorktreeHookSchema>;\nexport type WorktreeConfig = z.infer<typeof WorktreeConfigSchema>;\nexport type WorkflowKeybindings = z.infer<typeof WorkflowKeybindingsSchema>;\nexport type RunDirectoryEntry = z.infer<typeof RunDirectoryEntrySchema>;\nexport type RunDirectory = z.infer<typeof RunDirectorySchema>;\nexport type Workflow = z.infer<typeof WorkflowSchema>;\nexport type WorkflowStage = z.infer<typeof WorkflowStageSchema>;\nexport type WorkflowOutcome = z.infer<typeof WorkflowOutcomeSchema>;\nexport type WorkflowRepairStatus = z.infer<typeof WorkflowRepairStatusSchema>;\nexport type WorkflowResumeMode = z.infer<typeof WorkflowResumeModeSchema>;\nexport type WorkflowRepairJobStatus = z.infer<typeof WorkflowRepairJobStatusSchema>;\nexport type WorkflowRepairJobAttempt = z.infer<typeof WorkflowRepairJobAttemptSchema>;\nexport type WorkflowRepairJob = z.infer<typeof WorkflowRepairJobSchema>;\nexport type WorkflowRepairRoutingFallback = z.infer<typeof WorkflowRepairRoutingFallbackSchema>;\nexport type WorkflowProgressEvent = z.infer<typeof WorkflowProgressEventSchema>;\nexport type WorkflowRepairRecord = z.infer<typeof WorkflowRepairRecordSchema>;\nexport type WorkflowLauncherMetadata = z.infer<typeof WorkflowLauncherMetadataSchema>;\nexport type WorkflowLauncherType = WorkflowLauncherMetadata['type'];\nexport type WorkflowRunRecord = z.infer<typeof WorkflowRunRecordSchema>;\nexport type WorkflowRunHandle = z.infer<typeof WorkflowRunHandleSchema>;\n","import { BACKGROUND_CONTEXT, getOrThrow } from '@agimon-ai/po-core/platform';\n\nimport type { WorkflowRuntimeContext } from './type';\n\n/** Freeze the admitted environment too, so concurrent runs cannot mutate each other's facts. */\nexport function createWorkflowRuntime(\n input: Omit<WorkflowRuntimeContext, 'ioContext'> & Partial<Pick<WorkflowRuntimeContext, 'ioContext'>>,\n): WorkflowRuntimeContext {\n return Object.freeze({\n ...input,\n baseEnvironment: Object.freeze({ ...input.baseEnvironment }),\n ioContext: input.ioContext ?? BACKGROUND_CONTEXT,\n });\n}\n\n/** A bounded command on the admitted platform, without inheriting the server process environment. */\nexport async function workflowShellOutput(\n runtime: WorkflowRuntimeContext,\n command: string | readonly string[],\n options: { cwd?: string; environment?: Readonly<Record<string, string | undefined>>; timeoutMs?: number } = {},\n): Promise<string> {\n let output = '';\n const env = Object.fromEntries(\n Object.entries(options.environment ?? runtime.baseEnvironment).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n );\n const result = getOrThrow(\n await runtime.shell.exec(\n typeof command === 'string' ? command : [...command],\n {\n cwd: options.cwd ?? runtime.cwd,\n env,\n inheritEnv: false,\n ...(options.timeoutMs === undefined ? {} : { timeout: options.timeoutMs }),\n onOutput: (text) => {\n output += text;\n },\n },\n runtime.ioContext,\n ),\n );\n if (result.exitCode !== 0)\n throw new Error(\n `Workflow command exited with code ${result.exitCode}: ${typeof command === 'string' ? command : command.join(' ')}\\n${output}`,\n );\n return output;\n}\n","/**\n * Shell-quoting helpers for safely interpolating values into shell command strings.\n *\n * DESIGN PATTERNS:\n * - Pure functions with no side effects\n * - Context-aware escaping driven by the surrounding quote character\n *\n * AVOID:\n * - String.prototype.replace with a value as the replacement string: its replacement\n * patterns ($&, $1, $$, ...) would corrupt any value containing `$`. Build the result\n * with slice/concat or a function replacer instead.\n */\n\n/**\n * Escape a string for safe use as a single-quoted shell argument.\n *\n * Wraps the value in single quotes and neutralises embedded single quotes via the\n * quote-break-escape-requote pattern (`'\\''`).\n */\nexport function escapeShellArg(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/**\n * Escape a value for safe insertion inside a double-quoted shell string (`\"...\"`).\n *\n * Inside double quotes only `\\`, `$`, `` ` `` and `\"` retain special meaning, so each is\n * backslash-escaped in a single pass. A function replacer is used so a `$` in the value is\n * never interpreted as a replacement pattern.\n */\nexport function escapeForDoubleQuotes(value: string): string {\n return value.replace(/[\\\\$`\"]/g, (char) => `\\\\${char}`);\n}\n\n/**\n * Replace every occurrence of `placeholder` in `template` with `value`, escaping the value\n * for the shell-quoting context of the character immediately preceding the placeholder:\n *\n * - preceded by `\"` -> escape for a double-quoted slot (`\\ $ ` ` \" `)\n * - preceded by `'` -> escape embedded single quotes (the template supplies the surrounding quotes)\n * - otherwise (bare) -> wrap the value as a single safe single-quoted token\n *\n * The result is assembled with slice/concat so `value` is never treated as a\n * String.prototype.replace replacement pattern.\n */\nexport function substituteShellPlaceholder(template: string, placeholder: string, value: string): string {\n let result = '';\n let searchFrom = 0;\n for (;;) {\n const index = template.indexOf(placeholder, searchFrom);\n if (index === -1) {\n return result + template.slice(searchFrom);\n }\n result += template.slice(searchFrom, index) + escapeForPrecedingQuote(value, template[index - 1]);\n searchFrom = index + placeholder.length;\n }\n}\n\nfunction escapeForPrecedingQuote(value: string, precedingChar: string | undefined): string {\n if (precedingChar === '\"') {\n return escapeForDoubleQuotes(value);\n }\n if (precedingChar === \"'\") {\n return value.replace(/'/g, \"'\\\\''\");\n }\n return escapeShellArg(value);\n}\n","/**\n * WorkflowParserService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { resolve } from 'node:path';\n\nimport { getOrThrow, pathExists } from '@agimon-ai/po-core/platform';\nimport { load as parseYaml } from 'js-yaml';\nimport { Liquid } from 'liquidjs';\n\nimport { ChoiceSettingsSchema, WorkflowSchema } from '../../schemas/workflowEngine';\nimport type {\n Choice,\n CommandTemplate,\n Job,\n MatrixEntry,\n RunConfig,\n RunDirectory,\n Step,\n Workflow,\n} from '../../schemas/workflowEngine';\nimport type { InterpolationContext } from '../workflowEngine/type';\nimport { workflowShellOutput } from '../workflowRuntime';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport { escapeShellArg } from '../workflowShell';\n\nconst CUSTOM_RUN_KEY = 'customRun';\nconst RUN_CONFIG_KEY = 'runConfig';\nconst PROMPT_VARIABLE = 'prompt';\nconst SYSTEM_PROMPT_VARIABLE = 'systemPrompt';\nconst CHOICE_SETTING_KEYS = new Set(Object.keys(ChoiceSettingsSchema.shape));\n/** A prompt printed raw would be split and expanded by the shell, so templates must quote it. */\nconst UNQUOTED_PROMPT_PATTERN = /\\{\\{-?\\s*(prompt|systemPrompt)\\s*-?\\}\\}/;\nconst LEGACY_INTERPOLATION_MARKER = '${{';\n\n/**\n * Renders command templates. Strict, so a variable a launch does not provide\n * fails the step instead of rendering an empty flag; lenient in `if` and\n * `default`, so optional values such as the system prompt can be tested.\n */\nconst commandTemplates = new Liquid({ strictVariables: true, strictFilters: true, lenientIf: true });\ncommandTemplates.registerFilter('shell', (value: unknown) =>\n // Liquid filters deliberately accept arbitrary values with native string coercion.\n // oxlint-disable-next-line typescript/no-base-to-string\n escapeShellArg(Array.isArray(value) ? value.join(',') : String(value ?? '')),\n);\n\n/** A declared command's template and host options, whichever form it was written in. */\nexport function commandTemplateOf(command: CommandTemplate): { run: string; inProcess: boolean } {\n return typeof command === 'string'\n ? { run: command, inProcess: false }\n : { run: command.run, inProcess: command.inProcess === true };\n}\n\n/** Base step/subagent settings, with an optional command-specific override. */\nexport function choiceSettings(choice: Choice | undefined, command?: string): RunConfig {\n if (!choice) return {};\n const settings: RunConfig = {};\n for (const key of CHOICE_SETTING_KEYS) {\n const value = choice[key];\n if (typeof value === 'string') settings[key] = value;\n }\n const override = command === undefined ? undefined : choice[command];\n if (override && typeof override !== 'string') Object.assign(settings, override);\n return settings;\n}\n\nconst SKIPPED_ACTIONS = [\n 'actions/checkout',\n 'actions/setup-node',\n 'actions/cache',\n 'actions/upload-artifact',\n 'actions/download-artifact',\n 'pnpm/action-setup',\n];\n\nconst ADJECTIVES = [\n 'bold',\n 'calm',\n 'cool',\n 'dark',\n 'deep',\n 'fair',\n 'fast',\n 'free',\n 'gold',\n 'keen',\n 'kind',\n 'loud',\n 'neat',\n 'pure',\n 'rare',\n 'safe',\n 'slim',\n 'soft',\n 'tall',\n 'warm',\n 'wild',\n 'wise',\n 'blue',\n 'gray',\n 'jade',\n 'iron',\n 'zinc',\n 'ruby',\n 'opal',\n 'onyx',\n];\n\nconst NOUNS = [\n 'arch',\n 'beam',\n 'bird',\n 'bolt',\n 'cape',\n 'cove',\n 'dawn',\n 'dove',\n 'echo',\n 'fern',\n 'flux',\n 'gale',\n 'hawk',\n 'haze',\n 'iris',\n 'jade',\n 'kite',\n 'lake',\n 'lynx',\n 'mesa',\n 'moth',\n 'node',\n 'palm',\n 'peak',\n 'pine',\n 'raft',\n 'reef',\n 'sage',\n 'tide',\n 'vale',\n];\n\nexport class WorkflowParserService {\n private githubSha = 'local';\n\n constructor(readonly runtime: WorkflowRuntimeContext) {}\n\n generateHumanReadableId(): string {\n const adj = ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)];\n const noun = NOUNS[Math.floor(Math.random() * NOUNS.length)];\n return `${adj}-${noun}`;\n }\n\n async parseWorkflowFile(workflowPath: string): Promise<Workflow> {\n const resolved = resolve(this.runtime.cwd, workflowPath);\n if (!(await pathExists(this.runtime.fs, resolved, this.runtime.ioContext))) {\n throw new Error(`Workflow file not found: ${resolved}`);\n }\n\n const content = getOrThrow(await this.runtime.fs.readTextFile(resolved, this.runtime.ioContext));\n if (content.includes('github.sha')) {\n try {\n this.githubSha = (await workflowShellOutput(this.runtime, 'git rev-parse HEAD')).trim();\n } catch {\n this.githubSha = 'local';\n }\n }\n const workflow = WorkflowSchema.parse(parseYaml(content)) as Workflow;\n\n if (workflow.imports) {\n await this.resolveImports(workflow, resolved);\n }\n\n if (!workflow.jobs || Object.keys(workflow.jobs).length === 0) {\n throw new Error('No jobs found in workflow file');\n }\n\n this.resolveExtends(workflow);\n\n const parsed = WorkflowSchema.parse(this.applyRunConfigDefaults(workflow)) as Workflow;\n this.validateCommandTemplates(parsed);\n return parsed;\n }\n\n /**\n * Render a command template into the shell command a step runs.\n *\n * Values enter as data and are never rendered again, so `${{ }}` text a\n * prompt already went through, or Liquid syntax a prompt quotes, stays as it\n * is. Use the `shell` filter to quote a value as one shell word.\n */\n renderCommandTemplate(template: string, values: Record<string, unknown>): string {\n return commandTemplates.parseAndRenderSync(template, values).trim();\n }\n\n /** The top-level values a command template reads. */\n templateVariables(template: string): string[] {\n return commandTemplates.globalVariablesSync(template);\n }\n\n /** Whether a template passes the system prompt itself; when not, it is folded into the prompt. */\n templateUsesSystemPrompt(template: string): boolean {\n return commandTemplates.globalVariablesSync(template).includes(SYSTEM_PROMPT_VARIABLE);\n }\n\n /**\n * Check what the schema cannot see once imports and templates are merged:\n * that steps name declared commands and choices, that `parallel` and\n * `restart-from` sit in jobs, and that every command template parses and\n * quotes its prompts.\n */\n validateCommandTemplates(workflow: Workflow): void {\n const problems: string[] = [];\n const commands = workflow.commands ?? {};\n const choices = workflow.choices ?? {};\n const jobNames = new Set(Object.keys(workflow.jobs));\n\n for (const [name, command] of Object.entries(commands)) {\n const { run } = commandTemplateOf(command);\n if (run.includes(LEGACY_INTERPOLATION_MARKER)) {\n problems.push(`Command \"${name}\" uses \\${{ }}; command templates are Liquid, use {{ }} instead.`);\n }\n if (UNQUOTED_PROMPT_PATTERN.test(run)) {\n problems.push(`Command \"${name}\" prints a prompt unquoted; write {{ prompt | shell }}.`);\n }\n try {\n if (!commandTemplates.globalVariablesSync(run).includes(PROMPT_VARIABLE)) {\n problems.push(`Command \"${name}\" never passes {{ prompt | shell }} to the agent.`);\n }\n } catch (error) {\n problems.push(`Command \"${name}\" is not a valid Liquid template: ${(error as Error).message}`);\n }\n }\n for (const [name, choice] of Object.entries(choices)) {\n for (const key of Object.keys(choice)) {\n if (!CHOICE_SETTING_KEYS.has(key) && !(key in commands)) {\n problems.push(`Choice \"${name}\" overrides \"${key}\", which is not a declared command.`);\n }\n }\n }\n\n const checkStep = (step: Step, where: string, inJob: boolean): void => {\n if (Array.isArray(step.interactiveRun)) {\n for (const entry of step.interactiveRun) {\n if (!(entry.command in commands)) {\n problems.push(`${where} runs command \"${entry.command}\", which is not declared under commands.`);\n }\n if (entry.choice !== undefined && !(entry.choice in choices)) {\n problems.push(`${where} names choice \"${entry.choice}\", which is not declared under choices.`);\n }\n }\n }\n if (step.choice !== undefined && !(step.choice in choices)) {\n problems.push(`${where} names choice \"${step.choice}\", which is not declared under choices.`);\n }\n const restartFrom = step['restart-from'];\n if (restartFrom !== undefined) {\n if (!inJob) problems.push(`${where} sets restart-from, which only jobs support.`);\n else if (!jobNames.has(restartFrom)) {\n problems.push(`${where} restarts from \"${restartFrom}\", which is not a job.`);\n }\n }\n if (step.parallel) {\n if (!inJob) problems.push(`${where} is a parallel group, which only jobs support.`);\n const names = step.parallel.map((child) => child.name).filter((name) => name !== undefined);\n if (new Set(names).size !== names.length) problems.push(`${where} has parallel steps with the same name.`);\n for (const [index, child] of step.parallel.entries()) {\n checkStep(child, `${where} parallel ${child.name ?? index + 1}`, inJob);\n }\n }\n };\n const checkSteps = (steps: Step[] | undefined, where: string, inJob: boolean): void => {\n for (const [index, step] of (steps ?? []).entries()) {\n checkStep(step, `${where} step ${step.name ?? index + 1}`, inJob);\n }\n };\n const checkJob = (job: Job, where: string): void => {\n checkSteps(job.steps, where, true);\n checkSteps(job.preJob?.steps, `${where} preJob`, true);\n checkSteps(job.postJob?.steps, `${where} postJob`, true);\n };\n\n for (const [name, job] of Object.entries(workflow.jobs)) checkJob(job, `Job \"${name}\"`);\n if (workflow.repair) checkJob(workflow.repair as Job, 'Repair');\n checkSteps(workflow.pre?.steps, 'pre', false);\n checkSteps(workflow.post?.steps, 'post', false);\n checkSteps(workflow.on?.agent_decision?.steps, 'agent_decision', false);\n for (const [hook, block] of Object.entries(workflow.worktree ?? {})) {\n checkSteps(block?.steps, `worktree ${hook}`, false);\n }\n\n if (problems.length > 0) {\n throw new Error(`Invalid workflow:\\n - ${problems.join('\\n - ')}`);\n }\n }\n\n /**\n * Lay the workflow's `runConfig` under the one of every agent step, a step\n * with an `interactiveRun` or `customRun`, wherever it sits. A key the step\n * sets itself wins, so a step runs on the workflow default unless it says\n * otherwise.\n */\n private applyRunConfigDefaults(workflow: Workflow): Workflow {\n const defaults = workflow.runConfig;\n if (defaults === undefined) return workflow;\n const visit = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(visit);\n if (!value || typeof value !== 'object') return value;\n const copy: Record<string, unknown> = Object.fromEntries(\n Object.entries(value).map(([key, nested]) => [key, visit(nested)]),\n );\n if (copy[CUSTOM_RUN_KEY] !== undefined || copy.interactiveRun !== undefined) {\n copy[RUN_CONFIG_KEY] = { ...defaults, ...(copy[RUN_CONFIG_KEY] as RunConfig | undefined) };\n }\n return copy;\n };\n const { runConfig, ...rest } = workflow;\n return { ...(visit(rest) as Workflow), runConfig };\n }\n\n /**\n * The workflow as it runs on `runner`.\n *\n * A runner declared under `runners` lays its `runConfig` over the one of\n * every step that has a `customRun`, wherever the step sits: jobs, hooks,\n * triage and worktree steps alike. Any other runner, including a command\n * map's key, leaves the workflow as parsed.\n */\n selectRunner(workflow: Workflow, runner: string | undefined): Workflow {\n const overlay = runner === undefined ? undefined : workflow.runners?.[runner]?.runConfig;\n if (overlay === undefined) return workflow;\n const visit = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(visit);\n if (!value || typeof value !== 'object') return value;\n const copy: Record<string, unknown> = Object.fromEntries(\n Object.entries(value).map(([key, nested]) => [key, visit(nested)]),\n );\n if (copy[CUSTOM_RUN_KEY] !== undefined) {\n copy[RUN_CONFIG_KEY] = { ...(copy[RUN_CONFIG_KEY] as RunConfig | undefined), ...overlay };\n }\n return copy;\n };\n const { runners, ...rest } = workflow;\n return { ...(visit(rest) as Workflow), runners };\n }\n\n /**\n * Resolve `imports` references in a workflow.\n * Import paths are resolved relative to the importing workflow file.\n * Imported files provide base sections that the main workflow can override:\n * - env: merged (main overrides imported)\n * - pre.steps: imported steps prepended before main steps\n * - pre.services: imported services prepended before main services\n * - post.steps: imported steps prepended before main steps\n * - post.services: imported services prepended before main services\n * - worktree: imported hooks used as defaults, main overrides per-hook\n * - jobs: imported template jobs (dot-prefixed) merged in, main overrides\n * - system-prompt: concatenated (imported + main)\n * - commands, choices: merged per name (main overrides imported)\n * - runConfig: merged per key (main overrides imported)\n * Imports are processed in order; later imports override earlier ones.\n * Circular imports are detected and throw an error.\n */\n async resolveImports(workflow: Workflow, workflowPath: string, visited = new Set<string>()): Promise<void> {\n const normalizedPath = resolve(workflowPath);\n if (visited.has(normalizedPath)) {\n throw new Error(`Circular import detected: ${normalizedPath}`);\n }\n visited.add(normalizedPath);\n\n const baseDir = normalizedPath.replace(/\\/[^/]+$/, '');\n\n for (const importPath of workflow.imports ?? []) {\n const resolvedImport = resolve(baseDir, importPath);\n if (!(await pathExists(this.runtime.fs, resolvedImport, this.runtime.ioContext))) {\n throw new Error(`Imported workflow file not found: ${resolvedImport} (from ${normalizedPath})`);\n }\n\n const importContent = getOrThrow(await this.runtime.fs.readTextFile(resolvedImport, this.runtime.ioContext));\n const imported = parseYaml(importContent) as Workflow;\n\n // Recursively resolve nested imports\n if (imported.imports) {\n await this.resolveImports(imported, resolvedImport, visited);\n }\n\n // Merge env (main overrides imported)\n if (imported.env) {\n workflow.env = { ...imported.env, ...workflow.env };\n }\n\n // Merge pre block\n if (imported.pre) {\n if (!workflow.pre) {\n workflow.pre = {};\n }\n if (imported.pre.services) {\n workflow.pre.services = [...imported.pre.services, ...(workflow.pre.services ?? [])];\n }\n if (imported.pre.steps) {\n workflow.pre.steps = [...imported.pre.steps, ...(workflow.pre.steps ?? [])];\n }\n }\n\n // Merge post block\n if (imported.post) {\n if (!workflow.post) {\n workflow.post = {};\n }\n if (imported.post.services) {\n workflow.post.services = [...imported.post.services, ...(workflow.post.services ?? [])];\n }\n if (imported.post.steps) {\n workflow.post.steps = [...imported.post.steps, ...(workflow.post.steps ?? [])];\n }\n }\n\n // Merge worktree (main overrides per-hook)\n if (imported.worktree) {\n if (!workflow.worktree) {\n workflow.worktree = {};\n }\n const hooks = ['beforeCreate', 'afterCreate', 'beforeCompleted', 'afterCompleted'] as const;\n for (const hook of hooks) {\n if (imported.worktree[hook] && !workflow.worktree[hook]) {\n workflow.worktree[hook] = imported.worktree[hook];\n }\n }\n }\n\n // Merge max-workflows (main overrides imported)\n if (imported['max-workflows'] && !workflow['max-workflows']) {\n workflow['max-workflows'] = imported['max-workflows'];\n }\n\n // Merge launch-command and launcher (main overrides imported)\n if (imported['launch-command'] && !workflow['launch-command']) {\n workflow['launch-command'] = imported['launch-command'];\n }\n if (imported.launcher && !workflow.launcher) {\n workflow.launcher = imported.launcher;\n }\n\n // Merge keybindings (main overrides imported per action)\n if (imported.keybindings) {\n workflow.keybindings = { ...imported.keybindings, ...workflow.keybindings };\n }\n\n // Merge commands and choices (main overrides imported per name, whole entries)\n if (imported.commands) {\n workflow.commands = { ...imported.commands, ...workflow.commands };\n }\n if (imported.choices) {\n workflow.choices = { ...imported.choices, ...workflow.choices };\n }\n if (imported.runConfig) {\n workflow.runConfig = { ...imported.runConfig, ...workflow.runConfig };\n }\n\n if (imported['run-directory']) {\n workflow['run-directory'] = this.mergeRunDirectories(imported['run-directory'], workflow['run-directory']);\n }\n\n // Merge repair triage (main overrides imported)\n if (imported.repair && !workflow.repair) {\n workflow.repair = imported.repair;\n }\n\n // Merge system-prompt (concatenate)\n if (imported['system-prompt']) {\n if (workflow['system-prompt']) {\n workflow['system-prompt'] = `${imported['system-prompt']}\\n\\n${workflow['system-prompt']}`;\n } else {\n workflow['system-prompt'] = imported['system-prompt'];\n }\n }\n\n // Merge jobs (imported jobs used as base, main overrides)\n if (imported.jobs) {\n for (const [name, job] of Object.entries(imported.jobs)) {\n if (!(name in (workflow.jobs ?? {}))) {\n if (!workflow.jobs) {\n workflow.jobs = {};\n }\n workflow.jobs[name] = job;\n }\n }\n }\n }\n\n // Clean up imports field after resolution\n delete workflow.imports;\n }\n\n private mergeRunDirectories(base: RunDirectory, override?: RunDirectory): RunDirectory {\n if (!override) return base;\n const entries = new Map(base.entries.map((entry) => [entry.path, entry]));\n for (const entry of override.entries) entries.set(entry.path, entry);\n return {\n description: override.description,\n entries: [...entries.values()],\n };\n }\n\n /**\n * Resolve `extends` references in jobs.\n * Dot-prefixed jobs (e.g. `.ios-prebuild`) are shared templates.\n * When a job has `extends: .template-name`, it merges:\n * - steps: template steps prepended before job steps\n * - preJob.steps: template steps prepended before job preJob steps\n * - postJob.steps: template steps prepended before job postJob steps\n * - env: merged (job overrides template)\n * - system-prompt: concatenated (template + job)\n * - all other fields: job overrides template\n * Template jobs are removed from the jobs map after resolution.\n */\n resolveExtends(workflow: Workflow): void {\n const { jobs } = workflow;\n\n // Separate templates (dot-prefixed) from real jobs\n const templates = new Map<string, Job>();\n for (const [name, job] of Object.entries(jobs)) {\n if (name.startsWith('.')) {\n templates.set(name, job);\n }\n }\n\n // Resolve extends for each real job\n for (const [name, job] of Object.entries(jobs)) {\n if (name.startsWith('.')) continue;\n if (!job.extends) continue;\n\n const templateNames = Array.isArray(job.extends) ? job.extends : [job.extends];\n const jobOwnSteps = [...(job.steps ?? [])];\n const jobOwnPreSteps = [...(job.preJob?.steps ?? [])];\n const jobOwnPostSteps = [...(job.postJob?.steps ?? [])];\n const prependedSteps: import('../../schemas/workflowEngine').Step[] = [];\n const prependedPreJobSteps: import('../../schemas/workflowEngine').Step[] = [];\n const prependedPostJobSteps: import('../../schemas/workflowEngine').Step[] = [];\n\n for (const templateName of templateNames) {\n const template = templates.get(templateName);\n if (!template) {\n throw new Error(`Job \"${name}\" extends \"${templateName}\" but template not found`);\n }\n\n prependedSteps.push(...(template.steps ?? []));\n prependedPreJobSteps.push(...(template.preJob?.steps ?? []));\n prependedPostJobSteps.push(...(template.postJob?.steps ?? []));\n this.applyTemplate(job, template);\n }\n\n // Reconstruct steps: all template steps in order, then job's own steps\n job.steps = [...prependedSteps, ...jobOwnSteps];\n this.assignJobHookSteps(job, 'preJob', [...prependedPreJobSteps, ...jobOwnPreSteps]);\n this.assignJobHookSteps(job, 'postJob', [...prependedPostJobSteps, ...jobOwnPostSteps]);\n\n delete job.extends;\n }\n\n // Remove template jobs from the map\n for (const name of templates.keys()) {\n delete jobs[name];\n }\n }\n\n /**\n * Merge a single template into a job.\n * Called once per template when a job extends multiple templates.\n */\n private applyTemplate(job: Job, template: Job): void {\n // Steps: template steps prepended before job steps\n const templateSteps = template.steps ?? [];\n job.steps = [...templateSteps, ...(job.steps ?? [])];\n this.mergeJobHookSteps(job, template, 'preJob');\n this.mergeJobHookSteps(job, template, 'postJob');\n\n // Env: merge (job overrides template)\n if (template.env || job.env) {\n job.env = { ...template.env, ...job.env };\n }\n\n // System prompt: concatenate\n if (template['system-prompt'] && job['system-prompt']) {\n job['system-prompt'] = `${template['system-prompt']}\\n\\n${job['system-prompt']}`;\n } else if (template['system-prompt']) {\n job['system-prompt'] = template['system-prompt'];\n }\n\n // Scalar fields: inherit from template if not set on job\n if (template['runs-on'] && !job['runs-on']) job['runs-on'] = template['runs-on'];\n if (template.strategy && !job.strategy) job.strategy = template.strategy;\n if (template.context && !job.context) job.context = template.context;\n }\n\n private mergeJobHookSteps(job: Job, template: Job, hookKey: 'preJob' | 'postJob'): void {\n const templateSteps = template[hookKey]?.steps ?? [];\n const jobSteps = job[hookKey]?.steps ?? [];\n this.assignJobHookSteps(job, hookKey, [...templateSteps, ...jobSteps]);\n }\n\n private assignJobHookSteps(job: Job, hookKey: 'preJob' | 'postJob', steps: Job['steps']): void {\n if (steps.length > 0) {\n job[hookKey] = { steps };\n return;\n }\n\n delete job[hookKey];\n }\n\n async loadSecrets(secretFile: string): Promise<Map<string, string>> {\n const secrets = new Map<string, string>();\n if (!(await pathExists(this.runtime.fs, secretFile, this.runtime.ioContext))) {\n return secrets;\n }\n\n const content = getOrThrow(await this.runtime.fs.readTextFile(secretFile, this.runtime.ioContext));\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n const eqIdx = trimmed.indexOf('=');\n if (eqIdx === -1) continue;\n secrets.set(trimmed.slice(0, eqIdx), trimmed.slice(eqIdx + 1));\n }\n\n return secrets;\n }\n\n interpolate(template: string, context: InterpolationContext): string {\n return template.replace(/\\$\\{\\{\\s*(.+?)\\s*\\}\\}/g, (_match, expr: string) => {\n const parts = expr.trim().split('.');\n\n if (parts[0] === 'inputs' && parts[1]) {\n return context.inputs.get(parts[1]) || '';\n }\n if (parts[0] === 'matrix' && parts[1]) {\n return context.matrix[parts[1]] || '';\n }\n if (parts[0] === 'secrets' && parts[1]) {\n return context.secrets.get(parts[1]) || this.runtime.baseEnvironment[parts[1]] || '';\n }\n if (parts[0] === 'env' && parts[1]) {\n return context.env[parts[1]] || this.runtime.baseEnvironment[parts[1]] || '';\n }\n if (parts[0] === 'runConfig' && parts[1]) {\n const value = context.runConfig?.[parts[1]];\n return Array.isArray(value) ? value.join(',') : (value ?? '');\n }\n if (parts[0] === 'runner' && parts[1] === 'os') return 'macOS';\n if (parts[0] === 'github' && parts[1] === 'sha') {\n return this.githubSha;\n }\n\n if (expr.includes('hashFiles')) return 'local';\n\n return `\\${{ ${expr} }}`;\n });\n }\n\n isActionSkipped(uses: string): boolean {\n return SKIPPED_ACTIONS.some((prefix) => uses.startsWith(prefix));\n }\n\n resolveJobOrder(jobs: Record<string, Job>, targetJob: string | null): string[] {\n const visited = new Set<string>();\n const order: string[] = [];\n\n const visit = (jobName: string) => {\n if (visited.has(jobName)) return;\n visited.add(jobName);\n\n const job = jobs[jobName];\n if (!job) {\n throw new Error(`Job not found: ${jobName}`);\n }\n\n const deps = job.needs ? (Array.isArray(job.needs) ? job.needs : [job.needs]) : [];\n for (const dep of deps) {\n visit(dep);\n }\n\n order.push(jobName);\n };\n\n if (targetJob) {\n visit(targetJob);\n } else {\n for (const jobName of Object.keys(jobs)) {\n visit(jobName);\n }\n }\n\n return order;\n }\n\n expandMatrix(job: Job): MatrixEntry[] {\n if (!job.strategy?.matrix) return [{}];\n\n const { include, ...rest } = job.strategy.matrix;\n\n if (include && include.length > 0) {\n return include;\n }\n\n const keys = Object.keys(rest).filter((k) => Array.isArray(rest[k]));\n if (keys.length === 0) return [{}];\n\n let combos: MatrixEntry[] = [{}];\n for (const key of keys) {\n const values = rest[key] as string[];\n const newCombos: MatrixEntry[] = [];\n for (const combo of combos) {\n for (const val of values) {\n newCombos.push({ ...combo, [key]: String(val) });\n }\n }\n combos = newCombos;\n }\n\n return combos;\n }\n}\n","import { resolve } from 'node:path';\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\n\nimport type { CommandRef, Step, Workflow } from '../../schemas/workflowEngine';\nimport { compatibleRunners } from '../WorkflowCatalogService';\nimport { findWorkflowPaths } from '../workflowDiscovery';\nimport { commandTemplateOf, WorkflowParserService } from '../WorkflowParserService';\nimport type { WorkflowDiagnostic, WorkflowDoctorOptions, WorkflowDoctorReport } from './types';\n\nconst INVALID_WORKFLOW_PREFIX = 'Invalid workflow:';\nconst PROBLEM_SEPARATOR = /\\n\\s*- /;\nconst INPUT_REFERENCE = /\\$\\{\\{\\s*inputs\\.([A-Za-z0-9_-]+)\\s*\\}\\}/g;\nconst WORKFLOW_DISPATCH_TRIGGER = 'workflow_dispatch';\nconst STEP_SEPARATOR = ' › ';\n\n/** One step and where it sits, as a reader finds it in the file. */\ninterface LocatedStep {\n step: Step;\n location: string;\n}\n\nfunction stepLabel(step: Step, index: number): string {\n return step.name ?? step.id ?? `step ${String(index + 1)}`;\n}\n\n/** Every step a workflow can run, parallel ones included, each with where it is. */\nfunction collectSteps(workflow: Workflow): LocatedStep[] {\n const located: LocatedStep[] = [];\n const walk = (steps: readonly Step[] | undefined, where: string): void => {\n for (const [index, step] of (steps ?? []).entries()) {\n const location = `${where}${STEP_SEPARATOR}${stepLabel(step, index)}`;\n if (step.parallel) {\n walk(step.parallel as Step[], location);\n continue;\n }\n located.push({ step, location });\n }\n };\n walk(workflow.pre?.steps, 'pre');\n walk(workflow.post?.steps, 'post');\n walk(workflow.repair?.steps, 'repair');\n walk(workflow.worktree?.beforeCreate?.steps, 'worktree.beforeCreate');\n walk(workflow.worktree?.afterCreate?.steps, 'worktree.afterCreate');\n for (const [name, job] of Object.entries(workflow.jobs)) {\n walk(job.preJob?.steps, `jobs.${name}.preJob`);\n walk(job.steps, `jobs.${name}`);\n walk(job.postJob?.steps, `jobs.${name}.postJob`);\n }\n return located;\n}\n\nfunction referencesIn(value: unknown, pattern: RegExp): Set<string> {\n const found = new Set<string>();\n for (const match of JSON.stringify(value ?? null).matchAll(pattern)) {\n if (match[1] !== undefined) found.add(match[1]);\n }\n return found;\n}\n\n/** The customRun entries of a step: one entry any runner runs, or one per runner. */\nfunction customRunEntries(customRun: Step['customRun']): { runner?: string; runConfig?: Record<string, unknown> }[] {\n if (!customRun) return [];\n if (typeof (customRun as { prompt?: unknown }).prompt === 'string') {\n const entry = customRun as { runConfig?: Record<string, unknown> };\n return [entry.runConfig === undefined ? {} : { runConfig: entry.runConfig }];\n }\n return Object.entries(customRun as Record<string, { runConfig?: Record<string, unknown> }>).map(\n ([runner, entry]) => ({ runner, ...(entry.runConfig === undefined ? {} : { runConfig: entry.runConfig }) }),\n );\n}\n\n/** The problems the parser reports together, one diagnostic each. */\nfunction parseProblems(message: string): string[] {\n if (!message.startsWith(INVALID_WORKFLOW_PREFIX)) return [message];\n return message\n .slice(INVALID_WORKFLOW_PREFIX.length)\n .split(PROBLEM_SEPARATOR)\n .map((problem) => problem.trim())\n .filter((problem) => problem.length > 0);\n}\n\n/**\n * Check one workflow before anything runs it.\n *\n * Everything the parser refuses comes back as errors, one per problem. On top\n * of that, what only shows up once a step runs:\n * - runConfig keys nothing reads. A key a host does not know, such as a\n * misspelled `majormode`, would otherwise run the step on defaults or fail it\n * mid-run. Which keys are known depends on the host, so they are errors only\n * when `runConfigKeys` names the host's own; without them, keys a templated\n * step's command does not read are warnings.\n * - A job needing one that does not exist.\n * - Runner maps no runner satisfies, customRun steps no terminal can run, and\n * `${{ inputs.X }}` for inputs the workflow does not declare.\n */\nexport async function diagnoseWorkflow(\n workflowPath: string,\n options: WorkflowDoctorOptions,\n): Promise<WorkflowDoctorReport> {\n const path = resolve(workflowPath);\n const parser = options.parser ?? new WorkflowParserService(options.runtime);\n let workflow: Workflow;\n try {\n workflow = await parser.parseWorkflowFile(path);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n path,\n diagnostics: parseProblems(message).map((problem) => ({\n level: 'error',\n code: 'invalid-workflow',\n message: problem,\n })),\n };\n }\n\n const diagnostics: WorkflowDiagnostic[] = [];\n const hostKeys = options.runConfigKeys === undefined ? undefined : new Set(options.runConfigKeys);\n const reads = (command: string): Set<string> | undefined => {\n const declared = workflow.commands?.[command];\n return declared === undefined ? undefined : new Set(parser.templateVariables(commandTemplateOf(declared).run));\n };\n const unknownKeys = (keys: Iterable<string>, known: ReadonlySet<string>): string[] =>\n [...new Set(keys)].filter((key) => !known.has(key));\n\n for (const { step, location } of collectSteps(workflow)) {\n const stepKeys = Object.keys(step.runConfig ?? {});\n // A templated step runs through one of the commands it offers, whose\n // templates read runConfig values; a host running it in-process also reads\n // its own keys. The step's runConfig is shared by every command it offers,\n // while a command's own runConfig is that command's alone.\n if (Array.isArray(step.interactiveRun)) {\n const refs = step.interactiveRun as CommandRef[];\n const offeredReads = refs.map((ref) => reads(ref.command) ?? new Set<string>());\n const report = (key: string, commands: string): void => {\n diagnostics.push({\n level: hostKeys === undefined ? 'warning' : 'error',\n code: 'unknown-run-config-key',\n location,\n message:\n hostKeys === undefined\n ? `runConfig key \"${key}\" is not read by ${commands}; a host may still read it (pass the host's keys to check).`\n : `runConfig key \"${key}\" is neither a host setting nor read by ${commands}.`,\n });\n };\n const anyCommand = new Set([...offeredReads.flatMap((keys) => [...keys]), ...(hostKeys ?? [])]);\n const offeredNames = refs.map((ref) => `\"${ref.command}\"`).join(' or ');\n for (const key of unknownKeys(stepKeys, anyCommand)) report(key, `the ${offeredNames} command`);\n for (const [index, ref] of refs.entries()) {\n const own = new Set([...(offeredReads[index] ?? []), ...(hostKeys ?? [])]);\n for (const key of unknownKeys(Object.keys(ref.runConfig ?? {}), own))\n report(key, `the \"${ref.command}\" command`);\n }\n } else if (step.customRun && hostKeys !== undefined) {\n // A customRun step is the host's alone to run, so its keys are the host's.\n for (const entry of [{ runConfig: step.runConfig }, ...customRunEntries(step.customRun)]) {\n for (const key of unknownKeys(Object.keys(entry.runConfig ?? {}), hostKeys)) {\n diagnostics.push({\n level: 'error',\n code: 'unknown-run-config-key',\n location:\n 'runner' in entry && entry.runner ? `${location}${STEP_SEPARATOR}customRun.${entry.runner}` : location,\n message: `runConfig key \"${key}\" is not a host setting.`,\n });\n }\n }\n }\n if (step.customRun && step.run === undefined && step.interactiveRun === undefined) {\n diagnostics.push({\n level: 'warning',\n code: 'custom-run-only',\n location,\n message:\n 'customRun has no run or interactiveRun fallback, so only a host that runs steps itself can run it; the CLI fails it.',\n });\n }\n }\n\n if (hostKeys !== undefined) {\n for (const [runner, definition] of Object.entries(workflow.runners ?? {})) {\n for (const key of unknownKeys(Object.keys(definition.runConfig ?? {}), hostKeys)) {\n diagnostics.push({\n level: 'error',\n code: 'unknown-run-config-key',\n location: `runners.${runner}`,\n message: `runConfig key \"${key}\" is not a host setting.`,\n });\n }\n }\n }\n\n const jobs = new Set(Object.keys(workflow.jobs));\n for (const [name, job] of Object.entries(workflow.jobs)) {\n const needs = job.needs === undefined ? [] : Array.isArray(job.needs) ? job.needs : [job.needs];\n for (const needed of needs.filter((candidate) => !jobs.has(candidate))) {\n diagnostics.push({\n level: 'error',\n code: 'unknown-job',\n location: `jobs.${name}`,\n message: `needs \"${needed}\", which is not a job.`,\n });\n }\n }\n\n const runners = compatibleRunners(workflow);\n if (runners !== undefined && runners.length === 0) {\n diagnostics.push({\n level: 'warning',\n code: 'no-common-runner',\n message: 'No runner is offered by every step, so any launch that names a runner fails at a step that lacks it.',\n });\n }\n\n const dispatch = (workflow.on as Record<string, { inputs?: Record<string, unknown> } | null> | undefined)?.[\n WORKFLOW_DISPATCH_TRIGGER\n ];\n const declaredInputs = new Set(Object.keys(dispatch?.inputs ?? {}));\n const { on: _triggers, ...rest } = workflow;\n for (const input of referencesIn(rest, INPUT_REFERENCE)) {\n if (declaredInputs.has(input)) continue;\n diagnostics.push({\n level: 'warning',\n code: 'undeclared-input',\n message: `\\${{ inputs.${input} }} names an input workflow_dispatch does not declare, so it is empty unless a launch passes it.`,\n });\n }\n\n return { path, diagnostics };\n}\n\n/**\n * Check every workflow a path names: a workflow file, or each workflow file\n * under a directory. A file that does not even parse is one report, not the\n * end of the listing.\n */\nexport async function diagnoseWorkflows(\n paths: readonly string[],\n options: WorkflowDoctorOptions,\n): Promise<WorkflowDoctorReport[]> {\n const parser = options.parser ?? new WorkflowParserService(options.runtime);\n const reports: WorkflowDoctorReport[] = [];\n for (const target of paths) {\n const resolved = resolve(target);\n let directory = false;\n try {\n directory =\n getOrThrow(await options.runtime.fs.fileInfo(resolved, options.runtime.ioContext)).kind === 'directory';\n } catch {\n // A path that does not exist is a workflow file the parser reports as missing.\n }\n if (!directory) {\n reports.push(await diagnoseWorkflow(resolved, { ...options, parser }));\n continue;\n }\n for (const relativePath of (await findWorkflowPaths(options.runtime, resolved)).sort()) {\n reports.push(await diagnoseWorkflow(resolve(resolved, relativePath), { ...options, parser }));\n }\n }\n return reports;\n}\n","export class RmuxCommandError extends Error {\n run;\n constructor(run) {\n super(commandFailureMessage(run));\n this.name = \"RmuxCommandError\";\n this.run = run;\n }\n}\nexport class RmuxCompatibilityError extends Error {\n constructor(message) {\n super(message);\n this.name = \"RmuxCompatibilityError\";\n }\n}\nfunction commandFailureMessage(run) {\n const command = commandName(run.args);\n const outcome = run.signal === undefined\n ? `status ${run.returnCode}`\n : `signal ${run.signal}`;\n const stderr = run.stderr.trim();\n const suffix = stderr.length > 0 ? `: ${stderr}` : \"\";\n return `rmux command ${JSON.stringify(command)} failed with ${outcome}${suffix}`;\n}\nfunction commandName(args) {\n for (let index = 1; index < args.length; index += 1) {\n const arg = args[index];\n if (arg === \"-S\" || arg === \"-L\") {\n index += 1;\n continue;\n }\n if (arg !== undefined) {\n return arg;\n }\n }\n return args[0] ?? \"rmux\";\n}\n","import { RmuxCommandError } from \"./errors.js\";\nexport class CommandRun {\n args;\n returnCode;\n signal;\n stdout;\n stderr;\n constructor(args, returnCode, stdout, stderr, signal) {\n this.args = [...args];\n this.returnCode = returnCode;\n if (signal !== undefined) {\n this.signal = signal;\n }\n this.stdout = stdout;\n this.stderr = stderr;\n }\n get returncode() {\n return this.returnCode;\n }\n checkReturnCode() {\n if (this.returnCode !== 0) {\n throw new RmuxCommandError(this);\n }\n return this;\n }\n}\n","import { performance } from \"node:perf_hooks\";\nexport function durationMilliseconds(value) {\n const milliseconds = typeof value === \"number\"\n ? value * 1000\n : (value.milliseconds ?? 0) + (value.seconds ?? 0) * 1000;\n if (!Number.isFinite(milliseconds) || milliseconds < 0) {\n throw new RangeError(\"duration must be a non-negative finite value\");\n }\n return milliseconds;\n}\nexport function sleep(milliseconds) {\n return new Promise((resolve) => {\n setTimeout(resolve, milliseconds);\n });\n}\nexport function deadlineFromNow(timeout) {\n return performance.now() + durationMilliseconds(timeout);\n}\nexport function deadlineExpired(deadline) {\n return performance.now() >= deadline;\n}\nexport function remainingMilliseconds(deadline) {\n return Math.max(0, deadline - performance.now());\n}\n","import { spawn } from \"node:child_process\";\nimport { constants } from \"node:os\";\nexport function mergedEnv(env) {\n if (env === undefined) {\n return undefined;\n }\n return { ...process.env, ...env };\n}\nexport function runProcess(argv, options) {\n const command = argv[0];\n if (command === undefined) {\n return Promise.reject(new Error(\"argv must not be empty\"));\n }\n return new Promise((resolve, reject) => {\n const args = argv.slice(1);\n const child = spawn(command, args, {\n cwd: options.cwd,\n env: mergedEnv(options.env),\n stdio: \"pipe\",\n });\n child.stdin.end();\n let stdout = \"\";\n let stderr = \"\";\n child.stdout.setEncoding(\"utf8\");\n child.stderr.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk) => {\n stdout += chunk;\n });\n child.stderr.on(\"data\", (chunk) => {\n stderr += chunk;\n });\n child.on(\"error\", reject);\n child.on(\"close\", (code, signal) => {\n resolve({\n code: processReturnCode(code, signal),\n signal: signal ?? undefined,\n stdout,\n stderr,\n });\n });\n });\n}\nfunction processReturnCode(code, signal) {\n if (code !== null) {\n return code;\n }\n if (signal !== null) {\n const signalNumber = constants.signals[signal];\n if (typeof signalNumber === \"number\") {\n return -signalNumber;\n }\n }\n return 1;\n}\n","import { spawn } from \"node:child_process\";\nimport { deadlineFromNow, remainingMilliseconds, } from \"./duration.js\";\nimport { mergedEnv } from \"./process.js\";\nexport class ControlOutput {\n paneId;\n data;\n constructor(paneId, data) {\n this.paneId = paneId;\n this.data = data;\n }\n get pane_id() {\n return this.paneId;\n }\n}\nexport class ControlExtendedOutput {\n paneId;\n ageMs;\n data;\n constructor(paneId, ageMs, data) {\n this.paneId = paneId;\n this.ageMs = ageMs;\n this.data = data;\n }\n get pane_id() {\n return this.paneId;\n }\n get age_ms() {\n return this.ageMs;\n }\n}\nexport class ControlExit {\n reason;\n constructor(reason) {\n if (reason !== undefined) {\n this.reason = reason;\n }\n }\n}\nexport class ControlNotification {\n prefix;\n line;\n constructor(prefix, line) {\n this.prefix = prefix;\n this.line = line;\n }\n}\nexport class ControlMalformed {\n prefix;\n line;\n reason;\n constructor(prefix, line, reason) {\n this.prefix = prefix;\n this.line = line;\n this.reason = reason;\n }\n}\nexport class ControlModeStreamEndedError extends Error {\n constructor(message) {\n super(message);\n this.name = \"ControlModeStreamEndedError\";\n }\n}\nexport function spawnControlProcess(options) {\n const child = spawn(options.binary, options.args, {\n cwd: options.cwd,\n env: mergedEnv(options.env),\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n return child;\n}\nexport function waitForControlProcessSpawn(process) {\n return new Promise((resolve, reject) => {\n const cleanup = () => {\n process.off(\"error\", onError);\n process.off(\"spawn\", onSpawn);\n };\n const onError = (error) => {\n cleanup();\n reject(error);\n };\n const onSpawn = () => {\n cleanup();\n resolve();\n };\n process.once(\"error\", onError);\n process.once(\"spawn\", onSpawn);\n });\n}\nexport class ControlModeClient {\n process;\n #lines = new AsyncQueue();\n #deferredEvents = [];\n #buffer = \"\";\n #stderr = \"\";\n #closed = false;\n #ended = false;\n #processError;\n #activeReader;\n constructor(process) {\n this.process = process;\n this.process.stdout.setEncoding(\"utf8\");\n this.process.stderr.setEncoding(\"utf8\");\n this.process.stdout.on(\"data\", (chunk) => {\n this.feedStdout(chunk);\n });\n this.process.stdout.on(\"end\", () => {\n if (this.#buffer.length > 0) {\n this.#lines.push({ kind: \"line\", line: this.#buffer });\n this.#buffer = \"\";\n }\n this.finish();\n });\n this.process.stderr.on(\"data\", (chunk) => {\n this.#stderr = (this.#stderr + chunk).slice(-4096);\n });\n this.process.on(\"error\", (error) => {\n this.#processError = error;\n this.finish();\n });\n this.process.on(\"close\", () => {\n this.finish();\n });\n }\n sendCommand(command) {\n if (isChildClosed(this.process)) {\n throw new Error(\"control-mode process has exited\");\n }\n try {\n this.process.stdin.write(command);\n if (!command.endsWith(\"\\n\")) {\n this.process.stdin.write(\"\\n\");\n }\n }\n catch (error) {\n throw new Error(`failed to write control-mode command: ${errorMessage(error)}`);\n }\n }\n async runCommand(command, timeout = 5) {\n const releaseReader = this.acquireReader(\"runCommand\");\n const deadline = deadlineFromNow(timeout);\n try {\n this.sendCommand(command);\n let commandKey;\n for (;;) {\n const event = await this.readEventFromLines({\n milliseconds: remainingMilliseconds(deadline),\n });\n if (event instanceof ControlExit) {\n throw new ControlModeStreamEndedError(`control-mode exited while running ${command}: ${event.reason ?? \"unknown reason\"}`);\n }\n if (!(event instanceof ControlNotification)) {\n this.#deferredEvents.push(event);\n continue;\n }\n if (event.prefix === \"%begin\") {\n commandKey = controlCommandKey(event.line);\n continue;\n }\n if (event.prefix !== \"%end\" && event.prefix !== \"%error\") {\n continue;\n }\n const eventKey = controlCommandKey(event.line);\n if (commandKey !== undefined && eventKey !== undefined && eventKey !== commandKey) {\n continue;\n }\n if (event.prefix === \"%error\") {\n throw new Error(`control-mode command failed: ${command}; event=${JSON.stringify(event.line)}`);\n }\n return;\n }\n }\n finally {\n releaseReader();\n }\n }\n async readEvent(timeout) {\n const releaseReader = this.acquireReader(\"readEvent\");\n try {\n return await this.readEventUnlocked(timeout);\n }\n finally {\n releaseReader();\n }\n }\n async readEventUnlocked(timeout) {\n const deferred = this.#deferredEvents.shift();\n if (deferred !== undefined) {\n return deferred;\n }\n return this.readEventFromLines(timeout);\n }\n async readEventFromLines(timeout) {\n const deadline = timeout === undefined ? undefined : deadlineFromNow(timeout);\n for (;;) {\n if (this.#ended && this.#lines.isEmpty()) {\n throw this.streamEndedError();\n }\n const timeoutMs = deadline === undefined ? undefined : remainingMilliseconds(deadline);\n const item = await this.#lines.shift(timeoutMs);\n if (item.kind === \"end\") {\n throw this.streamEndedError();\n }\n const event = parseControlLine(item.line.replace(/\\n$/, \"\"));\n if (event !== undefined) {\n return event;\n }\n }\n }\n async *events(timeout) {\n const releaseReader = this.acquireReader(\"events\");\n try {\n for (;;) {\n let event;\n try {\n event = await this.readEventUnlocked(timeout);\n }\n catch (error) {\n if (error instanceof ControlModeStreamEndedError) {\n return;\n }\n throw error;\n }\n yield event;\n if (event instanceof ControlExit) {\n return;\n }\n }\n }\n finally {\n releaseReader();\n }\n }\n async waitForExit(timeout) {\n for await (const event of this.events(timeout)) {\n if (event instanceof ControlExit) {\n return event;\n }\n }\n throw new Error(\"control-mode stream ended before %exit\");\n }\n async close() {\n if (this.#closed) {\n return;\n }\n this.#closed = true;\n if (!isChildClosed(this.process)) {\n try {\n this.process.stdin.write(\"\\n\");\n this.process.stdin.end();\n }\n catch {\n // Best-effort close path.\n }\n try {\n await waitForChildClose(this.process, 2000);\n }\n catch {\n this.process.kill(\"SIGKILL\");\n await waitForChildClose(this.process, 2000);\n }\n }\n }\n acquireReader(operation) {\n if (this.#activeReader !== undefined) {\n throw new Error(`control-mode already has an active reader: ${this.#activeReader}`);\n }\n this.#activeReader = operation;\n return () => {\n if (this.#activeReader === operation) {\n this.#activeReader = undefined;\n }\n };\n }\n feedStdout(chunk) {\n this.#buffer += chunk;\n for (;;) {\n const index = this.#buffer.indexOf(\"\\n\");\n if (index < 0) {\n return;\n }\n const line = this.#buffer.slice(0, index + 1);\n this.#buffer = this.#buffer.slice(index + 1);\n this.#lines.push({ kind: \"line\", line });\n }\n }\n finish() {\n if (this.#ended) {\n return;\n }\n this.#ended = true;\n this.#lines.push({ kind: \"end\" });\n }\n streamEndedError() {\n if (this.#processError !== undefined) {\n return this.#processError;\n }\n const stderr = this.#stderr.trim();\n if (stderr.length > 0) {\n return new ControlModeStreamEndedError(`control-mode stream ended: ${stderr}`);\n }\n return new ControlModeStreamEndedError(\"control-mode stream ended\");\n }\n}\nexport function parseControlLine(line) {\n if (!line.startsWith(\"%\")) {\n return undefined;\n }\n if (line.startsWith(\"%output \")) {\n const [paneId, payload] = splitPayload(line.slice(\"%output \".length));\n if (paneId === undefined) {\n return new ControlMalformed(\"%output\", line, \"missing pane id\");\n }\n return new ControlOutput(paneId, decodeTmuxOctal(payload));\n }\n if (line.startsWith(\"%extended-output \")) {\n const [paneId, rest] = splitPayload(line.slice(\"%extended-output \".length));\n if (paneId === undefined) {\n return new ControlMalformed(\"%extended-output\", line, \"missing pane id\");\n }\n const [age, payloadRaw] = splitPayload(rest);\n if (age === undefined) {\n return new ControlMalformed(\"%extended-output\", line, \"missing age\");\n }\n const payload = payloadRaw.startsWith(\": \") ? payloadRaw.slice(2) : payloadRaw;\n const ageMs = parseInteger(age);\n if (ageMs === undefined) {\n return new ControlMalformed(\"%extended-output\", line, \"invalid age\");\n }\n return new ControlExtendedOutput(paneId, ageMs, decodeTmuxOctal(payload));\n }\n const prefix = line.split(\" \", 1)[0] ?? line;\n if (prefix === \"%exit\") {\n const reason = line.slice(\"%exit\".length).trim();\n return new ControlExit(reason || undefined);\n }\n return new ControlNotification(prefix, line);\n}\nexport function decodeTmuxOctal(value) {\n const chunks = [];\n let index = 0;\n while (index < value.length) {\n if (value[index] === \"\\\\\" &&\n index + 3 < value.length &&\n isOctal(value.slice(index + 1, index + 4))) {\n chunks.push(Number.parseInt(value.slice(index + 1, index + 4), 8));\n index += 4;\n continue;\n }\n const codePoint = value.codePointAt(index);\n if (codePoint === undefined) {\n break;\n }\n chunks.push(...Buffer.from(String.fromCodePoint(codePoint), \"utf8\"));\n index += codePoint > 0xffff ? 2 : 1;\n }\n return Buffer.from(chunks);\n}\nfunction splitPayload(value) {\n const separator = value.indexOf(\" \");\n if (separator <= 0) {\n return [undefined, \"\"];\n }\n return [value.slice(0, separator), value.slice(separator + 1)];\n}\nfunction isOctal(value) {\n return /^[0-7]{3}$/.test(value);\n}\nfunction parseInteger(value) {\n if (!/^-?[0-9]+$/.test(value)) {\n return undefined;\n }\n return Number.parseInt(value, 10);\n}\nfunction controlCommandKey(line) {\n const parts = line.trim().split(/\\s+/);\n if (parts.length < 4) {\n return undefined;\n }\n // RMUX control mode correlates command boundaries on time, number, and flags.\n return parts.slice(1, 4).join(\" \");\n}\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : String(error);\n}\nfunction waitForChildClose(child, timeoutMs) {\n if (isChildClosed(child)) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n cleanup();\n reject(new Error(\"timed out waiting for control-mode process\"));\n }, timeoutMs);\n const onClose = () => {\n cleanup();\n resolve();\n };\n const cleanup = () => {\n clearTimeout(timer);\n child.off(\"close\", onClose);\n };\n child.on(\"close\", onClose);\n });\n}\nfunction isChildClosed(child) {\n return child.exitCode !== null || child.signalCode !== null;\n}\nclass AsyncQueue {\n #items = [];\n #waiters = [];\n isEmpty() {\n return this.#items.length === 0;\n }\n push(value) {\n const waiter = this.#waiters.shift();\n if (waiter !== undefined) {\n waiter(value);\n return;\n }\n this.#items.push(value);\n }\n shift(timeoutMs) {\n if (this.#items.length > 0) {\n const item = this.#items.shift();\n if (item !== undefined) {\n return Promise.resolve(item);\n }\n }\n return new Promise((resolve, reject) => {\n let timer;\n const waiter = (value) => {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n resolve(value);\n };\n this.#waiters.push(waiter);\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n const index = this.#waiters.indexOf(waiter);\n if (index >= 0) {\n this.#waiters.splice(index, 1);\n }\n reject(new Error(\"timed out waiting for control-mode event\"));\n }, timeoutMs);\n }\n });\n }\n}\n","import { deadlineExpired, deadlineFromNow, durationMilliseconds, sleep } from \"./duration.js\";\nexport class TextMatch {\n text;\n row;\n column;\n constructor(text, row, column) {\n this.text = text;\n this.row = row;\n this.column = column;\n }\n}\nexport class TextExpectation {\n #pane;\n #mode;\n #expected;\n #interval;\n constructor(pane, options = {}) {\n this.#pane = pane;\n this.#mode = options.mode;\n this.#expected = options.expected;\n this.#interval = options.interval ?? 0.05;\n }\n toContain(text, options = {}) {\n return new TextExpectation(this.#pane, {\n mode: \"contains\",\n expected: text,\n interval: options.interval ?? 0.05,\n });\n }\n toHaveText(text, options = {}) {\n return new TextExpectation(this.#pane, {\n mode: \"equals\",\n expected: text,\n interval: options.interval ?? 0.05,\n });\n }\n async timeout(value) {\n if (this.#mode === undefined || this.#expected === undefined) {\n throw new Error(\"choose an expectation before setting a timeout\");\n }\n if (this.#mode === \"contains\") {\n return this.#pane.waitForText(this.#expected, {\n timeout: value,\n interval: this.#interval,\n });\n }\n return this.#pane.waitForExactText(this.#expected, {\n timeout: value,\n interval: this.#interval,\n });\n }\n}\nexport async function pollUntil(timeout, interval, callback, failure) {\n const deadline = deadlineFromNow(timeout);\n const intervalMs = durationMilliseconds(interval);\n for (;;) {\n const result = await callback();\n if (result !== undefined) {\n return result;\n }\n if (deadlineExpired(deadline)) {\n throw failure();\n }\n await sleep(intervalMs);\n }\n}\nexport function rowColumn(text, index) {\n const before = text.slice(0, index);\n const row = countOccurrences(before, \"\\n\");\n const lineStart = before.lastIndexOf(\"\\n\");\n if (lineStart < 0) {\n return [row, before.length];\n }\n return [row, before.length - lineStart - 1];\n}\nfunction countOccurrences(text, needle) {\n let count = 0;\n let index = text.indexOf(needle);\n while (index >= 0) {\n count += 1;\n index = text.indexOf(needle, index + needle.length);\n }\n return count;\n}\n","export async function ensureServerCompatible(server) {\n if (server.checkCompatibility) {\n await server.capabilities();\n }\n}\n","export class PaneExitState {\n dead;\n status;\n constructor(dead, status) {\n this.dead = dead;\n if (status !== undefined) {\n this.status = status;\n }\n }\n}\n","import { deadlineExpired, deadlineFromNow, durationMilliseconds, sleep } from \"./duration.js\";\nexport class TextLocator {\n pane;\n text;\n index;\n constructor(pane, text, index) {\n this.pane = pane;\n this.text = text;\n if (index !== undefined) {\n this.index = index;\n }\n }\n async all() {\n return (await this.pane.snapshot()).findAllText(this.text);\n }\n async count() {\n return (await this.all()).length;\n }\n first() {\n return new TextLocator(this.pane, this.text, 0);\n }\n last() {\n return new TextLocator(this.pane, this.text, -1);\n }\n nth(index) {\n return new TextLocator(this.pane, this.text, index);\n }\n async isVisible() {\n return this.resolve(await this.all()) !== undefined;\n }\n expect() {\n return new LocatorExpectation(this);\n }\n resolve(matches) {\n if (this.index === undefined) {\n return matches[0];\n }\n const normalized = this.index < 0 ? matches.length + this.index : this.index;\n return matches[normalized];\n }\n}\nexport class LocatorExpectation {\n #locator;\n #mode;\n #expected;\n #interval;\n constructor(locator, options = {}) {\n this.#locator = locator;\n this.#mode = options.mode;\n this.#expected = options.expected;\n this.#interval = options.interval ?? 0.05;\n }\n toBeVisible(options = {}) {\n return new LocatorExpectation(this.#locator, {\n mode: \"visible\",\n interval: options.interval ?? 0.05,\n });\n }\n toHaveText(text, options = {}) {\n return new LocatorExpectation(this.#locator, {\n mode: \"text\",\n expected: text,\n interval: options.interval ?? 0.05,\n });\n }\n toHaveCount(count, options = {}) {\n return new LocatorExpectation(this.#locator, {\n mode: \"count\",\n expected: count,\n interval: options.interval ?? 0.05,\n });\n }\n async timeout(value) {\n if (this.#mode === undefined) {\n throw new Error(\"choose an expectation before setting a timeout\");\n }\n const deadline = deadlineFromNow(value);\n const intervalMs = durationMilliseconds(this.#interval);\n let lastCount = 0;\n for (;;) {\n const matches = await this.#locator.all();\n lastCount = matches.length;\n const match = this.#locator.resolve(matches);\n if (this.#mode === \"visible\" && match !== undefined) {\n return match;\n }\n if (this.#mode === \"text\" && match !== undefined && match.text === this.#expected) {\n return match;\n }\n if (this.#mode === \"count\" && lastCount === this.#expected) {\n return lastCount;\n }\n if (deadlineExpired(deadline)) {\n throw new Error(this.failureMessage(lastCount));\n }\n await sleep(intervalMs);\n }\n }\n failureMessage(lastCount) {\n if (this.#mode === \"visible\") {\n return `text not visible before timeout: ${JSON.stringify(this.#locator.text)}`;\n }\n if (this.#mode === \"text\") {\n return `text locator did not resolve to expected text before timeout: ${JSON.stringify(this.#locator.text)} != ${JSON.stringify(this.#expected)}`;\n }\n if (this.#mode === \"count\") {\n return `text locator count did not match before timeout: ${lastCount} != ${this.#expected}`;\n }\n return \"locator expectation failed before timeout\";\n }\n}\n","import { rowColumn, TextMatch } from \"./expectations.js\";\nexport class PaneSnapshot {\n visibleText;\n constructor(visibleText) {\n this.visibleText = visibleText;\n }\n get visible_text() {\n return this.visibleText;\n }\n get lines() {\n return this.visibleText.split(/\\r?\\n/).filter((line, index, lines) => {\n return index < lines.length - 1 || line.length > 0;\n });\n }\n rowText(row) {\n const line = this.lines[row];\n if (line === undefined) {\n throw new RangeError(`row is outside the snapshot: ${row}`);\n }\n return line;\n }\n findText(text) {\n const index = this.visibleText.indexOf(text);\n if (index < 0) {\n return undefined;\n }\n const [row, column] = rowColumn(this.visibleText, index);\n return new TextMatch(text, row, column);\n }\n findAllText(text) {\n if (text.length === 0) {\n return [];\n }\n const matches = [];\n let start = 0;\n for (;;) {\n const index = this.visibleText.indexOf(text, start);\n if (index < 0) {\n return matches;\n }\n const [row, column] = rowColumn(this.visibleText, index);\n matches.push(new TextMatch(text, row, column));\n start = index + text.length;\n }\n }\n}\n","import { ControlExit, ControlExtendedOutput, ControlModeClient, ControlOutput, } from \"./control.js\";\nimport { deadlineFromNow, remainingMilliseconds } from \"./duration.js\";\nimport { PaneSnapshot } from \"./snapshot.js\";\nexport class PaneOutputChunk {\n paneId;\n data;\n ageMs;\n constructor(paneId, data, ageMs) {\n this.paneId = paneId;\n this.data = data;\n if (ageMs !== undefined) {\n this.ageMs = ageMs;\n }\n }\n get pane_id() {\n return this.paneId;\n }\n get age_ms() {\n return this.ageMs;\n }\n}\nexport class PaneOutputStream {\n #paneId;\n #control;\n constructor(paneId, control) {\n this.#paneId = paneId;\n this.#control = control;\n }\n static async open(pane) {\n const paneId = await pane.id();\n const control = new ControlModeClient(await pane.server.controlMode());\n try {\n await control.runCommand(`attach-session -t ${paneId}`);\n }\n catch (error) {\n await control.close();\n throw error;\n }\n return new PaneOutputStream(paneId, control);\n }\n async close() {\n await this.#control.close();\n }\n async next(timeout) {\n const deadline = timeout === undefined ? undefined : deadlineFromNow(timeout);\n for (;;) {\n const event = await this.#control.readEvent(deadline === undefined ? undefined : { milliseconds: remainingMilliseconds(deadline) });\n if (event instanceof ControlExit) {\n throw new Error(\"control-mode stream exited\");\n }\n if (event instanceof ControlOutput || event instanceof ControlExtendedOutput) {\n if (this.#paneId === undefined || event.paneId === this.#paneId) {\n return new PaneOutputChunk(event.paneId, event.data, event instanceof ControlExtendedOutput ? event.ageMs : undefined);\n }\n }\n }\n }\n}\nexport class PaneLineStream {\n #output;\n #buffer = [];\n #pending = [];\n constructor(output) {\n this.#output = output;\n }\n async close() {\n await this.#output.close();\n }\n async next(timeout) {\n const deadline = timeout === undefined ? undefined : deadlineFromNow(timeout);\n for (;;) {\n const pending = this.#pending.shift();\n if (pending !== undefined) {\n return pending;\n }\n const chunk = await this.#output.next(deadline === undefined ? undefined : { milliseconds: remainingMilliseconds(deadline) });\n this.feed(chunk.data);\n }\n }\n feed(data) {\n for (const byte of data) {\n if (byte === 0x0a) {\n let line = Buffer.from(this.#buffer);\n this.#buffer.length = 0;\n if (line.at(-1) === 0x0d) {\n line = line.subarray(0, -1);\n }\n this.#pending.push(line.toString(\"utf8\"));\n }\n else {\n this.#buffer.push(byte);\n }\n }\n }\n}\nexport class PaneRenderStream {\n #pane;\n #output;\n constructor(pane, output) {\n this.#pane = pane;\n this.#output = output;\n }\n static async open(pane) {\n return new PaneRenderStream(pane, await pane.outputStream());\n }\n async close() {\n await this.#output.close();\n }\n async next(timeout) {\n await this.#output.next(timeout);\n return this.#pane.snapshot();\n }\n}\n","export function requiredString(value, context, field) {\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n throw new TypeError(`${context} is missing non-empty string field ${JSON.stringify(field)}`);\n}\nexport function requiredInteger(value, context, field) {\n if (typeof value === \"number\" && Number.isInteger(value)) {\n return value;\n }\n throw new TypeError(`${context} is missing integer field ${JSON.stringify(field)}`);\n}\nexport function requiredPaneId(value, context) {\n const paneId = requiredString(value, context, \"pane_id\");\n if (/^%[0-9]+$/.test(paneId)) {\n return paneId;\n }\n throw new TypeError(`${context} has invalid pane_id ${JSON.stringify(paneId)}`);\n}\nexport function requiredSessionId(value, context) {\n const sessionId = requiredString(value, context, \"session_id\");\n if (/^\\$[0-9]+$/.test(sessionId)) {\n return sessionId;\n }\n throw new TypeError(`${context} has invalid session_id ${JSON.stringify(sessionId)}`);\n}\nexport function parseRequiredInteger(value, context) {\n if (/^-?[0-9]+$/.test(value)) {\n return Number.parseInt(value, 10);\n }\n throw new TypeError(`${context} is not an integer: ${JSON.stringify(value)}`);\n}\nexport function parsePaneId(value, context) {\n const paneId = value.trim();\n if (/^%[0-9]+$/.test(paneId)) {\n return paneId;\n }\n throw new TypeError(`${context} did not return a pane id: ${JSON.stringify(value)}`);\n}\nexport function parseWindowIndex(value, context) {\n const parsed = parseRequiredInteger(value.trim(), context);\n if (parsed < 0) {\n throw new TypeError(`${context} must be non-negative: ${JSON.stringify(value)}`);\n }\n return parsed;\n}\nexport function isJsonObject(value) {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { ensureServerCompatible } from \"../compatibility.js\";\nimport { deadlineExpired, deadlineFromNow, durationMilliseconds, sleep } from \"../duration.js\";\nimport { rowColumn, TextExpectation, TextMatch } from \"../expectations.js\";\nimport { PaneExitState } from \"../lifecycle.js\";\nimport { TextLocator } from \"../locators.js\";\nimport { PaneSnapshot } from \"../snapshot.js\";\nimport { PaneLineStream, PaneOutputStream, PaneRenderStream } from \"../streams.js\";\nimport { parsePaneId } from \"../validation.js\";\nexport class Pane {\n server;\n target;\n constructor(server, target) {\n this.server = server;\n this.target = target;\n }\n async sendKeys(...keys) {\n return this.server.sendKeys(this.target, ...keys);\n }\n async sendText(text) {\n return this.server.sendText(this.target, text);\n }\n async select() {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"select-pane\", \"-t\", this.target, { check: true });\n }\n async resize(options) {\n await ensureServerCompatible(this.server);\n const args = [\"resize-pane\", \"-t\", this.target];\n if (options.width !== undefined) {\n args.push(\"-x\", options.width);\n }\n if (options.height !== undefined) {\n args.push(\"-y\", options.height);\n }\n return this.server.cmd(...args, { check: true });\n }\n async split(options = {}) {\n await ensureServerCompatible(this.server);\n const direction = options.direction ?? \"vertical\";\n const args = [\n \"split-window\",\n \"-P\",\n \"-F\",\n \"#{pane_id}\",\n \"-t\",\n this.target,\n ];\n if (direction === \"horizontal\" || direction === \"h\") {\n args.push(\"-h\");\n }\n else if (direction === \"vertical\" || direction === \"v\") {\n args.push(\"-v\");\n }\n else {\n throw new Error(\"direction must be 'horizontal' or 'vertical'\");\n }\n if (options.size !== undefined) {\n args.push(\"-l\", options.size);\n }\n if (options.shellCommand !== undefined) {\n args.push(options.shellCommand);\n }\n const run = await this.server.cmd(...args, { check: true });\n return new Pane(this.server, parsePaneId(run.stdout, \"split-window output\"));\n }\n async respawn(options = {}) {\n await ensureServerCompatible(this.server);\n const args = [\"respawn-pane\", \"-t\", this.target];\n if (options.kill) {\n args.push(\"-k\");\n }\n if (options.shellCommand !== undefined) {\n args.push(options.shellCommand);\n }\n return this.server.cmd(...args, { check: true });\n }\n async close() {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"kill-pane\", \"-t\", this.target, { check: true });\n }\n async capture(options = {}) {\n return this.server.capturePane({ target: this.target, ...options });\n }\n async captureText(options = {}) {\n return (await this.snapshot(options)).visibleText;\n }\n async snapshot(options = {}) {\n return new PaneSnapshot(await this.capture(options));\n }\n getByText(text) {\n return new TextLocator(this, text);\n }\n locator(text) {\n return this.getByText(text);\n }\n async id() {\n await ensureServerCompatible(this.server);\n const run = await this.server.cmd(\"display-message\", \"-p\", \"-t\", this.target, \"#{pane_id}\", {\n check: true,\n });\n return parsePaneId(run.stdout, \"display-message #{pane_id}\");\n }\n async outputStream() {\n return PaneOutputStream.open(this);\n }\n async lineStream() {\n return new PaneLineStream(await this.outputStream());\n }\n async renderStream() {\n return PaneRenderStream.open(this);\n }\n async waitForText(text, options = {}) {\n return this.waitForTextInner(text, false, options.timeout ?? 5, options.interval ?? 0.05);\n }\n async waitForExactText(text, options = {}) {\n return this.waitForTextInner(text, true, options.timeout ?? 5, options.interval ?? 0.05);\n }\n expectVisibleText() {\n return new TextExpectation(this);\n }\n async waitForExit(options = {}) {\n const timeout = options.timeout ?? 5;\n const intervalMs = durationMilliseconds(options.interval ?? 0.05);\n const deadline = deadlineFromNow(timeout);\n for (;;) {\n const state = await this.exitState();\n if (state.dead) {\n return state;\n }\n if (deadlineExpired(deadline)) {\n throw new Error(`pane did not exit before timeout: ${this.target}`);\n }\n await sleep(intervalMs);\n }\n }\n async waitForTextInner(text, exact, timeout, interval) {\n const intervalMs = durationMilliseconds(interval);\n const deadline = deadlineFromNow(timeout);\n for (;;) {\n const captured = await this.captureText();\n if (exact) {\n if (captured.replace(/\\n+$/, \"\") === text) {\n const found = captured.indexOf(text);\n const [row, column] = rowColumn(captured, found < 0 ? 0 : found);\n return new TextMatch(text, row, column);\n }\n }\n else {\n const found = captured.indexOf(text);\n if (found >= 0) {\n const [row, column] = rowColumn(captured, found);\n return new TextMatch(text, row, column);\n }\n }\n if (deadlineExpired(deadline)) {\n throw new Error(`text not found before timeout: ${JSON.stringify(text)}`);\n }\n await sleep(intervalMs);\n }\n }\n async exitState() {\n await ensureServerCompatible(this.server);\n const run = await this.server.cmd(\"display-message\", \"-p\", \"-t\", this.target, \"#{pane_dead}:#{pane_dead_status}\", { check: true });\n const output = run.stdout.trim();\n const separator = output.indexOf(\":\");\n const dead = separator < 0 ? output : output.slice(0, separator);\n const status = separator < 0 ? \"\" : output.slice(separator + 1);\n if (dead !== \"1\" && dead !== \"true\") {\n return new PaneExitState(false);\n }\n return new PaneExitState(true, parseExitStatus(status));\n }\n}\nfunction parseExitStatus(value) {\n if (!/^[0-9]+$/.test(value)) {\n return undefined;\n }\n return Number.parseInt(value, 10);\n}\n","import { ensureServerCompatible } from \"../compatibility.js\";\nimport { requiredPaneId } from \"../validation.js\";\nimport { Pane } from \"./pane.js\";\nexport class Window {\n server;\n sessionName;\n sessionTarget;\n index;\n constructor(server, sessionName, sessionTarget, index) {\n this.server = server;\n this.sessionName = sessionName;\n this.sessionTarget = sessionTarget;\n this.index = index;\n }\n get target() {\n return `${this.sessionTarget}:${this.index}`;\n }\n async listPanes() {\n return this.server.listPanes({ target: this.target });\n }\n async panes() {\n const panes = [];\n for (const [index, pane] of (await this.listPanes()).entries()) {\n panes.push(new Pane(this.server, requiredPaneId(pane[\"pane_id\"], `list-panes row ${index}`)));\n }\n return panes;\n }\n pane(index) {\n return new Pane(this.server, `${this.target}.${index}`);\n }\n async select() {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"select-window\", \"-t\", this.target, { check: true });\n }\n async rename(name) {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"rename-window\", \"-t\", this.target, name, { check: true });\n }\n async resize(options) {\n await ensureServerCompatible(this.server);\n const args = [\"resize-window\", \"-t\", this.target];\n if (options.width !== undefined) {\n args.push(\"-x\", options.width);\n }\n if (options.height !== undefined) {\n args.push(\"-y\", options.height);\n }\n return this.server.cmd(...args, { check: true });\n }\n async selectLayout(layout) {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"select-layout\", \"-t\", this.target, layout, { check: true });\n }\n async close() {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"kill-window\", \"-t\", this.target, { check: true });\n }\n}\n","import { ensureServerCompatible } from \"../compatibility.js\";\nimport { parseWindowIndex, requiredInteger } from \"../validation.js\";\nimport { Window } from \"./window.js\";\nexport class Session {\n server;\n name;\n target;\n constructor(server, name, target = name) {\n this.server = server;\n this.name = name;\n this.target = target;\n }\n async listWindows() {\n return this.server.listWindows({ target: this.target });\n }\n async windows() {\n return (await this.listWindows()).map((window) => {\n return new Window(this.server, this.name, this.target, requiredInteger(window[\"window_index\"], \"list-windows row\", \"window_index\"));\n });\n }\n window(index) {\n return new Window(this.server, this.name, this.target, index);\n }\n pane(windowIndex = 0, paneIndex = 0) {\n return this.window(windowIndex).pane(paneIndex);\n }\n async rename(name) {\n await ensureServerCompatible(this.server);\n await this.server.cmd(\"rename-session\", \"-t\", this.target, name, { check: true });\n return new Session(this.server, name, this.target.startsWith(\"$\") ? this.target : name);\n }\n async kill() {\n await ensureServerCompatible(this.server);\n return this.server.cmd(\"kill-session\", \"-t\", this.target, { check: true });\n }\n async newWindow(options = {}) {\n await ensureServerCompatible(this.server);\n const args = [\n \"new-window\",\n \"-P\",\n \"-F\",\n \"#{window_index}\",\n \"-t\",\n this.target,\n ];\n if (options.detached ?? true) {\n args.push(\"-d\");\n }\n if (options.name !== undefined) {\n args.push(\"-n\", options.name);\n }\n if (options.shellCommand !== undefined) {\n args.push(options.shellCommand);\n }\n const run = await this.server.cmd(...args, { check: true });\n return new Window(this.server, this.name, this.target, parseWindowIndex(run.stdout, \"new-window output\"));\n }\n}\n","import { deadlineExpired, deadlineFromNow, durationMilliseconds, sleep } from \"./duration.js\";\nexport class PaneSetOutcome {\n matched;\n snapshots;\n constructor(matched, snapshots) {\n this.matched = [...matched];\n this.snapshots = [...snapshots];\n }\n}\nexport class PaneSet {\n panes;\n constructor(panes) {\n this.panes = [...panes];\n }\n get length() {\n return this.panes.length;\n }\n [Symbol.iterator]() {\n return this.panes[Symbol.iterator]();\n }\n isEmpty() {\n return this.panes.length === 0;\n }\n async broadcastText(text) {\n return Promise.all(this.panes.map((pane) => pane.sendText(text)));\n }\n async broadcastKey(key) {\n return Promise.all(this.panes.map((pane) => pane.sendKeys(key)));\n }\n async snapshotAll() {\n const snapshots = [];\n for (const pane of this.panes) {\n snapshots.push(await pane.snapshot());\n }\n return snapshots;\n }\n expectAll() {\n return new PaneSetExpectation(this, \"all\");\n }\n expectAny() {\n return new PaneSetExpectation(this, \"any\");\n }\n waitAll() {\n return this.expectAll();\n }\n waitAny() {\n return this.expectAny();\n }\n}\nexport class PaneSetExpectation {\n #paneSet;\n #mode;\n #text;\n #interval;\n constructor(paneSet, mode, options = {}) {\n this.#paneSet = paneSet;\n this.#mode = mode;\n this.#text = options.text;\n this.#interval = options.interval ?? 0.05;\n }\n visibleTextContains(text, options = {}) {\n return new PaneSetExpectation(this.#paneSet, this.#mode, {\n text,\n interval: options.interval ?? 0.05,\n });\n }\n async timeout(value) {\n if (this.#text === undefined) {\n throw new Error(\"choose an expectation before setting a timeout\");\n }\n const deadline = deadlineFromNow(value);\n const intervalMs = durationMilliseconds(this.#interval);\n for (;;) {\n const matched = [];\n const snapshots = [];\n for (const pane of this.#paneSet) {\n const snapshot = await pane.snapshot();\n if (snapshot.visibleText.includes(this.#text)) {\n matched.push(pane);\n snapshots.push(snapshot);\n }\n }\n if (this.#mode === \"all\" && matched.length === this.#paneSet.length) {\n return new PaneSetOutcome(matched, snapshots);\n }\n if (this.#mode === \"any\" && matched.length > 0) {\n return new PaneSetOutcome(matched, snapshots);\n }\n if (deadlineExpired(deadline)) {\n throw new Error(`pane set did not match visible text before timeout: ${JSON.stringify(this.#text)}`);\n }\n await sleep(intervalMs);\n }\n }\n}\n","import { Rmux } from \"./rmux.js\";\nexport class RmuxBuilder {\n #binary = \"rmux\";\n #socketPath;\n #socketName;\n #checkCompatibility = true;\n #env;\n #cwd;\n binary(value) {\n this.#binary = value;\n return this;\n }\n socketPath(value) {\n this.#socketPath = value;\n this.#socketName = undefined;\n return this;\n }\n socketName(value) {\n this.#socketName = value;\n this.#socketPath = undefined;\n return this;\n }\n checkCompatibility(enabled) {\n this.#checkCompatibility = enabled;\n return this;\n }\n env(value) {\n this.#env = value === undefined ? undefined : { ...value };\n return this;\n }\n cwd(value) {\n this.#cwd = value;\n return this;\n }\n async connectOrStart() {\n const rmux = new Rmux({\n binary: this.#binary,\n socketPath: this.#socketPath,\n socketName: this.#socketName,\n checkCompatibility: this.#checkCompatibility,\n env: this.#env,\n cwd: this.#cwd,\n });\n await rmux.startServer();\n if (this.#checkCompatibility) {\n await rmux.capabilities();\n }\n return rmux;\n }\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nexport class RmuxTraceBuilder {\n #maxEvents = 100_000;\n maxEvents(value) {\n if (!Number.isInteger(value) || value < 0) {\n throw new RangeError(\"maxEvents must be a non-negative integer\");\n }\n this.#maxEvents = value;\n return this;\n }\n start() {\n const trace = new TraceSession(this.#maxEvents);\n trace.record(\"trace.start\", {});\n return trace;\n }\n}\nexport class TraceSession {\n #maxEvents;\n #events = [];\n constructor(maxEvents) {\n this.#maxEvents = maxEvents;\n }\n recordAction(action) {\n this.record(\"action\", { action });\n }\n async recordSnapshot(pane) {\n const snapshot = await pane.snapshot();\n this.record(\"snapshot\", {\n pane: pane.target,\n visible_text: snapshot.visibleText,\n });\n }\n async stop(directory) {\n this.record(\"trace.stop\", {});\n await mkdir(directory, { recursive: true });\n const output = join(directory, \"trace.jsonl\");\n const content = this.#events.length === 0\n ? \"\"\n : this.#events.map((event) => JSON.stringify(event)).join(\"\\n\") + \"\\n\";\n await writeFile(output, content, \"utf8\");\n return output;\n }\n record(kind, payload) {\n const jsonPayload = copyJsonObject(payload, \"payload\");\n if (this.#maxEvents <= 0) {\n return;\n }\n if (this.#events.length === this.#maxEvents) {\n this.#events.shift();\n }\n this.#events.push({\n timestamp_ms: Date.now(),\n kind,\n payload: jsonPayload,\n });\n }\n}\nfunction copyJsonObject(value, path) {\n if (!isPlainObject(value)) {\n throw new TypeError(`${path} must be a JSON object`);\n }\n const copy = {};\n for (const [key, item] of Object.entries(value)) {\n copy[key] = copyJsonValue(item, `${path}.${key}`);\n }\n return copy;\n}\nfunction copyJsonValue(value, path) {\n if (value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new TypeError(`${path} must be a finite JSON number`);\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((item, index) => copyJsonValue(item, `${path}[${index}]`));\n }\n return copyJsonObject(value, path);\n}\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n","import { CommandRun } from \"./command.js\";\nimport { ControlModeClient, spawnControlProcess, waitForControlProcessSpawn, } from \"./control.js\";\nimport { RmuxCompatibilityError } from \"./errors.js\";\nimport { Session } from \"./handles/session.js\";\nimport { PaneSet } from \"./pane-set.js\";\nimport { runProcess } from \"./process.js\";\nimport { RmuxBuilder } from \"./builder.js\";\nimport { RmuxTraceBuilder } from \"./trace.js\";\nimport { isJsonObject, requiredSessionId, requiredString } from \"./validation.js\";\nexport const BINARY_CONTRACT_VERSION = 1;\nexport class Rmux {\n binary;\n socketPath;\n socketName;\n checkCompatibility;\n env;\n cwd;\n #capabilities;\n static builder() {\n return new RmuxBuilder();\n }\n constructor(options = {}) {\n if (options.socketPath !== undefined && options.socketName !== undefined) {\n throw new Error(\"choose only one of socketPath or socketName\");\n }\n this.binary = options.binary ?? \"rmux\";\n this.socketPath = options.socketPath;\n this.socketName = options.socketName;\n this.checkCompatibility = options.checkCompatibility ?? true;\n this.env = options.env === undefined ? undefined : { ...options.env };\n this.cwd = options.cwd;\n }\n async cmd(...argsAndOptions) {\n const { args, options } = splitCommandArguments(argsAndOptions);\n const argv = this.argv(args);\n const completed = await runProcess(argv, {\n cwd: this.cwd,\n env: this.env,\n });\n const run = new CommandRun(argv, completed.code, completed.stdout, completed.stderr, completed.signal);\n if (options.check) {\n run.checkReturnCode();\n }\n return run;\n }\n async capabilities() {\n if (this.#capabilities === undefined) {\n const capabilities = await this.jsonObject(\"capabilities\", \"--json\");\n if (this.checkCompatibility) {\n this.validateCapabilities(capabilities);\n }\n this.#capabilities = capabilities;\n }\n return { ...this.#capabilities };\n }\n async startServer() {\n return this.cmd(\"start-server\", { check: true });\n }\n async killServer(options = {}) {\n return this.cmd(\"kill-server\", { check: options.check ?? false });\n }\n async listSessions() {\n await this.ensureCompatible();\n return this.jsonList(\"list-sessions\", \"--json\");\n }\n async sessions() {\n return (await this.listSessions()).map((session, index) => {\n return this.sessionFromRow(session, `list-sessions row ${index}`);\n });\n }\n session(name) {\n return new Session(this, name);\n }\n async ensureSession(name, options = {}) {\n await this.ensureCompatible();\n const run = await this.cmd(\"has-session\", \"-t\", name);\n if (run.returnCode !== 0) {\n const args = [\"new-session\"];\n if (options.detached ?? true) {\n args.push(\"-d\");\n }\n args.push(\"-s\", name);\n if (options.shellCommand !== undefined) {\n args.push(options.shellCommand);\n }\n await this.cmd(...args, { check: true });\n }\n return this.sessionForTarget(name, name);\n }\n async listWindows(options = {}) {\n await this.ensureCompatible();\n const args = [\"list-windows\"];\n if (options.allSessions) {\n args.push(\"-a\");\n }\n if (options.target !== undefined) {\n args.push(\"-t\", options.target);\n }\n args.push(\"--json\");\n return this.jsonList(...args);\n }\n async listPanes(options = {}) {\n await this.ensureCompatible();\n const args = [\"list-panes\"];\n if (options.allSessions) {\n args.push(\"-a\");\n }\n if (options.target !== undefined) {\n args.push(\"-t\", options.target);\n }\n args.push(\"--json\");\n return this.jsonList(...args);\n }\n async listClients(options = {}) {\n await this.ensureCompatible();\n const args = [\"list-clients\"];\n if (options.targetSession !== undefined) {\n args.push(\"-t\", options.targetSession);\n }\n args.push(\"--json\");\n return this.jsonList(...args);\n }\n async sendKeys(target, ...keys) {\n await this.ensureCompatible();\n return this.cmd(\"send-keys\", \"-t\", target, ...keys, { check: true });\n }\n async sendText(target, text) {\n await this.ensureCompatible();\n return this.cmd(\"send-keys\", \"-t\", target, \"-l\", text, { check: true });\n }\n async displayMessage(message, options = {}) {\n await this.ensureCompatible();\n const args = [\"display-message\", \"--json\"];\n if (options.target !== undefined) {\n args.push(\"-t\", options.target);\n }\n args.push(message);\n return this.jsonObject(...args);\n }\n async capturePane(options = {}) {\n await this.ensureCompatible();\n const args = [\"capture-pane\", \"-p\"];\n if (options.target !== undefined) {\n args.push(\"-t\", options.target);\n }\n if (options.start !== undefined) {\n args.push(\"-S\", options.start);\n }\n if (options.end !== undefined) {\n args.push(\"-E\", options.end);\n }\n if (options.escapeAnsi) {\n args.push(\"-e\");\n }\n if (options.joinWrapped) {\n args.push(\"-J\");\n }\n return (await this.cmd(...args, { check: true })).stdout;\n }\n async controlMode() {\n await this.ensureCompatible();\n const process = spawnControlProcess({\n binary: this.binary,\n args: this.endpointArgs([\"-C\"]),\n cwd: this.cwd,\n env: this.env,\n });\n await waitForControlProcessSpawn(process);\n return process;\n }\n async control() {\n return new ControlModeClient(await this.controlMode());\n }\n paneSet(panes) {\n return new PaneSet(panes);\n }\n async broadcastText(panes, text) {\n return this.paneSet(panes).broadcastText(text);\n }\n async broadcastKey(panes, key) {\n return this.paneSet(panes).broadcastKey(key);\n }\n tracing() {\n return new RmuxTraceBuilder();\n }\n async jsonList(...args) {\n const value = await this.jsonValue(...args);\n if (!Array.isArray(value)) {\n throw new TypeError(\"rmux JSON response is not an array\");\n }\n return value.map((item) => {\n if (!isJsonObject(item)) {\n throw new TypeError(\"rmux JSON array contains a non-object item\");\n }\n return item;\n });\n }\n async jsonObject(...args) {\n const value = await this.jsonValue(...args);\n if (!isJsonObject(value)) {\n throw new TypeError(\"rmux JSON response is not an object\");\n }\n return value;\n }\n async jsonValue(...args) {\n const run = await this.cmd(...args, { check: true });\n try {\n return JSON.parse(run.stdout);\n }\n catch (error) {\n throw new TypeError(`rmux returned invalid JSON for ${args.map(String).join(\" \")}: ${errorMessage(error)}`);\n }\n }\n async ensureCompatible() {\n if (this.checkCompatibility) {\n await this.capabilities();\n }\n }\n async sessionForTarget(target, fallbackName) {\n const idMessage = await this.displayMessage(\"#{session_id}\", { target });\n const sessionId = requiredSessionId(idMessage[\"message\"], `display-message #{session_id} for ${JSON.stringify(target)}`);\n const row = (await this.listSessions()).find((session) => {\n return session[\"session_id\"] === sessionId;\n });\n if (row !== undefined) {\n return this.sessionFromRow(row, `session ${sessionId}`);\n }\n return new Session(this, fallbackName, sessionId);\n }\n sessionFromRow(session, context) {\n return new Session(this, requiredString(session[\"session_name\"], context, \"session_name\"), requiredSessionId(session[\"session_id\"], context));\n }\n validateCapabilities(capabilities) {\n const version = capabilities[\"binary_contract_version\"];\n if (version !== BINARY_CONTRACT_VERSION) {\n throw new RmuxCompatibilityError(`unsupported rmux binary contract version ${JSON.stringify(version)}; expected ${BINARY_CONTRACT_VERSION}`);\n }\n const commands = capabilities[\"json_commands\"];\n const requiredCommands = [\n \"capabilities\",\n \"display-message\",\n \"list-clients\",\n \"list-panes\",\n \"list-sessions\",\n \"list-windows\",\n ];\n if (!Array.isArray(commands) ||\n !requiredCommands.every((command) => commands.includes(command))) {\n throw new RmuxCompatibilityError(\"rmux binary does not advertise required JSON commands\");\n }\n const publicContract = capabilities[\"public_contract\"];\n if (!Array.isArray(publicContract) || !publicContract.includes(\"control-mode\")) {\n throw new RmuxCompatibilityError(\"rmux binary does not advertise control-mode\");\n }\n }\n argv(args) {\n return [this.binary, ...this.endpointArgs(args)];\n }\n endpointArgs(args) {\n const argv = [];\n if (this.socketName !== undefined) {\n argv.push(\"-L\", this.socketName);\n }\n if (this.socketPath !== undefined) {\n argv.push(\"-S\", this.socketPath);\n }\n argv.push(...args.map(String));\n return argv;\n }\n}\nfunction splitCommandArguments(values) {\n const last = values.at(-1);\n if (isCommandOptionsCandidate(last)) {\n return {\n args: values.slice(0, -1),\n options: parseCommandOptions(last),\n };\n }\n return {\n args: values,\n options: {},\n };\n}\nfunction isCommandOptionsCandidate(value) {\n if (!isJsonObject(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\nfunction parseCommandOptions(value) {\n for (const key of Object.keys(value)) {\n if (key !== \"check\") {\n throw new TypeError(`unknown rmux command option: ${key}`);\n }\n }\n if (value[\"check\"] !== undefined && typeof value[\"check\"] !== \"boolean\") {\n throw new TypeError(\"rmux command option check must be a boolean\");\n }\n return value[\"check\"] === undefined ? {} : { check: value[\"check\"] };\n}\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Terminal hosting for workflow runs through RMUX.\n *\n * DESIGN PATTERNS:\n * - RMUX owns the pseudo terminal, screen state, input, and process lifetime\n * - Platform payloads are optional and resolved at runtime, with PATH fallback\n * - The existing NativeTerminalService API remains stable for consumers\n *\n * CODING STANDARDS:\n * - Named exports only\n * - Explicit return types on exported members\n * - No top-level import of a platform payload package\n */\n\nimport { spawn } from 'node:child_process';\nimport fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\n\nimport { CommandRun, RMUX } from '@rmux/sdk';\n\nimport type {\n NativeTerminalDependencies,\n NativeTerminalSpawnInput,\n NativeTerminalViewer,\n RmuxTerminalClient,\n RmuxTerminalPane,\n} from '../NativeTerminalService/types';\nimport type { WorkflowHostOptions } from './type';\n\nconst EXECUTABLE_MODE = 0o755;\nconst EXECUTABLE_BITS = 0o111;\nconst VENDOR_DIRECTORY = 'vendor';\nconst FALLBACK_COLUMNS = 120;\nconst FALLBACK_ROWS = 40;\nconst PANE_PID_FORMAT = '#{pane_pid}';\nconst PANE_STATE_FORMAT = '#{pane_dead}:#{pane_dead_status}';\nconst POLL_MS = 100;\nconst RMUX_BINARY_ENV = 'AGIMON_RMUX_BINARY';\nconst RMUX_SOCKET_NAME = 'agimon-workflow-mcp';\nconst ENV_COMMAND = '/usr/bin/env';\n// Waits for the gate, loads the run's environment and deletes it, then becomes the command.\nconst GATE_SCRIPT = 'while [ ! -e \"$1\" ]; do sleep 0.01; done; . \"$2\"; rm -f \"$2\"; shift 2; exec \"$@\"';\nconst ENVIRONMENT_FILE = 'environment';\nconst PRIVATE_FILE_MODE = 0o600;\n/** Names a POSIX shell can export; any other name stays on the env command line. */\nconst SHELL_VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst TERMINAL_ENV = { TERM: 'xterm-256color', COLORTERM: 'truecolor' } as const;\n\nconst PACKAGE_BY_PLATFORM: Readonly<Record<string, string>> = {\n 'darwin-arm64': '@agimon-ai/rmux-darwin-arm64',\n 'darwin-x64': '@agimon-ai/rmux-darwin-x64',\n 'linux-arm64': '@agimon-ai/rmux-linux-arm64',\n 'linux-x64': '@agimon-ai/rmux-linux-x64',\n};\n\nconst requirePackage = createRequire(import.meta.url);\n\ninterface HostedRun {\n pane: RmuxTerminalPane;\n sessionName: string;\n exited: boolean;\n exitCode?: number;\n viewers: Set<object>;\n ended: Promise<number>;\n}\n\nfunction defaultGeometry(): { columns: number; rows: number } {\n return {\n columns: process.stdout.columns || FALLBACK_COLUMNS,\n rows: process.stdout.rows || FALLBACK_ROWS,\n };\n}\n\nfunction bundledBinary(): string | undefined {\n const packageName = PACKAGE_BY_PLATFORM[`${process.platform}-${process.arch}`];\n if (!packageName) return undefined;\n try {\n const manifest = requirePackage.resolve(`${packageName}/package.json`);\n return path.join(path.dirname(manifest), VENDOR_DIRECTORY, 'bin', 'rmux');\n } catch {\n return undefined;\n }\n}\n\n/**\n * Make the bundled payload runnable before RMUX is asked for anything.\n *\n * The prebuilt packages reach npm with plain 0644 files. Restoring the\n * executable bit on the launcher alone is not enough: rmux execs\n * `bin/rmux-daemon` and `libexec/rmux/rmux` itself and fails on the first with\n * a permission error, so every file the vendor tree ships is restored. A\n * stand-alone override outside a vendor tree only gets itself restored, and a\n * file that is already executable is left alone, since chmod on a binary\n * someone else owns would throw and drop a usable candidate.\n */\nexport function ensureExecutablePayload(binary: string): void {\n const vendor = path.resolve(path.dirname(binary), '..');\n const payload =\n path.basename(vendor) === VENDOR_DIRECTORY\n ? fs\n .readdirSync(vendor, { recursive: true, withFileTypes: true })\n .filter((entry) => entry.isFile())\n .map((entry) => path.join(entry.parentPath, entry.name))\n : [binary];\n for (const file of payload) {\n if ((fs.statSync(file).mode & EXECUTABLE_BITS) === 0) fs.chmodSync(file, EXECUTABLE_MODE);\n }\n}\n\nasync function createDefaultClient(options: WorkflowHostOptions): Promise<RmuxTerminalClient | undefined> {\n const candidates = [options.environment[RMUX_BINARY_ENV], bundledBinary(), 'rmux'].filter(\n (candidate): candidate is string => Boolean(candidate),\n );\n for (const binary of candidates) {\n try {\n if (binary !== 'rmux') ensureExecutablePayload(binary);\n const environment = Object.fromEntries(\n Object.entries(options.environment).filter((entry): entry is [string, string] => entry[1] !== undefined),\n );\n const client = new RMUX({ binary, socketName: RMUX_SOCKET_NAME, cwd: options.cwd, env: environment });\n // The SDK's default command runner merges process.env. Keep its handles and\n // compatibility checks, but run each command with the admitted environment.\n client.cmd = async (...arguments_) => {\n const last = arguments_.at(-1);\n const check = typeof last === 'object' ? last.check === true : false;\n const args = (typeof last === 'object' ? arguments_.slice(0, -1) : arguments_).map(String);\n const argv = ['-L', RMUX_SOCKET_NAME, ...args];\n const completed = await runRmux(binary, argv, options.cwd, environment);\n const run = new CommandRun([binary, ...argv], completed.code, completed.stdout, completed.stderr);\n return check ? run.checkReturnCode() : run;\n };\n await client.capabilities();\n return client;\n } catch {\n continue;\n }\n }\n return undefined;\n}\n\n/** Single-quotes a value for POSIX sh, which keeps newlines and every other byte literal. */\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\n/**\n * The run's environment, split into a script the pane sources and the few\n * assignments a shell cannot export.\n *\n * Passing the whole environment as arguments to RMUX's new-session breaks once\n * a host adds its own variables: RMUX refuses the command as too long. It also\n * puts every value, secrets included, into the process table. The script is\n * written to the run's private gate directory instead and deleted as soon as\n * the pane has read it.\n */\nfunction environmentScript(env: Record<string, string>): { script: string; unexportable: string[] } {\n const entries = Object.entries({ ...env, ...TERMINAL_ENV }).sort(([left], [right]) => left.localeCompare(right));\n const exported = entries.filter(([name]) => SHELL_VARIABLE_NAME.test(name));\n return {\n script: exported.map(([name, value]) => `export ${name}=${shellQuote(value)}\\n`).join(''),\n unexportable: entries\n .filter(([name]) => !SHELL_VARIABLE_NAME.test(name))\n .map(([name, value]) => `${name}=${value}`),\n };\n}\n\nfunction panePid(stdout: string): number {\n const pid = Number(stdout.trim());\n if (!Number.isInteger(pid) || pid <= 0)\n throw new Error(`RMUX returned an invalid pane pid: ${JSON.stringify(stdout)}`);\n return pid;\n}\n\nfunction delay(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\nasync function waitForRunEnd(client: RmuxTerminalClient, target: string): Promise<number> {\n for (;;) {\n const result = await client.cmd('display-message', '-p', '-t', target, PANE_STATE_FORMAT, { check: true });\n const [dead, status] = result.stdout.trim().split(':', 2);\n if (dead === '1') {\n const code = Number(status || 0);\n return Number.isInteger(code) ? code : 0;\n }\n await delay(POLL_MS);\n }\n}\n\nfunction screenLines(screen: string): string[] {\n const lines = screen.split('\\n');\n while (lines.length > 0 && lines.at(-1)?.trim() === '') lines.pop();\n return lines;\n}\n\n/**\n * Hosts workflow runs in RMUX while preserving the package's existing terminal\n * socket contract for callers in another process.\n */\nexport class NativeTerminalService {\n private readonly runs = new Map<string, HostedRun>();\n private clientPromise?: Promise<RmuxTerminalClient | undefined>;\n\n constructor(\n private readonly options: WorkflowHostOptions,\n private readonly dependencies: NativeTerminalDependencies = {},\n ) {}\n\n private client(): Promise<RmuxTerminalClient | undefined> {\n this.clientPromise ??= this.dependencies.createClient?.() ?? createDefaultClient(this.options);\n return this.clientPromise;\n }\n\n async available(): Promise<boolean> {\n return Boolean(await this.client());\n }\n\n async spawn(input: NativeTerminalSpawnInput): Promise<{ pid: number }> {\n const client = await this.client();\n if (!client) throw new Error('Terminal hosting is unavailable: RMUX did not load.');\n\n const { columns, rows } = defaultGeometry();\n if (!this.options.temporaryDirectory)\n throw new Error('Native workflow terminals require an admitted temporary directory.');\n const gateDirectory = fs.mkdtempSync(path.join(this.options.temporaryDirectory, 'workflow-mcp-rmux-'));\n const gate = path.join(gateDirectory, 'start');\n const environmentFile = path.join(gateDirectory, ENVIRONMENT_FILE);\n const environment = environmentScript(input.env);\n let created = false;\n let released = false;\n try {\n fs.writeFileSync(environmentFile, environment.script, { mode: PRIVATE_FILE_MODE });\n const opened = await client.cmd(\n 'new-session',\n '-d',\n '-P',\n '-F',\n PANE_PID_FORMAT,\n '-s',\n input.runKey,\n '-c',\n input.cwd,\n '-x',\n columns,\n '-y',\n rows,\n '/usr/bin/env',\n '-i',\n '/bin/sh',\n '-c',\n GATE_SCRIPT,\n 'workflow-mcp-gate',\n gate,\n environmentFile,\n ENV_COMMAND,\n ...environment.unexportable,\n input.command,\n ...input.args,\n { check: true },\n );\n created = true;\n const pid = panePid(opened.stdout);\n await client.cmd('set-option', '-t', input.runKey, 'remain-on-exit', 'on', { check: true });\n const pane = client.session(input.runKey).pane(0, 0);\n const hosted: HostedRun = {\n pane,\n sessionName: input.runKey,\n exited: false,\n viewers: new Set(),\n ended: Promise.resolve(0),\n };\n hosted.ended = waitForRunEnd(client, input.runKey)\n .then((code) => {\n hosted.exited = true;\n hosted.exitCode = code;\n return code;\n })\n .finally(() => fs.rmSync(gateDirectory, { recursive: true, force: true }));\n fs.writeFileSync(gate, '', { mode: 0o600 });\n released = true;\n this.runs.set(input.runKey, hosted);\n return { pid };\n } catch (error) {\n if (created)\n await client\n .session(input.runKey)\n .kill()\n .catch(() => undefined);\n throw error;\n } finally {\n if (!released) fs.rmSync(gateDirectory, { recursive: true, force: true });\n }\n }\n\n isHosted(runKey: string): boolean {\n return this.runs.has(runKey);\n }\n\n exitOf(runKey: string): { exited: boolean; exitCode?: number } | undefined {\n const hosted = this.runs.get(runKey);\n if (!hosted) return undefined;\n return { exited: hosted.exited, ...(hosted.exitCode === undefined ? {} : { exitCode: hosted.exitCode }) };\n }\n\n ended(runKey: string): Promise<number> {\n return this.runs.get(runKey)?.ended ?? Promise.resolve(0);\n }\n\n viewerCount(runKey: string): number {\n return this.runs.get(runKey)?.viewers.size ?? 0;\n }\n\n async attach(runKey: string, columns: number, rows: number): Promise<NativeTerminalViewer> {\n const hosted = this.runs.get(runKey);\n if (!hosted) throw new Error(`No RMUX-hosted workflow run matches ${JSON.stringify(runKey)}.`);\n\n const viewer = {};\n hosted.viewers.add(viewer);\n await hosted.pane.resize({ width: columns, height: rows });\n\n return {\n snapshot: async () => screenLines(await hosted.pane.captureText()),\n resize: async (nextColumns, nextRows) => {\n await hosted.pane.resize({ width: nextColumns, height: nextRows });\n },\n write: async (data) => {\n if (!hosted.exited) await hosted.pane.sendText(data);\n },\n detach: () => {\n hosted.viewers.delete(viewer);\n },\n };\n }\n\n async kill(runKey: string): Promise<void> {\n const hosted = this.runs.get(runKey);\n if (!hosted) return;\n const client = await this.client();\n await client?.session(hosted.sessionName).kill();\n hosted.viewers.clear();\n this.runs.delete(runKey);\n }\n\n async disposeAll(): Promise<void> {\n await Promise.all([...this.runs.keys()].map((runKey) => this.kill(runKey)));\n }\n}\n\nasync function runRmux(\n binary: string,\n args: string[],\n cwd: string,\n env: Record<string, string>,\n): Promise<{ code: number; stdout: string; stderr: string }> {\n return await new Promise((resolve, reject) => {\n const child = spawn(binary, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n child.stderr.on('data', (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n child.once('error', reject);\n child.once('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));\n });\n}\n","/**\n * An RMUX-hosted run, reachable through the existing native-launcher socket.\n *\n * WHY A SOCKET:\n * The run record's `native` discriminator predates RMUX and points callers at\n * this transport. Keeping that contract avoids teaching every cockpit process\n * how to discover the private RMUX server and target.\n *\n * DESIGN PATTERNS:\n * - One line of JSON per request and per answer. A screen is a list of strings\n * and a keystroke is a string, so nothing here earns a framing format\n * - One viewer per socket server, shared by its clients. RMUX owns screen state,\n * so requests capture the pane without allocating an emulator\n * - The client connects per request. A unix socket connect costs a fraction of\n * a millisecond, and a stateless client cannot leak a connection or need\n * reconnect logic when a host restarts\n *\n * CODING STANDARDS:\n * - Named exports only\n * - Explicit return types on exported members\n *\n * AVOID:\n * - Putting the socket inside the run directory: a run directory path is\n * already close to the 104 byte limit macOS puts on a unix socket path\n */\n\nimport { createHash } from 'node:crypto';\nimport { mkdirSync, rmSync } from 'node:fs';\nimport { createConnection, createServer, type Server } from 'node:net';\nimport { join } from 'node:path';\n\nimport type { WorkflowNativeTerminal as NativeTerminalService } from '../NativeTerminalService/types';\nimport type { NativeTerminalViewer } from '../NativeTerminalService/types';\n\nconst SOCKET_DIR_NAME = 'workflow-mcp-terminals';\nconst SOCKET_EXTENSION = '.sock';\nconst HASH_LENGTH = 24;\nconst REQUEST_TIMEOUT_MS = 2_000;\n/** Geometry a reader gets before it has said how much room it has. */\nconst DEFAULT_COLUMNS = 120;\nconst DEFAULT_ROWS = 40;\n\nexport type TerminalSocketOp = 'snapshot' | 'write' | 'resize';\n\nexport interface TerminalSocketRequest {\n op: TerminalSocketOp;\n data?: string;\n columns?: number;\n rows?: number;\n}\n\nexport interface TerminalSocketResponse {\n ok: boolean;\n lines?: string[];\n error?: string;\n}\n\n/**\n * Where one run's socket lives.\n *\n * Hashed and under the temp directory because the obvious home, the run's own\n * directory, is far past what a unix socket path may be: a workspace and a run\n * key nested under the registry root routinely exceed 104 bytes, and binding\n * fails with a message that names neither.\n */\nexport function terminalSocketPath(workspace: string, runKey: string, root: string): string {\n const digest = createHash('sha256').update(`${workspace}/${runKey}`).digest('hex').slice(0, HASH_LENGTH);\n return join(root, SOCKET_DIR_NAME, `${digest}${SOCKET_EXTENSION}`);\n}\n\nexport interface ServeTerminalOptions {\n service: NativeTerminalService;\n runKey: string;\n socketPath: string;\n onNotice?: (message: string) => void;\n}\n\nexport interface TerminalSocketServer {\n close(): Promise<void>;\n}\n\n/**\n * Serves one hosted run on a unix socket.\n *\n * The viewer is created on the first request rather than at bind time: a run\n * nobody ever opens should cost a socket file and nothing else.\n */\nexport async function serveNativeTerminal(options: ServeTerminalOptions): Promise<TerminalSocketServer> {\n const notice = options.onNotice ?? ((): void => {});\n let viewer: NativeTerminalViewer | undefined;\n\n const answer = async (request: TerminalSocketRequest): Promise<TerminalSocketResponse> => {\n if (viewer === undefined) {\n viewer = await options.service.attach(\n options.runKey,\n request.columns ?? DEFAULT_COLUMNS,\n request.rows ?? DEFAULT_ROWS,\n );\n }\n if (request.op === 'write') {\n await viewer.write(request.data ?? '');\n return { ok: true };\n }\n if (request.op === 'resize') {\n await viewer.resize(request.columns ?? DEFAULT_COLUMNS, request.rows ?? DEFAULT_ROWS);\n return { ok: true };\n }\n if (request.columns !== undefined && request.rows !== undefined) {\n await viewer.resize(request.columns, request.rows);\n }\n return { ok: true, lines: await viewer.snapshot() };\n };\n\n const server = createServer((socket) => {\n let buffered = '';\n socket.on('data', (chunk: Buffer) => {\n buffered += chunk.toString();\n let newline = buffered.indexOf('\\n');\n while (newline !== -1) {\n const line = buffered.slice(0, newline);\n buffered = buffered.slice(newline + 1);\n void handle(line);\n newline = buffered.indexOf('\\n');\n }\n });\n // A reader that goes away mid-request is ordinary; the run does not care.\n socket.on('error', () => socket.destroy());\n\n const handle = async (line: string): Promise<void> => {\n let response: TerminalSocketResponse;\n try {\n response = await answer(JSON.parse(line) as TerminalSocketRequest);\n } catch (error) {\n response = { ok: false, error: error instanceof Error ? error.message : String(error) };\n }\n if (socket.writable) socket.write(`${JSON.stringify(response)}\\n`);\n };\n });\n\n mkdirSync(join(options.socketPath, '..'), { recursive: true });\n // A socket left by a host that died would refuse the bind; nothing else owns\n // this path, since it is derived from the run's identity.\n rmSync(options.socketPath, { force: true });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(options.socketPath, () => {\n server.removeListener('error', reject);\n resolve();\n });\n });\n server.on('error', (error) => notice(`terminal socket for ${options.runKey}: ${error.message}`));\n\n return {\n close: () =>\n new Promise<void>((resolve) => {\n viewer?.detach();\n viewer = undefined;\n closeServer(server, options.socketPath, resolve);\n }),\n };\n}\n\nfunction closeServer(server: Server, socketPath: string, done: () => void): void {\n server.close(() => {\n rmSync(socketPath, { force: true });\n done();\n });\n}\n\n/** One request over a fresh connection, or a rejection naming what went wrong. */\nfunction request(socketPath: string, body: TerminalSocketRequest): Promise<TerminalSocketResponse> {\n return new Promise((resolve, reject) => {\n const socket = createConnection(socketPath);\n let buffered = '';\n const finish = (error?: Error, response?: TerminalSocketResponse): void => {\n socket.destroy();\n if (error) reject(error);\n else if (response) resolve(response);\n };\n const timer = setTimeout(\n () => finish(new Error(`The run's terminal did not answer within ${REQUEST_TIMEOUT_MS}ms.`)),\n REQUEST_TIMEOUT_MS,\n );\n timer.unref?.();\n socket.on('connect', () => socket.write(`${JSON.stringify(body)}\\n`));\n socket.on('data', (chunk: Buffer) => {\n buffered += chunk.toString();\n const newline = buffered.indexOf('\\n');\n if (newline === -1) return;\n clearTimeout(timer);\n try {\n finish(undefined, JSON.parse(buffered.slice(0, newline)) as TerminalSocketResponse);\n } catch (error) {\n finish(error instanceof Error ? error : new Error(String(error)));\n }\n });\n socket.on('error', (error) => {\n clearTimeout(timer);\n finish(error);\n });\n });\n}\n\n/**\n * The reader's half: a bridge over one run's socket, shaped for the terminal\n * facade so a natively hosted run reads like any other launcher.\n */\nexport function connectNativeTerminal(): {\n snapshot(socketPath: string, options: { lines?: number }): Promise<string[]>;\n write(socketPath: string, data: string): Promise<void>;\n resize(socketPath: string, columns: number, rows: number): Promise<void>;\n} {\n return {\n async snapshot(socketPath, options) {\n const response = await request(socketPath, { op: 'snapshot' });\n if (!response.ok) throw new Error(response.error ?? 'The run refused to answer.');\n const lines = response.lines ?? [];\n return options.lines === undefined ? lines : lines.slice(-options.lines);\n },\n async write(socketPath, data) {\n const response = await request(socketPath, { op: 'write', data });\n if (!response.ok) throw new Error(response.error ?? 'The run refused the keystrokes.');\n },\n async resize(socketPath, columns, rows) {\n const response = await request(socketPath, { op: 'resize', columns, rows });\n if (!response.ok) throw new Error(response.error ?? 'The run refused the resize.');\n },\n };\n}\n","import { execFileSync, spawn } from 'node:child_process';\nimport { constants } from 'node:fs';\nimport { chmod, link, open, writeFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport { createInterface } from 'node:readline';\n\nimport { lock } from 'proper-lockfile';\n\nimport { NativeTerminalService } from './nativeTerminal';\nimport { serveNativeTerminal, connectNativeTerminal } from './terminalSocket';\nimport type { WorkflowArtifactFile, WorkflowHost, WorkflowHostOptions } from './type';\n\nexport { PO_WORKFLOW_HOST_SERVICE, requirePoWorkflowHost } from './contract';\n\nexport function resolveWorkflowCliPath(): string {\n const manifest = createRequire(import.meta.url).resolve('@agimon-ai/po-workflow/package.json');\n return join(dirname(manifest), 'dist', 'cli.cjs');\n}\n\nexport function readWorkflowPackageVersion(): string {\n return (createRequire(import.meta.url)('@agimon-ai/po-workflow/package.json') as { version: string }).version;\n}\n\n/** Node implementation of the exceptional native workflow operations. */\nexport function createWorkflowHost(options: WorkflowHostOptions): WorkflowHost {\n options = { ...options, environment: Object.freeze({ ...options.environment }) };\n return Object.freeze<WorkflowHost>({\n processId: process.pid,\n executablePath: process.execPath,\n platform: process.platform,\n isElectron: Boolean(process.versions.electron),\n writeStdout: (text) => {\n process.stdout.write(text);\n },\n writeStderr: (text) => {\n process.stderr.write(text);\n },\n onSignal: (signal, listener) => {\n process.on(signal, listener);\n return () => {\n process.off(signal, listener);\n };\n },\n cliPath: options.cliPath,\n portRegistry: {\n reservePort: (request) => registryOperation(options, 'reservePort', request),\n releasePort: (request) => registryOperation(options, 'releasePort', request),\n },\n processRegistry: {\n registerProcess: (request) => registryOperation(options, 'registerProcess', request),\n releaseProcess: (request) => registryOperation(options, 'releaseProcess', request),\n },\n createTerminal: (dependencies) => new NativeTerminalService(options, dependencies),\n serveTerminal: serveNativeTerminal,\n connectTerminal: connectNativeTerminal,\n createPrompt: () => createInterface({ input: process.stdin, output: process.stdout }),\n openArtifact,\n writeExclusive: (path: string, content: string | Uint8Array) =>\n writeFile(path, content, { flag: 'wx', mode: 0o600 }),\n publishExclusive: (source: string, destination: string) => link(source, destination),\n acquireRecoveryLock: (path: string, lockOptions: Parameters<typeof lock>[1]) => lock(path, lockOptions),\n setMode: (path: string, mode: number) => chmod(path, mode),\n spawn: (command: string, args: readonly string[], spawnOptions: Parameters<WorkflowHost['spawn']>[2]) =>\n spawn(command, [...args], spawnOptions),\n signal: (processId: number, signal: NodeJS.Signals | 0) => process.kill(processId, signal),\n inspectProcesses: (columns: 'command' | 'parents' | 'groups', processId?: number) => {\n const args =\n columns === 'command'\n ? ['-p', String(processId), '-o', 'command=']\n : ['-axo', columns === 'parents' ? 'pid=,ppid=' : 'pid=,pgid='];\n return execFileSync('ps', args, {\n cwd: options.cwd,\n env: options.environment,\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n },\n readTerminalState: () => {\n try {\n return execFileSync('stty', ['-g'], {\n cwd: options.cwd,\n env: options.environment,\n encoding: 'utf-8',\n stdio: ['inherit', 'pipe', 'ignore'],\n }).trim();\n } catch {\n return undefined;\n }\n },\n restoreTerminalState: (state?: string) => {\n if (state)\n execFileSync('stty', [state], {\n cwd: options.cwd,\n env: options.environment,\n stdio: ['inherit', 'ignore', 'ignore'],\n });\n if (process.stdout.isTTY) process.stdout.write('\\x1b[0m\\x1b[?25h\\x1b[?1049l');\n },\n });\n}\n\nasync function openArtifact(path: string): Promise<WorkflowArtifactFile | undefined> {\n let file: Awaited<ReturnType<typeof open>>;\n try {\n file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);\n } catch (error) {\n if (\n error instanceof Error &&\n 'code' in error &&\n ['ENOENT', 'ENOTDIR', 'ELOOP', 'EACCES', 'EPERM'].includes(String(error.code))\n )\n return undefined;\n throw error;\n }\n let closed = false;\n const close = async (): Promise<void> => {\n if (closed) return;\n closed = true;\n await file.close();\n };\n try {\n const snapshot = await file.stat();\n if (!snapshot.isFile()) {\n await close();\n return undefined;\n }\n const identity = (stat: typeof snapshot): string =>\n `\"${stat.dev}-${stat.ino}-${stat.size}-${stat.mtimeMs}-${stat.ctimeMs}\"`;\n const version = identity(snapshot);\n const unchanged = async (): Promise<boolean> => !closed && identity(await file.stat()) === version;\n const readRange = async (start: number, end: number): Promise<Uint8Array | undefined> => {\n if (\n !Number.isSafeInteger(start) ||\n !Number.isSafeInteger(end) ||\n start < 0 ||\n end < start ||\n end >= snapshot.size\n )\n return undefined;\n if (!(await unchanged())) return undefined;\n const bytes = new Uint8Array(end - start + 1);\n let offset = 0;\n while (offset < bytes.length) {\n const read = await file.read(bytes, offset, bytes.length - offset, start + offset);\n if (read.bytesRead === 0) return undefined;\n offset += read.bytesRead;\n }\n return (await unchanged()) ? bytes : undefined;\n };\n return {\n size: snapshot.size,\n modifiedAt: snapshot.mtime.toUTCString(),\n version,\n readRange,\n stream: (start, end) => {\n let position = start;\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n if (position > end) {\n if (!(await unchanged())) throw new Error('Workflow artifact changed while streaming.');\n await close();\n controller.close();\n return;\n }\n const next = Math.min(end, position + 65_536 - 1);\n const bytes = await readRange(position, next);\n if (bytes === undefined) throw new Error('Workflow artifact changed while streaming.');\n position = next + 1;\n controller.enqueue(bytes);\n } catch (error) {\n await close();\n controller.error(error);\n }\n },\n cancel: close,\n });\n },\n close,\n };\n } catch (error) {\n await close();\n throw error;\n }\n}\n\n/** Foundation registries admit process environment internally, so isolate that admission per invocation. */\nasync function registryOperation<T>(\n options: WorkflowHostOptions,\n operation: 'reservePort' | 'releasePort' | 'registerProcess' | 'releaseProcess',\n request: unknown,\n): Promise<T> {\n const requirePackage = createRequire(import.meta.url);\n const portModule = requirePackage.resolve('@agimon-ai/foundation-port-registry');\n const processModule = requirePackage.resolve('@agimon-ai/foundation-process-registry');\n const source = `\n const { PortRegistryService } = require(${JSON.stringify(portModule)});\n const { ProcessRegistryService } = require(${JSON.stringify(processModule)});\n let input = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', chunk => { input += chunk; });\n process.stdin.on('end', async () => {\n try {\n const { operation, request, portRegistryPath, processRegistryPath } = JSON.parse(input);\n const ports = new PortRegistryService(portRegistryPath);\n const processes = new ProcessRegistryService(processRegistryPath);\n const registry = operation === 'reservePort' || operation === 'releasePort' ? ports : processes;\n const result = await registry[operation](request);\n process.stdout.write(JSON.stringify(result));\n } catch (error) { console.error(error); process.exitCode = 1; }\n });\n `;\n return await new Promise<T>((resolve, reject) => {\n const child = spawn(process.execPath, ['-e', source], {\n cwd: options.cwd,\n env: {\n ...options.environment,\n HOME: options.homeDirectory,\n ...(options.temporaryDirectory === undefined ? {} : { TMPDIR: options.temporaryDirectory }),\n },\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n let output = '';\n let errors = '';\n const timeout = setTimeout(() => child.kill('SIGKILL'), 15_000);\n child.stdout.on('data', (chunk: Buffer) => {\n output += chunk.toString('utf8');\n if (output.length > 1_048_576) child.kill('SIGKILL');\n });\n child.stderr.on('data', (chunk: Buffer) => {\n errors = (errors + chunk.toString('utf8')).slice(-65_536);\n });\n child.once('error', (error) => {\n clearTimeout(timeout);\n reject(error);\n });\n child.once('close', (code) => {\n clearTimeout(timeout);\n if (code !== 0) {\n reject(new Error(`Workflow ${operation} failed: ${errors}`));\n return;\n }\n try {\n resolve(JSON.parse(output) as T);\n } catch (error) {\n reject(error);\n }\n });\n child.stdin.end(\n JSON.stringify({\n operation,\n request,\n portRegistryPath: options.environment.PORT_REGISTRY_PATH,\n processRegistryPath: options.environment.PROCESS_REGISTRY_PATH,\n }),\n );\n });\n}\n","import { createHash } from 'node:crypto';\nimport { join } from 'node:path';\n\nimport { nodeHost } from '@agimon-ai/po-core/platform';\n\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport type { WorkflowNativeTerminal } from './types';\n\nexport interface ServeTerminalOptions {\n service: WorkflowNativeTerminal;\n runKey: string;\n socketPath: string;\n onNotice?: (message: string) => void;\n}\nexport interface TerminalSocketServer {\n close(): Promise<void>;\n}\nexport type TerminalSocketOp = 'snapshot' | 'write' | 'resize';\nexport interface TerminalSocketRequest {\n op: TerminalSocketOp;\n data?: string;\n columns?: number;\n rows?: number;\n}\nexport interface TerminalSocketResponse {\n ok: boolean;\n lines?: string[];\n error?: string;\n}\n\n/** Unix socket paths are capped at 104 bytes on macOS; a long admitted root falls back to the host temp dir. */\nconst SOCKET_PATH_LIMIT = 100;\n\nexport function terminalSocketPath(workspace: string, runKey: string, root: string): string {\n const digest = createHash('sha256').update(`${workspace}/${runKey}`).digest('hex').slice(0, 24);\n const preferred = join(root, 'workflow-mcp-terminals', `${digest}.sock`);\n if (Buffer.byteLength(preferred) <= SOCKET_PATH_LIMIT) return preferred;\n return join(nodeHost.temporaryDirectory(), `workflow-mcp-${digest}.sock`);\n}\nexport function serveNativeTerminal(\n runtime: WorkflowRuntimeContext,\n options: ServeTerminalOptions,\n): Promise<TerminalSocketServer> {\n return runtime.workflowHost.serveTerminal(options);\n}\nexport function connectNativeTerminal(runtime: WorkflowRuntimeContext) {\n return runtime.workflowHost.connectTerminal();\n}\n","import type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport type { NativeTerminalDependencies, NativeTerminalSpawnInput, WorkflowNativeTerminal } from './types';\n\n/** Portable facade. The injected host owns RMUX and its native process handles. */\nexport class NativeTerminalService implements WorkflowNativeTerminal {\n private readonly terminal: WorkflowNativeTerminal;\n\n constructor(runtime: WorkflowRuntimeContext, dependencies: NativeTerminalDependencies = {}) {\n this.terminal = runtime.workflowHost.createTerminal(dependencies);\n }\n\n available() {\n return this.terminal.available();\n }\n spawn(input: NativeTerminalSpawnInput) {\n return this.terminal.spawn(input);\n }\n isHosted(runKey: string) {\n return this.terminal.isHosted(runKey);\n }\n exitOf(runKey: string) {\n return this.terminal.exitOf(runKey);\n }\n ended(runKey: string) {\n return this.terminal.ended(runKey);\n }\n viewerCount(runKey: string) {\n return this.terminal.viewerCount(runKey);\n }\n attach(runKey: string, columns: number, rows: number) {\n return this.terminal.attach(runKey, columns, rows);\n }\n kill(runKey: string) {\n return this.terminal.kill(runKey);\n }\n disposeAll() {\n return this.terminal.disposeAll();\n }\n}\n","import { createHash } from 'node:crypto';\nimport { dirname, relative, resolve } from 'node:path';\n\nimport { createSerialRunner, type SerialRunner, getOrThrow } from '@agimon-ai/po-core/platform';\n\nimport type { RunDirectory, RunDirectoryEntry } from '../../schemas/workflowEngine';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport type {\n RunDirectoryInspectedEntry,\n RunDirectoryInspection,\n RunDirectoryInspectOptions,\n RunDirectoryEntryState,\n RunDirectorySnapshot,\n RunDirectoryWrite,\n RunDirectoryWriter,\n StepArtifactSnapshot,\n StepArtifactWarning,\n} from './types';\n\n/** Which job and step last wrote each declared entry, one change per line. */\nexport const RUN_DIRECTORY_WRITES_FILENAME = 'writes.ndjson';\nconst MISSING_STATE = 'missing';\n/** Writes to one run's records, in order: steps of a parallel group finish together. */\n\nconst BUILT_IN_ENTRIES: RunDirectoryEntry[] = [\n {\n path: 'run.json',\n kind: 'file',\n description: 'Runner-owned workflow identity, lifecycle, recovery, and resolved run-directory declaration.',\n },\n {\n path: 'context.md',\n kind: 'file',\n description: 'Runner-owned user prompt and durable repair references.',\n },\n {\n path: 'changelog.md',\n kind: 'file',\n description: 'Shared append-only handoff log maintained by workflow jobs.',\n },\n {\n path: 'fix.md',\n kind: 'file',\n description: 'Ephemeral repair request consumed and archived by the runner.',\n },\n {\n path: 'proceed.md',\n kind: 'file',\n description: 'Ephemeral forward-jump request consumed by the runner during an active repair.',\n },\n {\n path: 'issues',\n kind: 'directory',\n description: 'Runner-owned durable issue and repair records.',\n },\n {\n path: 'decisions',\n kind: 'directory',\n description: 'Runner-owned step decisions recorded through workflow-mcp step.',\n },\n {\n path: 'bin',\n kind: 'directory',\n description: 'Runner-owned workflow-mcp launcher that agents call to record step decisions.',\n },\n {\n path: RUN_DIRECTORY_WRITES_FILENAME,\n kind: 'file',\n description: 'Runner-owned record of which job and step last wrote each declared entry.',\n },\n];\n\nconst UNREADABLE_FINGERPRINT = 'inaccessible';\n\nexport class RunDirectoryService {\n constructor(\n readonly runtime: WorkflowRuntimeContext,\n private readonly recording: SerialRunner = createSerialRunner(),\n ) {}\n\n async materialize(runDir: string, declaration: RunDirectory | undefined, dryRun = false): Promise<void> {\n if (!declaration || dryRun) return;\n\n const directories = declaration.entries\n .filter((entry) => entry.kind === 'directory')\n .sort((left, right) => left.path.split('/').length - right.path.split('/').length);\n for (const entry of directories) {\n getOrThrow(\n await this.runtime.fs.createDir(\n this.resolveEntryPath(runDir, entry.path),\n { recursive: true },\n this.runtime.ioContext,\n ),\n );\n }\n\n for (const entry of declaration.entries.filter((candidate) => candidate.kind === 'file')) {\n const targetPath = this.resolveEntryPath(runDir, entry.path);\n getOrThrow(await this.runtime.fs.createDir(dirname(targetPath), { recursive: true }, this.runtime.ioContext));\n try {\n await this.runtime.workflowHost.writeExclusive(targetPath, entry['initial-content'] ?? '');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n }\n }\n\n async inspect(\n runDir: string,\n declaration: RunDirectory | undefined,\n options: RunDirectoryInspectOptions = {},\n ): Promise<RunDirectoryInspection> {\n const declaredEntries = declaration?.entries ?? [];\n const entries = await Promise.all(\n [...BUILT_IN_ENTRIES, ...declaredEntries].map(async (entry) =>\n this.inspectEntry(runDir, entry, declaration, options),\n ),\n );\n return {\n description: declaration?.description ?? 'Workflow run files managed by workflow-mcp.',\n entries,\n jobName: options.jobName,\n runDir,\n };\n }\n\n snapshot(inspection: RunDirectoryInspection): RunDirectorySnapshot {\n return {\n fingerprints: Object.fromEntries(inspection.entries.map((entry) => [entry.path, entry.fingerprint])),\n };\n }\n\n async snapshotStepArtifacts(runDir: string, paths: string[]): Promise<StepArtifactSnapshot[]> {\n return Promise.all(\n paths.map(async (path) => {\n const targetPath = this.resolveEntryPath(runDir, path);\n try {\n const stats = getOrThrow(await this.runtime.fs.fileInfo(targetPath, this.runtime.ioContext));\n if (stats.kind !== 'file') return { path };\n return { fingerprint: await this.fingerprint(targetPath, 'file'), path };\n } catch {\n return { path };\n }\n }),\n );\n }\n\n async findStepArtifactWarnings(runDir: string, snapshots: StepArtifactSnapshot[]): Promise<StepArtifactWarning[]> {\n const warnings = await Promise.all(\n snapshots.map(async (snapshot): Promise<StepArtifactWarning | null> => {\n const status = await this.stepArtifactStatus(runDir, snapshot);\n if (status === undefined) return null;\n return {\n path: snapshot.path,\n status,\n ...(snapshot.description === undefined ? {} : { description: snapshot.description }),\n };\n }),\n );\n return warnings.filter((warning): warning is StepArtifactWarning => warning !== null);\n }\n\n /** What is wrong with one artifact, or undefined once it was written. */\n private async stepArtifactStatus(\n runDir: string,\n snapshot: StepArtifactSnapshot,\n ): Promise<StepArtifactWarning['status'] | undefined> {\n // A job's output is written once anything changed since the job began, removal included.\n if (snapshot.job !== undefined) {\n const state = await this.entryState(runDir, snapshot.path, snapshot.kind ?? 'file');\n if (state.sha === UNREADABLE_FINGERPRINT) return 'inaccessible';\n return state.sha === snapshot.fingerprint && state.mtimeMs === snapshot.mtimeMs ? 'unchanged' : undefined;\n }\n const targetPath = this.resolveEntryPath(runDir, snapshot.path);\n try {\n const stats = getOrThrow(await this.runtime.fs.fileInfo(targetPath, this.runtime.ioContext));\n if (stats.kind !== 'file') return 'inaccessible';\n if (stats.size === 0) return 'empty';\n return (await this.fingerprint(targetPath, 'file')) === snapshot.fingerprint ? 'unchanged' : undefined;\n } catch (error) {\n return ['ENOENT', 'not_found'].includes(String((error as { code?: string }).code)) ? 'missing' : 'inaccessible';\n }\n }\n\n /** What an entry holds now. */\n async entryState(runDir: string, path: string, kind: RunDirectoryEntry['kind']): Promise<RunDirectoryEntryState> {\n const targetPath = this.resolveEntryPath(runDir, path);\n try {\n const stats = getOrThrow(await this.runtime.fs.fileInfo(targetPath, this.runtime.ioContext));\n if (kind === 'directory' ? stats.kind !== 'directory' : stats.kind !== 'file') {\n return { sha: `incompatible:${stats.kind}`, mtimeMs: stats.mtimeMs };\n }\n return { sha: await this.fingerprint(targetPath, kind), mtimeMs: stats.mtimeMs };\n } catch (error) {\n return {\n sha: ['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))\n ? MISSING_STATE\n : UNREADABLE_FINGERPRINT,\n };\n }\n }\n\n /** Every write recorded in a run, oldest first. A line that does not parse is skipped. */\n async readWrites(runDir: string): Promise<RunDirectoryWrite[]> {\n let text: string;\n try {\n text = getOrThrow(\n await this.runtime.fs.readTextFile(resolve(runDir, RUN_DIRECTORY_WRITES_FILENAME), this.runtime.ioContext),\n );\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) return [];\n throw error;\n }\n return text.split('\\n').flatMap((line) => {\n if (line.trim().length === 0) return [];\n try {\n return [JSON.parse(line) as RunDirectoryWrite];\n } catch {\n return [];\n }\n });\n }\n\n /**\n * Record each entry that changed since its last record, as written by\n * `writer`: new content, the same content rewritten, or its removal. Without\n * a writer, the change happened outside any step. Returns every record of\n * the run, oldest first, the new ones last.\n */\n async recordWrites(\n runDir: string,\n entries: readonly Pick<RunDirectoryEntry, 'path' | 'kind'>[],\n writer?: RunDirectoryWriter,\n ): Promise<RunDirectoryWrite[]> {\n const key = resolve(runDir);\n return await this.recording.forKey(key)(() => this.appendWrites(runDir, entries, writer));\n }\n\n private async appendWrites(\n runDir: string,\n entries: readonly Pick<RunDirectoryEntry, 'path' | 'kind'>[],\n writer: RunDirectoryWriter | undefined,\n ): Promise<RunDirectoryWrite[]> {\n const records = await this.readWrites(runDir);\n const latest = new Map(records.map((record) => [record.path, record]));\n const at = new Date().toISOString();\n const changes: RunDirectoryWrite[] = [];\n for (const entry of entries) {\n const state = await this.entryState(runDir, entry.path, entry.kind);\n const last = latest.get(entry.path);\n if (last && last.sha === state.sha && last.mtimeMs === state.mtimeMs) continue;\n changes.push({ path: entry.path, ...state, ...writer, at });\n }\n if (changes.length > 0) {\n getOrThrow(\n await this.runtime.fs.appendFile(\n resolve(runDir, RUN_DIRECTORY_WRITES_FILENAME),\n changes.map((change) => `${JSON.stringify(change)}\\n`).join(''),\n this.runtime.ioContext,\n ),\n );\n }\n return [...records, ...changes];\n }\n\n formatInspection(inspection: RunDirectoryInspection): string {\n const jobSuffix = inspection.jobName ? ` for job ${inspection.jobName}` : '';\n const lines = [`Workflow run directory${jobSuffix}: ${inspection.runDir}`, inspection.description, ''];\n for (const entry of inspection.entries) {\n const producers = entry.producedBy.length > 0 ? `, produced by ${entry.producedBy.join(', ')}` : '';\n lines.push(\n `- [${entry.status}] ${entry.path} (${entry.kind}, ${entry.relation}${producers}): ${entry.description}`,\n );\n }\n lines.push('', 'Refresh this view with: workflow-mcp describe-run --run-dir \"$WORKFLOW_RUN_DIR\"');\n lines.push(\n `Each job must write the entries it produces before it ends (new content, a rewrite, or removal), or the job fails. ${RUN_DIRECTORY_WRITES_FILENAME} records which job and step last wrote each entry.`,\n );\n return lines.join('\\n');\n }\n\n private async inspectEntry(\n runDir: string,\n entry: RunDirectoryEntry,\n declaration: RunDirectory | undefined,\n options: RunDirectoryInspectOptions,\n ): Promise<RunDirectoryInspectedEntry> {\n const builtIn = BUILT_IN_ENTRIES.some((candidate) => candidate.path === entry.path);\n const producedBy = entry['produced-by'] ?? [];\n const relation = builtIn ? 'built-in' : this.resolveRelation(producedBy, options.jobName, options.jobOrder);\n if (options.planned && !builtIn) {\n return {\n description: entry.description,\n kind: entry.kind,\n path: entry.path,\n producedBy,\n relation,\n status: 'missing',\n };\n }\n\n const targetPath = this.resolveEntryPath(runDir, entry.path);\n try {\n getOrThrow(await this.runtime.fs.fileInfo(targetPath, this.runtime.ioContext));\n const stats = getOrThrow(await this.runtime.fs.fileInfo(targetPath, this.runtime.ioContext));\n if (\n (entry.kind === 'file' && stats.kind !== 'file') ||\n (entry.kind === 'directory' && stats.kind !== 'directory')\n ) {\n return {\n description: entry.description,\n fingerprint: `incompatible:${stats.kind}`,\n kind: entry.kind,\n path: entry.path,\n producedBy,\n relation,\n status: 'incompatible',\n };\n }\n const fingerprint = await this.fingerprint(targetPath, entry.kind);\n const status = await this.resolveStatus(targetPath, entry, declaration, builtIn, fingerprint);\n return {\n description: entry.description,\n fingerprint,\n kind: entry.kind,\n path: entry.path,\n producedBy,\n relation,\n status,\n };\n } catch (error) {\n const status = ['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))\n ? 'missing'\n : 'inaccessible';\n return {\n description: entry.description,\n fingerprint: status === 'inaccessible' ? UNREADABLE_FINGERPRINT : undefined,\n kind: entry.kind,\n path: entry.path,\n producedBy,\n relation,\n status,\n };\n }\n }\n\n private resolveRelation(producedBy: string[], jobName?: string, jobOrder?: string[]) {\n if (!jobName || producedBy.length === 0) return 'shared' as const;\n if (producedBy.includes(jobName)) return 'output' as const;\n const currentIndex = jobOrder?.indexOf(jobName) ?? -1;\n const producerIndexes = producedBy.map((producer) => jobOrder?.indexOf(producer) ?? -1);\n return producerIndexes.some((index) => index >= 0 && index < currentIndex)\n ? ('input' as const)\n : ('future' as const);\n }\n\n private async resolveStatus(\n targetPath: string,\n entry: RunDirectoryEntry,\n declaration: RunDirectory | undefined,\n builtIn: boolean,\n fingerprint: string,\n ) {\n if (entry.kind === 'directory') {\n return getOrThrow(await this.runtime.fs.listDir(targetPath, this.runtime.ioContext)).map((entry) => entry.name)\n .length === 0\n ? ('empty' as const)\n : ('populated' as const);\n }\n if (builtIn && !declaration?.entries.some((candidate) => candidate.path === entry.path)) {\n return getOrThrow(await this.runtime.fs.readBinaryFile(targetPath, this.runtime.ioContext)).length === 0\n ? ('empty' as const)\n : ('populated' as const);\n }\n const initialFingerprint = this.hash(entry['initial-content'] ?? '');\n return fingerprint === initialFingerprint ? ('initial' as const) : ('populated' as const);\n }\n\n private async fingerprint(targetPath: string, kind: RunDirectoryEntry['kind']): Promise<string> {\n if (kind === 'file')\n return this.hash(getOrThrow(await this.runtime.fs.readBinaryFile(targetPath, this.runtime.ioContext)));\n const names = getOrThrow(await this.runtime.fs.listDir(targetPath, this.runtime.ioContext)).map(\n (entry) => entry.name,\n );\n return this.hash(names.sort().join('\\n'));\n }\n\n private hash(value: string | Uint8Array): string {\n return createHash('sha256').update(value).digest('hex');\n }\n\n private resolveEntryPath(runDir: string, entryPath: string): string {\n const targetPath = resolve(runDir, entryPath);\n const relativePath = relative(resolve(runDir), targetPath);\n if (relativePath.startsWith('..') || relativePath === '') {\n throw new Error(`Unsafe workflow run-directory path: ${entryPath}`);\n }\n return targetPath;\n }\n}\n","/**\n * StepDecisionService\n *\n * DESIGN PATTERNS:\n * - Single owner of the step decision file and the text agents are steered with\n * - Pure functions over a file path, so the engine, the `step` CLI, stop hooks\n * and host executors all read and write one format\n *\n * CODING STANDARDS:\n * - Write the decision file atomically; a hook and the CLI may touch it in turn\n * - Never throw from the gate: an unreadable file lets the agent stop\n *\n * AVOID:\n * - Deciding workflow routing here; the engine consumes decisions at job end\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { join } from 'node:path';\n\nimport { getOrThrow, pathExists, writeFileAtomic } from '@agimon-ai/po-core/platform';\n\nimport { StepDecisionFileSchema } from '../../schemas/workflowEngine';\nimport type { StepDecision, StepDecisionFile } from '../../schemas/workflowEngine';\nimport { RunDirectoryService } from '../RunDirectoryService';\nimport { type StepArtifactSnapshot } from '../RunDirectoryService/types';\nimport type { StepDecisionReport } from '../workflowEngine/type';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\n/** Per-attempt decision file of the running step. */\nexport const WORKFLOW_DECISION_FILE_ENV = 'WORKFLOW_DECISION_FILE';\n/** What the job tells its agents about recording a decision; set on every job with a run directory. */\nexport const WORKFLOW_DECISION_INSTRUCTIONS_ENV = 'WORKFLOW_DECISION_INSTRUCTIONS';\n/** Comma-separated jobs a fix may restart from; empty when this job cannot request a fix. */\nexport const WORKFLOW_RESTART_TARGETS_ENV = 'WORKFLOW_RESTART_TARGETS';\n/** How many times a stop is refused for a missing decision before the agent may stop anyway. */\nexport const WORKFLOW_DECISION_NUDGE_CAP_ENV = 'WORKFLOW_DECISION_NUDGE_CAP';\n/** Set to `host` in a session whose host steers it itself, so stop hooks inside it stand down. */\nexport const WORKFLOW_DECISION_STEERING_ENV = 'WORKFLOW_DECISION_STEERING';\nexport const WORKFLOW_DECISION_STEERING_HOST = 'host';\n\nconst DECISIONS_DIRECTORY = 'decisions';\nconst FIX_FILENAME = 'fix.md';\nconst FRONTMATTER_RESTART_FROM = /^---\\s*\\n[\\s\\S]*?^restart-from:\\s*(\\S+)\\s*$[\\s\\S]*?^---\\s*$/m;\nconst DECISION_FILE_SUFFIX = '.json';\nconst WORKFLOW_RUN_DIR_ENV = 'WORKFLOW_RUN_DIR';\nconst WORKFLOW_STEP_ARTIFACTS_ENV = 'WORKFLOW_STEP_ARTIFACTS';\nconst DEFAULT_NUDGE_CAP = 3;\n/** Stays below Claude Code's own limit of 8 blocked stops in a row. */\nconst MAX_NUDGE_CAP = 7;\n\nexport type StepDecisionGate = { action: 'allow' } | { action: 'block'; message: string };\n\n/** The command an agent runs, as it can reach it whatever its PATH. */\nexport function workflowCliPath(runDir: string): string {\n return join(runDir, 'bin', 'workflow-mcp');\n}\n\n/** Where a step's decision file will live; decided before the step's prompt is rendered, which names it. */\nexport function newDecisionFilePath(runDir: string): string {\n return join(runDir, DECISIONS_DIRECTORY, `${randomUUID()}${DECISION_FILE_SUFFIX}`);\n}\n\n/** Start a fresh decision file for one attempt of a step. */\nexport async function createDecisionFile(\n runtime: WorkflowRuntimeContext,\n runDir: string,\n step: { job: string; step: string; restartTargets: string[]; required: boolean },\n path: string = newDecisionFilePath(runDir),\n): Promise<string> {\n getOrThrow(await runtime.fs.createDir(join(runDir, DECISIONS_DIRECTORY), { recursive: true }, runtime.ioContext));\n await resetDecisionFile(runtime, path, step);\n return path;\n}\n\n/** Clear a decision file for another attempt, keeping its step identity. */\nexport async function resetDecisionFile(\n runtime: WorkflowRuntimeContext,\n path: string,\n step: { job: string; step: string; restartTargets: string[]; required: boolean },\n): Promise<void> {\n await writeDecisionFile(runtime, path, { schemaVersion: 1, ...step, nudges: 0 });\n}\n\nexport async function readDecisionFile(\n runtime: WorkflowRuntimeContext,\n path: string,\n): Promise<StepDecisionFile | undefined> {\n try {\n return StepDecisionFileSchema.parse(JSON.parse(getOrThrow(await runtime.fs.readTextFile(path, runtime.ioContext))));\n } catch {\n return undefined;\n }\n}\n\nexport async function readStepDecision(\n runtime: WorkflowRuntimeContext,\n path: string,\n): Promise<StepDecision | undefined> {\n return (await readDecisionFile(runtime, path))?.decision;\n}\n\n/**\n * Record what an agent decided, replacing any earlier decision of this attempt.\n * A fix must name a job this step may restart from; the error lists them.\n */\nexport async function recordStepDecision(\n runtime: WorkflowRuntimeContext,\n path: string,\n decision: StepDecision,\n): Promise<StepDecisionFile> {\n if (!(await pathExists(runtime.fs, path, runtime.ioContext))) {\n throw new Error(`No workflow step is waiting for a decision at ${path}.`);\n }\n const file = await readDecisionFile(runtime, path);\n if (!file) {\n throw new Error(`The workflow decision file ${path} is unreadable.`);\n }\n if (decision.decision === 'fix' && !file.restartTargets.includes(decision.restartFrom)) {\n throw new Error(\n file.restartTargets.length === 0\n ? `Job \"${file.job}\" cannot request a fix. Use \"workflow-mcp step fail\" if it cannot finish.`\n : `\"${decision.restartFrom}\" is not a job this step can restart from. Valid targets: ${file.restartTargets.join(', ')}.`,\n );\n }\n const next: StepDecisionFile = { ...file, decision, decidedAt: new Date().toISOString() };\n await writeDecisionFile(runtime, path, next);\n return next;\n}\n\n/**\n * How an agent runs `workflow-mcp step`: through the run's launcher, and with\n * the step's decision file named, so the command works from any shell even\n * when the agent's tools do not carry the step's environment.\n */\nfunction stepCommand(runDir: string | undefined, decisionFile: string | undefined): string {\n const cli = runDir ? `\"${workflowCliPath(runDir)}\"` : 'workflow-mcp';\n return decisionFile ? `${cli} step <decision> --decision-file \"${decisionFile}\"` : `${cli} step <decision>`;\n}\n\n/**\n * What a job's agents are told about ending their step. Text only: the engine\n * adds it to the system prompt of every templated step, naming the step's own\n * decision file when it has one.\n */\nexport function stepDecisionInstructions(\n runDir: string,\n jobName: string,\n restartTargets: string[],\n decisionFile?: string,\n): string {\n const step = (decision: string) => stepCommand(runDir, decisionFile).replace('<decision>', decision);\n const lines = [\n `You are running a step of workflow job \"${jobName}\". Before you stop, record the step's outcome with exactly one of these shell commands:`,\n `- ${step('complete')} --summary \"<one line on what you did>\"`,\n ];\n if (restartTargets.length > 0) {\n lines.push(\n `- ${step('fix')} --restart-from <job> --reason \"<what must be fixed and where>\"`,\n ` Valid restart targets: ${restartTargets.join(', ')}. Use the earliest job that owns the problem; fix minor issues yourself instead.`,\n );\n }\n lines.push(\n `- ${step('fail')} --reason \"<the blocker and its evidence>\"`,\n ' Only for a blocker this workflow cannot fix; it ends the whole run.',\n 'Use --reason-file <path> instead of --reason for a long reason. Stopping without a decision is a failure. A decision can be replaced by running the command again before you stop.',\n );\n return lines.join('\\n');\n}\n\n/** One artifact still to write, with what it should hold when the run directory says. */\nexport function formatArtifactWarning(warning: { path: string; status: string; description?: string }): string {\n return `- ${warning.path}: ${warning.status}${warning.description ? `. It holds: ${warning.description}` : ''}`;\n}\n\n/** What an agent is told when it tries to stop before writing what its step and job must leave. */\nexport function stepArtifactReminder(\n file: Pick<StepDecisionFile, 'step' | 'job'>,\n runDir: string | undefined,\n warnings: readonly { path: string; status: string; description?: string }[],\n): string {\n const where = runDir ? ` in ${runDir}` : '';\n const owner = file.job ? `Step \"${file.step}\" of job \"${file.job}\"` : `Step \"${file.step}\"`;\n return `${owner} is not done: it must write or update each of these files${where} before it stops.\\n${warnings\n .map(formatArtifactWarning)\n .join('\\n')}`;\n}\n\n/** What an agent is told when it tries to stop without a decision. */\nexport function stepDecisionReminder(\n file: StepDecisionFile,\n runDir: string | undefined,\n decisionFile?: string,\n): string {\n const step = (decision: string) => stepCommand(runDir, decisionFile).replace('<decision>', decision);\n const targets =\n file.restartTargets.length > 0\n ? `, \\`${step('fix')} --restart-from <${file.restartTargets.join('|')}> --reason ...\\``\n : '';\n return `Step \"${file.step}\" of job \"${file.job}\" has no recorded outcome yet. Do not stop: finish the work, then run \\`${step('complete')} --summary ...\\`${targets}, or \\`${step('fail')} --reason ...\\` if a blocker makes it impossible.`;\n}\n\n/**\n * Whether an agent may stop now, for stop hooks and hosts that steer their\n * own sessions. A step with a required decision is held until one is\n * recorded, and a step that must leave artifacts, its own or its job's, until\n * they are updated, each at most `WORKFLOW_DECISION_NUDGE_CAP` times so a stuck\n * agent cannot loop forever: past the cap the stop is allowed and the engine\n * fails the step with what is still missing.\n */\nexport async function gateStepDecision(\n runtime: WorkflowRuntimeContext,\n env: Readonly<Record<string, string | undefined>> = runtime.baseEnvironment,\n): Promise<StepDecisionGate> {\n const path = env[WORKFLOW_DECISION_FILE_ENV];\n if (!path) return { action: 'allow' };\n // The host running this session steers it itself; a hook inside it must not nudge too.\n if (env[WORKFLOW_DECISION_STEERING_ENV] === WORKFLOW_DECISION_STEERING_HOST) return { action: 'allow' };\n const file = await readDecisionFile(runtime, path);\n if (!file) return { action: 'allow' };\n const decision = file.decision;\n if (decision && decision.decision !== 'complete') return { action: 'allow' };\n if (file.nudges >= nudgeCap(env)) return { action: 'allow' };\n\n let message: string | undefined;\n if (!decision && file.required) {\n message = stepDecisionReminder(file, env[WORKFLOW_RUN_DIR_ENV], path);\n } else {\n const warnings = await findArtifactWarnings(runtime, env);\n if (warnings.length > 0) {\n message = stepArtifactReminder(file, env[WORKFLOW_RUN_DIR_ENV], warnings);\n }\n }\n if (!message) return { action: 'allow' };\n await writeDecisionFile(runtime, path, { ...file, nudges: file.nudges + 1 });\n return { action: 'block', message };\n}\n\n/**\n * Merge a job's fix requests into the run's fix.md, which the runner turns\n * into one repair after the job. The restart target is the earliest requested\n * in job order, so one loop back covers every request; each reason gets its\n * own section. A fix.md a script or agent wrote during the job is kept in it.\n */\nexport async function writeFixRequest(\n runtime: WorkflowRuntimeContext,\n runDir: string,\n jobOrder: string[],\n jobName: string,\n fixes: Extract<StepDecisionReport, { decision: 'fix' }>[],\n): Promise<string> {\n const path = join(runDir, FIX_FILENAME);\n let existing: string | undefined;\n try {\n existing = getOrThrow(await runtime.fs.readTextFile(path, runtime.ioContext));\n } catch {\n existing = undefined;\n }\n const existingTarget = existing?.match(FRONTMATTER_RESTART_FROM)?.[1];\n const targets = [...fixes.map((fix) => fix.restartFrom), ...(existingTarget ? [existingTarget] : [])];\n const restartFrom = [...targets].sort((left, right) => rank(jobOrder, left) - rank(jobOrder, right))[0] ?? jobName;\n const sections = fixes.map((fix) => `## ${fix.step} (restart-from: ${fix.restartFrom})\\n\\n${fix.reason.trim()}`);\n if (existing?.trim()) {\n sections.push(`## Earlier fix request\\n\\n${existing.replace(/^---\\s*\\n[\\s\\S]*?\\n---\\s*\\n?/, '').trim()}`);\n }\n const content = `---\\nrestart-from: ${restartFrom}\\n---\\n\\n# Fix requests from job \"${jobName}\"\\n\\n${sections.join('\\n\\n')}\\n`;\n getOrThrow(await runtime.fs.writeFile(path, content, runtime.ioContext));\n return restartFrom;\n}\n\nfunction rank(jobOrder: string[], job: string): number {\n const index = jobOrder.indexOf(job);\n return index < 0 ? Number.MAX_SAFE_INTEGER : index;\n}\n\nfunction nudgeCap(env: Readonly<Record<string, string | undefined>>): number {\n const parsed = Number.parseInt(env[WORKFLOW_DECISION_NUDGE_CAP_ENV] ?? '', 10);\n if (!Number.isFinite(parsed) || parsed < 0) return DEFAULT_NUDGE_CAP;\n return Math.min(parsed, MAX_NUDGE_CAP);\n}\n\nasync function findArtifactWarnings(\n runtime: WorkflowRuntimeContext,\n env: Readonly<Record<string, string | undefined>>,\n) {\n const raw = env[WORKFLOW_STEP_ARTIFACTS_ENV];\n const runDir = env[WORKFLOW_RUN_DIR_ENV];\n if (!raw || !runDir) return [];\n try {\n return await new RunDirectoryService(runtime).findStepArtifactWarnings(\n runDir,\n JSON.parse(raw) as StepArtifactSnapshot[],\n );\n } catch {\n return [];\n }\n}\n\nasync function writeDecisionFile(runtime: WorkflowRuntimeContext, path: string, file: StepDecisionFile): Promise<void> {\n await writeFileAtomic(runtime.fs, path, `${JSON.stringify(file, null, 2)}\\n`, runtime.ioContext);\n}\n","/**\n * Structured error raised when a persisted workflow run record is malformed.\n */\nexport class InvalidWorkflowRunRecordError extends Error {\n readonly code = 'INVALID_WORKFLOW_RUN_RECORD';\n\n constructor(\n public readonly recordPath: string,\n reason: string,\n options?: ErrorOptions,\n ) {\n super(`Invalid workflow run record at \"${recordPath}\": ${reason}`, options);\n this.name = 'InvalidWorkflowRunRecordError';\n }\n}\n","/**\n * Structured error raised when a workflow display name is already active in a workspace.\n */\nexport class WorkflowRunConflictError extends Error {\n readonly code = 'WORKFLOW_RUN_CONFLICT';\n\n constructor(\n public readonly workspace: string,\n public readonly runKey: string,\n ) {\n super(`Workflow \"${runKey}\" is already running in workspace \"${workspace}\"`);\n this.name = 'WorkflowRunConflictError';\n }\n}\n","/**\n * Append-only progress log for a workflow run.\n *\n * DESIGN PATTERNS:\n * - NDJSON append per event. A run is a detached process, so anything it holds\n * in memory is invisible to every other process and lost on crash. One line\n * per transition is crash-safe, tailable while the run is live, and readable\n * long after it finishes.\n * - Best-effort writes. Progress is an observability signal, never a\n * correctness one, so a failure to record must not fail the run.\n *\n * CODING STANDARDS:\n * - Named exports only\n * - Explicit return types on exported members\n *\n * AVOID:\n * - Rewriting the file: appending keeps concurrent readers consistent and keeps\n * the cost of an event independent of how many came before it\n * - Throwing: the run is the product, this is the commentary\n */\n\nimport { resolve } from 'node:path';\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\n\nimport { WorkflowProgressEventSchema } from '../../schemas/workflowEngine';\nimport type { StepExecutionRef, WorkflowProgressEvent } from '../../schemas/workflowEngine';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nexport const PROGRESS_FILENAME = 'progress.ndjson';\n\n/**\n * Job names the engine records for the `pre:` and `post:` blocks.\n *\n * Those blocks are not jobs, but they run steps and a reader wants to see them,\n * so they are recorded as pseudo-jobs under these reserved names. Exported so a\n * reader can tell a phase from a real job without hardcoding the strings the\n * writer happens to use. Worktree hooks are deliberately absent: they record no\n * progress at all, so nothing can report them.\n */\nexport const PHASE_JOB_PRE = 'pre';\nexport const PHASE_JOB_POST = 'post';\n\n/** Whether a recorded job is a real job or one of the two phase blocks. */\nexport type WorkflowRunPhase = 'job' | typeof PHASE_JOB_POST | typeof PHASE_JOB_PRE;\n\n/** Classify a recorded job name as a phase block or a real job. */\nexport function workflowRunPhase(job: string): WorkflowRunPhase {\n if (job === PHASE_JOB_PRE) return PHASE_JOB_PRE;\n if (job === PHASE_JOB_POST) return PHASE_JOB_POST;\n return 'job';\n}\n\nexport type WorkflowProgressInput = Omit<WorkflowProgressEvent, 'at'>;\n\n/** Records job and step transitions for one run. */\nexport class WorkflowProgressService {\n constructor(\n readonly runtime: WorkflowRuntimeContext,\n private readonly runDir: string | undefined,\n private readonly now: () => string = () => new Date().toISOString(),\n private readonly append: (path: string, data: string) => Promise<void> = (path, data) =>\n Promise.resolve(runtime.fs.appendFile(path, data, runtime.ioContext)).then(getOrThrow),\n ) {}\n\n private path(): string | undefined {\n return this.runDir ? resolve(this.runDir, PROGRESS_FILENAME) : undefined;\n }\n\n /**\n * Record one transition.\n *\n * Swallows write failures on purpose: a dry run has no run directory, and a\n * full disk should not turn a passing workflow into a failing one.\n */\n async record(event: WorkflowProgressInput): Promise<void> {\n const path = this.path();\n if (!path) return;\n try {\n await this.append(path, `${JSON.stringify({ ...event, at: this.now() })}\\n`);\n } catch {\n // Observability only.\n }\n }\n\n jobStarted(job: string, index: number, total: number): Promise<void> {\n return this.record({ type: 'job', status: 'running', job, index, total });\n }\n\n jobFinished(\n job: string,\n status: 'completed' | 'failed' | 'pause_requested' | 'paused' | 'resumed',\n reason?: string,\n ): Promise<void> {\n return this.record({ type: 'job', status, job, ...(reason ? { reason } : {}) });\n }\n\n /** A job a forward jump passed over: it never ran, so it never started either. */\n jobSkipped(job: string, reason?: string): Promise<void> {\n return this.record({ type: 'job', status: 'skipped', job, ...(reason ? { reason } : {}) });\n }\n\n /** `group` names the parallel group a step runs in, beside the other steps of that group. */\n stepStarted(job: string, step: string, index: number, total: number, group?: string): Promise<void> {\n return this.record({ type: 'step', status: 'running', job, step, index, total, ...(group ? { group } : {}) });\n }\n\n /** A host executor started the step; the ref says where a reader can follow it. */\n stepExecutionStarted(job: string, step: string, ref: StepExecutionRef): Promise<void> {\n return this.record({ type: 'step', status: 'running', job, step, ref });\n }\n\n stepFinished(\n job: string,\n step: string,\n status: 'completed' | 'failed' | 'pause_requested' | 'paused' | 'resumed',\n reason?: string,\n ): Promise<void> {\n return this.record({ type: 'step', status, job, step, ...(reason ? { reason } : {}) });\n }\n}\n\n/**\n * Read a run's progress log.\n *\n * Malformed lines are skipped rather than throwing: a reader may catch the file\n * mid-append, and a torn final line is expected rather than exceptional.\n */\nexport async function readWorkflowProgress(\n runtime: WorkflowRuntimeContext,\n runDir: string,\n read: (path: string) => Promise<string> = async (path) =>\n getOrThrow(await runtime.fs.readTextFile(path, runtime.ioContext)),\n): Promise<WorkflowProgressEvent[]> {\n let raw: string;\n try {\n raw = await read(resolve(runDir, PROGRESS_FILENAME));\n } catch {\n return [];\n }\n\n return parseProgressLines(raw);\n}\n\nfunction parseProgressLines(raw: string): WorkflowProgressEvent[] {\n const events: WorkflowProgressEvent[] = [];\n for (const line of raw.split('\\n')) {\n if (!line.trim()) continue;\n try {\n const parsed = WorkflowProgressEventSchema.safeParse(JSON.parse(line));\n if (parsed.success) events.push(parsed.data);\n } catch {\n // Torn or truncated line, expected while the run is still appending.\n }\n }\n return events;\n}\n\n/** Whatever a run has appended since a given byte offset, and the new offset. */\nexport interface WorkflowProgressTail {\n events: WorkflowProgressEvent[];\n offset: number;\n}\n\n/** Bytes from `offset` to the end of file, and where each end sat. */\nexport type ProgressTailReader = (\n path: string,\n offset: number,\n) => Promise<{ end: number; start: number; text: string } | undefined>;\n\nasync function readProgressTail(\n runtime: WorkflowRuntimeContext,\n path: string,\n offset: number,\n): ReturnType<ProgressTailReader> {\n const handle = getOrThrow(await runtime.fs.openBinaryReader(path, undefined, runtime.ioContext));\n try {\n const { size } = getOrThrow(await handle.info(runtime.ioContext));\n const start = offset > size ? 0 : offset;\n if (start === size) return { end: size, start, text: '' };\n const bytes = getOrThrow(await handle.read(start, size - start, runtime.ioContext));\n return { end: start + bytes.length, start, text: new TextDecoder().decode(bytes) };\n } finally {\n await handle.close(runtime.ioContext);\n }\n}\n\n/**\n * Read only what a run has appended since the last call.\n *\n * The whole-file `readWorkflowProgress` re-parses from byte zero every time,\n * which is fine once and wasteful on a timer: a watcher asking a live run for\n * its latest transition pays for every transition that came before it.\n *\n * Only whole lines are consumed. A reader routinely catches the file\n * mid-append, and the bytes of a torn line have to stay unread so the next call\n * sees the finished line instead of dropping it.\n */\nexport async function readWorkflowProgressFrom(\n runtime: WorkflowRuntimeContext,\n runDir: string,\n offset = 0,\n read: ProgressTailReader = (path, offset) => readProgressTail(runtime, path, offset),\n): Promise<WorkflowProgressTail> {\n let tail: Awaited<ReturnType<ProgressTailReader>>;\n try {\n tail = await read(resolve(runDir, PROGRESS_FILENAME), offset);\n } catch {\n // No log yet, or not readable. Hold the offset so nothing is skipped once\n // the file appears.\n return { events: [], offset };\n }\n if (!tail) return { events: [], offset };\n\n const lastBreak = tail.text.lastIndexOf('\\n');\n if (lastBreak < 0) return { events: [], offset: tail.start };\n\n const complete = tail.text.slice(0, lastBreak + 1);\n return {\n events: parseProgressLines(complete),\n // Byte length, not character count: a multi-byte character in a step name\n // would otherwise leave the offset short and replay part of a line.\n offset: tail.start + Buffer.byteLength(complete, 'utf-8'),\n };\n}\n\n/** Every state a recorded job or step can be in. */\nexport type WorkflowProgressStatus =\n | 'completed'\n | 'failed'\n | 'pause_requested'\n | 'paused'\n | 'resumed'\n | 'running'\n | 'skipped';\n\nexport interface WorkflowProgressStep {\n name: string;\n status: WorkflowProgressStatus;\n reason?: string;\n /** Where a host executor ran the step, kept after it finishes. */\n ref?: StepExecutionRef;\n /** The parallel group the step ran in, when it ran beside others. */\n group?: string;\n}\n\nexport interface WorkflowProgressJob {\n name: string;\n status: WorkflowProgressStatus;\n steps: WorkflowProgressStep[];\n index?: number;\n total?: number;\n reason?: string;\n}\n\n/**\n * Fold the event log into the current job tree.\n *\n * Later events win, so a job that started and later failed reads as failed.\n * This is what a progress view renders: completed jobs collapse, the running\n * one expands.\n */\nexport function summarizeWorkflowProgress(events: WorkflowProgressEvent[]): WorkflowProgressJob[] {\n const jobs = new Map<string, WorkflowProgressJob>();\n\n for (const event of events) {\n const job = jobs.get(event.job) ?? { name: event.job, status: 'running', steps: [] };\n if (event.type === 'job') {\n job.status = event.status;\n if (event.index !== undefined) job.index = event.index;\n if (event.total !== undefined) job.total = event.total;\n if (event.reason) job.reason = event.reason;\n } else if (event.step) {\n const existing = job.steps.find((step) => step.name === event.step);\n if (existing) {\n existing.status = event.status;\n if (event.reason) existing.reason = event.reason;\n if (event.ref) existing.ref = event.ref;\n if (event.group) existing.group = event.group;\n } else {\n job.steps.push({\n name: event.step,\n status: event.status,\n ...(event.reason ? { reason: event.reason } : {}),\n ...(event.ref ? { ref: event.ref } : {}),\n ...(event.group ? { group: event.group } : {}),\n });\n }\n }\n jobs.set(event.job, job);\n }\n\n return [...jobs.values()];\n}\n\n/** The job and step a run is on right now, for a one-line status. */\nexport function currentWorkflowPosition(\n jobs: WorkflowProgressJob[],\n): { job: string; step?: string; index?: number; total?: number } | undefined {\n const running = jobs.find((job) => job.status === 'running');\n if (!running) return undefined;\n const step = running.steps.find((candidate) => candidate.status === 'running');\n return { job: running.name, step: step?.name, index: running.index, total: running.total };\n}\n","import { randomUUID } from 'node:crypto';\nimport { resolve } from 'node:path';\n/**\n * WorkflowRegistryService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { createSerialRunner, getOrThrow, writeFileAtomic } from '@agimon-ai/po-core/platform';\n\nimport { InvalidWorkflowRunRecordError } from '../../models/InvalidWorkflowRunRecordError';\nimport { WorkflowRunConflictError } from '../../models/WorkflowRunConflictError';\nimport { WorkflowRepairRecordSchema, WorkflowRunRecordSchema } from '../../schemas/workflowEngine';\nimport type {\n RunDirectory,\n WorkflowExecutionCursor,\n WorkflowExecutionState,\n WorkflowLauncherMetadata,\n WorkflowOutcome,\n WorkflowRepairRecord,\n WorkflowRunHandle,\n WorkflowRunRecord,\n WorkflowStage,\n} from '../../schemas/workflowEngine';\nimport type { WorkflowHost } from '../workflowHost/type';\nimport { WorkflowProgressService } from '../WorkflowProgressService';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nconst DEFAULT_WORKFLOW_HOME = '.workflow-mcp';\nconst WORKFLOW_HOME_ENV = 'WORKFLOW_MCP_HOME';\nconst DEFAULT_WORKSPACE = 'default';\nconst RUNNING_STAGE: WorkflowStage = 'running';\nconst COMPLETED_STAGE: WorkflowStage = 'completed';\nconst ERROR_STAGE: WorkflowStage = 'error';\nconst WORKSPACES_DIRNAME = 'workspaces';\nconst RUN_RECORD_FILENAME = 'run.json';\nconst CONTEXT_FILENAME = 'context.md';\nconst CHANGELOG_FILENAME = 'changelog.md';\nconst FIX_FILENAME = 'fix.md';\nconst PROCEED_FILENAME = 'proceed.md';\nconst STOP_REQUEST_FILENAME = 'stop-request.json';\nconst PAUSE_REQUEST_FILENAME = 'pause-request.json';\nconst FINALIZING_FILENAME = 'finalizing.json';\nconst ISSUES_DIRNAME = 'issues';\nconst REPAIR_FILENAME = 'repair.json';\nconst RECOVERY_CLAIM_FILENAME = 'recovery-claim.json';\nconst RECOVERY_ADOPTION_FILENAME = 'recovery-adoption.json';\nconst FALLBACK_RUN_KEY = 'workflow-run';\nconst SLUG_SEPARATOR = '-';\nconst INTERRUPTED_EXIT_CODE = 130;\nconst STALE_RUNNING_ERROR_PREFIX = 'Workflow process is no longer running';\nconst DEFAULT_LIST_RUNS_PAGE = 1;\nconst DEFAULT_LIST_RUNS_PAGE_SIZE = 20;\nconst DEFAULT_RECOVERY_CLAIM_TTL_MS = 5 * 60 * 1000;\n\nexport interface WorkflowRegistryCreateRunInput {\n activeRepairId?: string;\n cliAgent?: string;\n continueOnError?: boolean;\n displayName: string;\n dryRun: boolean;\n env?: Record<string, string>;\n job?: string;\n keepWorktree?: boolean;\n inputs?: Record<string, string>;\n launcher?: WorkflowLauncherMetadata;\n prompt?: string;\n pid?: number;\n /** Required capability when promoting a terminal error run for recovery. */\n recoveryClaimId?: string;\n runner?: string;\n command?: string;\n choice?: string;\n runDirectory?: RunDirectory;\n secretFile?: string;\n skipLaunch?: boolean;\n statusFile?: string;\n /** Where a natively hosted run answers screen and key requests, when it does. */\n terminalSocket?: string;\n workflowPath: string;\n workflowId?: string;\n workflowName?: string;\n workflowWorkspace?: string;\n workspace?: string;\n}\n\nexport interface WorkflowRegistryFinalizeRunInput {\n errorMessage?: string;\n exitCode?: number;\n failedJob?: string;\n failureReason?: string;\n fixLoopCycle?: number;\n originalRepoPath?: string;\n outcome?: WorkflowOutcome;\n stage: Exclude<WorkflowStage, 'running'>;\n worktreeBranch?: string;\n worktreePath?: string;\n}\n\nexport interface WorkflowRegistryRepairStateInput {\n activeRepairId?: string | null;\n fixLoopCycle?: number;\n}\n\nexport interface WorkflowRegistryListRunsPageInput {\n page?: number;\n pageSize?: number;\n workspace?: string;\n /**\n * Applied before pagination, so `total`, `totalPages`, and `hasNextPage`\n * describe the filtered set rather than the whole registry.\n */\n filter?: (record: WorkflowRunRecord) => boolean;\n}\n\nexport interface WorkflowRegistryListRunsPage {\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n items: WorkflowRunRecord[];\n page: number;\n pageSize: number;\n total: number;\n totalPages: number;\n}\n\nexport interface WorkflowStopRequest {\n reason?: string;\n requestedAt: string;\n runId: string;\n schemaVersion: 1;\n}\n\nexport interface WorkflowPauseRequest {\n action: 'pause';\n schemaVersion: 1;\n reason?: string;\n requestId: string;\n requestedAt: string;\n revision: number;\n runId: string;\n}\n\nexport interface WorkflowResumeRequest {\n action: 'resume';\n schemaVersion: 1;\n requestId: string;\n requestedAt: string;\n revision: number;\n runId: string;\n}\n\nexport interface WorkflowRecoveryClaim {\n claimId: string;\n claimedAt: string;\n ownerSessionId?: string;\n pid: number;\n}\n\ninterface WorkflowRecoveryAdoption {\n adoptedAt: string;\n claimId: string;\n pid: number;\n}\n\n/**\n * Filesystem-backed registry for workflow runs.\n */\nexport class WorkflowRegistryService {\n readonly writeCoordinator = createSerialRunner();\n private readonly homeDir: string;\n private readonly lockRecoveryClaim: WorkflowHost['acquireRecoveryLock'];\n\n constructor(\n readonly runtime: WorkflowRuntimeContext,\n homeDir?: string,\n private readonly recoveryClaimTtlMs = DEFAULT_RECOVERY_CLAIM_TTL_MS,\n lockRecoveryClaim?: WorkflowHost['acquireRecoveryLock'],\n ) {\n this.homeDir = resolve(\n homeDir ?? runtime.baseEnvironment[WORKFLOW_HOME_ENV] ?? resolve(runtime.homeDirectory, DEFAULT_WORKFLOW_HOME),\n );\n this.lockRecoveryClaim = lockRecoveryClaim ?? runtime.workflowHost.acquireRecoveryLock.bind(runtime.workflowHost);\n }\n\n /**\n * Resolve the effective workspace from CLI/tool input or workflow YAML metadata.\n */\n resolveWorkspace(explicitWorkspace?: string, workflowWorkspace?: string): string {\n return this.slugifySegment(explicitWorkspace || workflowWorkspace || DEFAULT_WORKSPACE, DEFAULT_WORKSPACE);\n }\n\n /**\n * Create or resume a workflow run in the `running` stage for its workspace.\n */\n async createRun(input: WorkflowRegistryCreateRunInput): Promise<WorkflowRunHandle> {\n const workspace = this.resolveWorkspace(input.workspace, input.workflowWorkspace);\n const runKey = this.slugifySegment(input.displayName, FALLBACK_RUN_KEY);\n\n await this.ensureWorkspaceStructure(workspace);\n\n const existingStage = await this.findReusableRunStage(workspace, runKey);\n if (existingStage === RUNNING_STAGE) {\n throw new WorkflowRunConflictError(workspace, runKey);\n }\n\n const runningDir = this.getRunDirectory(workspace, RUNNING_STAGE, runKey);\n if (existingStage) {\n const existingDir = this.getRunDirectory(workspace, existingStage, runKey);\n let releaseRecoveryLock: (() => Promise<void>) | undefined;\n try {\n if (existingStage === ERROR_STAGE) {\n releaseRecoveryLock = await this.acquireRecoveryClaimLock(existingDir);\n await this.assertRecoveryPromotion(existingDir, workspace, runKey, input.recoveryClaimId);\n } else if (input.recoveryClaimId) {\n throw new Error(`Workflow recovery claim does not target a failed run: ${workspace}/${runKey}`);\n }\n getOrThrow(await this.runtime.fs.remove(runningDir, { recursive: true, force: true }, this.runtime.ioContext));\n getOrThrow(await this.runtime.fs.renameFile(existingDir, runningDir, this.runtime.ioContext));\n } finally {\n await releaseRecoveryLock?.();\n }\n await this.removeFileIfExists(resolve(runningDir, FIX_FILENAME));\n await this.removeFileIfExists(resolve(runningDir, PROCEED_FILENAME));\n await this.removeFileIfExists(resolve(runningDir, STOP_REQUEST_FILENAME));\n await this.removeFileIfExists(resolve(runningDir, PAUSE_REQUEST_FILENAME));\n await this.removeFileIfExists(resolve(runningDir, FINALIZING_FILENAME));\n await this.removeFileIfExists(resolve(runningDir, RECOVERY_CLAIM_FILENAME));\n await this.removeFileIfExists(resolve(runningDir, RECOVERY_ADOPTION_FILENAME));\n } else {\n if (input.recoveryClaimId) {\n throw new Error(`Workflow recovery claim target no longer exists: ${workspace}/${runKey}`);\n }\n getOrThrow(await this.runtime.fs.createDir(runningDir, { recursive: true }, this.runtime.ioContext));\n }\n\n const runId = randomUUID();\n const runRecord: WorkflowRunRecord = {\n activeRepairId: input.activeRepairId,\n cliAgent: input.cliAgent,\n continueOnError: input.continueOnError,\n displayName: input.displayName,\n dryRun: input.dryRun,\n env: input.env,\n inputs: input.inputs,\n job: input.job,\n keepWorktree: input.keepWorktree,\n launcher: input.launcher,\n runKey,\n prompt: input.prompt,\n runner: input.runner,\n ...(input.command === undefined ? {} : { command: input.command }),\n ...(input.choice === undefined ? {} : { choice: input.choice }),\n runDirectory: input.runDirectory,\n runId,\n secretFile: input.secretFile,\n skipLaunch: input.skipLaunch,\n statusFile: input.statusFile,\n terminalSocket: input.terminalSocket,\n executionState: 'running',\n executionCursor: {\n executionGeneration: 1,\n phase: 'starting',\n resumeMode: 'continue-next',\n revision: 0,\n },\n stage: RUNNING_STAGE,\n startedAt: new Date().toISOString(),\n pid: input.pid ?? this.runtime.workflowHost.processId,\n workflowPath: input.workflowPath,\n workflowId: input.workflowId,\n workflowName: input.workflowName,\n workspace,\n };\n\n const recordPath = resolve(runningDir, RUN_RECORD_FILENAME);\n await this.writeRunRecord(recordPath, runRecord);\n\n return {\n changelogPath: resolve(runningDir, CHANGELOG_FILENAME),\n contextPath: resolve(runningDir, CONTEXT_FILENAME),\n displayName: input.displayName,\n pauseRequestPath: resolve(runningDir, PAUSE_REQUEST_FILENAME),\n recordPath,\n runDir: runningDir,\n runId,\n runKey,\n stopRequestPath: resolve(runningDir, STOP_REQUEST_FILENAME),\n workspace,\n };\n }\n\n /**\n * Finalize a workflow run by moving it into a terminal stage and updating metadata.\n */\n async finalizeRun(handle: WorkflowRunHandle, input: WorkflowRegistryFinalizeRunInput): Promise<WorkflowRunHandle> {\n await this.ensureWorkspaceStructure(handle.workspace);\n\n const nextDir = this.getRunDirectory(handle.workspace, input.stage, handle.runKey);\n const currentRecord = await this.readRunRecord(handle.recordPath);\n const finalRecord: WorkflowRunRecord = {\n ...currentRecord,\n errorMessage: input.errorMessage,\n executionCursor: undefined,\n executionState: undefined,\n exitCode: input.exitCode,\n failedJob: input.failedJob,\n failureReason: input.failureReason,\n finishedAt: new Date().toISOString(),\n fixLoopCycle: input.fixLoopCycle,\n originalRepoPath: input.originalRepoPath,\n outcome: input.outcome,\n pid: currentRecord.pid,\n stage: input.stage,\n worktreeBranch: input.worktreeBranch,\n worktreePath: input.worktreePath,\n };\n\n await this.removeFileIfExists(resolve(handle.runDir, PAUSE_REQUEST_FILENAME));\n // The terminal record is written before the directory moves. Written after\n // the rename, a failure or kill in between left a `stage: running` record\n // under a terminal directory, where stale detection never looks, so every\n // reader saw a run that stayed running forever.\n await this.writeRunRecord(handle.recordPath, finalRecord);\n await this.removeFileIfExists(resolve(handle.runDir, FINALIZING_FILENAME));\n if (handle.runDir !== nextDir) {\n getOrThrow(await this.runtime.fs.remove(nextDir, { recursive: true, force: true }, this.runtime.ioContext));\n getOrThrow(await this.runtime.fs.renameFile(handle.runDir, nextDir, this.runtime.ioContext));\n }\n\n const nextRecordPath = resolve(nextDir, RUN_RECORD_FILENAME);\n\n return {\n ...handle,\n pauseRequestPath: resolve(nextDir, PAUSE_REQUEST_FILENAME),\n recordPath: nextRecordPath,\n runDir: nextDir,\n stopRequestPath: resolve(nextDir, STOP_REQUEST_FILENAME),\n };\n }\n\n /**\n * Request graceful interruption for a running workflow.\n */\n async requestStop(\n workspace: string | undefined,\n runKey: string,\n reason: string | undefined,\n expectedRunId: string,\n ): Promise<WorkflowStopRequest> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const runningDir = this.getRunDirectory(resolvedWorkspace, RUNNING_STAGE, resolvedRunKey);\n const recordPath = resolve(runningDir, RUN_RECORD_FILENAME);\n\n if (!(await this.pathExists(recordPath))) {\n throw new Error(`Running workflow not found: ${resolvedWorkspace}/${runKey}`);\n }\n\n const record = await this.inspectRunningRecord(resolvedWorkspace, resolvedRunKey);\n if (record.runId !== expectedRunId) {\n throw new Error(`Workflow run ownership changed: ${resolvedWorkspace}/${runKey}`);\n }\n if (record.stale) {\n throw new Error(record.staleReason ?? `Running workflow is stale: ${resolvedWorkspace}/${runKey}`);\n }\n\n if (!record.runId) throw new Error(`Running workflow has no run ID: ${resolvedWorkspace}/${runKey}`);\n const request: WorkflowStopRequest = {\n reason: reason?.trim() ? reason.trim() : undefined,\n requestedAt: new Date().toISOString(),\n runId: record.runId,\n schemaVersion: 1,\n };\n await this.writeControlRequest(\n {\n changelogPath: resolve(runningDir, CHANGELOG_FILENAME),\n contextPath: resolve(runningDir, CONTEXT_FILENAME),\n displayName: record.displayName,\n pauseRequestPath: resolve(runningDir, PAUSE_REQUEST_FILENAME),\n recordPath,\n runDir: runningDir,\n runId: record.runId,\n runKey: resolvedRunKey,\n stopRequestPath: resolve(runningDir, STOP_REQUEST_FILENAME),\n workspace: resolvedWorkspace,\n },\n resolve(runningDir, STOP_REQUEST_FILENAME),\n request,\n );\n return request;\n }\n\n async requestPause(\n workspace: string | undefined,\n runKey: string,\n reason: string | undefined,\n expectedRunId: string,\n ): Promise<WorkflowPauseRequest> {\n const handle = await this.getRunningHandle(workspace, runKey, expectedRunId);\n await this.assertNotFinalizing(handle);\n const record = await this.readRunRecord(handle.recordPath);\n const state = record.executionState ?? 'running';\n const existing = await this.readPauseRequest(handle);\n if (existing?.action === 'pause' && (state === 'pause_requested' || state === 'paused')) return existing;\n if (state === 'resume_requested') {\n throw new Error(`Workflow is resuming: ${handle.workspace}/${handle.runKey}`);\n }\n if (state !== 'running') {\n throw new Error(`Workflow cannot be paused from execution state ${state}: ${handle.workspace}/${handle.runKey}`);\n }\n\n if (existing?.action === 'resume') {\n await this.clearPauseRequest(handle);\n }\n const revision = record.executionCursor?.revision ?? 0;\n const request: WorkflowPauseRequest = {\n action: 'pause',\n schemaVersion: 1,\n reason: reason?.trim() ? reason.trim() : undefined,\n requestId: randomUUID(),\n requestedAt: new Date().toISOString(),\n revision,\n runId: handle.runId,\n };\n await this.assertCurrentRun(handle);\n await this.updateExecutionState(\n handle,\n 'pause_requested',\n {\n ...(record.executionCursor ?? {\n executionGeneration: 1,\n phase: 'unknown',\n resumeMode: 'replay-current',\n }),\n requestId: request.requestId,\n resumeMode: 'replay-current',\n revision: revision + 1,\n },\n revision,\n );\n await this.writeControlRequest(\n handle,\n handle.pauseRequestPath ?? resolve(handle.runDir, PAUSE_REQUEST_FILENAME),\n request,\n );\n const progressJob = record.executionCursor?.job ?? record.job ?? record.executionCursor?.phase ?? 'workflow';\n if (record.executionCursor?.stepName) {\n await new WorkflowProgressService(this.runtime, handle.runDir).stepFinished(\n progressJob,\n record.executionCursor.stepName,\n 'pause_requested',\n request.reason,\n );\n } else {\n await new WorkflowProgressService(this.runtime, handle.runDir).jobFinished(\n progressJob,\n 'pause_requested',\n request.reason,\n );\n }\n return request;\n }\n\n async requestResume(\n workspace: string | undefined,\n runKey: string,\n expectedRunId: string,\n ): Promise<WorkflowResumeRequest> {\n const handle = await this.getRunningHandle(workspace, runKey, expectedRunId);\n await this.assertNotFinalizing(handle);\n const record = await this.readRunRecord(handle.recordPath);\n const state = record.executionState ?? 'running';\n const existing = await this.readPauseRequest(handle);\n if (existing?.action === 'resume' && (state === 'resume_requested' || state === 'running')) return existing;\n if (state !== 'paused' || existing?.action !== 'pause') {\n throw new Error(`Workflow is not paused: ${handle.workspace}/${handle.runKey}`);\n }\n\n const revision = record.executionCursor?.revision ?? existing.revision;\n const request: WorkflowResumeRequest = {\n action: 'resume',\n schemaVersion: 1,\n requestId: randomUUID(),\n requestedAt: new Date().toISOString(),\n revision,\n runId: handle.runId,\n };\n await this.assertCurrentRun(handle);\n await this.updateExecutionState(\n handle,\n 'resume_requested',\n {\n ...(record.executionCursor ?? {\n executionGeneration: 1,\n phase: 'unknown',\n resumeMode: 'replay-current',\n }),\n requestId: request.requestId,\n resumeMode: 'replay-current',\n revision: revision + 1,\n },\n revision,\n );\n await this.writeControlRequest(\n handle,\n handle.pauseRequestPath ?? resolve(handle.runDir, PAUSE_REQUEST_FILENAME),\n request,\n );\n return request;\n }\n\n async readPauseRequest(handle: WorkflowRunHandle): Promise<WorkflowPauseRequest | WorkflowResumeRequest | null> {\n try {\n const value: unknown = JSON.parse(\n getOrThrow(\n await this.runtime.fs.readTextFile(\n handle.pauseRequestPath ?? resolve(handle.runDir, PAUSE_REQUEST_FILENAME),\n this.runtime.ioContext,\n ),\n ),\n );\n if (!value || typeof value !== 'object') return null;\n const candidate = value as Partial<WorkflowPauseRequest> & Partial<WorkflowResumeRequest>;\n if (\n (candidate.action !== 'pause' && candidate.action !== 'resume') ||\n candidate.schemaVersion !== 1 ||\n candidate.runId !== handle.runId ||\n typeof candidate.requestId !== 'string' ||\n typeof candidate.revision !== 'number' ||\n !Number.isInteger(candidate.revision) ||\n candidate.revision < 0 ||\n typeof candidate.requestedAt !== 'string'\n )\n return null;\n return candidate as WorkflowPauseRequest | WorkflowResumeRequest;\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) return null;\n throw error;\n }\n }\n\n async updateExecutionState(\n handle: WorkflowRunHandle,\n executionState: WorkflowExecutionState,\n executionCursor?: WorkflowExecutionCursor,\n expectedRevision?: number,\n ): Promise<WorkflowRunRecord> {\n const current = await this.readRunRecord(handle.recordPath);\n if (current.stage !== RUNNING_STAGE || (current.runId && current.runId !== handle.runId)) {\n throw new Error(`Workflow run is no longer controllable: ${handle.workspace}/${handle.runKey}`);\n }\n const currentRevision = current.executionCursor?.revision ?? 0;\n if (expectedRevision !== undefined && currentRevision !== expectedRevision) {\n throw new Error(`Workflow control revision changed for ${handle.workspace}/${handle.runKey}`);\n }\n const updated: WorkflowRunRecord = {\n ...current,\n executionCursor: executionCursor ?? current.executionCursor,\n executionState,\n };\n await this.writeRunRecord(handle.recordPath, updated);\n return updated;\n }\n\n async updateExecutionCursor(\n handle: WorkflowRunHandle,\n patch: Partial<WorkflowExecutionCursor>,\n ): Promise<WorkflowRunRecord> {\n const current = await this.readRunRecord(handle.recordPath);\n if (current.stage !== RUNNING_STAGE || (current.runId && current.runId !== handle.runId)) {\n throw new Error(`Workflow run is no longer controllable: ${handle.workspace}/${handle.runKey}`);\n }\n const currentCursor =\n current.executionCursor ??\n ({\n executionGeneration: 1,\n phase: 'unknown',\n resumeMode: 'continue-next',\n revision: 0,\n } satisfies WorkflowExecutionCursor);\n const updated: WorkflowRunRecord = {\n ...current,\n executionCursor: {\n ...currentCursor,\n ...patch,\n revision: currentCursor.revision ?? 0,\n },\n };\n await this.writeRunRecord(handle.recordPath, updated);\n return updated;\n }\n\n async clearPauseRequest(handle: WorkflowRunHandle): Promise<void> {\n await this.removeFileIfExists(handle.pauseRequestPath ?? resolve(handle.runDir, PAUSE_REQUEST_FILENAME));\n }\n\n async markFinalizing(handle: WorkflowRunHandle): Promise<void> {\n const current = await this.readRunRecord(handle.recordPath);\n if (current.stage !== RUNNING_STAGE || (current.runId && current.runId !== handle.runId)) {\n throw new Error(`Workflow run is no longer finalizable: ${handle.workspace}/${handle.runKey}`);\n }\n await this.writeAtomic(resolve(handle.runDir, FINALIZING_FILENAME), {\n at: new Date().toISOString(),\n runId: handle.runId,\n });\n }\n\n /**\n * Check whether a workflow run has been asked to stop.\n */\n async hasStopRequest(handle: WorkflowRunHandle): Promise<boolean> {\n try {\n const request = JSON.parse(\n getOrThrow(await this.runtime.fs.readTextFile(handle.stopRequestPath, this.runtime.ioContext)),\n ) as Partial<WorkflowStopRequest>;\n return request.schemaVersion === 1 && request.runId === handle.runId;\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) return false;\n throw error;\n }\n }\n\n private async assertNotFinalizing(handle: WorkflowRunHandle): Promise<void> {\n if (await this.pathExists(resolve(handle.runDir, FINALIZING_FILENAME))) {\n throw new Error(`Workflow is finalizing: ${handle.workspace}/${handle.runKey}`);\n }\n }\n\n private async assertCurrentRun(handle: WorkflowRunHandle): Promise<void> {\n const current = await this.readRunRecord(handle.recordPath);\n if (current.stage !== RUNNING_STAGE || current.runId !== handle.runId) {\n throw new Error(`Workflow run ownership changed: ${handle.workspace}/${handle.runKey}`);\n }\n }\n\n private async getRunningHandle(\n workspace: string | undefined,\n runKey: string,\n expectedRunId: string,\n ): Promise<WorkflowRunHandle> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const runningDir = this.getRunDirectory(resolvedWorkspace, RUNNING_STAGE, resolvedRunKey);\n const recordPath = resolve(runningDir, RUN_RECORD_FILENAME);\n if (!(await this.pathExists(recordPath)))\n throw new Error(`Running workflow not found: ${resolvedWorkspace}/${runKey}`);\n const record = await this.inspectRunningRecord(resolvedWorkspace, resolvedRunKey);\n if (record.stale)\n throw new Error(record.staleReason ?? `Running workflow is stale: ${resolvedWorkspace}/${runKey}`);\n if (!record.runId) throw new Error(`Running workflow has no run ID: ${resolvedWorkspace}/${runKey}`);\n if (record.runId !== expectedRunId) {\n throw new Error(`Workflow run ownership changed: ${resolvedWorkspace}/${runKey}`);\n }\n return {\n changelogPath: resolve(runningDir, CHANGELOG_FILENAME),\n contextPath: resolve(runningDir, CONTEXT_FILENAME),\n displayName: record.displayName,\n pauseRequestPath: resolve(runningDir, PAUSE_REQUEST_FILENAME),\n recordPath,\n runDir: runningDir,\n runId: record.runId,\n runKey: resolvedRunKey,\n stopRequestPath: resolve(runningDir, STOP_REQUEST_FILENAME),\n workspace: resolvedWorkspace,\n };\n }\n\n private async writeAtomic(path: string, value: unknown): Promise<void> {\n await writeFileAtomic(this.runtime.fs, path, `${JSON.stringify(value, null, 2)}\\n`, this.runtime.ioContext);\n }\n\n /** Publish complete JSON without ever exposing a partially written capability. */\n private async writeExclusiveJson(path: string, value: unknown): Promise<void> {\n const tempPath = `${path}.${this.runtime.workflowHost.processId}.${randomUUID()}.tmp`;\n try {\n getOrThrow(\n await this.runtime.fs.writeFile(tempPath, `${JSON.stringify(value, null, 2)}\\n`, this.runtime.ioContext),\n );\n await this.runtime.workflowHost.publishExclusive(tempPath, path);\n } finally {\n await this.removeFileIfExists(tempPath);\n }\n }\n\n private async writeControlRequest(handle: WorkflowRunHandle, path: string, value: unknown): Promise<void> {\n const tempPath = `${path}.${this.runtime.workflowHost.processId}.${randomUUID()}.tmp`;\n try {\n getOrThrow(\n await this.runtime.fs.writeFile(tempPath, `${JSON.stringify(value, null, 2)}\\n`, this.runtime.ioContext),\n );\n await this.assertCurrentRun(handle);\n getOrThrow(await this.runtime.fs.renameFile(tempPath, path, this.runtime.ioContext));\n } catch (error) {\n await this.removeFileIfExists(tempPath);\n throw error;\n }\n }\n\n /**\n * Read a run record from disk.\n */\n async readRunRecord(recordPath: string): Promise<WorkflowRunRecord> {\n try {\n return this.validateRunRecord(\n JSON.parse(getOrThrow(await this.runtime.fs.readTextFile(recordPath, this.runtime.ioContext))),\n recordPath,\n );\n } catch (error) {\n if (error instanceof InvalidWorkflowRunRecordError) {\n throw error;\n }\n\n const reason = error instanceof Error ? error.message : 'Unknown parse failure';\n throw new InvalidWorkflowRunRecordError(recordPath, reason, { cause: error });\n }\n }\n\n /**\n * Claim one terminal failed run for recovery.\n *\n * Exclusive creation is the cross-process compare-and-set: exactly one Pi or\n * CLI process may advance from inspection to replay. The claim file moves\n * with the run directory and is removed when createRun promotes the record.\n */\n async claimRunRecovery(\n workspace: string | undefined,\n runKey: string,\n ownerSessionId?: string,\n ): Promise<WorkflowRecoveryClaim> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const errorDir = this.getRunDirectory(resolvedWorkspace, ERROR_STAGE, resolvedRunKey);\n const recordPath = resolve(errorDir, RUN_RECORD_FILENAME);\n if (!(await this.pathExists(recordPath))) {\n throw new Error(`Workflow run not found: ${resolvedWorkspace}/${ERROR_STAGE}/${runKey}`);\n }\n\n const claim: WorkflowRecoveryClaim = {\n claimId: randomUUID(),\n claimedAt: new Date().toISOString(),\n ownerSessionId: ownerSessionId?.trim() || undefined,\n pid: this.runtime.workflowHost.processId,\n };\n const claimPath = resolve(errorDir, RECOVERY_CLAIM_FILENAME);\n const releaseLock = await this.acquireRecoveryClaimLock(errorDir).catch((error: NodeJS.ErrnoException) => {\n throw new Error(`Workflow recovery is already claimed: ${resolvedWorkspace}/${runKey}`, { cause: error });\n });\n try {\n try {\n await this.writeExclusiveJson(claimPath, claim);\n return claim;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n if (await this.reclaimAbandonedRecoveryClaim(errorDir)) {\n await this.writeExclusiveJson(claimPath, claim);\n return claim;\n }\n throw new Error(`Workflow recovery is already claimed: ${resolvedWorkspace}/${runKey}`, { cause: error });\n }\n } finally {\n await releaseLock();\n }\n }\n\n /**\n * Consume a claim handed from an embedding process to one recovery process.\n *\n * The caller-controlled claim ID is only a capability reference: ownership\n * comes from the pre-existing registry claim. Exclusive adoption prevents\n * replaying the same capability in two launcher processes.\n */\n async adoptRunRecoveryClaim(\n workspace: string | undefined,\n runKey: string,\n claimId: string,\n ): Promise<WorkflowRecoveryClaim> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const errorDir = this.getRunDirectory(resolvedWorkspace, ERROR_STAGE, resolvedRunKey);\n const claimPath = resolve(errorDir, RECOVERY_CLAIM_FILENAME);\n const claim = await this.readRecoveryClaim(claimPath);\n if (claim.claimId !== claimId) {\n throw new Error(`Workflow recovery claim was not authorized: ${resolvedWorkspace}/${runKey}`);\n }\n\n const adoption: WorkflowRecoveryAdoption = {\n adoptedAt: new Date().toISOString(),\n claimId,\n pid: this.runtime.workflowHost.processId,\n };\n const adoptionPath = resolve(errorDir, RECOVERY_ADOPTION_FILENAME);\n const releaseLock = await this.acquireRecoveryClaimLock(errorDir);\n try {\n const current = await this.readRecoveryClaim(claimPath);\n if (current.claimId !== claimId) {\n throw new Error(`Workflow recovery claim changed: ${resolvedWorkspace}/${runKey}`);\n }\n await this.writeExclusiveJson(adoptionPath, adoption);\n return current;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') {\n throw new Error(`Workflow recovery claim is already adopted: ${resolvedWorkspace}/${runKey}`, { cause: error });\n }\n await this.removeFileIfExists(adoptionPath);\n throw error;\n } finally {\n await releaseLock();\n }\n }\n\n /** Release a claim when recovery validation fails before replay starts. */\n async releaseRunRecoveryClaim(workspace: string | undefined, runKey: string, claimId: string): Promise<void> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const claimPath = resolve(\n this.getRunDirectory(resolvedWorkspace, ERROR_STAGE, resolvedRunKey),\n RECOVERY_CLAIM_FILENAME,\n );\n const errorDir = this.getRunDirectory(resolvedWorkspace, ERROR_STAGE, resolvedRunKey);\n const releaseLock = await this.acquireRecoveryClaimLock(errorDir);\n try {\n const current = await this.readRecoveryClaim(claimPath);\n if (current.claimId !== claimId) return;\n const adoptionPath = resolve(errorDir, RECOVERY_ADOPTION_FILENAME);\n try {\n const adoption = JSON.parse(\n getOrThrow(await this.runtime.fs.readTextFile(adoptionPath, this.runtime.ioContext)),\n ) as Partial<WorkflowRecoveryAdoption>;\n if (adoption.claimId === claimId)\n getOrThrow(await this.runtime.fs.remove(adoptionPath, undefined, this.runtime.ioContext));\n } catch (error) {\n if (!['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) throw error;\n }\n getOrThrow(await this.runtime.fs.remove(claimPath, undefined, this.runtime.ioContext));\n } catch (error) {\n if (!['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) throw error;\n } finally {\n await releaseLock();\n }\n }\n\n private async acquireRecoveryClaimLock(errorDir: string): Promise<() => Promise<void>> {\n return await this.lockRecoveryClaim(resolve(errorDir, RUN_RECORD_FILENAME), {\n lockfilePath: `${errorDir}.recovery-claim.lock`,\n realpath: false,\n retries: 0,\n stale: this.recoveryClaimTtlMs,\n });\n }\n\n /** Verify the exact adopted capability before moving error state to running. */\n private async assertRecoveryPromotion(\n errorDir: string,\n workspace: string,\n runKey: string,\n recoveryClaimId?: string,\n ): Promise<void> {\n if (!recoveryClaimId) {\n throw new Error(`Workflow recovery claim is required: ${workspace}/${runKey}`);\n }\n const claim = await this.readRecoveryClaim(resolve(errorDir, RECOVERY_CLAIM_FILENAME));\n if (claim.claimId !== recoveryClaimId) {\n throw new Error(`Workflow recovery claim was not authorized: ${workspace}/${runKey}`);\n }\n let adoption: WorkflowRecoveryAdoption;\n try {\n adoption = await this.readRecoveryAdoption(resolve(errorDir, RECOVERY_ADOPTION_FILENAME));\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) {\n throw new Error(`Workflow recovery claim was not adopted: ${workspace}/${runKey}`, { cause: error });\n }\n throw error;\n }\n if (adoption.claimId !== recoveryClaimId) {\n throw new Error(`Workflow recovery claim was not adopted: ${workspace}/${runKey}`);\n }\n }\n\n /**\n * Reclaim a claim when its launcher lease expired or its claimant died. An\n * adopted claim is protected while its adopting process remains alive.\n */\n private async reclaimAbandonedRecoveryClaim(errorDir: string): Promise<boolean> {\n const adoptionPath = resolve(errorDir, RECOVERY_ADOPTION_FILENAME);\n let deadAdoption: WorkflowRecoveryAdoption | undefined;\n try {\n const adoption = await this.readRecoveryAdoption(adoptionPath);\n if (this.isProcessAlive(adoption.pid)) return false;\n deadAdoption = adoption;\n } catch (error) {\n if (!['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) throw error;\n }\n\n const claimPath = resolve(errorDir, RECOVERY_CLAIM_FILENAME);\n let claim: WorkflowRecoveryClaim;\n try {\n claim = await this.readRecoveryClaim(claimPath);\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) return true;\n throw error;\n }\n if (deadAdoption && deadAdoption.claimId !== claim.claimId) return false;\n\n const claimedAt = Date.parse(claim.claimedAt);\n const expired = !Number.isFinite(claimedAt) || Date.now() - claimedAt >= this.recoveryClaimTtlMs;\n if (!deadAdoption && this.isProcessAlive(claim.pid) && !expired) return false;\n\n try {\n const current = await this.readRecoveryClaim(claimPath);\n if (current.claimId !== claim.claimId) return false;\n getOrThrow(await this.runtime.fs.remove(claimPath, undefined, this.runtime.ioContext));\n if (deadAdoption) await this.removeFileIfExists(adoptionPath);\n return true;\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) return true;\n throw error;\n }\n }\n\n private async readRecoveryClaim(path: string): Promise<WorkflowRecoveryClaim> {\n const value: unknown = JSON.parse(getOrThrow(await this.runtime.fs.readTextFile(path, this.runtime.ioContext)));\n if (!value || typeof value !== 'object') throw new Error(`Invalid workflow recovery claim: ${path}`);\n const claim = value as Partial<WorkflowRecoveryClaim>;\n if (\n typeof claim.claimId !== 'string' ||\n typeof claim.claimedAt !== 'string' ||\n typeof claim.pid !== 'number' ||\n !Number.isInteger(claim.pid) ||\n claim.pid <= 0 ||\n (claim.ownerSessionId !== undefined && typeof claim.ownerSessionId !== 'string')\n ) {\n throw new Error(`Invalid workflow recovery claim: ${path}`);\n }\n return claim as WorkflowRecoveryClaim;\n }\n\n private async readRecoveryAdoption(path: string): Promise<WorkflowRecoveryAdoption> {\n const value: unknown = JSON.parse(getOrThrow(await this.runtime.fs.readTextFile(path, this.runtime.ioContext)));\n if (!value || typeof value !== 'object') throw new Error(`Invalid workflow recovery adoption: ${path}`);\n const adoption = value as Partial<WorkflowRecoveryAdoption>;\n if (\n typeof adoption.claimId !== 'string' ||\n typeof adoption.adoptedAt !== 'string' ||\n typeof adoption.pid !== 'number' ||\n !Number.isInteger(adoption.pid) ||\n adoption.pid <= 0\n ) {\n throw new Error(`Invalid workflow recovery adoption: ${path}`);\n }\n return adoption as WorkflowRecoveryAdoption;\n }\n\n /**\n * Read a workflow run by workspace, stage, and run key.\n */\n async readRunByKey(workspace: string | undefined, stage: WorkflowStage, runKey: string): Promise<WorkflowRunRecord> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const recordPath = resolve(this.getRunDirectory(resolvedWorkspace, stage, resolvedRunKey), RUN_RECORD_FILENAME);\n\n if (!(await this.pathExists(recordPath))) {\n throw new Error(`Workflow run not found: ${resolvedWorkspace}/${stage}/${runKey}`);\n }\n\n return await this.readRunRecord(recordPath);\n }\n\n /**\n * Read a terminal fix.md artifact from a staged run without mutating it.\n */\n async readRunFixContent(workspace: string | undefined, stage: WorkflowStage, runKey: string): Promise<string | null> {\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const fixPath = resolve(this.getRunDirectory(resolvedWorkspace, stage, resolvedRunKey), FIX_FILENAME);\n\n try {\n return getOrThrow(await this.runtime.fs.readTextFile(fixPath, this.runtime.ioContext));\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Read one durable repair record from a staged workflow run.\n */\n async readRunRepair(\n workspace: string | undefined,\n stage: WorkflowStage,\n runKey: string,\n repairId: string,\n ): Promise<WorkflowRepairRecord> {\n if (!/^\\d+$/.test(repairId)) {\n throw new Error(`Invalid workflow repair ID: ${repairId}`);\n }\n\n const resolvedWorkspace = this.resolveWorkspace(workspace);\n const resolvedRunKey = this.slugifySegment(runKey, FALLBACK_RUN_KEY);\n const repairPath = resolve(\n this.getRunDirectory(resolvedWorkspace, stage, resolvedRunKey),\n ISSUES_DIRNAME,\n repairId,\n REPAIR_FILENAME,\n );\n const content = getOrThrow(await this.runtime.fs.readTextFile(repairPath, this.runtime.ioContext));\n return WorkflowRepairRecordSchema.parse(JSON.parse(content));\n }\n\n /**\n * Persist the active repair pointer and fix-cycle progress on a running record.\n */\n async updateRepairState(\n handle: WorkflowRunHandle,\n input: WorkflowRegistryRepairStateInput,\n ): Promise<WorkflowRunRecord> {\n const current = await this.readRunRecord(handle.recordPath);\n const updated: WorkflowRunRecord = {\n ...current,\n activeRepairId: input.activeRepairId === null ? undefined : (input.activeRepairId ?? current.activeRepairId),\n fixLoopCycle: input.fixLoopCycle ?? current.fixLoopCycle,\n };\n await this.writeRunRecord(handle.recordPath, updated);\n return updated;\n }\n\n /**\n * List workflow runs across all workspaces or a single workspace.\n */\n async listRuns(workspace?: string): Promise<WorkflowRunRecord[]> {\n const workspaces = workspace ? [this.resolveWorkspace(workspace)] : await this.listWorkspaceNames();\n const records = await Promise.all(workspaces.map(async (workspaceName) => this.listWorkspaceRuns(workspaceName)));\n\n return records.flat().sort((left, right) => this.compareRunRecordsByLatest(left, right));\n }\n\n /**\n * List workflow runs as a stable page sorted by latest activity first.\n */\n async listRunsPage(input: WorkflowRegistryListRunsPageInput = {}): Promise<WorkflowRegistryListRunsPage> {\n const page = input.page ?? DEFAULT_LIST_RUNS_PAGE;\n const pageSize = input.pageSize ?? DEFAULT_LIST_RUNS_PAGE_SIZE;\n const listed = await this.listRuns(input.workspace);\n const runs = input.filter ? listed.filter(input.filter) : listed;\n const total = runs.length;\n const totalPages = Math.ceil(total / pageSize);\n const startIndex = (page - 1) * pageSize;\n const items = runs.slice(startIndex, startIndex + pageSize);\n\n return {\n hasNextPage: page < totalPages,\n hasPreviousPage: page > 1 && total > 0,\n items,\n page,\n pageSize,\n total,\n totalPages,\n };\n }\n\n /**\n * Count live (non-stale) running workflows in a workspace.\n */\n async countRunningWorkflows(workspace: string): Promise<number> {\n const stageDir = this.getRunStageDirectory(workspace, RUNNING_STAGE);\n if (!(await this.pathExists(stageDir))) {\n return 0;\n }\n\n const entries = getOrThrow(await this.runtime.fs.listDir(stageDir, this.runtime.ioContext));\n let alive = 0;\n\n for (const entry of entries) {\n if (entry.kind !== 'directory') {\n continue;\n }\n\n const recordPath = resolve(stageDir, entry.name, RUN_RECORD_FILENAME);\n if (!(await this.pathExists(recordPath))) {\n continue;\n }\n\n try {\n const record = await this.readRunRecord(recordPath);\n if (record.pid && this.isProcessAlive(record.pid)) {\n alive++;\n }\n } catch {\n // Skip unreadable run records.\n }\n }\n\n return alive;\n }\n\n /**\n * Persist every dead running process in a workspace as an interrupted run.\n * The operation is idempotent and is only invoked by an explicit reconcile\n * request or before a new workflow is dispatched.\n */\n async reconcileStaleRuns(workspace?: string): Promise<WorkflowRunRecord[]> {\n const workspaces = workspace ? [this.resolveWorkspace(workspace)] : await this.listWorkspaceNames();\n const reconciled: WorkflowRunRecord[] = [];\n\n for (const workspaceName of workspaces) {\n const stageDir = this.getRunStageDirectory(workspaceName, RUNNING_STAGE);\n if (!(await this.pathExists(stageDir))) {\n continue;\n }\n\n const entries = getOrThrow(await this.runtime.fs.listDir(stageDir, this.runtime.ioContext));\n for (const entry of entries) {\n if (entry.kind !== 'directory') {\n continue;\n }\n\n const recordPath = resolve(stageDir, entry.name, RUN_RECORD_FILENAME);\n if (!(await this.pathExists(recordPath))) {\n continue;\n }\n\n const record = await this.inspectReconcilableRunningRecord(workspaceName, entry.name);\n if (!record) {\n continue;\n }\n const unmovedTerminal = record.stage !== RUNNING_STAGE && !!record.pid && !this.isProcessAlive(record.pid);\n if (record.stale || unmovedTerminal) {\n reconciled.push(await this.reconcileStaleRunningRecord(workspaceName, entry.name));\n }\n }\n }\n\n return reconciled;\n }\n\n /**\n * Ensure the stage directories exist for the workspace.\n */\n private async ensureWorkspaceStructure(workspace: string): Promise<void> {\n getOrThrow(\n await this.runtime.fs.createDir(\n this.getRunStageDirectory(workspace, RUNNING_STAGE),\n { recursive: true },\n this.runtime.ioContext,\n ),\n );\n getOrThrow(\n await this.runtime.fs.createDir(\n this.getRunStageDirectory(workspace, COMPLETED_STAGE),\n { recursive: true },\n this.runtime.ioContext,\n ),\n );\n getOrThrow(\n await this.runtime.fs.createDir(\n this.getRunStageDirectory(workspace, ERROR_STAGE),\n { recursive: true },\n this.runtime.ioContext,\n ),\n );\n }\n\n /**\n * Find the current stage for an existing run key.\n */\n private async findRunStage(workspace: string, runKey: string): Promise<WorkflowStage | null> {\n for (const stage of [RUNNING_STAGE, COMPLETED_STAGE, ERROR_STAGE] as const) {\n if (await this.pathExists(this.getRunDirectory(workspace, stage, runKey))) {\n return stage;\n }\n }\n return null;\n }\n\n /**\n * Read every run record within a workspace's stage directories.\n */\n private async listWorkspaceRuns(workspace: string): Promise<WorkflowRunRecord[]> {\n const records = new Map<string, WorkflowRunRecord>();\n\n for (const stage of [RUNNING_STAGE, COMPLETED_STAGE, ERROR_STAGE] as const) {\n const stageDir = this.getRunStageDirectory(workspace, stage);\n if (!(await this.pathExists(stageDir))) {\n continue;\n }\n\n const entries = getOrThrow(await this.runtime.fs.listDir(stageDir, this.runtime.ioContext));\n for (const entry of entries) {\n if (entry.kind !== 'directory') {\n continue;\n }\n\n const recordPath = resolve(stageDir, entry.name, RUN_RECORD_FILENAME);\n if (!(await this.pathExists(recordPath))) {\n continue;\n }\n\n const record = await this.readListableRunRecord(workspace, stage, entry.name, recordPath);\n if (record) {\n records.set(record.runKey, record);\n }\n }\n }\n\n return [...records.values()];\n }\n\n /**\n * Resolve the run stage, first converting dead running records into\n * interrupted terminal records so reruns are unblocked.\n */\n private async findReusableRunStage(workspace: string, runKey: string): Promise<WorkflowStage | null> {\n const existingStage = await this.findRunStage(workspace, runKey);\n if (existingStage !== RUNNING_STAGE) {\n return existingStage;\n }\n\n await this.reconcileStaleRunningRecord(workspace, runKey);\n return this.findRunStage(workspace, runKey);\n }\n\n /**\n * Read a running record for status displays without mutating it on disk.\n * If the recorded PID is gone, mark the returned record as stale but keep\n * the persisted state untouched so the original failure metadata is not\n * destroyed by a read-only status query.\n */\n private async inspectRunningRecord(workspace: string, runKey: string): Promise<WorkflowRunRecord> {\n const runningRecordPath = resolve(this.getRunDirectory(workspace, RUNNING_STAGE, runKey), RUN_RECORD_FILENAME);\n const currentRecord = await this.readRunRecord(runningRecordPath);\n\n // A terminal stage here means finalization wrote the record but has not\n // moved the directory yet, or died before it could. Either way it is\n // finished, not stale.\n if (currentRecord.stage !== RUNNING_STAGE || !currentRecord.pid || this.isProcessAlive(currentRecord.pid)) {\n return currentRecord;\n }\n\n return {\n ...currentRecord,\n effectiveOutcome: 'interrupted',\n effectiveStage: ERROR_STAGE,\n stale: true,\n staleReason: `${STALE_RUNNING_ERROR_PREFIX}: pid ${currentRecord.pid}`,\n };\n }\n\n /**\n * Read a running record for stale reconciliation. Malformed records cannot\n * be safely converted to terminal records, so they are skipped consistently\n * with list/count operations instead of blocking unrelated workflow runs.\n */\n private async inspectReconcilableRunningRecord(workspace: string, runKey: string): Promise<WorkflowRunRecord | null> {\n try {\n return await this.inspectRunningRecord(workspace, runKey);\n } catch (error) {\n if (error instanceof InvalidWorkflowRunRecordError) {\n return null;\n }\n\n throw error;\n }\n }\n\n /**\n * Read a run record for status listing. Invalid persisted records are\n * skipped explicitly by returning null so callers do not need to suppress\n * exceptions inline.\n */\n private async readListableRunRecord(\n workspace: string,\n stage: WorkflowStage,\n runKey: string,\n recordPath: string,\n ): Promise<WorkflowRunRecord | null> {\n try {\n if (stage === RUNNING_STAGE) return await this.inspectRunningRecord(workspace, runKey);\n const record = await this.readRunRecord(recordPath);\n // Written by versions that renamed before writing the terminal record:\n // the directory is the commit, so its stage wins over the stale field.\n if (record.stage !== RUNNING_STAGE) return record;\n return {\n ...record,\n finishedAt:\n record.finishedAt ??\n new Date(\n getOrThrow(await this.runtime.fs.fileInfo(recordPath, this.runtime.ioContext)).mtimeMs,\n ).toISOString(),\n outcome: record.outcome ?? (stage === COMPLETED_STAGE ? 'success' : 'interrupted'),\n stage,\n };\n } catch (error) {\n if (error instanceof InvalidWorkflowRunRecordError) {\n return null;\n }\n\n throw error;\n }\n }\n\n /**\n * Convert a stale running record into an interrupted error record when its\n * recorded PID is no longer alive.\n */\n private async reconcileStaleRunningRecord(workspace: string, runKey: string): Promise<WorkflowRunRecord> {\n const runningDir = this.getRunDirectory(workspace, RUNNING_STAGE, runKey);\n const runningRecordPath = resolve(runningDir, RUN_RECORD_FILENAME);\n const currentRecord = await this.readRunRecord(runningRecordPath);\n\n if (!currentRecord.pid || this.isProcessAlive(currentRecord.pid)) {\n return currentRecord;\n }\n\n // Finalization already wrote the outcome and died before moving the\n // directory, so finish the move instead of overwriting it as interrupted.\n if (currentRecord.stage !== RUNNING_STAGE) {\n const stageDir = this.getRunDirectory(workspace, currentRecord.stage, runKey);\n await this.removeFileIfExists(resolve(runningDir, FINALIZING_FILENAME));\n getOrThrow(await this.runtime.fs.remove(stageDir, { recursive: true, force: true }, this.runtime.ioContext));\n getOrThrow(await this.runtime.fs.renameFile(runningDir, stageDir, this.runtime.ioContext));\n return currentRecord;\n }\n\n const errorDir = this.getRunDirectory(workspace, ERROR_STAGE, runKey);\n const finalRecord: WorkflowRunRecord = {\n ...currentRecord,\n errorMessage: `${STALE_RUNNING_ERROR_PREFIX}: pid ${currentRecord.pid}`,\n exitCode: INTERRUPTED_EXIT_CODE,\n failedJob: currentRecord.failedJob ?? currentRecord.executionCursor?.job,\n finishedAt: new Date().toISOString(),\n outcome: 'interrupted',\n stage: ERROR_STAGE,\n };\n\n getOrThrow(await this.runtime.fs.remove(errorDir, { recursive: true, force: true }, this.runtime.ioContext));\n getOrThrow(await this.runtime.fs.renameFile(runningDir, errorDir, this.runtime.ioContext));\n await this.writeRunRecord(resolve(errorDir, RUN_RECORD_FILENAME), finalRecord);\n\n return finalRecord;\n }\n\n /**\n * Enumerate known workspace directory names.\n */\n private async listWorkspaceNames(): Promise<string[]> {\n const workspacesDir = resolve(this.homeDir, WORKSPACES_DIRNAME);\n if (!(await this.pathExists(workspacesDir))) {\n return [];\n }\n\n const entries = getOrThrow(await this.runtime.fs.listDir(workspacesDir, this.runtime.ioContext));\n return entries\n .filter((entry) => entry.kind === 'directory')\n .map((entry) => entry.name)\n .sort((left, right) => left.localeCompare(right));\n }\n\n /**\n * Order runs by latest activity across all stages.\n */\n private compareRunRecordsByLatest(left: WorkflowRunRecord, right: WorkflowRunRecord): number {\n const leftTimestamp = left.finishedAt ?? left.startedAt;\n const rightTimestamp = right.finishedAt ?? right.startedAt;\n const timeDifference = rightTimestamp.localeCompare(leftTimestamp);\n if (timeDifference !== 0) {\n return timeDifference;\n }\n\n const workspaceDifference = left.workspace.localeCompare(right.workspace);\n if (workspaceDifference !== 0) {\n return workspaceDifference;\n }\n\n return left.runKey.localeCompare(right.runKey);\n }\n\n /**\n * Persist a run record with stable formatting.\n */\n private async writeRunRecord(recordPath: string, record: WorkflowRunRecord): Promise<void> {\n await this.writeAtomic(recordPath, record);\n }\n\n /**\n * Validate the persisted run record shape before returning it to callers.\n */\n private validateRunRecord(value: unknown, recordPath: string): WorkflowRunRecord {\n const result = WorkflowRunRecordSchema.safeParse(value);\n if (!result.success) {\n throw new InvalidWorkflowRunRecordError(recordPath, result.error.message);\n }\n return result.data;\n }\n\n /**\n * Resolve the directory for a workspace-scoped run stage.\n */\n private getRunStageDirectory(workspace: string, stage: WorkflowStage): string {\n return resolve(this.homeDir, WORKSPACES_DIRNAME, workspace, stage);\n }\n\n /**\n * Resolve the directory for a single run inside a stage.\n */\n private getRunDirectory(workspace: string, stage: WorkflowStage, runKey: string): string {\n return resolve(this.getRunStageDirectory(workspace, stage), runKey);\n }\n\n /**\n * Directory holding a run's artifacts, derived from a listed record.\n *\n * A record carries workspace, stage, and run key but not its own path, so a\n * reader that wants an artifact such as the progress log would otherwise have\n * to reconstruct the layout itself and drift from it.\n */\n runDirectoryFor(record: Pick<WorkflowRunRecord, 'runKey' | 'stage' | 'workspace'>): string {\n return this.getRunDirectory(record.workspace, record.stage, record.runKey);\n }\n\n /**\n * The directory every workspace lives under.\n *\n * Exposed so an observer can watch exactly what this service writes. Deriving\n * it independently would let the two drift, and a watcher pointed at the\n * wrong tree reports nothing rather than failing.\n */\n workspacesDirectory(): string {\n return resolve(this.homeDir, WORKSPACES_DIRNAME);\n }\n\n /**\n * Test whether a path exists while preserving unexpected filesystem errors.\n */\n private async pathExists(path: string): Promise<boolean> {\n try {\n getOrThrow(await this.runtime.fs.fileInfo(path, this.runtime.ioContext));\n return true;\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Remove a file when present without masking other filesystem failures.\n */\n private async removeFileIfExists(path: string): Promise<void> {\n try {\n getOrThrow(await this.runtime.fs.remove(path, undefined, this.runtime.ioContext));\n } catch (error) {\n if (!['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) {\n throw error;\n }\n }\n }\n\n /**\n * Normalize a user-supplied workspace or run name into a safe directory key.\n */\n private slugifySegment(value: string, fallback: string): string {\n const normalized = value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, SLUG_SEPARATOR)\n .replace(/^-+|-+$/g, '');\n\n return normalized || fallback;\n }\n\n /**\n * Check whether a locally tracked process still exists.\n */\n private isProcessAlive(pid: number): boolean {\n try {\n this.runtime.workflowHost.signal(pid, 0);\n return true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ESRCH') {\n return false;\n }\n if (code === 'EPERM') {\n return true;\n }\n throw error;\n }\n }\n}\n","/**\n * Structured error raised when a workspace has reached its maximum concurrent workflow limit.\n */\nexport class WorkflowCapacityError extends Error {\n readonly code = 'WORKFLOW_CAPACITY_EXCEEDED';\n\n constructor(\n public readonly workspace: string,\n public readonly running: number,\n public readonly max: number,\n ) {\n super(\n `Workspace \"${workspace}\" is at capacity: ${running}/${max} workflows running.\\n` +\n ` → Check running workflows: list-workflow-statuses --workspace ${workspace}\\n` +\n ` → Wait for a running workflow to complete, or cancel one before dispatching again.`,\n );\n this.name = 'WorkflowCapacityError';\n }\n}\n","export interface WorkflowInterruptContext {\n phase: string;\n jobName?: string;\n stepName?: string;\n commandPreview?: string;\n source?: string;\n}\n\nexport interface WorkflowInterruptedErrorOptions {\n cause?: unknown;\n context?: WorkflowInterruptContext;\n}\n\n/**\n * Structured interruption error for workflow shutdown paths.\n */\nexport class WorkflowInterruptedError extends Error {\n readonly code = 'WORKFLOW_INTERRUPTED';\n readonly context?: WorkflowInterruptContext;\n\n constructor(\n public readonly signal: NodeJS.Signals,\n options: WorkflowInterruptedErrorOptions = {},\n ) {\n const contextSuffix = options.context ? ` during ${options.context.phase}` : '';\n super(`Workflow interrupted by ${signal}${contextSuffix}`, {\n cause: options.cause ?? options.context,\n });\n this.name = 'WorkflowInterruptedError';\n this.context = options.context;\n }\n}\n","/**\n * BackgroundServiceManager\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { dirname, join, resolve } from 'node:path';\n\nimport { pathExists } from '@agimon-ai/po-core/platform';\n\nimport type { ServiceDef } from '../../schemas/workflowEngine';\nimport type { Logger, RunningService } from '../workflowEngine/type';\nimport { workflowShellOutput } from '../workflowRuntime';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport { escapeShellArg } from '../workflowShell';\n\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\nconst GREEN = '\\x1b[32m';\nconst RED = '\\x1b[31m';\nconst BLUE = '\\x1b[34m';\nconst DEFAULT_HOST = '127.0.0.1';\nconst DEFAULT_ENVIRONMENT = 'development';\nconst WORKSPACE_MARKERS = ['pnpm-workspace.yaml', 'nx.json', '.git'];\n\nasync function resolveWorkspaceRoot(runtime: WorkflowRuntimeContext, startPath: string): Promise<string> {\n let currentDir = resolve(runtime.cwd, startPath);\n\n while (true) {\n for (const marker of WORKSPACE_MARKERS) {\n if (await pathExists(runtime.fs, join(currentDir, marker), runtime.ioContext)) {\n return currentDir;\n }\n }\n\n const parentDir = dirname(currentDir);\n if (parentDir === currentDir) {\n return startPath;\n }\n\n currentDir = parentDir;\n }\n}\n\nexport class BackgroundServiceManager {\n private runningServices: RunningService[] = [];\n constructor(\n private runtime: WorkflowRuntimeContext,\n private logger: Logger,\n ) {}\n\n private resolveWorkingDirectory(service: ServiceDef, workflowDir: string): string {\n return resolve(this.runtime.cwd, workflowDir, service['working-directory'] ?? '');\n }\n\n getRunningServices(): RunningService[] {\n return this.runningServices;\n }\n\n async startService(\n service: ServiceDef,\n baseEnv: Record<string, string>,\n workflowDir: string,\n dryRun: boolean,\n ): Promise<RunningService | null> {\n const command = service.run;\n\n if (dryRun) {\n this.logger.info(` ${BLUE}dry ${RESET} ${service.name}`);\n this.logger.info(` ${DIM}$ ${command}${RESET}`);\n return null;\n }\n\n this.logger.info(` ${BLUE}start${RESET} ${service.name}`);\n this.logger.info(` ${DIM}$ ${command}${RESET}`);\n\n const serviceEnv: Record<string, string> = { ...this.runtime.baseEnvironment, ...baseEnv } as Record<\n string,\n string\n >;\n if (service.env) {\n for (const [key, val] of Object.entries(service.env)) {\n serviceEnv[key] = String(val);\n }\n }\n\n const workDir = this.resolveWorkingDirectory(service, workflowDir);\n const repositoryPath = await resolveWorkspaceRoot(this.runtime, workDir);\n const environment = serviceEnv.NODE_ENV ?? this.runtime.baseEnvironment.NODE_ENV ?? DEFAULT_ENVIRONMENT;\n const host = service.host ?? DEFAULT_HOST;\n let reservedPort: number | undefined;\n\n if (service.port !== undefined || service['port-range']) {\n const portResult = await this.runtime.workflowHost.portRegistry.reservePort({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n preferredPort: service.port,\n portRange: service['port-range'],\n host,\n force: true,\n });\n\n if (!portResult.success || portResult.port === undefined) {\n throw new Error(portResult.error ?? `Failed to reserve port for background service ${service.name}`);\n }\n\n reservedPort = portResult.port;\n serviceEnv.PORT ??= String(reservedPort);\n serviceEnv.SERVICE_PORT ??= String(reservedPort);\n serviceEnv.HOST ??= host;\n serviceEnv.SERVICE_HOST ??= host;\n }\n\n let child: ReturnType<WorkflowRuntimeContext['workflowHost']['spawn']>;\n try {\n child = this.runtime.workflowHost.spawn(command, [], {\n stdio: ['ignore', 'pipe', 'pipe'],\n cwd: workDir,\n env: { ...serviceEnv, FORCE_COLOR: '1' },\n shell: '/bin/zsh',\n detached: true,\n });\n } catch (error) {\n if (reservedPort !== undefined) {\n await this.runtime.workflowHost.portRegistry.releasePort({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n force: true,\n });\n }\n throw error;\n }\n\n if (child.pid === undefined) {\n if (reservedPort !== undefined) {\n await this.runtime.workflowHost.portRegistry.releasePort({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n force: true,\n });\n }\n\n throw new Error(`Failed to spawn background service ${service.name}`);\n }\n\n const prefix = `${BLUE}[${service.name}]${RESET}`;\n child.stdout?.on('data', (data: Buffer) => {\n for (const line of data.toString().split('\\n')) {\n if (line.trim()) this.logger.info(`${prefix} ${line}`);\n }\n });\n child.stderr?.on('data', (data: Buffer) => {\n for (const line of data.toString().split('\\n')) {\n if (line.trim()) this.logger.error(`${prefix} ${line}`);\n }\n });\n\n child.on('error', (err) => {\n this.logger.error(`${prefix} Process error: ${err.message}`);\n });\n\n let release = async () => {\n if (reservedPort !== undefined) {\n await this.runtime.workflowHost.portRegistry.releasePort({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n force: true,\n });\n }\n };\n\n if (child.pid !== undefined) {\n const registerResult = await this.runtime.workflowHost.processRegistry\n .registerProcess({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n pid: child.pid,\n port: reservedPort,\n host: reservedPort !== undefined ? host : undefined,\n command,\n args: [],\n metadata: {\n workingDirectory: workDir,\n readyCheck: service['ready-check'],\n },\n force: true,\n })\n .catch((error: unknown) => ({ success: false, error: error instanceof Error ? error.message : String(error) }));\n\n if (!registerResult.success) {\n try {\n this.runtime.workflowHost.signal(-child.pid, 'SIGTERM');\n } catch {\n child.kill('SIGTERM');\n }\n\n if (reservedPort !== undefined) {\n await this.runtime.workflowHost.portRegistry.releasePort({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n force: true,\n });\n }\n\n throw new Error(registerResult.error ?? `Failed to register process for background service ${service.name}`);\n }\n\n release = async () => {\n const releaseProcessResult = await this.runtime.workflowHost.processRegistry.releaseProcess({\n repositoryPath,\n serviceName: service.name,\n serviceType: service['service-type'] ?? 'tool',\n environment,\n pid: child.pid,\n kill: true,\n releasePort: true,\n force: true,\n });\n\n if (!releaseProcessResult.success && !releaseProcessResult.error?.includes('No matching process entry')) {\n throw new Error(releaseProcessResult.error ?? `Failed to release ${service.name}`);\n }\n };\n }\n\n const runningSvc: RunningService = { name: service.name, process: child, env: serviceEnv, release };\n this.runningServices.push(runningSvc);\n return runningSvc;\n }\n\n async waitForServiceReady(\n service: ServiceDef,\n workflowDir: string,\n baseEnv: Record<string, string>,\n shouldAbort?: () => boolean,\n ): Promise<boolean> {\n if (!service['ready-check'] || typeof service['ready-check'] !== 'string') return true;\n\n const timeout = (service['ready-timeout'] || 30) * 1000;\n const start = Date.now();\n const checkCmd = service['ready-check'];\n const workDir = this.resolveWorkingDirectory(service, workflowDir);\n const runningService = this.runningServices.find((entry) => entry.name === service.name);\n const readyEnv = runningService?.env ?? ({ ...this.runtime.baseEnvironment, ...baseEnv } as Record<string, string>);\n\n this.logger.info(` ${DIM}wait${RESET} Waiting for ${service.name} to be ready...`);\n\n while (Date.now() - start < timeout) {\n if (shouldAbort?.()) {\n return false;\n }\n\n try {\n await workflowShellOutput(this.runtime, `/bin/zsh -c ${escapeShellArg(checkCmd)}`, {\n cwd: workDir,\n environment: readyEnv,\n timeoutMs: 5000,\n });\n this.logger.info(` ${GREEN}ready${RESET} ${service.name}`);\n return true;\n } catch {\n if (shouldAbort?.()) {\n return false;\n }\n }\n\n await new Promise((resolveDelay) => {\n setTimeout(resolveDelay, 1000);\n });\n }\n\n if (shouldAbort?.()) {\n return false;\n }\n\n this.logger.error(` ${RED}timeout${RESET} ${service.name} not ready after ${service['ready-timeout'] || 30}s`);\n return false;\n }\n\n async stopAll(): Promise<void> {\n if (this.runningServices.length === 0) return;\n\n this.logger.info(`\\n ${BLUE}${BOLD}pre${RESET} ${BOLD}Stopping services${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n for (const svc of this.runningServices) {\n if (!svc.process.killed && svc.process.pid) {\n this.logger.info(` ${DIM}stop${RESET} ${svc.name} (pid ${svc.process.pid})`);\n }\n\n if (svc.release) {\n try {\n await svc.release();\n continue;\n } catch (error) {\n this.logger.warn(\n ` ${RED}warn${RESET} Failed registry cleanup for ${svc.name}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n\n if (!svc.process.killed && svc.process.pid) {\n try {\n this.runtime.workflowHost.signal(-svc.process.pid, 'SIGTERM');\n } catch {\n svc.process.kill('SIGTERM');\n }\n }\n }\n\n this.runningServices = [];\n }\n}\n","import type { PoTraceContext } from '@agimon-ai/po-core/telemetry';\n\nimport type { Logger } from '../workflowEngine/type';\n\n/** Telemetry belongs to the caller's scope. Exporter failures never change a run's outcome. */\nexport function createWorkflowLogger(baseLogger: Logger): Logger {\n return {\n ...baseLogger,\n async event(...args) {\n try {\n await baseLogger.event?.(...args);\n } catch {\n // The caller owns exporter recovery; workflow execution must continue.\n }\n },\n async flush() {\n try {\n await baseLogger.flush?.();\n } catch {\n // A telemetry outage must not replace the run's result during cleanup.\n }\n },\n };\n}\n\n/** Delegate fallback to PoTelemetry, never retry work after a span error. */\nexport function runWorkflowSpan<T>(\n logger: Logger,\n name: string,\n attributes: Record<string, unknown>,\n work: (context?: PoTraceContext) => Promise<T> | T,\n): Promise<T> {\n return logger.runInSpan ? logger.runInSpan(name, attributes, work) : Promise.resolve().then(() => work());\n}\n","/**\n * JobRunnerService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { dirname, resolve } from 'node:path';\n\nimport { getOrThrow, pathExists } from '@agimon-ai/po-core/platform';\n\nimport type { Job, MatrixEntry, RunDirectory, Step, StepExecutionRef } from '../../schemas/workflowEngine';\nimport { RunDirectoryService } from '../RunDirectoryService';\nimport type { RunDirectoryWrite, StepArtifactSnapshot } from '../RunDirectoryService/types';\nimport {\n stepDecisionInstructions,\n WORKFLOW_DECISION_INSTRUCTIONS_ENV,\n WORKFLOW_RESTART_TARGETS_ENV,\n writeFixRequest,\n} from '../StepDecisionService';\nimport type { StepRunnerService } from '../StepRunnerService';\nimport type { Logger, StepDecisionReport, StepRunOptions } from '../workflowEngine/type';\nimport type { WorkflowParserService } from '../WorkflowParserService';\nimport { WorkflowProgressService } from '../WorkflowProgressService';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport { runWorkflowSpan } from '../workflowTelemetry';\n\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\nconst GREEN = '\\x1b[32m';\nconst YELLOW = '\\x1b[33m';\nconst RED = '\\x1b[31m';\nconst MAGENTA = '\\x1b[35m';\nconst WORKFLOW_JOB_ID_ENV_KEY = 'WORKFLOW_JOB_ID';\nconst WORKFLOW_JOB_NAME_ENV_KEY = 'WORKFLOW_JOB_NAME';\nconst PROCESS_REGISTRY_TAG_ENV_KEY = 'PROCESS_REGISTRY_TAG';\nconst WORKFLOW_FIX_LOOP_DISABLED_ENV_KEY = 'WORKFLOW_FIX_LOOP_DISABLED';\nconst WORKFLOW_ACTIVE_REPAIR_PROMPT_ENV_KEY = 'WORKFLOW_ACTIVE_REPAIR_PROMPT';\n\ntype FixDecision = Extract<StepDecisionReport, { decision: 'fix' }>;\n\n/** Every step a job runs, with parallel groups opened up. */\nfunction jobSteps(job: Job): Step[] {\n return [...(job.preJob?.steps ?? []), ...(job.steps ?? []), ...(job.postJob?.steps ?? [])].flatMap(\n (step) => step.parallel ?? [step],\n );\n}\n\n/**\n * Whether a job's agents still end through fix.md: any job without templated\n * steps, and any with customRun or command-map steps beside them. Only a job\n * whose agents all run templated commands is told to use `workflow-mcp step`\n * alone.\n */\nfunction usesFixFileContract(job: Job): boolean {\n const steps = jobSteps(job);\n const templated = steps.some((step) => Array.isArray(step.interactiveRun));\n const legacyAgent = steps.some(\n (step) =>\n step.customRun !== undefined || (step.interactiveRun !== undefined && !Array.isArray(step.interactiveRun)),\n );\n return !templated || legacyAgent;\n}\n\nfunction envFlagEnabled(value: string | undefined): boolean {\n return ['1', 'true', 'yes', 'on'].includes(\n String(value ?? '')\n .trim()\n .toLowerCase(),\n );\n}\n\n/**\n * The agent step that ends a sequence: the last step, or the last agent step\n * of a parallel group that ends it. A sequence that ends with a script has\n * none, since that script may still write what the job produces.\n */\nfunction finalAgentStep(steps: readonly Step[]): Step | undefined {\n const last = steps.at(-1);\n if (last === undefined) return undefined;\n return ((last.parallel as Step[] | undefined) ?? [last])\n .filter((step) => step.interactiveRun !== undefined || step.customRun !== undefined)\n .at(-1);\n}\n\n/** What one attempt of a job writes: its outputs to hold, and a record after each step. */\ninterface AttemptWrites {\n /** Every entry the job produces. */\n produced: string[];\n /** The outputs this job has yet to write, as they stood when the attempt began. */\n outputs: StepArtifactSnapshot[];\n stepFinished(stepName: string): Promise<void>;\n}\n\n/**\n * Whether this job is the last to have written an entry: its latest record is\n * this job's, from any attempt or earlier run of the job, so nothing else\n * changed it since. A retry, or a job that skips work it already did, keeps\n * its own output; a file another job wrote after it must be written again.\n */\nfunction lastWrittenBy(records: readonly RunDirectoryWrite[], path: string, jobName: string): boolean {\n return records.filter((record) => record.path === path).at(-1)?.job === jobName;\n}\n\n/**\n * The outputs this job is not the last to have written, each with the job and\n * step that wrote it last, as a reason a reader can act on.\n */\nfunction describeUnwritten(\n records: readonly RunDirectoryWrite[],\n jobName: string,\n paths: readonly string[],\n): string | undefined {\n const unwritten = paths.flatMap((path) => {\n if (lastWrittenBy(records, path, jobName)) return [];\n const last = records.filter((record) => record.path === path && record.job !== undefined).at(-1);\n const by = last ? `last written by job \"${last.job}\", step \"${last.step}\"` : 'not written by any step';\n return [`${path} (${by})`];\n });\n return unwritten.length === 0\n ? undefined\n : `job \"${jobName}\" did not write what it produces: ${unwritten.join(', ')}`;\n}\n\nexport class JobRunnerService {\n constructor(\n private runtime: WorkflowRuntimeContext,\n private parser: WorkflowParserService,\n private stepRunner: StepRunnerService,\n private logger: Logger,\n private runDirectoryService = new RunDirectoryService(runtime),\n ) {}\n\n async runJob(\n jobName: string,\n job: Job,\n context: {\n inputs: Map<string, string>;\n secrets: Map<string, string>;\n workflowEnv: Record<string, string>;\n workflowSystemPrompt?: string;\n jobOrder: string[];\n allJobs: Record<string, Job>;\n repairTriage?: boolean;\n activeRepairIssue?: string;\n /** Job that raised the active repair, when this job is inside its scope. */\n activeRepairVerificationJob?: string;\n allowRepairTerminalStop?: boolean;\n /** Fix cycles already raised in this run, and how many the run allows. */\n fixLoop?: { cycle: number; maxCycles: number };\n runDirectory?: RunDirectory;\n /** Why the job failed, when a step decided so; the run reports it instead of a generic reason. */\n onFailed?: (reason: string) => void;\n onPromptAssembled?: (assembly: { jobName: string; matrix: MatrixEntry; prompt: string }) => void;\n },\n options: {\n cliAgent?: string;\n runner?: string;\n dryRun: boolean;\n continueOnError: boolean;\n stopRequestPath?: string;\n workflowDir: string;\n maxRetries: number;\n onStepStarted?: (\n stepName: string,\n index: number,\n total: number,\n matrixIndex?: number,\n attempt?: number,\n ) => Promise<void> | void;\n onExecutionStateChange?: (state: 'paused' | 'resumed', stepName: string) => Promise<void> | void;\n },\n ): Promise<boolean> {\n return runWorkflowSpan(\n this.logger,\n 'workflow.job',\n {\n 'workflow.run.id': context.workflowEnv.WORKFLOW_RUN_ID ?? '',\n 'workflow.job.name': jobName,\n },\n async () => {\n const matrixCombos = this.parser.expandMatrix(job);\n const maxRetries = options.maxRetries;\n\n for (const [matrixIndex, matrix] of matrixCombos.entries()) {\n const jobExecutionId = randomUUID();\n const matrixLabel =\n Object.keys(matrix).length > 0\n ? ` ${DIM}(${Object.entries(matrix)\n .map(([k, v]) => `${k}=${v}`)\n .join(', ')})${RESET}`\n : '';\n\n this.logger.info(`\\n ${MAGENTA}${BOLD}job${RESET} ${BOLD}${jobName}${RESET}${matrixLabel}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n // Merge env: workflow env -> job env\n const jobEnv: Record<string, string> = {\n ...context.workflowEnv,\n [WORKFLOW_JOB_ID_ENV_KEY]: jobExecutionId,\n [WORKFLOW_JOB_NAME_ENV_KEY]: jobName,\n [PROCESS_REGISTRY_TAG_ENV_KEY]: jobExecutionId,\n };\n if (job.env) {\n for (const [key, val] of Object.entries(job.env)) {\n jobEnv[key] = this.parser.interpolate(String(val), {\n inputs: context.inputs,\n matrix,\n secrets: context.secrets,\n env: jobEnv,\n });\n }\n }\n // Run identity belongs to the engine, not job-level overrides.\n for (const key of [\n 'WORKFLOW_RUN_ID',\n 'WORKFLOW_RUN_KEY',\n 'WORKFLOW_RUN_DIR',\n 'WORKFLOW_WORKSPACE',\n 'WORKFLOW_PHASE',\n ]) {\n if (context.workflowEnv[key] !== undefined) jobEnv[key] = context.workflowEnv[key];\n else delete jobEnv[key];\n }\n jobEnv[WORKFLOW_JOB_ID_ENV_KEY] = jobExecutionId;\n jobEnv[WORKFLOW_JOB_NAME_ENV_KEY] = jobName;\n jobEnv[PROCESS_REGISTRY_TAG_ENV_KEY] = jobExecutionId;\n for (const key of [\n 'WORKFLOW_ACTIVE_REPAIR_ID',\n 'WORKFLOW_ACTIVE_REPAIR_DIR',\n 'WORKFLOW_ACTIVE_REPAIR_FILE',\n 'WORKFLOW_ACTIVE_ISSUE_FILE',\n ]) {\n if (context.workflowEnv[key]) {\n jobEnv[key] = context.workflowEnv[key];\n } else {\n delete jobEnv[key];\n }\n }\n if (!context.repairTriage) {\n delete jobEnv[WORKFLOW_ACTIVE_REPAIR_PROMPT_ENV_KEY];\n }\n this.logger.info(` ${DIM}jobid${RESET} ${jobExecutionId}`);\n const fixLoopDisabled = envFlagEnabled(jobEnv[WORKFLOW_FIX_LOOP_DISABLED_ENV_KEY]);\n const fixFileContract = usesFixFileContract(job);\n const currentJobIndex = context.jobOrder.indexOf(jobName);\n const reachedJobs = currentJobIndex >= 0 ? context.jobOrder.slice(0, currentJobIndex + 1) : [jobName];\n if (jobEnv.WORKFLOW_RUN_DIR) {\n // Steps record their outcome with `workflow-mcp step`; these tell them\n // which jobs a fix may restart from, and what to tell their agents.\n const restartTargets = fixLoopDisabled || context.repairTriage ? [] : reachedJobs;\n jobEnv[WORKFLOW_RESTART_TARGETS_ENV] = restartTargets.join(',');\n jobEnv[WORKFLOW_DECISION_INSTRUCTIONS_ENV] = stepDecisionInstructions(\n jobEnv.WORKFLOW_RUN_DIR,\n jobName,\n restartTargets,\n );\n } else {\n delete jobEnv[WORKFLOW_RESTART_TARGETS_ENV];\n delete jobEnv[WORKFLOW_DECISION_INSTRUCTIONS_ENV];\n }\n let runDirectoryGuidance: string | undefined;\n if (jobEnv.WORKFLOW_RUN_DIR) {\n const inspection = await this.runDirectoryService.inspect(jobEnv.WORKFLOW_RUN_DIR, context.runDirectory, {\n jobName,\n jobOrder: context.jobOrder,\n planned: options.dryRun,\n });\n runDirectoryGuidance = this.runDirectoryService.formatInspection(inspection);\n }\n // Which step wrote each declared entry is recorded as each step\n // finishes, so a job that must write an entry is held to its own write,\n // not to one an earlier job made.\n const declaredEntries = context.runDirectory?.entries ?? [];\n const writesRunDir = options.dryRun || declaredEntries.length === 0 ? undefined : jobEnv.WORKFLOW_RUN_DIR;\n const jobStartedAt = Date.now();\n await this.logger.event?.('info', 'workflow.job.started', {\n attributes: this.buildLifecycleAttributes(jobEnv, {\n 'workflow.job.attempt_limit': maxRetries,\n }),\n });\n\n // Inject system-prompt as env var (runner default + workflow-level + job-level)\n const promptParts: string[] = [];\n\n // Runner-level default prompt (fix.md convention + workflow structure)\n if (jobEnv.WORKFLOW_RUN_DIR && !fixLoopDisabled) {\n if (!context.repairTriage && fixFileContract) {\n const jobList = reachedJobs\n .map((name) => {\n const description = context.allJobs[name]?.description ?? 'No description provided.';\n return ` - Job key: ${name}\\n Description: ${description}`;\n })\n .join('\\n');\n\n promptParts.push(\n `You are currently running job \"${jobName}\". Valid repair targets reached so far, including previous jobs and the current job:\\n${jobList}\\n\\nWhen you have completed your task, you MUST either:\\n1. If you find bugs, missing features, or issues that need fixes from a previous job, write to ${jobEnv.WORKFLOW_RUN_DIR}/fix.md with a YAML frontmatter restart-from field specifying which job key listed above should handle the fix, followed by a detailed description. Future jobs that are not listed above are not valid restart targets. Example:\\n---\\nrestart-from: ${jobName}\\n---\\nDescription of what needs to be fixed...\\n\\nThe workflow runner will restart from the specified job. Only create fix.md for issues that require code changes, and fix minor issues yourself.\\n2. Otherwise, stop. Do not continue with unrelated work.`,\n );\n const budget = context.fixLoop\n ? ` This run has raised ${context.fixLoop.cycle} of ${context.fixLoop.maxCycles} allowed fix cycles.`\n : '';\n promptParts.push(\n `fix.md is the only way you can fail this job. Ending your session always counts as success, so a failure written only to a report, a review, or chat is recorded as success.${budget} If this job's result is not acceptable, you MUST write ${jobEnv.WORKFLOW_RUN_DIR}/fix.md, even when you believe the fix budget is exhausted. Do not decide that yourself: the runner counts fix cycles and fails the run with a nonzero exit once the budget is spent. If a failure has no earlier job to repair, use restart-from: ${jobName}.`,\n );\n }\n\n if (\n jobEnv.WORKFLOW_ACTIVE_REPAIR_ID &&\n jobEnv.WORKFLOW_ACTIVE_REPAIR_FILE &&\n jobEnv.WORKFLOW_ACTIVE_ISSUE_FILE\n ) {\n promptParts.push(\n context.repairTriage\n ? `You are triaging pending repair ${jobEnv.WORKFLOW_ACTIVE_REPAIR_ID}. Read the complete repair request from ${jobEnv.WORKFLOW_ACTIVE_ISSUE_FILE} and job tracking from ${jobEnv.WORKFLOW_ACTIVE_REPAIR_FILE}. Use only this repair. Do not scan historical issue folders, and do not edit or delete issue.md or the runner-owned repair.json.`\n : `This job is part of active repair ${jobEnv.WORKFLOW_ACTIVE_REPAIR_ID}. Read the complete repair request from ${jobEnv.WORKFLOW_ACTIVE_ISSUE_FILE} and job tracking from ${jobEnv.WORKFLOW_ACTIVE_REPAIR_FILE} before working. Use only this active repair. Do not scan historical issue folders, and do not edit or delete issue.md or the runner-owned repair.json.`,\n );\n if (context.activeRepairIssue) {\n promptParts.push(`Active repair request:\\n\\n${context.activeRepairIssue}`);\n }\n if (!context.repairTriage && context.activeRepairVerificationJob) {\n const verifierIndex = context.jobOrder.indexOf(context.activeRepairVerificationJob);\n const currentIndex = context.jobOrder.indexOf(jobName);\n const forwardTargets =\n currentIndex >= 0 && verifierIndex > currentIndex\n ? context.jobOrder.slice(currentIndex + 1, verifierIndex + 1)\n : [];\n if (forwardTargets.length > 0) {\n const targetList = forwardTargets\n .map((name) => {\n const description = context.allJobs[name]?.description ?? 'No description provided.';\n return ` - Job key: ${name}\\n Description: ${description}`;\n })\n .join('\\n');\n promptParts.push(\n `This repair replays every job from here to \"${context.activeRepairVerificationJob}\", the job that raised it. If the fix is fully complete and some of those jobs have no work left to do for it, you may skip ahead by writing ${jobEnv.WORKFLOW_RUN_DIR}/proceed.md with this YAML frontmatter:\\n---\\nproceed-to: ${context.activeRepairVerificationJob}\\n---\\nThen explain why the skipped jobs are unnecessary. Valid forward targets:\\n${targetList}\\n\\nUse proceed-to: ${context.activeRepairVerificationJob} to go straight back to the job that raised the fix. Skipped jobs will not run, so their outputs will not be refreshed; skip a job only when you are certain this fix does not change what it would produce. If you are unsure, do not write proceed.md and the workflow continues job by job. If you instead found a new issue, write fix.md — it always takes precedence over proceed.md.`,\n );\n }\n }\n if ((context.repairTriage || context.allowRepairTerminalStop) && fixFileContract) {\n promptParts.push(\n `If this repair cannot proceed because of a proven external blocker, write ${jobEnv.WORKFLOW_RUN_DIR}/fix.md with this YAML frontmatter:\\n---\\nstatus: stop\\n---\\nThen explain the blocker and the evidence. Use status: stop only for a confirmed blocker that cannot be fixed within this workflow run.`,\n );\n }\n if (context.repairTriage && jobEnv.WORKFLOW_ACTIVE_REPAIR_PROMPT) {\n promptParts.push(jobEnv.WORKFLOW_ACTIVE_REPAIR_PROMPT);\n }\n }\n }\n\n if (context.workflowSystemPrompt) {\n promptParts.push(\n this.parser.interpolate(context.workflowSystemPrompt, {\n inputs: context.inputs,\n matrix,\n secrets: context.secrets,\n env: jobEnv,\n }),\n );\n }\n if (runDirectoryGuidance) {\n promptParts.push(runDirectoryGuidance);\n }\n if (job['system-prompt']) {\n promptParts.push(\n this.parser.interpolate(job['system-prompt'], {\n inputs: context.inputs,\n matrix,\n secrets: context.secrets,\n env: jobEnv,\n }),\n );\n }\n if (promptParts.length > 0) {\n const prompt = promptParts.join('\\n\\n');\n jobEnv.JOB_SYSTEM_PROMPT = prompt;\n context.onPromptAssembled?.({ jobName, matrix, prompt });\n this.logger.info(\n ` ${DIM}prompt${RESET} ${prompt.split('\\n')[0].slice(0, 80)}${prompt.includes('\\n') ? '...' : ''}`,\n );\n }\n\n // Load context file content into env var\n const contextPath = job.context\n ? this.parser.interpolate(job.context, {\n inputs: context.inputs,\n matrix,\n secrets: context.secrets,\n env: jobEnv,\n })\n : jobEnv.CONTEXT_FILE;\n\n if (contextPath) {\n const resolvedPath = resolve(this.runtime.cwd, options.workflowDir, contextPath);\n if (await pathExists(this.runtime.fs, resolvedPath, this.runtime.ioContext)) {\n jobEnv.WORKFLOW_CONTEXT = resolvedPath;\n jobEnv.WORKFLOW_CONTEXT_FILE = resolvedPath;\n this.logger.info(` ${DIM}ctx ${RESET} ${contextPath}`);\n } else if (!options.dryRun) {\n this.logger.warn(` ${YELLOW}warn${RESET} context file not found: ${contextPath}`);\n }\n }\n\n // Load or initialize changelog file\n if (jobEnv.CHANGELOG_FILE) {\n const changelogPath = resolve(this.runtime.cwd, options.workflowDir, jobEnv.CHANGELOG_FILE);\n const changelogDir = dirname(changelogPath);\n if (!(await pathExists(this.runtime.fs, changelogDir, this.runtime.ioContext))) {\n getOrThrow(await this.runtime.fs.createDir(changelogDir, { recursive: true }, this.runtime.ioContext));\n }\n if (!(await pathExists(this.runtime.fs, changelogPath, this.runtime.ioContext))) {\n getOrThrow(await this.runtime.fs.writeFile(changelogPath, '# Changelog\\n', this.runtime.ioContext));\n }\n jobEnv.WORKFLOW_CHANGELOG = changelogPath;\n this.logger.info(` ${DIM}log ${RESET} changelog at ${jobEnv.CHANGELOG_FILE}`);\n }\n\n const stepContext = {\n inputs: context.inputs,\n matrix,\n secrets: context.secrets,\n env: jobEnv,\n };\n\n let jobPassed = false;\n const preJobSteps = job.preJob?.steps ?? [];\n const mainSteps = job.steps ?? [];\n const postJobSteps = job.postJob?.steps ?? [];\n\n let decidedFailure: string | undefined;\n let unwrittenOutputs: string | undefined;\n let fixRequested = false;\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n unwrittenOutputs = undefined;\n if (attempt > 1) {\n this.logger.info(\n `\\n ${YELLOW}retry${RESET} ${BOLD}${jobName}${RESET}${matrixLabel} (attempt ${attempt}/${maxRetries})`,\n );\n this.logger.info(` ${'─'.repeat(50)}`);\n }\n\n // A change made outside a step since the last one finished is nobody's write.\n const baseline = writesRunDir\n ? await this.runDirectoryService.recordWrites(writesRunDir, declaredEntries)\n : undefined;\n const writes =\n writesRunDir && baseline\n ? this.attemptWrites(writesRunDir, jobName, jobEnv, baseline, declaredEntries)\n : undefined;\n\n const decisions: StepDecisionReport[] = [];\n let allStepsPassed = true;\n if (preJobSteps.length > 0) {\n allStepsPassed = await this.runStepSequence(\n preJobSteps,\n stepContext,\n options,\n matrixIndex,\n attempt,\n decisions,\n writes && { ...writes, outputs: [] },\n );\n }\n\n if (allStepsPassed && decisions.length === 0) {\n allStepsPassed = await this.runStepSequence(\n mainSteps,\n stepContext,\n options,\n matrixIndex,\n attempt,\n decisions,\n writes,\n );\n }\n\n if (postJobSteps.length > 0) {\n const postJobPassed = await this.runStepSequence(\n postJobSteps,\n stepContext,\n options,\n matrixIndex,\n attempt,\n decisions,\n writes && { ...writes, outputs: [] },\n );\n allStepsPassed = allStepsPassed && postJobPassed;\n }\n\n // The job must be the last to have written every output it produces.\n if (allStepsPassed && decisions.length === 0 && writesRunDir && writes) {\n unwrittenOutputs = describeUnwritten(\n await this.runDirectoryService.readWrites(writesRunDir),\n jobName,\n writes.produced,\n );\n if (unwrittenOutputs) {\n allStepsPassed = false;\n this.logger.error(` ${RED}error${RESET} ${unwrittenOutputs}`);\n await this.logger.event?.('error', 'workflow.job.outputs_unwritten', {\n attributes: this.buildLifecycleAttributes(jobEnv, {\n 'workflow.job.attempt': attempt,\n 'workflow.job.failure_reason': unwrittenOutputs,\n }),\n });\n }\n }\n\n // A step that decided the job cannot finish ends the run: retrying\n // would only repeat the blocker it reported.\n const failure = decisions.find((decision) => decision.decision === 'fail');\n if (failure) {\n decidedFailure = `Step \"${failure.step}\" failed: ${failure.reason}`;\n break;\n }\n\n // Fix requests, from agents and failing restart-from checks alike,\n // become one repair: the job passes and the run loops back once.\n const fixes = decisions.filter((decision): decision is FixDecision => decision.decision === 'fix');\n if (fixes.length > 0) {\n if (!jobEnv.WORKFLOW_RUN_DIR || fixLoopDisabled || options.dryRun) {\n decidedFailure = `Step \"${fixes[0]?.step}\" requested a fix, but this run cannot loop back: ${fixes[0]?.reason}`;\n break;\n }\n const restartFrom = await writeFixRequest(\n this.runtime,\n jobEnv.WORKFLOW_RUN_DIR,\n context.jobOrder,\n jobName,\n fixes,\n );\n this.logger.warn(\n ` ${YELLOW}Job \"${jobName}\" requested ${fixes.length} fix${fixes.length === 1 ? '' : 'es'}; restarting from \"${restartFrom}\"${RESET}`,\n );\n jobPassed = true;\n fixRequested = true;\n break;\n }\n\n if (allStepsPassed) {\n jobPassed = true;\n break;\n }\n\n if (attempt < maxRetries) {\n this.logger.warn(` ${YELLOW}Job \"${jobName}\" failed, retrying...${RESET}`);\n }\n }\n\n if (decidedFailure) {\n context.onFailed?.(decidedFailure);\n this.logger.error(`\\n ${RED}${decidedFailure}${RESET}`);\n }\n\n if (!jobPassed) {\n // The last attempt failed on what it did not write: that is why the job failed.\n if (!decidedFailure && unwrittenOutputs) context.onFailed?.(unwrittenOutputs);\n this.logger.error(`\\n ${RED}Job \"${jobName}\" failed after ${maxRetries} attempts${RESET}`);\n await this.logger.event?.('error', 'workflow.job.finished', {\n attributes: this.buildLifecycleAttributes(jobEnv, {\n 'workflow.job.duration_ms': Date.now() - jobStartedAt,\n 'workflow.job.outcome': 'failed',\n }),\n });\n if (decidedFailure || job.strategy?.['fail-fast'] !== false) {\n return false;\n }\n } else {\n this.logger.info(` ${GREEN}Job \"${jobName}\" completed${RESET}${matrixLabel}`);\n await this.logger.event?.('info', 'workflow.job.finished', {\n attributes: this.buildLifecycleAttributes(jobEnv, {\n 'workflow.job.duration_ms': Date.now() - jobStartedAt,\n 'workflow.job.outcome': fixRequested ? 'fix' : 'success',\n }),\n });\n // The loop back reruns this job, so its remaining matrix entries would\n // only run against the state the fix is about to change.\n if (fixRequested) return true;\n }\n }\n\n return true;\n },\n );\n }\n\n /**\n * An attempt's outputs, taken from the records at its start, and the record\n * each finished step adds. The step that ends the job is reminded only of\n * outputs another job, or no step, wrote last.\n */\n private attemptWrites(\n runDir: string,\n jobName: string,\n env: Record<string, string>,\n baseline: readonly RunDirectoryWrite[],\n entries: RunDirectory['entries'],\n ): AttemptWrites {\n const latest = new Map(baseline.map((record) => [record.path, record]));\n const jobId = env[WORKFLOW_JOB_ID_ENV_KEY];\n const produced = entries.filter((entry) => entry['produced-by']?.includes(jobName));\n return {\n produced: produced.map((entry) => entry.path),\n outputs: produced\n .filter((entry) => !lastWrittenBy(baseline, entry.path, jobName))\n .map((entry) => ({\n path: entry.path,\n kind: entry.kind,\n description: entry.description,\n job: jobName,\n fingerprint: latest.get(entry.path)?.sha,\n mtimeMs: latest.get(entry.path)?.mtimeMs,\n })),\n stepFinished: async (step) => {\n await this.runDirectoryService.recordWrites(runDir, entries, {\n job: jobName,\n step,\n ...(jobId ? { jobId } : {}),\n });\n },\n };\n }\n\n /**\n * Run steps in order, recording each transition.\n *\n * The recorder is built from the environment rather than threaded through the\n * call chain: WORKFLOW_RUN_DIR and the job name are already there for\n * telemetry, and a run without a run directory records nothing.\n */\n private async runStepSequence(\n steps: Job['steps'],\n context: Parameters<StepRunnerService['runStep']>[1],\n options: Parameters<StepRunnerService['runStep']>[2],\n matrixIndex: number,\n attempt: number,\n decisions: StepDecisionReport[],\n writes?: AttemptWrites,\n ): Promise<boolean> {\n const env = context.env ?? {};\n // An agent step that ends the job is reminded of the job's outputs before it\n // stops; a job that ends with a script is only checked once it ends.\n const jobOutputs = writes?.outputs ?? [];\n const outputOwner = jobOutputs.length > 0 ? finalAgentStep(steps) : undefined;\n const optionsFor = (step: Step): StepRunOptions => (step === outputOwner ? { ...options, jobOutputs } : options);\n const progress = new WorkflowProgressService(this.runtime, env.WORKFLOW_RUN_DIR);\n const jobName = env[WORKFLOW_JOB_NAME_ENV_KEY] ?? '';\n const onDecision = (decision: StepDecisionReport) => {\n decisions.push(decision);\n };\n\n for (const [index, step] of steps.entries()) {\n // Unnamed steps are common, so fall back to a stable positional label\n // rather than recording an empty name a reader cannot match up.\n const stepName = step.name ?? `step ${index + 1}`;\n const started = () => options.onStepStarted?.(stepName, index, steps.length, matrixIndex, attempt);\n const ok = step.parallel\n ? await this.runParallelGroup(\n step.parallel,\n stepName,\n started,\n context,\n optionsFor,\n onDecision,\n progress,\n jobName,\n writes?.stepFinished.bind(writes),\n )\n : await this.runTrackedStep(step, stepName, context, optionsFor(step), onDecision, progress, jobName, {\n index,\n total: steps.length,\n started,\n finished: writes?.stepFinished.bind(writes),\n });\n if (!ok) {\n return false;\n }\n // A decided step ends the sequence: a fix reruns these steps after the\n // loop back, and a failure ends the run.\n if (decisions.length > 0) {\n return true;\n }\n }\n\n return true;\n }\n\n /** Run one step, recording its transitions in the run progress log. */\n private async runTrackedStep(\n step: Step,\n stepName: string,\n context: Parameters<StepRunnerService['runStep']>[1],\n options: StepRunOptions,\n onDecision: (decision: StepDecisionReport) => void,\n progress: WorkflowProgressService,\n jobName: string,\n position: {\n index: number;\n total: number;\n group?: string;\n started?: () => Promise<void> | void;\n /** Records what the step wrote, once it ended either way. */\n finished?: (stepName: string) => Promise<void>;\n },\n runner: StepRunnerService = this.stepRunner,\n ): Promise<boolean> {\n await progress.stepStarted(jobName, stepName, position.index, position.total, position.group);\n await position.started?.();\n let failure: string | undefined;\n const stepOptions: StepRunOptions = {\n ...options,\n onDecision,\n onFailure: (reason: string) => {\n failure = reason;\n options.onFailure?.(reason);\n },\n onExecutionStateChange: async (state: 'paused' | 'resumed', pausedStepName: string) => {\n await options.onExecutionStateChange?.(state, pausedStepName);\n await progress.stepFinished(jobName, pausedStepName, state);\n },\n onExecutionStarted: async (ref: StepExecutionRef) => {\n await options.onExecutionStarted?.(ref);\n await progress.stepExecutionStarted(jobName, stepName, ref);\n },\n };\n const ok = await runner.runStep(step, context, stepOptions);\n await position.finished?.(stepName);\n await progress.stepFinished(jobName, stepName, ok ? 'completed' : 'failed', ok ? undefined : failure);\n return ok;\n }\n\n /**\n * Run a parallel group: every step at once, each on a runner of its own.\n *\n * No step is cancelled when another fails, so every fix request of the\n * group is collected and one loop back fixes them all. An interruption is\n * rethrown once every step has settled.\n */\n private async runParallelGroup(\n steps: Step[],\n groupName: string,\n started: () => Promise<void> | void,\n context: Parameters<StepRunnerService['runStep']>[1],\n optionsFor: (step: Step) => StepRunOptions,\n onDecision: (decision: StepDecisionReport) => void,\n progress: WorkflowProgressService,\n jobName: string,\n finished?: (stepName: string) => Promise<void>,\n ): Promise<boolean> {\n // The execution cursor names the group; the progress log names each step.\n await started();\n const results = await Promise.allSettled(\n steps.map(async (step, index) => {\n const stepName = step.name ?? `${groupName} ${index + 1}`;\n const runner = this.stepRunner.fork(stepName);\n try {\n return await this.runTrackedStep(\n { ...step, name: stepName },\n stepName,\n context,\n optionsFor(step),\n onDecision,\n progress,\n jobName,\n { index, total: steps.length, group: groupName, finished },\n runner,\n );\n } finally {\n this.stepRunner.release(runner);\n }\n }),\n );\n const interrupted = results.find((result) => result.status === 'rejected');\n if (interrupted) throw interrupted.reason;\n return results.every((result) => result.status === 'fulfilled' && result.value);\n }\n\n private buildLifecycleAttributes(\n env: Record<string, string>,\n attributes: Record<string, string | number | boolean>,\n ): Record<string, string | number | boolean> {\n return {\n 'workflow.id': env.WORKFLOW_ID ?? '',\n 'workflow.name': env.WORKFLOW_NAME ?? '',\n 'workflow.workspace': env.WORKFLOW_WORKSPACE ?? '',\n 'workflow.run.id': env.WORKFLOW_RUN_ID ?? '',\n 'workflow.run.key': env.WORKFLOW_RUN_KEY ?? '',\n 'workflow.phase': env.WORKFLOW_PHASE ?? 'job',\n 'workflow.job.id': env[WORKFLOW_JOB_ID_ENV_KEY] ?? '',\n 'workflow.job.name': env[WORKFLOW_JOB_NAME_ENV_KEY] ?? '',\n ...(env.WORKFLOW_ACTIVE_REPAIR_ID ? { 'workflow.repair.id': env.WORKFLOW_ACTIVE_REPAIR_ID } : {}),\n ...attributes,\n };\n }\n}\n","export interface WorkflowStepSpawnContext {\n commandPreview: string;\n source: string;\n stepName: string;\n workDir: string;\n}\n\nexport interface WorkflowStepSpawnErrorOptions {\n cause?: unknown;\n}\n\n/**\n * Structured error raised when a workflow step cannot be spawned.\n */\nexport class WorkflowStepSpawnError extends Error {\n readonly code = 'WORKFLOW_STEP_SPAWN_FAILED';\n\n constructor(\n public readonly context: WorkflowStepSpawnContext,\n options: WorkflowStepSpawnErrorOptions = {},\n ) {\n super(`Failed to start workflow step \"${context.stepName}\"`, {\n cause: options.cause ?? context,\n });\n this.name = 'WorkflowStepSpawnError';\n }\n}\n","export interface WorkflowStepTimeoutConfigContext {\n stepName: string;\n configKey: string;\n timeoutValue: unknown;\n}\n\nexport interface WorkflowStepTimeoutConfigErrorOptions {\n cause?: unknown;\n}\n\n/**\n * Structured error raised when a timeout-related config field is malformed for a workflow step.\n */\nexport class WorkflowStepTimeoutConfigError extends Error {\n readonly code = 'WORKFLOW_STEP_TIMEOUT_CONFIG_INVALID';\n\n constructor(\n public readonly context: WorkflowStepTimeoutConfigContext,\n options: WorkflowStepTimeoutConfigErrorOptions = {},\n ) {\n super(`Invalid ${context.configKey} for workflow step \"${context.stepName}\"`, {\n cause: options.cause ?? context,\n });\n this.name = 'WorkflowStepTimeoutConfigError';\n }\n}\n","import { z } from 'zod';\n\nconst STEP_TIMEOUT_MAX_RETRIES = 2;\nconst STEP_TIMEOUT_RETRIES_LIMIT = 10;\nconst MINUTE_IN_MS = 60_000;\nconst MAX_TIMEOUT_DELAY_MS = 2_147_483_647;\nconst MAX_STEP_TIMEOUT_MINUTES = Math.floor(MAX_TIMEOUT_DELAY_MS / MINUTE_IN_MS);\n\nexport const StepTimeoutMinutesSchema = z.number().positive().finite().max(MAX_STEP_TIMEOUT_MINUTES);\nexport const StepTimeoutRetriesSchema = z\n .number()\n .int()\n .min(0)\n .max(STEP_TIMEOUT_RETRIES_LIMIT)\n .default(STEP_TIMEOUT_MAX_RETRIES);\n","/**\n * CodexQuotaService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n * - Document complex logic with comments\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { join } from 'node:path';\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\n\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nconst DEFAULT_CODEX_HOME_DIRNAME = '.codex';\nconst AUTH_FILENAME = 'auth.json';\nconst CONFIG_FILENAME = 'config.toml';\nconst DEFAULT_CHATGPT_BASE_URL = 'https://chatgpt.com/backend-api/';\nconst CHATGPT_HOST = 'https://chatgpt.com';\nconst CHAT_OPENAI_HOST = 'https://chat.openai.com';\nconst BACKEND_API_SEGMENT = '/backend-api';\nconst QUOTA_USER_AGENT = 'codex-cli';\nconst PRIMARY_WINDOW = 'primary' as const;\nconst SECONDARY_WINDOW = 'secondary' as const;\nconst QUOTA_REACHED_PERCENT = 100;\n\ninterface CodexAuthFile {\n tokens?: {\n access_token?: string;\n account_id?: string;\n };\n}\n\ninterface CodexQuotaWindowPayload {\n limit_window_seconds?: number;\n reset_after_seconds?: number;\n reset_at?: number;\n used_percent?: number;\n}\n\ninterface CodexQuotaLimitPayload {\n allowed?: boolean;\n limit_reached?: boolean;\n primary_window?: CodexQuotaWindowPayload;\n secondary_window?: CodexQuotaWindowPayload;\n}\n\ninterface CodexAdditionalQuotaPayload {\n limit_name?: string;\n metered_feature?: string;\n rate_limit?: CodexQuotaLimitPayload;\n}\n\ninterface CodexQuotaResponsePayload {\n additional_rate_limits?: CodexAdditionalQuotaPayload[];\n plan_type?: string;\n rate_limit?: CodexQuotaLimitPayload;\n}\n\ntype CodexQuotaWindowKind = typeof PRIMARY_WINDOW | typeof SECONDARY_WINDOW;\n\nexport interface CodexQuotaBlock {\n limitId: string;\n limitName: string;\n resetAfterSeconds: number | null;\n resetAt: number;\n usedPercent: number;\n window: CodexQuotaWindowKind;\n windowSeconds: number | null;\n}\n\nexport interface CodexQuotaStatus {\n blockingLimit: CodexQuotaBlock | null;\n planType: string | null;\n}\n\nexport interface CodexQuotaServiceDeps {\n codexHome?: string;\n fetchFn?: typeof fetch;\n now?: () => number;\n readTextFile?: (path: string) => Promise<string>;\n}\n\nexport class CodexQuotaService {\n private readonly codexHome: string;\n\n private readonly fetchFn: typeof fetch;\n\n private readonly now: () => number;\n\n private readonly readTextFile: (path: string) => Promise<string>;\n\n constructor(runtime: WorkflowRuntimeContext, deps: CodexQuotaServiceDeps = {}) {\n this.codexHome =\n deps.codexHome ?? runtime.baseEnvironment.CODEX_HOME ?? join(runtime.homeDirectory, DEFAULT_CODEX_HOME_DIRNAME);\n this.fetchFn = deps.fetchFn ?? fetch;\n this.now = deps.now ?? (() => Date.now());\n this.readTextFile =\n deps.readTextFile ?? (async (path: string) => getOrThrow(await runtime.fs.readTextFile(path, runtime.ioContext)));\n }\n\n isCodexCommand(command: string, _sourceAgentKey?: string): boolean {\n const trimmed = command.trim();\n return trimmed === 'codex' || trimmed.startsWith('codex ');\n }\n\n async getQuotaStatus(): Promise<CodexQuotaStatus | null> {\n const auth = await this.readAuthFile();\n const accessToken = auth?.tokens?.access_token?.trim();\n const accountId = auth?.tokens?.account_id?.trim();\n\n if (!accessToken || !accountId) {\n return null;\n }\n\n const baseUrl = await this.readChatgptBaseUrl();\n const response = await this.fetchFn(this.buildUsageUrl(baseUrl), {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'ChatGPT-Account-Id': accountId,\n 'User-Agent': QUOTA_USER_AGENT,\n },\n });\n\n if (!response.ok) {\n throw new Error(`codex quota request failed with HTTP ${response.status}`);\n }\n\n const payload = (await response.json()) as CodexQuotaResponsePayload;\n return {\n blockingLimit: this.findBlockingLimit(payload),\n planType: payload.plan_type ?? null,\n };\n }\n\n private async readAuthFile(): Promise<CodexAuthFile | null> {\n const raw = await this.readOptionalTextFile(join(this.codexHome, AUTH_FILENAME));\n if (!raw) {\n return null;\n }\n\n return JSON.parse(raw) as CodexAuthFile;\n }\n\n private async readChatgptBaseUrl(): Promise<string> {\n const config = await this.readOptionalTextFile(join(this.codexHome, CONFIG_FILENAME));\n const match = config?.match(/^\\s*chatgpt_base_url\\s*=\\s*\"([^\"]+)\"/m);\n return this.normalizeBaseUrl(match?.[1] ?? DEFAULT_CHATGPT_BASE_URL);\n }\n\n private buildUsageUrl(baseUrl: string): string {\n return baseUrl.includes(BACKEND_API_SEGMENT) ? `${baseUrl}/wham/usage` : `${baseUrl}/api/codex/usage`;\n }\n\n private normalizeBaseUrl(baseUrl: string): string {\n let normalized = baseUrl.trim().replace(/\\/+$/, '');\n if (\n (normalized.startsWith(CHATGPT_HOST) || normalized.startsWith(CHAT_OPENAI_HOST)) &&\n !normalized.includes(BACKEND_API_SEGMENT)\n ) {\n normalized = `${normalized}${BACKEND_API_SEGMENT}`;\n }\n\n return normalized;\n }\n\n private async readOptionalTextFile(path: string): Promise<string | null> {\n try {\n return await this.readTextFile(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n\n throw error;\n }\n }\n\n private findBlockingLimit(payload: CodexQuotaResponsePayload): CodexQuotaBlock | null {\n const blocks: CodexQuotaBlock[] = [];\n\n this.collectBlockingLimit(blocks, 'codex', 'codex', payload.rate_limit);\n\n for (const additionalLimit of payload.additional_rate_limits ?? []) {\n this.collectBlockingLimit(\n blocks,\n additionalLimit.metered_feature ?? additionalLimit.limit_name ?? 'codex',\n additionalLimit.limit_name ?? additionalLimit.metered_feature ?? 'codex',\n additionalLimit.rate_limit,\n );\n }\n\n blocks.sort((left, right) => left.resetAt - right.resetAt || right.usedPercent - left.usedPercent);\n return blocks[0] ?? null;\n }\n\n private collectBlockingLimit(\n blocks: CodexQuotaBlock[],\n limitId: string,\n limitName: string,\n limit: CodexQuotaLimitPayload | undefined,\n ): void {\n if (!limit) {\n return;\n }\n\n const windows: Array<{\n payload: CodexQuotaWindowPayload | undefined;\n window: CodexQuotaWindowKind;\n }> = [\n { payload: limit.primary_window, window: PRIMARY_WINDOW },\n { payload: limit.secondary_window, window: SECONDARY_WINDOW },\n ];\n\n for (const { payload, window } of windows) {\n const resetAt = payload?.reset_at;\n const usedPercent = payload?.used_percent ?? 0;\n if (typeof resetAt !== 'number') {\n continue;\n }\n\n const isBlocked =\n usedPercent >= QUOTA_REACHED_PERCENT ||\n (limit.limit_reached === true && resetAt * 1000 > this.now()) ||\n (limit.allowed === false && resetAt * 1000 > this.now());\n\n if (!isBlocked) {\n continue;\n }\n\n blocks.push({\n limitId,\n limitName,\n resetAfterSeconds: payload?.reset_after_seconds ?? null,\n resetAt,\n usedPercent,\n window,\n windowSeconds: payload?.limit_window_seconds ?? null,\n });\n }\n }\n}\n","import type { ChildProcess } from 'node:child_process';\n/**\n * StepRunnerService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\nimport { randomUUID } from 'node:crypto';\nimport { dirname, join, resolve } from 'node:path';\n\nimport { getOrThrow, pathExists, writeFileAtomic } from '@agimon-ai/po-core/platform';\n\nimport { type WorkflowInterruptContext, WorkflowInterruptedError } from '../../models/WorkflowInterruptedError';\nimport { WorkflowStepSpawnError } from '../../models/WorkflowStepSpawnError';\nimport { WorkflowStepTimeoutConfigError } from '../../models/WorkflowStepTimeoutConfigError';\nimport type {\n CommandRef,\n CustomRun,\n CustomRunEntry,\n RunConfig,\n Step,\n StepCommand,\n Workflow,\n} from '../../schemas/workflowEngine';\nimport { StepTimeoutMinutesSchema, StepTimeoutRetriesSchema } from '../../schemas/workflowStepTimeout';\nimport { CodexQuotaService, type CodexQuotaStatus } from '../CodexQuotaService';\nimport { RunDirectoryService } from '../RunDirectoryService';\nimport { type StepArtifactSnapshot } from '../RunDirectoryService/types';\nimport {\n createDecisionFile,\n newDecisionFilePath,\n readStepDecision,\n stepDecisionInstructions,\n resetDecisionFile,\n WORKFLOW_DECISION_FILE_ENV,\n WORKFLOW_DECISION_INSTRUCTIONS_ENV,\n WORKFLOW_RESTART_TARGETS_ENV,\n} from '../StepDecisionService';\nimport type {\n InterpolationContext,\n Logger,\n ResolvedCustomRun,\n StepCommandTemplate,\n StepExecution,\n StepExecutor,\n StepRunOptions,\n} from '../workflowEngine/type';\nimport { choiceSettings, commandTemplateOf, type WorkflowParserService } from '../WorkflowParserService';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport { runWorkflowSpan } from '../workflowTelemetry';\n\nconst RESET = '\\x1b[0m';\nconst DIM = '\\x1b[2m';\nconst CYAN = '\\x1b[36m';\nconst GREEN = '\\x1b[32m';\nconst YELLOW = '\\x1b[33m';\nconst RED = '\\x1b[31m';\nconst INTERRUPT_EXIT_CODE = 130;\nconst TERMINATE_EXIT_CODE = 143;\nconst INTERRUPT_SIGNAL: NodeJS.Signals = 'SIGINT';\nconst HANGUP_SIGNAL: NodeJS.Signals = 'SIGHUP';\nconst TERMINATE_SIGNAL: NodeJS.Signals = 'SIGTERM';\nconst DEFAULT_STEP_NAME = 'unnamed';\nconst DEFAULT_SHELL = '/bin/zsh';\nconst FORCE_COLOR_KEY = 'FORCE_COLOR';\nconst FORCE_COLOR_VALUE = '1';\nconst PROJECT_PATH_ENV_KEY = 'PROJECT_PATH';\nconst UNKNOWN_EXIT_CODE = 1;\nconst STDIO_INHERIT = 'inherit';\nconst STDIO_PIPE = 'pipe';\nconst STDIO_IGNORE = 'ignore';\nconst COMMAND_LINE_BREAK = '\\n';\nconst COMMAND_LOG_INDENT = ' ';\nconst COMMAND_LOG_PROMPT = '$ ';\nconst COMMAND_LOG_CONTINUATION = `${COMMAND_LINE_BREAK}${COMMAND_LOG_INDENT}${COMMAND_LOG_PROMPT}`;\nconst STEP_EXECUTION_PHASE = 'step_execution';\nconst STEP_RUNNER_SOURCE = 'StepRunnerService.runStep';\nconst STEP_RUNNER_EXECUTE_SOURCE = 'StepRunnerService.executeCommand';\nconst STATUS_SKIP = 'skip';\nconst STATUS_WARN = 'warn';\nconst STATUS_DRY = 'dry ';\nconst STATUS_RUN = 'run ';\nconst STATUS_ERROR = 'error';\nconst STATUS_PASS = 'pass';\nconst STATUS_FAIL = 'fail';\nconst STATUS_INTERRUPTED = 'interrupted';\nconst STATUS_WAIT = 'wait ';\nconst NO_ACTIVE_STEP_MESSAGE = 'no active step to stop';\nconst ALREADY_STOPPING_SUFFIX = 'already stopping';\nconst FAILED_TO_SIGNAL_MESSAGE = 'failed to signal';\nconst FAILED_TO_CLEANUP_PROCESS_GROUP_MESSAGE = 'failed to clean up process group for';\nconst UNSUPPORTED_ACTION_PREFIX = 'Unsupported action:';\nconst UNSUPPORTED_ACTION_SUFFIX = '(skipped)';\nconst CONTINUE_ON_ERROR_SUFFIX = '(continue-on-error)';\nconst SPAWN_FAILURE_PREFIX = 'unable to start step';\nconst SPAWN_ERROR_FALLBACK_HINT = 'check shell availability, PATH, and permissions';\nconst SPAWN_ERROR_RECOVERY_HINT = 'verify command, shell, and permissions';\nconst STEP_EXIT_FAILURE_PREFIX = 'step';\nconst STEP_EXIT_FAILURE_MIDDLE = 'exited with code';\nconst STEP_TIMEOUT_FAILURE_PREFIX = 'step timed out after';\nconst STEP_TIMEOUT_FORCE_KILL_SUFFIX = 'forcing SIGKILL';\nconst PLATFORM_WINDOWS = 'win32';\nconst ESRCH_ERROR_CODE = 'ESRCH';\nconst RUN_KEY = 'run';\nconst INTERACTIVE_RUN_KEY = 'interactiveRun';\nconst CUSTOM_RUN_KEY = 'customRun';\nconst CUSTOM_RUN_UNSUPPORTED_MESSAGE =\n 'customRun needs a host step executor and no run or interactiveRun fallback exists for step';\nconst WORKFLOW_RUN_CONFIG_ENV_KEY = 'WORKFLOW_RUN_CONFIG';\nconst DEFAULT_CHOICE = 'default';\nconst OUTPUT_TAIL_LINES = 50;\n\n/** Whether a customRun keyed by runner has an entry of its own for this runner. */\nfunction customRunNames(customRun: CustomRun | undefined, runner: string | undefined): boolean {\n if (customRun === undefined || runner === undefined) return false;\n if (typeof (customRun as { prompt?: unknown }).prompt === 'string') return false;\n return Object.hasOwn(customRun, runner);\n}\n\n/**\n * The customRun entry a runner runs: the one entry of a plain customRun, the\n * runner's own entry of a runner map, or the map's first entry for a runner it\n * does not name, the way a command map falls back to its first command.\n */\n/** Resolves once a child's piped output has ended, or after OUTPUT_DRAIN_TIMEOUT_MS. */\nfunction outputDrained(child: ChildProcess): Promise<void> {\n const ended = (stream: NodeJS.ReadableStream | null): Promise<void> =>\n !stream || (stream as { readableEnded?: boolean }).readableEnded\n ? Promise.resolve()\n : new Promise((resolveEnded) => {\n stream.once('end', () => resolveEnded());\n stream.once('close', () => resolveEnded());\n stream.once('error', () => resolveEnded());\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolveTimeout) => {\n timer = setTimeout(resolveTimeout, OUTPUT_DRAIN_TIMEOUT_MS);\n });\n return Promise.race([Promise.all([ended(child.stdout), ended(child.stderr)]).then(() => {}), timeout]).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/** A logger whose lines name the parallel step they came from. */\nfunction labelledLogger(logger: Logger, label: string): Logger {\n const prefix = `${DIM}[${label}]${RESET} `;\n return {\n info: (message: string) => logger.info(`${prefix}${message}`),\n error: (message: string) => logger.error(`${prefix}${message}`),\n warn: (message: string) => logger.warn(`${prefix}${message}`),\n ...(logger.event ? { event: logger.event.bind(logger) } : {}),\n ...(logger.flush ? { flush: logger.flush.bind(logger) } : {}),\n ...(logger.runInSpan ? { runInSpan: logger.runInSpan.bind(logger) } : {}),\n };\n}\n\nfunction firstLine(text: string): string {\n return text.split(COMMAND_LINE_BREAK)[0] ?? '';\n}\n\n/** A step command in its legacy string or runner-map form; a templated list is resolved elsewhere. */\nfunction legacyCommand(command: StepCommand | CommandRef[] | undefined): StepCommand | undefined {\n return Array.isArray(command) ? undefined : command;\n}\n\nfunction customRunEntry(customRun: CustomRun, runner: string | undefined): CustomRunEntry | undefined {\n if (typeof (customRun as { prompt?: unknown }).prompt === 'string') return customRun as CustomRunEntry;\n const entries = customRun as Record<string, CustomRunEntry>;\n return (runner === undefined ? undefined : entries[runner]) ?? Object.values(entries)[0];\n}\nconst INTERACTIVE_OUTPUT_NOTICE = '(interactive: output renders directly to terminal)';\nconst STEP_TIMEOUT_MINUTES_KEY = 'timeout-minutes';\nconst STEP_TIMEOUT_RETRIES_KEY = 'timeout-retries';\nconst STATUS_RETRY = 'retry';\nconst STEP_TIMEOUT_RETRY_PREFIX = 'retrying step after timeout';\nconst TERMINATE_FORCE_KILL_SIGNAL: NodeJS.Signals = 'SIGKILL';\nconst FORCE_KILL_GRACE_PERIOD_MS = 1_000;\nconst PROCESS_EXIT_POLL_INTERVAL_MS = 50;\nconst PROCESS_EXIT_WAIT_TIMEOUT_MS = 1_000;\n/**\n * How long a finished step's output may still arrive. A child can exit before\n * its piped output is read; a background process that keeps the pipe open\n * must not hold the step past this.\n */\nconst OUTPUT_DRAIN_TIMEOUT_MS = 500;\nconst STEP_COMPLETION_KILL_GRACE_MS_ENV_KEY = 'WORKFLOW_STEP_FORCE_KILL_GRACE_MS';\n// SIGTERM→SIGKILL grace on the completion path (status file signalled `YES`).\n// Deliberately longer than the 1s timeout-path grace so an interactive agent can\n// flush its final telemetry batch (e.g. Claude Code OTEL Stop-hook events) before\n// SIGKILL. A fast graceful exit still settles immediately, so this only adds\n// latency when a child lingers. Operator-tunable via the env key above.\nconst STEP_COMPLETION_KILL_GRACE_MS = 5_000;\n// Interactive teardown re-walks the process tree every round so descendants\n// spawned or re-parented after an earlier snapshot are still reaped. The grace\n// budget per signal phase is operator-tunable but defaults to today's value so\n// ordinary steps see no behaviour change.\nconst INTERACTIVE_REAP_ROUND_INTERVAL_MS = 100;\nconst INTERACTIVE_PROCESS_TRACK_INTERVAL_MS = 1_000;\nconst INTERACTIVE_KILL_GRACE_MS_ENV_KEY = 'WORKFLOW_INTERACTIVE_KILL_GRACE_MS';\nconst WORKFLOW_RUN_DIR_ENV_KEY = 'WORKFLOW_RUN_DIR';\nconst INTERACTIVE_REAP_LOG_FILENAME = 'interactive-reap.json';\nconst PAUSE_REQUEST_FILENAME = 'pause-request.json';\nconst RUN_RECORD_FILENAME = 'run.json';\nconst INTERACTIVE_REAP_LOG_MAX_ENTRIES = 50;\nconst MINUTE_IN_MS = 60_000;\nconst TIMEOUT_UNIT_MILLISECONDS = 'ms';\nconst TIMEOUT_UNIT_MINUTES = 'minute(s)';\nconst STATUS_FILE_ENV_KEY = 'WORKFLOW_STATUS_FILE';\nconst WORKFLOW_JOB_NAME_ENV_KEY = 'WORKFLOW_JOB_NAME';\nconst WORKFLOW_STEP_NAME_ENV_KEY = 'WORKFLOW_STEP_NAME';\nconst WORKFLOW_STEP_DISPLAY_ENV_KEY = 'WORKFLOW_STEP_DISPLAY';\nconst WORKFLOW_STEP_ARTIFACTS_ENV_KEY = 'WORKFLOW_STEP_ARTIFACTS';\nconst WORKFLOW_TERMINAL_TITLE = 'workflow-mcp';\nconst STATUS_FILE_PREFIX = 'workflow-step-';\nconst STATUS_FILE_SUFFIX = '.status';\nconst STATUS_FILE_COMPLETION_VALUE = 'YES';\nconst STATUS_FILE_COMPLETED_RESULT: StepExecutionResult = { status: 'status_completed' };\nconst TRANSIENT_FS_ERROR_CODES = new Set(['ENOENT', 'EBUSY', 'EAGAIN', 'EPERM', 'not_found']);\nconst STATUS_FILE_POLL_INTERVAL_MS = 1_000;\nconst STOP_REQUEST_POLL_INTERVAL_MS = 1_000;\nconst STATUS_DONE = 'done';\nconst STATUS_STOP = 'stop';\nconst EXPLICIT_RUNNER_MISSING_PREFIX = 'runner';\nconst EXPLICIT_RUNNER_MISSING_MIDDLE = 'not found for step';\nconst EXPLICIT_RUNNER_AVAILABLE_PREFIX = 'available runner keys:';\nconst QUOTA_WAIT_POLL_INTERVAL_MS = 30_000;\nconst QUOTA_WAIT_RESET_BUFFER_MS = 1_000;\nconst QUOTA_WAIT_SOURCE = 'StepRunnerService.waitForCodexQuota';\nconst QUOTA_RETRY_REASON = 'codex quota reached after failed step, retrying after reset';\nconst RESULT_STATUS_COMPLETED = 'completed' as const;\nconst RESULT_STATUS_SPAWN_ERROR = 'spawn_error' as const;\nconst RESULT_STATUS_SIGNALED = 'signaled' as const;\nconst RESULT_STATUS_TIMED_OUT = 'timed_out' as const;\nconst RESULT_STATUS_STATUS_COMPLETED = 'status_completed' as const;\nconst RESULT_STATUS_STOP_REQUESTED = 'stop_requested' as const;\nconst RESULT_STATUS_PAUSE_REQUESTED = 'pause_requested' as const;\n\n/**\n * Normalized child-process termination states used by `runStep`.\n */\ntype StepExecutionResult =\n // `failure` is why a host execution failed, when it said so, in place of an exit code.\n | { status: 'completed'; exitCode: number; outputTail?: string; failure?: string }\n | { status: 'pause_requested'; survivors?: InteractiveProcessReport[] }\n | { status: 'spawn_error'; error: WorkflowStepSpawnError }\n | { status: 'signaled'; signal: NodeJS.Signals }\n | { status: 'timed_out'; timeoutMs: number }\n | { status: 'status_completed' }\n | { status: 'stop_requested' };\n\n/** Why the step being run failed, filled in by the step as it fails. */\ninterface StepFailureReport {\n reason?: string;\n}\n\n/** The reason a step failure carries when nothing more specific was recorded. */\nconst STEP_FAILED_REASON = 'The step failed.';\n\n/**\n * Snapshot of the currently running step process for cancellation.\n */\ninterface ActiveStepExecution {\n command: string;\n interactive: boolean;\n lastSignaledProcessIds: number[];\n process: ChildProcess;\n processGroupId: number | null;\n rootProcessId: number | null;\n stepName: string;\n trackedProcessGroupIds: number[];\n trackedProcessIds: number[];\n}\n\n/**\n * A step a host executor owns. `stopSignal` records the first stop request so\n * a later escalation is not sent twice and the outcome reads as a termination.\n */\ninterface ActiveExternalExecution {\n execution: StepExecution;\n stepName: string;\n stopSignal: NodeJS.Signals | null;\n}\n\ninterface ProcessTreeEntry {\n depth: number;\n pid: number;\n}\n\ninterface InteractiveProcessReport {\n pid: number;\n command: string;\n}\n\ninterface InteractiveReapResult {\n survivors: InteractiveProcessReport[];\n sigkillEscalated: boolean;\n}\n\ntype InteractiveCompletionSource =\n | 'status-file'\n | 'stop-request'\n | 'pause-request'\n | 'natural-exit'\n | 'timed-out'\n | 'signaled'\n | 'spawn-error';\n\n/**\n * Forensic record written once per interactive run so a session that fails to\n * exit is self-diagnosing: it captures how completion was signalled and which\n * processes (with their command) survived termination.\n */\ninterface InteractiveCompletionRecord {\n timestamp: string;\n stepName: string;\n statusFilePath: string;\n completionSource: InteractiveCompletionSource;\n statusFileSignaled: boolean;\n sigkillEscalated: boolean;\n survivors: InteractiveProcessReport[];\n}\n\n/**\n * What a launch selected for templated interactiveRun steps: the workflow's\n * command templates and choices, and the `--command` and `--choice` it named.\n */\nexport interface CommandTemplateSelection {\n commands?: Workflow['commands'];\n choices?: Workflow['choices'];\n command?: string;\n choice?: string;\n}\n\ninterface ResolvedStepCommand {\n agentKey?: string;\n command: string;\n /** Set for a templated interactiveRun: the structured values the command was rendered from. */\n template?: StepCommandTemplate;\n /** Why a templated interactiveRun could not be rendered; the step fails with it. */\n templateError?: string;\n /** Set when a host executor runs the step's `customRun`; `command` is then only a label. */\n custom?: ResolvedCustomRun;\n /** Effective settings: step, selected entry, then the applicable choice settings. */\n runConfig?: RunConfig;\n missingRunner?: {\n availableKeys: string[];\n runner: string;\n };\n interactive: boolean;\n}\n\ninterface ActiveQuotaWait {\n controller: AbortController;\n signal: NodeJS.Signals | null;\n stepName: string;\n}\n\n/**\n * Executes workflow steps in child processes and tracks the active process so\n * the workflow runner can interrupt it safely.\n *\n * Runtime configuration:\n * - Environment precedence is `runtime.baseEnvironment` -> workflow/job env -> step env.\n * - Child commands run through `/bin/zsh` to match local workflow execution.\n * - `FORCE_COLOR=1` is injected so tool output keeps ANSI formatting.\n */\nexport class StepRunnerService {\n private activeStep: ActiveStepExecution | null = null;\n private activeExternal: ActiveExternalExecution | null = null;\n private lastInteractiveReap: InteractiveReapResult | null = null;\n private interruptedSignal: NodeJS.Signals | null = null;\n\n private activeQuotaWait: ActiveQuotaWait | null = null;\n private commandSelection: CommandTemplateSelection = {};\n /** Runners of a parallel group's steps, which a stop must reach too. */\n private forks = new Set<StepRunnerService>();\n /** Shared by a runner and its forks: one engine-spawned interactive step owns the terminal at a time. */\n private terminalLock: { tail: Promise<void> } = { tail: Promise.resolve() };\n\n /**\n * Create a step runner bound to the workflow parser and shared logger.\n *\n * `ownsTerminal` is false when the runner is embedded in a host that owns the\n * terminal itself, which is the Pi extension: there stdin is the TUI's\n * keyboard and stdout is its screen. A runner that does not own the terminal\n * must not hand a step's stdin to it, and must not `stty` or reset it\n * afterwards, however cooperative the intent.\n */\n constructor(\n private runtime: WorkflowRuntimeContext,\n private parser: WorkflowParserService,\n private logger: Logger,\n private quotaService: Pick<CodexQuotaService, 'getQuotaStatus' | 'isCodexCommand'> = new CodexQuotaService(runtime),\n private watchStatusFile = runtime.fs.watch.bind(runtime.fs),\n private runDirectoryService = new RunDirectoryService(runtime),\n private ownsTerminal = true,\n private stepExecutor?: StepExecutor,\n ) {}\n\n /**\n * Use a workflow's command templates and choices, and what the launch\n * selected, for the templated interactiveRun steps this runner starts.\n * Called again whenever the workflow file is re-read.\n */\n useCommandTemplates(selection: CommandTemplateSelection): void {\n this.commandSelection = selection;\n }\n\n /**\n * A runner for one step of a parallel group. It shares this runner's\n * collaborators, command selection and terminal, and has its own active\n * step, so group members run side by side and a stop reaches each of them.\n * Release it once its step has finished.\n */\n fork(label: string): StepRunnerService {\n const child = new StepRunnerService(\n this.runtime,\n this.parser,\n labelledLogger(this.logger, label),\n this.quotaService,\n this.watchStatusFile,\n this.runDirectoryService,\n this.ownsTerminal,\n this.stepExecutor,\n );\n child.commandSelection = this.commandSelection;\n child.interruptedSignal = this.interruptedSignal;\n child.terminalLock = this.terminalLock;\n this.forks.add(child);\n return child;\n }\n\n release(child: StepRunnerService): void {\n this.forks.delete(child);\n }\n\n /**\n * Clear a previous workflow's shutdown state before starting a new run.\n */\n resetInterruption(): void {\n this.interruptedSignal = null;\n }\n\n /**\n * Stop the active step process during workflow shutdown.\n */\n stopActiveStep(signal: NodeJS.Signals): void {\n this.interruptedSignal = signal;\n if (this.forks.size > 0) {\n for (const child of this.forks) child.stopActiveStep(signal);\n return;\n }\n if (this.activeQuotaWait) {\n if (this.activeQuotaWait.controller.signal.aborted) {\n this.logger.info(\n ` ${DIM}${STATUS_SKIP}${RESET} ${this.activeQuotaWait.stepName} ${ALREADY_STOPPING_SUFFIX}`,\n );\n return;\n }\n\n this.activeQuotaWait.signal = signal;\n this.activeQuotaWait.controller.abort();\n this.logger.info(\n ` ${YELLOW}${STATUS_INTERRUPTED}${RESET} cancelling quota wait for ${this.activeQuotaWait.stepName}`,\n );\n return;\n }\n\n if (this.activeExternal) {\n if (this.activeExternal.stopSignal) {\n this.logger.info(\n ` ${DIM}${STATUS_SKIP}${RESET} ${this.activeExternal.stepName} ${ALREADY_STOPPING_SUFFIX}`,\n );\n return;\n }\n this.logger.info(\n ` ${YELLOW}${STATUS_INTERRUPTED}${RESET} stopping ${this.activeExternal.stepName} (${signal})`,\n );\n this.stopExternal(this.activeExternal, signal);\n return;\n }\n\n if (!this.activeStep) {\n this.logger.info(` ${DIM}${STATUS_SKIP}${RESET} ${NO_ACTIVE_STEP_MESSAGE}`);\n return;\n }\n\n if (this.activeStep.process.killed) {\n this.logger.info(` ${DIM}${STATUS_SKIP}${RESET} ${this.activeStep.stepName} ${ALREADY_STOPPING_SUFFIX}`);\n return;\n }\n\n this.logger.info(` ${YELLOW}${STATUS_INTERRUPTED}${RESET} sending ${signal} to ${this.activeStep.stepName}`);\n const killRequested = this.killActiveStep(signal);\n if (!killRequested) {\n this.logger.warn(` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_SIGNAL_MESSAGE} ${this.activeStep.stepName}`);\n }\n }\n\n /**\n * Execute a single workflow step and stream its output to the workflow logger.\n *\n * The runner interpolates the final command before execution, resolves the\n * working directory relative to the workflow root, and merges step-scoped\n * environment variables over the inherited process environment.\n */\n async runStep(step: Step, context: InterpolationContext, options: StepRunOptions): Promise<boolean> {\n const report: StepFailureReport = {};\n const ok = await this.executeStep(step, context, options, report);\n if (!ok) options.onFailure?.(report.reason ?? STEP_FAILED_REASON);\n return ok;\n }\n\n /**\n * Run one step. Each cause of a failure is logged through `fail`, which also\n * keeps it on `report`, so the step's failure carries its reason to the job's\n * progress log and telemetry instead of existing only as a log line.\n */\n private async executeStep(\n step: Step,\n context: InterpolationContext,\n options: StepRunOptions,\n report: StepFailureReport,\n ): Promise<boolean> {\n const fail = (reason: string): void => {\n this.logger.error(` ${RED}${STATUS_ERROR}${RESET} ${reason}`);\n report.reason = reason;\n };\n if (step.customRun) step = { ...step, runConfig: this.customRunChoiceConfig(step.runConfig) };\n const stepContext: InterpolationContext = step.runConfig ? { ...context, runConfig: step.runConfig } : context;\n const runner = this.resolveRunner(options);\n // A job step may record its outcome with `workflow-mcp step`, and a\n // templated agent step must. Its decision file is placed first so the\n // step's instructions can name it; outside jobs nothing routes a decision.\n const decisionRunDir = stepContext.env[WORKFLOW_RUN_DIR_ENV_KEY];\n const plannedDecisionFile =\n stepContext.env[WORKFLOW_DECISION_INSTRUCTIONS_ENV] !== undefined && decisionRunDir && !options.dryRun\n ? newDecisionFilePath(decisionRunDir)\n : undefined;\n const resolvedStepCommand = this.resolveStepCommand(step, stepContext, runner, plannedDecisionFile);\n const stepName = step.name\n ? this.parser.interpolate(step.name, stepContext)\n : resolvedStepCommand?.command.slice(0, 60) || step.uses || DEFAULT_STEP_NAME;\n\n if (this.interruptedSignal) {\n throw new WorkflowInterruptedError(this.interruptedSignal, {\n cause: new Error(`Workflow interrupted before step started: ${stepName}`),\n context: this.createInterruptContext(stepName, resolvedStepCommand?.command ?? ''),\n });\n }\n\n if (step.uses) {\n const action = this.parser.interpolate(step.uses, stepContext);\n if (this.parser.isActionSkipped(action)) {\n this.logger.info(` ${DIM}${STATUS_SKIP}${RESET} ${action}`);\n return true;\n }\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${UNSUPPORTED_ACTION_PREFIX} ${action} ${UNSUPPORTED_ACTION_SUFFIX}`,\n );\n return true;\n }\n\n if (!resolvedStepCommand) {\n if (!step.customRun) return true;\n // A step that only a host can run must not pass by doing nothing.\n fail(`${CUSTOM_RUN_UNSUPPORTED_MESSAGE} \"${stepName}\"`);\n if (step['continue-on-error'] || options.continueOnError) {\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n return false;\n }\n\n if (resolvedStepCommand.missingRunner) {\n fail(\n `${EXPLICIT_RUNNER_MISSING_PREFIX} \"${resolvedStepCommand.missingRunner.runner}\" ${EXPLICIT_RUNNER_MISSING_MIDDLE} \"${stepName}\" (${EXPLICIT_RUNNER_AVAILABLE_PREFIX} ${resolvedStepCommand.missingRunner.availableKeys.join(', ')})`,\n );\n if (step['continue-on-error'] || options.continueOnError) {\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n return false;\n }\n\n if (resolvedStepCommand.templateError) {\n fail(`step \"${stepName}\": ${resolvedStepCommand.templateError}`);\n if (step['continue-on-error'] || options.continueOnError) {\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n return false;\n }\n\n const { command, custom, interactive, template } = resolvedStepCommand;\n const isCodexCommand = this.quotaService.isCodexCommand(command, resolvedStepCommand.agentKey);\n const shouldContinue = step['continue-on-error'] || options.continueOnError;\n let timeoutMs: number | null;\n try {\n timeoutMs = this.resolveTimeoutMs(step, stepName);\n } catch (error) {\n if (!(error instanceof WorkflowStepTimeoutConfigError)) {\n throw error;\n }\n\n fail(`invalid ${error.context.configKey} for \"${stepName}\": ${String(error.context.timeoutValue)}`);\n if (shouldContinue) {\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n return false;\n }\n\n const workDir = step['working-directory']\n ? resolve(this.runtime.cwd, options.workflowDir, this.parser.interpolate(step['working-directory'], stepContext))\n : resolve(this.runtime.cwd, options.workflowDir);\n const stepEnv: NodeJS.ProcessEnv = { ...this.runtime.baseEnvironment, ...stepContext.env };\n if (step.env) {\n for (const [key, val] of Object.entries(step.env)) {\n stepEnv[key] = this.parser.interpolate(String(val), stepContext);\n }\n }\n // YAML cannot retarget the run whose capabilities this step receives.\n for (const key of [\n 'WORKFLOW_RUN_ID',\n 'WORKFLOW_RUN_KEY',\n 'WORKFLOW_RUN_DIR',\n 'WORKFLOW_WORKSPACE',\n 'WORKFLOW_PHASE',\n 'WORKFLOW_JOB_ID',\n 'WORKFLOW_JOB_NAME',\n ]) {\n if (stepContext.env[key] !== undefined) stepEnv[key] = stepContext.env[key];\n else delete stepEnv[key];\n }\n // A globally hosted workflow-mcp can execute another checkout. Pin every\n // nested MCP runtime to the checkout containing this step, not the host cwd.\n stepEnv[PROJECT_PATH_ENV_KEY] = workDir;\n stepEnv[WORKFLOW_STEP_NAME_ENV_KEY] = stepName;\n stepEnv[WORKFLOW_STEP_DISPLAY_ENV_KEY] = this.formatStepDisplay(stepEnv[WORKFLOW_JOB_NAME_ENV_KEY], stepName);\n const runConfig = resolvedStepCommand?.runConfig ?? step.runConfig;\n // An explicit empty payload clears stale preferences inherited from the host.\n stepEnv[WORKFLOW_RUN_CONFIG_ENV_KEY] = JSON.stringify(runConfig ?? {});\n if (step.if !== undefined && !options.dryRun) {\n const condition = await this.evaluateStepCondition(step.if, stepContext, workDir, stepEnv, stepName, timeoutMs);\n if (!condition.run) {\n if (condition.error) fail(condition.error);\n return condition.error ? Boolean(shouldContinue) : true;\n }\n }\n // What an agent step is held to before it stops: its own artifacts, updated\n // during the step, and, when it ends its job, the job's outputs, written\n // during the job's attempt.\n let artifactSnapshots: StepArtifactSnapshot[] | undefined;\n const jobOutputs = interactive || custom ? (options.jobOutputs ?? []) : [];\n if ((interactive || custom) && ((step.artifacts?.length ?? 0) > 0 || jobOutputs.length > 0)) {\n const runDir = stepEnv[WORKFLOW_RUN_DIR_ENV_KEY];\n if (!runDir) {\n fail(`step \"${stepName}\" declares artifacts but WORKFLOW_RUN_DIR is unavailable`);\n return false;\n }\n const artifactPaths = (step.artifacts ?? []).map((path) => this.parser.interpolate(path, stepContext));\n const stepSnapshots =\n artifactPaths.length > 0 ? await this.runDirectoryService.snapshotStepArtifacts(runDir, artifactPaths) : [];\n const own = new Set(stepSnapshots.map((snapshot) => snapshot.path));\n const described = stepSnapshots.map((snapshot) => {\n const description = jobOutputs.find((output) => output.path === snapshot.path)?.description;\n return description === undefined ? snapshot : { ...snapshot, description };\n });\n artifactSnapshots = [...described, ...jobOutputs.filter((output) => !own.has(output.path))];\n stepEnv[WORKFLOW_STEP_ARTIFACTS_ENV_KEY] = JSON.stringify(artifactSnapshots);\n }\n // A step that must record a decision gets a decision file, and so does one\n // that must leave artifacts: the gate counts its reminders there, and its\n // presence is what turns on the agents' stop hooks. Steps outside a run\n // get neither, and a stray inherited one is dropped.\n const decisionIdentity =\n plannedDecisionFile !== undefined\n ? {\n job: stepContext.env[WORKFLOW_JOB_NAME_ENV_KEY] ?? '',\n step: stepName,\n restartTargets: (stepContext.env[WORKFLOW_RESTART_TARGETS_ENV] ?? '').split(',').filter(Boolean),\n required: template !== undefined,\n }\n : artifactSnapshots !== undefined && decisionRunDir && !options.dryRun\n ? {\n job: stepContext.env[WORKFLOW_JOB_NAME_ENV_KEY] ?? '',\n step: stepName,\n restartTargets: [],\n required: false,\n }\n : undefined;\n let decisionFilePath: string | undefined;\n if (decisionIdentity && decisionRunDir) {\n decisionFilePath = await createDecisionFile(this.runtime, decisionRunDir, decisionIdentity, plannedDecisionFile);\n stepEnv[WORKFLOW_DECISION_FILE_ENV] = decisionFilePath;\n } else {\n delete stepEnv[WORKFLOW_DECISION_FILE_ENV];\n delete stepEnv[WORKFLOW_DECISION_INSTRUCTIONS_ENV];\n delete stepEnv[WORKFLOW_RESTART_TARGETS_ENV];\n }\n\n const stepStartedAt = Date.now();\n await this.logStepLifecycle('info', 'workflow.step.started', stepEnv, {\n 'workflow.step.interactive': interactive,\n });\n\n // Only provision a status file for interactive steps (Claude Code / Codex agents).\n // Plain run: steps (e.g. pnpm install) must not receive a status file — a Stop\n // hook fired from an unrelated Claude session must not be able to kill them.\n let statusFilePath: string | undefined;\n if (interactive) {\n statusFilePath = await this.createStatusFile();\n stepEnv[STATUS_FILE_ENV_KEY] = statusFilePath;\n this.logger.info(` ${DIM}status-file${RESET} ${statusFilePath}`);\n } else {\n // Drop any status file inherited from a parent runner/agent so a foreign Stop hook\n // cannot signal completion of this plain run: step.\n delete stepEnv[STATUS_FILE_ENV_KEY];\n }\n\n if (options.dryRun) {\n this.logger.info(` ${CYAN}${STATUS_DRY}${RESET} ${stepName}`);\n this.logger.info(\n `${COMMAND_LOG_INDENT}${DIM}${COMMAND_LOG_PROMPT}${command.split(COMMAND_LINE_BREAK).join(COMMAND_LOG_CONTINUATION)}${RESET}`,\n );\n await this.logStepLifecycle('info', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'dry-run',\n });\n return true;\n }\n\n const pausePolicy = step['pause-policy'] ?? 'replay';\n const pauseRequestPath = options.stopRequestPath\n ? join(dirname(options.stopRequestPath), PAUSE_REQUEST_FILENAME)\n : undefined;\n if (pauseRequestPath && (await this.readControlAction(pauseRequestPath)) === 'pause') {\n if (options.stopRequestPath && (await this.hasCurrentStopRequest(options.stopRequestPath))) {\n throw new WorkflowInterruptedError(TERMINATE_SIGNAL, {\n cause: new Error(`Workflow stop requested before pause acknowledgement for \"${stepName}\"`),\n context: this.createInterruptContext(stepName, command),\n });\n }\n await this.markPaused(options.stopRequestPath, stepName, pausePolicy);\n await options.onExecutionStateChange?.('paused', stepName);\n await this.waitForResume(options.stopRequestPath, stepName);\n await options.onExecutionStateChange?.('resumed', stepName);\n }\n\n let maxTimeoutRetries: number;\n try {\n maxTimeoutRetries = this.resolveTimeoutRetries(step, stepName);\n } catch (error) {\n if (!(error instanceof WorkflowStepTimeoutConfigError)) {\n throw error;\n }\n\n fail(`invalid ${error.context.configKey} for \"${stepName}\": ${String(error.context.timeoutValue)}`);\n if (shouldContinue) {\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n return false;\n }\n\n let quotaFailureRetried = false;\n for (let attempt = 0; attempt <= maxTimeoutRetries; attempt++) {\n await this.waitForCodexQuotaAvailability(stepName, command, isCodexCommand);\n if (decisionFilePath && decisionIdentity)\n await resetDecisionFile(this.runtime, decisionFilePath, decisionIdentity);\n\n if (attempt > 0) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_RETRY}${RESET} ${STEP_TIMEOUT_RETRY_PREFIX} \"${stepName}\" (attempt ${attempt + 1}/${maxTimeoutRetries + 1})`,\n );\n } else {\n this.logger.info(` ${CYAN}${STATUS_RUN}${RESET} ${stepName}`);\n }\n this.logger.info(\n `${COMMAND_LOG_INDENT}${DIM}${COMMAND_LOG_PROMPT}${command.split(COMMAND_LINE_BREAK)[0]}${command.includes(COMMAND_LINE_BREAK) ? ' ...' : ''}${RESET}`,\n );\n\n if (options.stopRequestPath && (await this.hasCurrentStopRequest(options.stopRequestPath))) {\n this.logger.info(`\\n ${YELLOW}${STATUS_INTERRUPTED}${RESET} ${stepName} (${STATUS_STOP})`);\n throw new WorkflowInterruptedError(TERMINATE_SIGNAL, {\n cause: new Error(`Workflow stop requested before \"${stepName}\"`),\n context: this.createInterruptContext(stepName, command),\n });\n }\n\n const executionPromise = runWorkflowSpan(\n this.logger,\n 'workflow.step.attempt',\n {\n 'workflow.run.id': stepEnv.WORKFLOW_RUN_ID ?? '',\n 'workflow.job.name': stepEnv.WORKFLOW_JOB_NAME ?? stepEnv.WORKFLOW_PHASE ?? '',\n 'workflow.step.name': stepName,\n 'workflow.step.attempt': attempt + 1,\n },\n (trace) =>\n this.startStepExecution({\n traceparent: trace?.traceparent,\n command,\n custom,\n interactive,\n onExecutionStarted: options.onExecutionStarted,\n runConfig,\n stepEnv,\n stepName,\n jobEnvironment: this.definedEnv({ ...this.runtime.baseEnvironment, ...stepContext.env }),\n attempt: attempt + 1,\n template,\n timeoutMs,\n workDir,\n }),\n );\n\n const executionResult =\n interactive && statusFilePath\n ? await this.raceInteractiveCompletion(\n executionPromise,\n statusFilePath,\n stepName,\n options.stopRequestPath,\n step['pause-policy'] ?? 'replay',\n )\n : options.stopRequestPath\n ? await this.raceStopRequest(\n executionPromise,\n stepName,\n options.stopRequestPath,\n step['pause-policy'] ?? 'replay',\n )\n : await executionPromise;\n\n if (executionResult.status === RESULT_STATUS_PAUSE_REQUESTED) {\n await this.logStepLifecycle('info', 'workflow.step.pause_requested', stepEnv, {\n 'workflow.step.outcome': pausePolicy === 'replay' ? 'cancelled_for_pause' : 'protected_boundary',\n 'workflow.step.pause_policy': pausePolicy,\n });\n await this.markPaused(options.stopRequestPath, stepName, pausePolicy, executionResult.survivors);\n await options.onExecutionStateChange?.('paused', stepName);\n await this.waitForResume(options.stopRequestPath, stepName);\n await options.onExecutionStateChange?.('resumed', stepName);\n if (pausePolicy === 'protected') return true;\n await this.logStepLifecycle('info', 'workflow.step.replay', stepEnv, {\n 'workflow.step.outcome': 'replay-current',\n });\n attempt -= 1;\n continue;\n }\n\n if (executionResult.status === 'stop_requested') {\n this.logger.info(`\\n ${YELLOW}${STATUS_INTERRUPTED}${RESET} ${stepName} (${STATUS_STOP})`);\n throw new WorkflowInterruptedError(TERMINATE_SIGNAL, {\n cause: new Error(`Workflow stop requested during \"${stepName}\"`),\n context: this.createInterruptContext(stepName, command),\n });\n }\n\n if (executionResult.status === 'signaled') {\n this.logger.info(`\\n ${YELLOW}${STATUS_INTERRUPTED}${RESET} ${stepName}`);\n throw new WorkflowInterruptedError(executionResult.signal, {\n cause: new Error(`Step process ended with ${executionResult.signal}`),\n context: this.createInterruptContext(stepName, command),\n });\n }\n\n if (\n executionResult.status === 'completed' &&\n (executionResult.exitCode === INTERRUPT_EXIT_CODE || executionResult.exitCode === TERMINATE_EXIT_CODE)\n ) {\n const interruptSignal = executionResult.exitCode === INTERRUPT_EXIT_CODE ? INTERRUPT_SIGNAL : TERMINATE_SIGNAL;\n this.logger.info(`\\n ${YELLOW}${STATUS_INTERRUPTED}${RESET} ${stepName}`);\n throw new WorkflowInterruptedError(interruptSignal, {\n cause: new Error(`Step process exited with ${executionResult.exitCode}`),\n context: this.createInterruptContext(stepName, command),\n });\n }\n\n if (executionResult.status === 'spawn_error') {\n fail(\n `${SPAWN_FAILURE_PREFIX} \"${stepName}\" in ${executionResult.error.context.workDir} (${this.formatSpawnError(\n executionResult.error,\n )})`,\n );\n if (shouldContinue) {\n await this.logStepLifecycle('warn', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'continued',\n });\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n await this.logStepLifecycle('error', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'failed',\n 'workflow.step.failure_reason': report.reason ?? '',\n });\n return false;\n }\n\n // A recorded decision is the step's outcome however the agent ended:\n // stopped by its hook, exited, or ran out of time after deciding.\n const decision = decisionFilePath ? await readStepDecision(this.runtime, decisionFilePath) : undefined;\n if (decision) {\n if (statusFilePath) await this.cleanupStatusFile(statusFilePath);\n if (decision.decision === 'complete') {\n const artifactProblem = artifactSnapshots\n ? await this.describeArtifactWarnings(stepEnv, artifactSnapshots)\n : undefined;\n if (!artifactProblem) {\n this.logger.info(\n `\\n ${GREEN}${STATUS_PASS}${RESET} ${stepName}${decision.summary ? ` (${decision.summary})` : ''}\\n`,\n );\n await this.logStepLifecycle('info', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'success',\n });\n return true;\n }\n fail(`step \"${stepName}\" ${artifactProblem}`);\n } else if (decision.decision === 'fix' && options.onDecision) {\n this.logger.warn(\n `\\n ${YELLOW}fix${RESET} ${stepName} asks to restart from \"${decision.restartFrom}\": ${firstLine(decision.reason)}\\n`,\n );\n options.onDecision({ ...decision, step: stepName });\n await this.logStepLifecycle('warn', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'fix',\n });\n return true;\n } else if (decision.decision === 'fail') {\n fail(`step \"${stepName}\" failed: ${firstLine(decision.reason)}`);\n if (!shouldContinue) options.onDecision?.({ ...decision, step: stepName });\n } else {\n fail(`step \"${stepName}\" asked for a fix, which only a job can route`);\n }\n return this.failStep(stepName, stepEnv, stepStartedAt, shouldContinue, report);\n }\n\n if (executionResult.status === 'timed_out') {\n fail(\n `${STEP_TIMEOUT_FAILURE_PREFIX} ${this.formatTimeoutMs(\n executionResult.timeoutMs,\n )} \"${stepName}\" (${command.split(COMMAND_LINE_BREAK)[0]})`,\n );\n\n if (attempt < maxTimeoutRetries) {\n // Reset status file for next attempt (clear stale content from timed-out Stop hook)\n if (statusFilePath) {\n try {\n getOrThrow(await this.runtime.fs.writeFile(statusFilePath, '', this.runtime.ioContext));\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} status-file reset failed for ${stepName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n continue;\n }\n\n if (statusFilePath) await this.cleanupStatusFile(statusFilePath);\n if (shouldContinue) {\n await this.logStepLifecycle('warn', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'continued',\n });\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n await this.logStepLifecycle('error', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'timed-out',\n 'workflow.step.failure_reason': report.reason ?? '',\n });\n return false;\n }\n\n // Clean up status file before returning for non-retry exits\n if (statusFilePath) await this.cleanupStatusFile(statusFilePath);\n\n if (\n decisionIdentity?.required &&\n !(executionResult.status === 'completed' && executionResult.failure !== undefined)\n ) {\n fail(`step \"${stepName}\" ended without a workflow decision (workflow-mcp step complete|fix|fail)`);\n return this.failStep(stepName, stepEnv, stepStartedAt, shouldContinue, report);\n }\n\n const restartFrom = step['restart-from'];\n if (\n restartFrom &&\n options.onDecision &&\n executionResult.status === 'completed' &&\n executionResult.exitCode !== 0\n ) {\n const tail = executionResult.outputTail?.trim();\n const ended = executionResult.failure\n ? `failed: ${executionResult.failure}`\n : `exited with code ${executionResult.exitCode}.`;\n const reason = `\\`${command.split(COMMAND_LINE_BREAK)[0]}\\` ${ended}${\n tail ? `\\n\\nLast output:\\n\\n\\`\\`\\`\\n${tail}\\n\\`\\`\\`` : ''\n }`;\n this.logger.warn(`\\n ${YELLOW}fix${RESET} ${stepName} failed; restarting from \"${restartFrom}\"\\n`);\n options.onDecision({ decision: 'fix', restartFrom, reason, step: stepName });\n await this.logStepLifecycle('warn', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'fix',\n });\n return true;\n }\n\n if (executionResult.status === 'status_completed') {\n // An agent's hook lets it stop once its gate runs out of reminders, so\n // the artifacts it still lacks fail the step here.\n const artifactProblem = artifactSnapshots\n ? await this.describeArtifactWarnings(stepEnv, artifactSnapshots)\n : undefined;\n if (artifactProblem) {\n fail(`step \"${stepName}\" ${artifactProblem}`);\n return this.failStep(stepName, stepEnv, stepStartedAt, shouldContinue, report);\n }\n this.logger.info(`\\n ${GREEN}${STATUS_DONE}${RESET} ${stepName} (status-file signaled completion)\\n`);\n await this.logStepLifecycle('info', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'success',\n });\n return true;\n }\n\n if (executionResult.status === 'completed' && executionResult.exitCode === 0) {\n // Whatever held the agent, its hook or its host, it may have stopped past\n // the gate's cap, so the engine checks the artifacts once the step ends.\n const artifactProblem = artifactSnapshots\n ? await this.describeArtifactWarnings(stepEnv, artifactSnapshots)\n : undefined;\n if (!artifactProblem) {\n this.logger.info(`\\n ${GREEN}${STATUS_PASS}${RESET} ${stepName}\\n`);\n await this.logStepLifecycle('info', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'success',\n });\n return true;\n }\n fail(`step \"${stepName}\" ${artifactProblem}`);\n }\n\n if (executionResult.status === 'completed' && executionResult.exitCode !== 0) {\n fail(\n executionResult.failure\n ? `step \"${stepName}\" failed: ${executionResult.failure}`\n : `${STEP_EXIT_FAILURE_PREFIX} \"${stepName}\" ${STEP_EXIT_FAILURE_MIDDLE} ${executionResult.exitCode} (${command.split(COMMAND_LINE_BREAK)[0]})`,\n );\n }\n\n if (!quotaFailureRetried && (await this.shouldRetryForCodexQuota(stepName, isCodexCommand))) {\n quotaFailureRetried = true;\n this.logger.warn(` ${YELLOW}${STATUS_RETRY}${RESET} ${QUOTA_RETRY_REASON}`);\n attempt -= 1;\n continue;\n }\n\n if (shouldContinue) {\n await this.logStepLifecycle('warn', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'continued',\n });\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n await this.logStepLifecycle('error', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'failed',\n 'workflow.step.failure_reason': report.reason ?? '',\n });\n return false;\n }\n\n return false;\n }\n\n /** Report a failed step, which passes under continue-on-error. */\n private async failStep(\n stepName: string,\n stepEnv: NodeJS.ProcessEnv,\n stepStartedAt: number,\n shouldContinue: boolean | undefined,\n report: StepFailureReport,\n ): Promise<boolean> {\n if (shouldContinue) {\n await this.logStepLifecycle('warn', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'continued',\n });\n this.logger.warn(` ${YELLOW}${STATUS_FAIL}${RESET} ${stepName} ${CONTINUE_ON_ERROR_SUFFIX}\\n`);\n return true;\n }\n this.logger.error(` ${RED}${STATUS_FAIL}${RESET} ${stepName}\\n`);\n await this.logStepLifecycle('error', 'workflow.step.finished', stepEnv, {\n 'workflow.step.duration_ms': Date.now() - stepStartedAt,\n 'workflow.step.outcome': 'failed',\n 'workflow.step.failure_reason': report.reason ?? '',\n });\n return false;\n }\n\n private async logStepLifecycle(\n level: 'info' | 'warn' | 'error',\n message: string,\n env: NodeJS.ProcessEnv,\n attributes: Record<string, string | number | boolean>,\n ): Promise<void> {\n await this.logger.event?.(level, message, {\n attributes: {\n 'workflow.id': env.WORKFLOW_ID ?? '',\n 'workflow.name': env.WORKFLOW_NAME ?? '',\n 'workflow.workspace': env.WORKFLOW_WORKSPACE ?? '',\n 'workflow.run.id': env.WORKFLOW_RUN_ID ?? '',\n 'workflow.run.key': env.WORKFLOW_RUN_KEY ?? '',\n 'workflow.phase': env.WORKFLOW_PHASE ?? 'job',\n 'workflow.job.id': env.WORKFLOW_JOB_ID ?? '',\n 'workflow.job.name': env.WORKFLOW_JOB_NAME ?? '',\n 'workflow.step.name': env[WORKFLOW_STEP_NAME_ENV_KEY] ?? '',\n ...attributes,\n },\n });\n }\n\n /** A host-shell predicate: exit 0 runs the step, 1 skips it, anything else fails closed. */\n private async evaluateStepCondition(\n expression: string,\n context: InterpolationContext,\n workDir: string,\n stepEnv: NodeJS.ProcessEnv,\n stepName: string,\n timeoutMs: number | null,\n ): Promise<{ run: boolean; error?: string }> {\n const command = this.parser.interpolate(expression, context).trim();\n if (!command) return { run: false, error: `empty condition for step \"${stepName}\"` };\n const env = { ...stepEnv };\n delete env[STATUS_FILE_ENV_KEY];\n delete env[WORKFLOW_DECISION_FILE_ENV];\n delete env[WORKFLOW_DECISION_INSTRUCTIONS_ENV];\n const result = await this.executeCommand(\n command,\n workDir,\n env,\n `${stepName} (condition)`,\n false,\n Math.min(timeoutMs ?? 30_000, 30_000),\n );\n if (result.status === 'signaled' || this.interruptedSignal) {\n const signal = result.status === 'signaled' ? result.signal : (this.interruptedSignal ?? TERMINATE_SIGNAL);\n throw new WorkflowInterruptedError(signal, {\n cause: new Error(`Workflow interrupted during condition for \"${stepName}\"`),\n context: this.createInterruptContext(stepName, command),\n });\n }\n if (result.status === 'completed' && result.exitCode === 0) return { run: true };\n if (result.status === 'completed' && result.exitCode === 1) {\n this.logger.info(` ${DIM}${STATUS_SKIP}${RESET} ${stepName} (condition is false)`);\n await this.logStepLifecycle('info', 'workflow.step.skipped', stepEnv, { 'workflow.step.outcome': 'skipped' });\n return { run: false };\n }\n const reason = result.status === 'completed' ? `exit code ${result.exitCode}` : result.status;\n return { run: false, error: `condition for step \"${stepName}\" failed: ${reason}` };\n }\n\n /**\n * Spawn a child shell for the step command and normalize its termination\n * into a typed result.\n */\n private async executeCommand(\n command: string,\n workDir: string,\n stepEnv: NodeJS.ProcessEnv,\n stepName: string,\n interactive: boolean,\n timeoutMs: number | null,\n ): Promise<StepExecutionResult> {\n if (interactive) {\n this.logger.info(` ${DIM}${INTERACTIVE_OUTPUT_NOTICE}${RESET}`);\n }\n\n return await new Promise<StepExecutionResult>((resolveResult) => {\n const terminalState = interactive ? this.captureTerminalState() : null;\n // Interactive steps inherit all stdio so the child process gets a real\n // TTY — required for TUI tools like Claude Code that detect isTTY to\n // render their interactive UI. The trade-off is that stdout/stderr are\n // null (not piped), so output goes directly to the terminal instead of\n // through this.logger. Step lifecycle events (run/pass/fail/timeout)\n // are still logged normally by the caller.\n //\n // Interactive steps are NOT detached (detached: false) because\n // detaching moves the child into a separate process group, which\n // breaks terminal job control for TTY-attached programs. On\n // timeout/interrupt, killActiveStep falls back to child.kill(signal)\n // which sends SIGTERM to the shell. Descendant ownership is sampled\n // while the step runs so cleanup retains children that re-parent before\n // the interactive shell receives that signal.\n const child = interactive\n ? this.runtime.workflowHost.spawn(command, [], {\n stdio: [STDIO_INHERIT, STDIO_INHERIT, STDIO_INHERIT],\n cwd: workDir,\n detached: false,\n env: { ...stepEnv, [FORCE_COLOR_KEY]: FORCE_COLOR_VALUE },\n shell: DEFAULT_SHELL,\n })\n : this.runtime.workflowHost.spawn(command, [], {\n // Non-interactive steps inherit stdin so a CLI run can still prompt.\n // Embedded, that stdin is the host's keyboard: a `pre:`/`post:` shell\n // step would sit there silently eating the user's keystrokes.\n stdio: [this.ownsTerminal ? STDIO_INHERIT : STDIO_IGNORE, STDIO_PIPE, STDIO_PIPE],\n cwd: workDir,\n detached: this.runtime.workflowHost.platform !== PLATFORM_WINDOWS,\n env: { ...stepEnv, [FORCE_COLOR_KEY]: FORCE_COLOR_VALUE },\n shell: DEFAULT_SHELL,\n });\n\n this.activeStep = {\n command,\n interactive,\n lastSignaledProcessIds: [],\n process: child,\n processGroupId:\n this.runtime.workflowHost.platform !== PLATFORM_WINDOWS && !interactive && typeof child.pid === 'number'\n ? child.pid\n : null,\n rootProcessId: typeof child.pid === 'number' ? child.pid : null,\n stepName,\n trackedProcessGroupIds: [],\n trackedProcessIds: [],\n };\n\n let ownershipTracker: NodeJS.Timeout | null = null;\n if (interactive) {\n this.captureInteractiveProcessOwnership(child);\n ownershipTracker = setInterval(() => {\n this.captureInteractiveProcessOwnership(child);\n }, INTERACTIVE_PROCESS_TRACK_INTERVAL_MS);\n ownershipTracker.unref();\n }\n\n let forceKillTimer: NodeJS.Timeout | null = null;\n let timedOut = false;\n let settled = false;\n const settle = async (result: StepExecutionResult) => {\n if (settled) {\n return;\n }\n\n settled = true;\n if (timeoutTimer) {\n clearTimeout(timeoutTimer);\n }\n if (forceKillTimer) {\n clearTimeout(forceKillTimer);\n }\n if (ownershipTracker) {\n clearInterval(ownershipTracker);\n ownershipTracker = null;\n }\n // Only tear down / clear the active step if it is still THIS invocation's\n // child. The completion race can settle on the status file before an\n // unkillable child exits; by the time that stale child finally emits its\n // exit event a later step may already own `activeStep`, and reaping it\n // here would terminate the wrong process tree.\n const ownsActiveStep = this.activeStep?.process === child;\n if (interactive) {\n if (ownsActiveStep) {\n this.captureInteractiveProcessOwnership(child);\n await this.cleanupInteractiveProcessTree(TERMINATE_SIGNAL);\n }\n this.restoreTerminalState(terminalState);\n }\n if (ownsActiveStep) {\n this.activeStep = null;\n }\n resolveResult(result);\n };\n\n const timeoutTimer =\n timeoutMs === null\n ? null\n : setTimeout(() => {\n timedOut = true;\n const terminateRequested = this.killActiveStep(TERMINATE_SIGNAL);\n if (terminateRequested) {\n forceKillTimer = setTimeout(() => {\n if (!settled) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} ${STEP_TIMEOUT_FORCE_KILL_SUFFIX}`,\n );\n this.killActiveStep(TERMINATE_FORCE_KILL_SIGNAL);\n }\n }, FORCE_KILL_GRACE_PERIOD_MS);\n return;\n }\n\n void settle({ status: 'timed_out', timeoutMs });\n }, timeoutMs);\n\n // The end of the output becomes the reason when a failing\n // `restart-from` step turns into a fix request.\n const outputTail: string[] = [];\n const keep = (line: string) => {\n outputTail.push(line);\n if (outputTail.length > OUTPUT_TAIL_LINES) outputTail.shift();\n };\n\n child.stdout?.on('data', (data: Buffer) => {\n for (const line of data.toString().split('\\n')) {\n if (line) {\n keep(line);\n this.logger.info(line);\n }\n }\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n for (const line of data.toString().split('\\n')) {\n if (line) {\n keep(line);\n this.logger.error(line);\n }\n }\n });\n\n child.on('error', (error) => {\n void settle({\n status: 'spawn_error',\n error: new WorkflowStepSpawnError(\n {\n commandPreview: command.split(COMMAND_LINE_BREAK)[0],\n source: STEP_RUNNER_EXECUTE_SOURCE,\n stepName,\n workDir,\n },\n { cause: error },\n ),\n });\n });\n\n child.on('exit', async (code, signal) => {\n // Kill the process group to clean up any orphaned background processes\n // (e.g. http servers spawned by claude during manual testing)\n if (!interactive) {\n await this.cleanupProcessGroup();\n }\n // The exit event can come before the last output is read, and that\n // output is what the step's log and a restart-from reason report.\n await outputDrained(child);\n\n if (timedOut && timeoutMs !== null) {\n void settle({ status: 'timed_out', timeoutMs });\n return;\n }\n\n if (signal === INTERRUPT_SIGNAL) {\n void settle({ status: 'signaled', signal: INTERRUPT_SIGNAL });\n return;\n }\n\n if (signal === TERMINATE_SIGNAL) {\n void settle({ status: 'signaled', signal: TERMINATE_SIGNAL });\n return;\n }\n\n // A hangup is a termination like the two above. Falling through would\n // report the killed step as completed with an unknown exit code, and\n // the run would carry on as if nothing had gone wrong.\n if (signal === HANGUP_SIGNAL) {\n void settle({ status: 'signaled', signal: HANGUP_SIGNAL });\n return;\n }\n\n void settle({\n status: 'completed',\n exitCode: code ?? UNKNOWN_EXIT_CODE,\n ...(outputTail.length === 0 ? {} : { outputTail: outputTail.join(COMMAND_LINE_BREAK) }),\n });\n });\n });\n }\n\n /**\n * Start a step through the host executor when it offers one, else spawn it.\n */\n private startStepExecution(request: {\n traceparent?: string;\n command: string;\n custom: ResolvedCustomRun | undefined;\n interactive: boolean;\n onExecutionStarted: StepRunOptions['onExecutionStarted'];\n runConfig: RunConfig | undefined;\n stepEnv: NodeJS.ProcessEnv;\n stepName: string;\n jobEnvironment: Readonly<Record<string, string>>;\n attempt: number;\n template: StepCommandTemplate | undefined;\n timeoutMs: number | null;\n workDir: string;\n }): Promise<StepExecutionResult> {\n const { command, custom, interactive, stepEnv, stepName, template, timeoutMs, workDir } = request;\n const executor = this.stepExecutor;\n const base = {\n traceparent: request.traceparent,\n cwd: workDir,\n env: this.definedEnv({ ...stepEnv, [FORCE_COLOR_KEY]: FORCE_COLOR_VALUE }),\n stepName,\n jobEnvironment: request.jobEnvironment,\n attempt: request.attempt,\n ...(request.runConfig ? { runConfig: request.runConfig } : {}),\n };\n const executeCustom = executor?.custom?.bind(executor);\n if (custom && executeCustom) {\n return this.executeExternal(\n () => executeCustom.call(executor, { ...base, customRun: custom }),\n stepName,\n workDir,\n command,\n timeoutMs,\n request.onExecutionStarted,\n );\n }\n\n const executionCommand = interactive ? this.withInteractiveTerminalTitle(command, stepEnv) : command;\n const executeCommand = executor?.command?.bind(executor);\n const spawnHere = () =>\n interactive\n ? this.withTerminal(() =>\n this.interruptedSignal\n ? Promise.resolve<StepExecutionResult>({ status: RESULT_STATUS_SIGNALED, signal: this.interruptedSignal })\n : this.executeCommand(executionCommand, workDir, stepEnv, stepName, interactive, timeoutMs),\n )\n : this.executeCommand(executionCommand, workDir, stepEnv, stepName, interactive, timeoutMs);\n if (!executeCommand) {\n return spawnHere();\n }\n return this.executeExternal(\n () =>\n executeCommand.call(executor, {\n ...base,\n command: executionCommand,\n interactive,\n ...(template === undefined ? {} : { template }),\n }),\n stepName,\n workDir,\n command,\n timeoutMs,\n request.onExecutionStarted,\n spawnHere,\n );\n }\n\n /**\n * Run with the terminal to itself. An interactive step the engine spawns\n * inherits the terminal, so parallel ones take turns instead of fighting\n * over one keyboard; a host places its steps in panes of their own.\n */\n private async withTerminal<T>(run: () => Promise<T>): Promise<T> {\n const previous = this.terminalLock.tail;\n let release: () => void = () => {};\n this.terminalLock.tail = new Promise<void>((resolve) => {\n release = resolve;\n });\n await previous;\n try {\n return await run();\n } finally {\n release();\n }\n }\n\n /**\n * Await a host-owned execution and normalize it like a child process.\n *\n * The engine keeps ownership of the timeout; stop, pause and status-file\n * completion reach the execution through `killActiveStep`, which calls its\n * `stop`. A stopped execution reads as signalled so shutdown still interrupts\n * the workflow, while the completion races report their own outcome.\n */\n private async executeExternal(\n start: () => Promise<StepExecution | undefined>,\n stepName: string,\n workDir: string,\n command: string,\n timeoutMs: number | null,\n onExecutionStarted: StepRunOptions['onExecutionStarted'],\n declined?: () => Promise<StepExecutionResult>,\n ): Promise<StepExecutionResult> {\n let execution: StepExecution | undefined;\n try {\n execution = await start();\n } catch (error) {\n return {\n status: RESULT_STATUS_SPAWN_ERROR,\n error: new WorkflowStepSpawnError(\n {\n commandPreview: command.split(COMMAND_LINE_BREAK)[0],\n source: STEP_RUNNER_EXECUTE_SOURCE,\n stepName,\n workDir,\n },\n { cause: error },\n ),\n };\n }\n\n if (!execution) {\n if (declined) return declined();\n return {\n status: RESULT_STATUS_SPAWN_ERROR,\n error: new WorkflowStepSpawnError({\n commandPreview: command.split(COMMAND_LINE_BREAK)[0],\n source: STEP_RUNNER_EXECUTE_SOURCE,\n stepName,\n workDir,\n }),\n };\n }\n\n const active: ActiveExternalExecution = { execution, stepName, stopSignal: null };\n this.activeExternal = active;\n let timedOut = false;\n const timeoutTimer =\n timeoutMs === null\n ? null\n : setTimeout(() => {\n timedOut = true;\n this.stopExternal(active, TERMINATE_SIGNAL);\n }, timeoutMs);\n try {\n if (execution.ref) {\n this.logger.info(` ${DIM}${execution.ref.kind}${RESET} ${execution.ref.label ?? execution.ref.id}`);\n await onExecutionStarted?.(execution.ref);\n }\n const outcome = await execution.completion.catch((error: unknown) => ({\n error: error instanceof Error ? error : new Error(String(error)),\n }));\n if (timedOut && timeoutMs !== null) return { status: RESULT_STATUS_TIMED_OUT, timeoutMs };\n if (active.stopSignal) return { status: RESULT_STATUS_SIGNALED, signal: active.stopSignal };\n if ('error' in outcome) {\n return { status: RESULT_STATUS_COMPLETED, exitCode: UNKNOWN_EXIT_CODE, failure: outcome.error.message };\n }\n return {\n status: RESULT_STATUS_COMPLETED,\n exitCode: outcome.exitCode,\n ...(outcome.outputTail === undefined ? {} : { outputTail: outcome.outputTail }),\n };\n } finally {\n if (timeoutTimer) clearTimeout(timeoutTimer);\n if (this.activeExternal === active) this.activeExternal = null;\n }\n }\n\n /** Ask a host execution to end, once. A failed request is reported, not thrown. */\n private stopExternal(active: ActiveExternalExecution, signal: NodeJS.Signals): void {\n if (active.stopSignal) return;\n active.stopSignal = signal;\n void active.execution.stop().catch((error: unknown) => {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_SIGNAL_MESSAGE} ${active.stepName} (${error instanceof Error ? error.message : String(error)})`,\n );\n });\n }\n\n private definedEnv(env: NodeJS.ProcessEnv): Record<string, string> {\n const defined: Record<string, string> = {};\n for (const [key, value] of Object.entries(env)) {\n if (value !== undefined) defined[key] = value;\n }\n return defined;\n }\n\n /**\n * Why the step's own artifacts fail it, or undefined when all were updated.\n * The job's outputs it was reminded of are the job's to check once it ends,\n * since a later step may still write them.\n */\n private async describeArtifactWarnings(\n stepEnv: NodeJS.ProcessEnv,\n snapshots: StepArtifactSnapshot[],\n ): Promise<string | undefined> {\n const runDir = stepEnv[WORKFLOW_RUN_DIR_ENV_KEY];\n if (!runDir) return undefined;\n const own = snapshots.filter((snapshot) => snapshot.job === undefined);\n if (own.length === 0) return undefined;\n const warnings = await this.runDirectoryService.findStepArtifactWarnings(runDir, own);\n if (warnings.length === 0) return undefined;\n return `did not update its declared artifacts: ${warnings.map((warning) => `${warning.path} (${warning.status})`).join(', ')}`;\n }\n\n /**\n * Build interruption metadata for downstream workflow error handling.\n */\n private createInterruptContext(stepName: string, command: string): WorkflowInterruptContext {\n return {\n phase: STEP_EXECUTION_PHASE,\n stepName,\n commandPreview: command.split(COMMAND_LINE_BREAK)[0],\n source: STEP_RUNNER_SOURCE,\n };\n }\n\n /**\n * Render a safe summary of the spawn failure cause for operator logs.\n */\n private formatSpawnError(error: WorkflowStepSpawnError): string {\n const cause = error.cause;\n if (!(cause instanceof Error)) {\n return SPAWN_ERROR_FALLBACK_HINT;\n }\n\n // A host executor that could not start the step says why in its message; an\n // OS spawn failure says it in its code.\n if (!('code' in cause) || typeof cause.code !== 'string') return cause.message || SPAWN_ERROR_FALLBACK_HINT;\n const causePath = 'path' in cause && typeof cause.path === 'string' ? ` at ${cause.path}` : '';\n return `${cause.code}${causePath}; ${SPAWN_ERROR_RECOVERY_HINT}`;\n }\n\n /** Only launch/default subagent preferences affect customRun, never runner-name overrides. */\n private customRunChoiceConfig(runConfig: RunConfig | undefined): RunConfig | undefined {\n const selection = this.commandSelection;\n const settings = choiceSettings(selection.choices?.[selection.choice ?? DEFAULT_CHOICE]);\n const { subagentModel, subagentThinking } = settings;\n if (subagentModel === undefined && subagentThinking === undefined) return runConfig;\n return {\n ...runConfig,\n ...(subagentModel === undefined ? {} : { subagentModel }),\n ...(subagentThinking === undefined ? {} : { subagentThinking }),\n };\n }\n\n private resolveStepCommand(\n step: Step,\n context: InterpolationContext,\n runner?: string,\n decisionFile?: string,\n ): ResolvedStepCommand | null {\n if (Array.isArray(step.interactiveRun)) {\n return this.resolveTemplateCommand(step, step.interactiveRun, context, runner, decisionFile);\n }\n const customRun = step[CUSTOM_RUN_KEY];\n // A command mapped to the selected runner is that runner's own way to run the\n // step, so it beats customRun, unless customRun names the runner too: the\n // command is then the runner's terminal fallback for a host with no executor.\n const runnerCommand = runner !== undefined && this.collectMappedRunnerKeys(step).includes(runner);\n const entry = customRun ? customRunEntry(customRun, runner) : undefined;\n if (entry && this.stepExecutor?.custom && (!runnerCommand || customRunNames(customRun, runner))) {\n const runConfig = this.customRunChoiceConfig(\n entry.runConfig ? { ...step.runConfig, ...entry.runConfig } : step.runConfig,\n );\n const entryContext: InterpolationContext = runConfig ? { ...context, runConfig } : context;\n const prompt = this.parser.interpolate(entry.prompt, entryContext);\n const systemPrompt =\n entry.systemPrompt === undefined ? undefined : this.parser.interpolate(entry.systemPrompt, entryContext);\n return {\n command: `${CUSTOM_RUN_KEY}: ${prompt.split(COMMAND_LINE_BREAK)[0]}`,\n custom: { prompt, ...(systemPrompt === undefined ? {} : { systemPrompt }) },\n ...(runConfig === undefined ? {} : { runConfig }),\n interactive: false,\n };\n }\n\n const interactiveRun = legacyCommand(step[INTERACTIVE_RUN_KEY]);\n const hasInteractiveRun = interactiveRun != null;\n const primary = hasInteractiveRun\n ? { command: interactiveRun, interactive: true }\n : { command: step[RUN_KEY], interactive: false };\n const secondary = hasInteractiveRun\n ? { command: step[RUN_KEY], interactive: false }\n : { command: interactiveRun, interactive: true };\n\n const exactPrimary = this.resolveExactAgentCommand(primary.command, context, runner);\n if (exactPrimary) {\n return { ...exactPrimary, interactive: primary.interactive };\n }\n\n const exactSecondary = this.resolveExactAgentCommand(secondary.command, context, runner);\n if (exactSecondary) {\n return { ...exactSecondary, interactive: secondary.interactive };\n }\n\n // A customRun step's commands are its fallback on a host without an executor,\n // so a runner they do not name, such as a named custom runner, is not missing.\n const missingRunner = customRun ? null : this.resolveMissingExplicitRunner(step, runner);\n if (missingRunner) {\n return { command: '', interactive: false, missingRunner };\n }\n\n const stringPrimary = this.resolveStringCommand(primary.command, context);\n if (stringPrimary) {\n return { command: stringPrimary, interactive: primary.interactive };\n }\n\n const stringSecondary = this.resolveStringCommand(secondary.command, context);\n if (stringSecondary) {\n return { command: stringSecondary, interactive: secondary.interactive };\n }\n\n const firstPrimary = this.resolveFirstMappedCommand(primary.command, context);\n if (firstPrimary) {\n return { command: firstPrimary, interactive: primary.interactive };\n }\n\n const firstSecondary = this.resolveFirstMappedCommand(secondary.command, context);\n if (firstSecondary) {\n return { command: firstSecondary, interactive: secondary.interactive };\n }\n\n return null;\n }\n\n /**\n * Render a templated interactiveRun for the selected command and choice.\n *\n * The command is the launch's `--command`, else `--runner` when the step\n * offers a command of that name, else the step's first. The choice is the\n * entry's, else the step's, else the launch's `--choice`, else `default`.\n * Its step/subagent settings, with the command's own override, lay over the\n * step's runConfig; the result feeds both the template and host executors.\n */\n private resolveTemplateCommand(\n step: Step,\n offered: CommandRef[],\n context: InterpolationContext,\n runner: string | undefined,\n decisionFile: string | undefined,\n ): ResolvedStepCommand {\n const selection = this.commandSelection;\n const failed = (templateError: string): ResolvedStepCommand => ({ command: '', interactive: true, templateError });\n const wanted =\n selection.command ??\n (runner !== undefined && offered.some((entry) => entry.command === runner) ? runner : undefined);\n const entry = wanted === undefined ? offered[0] : offered.find((candidate) => candidate.command === wanted);\n if (!entry) {\n return failed(\n `command \"${wanted}\" is not offered by this step (offered: ${offered.map((candidate) => candidate.command).join(', ')})`,\n );\n }\n const declared = selection.commands?.[entry.command];\n if (!declared) return failed(`command \"${entry.command}\" is not declared under commands`);\n\n const choiceName =\n entry.choice ??\n step.choice ??\n selection.choice ??\n (selection.choices?.[DEFAULT_CHOICE] ? DEFAULT_CHOICE : undefined);\n const choice = choiceName === undefined ? undefined : selection.choices?.[choiceName];\n if (choiceName !== undefined && !choice) return failed(`choice \"${choiceName}\" is not declared under choices`);\n\n const runConfig: RunConfig = {\n ...step.runConfig,\n ...entry.runConfig,\n ...choiceSettings(choice, entry.command),\n };\n const promptContext: InterpolationContext = { ...context, runConfig };\n const promptSource = entry.prompt ?? step.prompt ?? '';\n const prompt = this.parser.interpolate(promptSource, promptContext);\n const systemPromptSource = entry.systemPrompt ?? step.systemPrompt;\n const systemPrompt =\n [\n systemPromptSource === undefined ? undefined : this.parser.interpolate(systemPromptSource, promptContext),\n this.decisionInstructions(context, decisionFile),\n ]\n .filter((part): part is string => part !== undefined && part.length > 0)\n .join('\\n\\n') || undefined;\n\n const { run, inProcess } = commandTemplateOf(declared);\n // A command with no system-prompt flag still has to carry the decision\n // instructions, so they lead its prompt instead.\n const passesSystemPrompt = this.parser.templateUsesSystemPrompt(run);\n const values: Record<string, unknown> = {\n ...runConfig,\n command: entry.command,\n prompt: systemPrompt === undefined || passesSystemPrompt ? prompt : `${systemPrompt}\\n\\n${prompt}`,\n ...(choiceName === undefined ? {} : { choice: choiceName }),\n ...(systemPrompt === undefined || !passesSystemPrompt ? {} : { systemPrompt }),\n };\n let command: string;\n try {\n command = this.parser.renderCommandTemplate(run, values);\n } catch (error) {\n return failed(\n `command \"${entry.command}\" did not render: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return {\n agentKey: entry.command,\n command,\n interactive: true,\n runConfig,\n template: {\n name: entry.command,\n inProcess,\n prompt,\n reads: [\n ...new Set(\n offered.flatMap((candidate) => {\n const offeredTemplate = selection.commands?.[candidate.command];\n return offeredTemplate === undefined\n ? []\n : this.parser.templateVariables(commandTemplateOf(offeredTemplate).run);\n }),\n ),\n ],\n ...(choiceName === undefined ? {} : { choice: choiceName }),\n ...(systemPrompt === undefined ? {} : { systemPrompt }),\n },\n };\n }\n\n /** The job's decision instructions, naming this step's own decision file once it has one. */\n private decisionInstructions(context: InterpolationContext, decisionFile: string | undefined): string | undefined {\n const instructions = context.env[WORKFLOW_DECISION_INSTRUCTIONS_ENV];\n const runDir = context.env[WORKFLOW_RUN_DIR_ENV_KEY];\n if (instructions === undefined || decisionFile === undefined || !runDir) return instructions;\n const job = context.env[WORKFLOW_JOB_NAME_ENV_KEY] ?? '';\n const targets = (context.env[WORKFLOW_RESTART_TARGETS_ENV] ?? '').split(',').filter(Boolean);\n return stepDecisionInstructions(runDir, job, targets, decisionFile);\n }\n\n private resolveExactAgentCommand(\n command: StepCommand | undefined,\n context: InterpolationContext,\n runner?: string,\n ): ResolvedStepCommand | null {\n if (!runner || !command || typeof command === 'string') {\n return null;\n }\n const exactCommand = command[runner];\n return exactCommand\n ? {\n agentKey: runner,\n command: this.parser.interpolate(exactCommand, context),\n interactive: false,\n }\n : null;\n }\n\n private resolveStringCommand(command: StepCommand | undefined, context: InterpolationContext): string | null {\n if (!command || typeof command !== 'string') {\n return null;\n }\n return this.parser.interpolate(command, context);\n }\n\n private resolveFirstMappedCommand(command: StepCommand | undefined, context: InterpolationContext): string | null {\n if (!command || typeof command === 'string') {\n return null;\n }\n const [firstCommand] = Object.values(command);\n return firstCommand ? this.parser.interpolate(firstCommand, context) : null;\n }\n\n private resolveMissingExplicitRunner(\n step: Step,\n runner: string | undefined,\n ): { availableKeys: string[]; runner: string } | null {\n if (!runner) {\n return null;\n }\n\n const availableKeys = this.collectMappedRunnerKeys(step);\n if (availableKeys.length === 0) {\n return null;\n }\n\n return availableKeys.includes(runner) ? null : { availableKeys, runner };\n }\n\n private collectMappedRunnerKeys(step: Step): string[] {\n const keys = new Set<string>();\n for (const command of [legacyCommand(step[INTERACTIVE_RUN_KEY]), step[RUN_KEY]]) {\n if (command && typeof command !== 'string') {\n for (const key of Object.keys(command)) {\n keys.add(key);\n }\n }\n }\n return [...keys];\n }\n\n private resolveRunner(options: StepRunOptions): string | undefined {\n return options.runner ?? options.cliAgent;\n }\n\n private formatStepDisplay(jobName: string | undefined, stepName: string): string {\n return jobName ? `${jobName} > ${stepName}` : stepName;\n }\n\n private withInteractiveTerminalTitle(command: string, stepEnv: NodeJS.ProcessEnv): string {\n const stepDisplay =\n stepEnv[WORKFLOW_STEP_DISPLAY_ENV_KEY] ?? command.split(COMMAND_LINE_BREAK)[0] ?? DEFAULT_STEP_NAME;\n const title = `${WORKFLOW_TERMINAL_TITLE}: ${stepDisplay}`;\n const setTitleCommand = `[ -t 1 ] && printf '\\\\033]0;%s\\\\007' ${this.escapeShellArg(title)}`;\n const resetTitleCommand = `[ -t 1 ] && printf '\\\\033]0;%s\\\\007' ${this.escapeShellArg(WORKFLOW_TERMINAL_TITLE)}`;\n return `trap ${this.escapeShellArg(resetTitleCommand)} EXIT${COMMAND_LINE_BREAK}${setTitleCommand}${COMMAND_LINE_BREAK}${command}`;\n }\n\n private escapeShellArg(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n }\n\n private async shouldRetryForCodexQuota(stepName: string, isCodexCommand: boolean): Promise<boolean> {\n if (!isCodexCommand) {\n return false;\n }\n\n const quotaStatus = await this.readCodexQuotaStatus(stepName);\n return quotaStatus?.blockingLimit != null;\n }\n\n private async waitForCodexQuotaAvailability(\n stepName: string,\n command: string,\n isCodexCommand: boolean,\n ): Promise<void> {\n if (!isCodexCommand) {\n return;\n }\n\n while (true) {\n const quotaStatus = await this.readCodexQuotaStatus(stepName);\n const blockingLimit = quotaStatus?.blockingLimit;\n if (!blockingLimit) {\n return;\n }\n\n const waitTargetMs = blockingLimit.resetAt * 1000 + QUOTA_WAIT_RESET_BUFFER_MS;\n const remainingMs = Math.max(waitTargetMs - Date.now(), QUOTA_WAIT_RESET_BUFFER_MS);\n const waitDescription = new Date(waitTargetMs).toLocaleString();\n const planSuffix = quotaStatus?.planType ? ` (${quotaStatus.planType})` : '';\n\n this.logger.warn(\n ` ${YELLOW}${STATUS_WAIT}${RESET} codex quota ${blockingLimit.limitName}/${blockingLimit.window} is at ${blockingLimit.usedPercent}%${planSuffix}; waiting until ${waitDescription}`,\n );\n\n await this.waitForQuotaDelay(stepName, command, remainingMs);\n }\n }\n\n private async readCodexQuotaStatus(stepName: string): Promise<CodexQuotaStatus | null> {\n try {\n return await this.quotaService.getQuotaStatus();\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} unable to read codex quota for \"${stepName}\" (${this.formatQuotaError(error)})`,\n );\n return null;\n }\n }\n\n private async waitForQuotaDelay(stepName: string, command: string, remainingMs: number): Promise<void> {\n const controller = new AbortController();\n this.activeQuotaWait = {\n controller,\n signal: null,\n stepName,\n };\n\n try {\n let timeLeftMs = remainingMs;\n while (timeLeftMs > 0) {\n const sleepMs = Math.min(timeLeftMs, QUOTA_WAIT_POLL_INTERVAL_MS);\n await this.waitForDelay(sleepMs, controller.signal);\n timeLeftMs -= sleepMs;\n }\n } catch (error) {\n if (controller.signal.aborted) {\n const interruptSignal = this.activeQuotaWait?.signal ?? TERMINATE_SIGNAL;\n throw new WorkflowInterruptedError(interruptSignal, {\n cause: new Error(`Interrupted while waiting for Codex quota reset`),\n context: {\n ...this.createInterruptContext(stepName, command),\n phase: QUOTA_WAIT_SOURCE,\n },\n });\n }\n\n throw error;\n } finally {\n this.activeQuotaWait = null;\n }\n }\n\n private async waitForDelay(delayMs: number, signal: AbortSignal): Promise<void> {\n await new Promise<void>((resolveDelay, rejectDelay) => {\n const timeout = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolveDelay();\n }, delayMs);\n\n const onAbort = () => {\n clearTimeout(timeout);\n signal.removeEventListener('abort', onAbort);\n rejectDelay(new Error('aborted'));\n };\n\n signal.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n private formatQuotaError(error: unknown): string {\n if (error instanceof Error && error.message.trim().length > 0) {\n return error.message;\n }\n\n return 'unknown quota error';\n }\n\n /**\n * Resolve the per-step timeout from workflow YAML into milliseconds.\n */\n private resolveTimeoutMs(step: Step, stepName: string): number | null {\n const timeoutMinutes = step[STEP_TIMEOUT_MINUTES_KEY];\n if (timeoutMinutes === undefined) {\n return null;\n }\n\n try {\n const parsedTimeoutMinutes = StepTimeoutMinutesSchema.parse(timeoutMinutes);\n return Math.ceil(parsedTimeoutMinutes * MINUTE_IN_MS);\n } catch (error) {\n throw new WorkflowStepTimeoutConfigError(\n {\n stepName,\n configKey: STEP_TIMEOUT_MINUTES_KEY,\n timeoutValue: timeoutMinutes,\n },\n { cause: error },\n );\n }\n }\n\n /**\n * Resolve the per-step timeout retry count from workflow YAML.\n */\n private resolveTimeoutRetries(step: Step, stepName: string): number {\n const rawValue = step[STEP_TIMEOUT_RETRIES_KEY];\n try {\n return StepTimeoutRetriesSchema.parse(rawValue);\n } catch (error) {\n throw new WorkflowStepTimeoutConfigError(\n {\n stepName,\n configKey: STEP_TIMEOUT_RETRIES_KEY,\n timeoutValue: rawValue,\n },\n { cause: error },\n );\n }\n }\n\n /**\n * Format timeout durations for operator-facing logs.\n */\n private formatTimeoutMs(timeoutMs: number): string {\n return timeoutMs % MINUTE_IN_MS === 0\n ? `${timeoutMs / MINUTE_IN_MS} ${TIMEOUT_UNIT_MINUTES}`\n : `${timeoutMs}${TIMEOUT_UNIT_MILLISECONDS}`;\n }\n\n /**\n * Send SIGTERM to the active step's process group to clean up orphaned\n * background processes (e.g. http servers spawned during manual testing).\n * Silently ignores ESRCH when the group has already exited.\n */\n private async cleanupProcessGroup(): Promise<void> {\n const processGroupId = this.activeStep?.processGroupId;\n const stepName = this.activeStep?.stepName;\n if (processGroupId === null || processGroupId === undefined || !stepName) {\n return;\n }\n try {\n this.runtime.workflowHost.signal(-processGroupId, TERMINATE_SIGNAL);\n } catch (error) {\n const errorCode = (error as NodeJS.ErrnoException).code;\n if (errorCode !== ESRCH_ERROR_CODE) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_CLEANUP_PROCESS_GROUP_MESSAGE} ${stepName} (pgid=${processGroupId}, error=${errorCode})`,\n );\n } else {\n this.logger.info(` ${DIM}cleanup${RESET} process group ${processGroupId} already exited (ESRCH)`);\n }\n return;\n }\n\n await this.waitForProcessGroupToExit(processGroupId, FORCE_KILL_GRACE_PERIOD_MS);\n if (!this.isProcessGroupAlive(processGroupId)) return;\n\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} process group did not exit after SIGTERM, forcing SIGKILL`,\n );\n try {\n this.runtime.workflowHost.signal(-processGroupId, TERMINATE_FORCE_KILL_SIGNAL);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== ESRCH_ERROR_CODE) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_CLEANUP_PROCESS_GROUP_MESSAGE} ${stepName} (pgid=${processGroupId}, error=${(error as NodeJS.ErrnoException).code})`,\n );\n }\n return;\n }\n await this.waitForProcessGroupToExit(processGroupId, PROCESS_EXIT_WAIT_TIMEOUT_MS);\n }\n\n private isProcessGroupAlive(processGroupId: number): boolean {\n try {\n this.runtime.workflowHost.signal(-processGroupId, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== ESRCH_ERROR_CODE;\n }\n }\n\n private async waitForProcessGroupToExit(processGroupId: number, timeoutMs: number): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while (this.isProcessGroupAlive(processGroupId) && Date.now() < deadline) {\n await new Promise((resolveWait) => setTimeout(resolveWait, PROCESS_EXIT_POLL_INTERVAL_MS));\n }\n }\n\n /**\n * Best-effort cleanup for interactive commands that inherit the terminal.\n * These commands are intentionally not detached, so keep an explicit PID\n * snapshot before signaling; once the shell exits, descendants may be\n * re-parented and no longer discoverable from the shell PID.\n */\n private async cleanupInteractiveProcessTree(signal: NodeJS.Signals): Promise<boolean> {\n if (!this.activeStep || !this.activeStep.interactive) {\n return false;\n }\n\n const stepName = this.activeStep.stepName;\n this.captureInteractiveProcessOwnership(this.activeStep.process);\n const initialProcessIds = this.collectInteractiveProcessIds();\n if (initialProcessIds.length === 0) {\n this.lastInteractiveReap = { survivors: [], sigkillEscalated: false };\n return false;\n }\n\n const initialProcessGroupIds = [\n ...new Set([\n ...this.activeStep.trackedProcessGroupIds,\n ...this.collectInteractiveProcessGroupIds(initialProcessIds),\n ]),\n ];\n this.logger.info(\n ` ${DIM}cleanup${RESET} reaping ${stepName} interactive pids [${initialProcessIds.join(', ')}]${initialProcessGroupIds.length > 0 ? ` groups [${initialProcessGroupIds.join(', ')}]` : ''}`,\n );\n\n const graceMs = this.interactiveKillGraceMs();\n if (signal !== TERMINATE_FORCE_KILL_SIGNAL) {\n await this.reapInteractiveTree(signal, graceMs);\n }\n\n const sigkillEscalated = this.collectInteractiveProcessIds().length > 0;\n if (sigkillEscalated) {\n // Anything alive after the SIGTERM grace is force-killed. Re-walking each\n // round catches descendants that re-parented away from the original root\n // after the shell exited and would escape a single snapshot.\n await this.reapInteractiveTree(TERMINATE_FORCE_KILL_SIGNAL, graceMs);\n }\n\n const survivors = this.collectInteractiveProcessIds().map((pid) => ({\n pid,\n command: this.describeProcess(pid),\n }));\n this.lastInteractiveReap = { survivors, sigkillEscalated };\n if (survivors.length > 0) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} interactive processes survived termination: ${survivors\n .map((entry) => `${entry.pid} (${entry.command})`)\n .join(', ')}`,\n );\n }\n\n return true;\n }\n\n /**\n * Re-signal the live interactive descendants until none remain or `budgetMs`\n * elapses, re-walking the process tree each round. An interactive TUI keeps\n * spawning and re-parenting descendants (MCP servers, browser/render helpers)\n * that a single snapshot misses; group-signalling also reaps members spawned\n * after the snapshot. Returns as soon as the tree is empty so the common,\n * already-exited case adds no latency.\n */\n private async reapInteractiveTree(signal: NodeJS.Signals, budgetMs: number): Promise<void> {\n const deadline = Date.now() + budgetMs;\n do {\n this.captureInteractiveProcessOwnership(this.activeStep?.process);\n const liveProcessIds = this.collectInteractiveProcessIds();\n if (liveProcessIds.length === 0) {\n return;\n }\n\n if (this.activeStep) {\n this.activeStep.lastSignaledProcessIds = liveProcessIds;\n }\n this.signalProcessIds(liveProcessIds, signal);\n this.signalProcessGroups(\n [\n ...new Set([\n ...(this.activeStep?.trackedProcessGroupIds ?? []),\n ...this.collectInteractiveProcessGroupIds(liveProcessIds),\n ]),\n ],\n signal,\n );\n await this.waitForProcessIdsToExit(liveProcessIds, INTERACTIVE_REAP_ROUND_INTERVAL_MS);\n } while (Date.now() < deadline);\n }\n\n /**\n * Operator-tunable SIGTERM→SIGKILL grace per teardown phase. Defaults to the\n * process-exit wait so ordinary interactive steps see no behaviour change.\n */\n private interactiveKillGraceMs(): number {\n const raw = this.runtime.baseEnvironment[INTERACTIVE_KILL_GRACE_MS_ENV_KEY];\n if (raw === undefined) {\n return PROCESS_EXIT_WAIT_TIMEOUT_MS;\n }\n\n const parsed = Number(raw);\n return Number.isInteger(parsed) && parsed > 0 ? parsed : PROCESS_EXIT_WAIT_TIMEOUT_MS;\n }\n\n /**\n * SIGTERM→SIGKILL grace on the completion path (status file signalled `YES`).\n * Deliberately longer than the timeout-path `FORCE_KILL_GRACE_PERIOD_MS` so an\n * interactive agent can flush its final telemetry batch (e.g. Claude Code's\n * OTEL Stop-hook events) before SIGKILL. A fast graceful exit still settles\n * immediately, so this only adds latency when a child lingers. Operator-tunable\n * via `WORKFLOW_STEP_FORCE_KILL_GRACE_MS`; defaults to STEP_COMPLETION_KILL_GRACE_MS.\n */\n private stepCompletionKillGraceMs(): number {\n const raw = this.runtime.baseEnvironment[STEP_COMPLETION_KILL_GRACE_MS_ENV_KEY];\n if (raw === undefined) {\n return STEP_COMPLETION_KILL_GRACE_MS;\n }\n\n const parsed = Number(raw);\n return Number.isInteger(parsed) && parsed > 0 ? parsed : STEP_COMPLETION_KILL_GRACE_MS;\n }\n\n /** Resolve a pid to its `ps` command line so survivors are identifiable. */\n private describeProcess(processId: number): string {\n try {\n const command = this.runtime.workflowHost.inspectProcesses('command', processId).trim();\n return command.length > 0 ? command : 'unknown';\n } catch {\n return 'unknown';\n }\n }\n\n /**\n * Append a forensic record for an interactive run to a capped JSON log so a\n * session that does not exit is self-diagnosing (which signal completed it and\n * what survived). Best-effort: logging never affects step control flow.\n */\n private async recordInteractiveCompletion(record: InteractiveCompletionRecord): Promise<void> {\n try {\n const logPath = await this.interactiveReapLogPath();\n const entries = await this.readInteractiveCompletionLog(logPath);\n entries.push(record);\n getOrThrow(await this.runtime.fs.createDir(dirname(logPath), { recursive: true }, this.runtime.ioContext));\n getOrThrow(\n await this.runtime.fs.writeFile(\n logPath,\n `${JSON.stringify(entries.slice(-INTERACTIVE_REAP_LOG_MAX_ENTRIES), null, 2)}\\n`,\n this.runtime.ioContext,\n ),\n );\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} interactive-reap log write failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n private async interactiveReapLogPath(): Promise<string> {\n const runDir = this.runtime.baseEnvironment[WORKFLOW_RUN_DIR_ENV_KEY];\n const baseDir =\n runDir && (await pathExists(this.runtime.fs, runDir, this.runtime.ioContext))\n ? runDir\n : join(this.runtime.cwd, 'tmp');\n return join(baseDir, INTERACTIVE_REAP_LOG_FILENAME);\n }\n\n private async readInteractiveCompletionLog(logPath: string): Promise<InteractiveCompletionRecord[]> {\n try {\n const parsed = JSON.parse(\n getOrThrow(await this.runtime.fs.readTextFile(logPath, this.runtime.ioContext)),\n ) as unknown;\n return Array.isArray(parsed) ? (parsed as InteractiveCompletionRecord[]) : [];\n } catch {\n return [];\n }\n }\n\n private captureInteractiveProcessOwnership(expectedProcess?: ChildProcess): void {\n const activeStep = this.activeStep;\n if (\n !activeStep?.interactive ||\n activeStep.rootProcessId === null ||\n (expectedProcess !== undefined && activeStep.process !== expectedProcess)\n ) {\n return;\n }\n\n const treeRoots = this.uniqueLiveProcessIds([\n activeStep.rootProcessId,\n ...activeStep.trackedProcessIds,\n ...activeStep.lastSignaledProcessIds,\n ]);\n const treeProcessIds = this.snapshotProcessTree(treeRoots).map((entry) => entry.pid);\n activeStep.trackedProcessIds = this.uniqueLiveProcessIds([\n ...activeStep.trackedProcessIds,\n ...activeStep.lastSignaledProcessIds,\n ...treeProcessIds,\n activeStep.rootProcessId,\n ]);\n activeStep.trackedProcessGroupIds = this.collectInteractiveProcessGroupIds(activeStep.trackedProcessIds);\n }\n\n private collectInteractiveProcessIds(): number[] {\n if (!this.activeStep?.interactive || this.activeStep.rootProcessId === null) {\n return [];\n }\n\n const rootProcessId = this.activeStep.rootProcessId;\n // Walk from every process observed while it was still owned by the\n // interactive root. A descendant can re-parent before teardown begins, so\n // final cleanup must not depend on current PPID ancestry alone.\n const treeRoots = this.uniqueLiveProcessIds([\n rootProcessId,\n ...this.activeStep.trackedProcessIds,\n ...this.activeStep.lastSignaledProcessIds,\n ]);\n const treeProcessIds = this.snapshotProcessTree(treeRoots).map((entry) => entry.pid);\n const processIds = [\n ...treeProcessIds,\n ...this.activeStep.trackedProcessIds,\n ...this.activeStep.lastSignaledProcessIds,\n rootProcessId,\n ];\n return this.uniqueLiveProcessIds(processIds);\n }\n\n private snapshotProcessTree(rootProcessIds: number[]): ProcessTreeEntry[] {\n if (rootProcessIds.length === 0) {\n return [];\n }\n\n let processRows: string;\n try {\n processRows = this.runtime.workflowHost.inspectProcesses('parents');\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} unable to inspect process tree for [${rootProcessIds.join(', ')}] (${error instanceof Error ? error.message : String(error)})`,\n );\n return rootProcessIds.filter((pid) => this.isProcessAlive(pid)).map((pid) => ({ depth: 0, pid }));\n }\n\n const childrenByParent = new Map<number, number[]>();\n for (const line of processRows.split(COMMAND_LINE_BREAK)) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n\n const [pidRaw, parentPidRaw] = trimmed.split(/\\s+/);\n const pid = Number(pidRaw);\n const parentPid = Number(parentPidRaw);\n if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) {\n continue;\n }\n\n const children = childrenByParent.get(parentPid) ?? [];\n children.push(pid);\n childrenByParent.set(parentPid, children);\n }\n\n const entries: ProcessTreeEntry[] = [];\n const visited = new Set<number>();\n const walk = (pid: number, depth: number) => {\n if (visited.has(pid)) {\n return;\n }\n visited.add(pid);\n if (pid !== this.runtime.workflowHost.processId) {\n entries.push({ depth, pid });\n }\n\n for (const childPid of childrenByParent.get(pid) ?? []) {\n walk(childPid, depth + 1);\n }\n };\n\n for (const rootProcessId of rootProcessIds) {\n walk(rootProcessId, 0);\n }\n return entries.sort((left, right) => right.depth - left.depth);\n }\n\n private signalProcessIds(processIds: number[], signal: NodeJS.Signals): boolean {\n let signaled = false;\n for (const processId of processIds) {\n if (processId === this.runtime.workflowHost.processId) {\n continue;\n }\n\n try {\n this.runtime.workflowHost.signal(processId, signal);\n signaled = true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== ESRCH_ERROR_CODE) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_SIGNAL_MESSAGE} pid ${processId} (${code ?? (error as Error).message})`,\n );\n }\n }\n }\n\n return signaled;\n }\n\n /**\n * Resolve the distinct process-group ids owned by the given pids, excluding\n * the runner's own group so a `kill(-pgid)` can never terminate this process.\n *\n * Interactive TUIs such as Claude Code make themselves process-group leaders\n * (pid === pgid) and spawn descendants into that group. Reaping by pid alone\n * leaves anything spawned after the one-shot tree snapshot alive, which keeps\n * the interactive session running after the Stop hook signalled completion.\n */\n private collectInteractiveProcessGroupIds(processIds: number[]): number[] {\n if (processIds.length === 0) {\n return [];\n }\n\n let processRows: string;\n try {\n processRows = this.runtime.workflowHost.inspectProcesses('groups');\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} unable to inspect process groups (${error instanceof Error ? error.message : String(error)})`,\n );\n return [];\n }\n\n const processGroupByPid = new Map<number, number>();\n for (const line of processRows.split(COMMAND_LINE_BREAK)) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n\n const [pidRaw, processGroupRaw] = trimmed.split(/\\s+/);\n const pid = Number(pidRaw);\n const processGroupId = Number(processGroupRaw);\n if (Number.isInteger(pid) && Number.isInteger(processGroupId)) {\n processGroupByPid.set(pid, processGroupId);\n }\n }\n\n const runnerProcessGroupId = processGroupByPid.get(this.runtime.workflowHost.processId);\n const processGroupIds = new Set<number>();\n for (const pid of processIds) {\n const processGroupId = processGroupByPid.get(pid);\n if (processGroupId === undefined || processGroupId <= 1 || processGroupId === runnerProcessGroupId) {\n continue;\n }\n processGroupIds.add(processGroupId);\n }\n\n return [...processGroupIds];\n }\n\n private signalProcessGroups(processGroupIds: number[], signal: NodeJS.Signals): boolean {\n let signaled = false;\n for (const processGroupId of processGroupIds) {\n try {\n this.runtime.workflowHost.signal(-processGroupId, signal);\n signaled = true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== ESRCH_ERROR_CODE) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_SIGNAL_MESSAGE} process group ${processGroupId} (${code ?? (error as Error).message})`,\n );\n }\n }\n }\n\n return signaled;\n }\n\n private uniqueLiveProcessIds(processIds: number[]): number[] {\n const seen = new Set<number>();\n const liveProcessIds: number[] = [];\n for (const processId of processIds) {\n if (\n !Number.isInteger(processId) ||\n processId <= 0 ||\n processId === this.runtime.workflowHost.processId ||\n seen.has(processId)\n ) {\n continue;\n }\n\n seen.add(processId);\n if (this.isProcessAlive(processId)) {\n liveProcessIds.push(processId);\n }\n }\n\n return liveProcessIds;\n }\n\n private isProcessAlive(processId: number): boolean {\n try {\n this.runtime.workflowHost.signal(processId, 0);\n return true;\n } catch {\n return false;\n }\n }\n\n private async waitForProcessIdsToExit(processIds: number[], timeoutMs: number): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (processIds.every((processId) => !this.isProcessAlive(processId))) {\n return;\n }\n\n await new Promise((resolveWait) => setTimeout(resolveWait, PROCESS_EXIT_POLL_INTERVAL_MS));\n }\n }\n\n /**\n * Signal the active step, preferring the detached process group so shell\n * pipelines shut down as a unit before falling back to the shell process.\n *\n * @param signal POSIX signal used to interrupt the running step.\n * @returns `true` when a signal was dispatched successfully, otherwise `false`.\n */\n private killActiveStep(signal: NodeJS.Signals): boolean {\n if (this.activeExternal) {\n this.stopExternal(this.activeExternal, signal);\n return true;\n }\n\n if (!this.activeStep) {\n return false;\n }\n\n if (this.activeStep.interactive) {\n this.captureInteractiveProcessOwnership(this.activeStep.process);\n const processIds = this.collectInteractiveProcessIds();\n if (processIds.length > 0) {\n this.activeStep.lastSignaledProcessIds = processIds;\n const signaledPids = this.signalProcessIds(processIds, signal);\n // Also reap the session's process group(s): an interactive TUI makes\n // itself a group leader and spawns descendants that escape a one-shot\n // pid snapshot, so a per-pid signal alone can leave the session alive.\n const signaledGroups = this.signalProcessGroups(\n [\n ...new Set([\n ...this.activeStep.trackedProcessGroupIds,\n ...this.collectInteractiveProcessGroupIds(processIds),\n ]),\n ],\n signal,\n );\n return signaledPids || signaledGroups;\n }\n }\n\n const { process: child, processGroupId } = this.activeStep;\n if (processGroupId !== null) {\n try {\n this.runtime.workflowHost.signal(-processGroupId, signal);\n return true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== ESRCH_ERROR_CODE) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_SIGNAL_MESSAGE} process group for ${this.activeStep.stepName}`,\n );\n } else {\n this.logger.info(\n ` ${DIM}signal${RESET} process group for ${this.activeStep.stepName} already exited (ESRCH)`,\n );\n }\n }\n }\n\n try {\n return child.kill(signal);\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${FAILED_TO_SIGNAL_MESSAGE} ${this.activeStep.stepName} (${(error as Error).message})`,\n );\n return false;\n }\n }\n\n /**\n * Create an empty temp file that the Claude Code Stop hook will write\n * YES to when the agent finishes its turn. The path is injected into\n * WORKFLOW_STATUS_FILE so the hook can locate it directly — no fallback\n * marker file is used.\n */\n private async createStatusFile(): Promise<string> {\n if (!this.runtime.temporaryDirectory)\n throw new Error('Workflow interactive status files require an admitted temporaryDirectory');\n const filePath = join(this.runtime.temporaryDirectory, `${STATUS_FILE_PREFIX}${randomUUID()}${STATUS_FILE_SUFFIX}`);\n getOrThrow(await this.runtime.fs.writeFile(filePath, '', this.runtime.ioContext));\n return filePath;\n }\n\n /**\n * Race interactive step execution against agent completion and workflow stop files.\n * When the file contains YES, SIGTERM the step process and wait for\n * it to exit before returning `status_completed`. Escalates to SIGKILL\n * if the process ignores SIGTERM. The next job must not start until\n * the child process tree has fully exited.\n */\n private async raceInteractiveCompletion(\n executionPromise: Promise<StepExecutionResult>,\n statusFilePath: string,\n stepName: string,\n stopRequestPath: string | undefined,\n pausePolicy: 'replay' | 'protected',\n ): Promise<StepExecutionResult> {\n return new Promise<StepExecutionResult>((resolveRace) => {\n let settled = false;\n let statusFileTriggered = false;\n let stopRequestTriggered = false;\n let pauseRequestTriggered = false;\n const pauseRequestPath = stopRequestPath ? join(dirname(stopRequestPath), PAUSE_REQUEST_FILENAME) : undefined;\n let forceKillTimer: NodeJS.Timeout | null = null;\n let completionSettleTimer: NodeJS.Timeout | null = null;\n let watcher: { close(context: WorkflowRuntimeContext['ioContext']): Promise<void> } | null = null;\n let stopWatcher: { close(context: WorkflowRuntimeContext['ioContext']): Promise<void> } | null = null;\n let pauseWatcher: { close(context: WorkflowRuntimeContext['ioContext']): Promise<void> } | null = null;\n let pollTimer: NodeJS.Timeout | null = null;\n let stopPollTimer: NodeJS.Timeout | null = null;\n let pausePollTimer: NodeJS.Timeout | null = null;\n // Tracks whether SIGTERM was actually delivered to the child\n let signalDelivered = false;\n // Tracks whether escalation to SIGKILL was required\n let sigkillEscalated = false;\n\n const resolveCompletionSource = (result: StepExecutionResult): InteractiveCompletionSource => {\n if (stopRequestTriggered) {\n return 'stop-request';\n }\n if (pauseRequestTriggered) {\n return 'pause-request';\n }\n if (statusFileTriggered) {\n return 'status-file';\n }\n switch (result.status) {\n case RESULT_STATUS_TIMED_OUT:\n return 'timed-out';\n case RESULT_STATUS_SPAWN_ERROR:\n return 'spawn-error';\n case RESULT_STATUS_SIGNALED:\n return 'signaled';\n default:\n return 'natural-exit';\n }\n };\n\n const settle = async (result: StepExecutionResult) => {\n if (settled) return;\n settled = true;\n if (watcher) {\n await watcher\n .close(this.runtime.ioContext)\n .catch((error: unknown) => this.logger.warn(`Workflow watcher cleanup failed: ${String(error)}`));\n watcher = null;\n }\n if (stopWatcher) {\n await stopWatcher\n .close(this.runtime.ioContext)\n .catch((error: unknown) => this.logger.warn(`Workflow watcher cleanup failed: ${String(error)}`));\n stopWatcher = null;\n }\n if (pauseWatcher) {\n await pauseWatcher\n .close(this.runtime.ioContext)\n .catch((error: unknown) => this.logger.warn(`Workflow watcher cleanup failed: ${String(error)}`));\n pauseWatcher = null;\n }\n if (pollTimer) {\n clearInterval(pollTimer);\n pollTimer = null;\n }\n if (stopPollTimer) {\n clearInterval(stopPollTimer);\n stopPollTimer = null;\n }\n if (pausePollTimer) {\n clearInterval(pausePollTimer);\n pausePollTimer = null;\n }\n if (forceKillTimer) {\n clearTimeout(forceKillTimer);\n forceKillTimer = null;\n }\n if (completionSettleTimer) {\n clearTimeout(completionSettleTimer);\n completionSettleTimer = null;\n }\n const settledResult =\n result.status === RESULT_STATUS_PAUSE_REQUESTED && this.lastInteractiveReap?.survivors.length\n ? { ...result, survivors: this.lastInteractiveReap.survivors }\n : result;\n await this.recordInteractiveCompletion({\n timestamp: new Date().toISOString(),\n stepName,\n statusFilePath,\n completionSource: resolveCompletionSource(settledResult),\n statusFileSignaled: statusFileTriggered,\n sigkillEscalated: sigkillEscalated || (this.lastInteractiveReap?.sigkillEscalated ?? false),\n survivors: this.lastInteractiveReap?.survivors ?? [],\n });\n this.lastInteractiveReap = null;\n resolveRace(settledResult);\n };\n\n const statusFileHasCompletionValue = async () => {\n try {\n return (\n (await pathExists(this.runtime.fs, statusFilePath, this.runtime.ioContext)) &&\n getOrThrow(await this.runtime.fs.readTextFile(statusFilePath, this.runtime.ioContext)).trim() ===\n STATUS_FILE_COMPLETION_VALUE\n );\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (!code || !TRANSIENT_FS_ERROR_CODES.has(code)) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} status-file read failed for ${stepName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n } else {\n this.logger.info(` ${DIM}status-file${RESET} transient FS error (${code}) polling ${stepName}`);\n }\n return false;\n }\n };\n\n // Absolute backstop: the status file is the source of truth for completion.\n // If a child ignores SIGTERM *and* SIGKILL its exit event never fires, so\n // `executionPromise` never resolves. Rather than hang the workflow until\n // `timeout-minutes`, settle on the verified completion once the kill grace\n // has elapsed, recording any survivors for the forensic reap log.\n const scheduleAbsoluteSettle = (result: StepExecutionResult, delayMs: number) => {\n if (settled || completionSettleTimer) {\n return;\n }\n completionSettleTimer = setTimeout(() => {\n if (settled) return;\n const survivors = this.collectInteractiveProcessIds().map((pid) => ({\n pid,\n command: this.describeProcess(pid),\n }));\n if (survivors.length > 0) {\n this.lastInteractiveReap = { survivors, sigkillEscalated: true };\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} signalled completion but ${survivors.length} process(es) survived termination; proceeding to the next step: ${survivors\n .map((entry) => `${entry.pid} (${entry.command})`)\n .join(', ')}`,\n );\n }\n void settle(result);\n }, delayMs);\n };\n\n const checkFileContent = async () => {\n if (!(await statusFileHasCompletionValue()) || settled || statusFileTriggered) {\n return;\n }\n\n statusFileTriggered = true;\n const graceMs = this.stepCompletionKillGraceMs();\n signalDelivered = this.killActiveStep(TERMINATE_SIGNAL);\n if (!signalDelivered) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} status-file: SIGTERM could not be delivered, process may have already exited`,\n );\n // The process appears gone; its exit should resolve the race shortly.\n // Still arm the backstop in case the awaited child is not the live agent.\n scheduleAbsoluteSettle(STATUS_FILE_COMPLETED_RESULT, PROCESS_EXIT_WAIT_TIMEOUT_MS);\n return;\n }\n // Give the agent the grace window to flush telemetry and exit before the\n // next job starts; escalate to SIGKILL if SIGTERM is ignored.\n forceKillTimer = setTimeout(() => {\n if (settled) return;\n sigkillEscalated = true;\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} did not exit after status-file SIGTERM, forcing SIGKILL`,\n );\n this.killActiveStep(TERMINATE_FORCE_KILL_SIGNAL);\n }, graceMs);\n // Backstop the child's exit event so a process that survives SIGKILL\n // cannot stall the workflow past the kill grace.\n scheduleAbsoluteSettle(STATUS_FILE_COMPLETED_RESULT, graceMs + PROCESS_EXIT_WAIT_TIMEOUT_MS);\n };\n\n const stopRequestExists = async () =>\n Boolean(stopRequestPath && (await this.hasCurrentStopRequest(stopRequestPath)));\n const pauseRequestExists = async () =>\n Boolean(\n pauseRequestPath &&\n (await pathExists(this.runtime.fs, pauseRequestPath, this.runtime.ioContext)) &&\n (await this.readControlAction(pauseRequestPath)) === 'pause',\n );\n\n const checkStopRequest = async () => {\n if (!(await stopRequestExists()) || settled || stopRequestTriggered) {\n return;\n }\n\n stopRequestTriggered = true;\n const graceMs = this.stepCompletionKillGraceMs();\n signalDelivered = this.killActiveStep(TERMINATE_SIGNAL);\n if (!signalDelivered) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} stop request: SIGTERM could not be delivered, process may have already exited`,\n );\n scheduleAbsoluteSettle({ status: RESULT_STATUS_STOP_REQUESTED }, PROCESS_EXIT_WAIT_TIMEOUT_MS);\n return;\n }\n\n forceKillTimer = setTimeout(() => {\n if (settled) return;\n sigkillEscalated = true;\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} did not exit after stop-request SIGTERM, forcing SIGKILL`,\n );\n this.killActiveStep(TERMINATE_FORCE_KILL_SIGNAL);\n }, graceMs);\n scheduleAbsoluteSettle({ status: RESULT_STATUS_STOP_REQUESTED }, graceMs + PROCESS_EXIT_WAIT_TIMEOUT_MS);\n };\n\n const checkPauseRequest = async () => {\n if (!(await pauseRequestExists()) || settled || stopRequestTriggered || pauseRequestTriggered) {\n return;\n }\n pauseRequestTriggered = true;\n if (pausePolicy === 'protected') return;\n\n const graceMs = this.stepCompletionKillGraceMs();\n signalDelivered = this.killActiveStep(TERMINATE_SIGNAL);\n if (!signalDelivered) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} pause request: SIGTERM could not be delivered, process may have already exited`,\n );\n scheduleAbsoluteSettle({ status: RESULT_STATUS_PAUSE_REQUESTED }, PROCESS_EXIT_WAIT_TIMEOUT_MS);\n return;\n }\n\n forceKillTimer = setTimeout(() => {\n if (settled) return;\n sigkillEscalated = true;\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} did not exit after pause-request SIGTERM, forcing SIGKILL`,\n );\n this.killActiveStep(TERMINATE_FORCE_KILL_SIGNAL);\n }, graceMs);\n scheduleAbsoluteSettle({ status: RESULT_STATUS_PAUSE_REQUESTED }, graceMs + PROCESS_EXIT_WAIT_TIMEOUT_MS);\n };\n\n // fs.watch for instant notification, poll as fallback for edge cases\n try {\n void this.watchStatusFile(\n [{ path: statusFilePath }],\n () => {\n void checkFileContent().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n },\n this.runtime.ioContext,\n )\n .then(async (result) => {\n const admitted = getOrThrow(result);\n if (settled) await admitted.close(this.runtime.ioContext);\n else watcher = admitted;\n })\n .catch((error: unknown) =>\n this.logger.warn(`Workflow status-file watcher unavailable, polling instead: ${String(error)}`),\n );\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} status-file watcher setup failed for ${stepName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n pollTimer = setInterval(() => {\n void checkFileContent().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n }, STATUS_FILE_POLL_INTERVAL_MS);\n if (stopRequestPath) {\n try {\n void this.watchStatusFile(\n [{ path: stopRequestPath }],\n () => {\n void checkStopRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n },\n this.runtime.ioContext,\n )\n .then(async (result) => {\n const admitted = getOrThrow(result);\n if (settled) await admitted.close(this.runtime.ioContext);\n else stopWatcher = admitted;\n })\n .catch((error: unknown) =>\n this.logger.warn(`Workflow stop-request watcher unavailable, polling instead: ${String(error)}`),\n );\n } catch (error) {\n const errorCode = (error as NodeJS.ErrnoException).code;\n if (errorCode !== 'ENOENT') {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} stop-request watcher setup failed for ${stepName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n stopPollTimer = setInterval(() => {\n void checkStopRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n }, STOP_REQUEST_POLL_INTERVAL_MS);\n }\n if (pauseRequestPath) {\n try {\n void this.watchStatusFile(\n [{ path: pauseRequestPath }],\n () => {\n void checkPauseRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n },\n this.runtime.ioContext,\n )\n .then(async (result) => {\n const admitted = getOrThrow(result);\n if (settled) await admitted.close(this.runtime.ioContext);\n else pauseWatcher = admitted;\n })\n .catch((error: unknown) =>\n this.logger.warn(`Workflow pause-request watcher unavailable, polling instead: ${String(error)}`),\n );\n } catch (error) {\n const errorCode = (error as NodeJS.ErrnoException).code;\n if (errorCode !== 'ENOENT') {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} pause-request watcher setup failed for ${stepName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n pausePollTimer = setInterval(() => {\n void checkPauseRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n }, STOP_REQUEST_POLL_INTERVAL_MS);\n }\n\n // Immediate check in case the file was written before watcher setup\n void checkFileContent().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n void checkStopRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n void checkPauseRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n\n void executionPromise.then(async (result) => {\n if (stopRequestTriggered) {\n if (sigkillEscalated) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} required SIGKILL escalation after stop request`,\n );\n }\n void settle({ status: RESULT_STATUS_STOP_REQUESTED });\n return;\n }\n\n const completedViaStatusFile = statusFileTriggered || (await statusFileHasCompletionValue());\n const protectedPauseEligible =\n result.status === RESULT_STATUS_STATUS_COMPLETED ||\n (result.status === RESULT_STATUS_COMPLETED && result.exitCode === 0);\n if (\n pauseRequestTriggered &&\n (pausePolicy !== 'protected' || protectedPauseEligible) &&\n (pausePolicy === 'protected' || !statusFileTriggered)\n ) {\n void settle({ status: RESULT_STATUS_PAUSE_REQUESTED });\n return;\n }\n if (!completedViaStatusFile) {\n void settle(result);\n return;\n }\n\n if (!statusFileTriggered) {\n statusFileTriggered = true;\n this.logger.info(\n ` ${GREEN}${STATUS_DONE}${RESET} ${stepName} status-file observed during process exit handling`,\n );\n }\n\n // The status file is the source of truth for work completion, even\n // when the hook write lands immediately before the process exits and\n // the watcher/poller does not observe it in time.\n switch (result.status) {\n case RESULT_STATUS_SPAWN_ERROR:\n case RESULT_STATUS_TIMED_OUT:\n // Preserve infrastructure failures unchanged.\n void settle(result);\n return;\n case RESULT_STATUS_SIGNALED:\n // Process was killed by a signal, or exited as the Stop hook fired.\n if (sigkillEscalated) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} required SIGKILL escalation (work completed via status-file)`,\n );\n }\n void settle(STATUS_FILE_COMPLETED_RESULT);\n return;\n case RESULT_STATUS_COMPLETED: {\n // Once the stop hook has marked the status file, it is the source\n // of truth for the workflow step. Some CLIs convert SIGTERM into a\n // plain non-zero exit code after their own cleanup; that should not\n // turn verified completion into a failed step.\n if (sigkillEscalated) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} ${stepName} required SIGKILL escalation (work completed via status-file, exit code ${result.exitCode})`,\n );\n }\n void settle(STATUS_FILE_COMPLETED_RESULT);\n return;\n }\n case RESULT_STATUS_STATUS_COMPLETED:\n // Should not happen (would mean double status-file trigger),\n // but pass through as-is.\n void settle(result);\n return;\n case RESULT_STATUS_STOP_REQUESTED:\n case RESULT_STATUS_PAUSE_REQUESTED:\n void settle(result);\n return;\n default: {\n const _exhaustive: never = result;\n void settle(_exhaustive);\n }\n }\n });\n });\n }\n\n private async raceStopRequest(\n executionPromise: Promise<StepExecutionResult>,\n stepName: string,\n stopRequestPath: string,\n pausePolicy: 'replay' | 'protected',\n ): Promise<StepExecutionResult> {\n return new Promise<StepExecutionResult>((resolveRace) => {\n let settled = false;\n let stopRequestTriggered = false;\n let pauseRequestTriggered = false;\n const pauseRequestPath = join(dirname(stopRequestPath), PAUSE_REQUEST_FILENAME);\n let forceKillTimer: NodeJS.Timeout | null = null;\n let pollTimer: NodeJS.Timeout | null = null;\n let watcher: { close(context: WorkflowRuntimeContext['ioContext']): Promise<void> } | null = null;\n\n const settle = async (result: StepExecutionResult) => {\n if (settled) return;\n settled = true;\n if (watcher) {\n await watcher\n .close(this.runtime.ioContext)\n .catch((error: unknown) => this.logger.warn(`Workflow watcher cleanup failed: ${String(error)}`));\n watcher = null;\n }\n if (pollTimer) {\n clearInterval(pollTimer);\n pollTimer = null;\n }\n if (forceKillTimer) {\n clearTimeout(forceKillTimer);\n forceKillTimer = null;\n }\n resolveRace(result);\n };\n\n const checkStopRequest = async () => {\n if ((await this.hasCurrentStopRequest(stopRequestPath)) && !settled && !stopRequestTriggered) {\n stopRequestTriggered = true;\n this.killActiveStep(TERMINATE_SIGNAL);\n forceKillTimer ??= setTimeout(() => {\n if (!settled) this.killActiveStep(TERMINATE_FORCE_KILL_SIGNAL);\n }, FORCE_KILL_GRACE_PERIOD_MS);\n return;\n }\n if (\n stopRequestTriggered ||\n pauseRequestTriggered ||\n !(await pathExists(this.runtime.fs, pauseRequestPath, this.runtime.ioContext))\n )\n return;\n if (\n (await this.readControlAction(pauseRequestPath)) !== 'pause' ||\n settled ||\n stopRequestTriggered ||\n pauseRequestTriggered\n )\n return;\n pauseRequestTriggered = true;\n if (pausePolicy === 'protected') return;\n this.killActiveStep(TERMINATE_SIGNAL);\n forceKillTimer ??= setTimeout(() => {\n if (!settled) this.killActiveStep(TERMINATE_FORCE_KILL_SIGNAL);\n }, FORCE_KILL_GRACE_PERIOD_MS);\n };\n\n try {\n void this.watchStatusFile(\n [{ path: stopRequestPath }],\n () => {\n void checkStopRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n },\n this.runtime.ioContext,\n )\n .then(async (result) => {\n const admitted = getOrThrow(result);\n if (settled) await admitted.close(this.runtime.ioContext);\n else watcher = admitted;\n })\n .catch((error: unknown) =>\n this.logger.warn(`Workflow stop-request watcher unavailable, polling instead: ${String(error)}`),\n );\n } catch (error) {\n const errorCode = (error as NodeJS.ErrnoException).code;\n if (errorCode !== 'ENOENT') {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} stop-request watcher setup failed for ${stepName}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n pollTimer = setInterval(() => {\n void checkStopRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n }, STOP_REQUEST_POLL_INTERVAL_MS);\n void checkStopRequest().catch((error: unknown) =>\n this.logger.warn(`Workflow control check failed: ${String(error)}`),\n );\n\n void executionPromise.then(async (result) => {\n const protectedPauseEligible =\n result.status === RESULT_STATUS_STATUS_COMPLETED ||\n (result.status === RESULT_STATUS_COMPLETED && result.exitCode === 0);\n if (stopRequestTriggered) void settle({ status: RESULT_STATUS_STOP_REQUESTED });\n else if (pauseRequestTriggered && (pausePolicy !== 'protected' || protectedPauseEligible)) {\n void settle({ status: RESULT_STATUS_PAUSE_REQUESTED });\n } else void settle(result);\n });\n });\n }\n\n private async hasCurrentStopRequest(path: string): Promise<boolean> {\n try {\n const value: unknown = JSON.parse(getOrThrow(await this.runtime.fs.readTextFile(path, this.runtime.ioContext)));\n if (!value || typeof value !== 'object') return false;\n const request = value as { runId?: unknown; schemaVersion?: unknown };\n if (request.schemaVersion !== 1 || typeof request.runId !== 'string') return false;\n const record = JSON.parse(\n getOrThrow(\n await this.runtime.fs.readTextFile(join(dirname(path), RUN_RECORD_FILENAME), this.runtime.ioContext),\n ),\n ) as {\n runId?: unknown;\n };\n return request.runId === record.runId;\n } catch {\n return false;\n }\n }\n\n private async readControlAction(path: string): Promise<'pause' | 'resume' | undefined> {\n try {\n const value: unknown = JSON.parse(getOrThrow(await this.runtime.fs.readTextFile(path, this.runtime.ioContext)));\n if (!value || typeof value !== 'object') return undefined;\n const request = value as { action?: unknown; runId?: unknown; schemaVersion?: unknown };\n if (\n (request.action !== 'pause' && request.action !== 'resume') ||\n request.schemaVersion !== 1 ||\n typeof request.runId !== 'string'\n ) {\n return undefined;\n }\n const record = JSON.parse(\n getOrThrow(\n await this.runtime.fs.readTextFile(join(dirname(path), RUN_RECORD_FILENAME), this.runtime.ioContext),\n ),\n ) as {\n runId?: unknown;\n };\n return request.runId === record.runId ? request.action : undefined;\n } catch {\n return undefined;\n }\n }\n\n private async markPaused(\n stopRequestPath: string | undefined,\n stepName: string,\n pausePolicy: 'replay' | 'protected',\n survivors: InteractiveProcessReport[] = [],\n resumeMode: 'replay-current' | 'continue-next' = pausePolicy === 'protected' ? 'continue-next' : 'replay-current',\n ): Promise<void> {\n if (!stopRequestPath) return;\n if (await this.hasCurrentStopRequest(stopRequestPath)) {\n throw new WorkflowInterruptedError(TERMINATE_SIGNAL, {\n cause: new Error(`Workflow stop requested before pause acknowledgement for \"${stepName}\"`),\n context: this.createInterruptContext(stepName, ''),\n });\n }\n if (survivors.length > 0) {\n throw new Error(\n `Cannot acknowledge pause for \"${stepName}\" because ${survivors.length} child process(es) survived termination: ${survivors\n .map((entry) => `${entry.pid} (${entry.command})`)\n .join(', ')}`,\n );\n }\n const recordPath = join(dirname(stopRequestPath), RUN_RECORD_FILENAME);\n try {\n const record = JSON.parse(\n getOrThrow(await this.runtime.fs.readTextFile(recordPath, this.runtime.ioContext)),\n ) as Record<string, unknown>;\n const cursor =\n record.executionCursor && typeof record.executionCursor === 'object'\n ? (record.executionCursor as Record<string, unknown>)\n : { executionGeneration: 1, phase: 'step', resumeMode: 'replay-current' };\n const request = (await pathExists(\n this.runtime.fs,\n join(dirname(stopRequestPath), PAUSE_REQUEST_FILENAME),\n this.runtime.ioContext,\n ))\n ? (JSON.parse(\n getOrThrow(\n await this.runtime.fs.readTextFile(\n join(dirname(stopRequestPath), PAUSE_REQUEST_FILENAME),\n this.runtime.ioContext,\n ),\n ),\n ) as Record<string, unknown>)\n : undefined;\n record.executionState = 'paused';\n record.executionCursor = {\n ...cursor,\n phase: 'step',\n requestId: typeof request?.requestId === 'string' ? request.requestId : cursor.requestId,\n revision: typeof cursor.revision === 'number' ? cursor.revision + 1 : 1,\n stepName,\n resumeMode,\n };\n await this.writeControlRecord(recordPath, record);\n } catch (error) {\n this.logger.warn(` ${YELLOW}${STATUS_WARN}${RESET} could not persist paused state: ${String(error)}`);\n throw error;\n }\n }\n\n private async waitForResume(stopRequestPath: string | undefined, stepName: string): Promise<void> {\n if (!stopRequestPath) return;\n const pauseRequestPath = join(dirname(stopRequestPath), PAUSE_REQUEST_FILENAME);\n const recordPath = join(dirname(stopRequestPath), RUN_RECORD_FILENAME);\n this.logger.info(` ${YELLOW}${STATUS_WAIT}${RESET} ${stepName} paused; waiting for resume`);\n while (true) {\n if (this.interruptedSignal) {\n throw new WorkflowInterruptedError(this.interruptedSignal, {\n cause: new Error(`Workflow interrupted while paused: ${stepName}`),\n context: this.createInterruptContext(stepName, ''),\n });\n }\n if (await this.hasCurrentStopRequest(stopRequestPath))\n throw new WorkflowInterruptedError(TERMINATE_SIGNAL, {\n cause: new Error(`Workflow stop requested while paused: ${stepName}`),\n context: this.createInterruptContext(stepName, ''),\n });\n if (\n (await pathExists(this.runtime.fs, pauseRequestPath, this.runtime.ioContext)) &&\n (await this.readControlAction(pauseRequestPath)) === 'resume'\n ) {\n const record = JSON.parse(\n getOrThrow(await this.runtime.fs.readTextFile(recordPath, this.runtime.ioContext)),\n ) as Record<string, unknown>;\n record.executionState = 'running';\n const cursor =\n record.executionCursor && typeof record.executionCursor === 'object'\n ? (record.executionCursor as Record<string, unknown>)\n : {};\n const request = JSON.parse(\n getOrThrow(await this.runtime.fs.readTextFile(pauseRequestPath, this.runtime.ioContext)),\n ) as Record<string, unknown>;\n const resumeMode = cursor.resumeMode === 'continue-next' ? 'continue-next' : 'replay-current';\n record.executionCursor = {\n ...cursor,\n executionGeneration:\n resumeMode === 'replay-current' && typeof cursor.executionGeneration === 'number'\n ? cursor.executionGeneration + 1\n : typeof cursor.executionGeneration === 'number'\n ? cursor.executionGeneration\n : 1,\n requestId: typeof request.requestId === 'string' ? request.requestId : cursor.requestId,\n revision: typeof cursor.revision === 'number' ? cursor.revision + 1 : 1,\n resumeMode,\n };\n await this.writeControlRecord(recordPath, record);\n return;\n }\n await new Promise((resolvePromise) => setTimeout(resolvePromise, STOP_REQUEST_POLL_INTERVAL_MS));\n }\n }\n\n private async writeControlRecord(recordPath: string, record: Record<string, unknown>): Promise<void> {\n await writeFileAtomic(this.runtime.fs, recordPath, `${JSON.stringify(record, null, 2)}\\n`, this.runtime.ioContext);\n }\n\n private captureTerminalState(): string | null {\n // Not ours to save or put back. The host that owns this terminal is the one\n // that knows what state it wants, and it is still using it while we run.\n if (!this.ownsTerminal) {\n return null;\n }\n\n return this.runtime.workflowHost.readTerminalState() ?? null;\n }\n\n private restoreTerminalState(terminalState: string | null): void {\n if (!this.ownsTerminal) return;\n try {\n this.runtime.workflowHost.restoreTerminalState(terminalState ?? undefined);\n } catch (error) {\n this.logger.warn(` ${YELLOW}${STATUS_WARN}${RESET} failed to restore terminal state: ${String(error)}`);\n }\n }\n\n /**\n * Remove the temp status file and the well-known marker file after step completion.\n */\n private async cleanupStatusFile(statusFilePath: string): Promise<void> {\n try {\n if (await pathExists(this.runtime.fs, statusFilePath, this.runtime.ioContext)) {\n getOrThrow(await this.runtime.fs.remove(statusFilePath, { force: true }, this.runtime.ioContext));\n }\n } catch (error) {\n this.logger.warn(\n ` ${YELLOW}${STATUS_WARN}${RESET} status-file cleanup failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n}\n","import { dirname, resolve } from 'node:path';\nimport type { Interface } from 'node:readline';\n/**\n * TriggerService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\n\nimport { WorkflowInterruptedError } from '../../models/WorkflowInterruptedError';\nimport type { AgentDecisionTrigger, MatrixEntry, Workflow } from '../../schemas/workflowEngine';\nimport type { StepRunnerService } from '../StepRunnerService';\nimport type { Logger, StepRunOptions } from '../workflowEngine/type';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\nconst CYAN = '\\x1b[36m';\nconst GREEN = '\\x1b[32m';\nconst RED = '\\x1b[31m';\nconst BLUE = '\\x1b[34m';\nconst INTERRUPT_SIGNAL: NodeJS.Signals = 'SIGINT';\nconst USER_PROMPT_EVENT = 'user_prompt';\nconst AGENT_DECISION_EVENT = 'agent_decision';\nconst SEPARATOR_WIDTH = 50;\nconst PROMPT_PREVIEW_MAX_CHARS = 80;\nconst DRY_RUN_PROMPT_TEXT = '(dry-run: no prompt collected)';\n\n/**\n * Handles trigger-specific setup before the workflow job graph starts.\n */\nexport class TriggerService {\n private activePrompt: Interface | null = null;\n private activePromptSignal: NodeJS.Signals | null = null;\n\n /**\n * Create a trigger handler bound to the step runner used for trigger steps\n * and the workflow logger used for user-facing output.\n */\n constructor(\n readonly runtime: WorkflowRuntimeContext,\n private stepRunner: StepRunnerService,\n private logger: Logger,\n ) {}\n\n /**\n * Check whether a path exists without throwing when it is absent.\n */\n private async pathExists(path: string): Promise<boolean> {\n try {\n getOrThrow(await this.runtime.fs.fileInfo(path, this.runtime.ioContext));\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Clear the cancellation state retained from a previous workflow run.\n */\n resetInterruption(): void {\n this.activePromptSignal = null;\n }\n\n /**\n * Abort an active interactive prompt so the workflow can unwind quickly.\n */\n abortActivePrompt(signal: NodeJS.Signals): void {\n this.activePromptSignal = signal;\n this.activePrompt?.close();\n }\n\n /**\n * Collect prompt context for workflows triggered by `user_prompt`.\n *\n * Uses `workflowEnv.CONTEXT_FILE` when present to read or persist the prompt,\n * and writes the final prompt to `workflowEnv.USER_PROMPT` for downstream\n * job execution.\n */\n async handleUserPrompt(\n workflow: Workflow,\n cliPrompt: string | null,\n workflowEnv: Record<string, string>,\n workflowDir: string,\n dryRun: boolean,\n ): Promise<boolean> {\n if (!workflow.on || !(USER_PROMPT_EVENT in workflow.on)) return true;\n\n this.logger.info(`\\n ${BLUE}${BOLD}trigger${RESET} ${BOLD}user_prompt${RESET}`);\n this.logger.info(` ${'─'.repeat(SEPARATOR_WIDTH)}`);\n\n let userInput = cliPrompt;\n\n // If context file already exists, read from it instead of prompting\n const contextFile = workflowEnv.CONTEXT_FILE;\n if (!userInput && contextFile) {\n const contextPath = resolve(workflowDir, contextFile);\n if (await this.pathExists(contextPath)) {\n userInput = getOrThrow(await this.runtime.fs.readTextFile(contextPath, this.runtime.ioContext)).trim();\n if (userInput) {\n this.logger.info(` ${GREEN}found${RESET} Existing context.md -> ${contextFile}`);\n }\n }\n }\n\n if (!userInput) {\n if (dryRun) {\n this.logger.info(` ${CYAN}dry ${RESET} Would prompt user for input`);\n userInput = DRY_RUN_PROMPT_TEXT;\n } else {\n this.logger.info(` ${CYAN}input${RESET} Enter your prompt (press Enter twice to finish):\\n`);\n const lines: string[] = [];\n const rl = this.runtime.workflowHost.createPrompt();\n const promptResult = new Promise<string>((res, rej) => {\n let settled = false;\n const finish = (callback: () => void) => {\n if (settled) {\n return;\n }\n settled = true;\n this.activePrompt = null;\n callback();\n };\n\n rl.on('line', (line) => {\n if (line === '' && lines.length > 0 && lines[lines.length - 1] === '') {\n rl.close();\n } else {\n lines.push(line);\n }\n });\n\n rl.on('SIGINT', () => {\n this.activePromptSignal = INTERRUPT_SIGNAL;\n rl.close();\n });\n\n rl.on('close', () =>\n finish(() => {\n const signal = this.activePromptSignal;\n this.activePromptSignal = null;\n if (signal) {\n rej(new WorkflowInterruptedError(signal));\n return;\n }\n\n if (lines.length > 0 && lines[lines.length - 1] === '') {\n lines.pop();\n }\n res(lines.join('\\n'));\n }),\n );\n });\n this.activePrompt = rl;\n if (this.activePromptSignal) {\n rl.close();\n }\n userInput = await promptResult;\n }\n }\n\n if (!userInput) {\n this.logger.error(` ${RED}fail${RESET} No prompt provided. Aborting.`);\n return false;\n }\n\n // Write prompt to context file\n if (contextFile) {\n const contextPath = resolve(workflowDir, contextFile);\n const contextDir = dirname(contextPath);\n getOrThrow(await this.runtime.fs.createDir(contextDir, { recursive: true }, this.runtime.ioContext));\n getOrThrow(await this.runtime.fs.writeFile(contextPath, userInput, this.runtime.ioContext));\n this.logger.info(` ${GREEN}saved${RESET} ${userInput.split('\\n').length} line(s) -> ${contextFile}`);\n }\n\n workflowEnv.USER_PROMPT = userInput;\n\n this.logger.info(\n ` ${DIM}prompt${RESET} ${userInput.split('\\n')[0].slice(0, PROMPT_PREVIEW_MAX_CHARS)}${userInput.includes('\\n') ? '...' : ''}`,\n );\n return true;\n }\n\n /**\n * Execute `agent_decision` steps that decide whether the workflow should proceed.\n *\n * Reads and writes workflow context via `workflowEnv.CONTEXT_FILE`, and\n * copies CLI prompt content into `workflowEnv.HEARTBEAT_PROMPT` when supplied.\n */\n async handleAgentDecision(\n workflow: Workflow,\n workflowEnv: Record<string, string>,\n inputs: Map<string, string>,\n secrets: Map<string, string>,\n options: StepRunOptions,\n prompt: string | null,\n ): Promise<boolean> {\n const trigger = workflow.on?.[AGENT_DECISION_EVENT] as AgentDecisionTrigger | undefined;\n if (!trigger?.steps) return true;\n\n this.logger.info(`\\n ${BLUE}${BOLD}trigger${RESET} ${BOLD}agent_decision${RESET}`);\n this.logger.info(` ${'─'.repeat(SEPARATOR_WIDTH)}`);\n\n if (prompt) {\n workflowEnv.HEARTBEAT_PROMPT = prompt;\n this.logger.info(\n ` ${DIM}prompt${RESET} ${prompt.split('\\n')[0].slice(0, PROMPT_PREVIEW_MAX_CHARS)}${prompt.includes('\\n') ? '...' : ''}`,\n );\n }\n\n // Ensure context dir exists\n const contextFile = workflowEnv.CONTEXT_FILE;\n if (contextFile) {\n const contextDir = dirname(resolve(options.workflowDir, contextFile));\n getOrThrow(await this.runtime.fs.createDir(contextDir, { recursive: true }, this.runtime.ioContext));\n }\n\n const stepContext = {\n inputs,\n matrix: {} as MatrixEntry,\n secrets,\n env: workflowEnv,\n };\n\n for (const [index, step] of trigger.steps.entries()) {\n const stepName = step.name ?? `step ${index + 1}`;\n await options.onStepStarted?.(stepName, index, trigger.steps.length);\n const ok = await this.stepRunner.runStep(step, stepContext, options);\n if (!ok) {\n this.logger.error(`\\n ${RED}Agent decision aborted workflow${RESET}`);\n return false;\n }\n }\n\n // Verify context file has content\n if (contextFile && !options.dryRun) {\n const contextPath = resolve(options.workflowDir, contextFile);\n if (!(await this.pathExists(contextPath))) {\n this.logger.error(` ${RED}fail${RESET} Context file not created: ${contextFile}`);\n return false;\n }\n const content = getOrThrow(await this.runtime.fs.readTextFile(contextPath, this.runtime.ioContext)).trim();\n if (!content) {\n this.logger.error(` ${RED}fail${RESET} Context file is empty: ${contextFile}`);\n return false;\n }\n this.logger.info(` ${GREEN}ready${RESET} context has ${content.split('\\n').length} line(s)`);\n }\n\n return true;\n }\n}\n","import { basename, resolve } from 'node:path';\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\n/**\n * WorkflowRepairService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n * - Document complex logic with comments\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { WorkflowRepairRecordSchema } from '../../schemas/workflowEngine';\nimport type {\n WorkflowRepairJobStatus,\n WorkflowRepairRecord,\n WorkflowRepairRoutingFallback,\n} from '../../schemas/workflowEngine';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nconst ISSUES_DIRNAME = 'issues';\nconst ISSUE_FILENAME = 'issue.md';\nconst REPAIR_FILENAME = 'repair.json';\nconst MINIMUM_REPAIR_ID_WIDTH = 3;\nconst DEVELOPMENT_JOB_NAME = 'development';\nconst FALLBACK_RESTART_JOB_INDEX = 1;\n\nexport interface CreateWorkflowRepairInput {\n emittingJob: string;\n fixContent: string;\n fixCycle: number;\n invalidTarget?: string;\n jobOrder: string[];\n restartFrom?: string;\n runDir: string;\n}\n\nexport interface ResolveRepairRouteResult {\n rejected: boolean;\n restartFrom: string;\n routingFallback?: WorkflowRepairRoutingFallback;\n scopeJobs: string[];\n}\n\nexport class WorkflowRepairService {\n constructor(readonly runtime: WorkflowRuntimeContext) {}\n\n async createRepair(input: CreateWorkflowRepairInput): Promise<WorkflowRepairRecord> {\n const issueDir = await this.allocateIssueDirectory(input.runDir);\n const repairId = basename(issueDir);\n if (!repairId) {\n throw new Error(`Unable to resolve repair ID from issue directory: ${issueDir}`);\n }\n\n const issuePath = resolve(issueDir, ISSUE_FILENAME);\n const route = this.resolveRoute(input);\n const now = new Date().toISOString();\n const repair: WorkflowRepairRecord = {\n createdAt: now,\n fixCycle: input.fixCycle,\n issueFile: `${ISSUES_DIRNAME}/${repairId}/${ISSUE_FILENAME}`,\n jobs: route.scopeJobs.map((jobName) => ({ attempts: [], jobName, status: 'pending' })),\n rejectedAt: route.rejected ? now : undefined,\n repairId,\n restartFrom: route.restartFrom,\n routingFallback: route.routingFallback,\n schemaVersion: 1,\n scopeJobs: route.scopeJobs,\n status: route.rejected ? 'rejected' : 'pending',\n updatedAt: now,\n verificationJob: input.emittingJob,\n };\n\n try {\n getOrThrow(await this.runtime.fs.writeFile(issuePath, input.fixContent, this.runtime.ioContext));\n await this.writeRepair(input.runDir, repair);\n return repair;\n } catch (error) {\n getOrThrow(await this.runtime.fs.remove(issueDir, { force: true, recursive: true }, this.runtime.ioContext));\n throw error;\n }\n }\n\n async readRepair(runDir: string, repairId: string): Promise<WorkflowRepairRecord> {\n const content = getOrThrow(\n await this.runtime.fs.readTextFile(this.repairPath(runDir, repairId), this.runtime.ioContext),\n );\n return WorkflowRepairRecordSchema.parse(JSON.parse(content));\n }\n\n async activateRepair(runDir: string, repair: WorkflowRepairRecord): Promise<WorkflowRepairRecord> {\n if (repair.status !== 'pending') {\n return repair;\n }\n return await this.writeStatus(runDir, repair, 'active');\n }\n\n async resolveRepair(runDir: string, repair: WorkflowRepairRecord): Promise<WorkflowRepairRecord> {\n const now = new Date().toISOString();\n return await this.writeRepair(runDir, {\n ...repair,\n resolvedAt: now,\n status: 'resolved',\n updatedAt: now,\n });\n }\n\n async supersedeRepair(\n runDir: string,\n repair: WorkflowRepairRecord,\n supersededBy: string,\n ): Promise<WorkflowRepairRecord> {\n const now = new Date().toISOString();\n return await this.writeRepair(runDir, {\n ...repair,\n status: 'superseded',\n supersededAt: now,\n supersededBy,\n updatedAt: now,\n });\n }\n\n async startJob(\n runDir: string,\n repair: WorkflowRepairRecord,\n jobName: string,\n workflowRunId?: string,\n ): Promise<WorkflowRepairRecord> {\n const jobIndex = repair.jobs.findIndex((job) => job.jobName === jobName);\n if (jobIndex < 0) {\n throw new Error(`Job \"${jobName}\" is outside repair ${repair.repairId} scope`);\n }\n\n const now = new Date().toISOString();\n const jobs = repair.jobs.map((job, index) => {\n if (index !== jobIndex) {\n return job;\n }\n return {\n ...job,\n attempts: [\n ...job.attempts,\n {\n attempt: job.attempts.length + 1,\n startedAt: now,\n status: 'running' as const,\n workflowRunId,\n },\n ],\n status: 'running' as const,\n };\n });\n\n return await this.writeRepair(runDir, { ...repair, jobs, status: 'active', updatedAt: now });\n }\n\n async finishJob(\n runDir: string,\n repair: WorkflowRepairRecord,\n jobName: string,\n status: Exclude<WorkflowRepairJobStatus, 'pending' | 'running' | 'skipped'>,\n ): Promise<WorkflowRepairRecord> {\n const now = new Date().toISOString();\n const jobs = repair.jobs.map((job) => {\n if (job.jobName !== jobName) {\n return job;\n }\n const attempts = [...job.attempts];\n const latest = attempts.at(-1);\n if (!latest) {\n throw new Error(`Repair ${repair.repairId} job \"${jobName}\" has no running attempt`);\n }\n attempts[attempts.length - 1] = { ...latest, finishedAt: now, status };\n return { ...job, attempts, status };\n });\n\n return await this.writeRepair(runDir, { ...repair, jobs, updatedAt: now });\n }\n\n /**\n * Mark scope jobs the run jumped over as skipped.\n *\n * A forward jump inside an active repair leaves jobs that never ran and never\n * will for this repair. They carry no attempt: an attempt records an\n * execution, and none happened. Recording the decision keeps recovery honest —\n * `resolveRecoveryStart` would otherwise resume at a job the repair\n * deliberately passed by.\n */\n async skipJobs(runDir: string, repair: WorkflowRepairRecord, jobNames: string[]): Promise<WorkflowRepairRecord> {\n const skipped = new Set(jobNames);\n for (const jobName of skipped) {\n if (!repair.jobs.some((job) => job.jobName === jobName)) {\n throw new Error(`Job \"${jobName}\" is outside repair ${repair.repairId} scope`);\n }\n }\n\n const now = new Date().toISOString();\n const jobs = repair.jobs.map((job) => (skipped.has(job.jobName) ? { ...job, status: 'skipped' as const } : job));\n\n return await this.writeRepair(runDir, { ...repair, jobs, updatedAt: now });\n }\n\n resolveRecoveryStart(repair: WorkflowRepairRecord): string {\n if (repair.status === 'pending') {\n return repair.restartFrom;\n }\n\n for (const jobName of repair.scopeJobs) {\n const job = repair.jobs.find((candidate) => candidate.jobName === jobName);\n // A skipped job is as done as a completed one: the repair chose to pass\n // over it, so resuming there would undo that decision.\n if (!job || (job.status !== 'completed' && job.status !== 'skipped')) {\n return jobName;\n }\n }\n\n return repair.verificationJob;\n }\n\n private resolveRoute(input: CreateWorkflowRepairInput): ResolveRepairRouteResult {\n if (input.jobOrder.length === 0) {\n throw new Error('Cannot create a workflow repair without jobs');\n }\n\n const emittingIndex = input.jobOrder.indexOf(input.emittingJob);\n if (emittingIndex < 0) {\n throw new Error(`Repair emitter \"${input.emittingJob}\" is not in the workflow job order`);\n }\n\n let restartFrom = input.restartFrom;\n let routingFallback: WorkflowRepairRoutingFallback | undefined;\n if (!restartFrom) {\n const fallbackIndex = this.fallbackRestartIndex(input.jobOrder);\n restartFrom = input.jobOrder[fallbackIndex];\n routingFallback = {\n reason: input.invalidTarget ? 'unknown' : 'missing',\n requestedTarget: input.invalidTarget,\n resolvedTarget: restartFrom,\n };\n }\n\n const restartIndex = input.jobOrder.indexOf(restartFrom);\n if (restartIndex < 0) {\n throw new Error(`Resolved repair target \"${restartFrom}\" is not in the workflow job order`);\n }\n\n const rejected = Boolean(input.invalidTarget) || restartIndex > emittingIndex;\n return {\n rejected,\n restartFrom,\n routingFallback,\n scopeJobs: rejected ? [] : input.jobOrder.slice(restartIndex, emittingIndex + 1),\n };\n }\n\n private fallbackRestartIndex(jobOrder: string[]): number {\n const developmentIndex = jobOrder.indexOf(DEVELOPMENT_JOB_NAME);\n if (developmentIndex >= 0) {\n return developmentIndex;\n }\n return Math.min(FALLBACK_RESTART_JOB_INDEX, jobOrder.length - 1);\n }\n\n private async allocateIssueDirectory(runDir: string): Promise<string> {\n const issuesDir = resolve(runDir, ISSUES_DIRNAME);\n getOrThrow(await this.runtime.fs.createDir(issuesDir, { recursive: true }, this.runtime.ioContext));\n const entries = getOrThrow(await this.runtime.fs.listDir(issuesDir, this.runtime.ioContext));\n const highest = entries.reduce((max, entry) => {\n if (entry.kind !== 'directory' || !/^\\d+$/.test(entry.name)) {\n return max;\n }\n return Math.max(max, Number(entry.name));\n }, 0);\n\n for (let next = highest + 1; ; next++) {\n const repairId = String(next).padStart(MINIMUM_REPAIR_ID_WIDTH, '0');\n const issueDir = resolve(issuesDir, repairId);\n try {\n getOrThrow(await this.runtime.fs.createDir(issueDir, undefined, this.runtime.ioContext));\n return issueDir;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error;\n }\n }\n }\n }\n\n private async writeStatus(\n runDir: string,\n repair: WorkflowRepairRecord,\n status: WorkflowRepairRecord['status'],\n ): Promise<WorkflowRepairRecord> {\n const updated = { ...repair, status, updatedAt: new Date().toISOString() };\n return await this.writeRepair(runDir, updated);\n }\n\n private async writeRepair(runDir: string, repair: WorkflowRepairRecord): Promise<WorkflowRepairRecord> {\n const validated = WorkflowRepairRecordSchema.parse(repair);\n const targetPath = this.repairPath(runDir, repair.repairId);\n const tempPath = `${targetPath}.${this.runtime.workflowHost.processId}.${Date.now()}.tmp`;\n try {\n getOrThrow(\n await this.runtime.fs.writeFile(tempPath, `${JSON.stringify(validated, null, 2)}\\n`, this.runtime.ioContext),\n );\n getOrThrow(await this.runtime.fs.renameFile(tempPath, targetPath, this.runtime.ioContext));\n return validated;\n } catch (error) {\n try {\n getOrThrow(await this.runtime.fs.remove(tempPath, undefined, this.runtime.ioContext));\n } catch (cleanupError) {\n if ((cleanupError as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw cleanupError;\n }\n }\n throw error;\n }\n }\n\n private repairPath(runDir: string, repairId: string): string {\n return resolve(runDir, ISSUES_DIRNAME, repairId, REPAIR_FILENAME);\n }\n}\n","/**\n * WorktreeService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { basename, dirname, resolve } from 'node:path';\n\nimport { getOrThrow, pathExists, removePath } from '@agimon-ai/po-core/platform';\n\nimport type { MatrixEntry, WorktreeHook } from '../../schemas/workflowEngine';\nimport type { StepRunnerService } from '../StepRunnerService';\nimport type { Logger } from '../workflowEngine/type';\nimport { workflowShellOutput } from '../workflowRuntime';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\n\nconst RESET = '\\x1b[0m';\nconst DIM = '\\x1b[2m';\nconst CYAN = '\\x1b[36m';\nconst YELLOW = '\\x1b[33m';\n\nexport class WorktreeService {\n constructor(\n private runtime: WorkflowRuntimeContext,\n private stepRunner: StepRunnerService,\n private logger: Logger,\n ) {}\n\n getWorktreeBranchName(workflowName: string): string {\n const safeName = workflowName\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-|-$/g, '');\n\n return `worktree/${safeName}`;\n }\n\n async createWorktree(repoRoot: string, workflowName: string): Promise<string> {\n repoRoot = resolve(this.runtime.cwd, repoRoot);\n const branchName = this.getWorktreeBranchName(workflowName);\n const safeName = branchName.slice('worktree/'.length);\n const parentDir = dirname(repoRoot);\n const folderName = basename(repoRoot);\n const worktreeBase = resolve(parentDir, `${folderName}-worktree`);\n const worktreePath = resolve(worktreeBase, safeName);\n\n if (!(await pathExists(this.runtime.fs, worktreeBase, this.runtime.ioContext))) {\n getOrThrow(await this.runtime.fs.createDir(worktreeBase, { recursive: true }, this.runtime.ioContext));\n }\n\n // Remove stale worktree if it exists\n if (await pathExists(this.runtime.fs, worktreePath, this.runtime.ioContext)) {\n this.logger.info(` ${DIM}clean${RESET} Removing stale worktree at ${worktreePath}`);\n await this.cleanupWorktreePath(repoRoot, worktreePath);\n }\n\n // Delete existing branch if it exists (from a previous run)\n try {\n await workflowShellOutput(this.runtime, `git branch -D \"${branchName}\"`, { cwd: repoRoot });\n } catch {\n // Branch doesn't exist, that's fine\n }\n\n this.logger.info(` ${CYAN}create${RESET} Worktree at ${worktreePath} (branch: ${branchName})`);\n await workflowShellOutput(this.runtime, `git worktree add -b \"${branchName}\" \"${worktreePath}\" HEAD`, {\n cwd: repoRoot,\n });\n\n return worktreePath;\n }\n\n async removeWorktree(repoRoot: string, worktreePath: string): Promise<void> {\n repoRoot = resolve(this.runtime.cwd, repoRoot);\n worktreePath = resolve(this.runtime.cwd, worktreePath);\n if (!(await pathExists(this.runtime.fs, worktreePath, this.runtime.ioContext))) return;\n\n this.logger.info(` ${DIM}remove${RESET} Worktree at ${worktreePath}`);\n try {\n await this.cleanupWorktreePath(repoRoot, worktreePath);\n } catch {\n this.logger.warn(` ${YELLOW}warn${RESET} Failed to remove worktree (may need manual cleanup)`);\n }\n }\n\n private async cleanupWorktreePath(repoRoot: string, worktreePath: string): Promise<void> {\n if (await this.isRegisteredWorktree(repoRoot, worktreePath)) {\n await workflowShellOutput(this.runtime, `git worktree remove --force \"${worktreePath}\"`, { cwd: repoRoot });\n return;\n }\n\n await removePath(this.runtime.fs, worktreePath, this.runtime.ioContext);\n }\n\n private async isRegisteredWorktree(repoRoot: string, worktreePath: string): Promise<boolean> {\n try {\n const output = await workflowShellOutput(this.runtime, 'git worktree list --porcelain', { cwd: repoRoot });\n\n return output\n .split('\\n')\n .some(\n (line) =>\n line.startsWith('worktree ') && resolve(this.runtime.cwd, line.slice('worktree '.length)) === worktreePath,\n );\n } catch {\n return false;\n }\n }\n\n async runHook(\n hook: WorktreeHook,\n cwd: string,\n baseEnv: Record<string, string>,\n inputs: Map<string, string>,\n secrets: Map<string, string>,\n options: {\n cliAgent?: string;\n runner?: string;\n dryRun: boolean;\n continueOnError: boolean;\n stopRequestPath?: string;\n onStepStarted?: (\n stepName: string,\n index: number,\n total: number,\n matrixIndex?: number,\n attempt?: number,\n ) => Promise<void> | void;\n onExecutionStateChange?: (state: 'paused' | 'resumed', stepName: string) => Promise<void> | void;\n },\n ): Promise<boolean> {\n const stepContext = {\n inputs,\n matrix: {} as MatrixEntry,\n secrets,\n env: baseEnv,\n };\n\n for (const [index, step] of hook.steps.entries()) {\n const stepName = step.name ?? `step ${index + 1}`;\n await options.onStepStarted?.(stepName, index, hook.steps.length);\n const ok = await this.stepRunner.runStep(step, stepContext, { ...options, workflowDir: cwd });\n if (!ok) return false;\n }\n return true;\n }\n}\n","import { createHash } from 'node:crypto';\nimport { basename, dirname, extname, relative, resolve } from 'node:path';\n\nimport { getOrThrow } from '@agimon-ai/po-core/platform';\nimport { dump as serializeYaml } from 'js-yaml';\n/**\n * RunWorkflowService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Orchestrator pattern coordinating sub-services\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { WorkflowCapacityError } from '../../models/WorkflowCapacityError';\nimport { type WorkflowInterruptContext, WorkflowInterruptedError } from '../../models/WorkflowInterruptedError';\nimport type {\n MatrixEntry,\n StepExecutionRef,\n Workflow,\n WorkflowExecutionCursor,\n WorkflowLauncherMetadata,\n WorkflowLauncherType,\n WorkflowOutcome,\n WorkflowRepairRecord,\n WorkflowRunHandle,\n WorkflowRunRecord,\n} from '../../schemas/workflowEngine';\nimport { BackgroundServiceManager } from '../BackgroundServiceManager';\nimport { JobRunnerService } from '../JobRunnerService';\nimport { RunDirectoryService } from '../RunDirectoryService';\nimport { StepRunnerService } from '../StepRunnerService';\nimport { TriggerService } from '../TriggerService';\nimport { compatibleCommands } from '../WorkflowCatalogService';\nimport type { Logger, StepExecutor } from '../workflowEngine/type';\nimport { WorkflowParserService } from '../WorkflowParserService';\nimport { PHASE_JOB_POST, PHASE_JOB_PRE, WorkflowProgressService } from '../WorkflowProgressService';\nimport { WorkflowRegistryService } from '../WorkflowRegistryService';\nimport { WorkflowRepairService } from '../WorkflowRepairService';\nimport { workflowShellOutput } from '../workflowRuntime';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport { escapeShellArg, substituteShellPlaceholder } from '../workflowShell';\nimport { createWorkflowLogger, runWorkflowSpan } from '../workflowTelemetry';\nimport { WorktreeService } from '../WorktreeService';\n\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\nconst GREEN = '\\x1b[32m';\nconst YELLOW = '\\x1b[33m';\nconst RED = '\\x1b[31m';\nconst BLUE = '\\x1b[34m';\nconst INTERRUPT_SIGNAL: NodeJS.Signals = 'SIGINT';\nconst TERMINATE_SIGNAL: NodeJS.Signals = 'SIGTERM';\n// A run hosted in a terminal pane is hung up, not interrupted, when that pane\n// goes away. Without a handler Node takes the default action and dies on the\n// spot, so the active step's descendants are never reaped and survive as\n// orphans holding the worktree open.\nconst HANGUP_SIGNAL: NodeJS.Signals = 'SIGHUP';\nconst INTERRUPTED_EXIT_CODE = 130;\nconst WORKFLOW_FAILED_EXIT_CODE = 1;\nconst WORKFLOW_SKIPPED_EXIT_CODE = 2;\nconst WORKFLOW_PHASE = 'workflow_execution';\nconst GIT_DIRNAME = '.git';\nconst FIX_FILENAME = 'fix.md';\nconst FIX_FRONTMATTER_DELIMITER = '---';\nconst FIX_RESTART_FROM_KEY = 'restart-from';\nconst FIX_STATUS_KEY = 'status';\nconst FIX_TERMINAL_TARGET = 'stop';\nconst PROCEED_FILENAME = 'proceed.md';\nconst PROCEED_TO_KEY = 'proceed-to';\nconst DRY_RUN_ARTIFACT_PREFIX = 'workflow-mcp-dry-run-';\nconst DRY_RUN_ARTIFACT_FILENAME = 'assembled-workflow.yml';\nconst TRIGGER_USER_PROMPT = 'user_prompt';\nconst TRIGGER_AGENT_DECISION = 'agent_decision';\nconst TRIGGER_WORKFLOW_DISPATCH = 'workflow_dispatch';\nconst WORKTREE_DRY_RUN_MESSAGE = 'Would create at';\nconst SERVICE_STARTUP_DELAY_MS = 2_000;\nconst DEFAULT_WORKSPACE = 'default';\nconst WORKFLOW_SUCCESS_TEXT = 'Workflow completed successfully';\nconst WORKFLOW_SKIPPED_TEXT = 'Workflow skipped: agent decided nothing to do';\nconst WORKFLOW_ABORTED_PROMPT_TEXT = 'Workflow aborted: no prompt provided';\nconst WORKFLOW_ABORTED_PRECONDITIONS_TEXT = 'Workflow aborted: pre-conditions failed';\nconst WORKFLOW_POST_FAILED_TEXT = 'Workflow post-cleanup failed';\nconst WORKFLOW_ABORTED_WORKTREE_BEFORE_CREATE_TEXT = 'Workflow aborted: worktree beforeCreate hook failed';\nconst WORKFLOW_ABORTED_WORKTREE_AFTER_CREATE_TEXT = 'Workflow aborted: worktree afterCreate hook failed';\nconst WORKFLOW_FAILED_AT_JOB_PREFIX = 'Workflow failed at job';\nconst COMPLETED_STAGE = 'completed';\nconst ERROR_STAGE = 'error';\nconst OUTCOME_SUCCESS: WorkflowOutcome = 'success';\nconst OUTCOME_SKIPPED: WorkflowOutcome = 'skipped';\nconst OUTCOME_FAILED: WorkflowOutcome = 'failed';\nconst OUTCOME_INTERRUPTED: WorkflowOutcome = 'interrupted';\n\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_MAX_FIX_CYCLES = 3;\nconst MAX_OUTPUT_LINES = 5_000;\nconst LAUNCH_COMMAND_PLACEHOLDER = '{command}';\nconst LAUNCH_NAME_PLACEHOLDER = '{name}';\nconst CMUX_SURFACE_ID_ENV = 'CMUX_SURFACE_ID';\nconst CMUX_WORKSPACE_ID_ENV = 'CMUX_WORKSPACE_ID';\nconst TMUX_PANE_ENV = 'TMUX_PANE';\nconst WORKFLOW_LAUNCHER_ENV = 'WORKFLOW_LAUNCHER';\nconst WORKFLOW_LAUNCHER_TYPE_ENV = 'WORKFLOW_LAUNCHER_TYPE';\n/** Set by `host-run`, naming where this run's own terminal is answering. */\nconst WORKFLOW_TERMINAL_SOCKET_ENV = 'WORKFLOW_TERMINAL_SOCKET';\nconst NATIVE_LAUNCHER_TYPE = 'native';\nconst WORKFLOW_TMUX_SESSION_NAME_ENV = 'WORKFLOW_TMUX_SESSION_NAME';\nconst WORKFLOW_LAUNCHER_ORIGIN_PANE_ID_ENV = 'WORKFLOW_LAUNCHER_ORIGIN_PANE_ID';\nconst WORKFLOW_LAUNCHER_ORIGIN_SESSION_ID_ENV = 'WORKFLOW_LAUNCHER_ORIGIN_SESSION_ID';\nconst WORKFLOW_LAUNCHER_ORIGIN_SURFACE_ID_ENV = 'WORKFLOW_LAUNCHER_ORIGIN_SURFACE_ID';\nconst WORKFLOW_LAUNCHER_ORIGIN_WORKSPACE_ID_ENV = 'WORKFLOW_LAUNCHER_ORIGIN_WORKSPACE_ID';\nconst WORKFLOW_STATUS_FILE_ENV = 'WORKFLOW_STATUS_FILE';\nconst WORKFLOW_FIX_LOOP_DISABLED_ENV = 'WORKFLOW_FIX_LOOP_DISABLED';\nconst WORKFLOW_PHASE_ENV = 'WORKFLOW_PHASE';\n/**\n * Progress-log names for the two phases that are not jobs.\n *\n * A reader renders these beside real jobs the way GitHub Actions shows \"Set up\n * job\" and \"Post job cleanup\" around the jobs between them. Named for what the\n * console already prints for these phases, so the log and the terminal agree.\n *\n * A workflow whose own job is literally named `pre` would merge into this entry.\n * That is cosmetic rather than corrupting, and is not worth an escaping scheme.\n */\n// Taken from the progress module rather than restated here: these names are the\n// log's format, and a reader classifying phases has to agree with this writer.\nconst PRE_PHASE_JOB = PHASE_JOB_PRE;\nconst POST_PHASE_JOB = PHASE_JOB_POST;\nconst WORKFLOW_EXIT_CODE_ENV = 'WORKFLOW_EXIT_CODE';\nconst WORKFLOW_OUTCOME_ENV = 'WORKFLOW_OUTCOME';\nconst WORKFLOW_FAILED_JOB_ENV = 'WORKFLOW_FAILED_JOB';\nconst WORKFLOW_ACTIVE_REPAIR_ID_ENV = 'WORKFLOW_ACTIVE_REPAIR_ID';\nconst WORKFLOW_ACTIVE_REPAIR_DIR_ENV = 'WORKFLOW_ACTIVE_REPAIR_DIR';\nconst WORKFLOW_ACTIVE_REPAIR_FILE_ENV = 'WORKFLOW_ACTIVE_REPAIR_FILE';\nconst WORKFLOW_ACTIVE_ISSUE_FILE_ENV = 'WORKFLOW_ACTIVE_ISSUE_FILE';\nconst REPAIR_TRIAGE_JOB_NAME = 'repair-triage';\n\nfunction parsePositiveIntegerEnv(value: string | undefined, defaultValue: number): number {\n const parsed = Number(value);\n return Number.isInteger(parsed) && parsed > 0 ? parsed : defaultValue;\n}\n\nconst STEP_CLI_DIRECTORY = 'bin';\nconst STEP_CLI_NAME = 'workflow-mcp';\n\nfunction envFlagEnabled(value: string | undefined): boolean {\n return ['1', 'true', 'yes', 'on'].includes(\n String(value ?? '')\n .trim()\n .toLowerCase(),\n );\n}\n\nexport interface RunWorkflowInput {\n cliAgent?: string;\n runner?: string;\n /** Command templated interactiveRun steps run through; defaults to each step's first. */\n command?: string;\n /** Choice for steps that do not pin one; defaults to the choice named `default`. */\n choice?: string;\n workflowPath: string;\n job?: string;\n inputs?: Record<string, string>;\n env?: Record<string, string>;\n secretFile?: string;\n dryRun?: boolean;\n continueOnError?: boolean;\n keepWorktree?: boolean;\n launcher?: WorkflowLauncherType;\n prompt?: string;\n name?: string;\n workspace?: string;\n skipLaunch?: boolean;\n statusFile?: string;\n /**\n * The run is registered and its directory is ready: the earliest point a\n * host can follow it, identified exactly rather than guessed from the registry.\n */\n onRegistered?: (run: WorkflowRunRegistration) => void;\n /** The engine reloaded its definition for the next job or repair cycle. */\n onConfigChanged?: (run: WorkflowRunRegistration) => void;\n recovery?: {\n activeRepairId?: string;\n /** Omitted only for a read-only recovery dry run. */\n claimId?: string;\n originalJob?: string;\n originalRepoPath?: string;\n runKey: string;\n startJob?: string;\n worktreeBranch?: string;\n worktreePath?: string;\n };\n}\n\nexport interface RunWorkflowResult {\n exitCode: number;\n output: string;\n}\n\n/** Where a registered run lives, as `RunWorkflowInput.onRegistered` reports it. */\nexport interface WorkflowRunRegistration {\n runKey: string;\n runId: string;\n workspace: string;\n runDir: string;\n displayName: string;\n /** The resolved parsed definition used by this execution, never a later disk read. */\n workflow: Workflow;\n revision: string;\n}\n\n/**\n * Optional collaborators for `RunWorkflowService`.\n *\n * Supplying these allows tests and higher-level callers to replace concrete\n * orchestration services without changing the public command API.\n */\nexport interface RunWorkflowDependencies {\n runtime: WorkflowRuntimeContext;\n /**\n * Stdio handed to `launch-command` delegation.\n *\n * The CLI owns its terminal, so it inherits and lets the launcher paint on\n * it. An embedded host does not: inside the Pi extension stdout is the TUI's\n * screen and stdin is its keyboard, and inside the stdio MCP server stdout is\n * the JSON-RPC stream. Those hosts pass `pipe` so the child gets neither.\n */\n launchStdio?: 'inherit' | 'pipe';\n /**\n * Launcher identity to persist instead of inferring one from this process.\n *\n * An embedded host can itself run inside cmux or tmux without that host\n * terminal being the workflow's launcher. It supplies `native` so readers do\n * not later scrape or foreground the host application's own terminal.\n */\n launcherMetadata?: WorkflowLauncherMetadata;\n /**\n * Whether this process owns the terminal its steps would write to.\n *\n * The same distinction `launchStdio` draws, applied to the steps themselves.\n * `launchStdio` only covers the `launch-command` child; a step spawned by\n * `StepRunnerService` still reaches the terminal, and an interactive one also\n * runs `stty` over it. An embedded host passes false to keep both away.\n */\n ownsTerminal?: boolean;\n /**\n * Host execution for `customRun` steps, and optionally for commands.\n *\n * Only an embedding host can supply one: it runs inside the host process. A\n * run delegated through `launch-command` executes elsewhere and never sees it,\n * so a host that wants its executor used launches with `skipLaunch`.\n */\n stepExecutor?: StepExecutor;\n parser?: WorkflowParserService;\n serviceManager?: BackgroundServiceManager;\n stepRunner?: StepRunnerService;\n jobRunner?: JobRunnerService;\n triggerService?: TriggerService;\n worktreeService?: WorktreeService;\n registry?: WorkflowRegistryService;\n repairService?: WorkflowRepairService;\n runDirectoryService?: RunDirectoryService;\n}\n\ninterface DryRunPromptAssembly {\n jobName: string;\n matrix: MatrixEntry;\n prompt: string;\n}\n\n/**\n * Orchestrates local workflow execution, including triggers, jobs, services,\n * worktree lifecycle, and graceful interruption handling.\n */\nexport class RunWorkflowService {\n readonly runtime: WorkflowRuntimeContext;\n private readonly ownsProcessSignals: boolean;\n private logger: Logger;\n private parser: WorkflowParserService;\n private serviceManager: BackgroundServiceManager;\n private stepRunner: StepRunnerService;\n private jobRunner: JobRunnerService;\n private triggerService: TriggerService;\n private worktreeService: WorktreeService;\n private registry: WorkflowRegistryService;\n private repairService: WorkflowRepairService;\n private runDirectoryService: RunDirectoryService;\n private outputLines: string[] = [];\n private interruptedSignal: NodeJS.Signals | null = null;\n private launchStdio: 'inherit' | 'pipe';\n private launcherMetadata: WorkflowLauncherMetadata | undefined;\n\n /**\n * Create a workflow runner with an optional logger and overridable\n * collaborators for tests or alternate orchestration behavior.\n */\n constructor(logger: Logger | undefined, dependencies: RunWorkflowDependencies) {\n this.runtime = dependencies.runtime;\n this.ownsProcessSignals = dependencies.ownsTerminal !== false;\n const baseLogger = createWorkflowLogger(\n logger ?? {\n info: (message: string) => this.runtime.workflowHost.writeStdout(`${message}\\n`),\n error: (message: string) => this.runtime.workflowHost.writeStderr(`${message}\\n`),\n warn: (message: string) => this.runtime.workflowHost.writeStderr(`${message}\\n`),\n },\n );\n\n const pushLine = (message: string) => {\n this.outputLines.push(message);\n if (this.outputLines.length > MAX_OUTPUT_LINES) {\n this.outputLines.shift();\n }\n };\n\n this.logger = {\n info: (message: string) => {\n pushLine(message);\n baseLogger.info(message);\n },\n error: (message: string) => {\n pushLine(message);\n baseLogger.error(message);\n },\n warn: (message: string) => {\n pushLine(message);\n baseLogger.warn(message);\n },\n runInSpan: baseLogger.runInSpan?.bind(baseLogger),\n event: baseLogger.event?.bind(baseLogger),\n flush: baseLogger.flush?.bind(baseLogger),\n };\n\n this.launchStdio = dependencies.launchStdio ?? 'inherit';\n this.launcherMetadata = dependencies.launcherMetadata;\n this.parser = dependencies.parser ?? new WorkflowParserService(this.runtime);\n this.serviceManager = dependencies.serviceManager ?? new BackgroundServiceManager(this.runtime, this.logger);\n // The three `undefined`s keep the quota service, status-file watcher and\n // run-directory service on their own defaults; only terminal ownership and\n // the host executor are being set here.\n this.stepRunner =\n dependencies.stepRunner ??\n new StepRunnerService(\n this.runtime,\n this.parser,\n this.logger,\n undefined,\n undefined,\n undefined,\n dependencies.ownsTerminal,\n dependencies.stepExecutor,\n );\n this.registry = dependencies.registry ?? new WorkflowRegistryService(this.runtime);\n this.runDirectoryService =\n dependencies.runDirectoryService ?? new RunDirectoryService(this.runtime, this.registry.writeCoordinator);\n this.jobRunner =\n dependencies.jobRunner ??\n new JobRunnerService(this.runtime, this.parser, this.stepRunner, this.logger, this.runDirectoryService);\n this.triggerService = dependencies.triggerService ?? new TriggerService(this.runtime, this.stepRunner, this.logger);\n this.worktreeService =\n dependencies.worktreeService ?? new WorktreeService(this.runtime, this.stepRunner, this.logger);\n this.repairService = dependencies.repairService ?? new WorkflowRepairService(this.runtime);\n }\n\n /**\n * Run the workflow from trigger preparation through cleanup.\n */\n async run(input: RunWorkflowInput): Promise<RunWorkflowResult> {\n this.stepRunner.resetInterruption();\n this.triggerService.resetInterruption();\n this.outputLines = [];\n this.interruptedSignal = null;\n const dryRun = input.dryRun ?? false;\n const continueOnError = input.continueOnError ?? false;\n let isCleaningUp = false;\n\n const cleanup = (signal: NodeJS.Signals) => {\n if (isCleaningUp) {\n return;\n }\n isCleaningUp = true;\n this.interrupt(signal);\n };\n const handleSigint = () => cleanup(INTERRUPT_SIGNAL);\n const handleSigterm = () => cleanup(TERMINATE_SIGNAL);\n const handleSighup = () => cleanup(HANGUP_SIGNAL);\n const unsubscribe = this.ownsProcessSignals\n ? [\n this.runtime.workflowHost.onSignal(INTERRUPT_SIGNAL, handleSigint),\n this.runtime.workflowHost.onSignal(TERMINATE_SIGNAL, handleSigterm),\n this.runtime.workflowHost.onSignal(HANGUP_SIGNAL, handleSighup),\n ]\n : [];\n\n try {\n return await runWorkflowSpan(this.logger, 'workflow.run', {}, () =>\n this.executeWorkflow(input, dryRun, continueOnError, input.keepWorktree ?? false),\n );\n } catch (error) {\n if (error instanceof WorkflowInterruptedError || this.isInterrupted()) {\n await this.serviceManager.stopAll();\n return this.createInterruptedResult();\n }\n throw error;\n } finally {\n await this.logger.flush?.();\n for (const off of unsubscribe) off();\n await this.serviceManager.stopAll();\n }\n }\n\n /**\n * Trigger the same interruption cleanup path used by process signal handlers.\n *\n * The optional context records where shutdown started so subsequent\n * `WorkflowInterruptedError` instances carry structured diagnostics.\n */\n interrupt(signal: NodeJS.Signals, context: WorkflowInterruptContext = { phase: WORKFLOW_PHASE }): void {\n if (this.interruptedSignal) {\n return;\n }\n\n this.interruptedSignal = signal;\n const contextSuffix = context.phase === WORKFLOW_PHASE ? '' : ` (${context.phase})`;\n this.logger.info(`\\n\\n${YELLOW}${BOLD}Interrupted, shutting down...${RESET}${contextSuffix}`);\n // SIGHUP can be ignored by non-interactive shells. Record the original signal,\n // but use SIGTERM so the active process tree shuts down reliably.\n const shutdownSignal = signal === HANGUP_SIGNAL ? TERMINATE_SIGNAL : signal;\n this.triggerService.abortActivePrompt(shutdownSignal);\n this.stepRunner.stopActiveStep(shutdownSignal);\n\n void this.serviceManager.stopAll();\n }\n\n /**\n * Check whether workflow shutdown has been requested.\n */\n private isInterrupted(): boolean {\n return (\n this.interruptedSignal === INTERRUPT_SIGNAL ||\n this.interruptedSignal === TERMINATE_SIGNAL ||\n this.interruptedSignal === HANGUP_SIGNAL\n );\n }\n\n /**\n * Build the standard process-style result for an interrupted workflow run.\n */\n private createInterruptedResult(): RunWorkflowResult {\n return { exitCode: INTERRUPTED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n\n /**\n * Extract the restart-from job name from fix.md YAML frontmatter.\n * Returns the parsed target and any invalid target for caller logging.\n */\n private parseFixRestartFrom(\n fixContent: string,\n jobOrder: string[],\n allowTerminalStop: boolean,\n ): {\n restartFrom?: string;\n invalidTarget?: string;\n terminal?: boolean;\n terminalRequested?: boolean;\n } {\n let requestedTarget: string | undefined;\n let requestedStatus: string | undefined;\n if (fixContent.startsWith(FIX_FRONTMATTER_DELIMITER)) {\n const endIndex = fixContent.indexOf(FIX_FRONTMATTER_DELIMITER, FIX_FRONTMATTER_DELIMITER.length);\n if (endIndex >= 0) {\n const frontmatter = fixContent.slice(FIX_FRONTMATTER_DELIMITER.length, endIndex);\n for (const line of frontmatter.split('\\n')) {\n const separatorIndex = line.indexOf(':');\n if (separatorIndex < 0) {\n continue;\n }\n const key = line.slice(0, separatorIndex).trim().toLowerCase();\n if (key === FIX_RESTART_FROM_KEY) {\n requestedTarget = line.slice(separatorIndex + 1).trim();\n }\n if (key === FIX_STATUS_KEY) {\n requestedStatus = line.slice(separatorIndex + 1).trim();\n }\n }\n }\n }\n\n const normalizedTarget = requestedTarget?.toLowerCase();\n const terminalRequested =\n requestedStatus?.toLowerCase() === FIX_TERMINAL_TARGET || normalizedTarget === FIX_TERMINAL_TARGET;\n if (terminalRequested && allowTerminalStop) {\n return { terminal: true, terminalRequested: true };\n }\n\n if (normalizedTarget && normalizedTarget !== FIX_TERMINAL_TARGET) {\n const exactMatch = jobOrder.find((jobName) => jobName.toLowerCase() === normalizedTarget);\n if (exactMatch) {\n return { restartFrom: exactMatch, terminalRequested };\n }\n }\n\n const normalizedFixContent = fixContent.toLowerCase();\n const contentMatch = jobOrder\n .map((jobName, order) => ({\n index: normalizedFixContent.indexOf(jobName.toLowerCase()),\n jobName,\n order,\n }))\n .filter((candidate) => candidate.index >= 0)\n .sort(\n (left, right) =>\n left.index - right.index || right.jobName.length - left.jobName.length || left.order - right.order,\n )[0];\n\n if (contentMatch) {\n return { restartFrom: contentMatch.jobName, terminalRequested };\n }\n\n if (requestedTarget && normalizedTarget !== FIX_TERMINAL_TARGET) {\n return { invalidTarget: requestedTarget, terminalRequested };\n }\n\n return { terminalRequested };\n }\n\n /**\n * Extract the proceed-to job name from proceed.md YAML frontmatter.\n *\n * Frontmatter only, with no fall back to job names mentioned in the body the\n * way fix.md routing does. A mis-routed restart costs re-run time; a\n * mis-routed forward jump silently drops jobs that were supposed to run, so a\n * request this parser cannot read exactly is one the caller should ignore.\n */\n private parseProceedTo(proceedContent: string, jobOrder: string[]): { target?: string; invalidTarget?: string } {\n let requestedTarget: string | undefined;\n if (proceedContent.startsWith(FIX_FRONTMATTER_DELIMITER)) {\n const endIndex = proceedContent.indexOf(FIX_FRONTMATTER_DELIMITER, FIX_FRONTMATTER_DELIMITER.length);\n if (endIndex >= 0) {\n const frontmatter = proceedContent.slice(FIX_FRONTMATTER_DELIMITER.length, endIndex);\n for (const line of frontmatter.split('\\n')) {\n const separatorIndex = line.indexOf(':');\n if (separatorIndex < 0) {\n continue;\n }\n if (line.slice(0, separatorIndex).trim().toLowerCase() === PROCEED_TO_KEY) {\n requestedTarget = line.slice(separatorIndex + 1).trim();\n }\n }\n }\n }\n\n if (!requestedTarget) {\n return {};\n }\n\n const normalizedTarget = requestedTarget.toLowerCase();\n const exactMatch = jobOrder.find((jobName) => jobName.toLowerCase() === normalizedTarget);\n return exactMatch ? { target: exactMatch } : { invalidTarget: requestedTarget };\n }\n\n /**\n * Check whether a file-system path exists while preserving non-ENOENT errors.\n */\n private async pathExists(path: string): Promise<boolean> {\n try {\n getOrThrow(await this.runtime.fs.fileInfo(path, this.runtime.ioContext));\n return true;\n } catch (error) {\n if (['ENOENT', 'not_found'].includes(String((error as { code?: string }).code))) {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Give background services a short async window to finish booting.\n */\n private async waitForServiceStartup(): Promise<void> {\n await new Promise<void>((resolveDelay) => {\n setTimeout(resolveDelay, SERVICE_STARTUP_DELAY_MS);\n });\n }\n\n private resolveWorkflowRunner(workflow: Workflow): string | undefined {\n if (workflow.runner && workflow['default-runner'] && workflow.runner !== workflow['default-runner']) {\n throw new Error(\n `Conflicting workflow runner selectors: runner=\"${workflow.runner}\" default-runner=\"${workflow['default-runner']}\"`,\n );\n }\n\n return workflow.runner ?? workflow['default-runner'];\n }\n\n /**\n * Hand the step runner the workflow's command templates and what the launch\n * selected, refusing a `--command` some templated step does not offer or a\n * `--choice` the workflow does not declare before anything runs.\n */\n private useCommandSelection(workflow: Workflow, input: RunWorkflowInput): void {\n if (input.command !== undefined) {\n const offered = compatibleCommands(workflow);\n if (!offered?.includes(input.command)) {\n throw new Error(\n offered\n ? `Command \"${input.command}\" is not offered by every templated step (offered: ${offered.join(', ') || 'none in common'}).`\n : `Command \"${input.command}\" was selected, but no step of this workflow is templated.`,\n );\n }\n }\n if (input.choice !== undefined && !workflow.choices?.[input.choice]) {\n const declared = Object.keys(workflow.choices ?? {});\n throw new Error(`Choice \"${input.choice}\" is not declared (declared: ${declared.join(', ') || 'none'}).`);\n }\n this.stepRunner.useCommandTemplates({\n commands: workflow.commands,\n choices: workflow.choices,\n command: input.command,\n choice: input.choice,\n });\n }\n\n private resolveRunner(input: RunWorkflowInput, workflow?: Workflow): string | undefined {\n if (input.runner && input.cliAgent && input.runner !== input.cliAgent) {\n throw new Error(`Conflicting runner selectors: runner=\"${input.runner}\" cliAgent=\"${input.cliAgent}\"`);\n }\n\n return input.runner ?? input.cliAgent ?? (workflow ? this.resolveWorkflowRunner(workflow) : undefined);\n }\n\n /**\n * Execute the workflow after signal handlers are installed.\n */\n private async executeWorkflow(\n input: RunWorkflowInput,\n dryRun: boolean,\n continueOnError: boolean,\n keepWorktree = false,\n ): Promise<RunWorkflowResult> {\n if (input.statusFile) {\n input = { ...input, statusFile: resolve(input.statusFile) };\n }\n\n const workflowPath = resolve(this.runtime.cwd, input.workflowPath);\n const parsedWorkflow = await this.parser.parseWorkflowFile(workflowPath);\n const runner = this.resolveRunner(input, parsedWorkflow);\n let workflow = this.parser.selectRunner(parsedWorkflow, runner);\n this.useCommandSelection(workflow, input);\n let registryRun: WorkflowRunHandle | null = null;\n const configuration = () => ({\n workflow: structuredClone(workflow),\n revision: createHash('sha256').update(JSON.stringify(workflow)).digest('hex'),\n });\n /**\n * Whether this process handed the run to a launcher instead of running it.\n *\n * The delegating process returns from inside the `try`, so the `finally`\n * still fires for it. Most of that block is already inert here, keyed off\n * state delegation never creates: no run record, no worktree, no completion\n * hooks. `post:` is the exception, and it is not a harmless one.\n */\n let delegated = false;\n // Declared out here because post cleanup runs in the `finally` below, and it\n // is a phase readers care about: it is where a dispatch run releases its lock.\n let progress: WorkflowProgressService | undefined;\n let result: RunWorkflowResult | null = null;\n let runError: unknown = null;\n let workflowDir = dirname(workflowPath);\n let originalDir = workflowDir;\n let worktreePath: string | null = null;\n let worktreeBranch: string | null = null;\n let shouldRunSuccessCompletionHooks = false;\n let shouldRemoveWorktreeOnExit = false;\n let failedJob: string | undefined;\n let failureReason: string | undefined;\n let persistedFixLoopCycle: number | undefined;\n let activeJob: string | undefined;\n let activeRepair: WorkflowRepairRecord | null = null;\n const dryRunPromptAssemblies: DryRunPromptAssembly[] = [];\n const useWorktree = !!workflow.worktree;\n const inputs = new Map<string, string>();\n const secrets = input.secretFile ? await this.parser.loadSecrets(input.secretFile) : new Map<string, string>();\n const workflowEnv: Record<string, string> = {};\n const persistExecutionCursor = async (patch: Partial<WorkflowExecutionCursor>): Promise<void> => {\n if (!registryRun) return;\n try {\n await this.registry.updateExecutionCursor(registryRun, patch);\n } catch (error) {\n this.logger.warn(\n `${YELLOW}${BOLD}Workflow cursor update skipped${RESET}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n };\n const onStepStarted = async (\n stepName: string,\n index: number,\n total: number,\n matrixIndex?: number,\n attempt?: number,\n ): Promise<void> => {\n await persistExecutionCursor({\n attempt,\n job: activeJob,\n matrixIndex,\n phase: activeJob ? 'step' : (workflowEnv[WORKFLOW_PHASE_ENV] ?? 'step'),\n resumeMode: 'continue-next',\n stepIndex: index,\n stepName,\n });\n void total;\n };\n const onExecutionStateChange = async (state: 'paused' | 'resumed', stepName: string): Promise<void> => {\n await persistExecutionCursor({\n job: activeJob,\n phase: activeJob ? 'step' : (workflowEnv[WORKFLOW_PHASE_ENV] ?? 'step'),\n stepName,\n });\n await this.logger.event?.('info', `workflow.run.${state}`, {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.step.name': stepName,\n }),\n });\n };\n\n try {\n // Resolve inputs with defaults\n const inputDefs = workflow.on?.[TRIGGER_WORKFLOW_DISPATCH]?.inputs || {};\n for (const [key, def] of Object.entries(inputDefs)) {\n if (def.default) inputs.set(key, def.default);\n }\n if (input.inputs) {\n for (const [key, val] of Object.entries(input.inputs)) {\n inputs.set(key, val);\n }\n }\n\n // Build workflow env\n if (workflow.env) {\n for (const [key, val] of Object.entries(workflow.env)) {\n workflowEnv[key] = String(val);\n }\n }\n if (input.env) {\n for (const [key, val] of Object.entries(input.env)) {\n workflowEnv[key] = val;\n }\n }\n if (runner) {\n workflowEnv.WORKFLOW_RUNNER = runner;\n workflowEnv.WORKFLOW_CLI_AGENT = runner;\n }\n if (input.command) workflowEnv.WORKFLOW_COMMAND = input.command;\n if (input.choice) workflowEnv.WORKFLOW_CHOICE = input.choice;\n\n // Resolve the repo root from workflow path\n let candidate = workflowDir;\n while (candidate !== '/') {\n if (await this.pathExists(resolve(candidate, GIT_DIRNAME))) {\n workflowDir = candidate;\n break;\n }\n candidate = dirname(candidate);\n }\n const workflowPathFromRoot = relative(workflowDir, workflowPath);\n const currentWorkflowPath = async () => {\n const workflowPathInCurrentDir = resolve(workflowDir, workflowPathFromRoot);\n return (await this.pathExists(workflowPathInCurrentDir)) ? workflowPathInCurrentDir : workflowPath;\n };\n\n const resolvedWorkspace = this.registry.resolveWorkspace(input.workspace, workflow.workspace);\n await this.registry.reconcileStaleRuns(resolvedWorkspace);\n\n // Capacity check: enforce max-workflows before creating a run\n const maxWorkflows = workflow['max-workflows'];\n if (maxWorkflows) {\n const running = await this.registry.countRunningWorkflows(resolvedWorkspace);\n if (running >= maxWorkflows) {\n throw new WorkflowCapacityError(resolvedWorkspace, running, maxWorkflows);\n }\n }\n\n // Launch-command delegation: re-invoke via configured launcher (e.g. cmux)\n const launchCommand = workflow['launch-command'];\n if (launchCommand && !input.skipLaunch) {\n const innerCommand = await this.createLaunchScriptCommand(input, workflowPath, workflow);\n const launchBaseName = input.name || workflow.name || basename(workflowPath);\n const launchDisplayName = input.name\n ? launchBaseName\n : `${launchBaseName}-${this.parser.generateHumanReadableId()}`;\n const namedLaunchCommand = substituteShellPlaceholder(\n launchCommand,\n LAUNCH_NAME_PLACEHOLDER,\n launchDisplayName,\n );\n const shell = substituteShellPlaceholder(namedLaunchCommand, LAUNCH_COMMAND_PLACEHOLDER, innerCommand);\n this.logger.info(`${DIM}Delegating via launch-command: ${shell}${RESET}`);\n delegated = true;\n const launched = await this.spawnLaunchCommand(shell, {\n cwd: workflowDir,\n env: this.buildLaunchEnvironment(input.launcher ?? workflow.launcher),\n });\n // Piped output would otherwise be dropped on the floor; routing it\n // through the logger puts it in `outputLines` where the caller reads it.\n if (launched.stdout) this.logger.info(launched.stdout);\n // With piped stdio the launcher's diagnosis is on stderr, and a failed\n // launch leaves no run behind, so this is its only explanation.\n if (launched.stderr && launched.exitCode !== 0) this.logger.error(launched.stderr);\n return { exitCode: launched.exitCode, output: this.outputLines.join('\\n') };\n }\n\n const baseName = input.name || workflow.name || basename(workflowPath);\n const workflowName = input.name ? baseName : `${baseName}-${this.parser.generateHumanReadableId()}`;\n const workflowId = basename(workflowPath, extname(workflowPath));\n if (dryRun && input.recovery) {\n registryRun = await this.createRecoveryDryRunHandle(input, resolvedWorkspace);\n } else {\n registryRun = await this.registry.createRun({\n activeRepairId: input.recovery?.activeRepairId,\n cliAgent: input.cliAgent,\n continueOnError: input.continueOnError,\n displayName: workflowName,\n dryRun,\n env: input.env,\n inputs: input.inputs,\n job: input.recovery ? input.recovery.originalJob : input.job,\n keepWorktree: input.keepWorktree,\n launcher: this.launcherMetadata ?? (await this.resolveLauncherMetadata()),\n prompt: input.prompt,\n recoveryClaimId: input.recovery?.claimId,\n runner,\n command: input.command,\n choice: input.choice,\n runDirectory: workflow['run-directory'],\n secretFile: input.secretFile,\n skipLaunch: input.skipLaunch,\n statusFile: input.statusFile,\n terminalSocket: this.runtime.baseEnvironment[WORKFLOW_TERMINAL_SOCKET_ENV],\n workflowPath,\n workflowId,\n workflowName: workflow.name ?? workflowId,\n workflowWorkspace: workflow.workspace,\n workspace: input.workspace,\n });\n }\n\n if (input.recovery?.activeRepairId && !dryRun) {\n activeRepair = await this.repairService.readRepair(registryRun.runDir, input.recovery.activeRepairId);\n }\n\n workflowEnv.WORKFLOW_RUN_DIR = registryRun.runDir;\n workflowEnv.WORKFLOW_RUN_ID = registryRun.runId;\n workflowEnv.WORKFLOW_RUN_KEY = registryRun.runKey;\n workflowEnv.WORKFLOW_ID = workflowId;\n workflowEnv.WORKFLOW_NAME = workflow.name ?? workflowId;\n workflowEnv.WORKFLOW_WORKSPACE = registryRun.workspace;\n workflowEnv[WORKFLOW_PHASE_ENV] = 'trigger';\n await this.runDirectoryService.materialize(registryRun.runDir, workflow['run-directory'], dryRun);\n if (!dryRun) await this.installStepCli(registryRun.runDir, workflowEnv);\n if (!dryRun) {\n input.onRegistered?.({\n runKey: registryRun.runKey,\n runId: registryRun.runId,\n workspace: registryRun.workspace,\n runDir: registryRun.runDir,\n displayName: registryRun.displayName,\n ...configuration(),\n });\n }\n await this.logger.event?.('info', 'workflow.run.started', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.display_name': registryRun.displayName,\n 'workflow.runner': runner ?? 'default',\n }),\n });\n if (workflowEnv.CONTEXT_FILE) {\n workflowEnv.CONTEXT_FILE = registryRun.contextPath;\n workflowEnv.CHANGELOG_FILE = registryRun.changelogPath;\n }\n\n // Print header\n this.logger.info(`${BOLD}${'═'.repeat(60)}${RESET}`);\n this.logger.info(` ${BOLD}run-workflow${RESET} - ${registryRun.displayName}`);\n this.logger.info(`${BOLD}${'═'.repeat(60)}${RESET}`);\n this.logger.info(` File: ${workflowPath}`);\n this.logger.info(` Workspace: ${registryRun.workspace || DEFAULT_WORKSPACE}`);\n this.logger.info(` Run Dir: ${registryRun.runDir}`);\n if (workflow['run-directory']) {\n this.logger.info(` Run Files: ${workflow['run-directory'].entries.length} declared entries`);\n }\n this.logger.info(` CWD: ${workflowDir}`);\n if (inputs.size > 0) {\n this.logger.info(` Inputs: ${[...inputs.entries()].map(([k, v]) => `${k}=${v}`).join(', ')}`);\n }\n if (secrets.size > 0) {\n this.logger.info(` Secrets: ${[...secrets.keys()].join(', ')}`);\n }\n if (input.job) {\n this.logger.info(` Target: ${input.job}`);\n }\n if (runner) {\n this.logger.info(` Runner: ${runner}`);\n }\n if (workflow.pre) {\n const svcCount = workflow.pre.services?.length || 0;\n const stepCount = workflow.pre.steps?.length || 0;\n this.logger.info(` Pre: ${svcCount} service(s), ${stepCount} setup step(s)`);\n }\n if (workflow.post) {\n const svcCount = workflow.post.services?.length || 0;\n const stepCount = workflow.post.steps?.length || 0;\n this.logger.info(` Post: ${svcCount} service(s), ${stepCount} cleanup step(s)`);\n }\n if (useWorktree) {\n this.logger.info(` Worktree: enabled${keepWorktree ? ' (keep on completion)' : ''}`);\n }\n const triggerType =\n workflow.on && TRIGGER_USER_PROMPT in workflow.on\n ? TRIGGER_USER_PROMPT\n : workflow.on?.[TRIGGER_AGENT_DECISION]\n ? TRIGGER_AGENT_DECISION\n : TRIGGER_WORKFLOW_DISPATCH;\n this.logger.info(` Trigger: ${triggerType}`);\n this.logger.info(` Mode: ${dryRun ? 'dry-run' : 'execute'}`);\n this.logger.info(`${BOLD}${'═'.repeat(60)}${RESET}`);\n\n // Handle user_prompt trigger\n const promptOk = await this.triggerService.handleUserPrompt(\n workflow,\n input.prompt || null,\n workflowEnv,\n workflowDir,\n dryRun,\n );\n if (!promptOk) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n return result;\n }\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_ABORTED_PROMPT_TEXT}${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n return result;\n }\n\n // Handle agent_decision trigger\n const decisionOk = await this.triggerService.handleAgentDecision(\n workflow,\n workflowEnv,\n inputs,\n secrets,\n {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n stopRequestPath: registryRun.stopRequestPath,\n workflowDir,\n onStepStarted,\n onExecutionStateChange,\n },\n input.prompt || null,\n );\n if (!decisionOk) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n return result;\n }\n this.logger.info(`\\n${YELLOW}${BOLD}${WORKFLOW_SKIPPED_TEXT}${RESET}`);\n result = { exitCode: WORKFLOW_SKIPPED_EXIT_CODE, output: this.outputLines.join('\\n') };\n return result;\n }\n\n // Worktree creation\n originalDir = workflowDir;\n\n if (useWorktree && input.recovery) {\n if (!input.recovery.worktreePath || !(await this.pathExists(input.recovery.worktreePath))) {\n throw new Error(`Recoverable worktree not found: ${input.recovery.worktreePath ?? '(missing)'}`);\n }\n\n originalDir = input.recovery.originalRepoPath ?? originalDir;\n worktreePath = input.recovery.worktreePath;\n worktreeBranch =\n input.recovery.worktreeBranch ?? this.worktreeService.getWorktreeBranchName(registryRun.displayName);\n workflowDir = worktreePath;\n\n workflowEnv.WORKTREE_PATH = worktreePath;\n workflowEnv.WORKTREE_BRANCH = worktreeBranch;\n workflowEnv.ORIGINAL_REPO_PATH = originalDir;\n\n this.logger.info(`\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}Reusing worktree${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n this.logger.info(` ${DIM}path ${RESET} ${worktreePath}`);\n } else if (useWorktree && !dryRun) {\n if (workflow.worktree?.beforeCreate) {\n workflowEnv[WORKFLOW_PHASE_ENV] = 'worktree-before-create';\n this.logger.info(`\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}beforeCreate${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n const hookOk = await this.worktreeService.runHook(\n workflow.worktree.beforeCreate,\n workflowDir,\n workflowEnv,\n inputs,\n secrets,\n {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n stopRequestPath: registryRun.stopRequestPath,\n onStepStarted,\n onExecutionStateChange,\n },\n );\n\n if (!hookOk) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n } else {\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_ABORTED_WORKTREE_BEFORE_CREATE_TEXT}${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n }\n }\n if (!result) {\n this.logger.info(`\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}Creating worktree${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n worktreeBranch = this.worktreeService.getWorktreeBranchName(registryRun.displayName);\n worktreePath = await this.worktreeService.createWorktree(workflowDir, registryRun.displayName);\n workflowDir = worktreePath;\n\n workflowEnv.WORKTREE_PATH = worktreePath;\n workflowEnv.WORKTREE_BRANCH = worktreeBranch;\n workflowEnv.ORIGINAL_REPO_PATH = originalDir;\n\n if (workflow.worktree?.afterCreate) {\n workflowEnv[WORKFLOW_PHASE_ENV] = 'worktree-after-create';\n this.logger.info(`\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}afterCreate${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n const hookOk = await this.worktreeService.runHook(\n workflow.worktree.afterCreate,\n worktreePath,\n workflowEnv,\n inputs,\n secrets,\n {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n stopRequestPath: registryRun.stopRequestPath,\n onStepStarted,\n onExecutionStateChange,\n },\n );\n\n if (!hookOk) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n } else {\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_ABORTED_WORKTREE_AFTER_CREATE_TEXT}${RESET}`);\n result = {\n exitCode: WORKFLOW_FAILED_EXIT_CODE,\n output: this.outputLines.join('\\n'),\n };\n }\n shouldRemoveWorktreeOnExit = !keepWorktree;\n }\n }\n }\n } else if (useWorktree && dryRun) {\n const parentDir = dirname(workflowDir);\n const folderName = basename(workflowDir);\n const safeName = registryRun.displayName\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-|-$/g, '');\n const dryWorktreePath = resolve(parentDir, `${folderName}-worktree`, safeName);\n this.logger.info(\n `\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}(dry-run)${RESET} ${WORKTREE_DRY_RUN_MESSAGE} ${dryWorktreePath}`,\n );\n }\n\n // Records job transitions where another process can read them.\n //\n // Created before the pre block, not at the job loop: a dispatch workflow\n // spends its opening minutes in `pre:` claiming its job, and a progress\n // log that only starts at the first job leaves every reader staring at an\n // empty tree for exactly the stretch where it most wants to know what is\n // happening. Dry runs record too; they have a run directory like any other\n // run, and a log with steps but no job transitions folds into a job that\n // never finishes.\n progress = new WorkflowProgressService(this.runtime, registryRun.runDir);\n\n // Run pre-conditions (after worktree so pre steps run in worktree dir)\n if (!result && workflow.pre) {\n workflowEnv[WORKFLOW_PHASE_ENV] = 'pre';\n const preBlock = workflow.pre;\n const preStopRequestPath = registryRun.stopRequestPath;\n const preResult = await this.recordPhase(progress, PRE_PHASE_JOB, () =>\n this.runPreBlock(preBlock, workflowEnv, inputs, secrets, {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n progress,\n stopRequestPath: preStopRequestPath,\n workflowDir,\n onStepStarted,\n onExecutionStateChange,\n }),\n );\n\n if (!preResult) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n } else {\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_ABORTED_PRECONDITIONS_TEXT}${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n shouldRemoveWorktreeOnExit = Boolean(worktreePath && !keepWorktree);\n }\n }\n\n const maxRetries = parsePositiveIntegerEnv(workflowEnv.MAX_RETRIES, DEFAULT_MAX_RETRIES);\n const maxFixCycles = parsePositiveIntegerEnv(workflowEnv.FIX_LOOP_MAX_CYCLES, DEFAULT_MAX_FIX_CYCLES);\n const fixLoopDisabled = envFlagEnabled(workflowEnv[WORKFLOW_FIX_LOOP_DISABLED_ENV]);\n\n // Run jobs with fix-loop support\n const jobOrderTarget = input.recovery ? input.recovery.originalJob || null : input.job || null;\n let jobOrder = this.parser.resolveJobOrder(workflow.jobs, jobOrderTarget);\n let loggedJobOrder = jobOrder.join(' -> ');\n this.logger.info(`\\n ${DIM}Job order: ${loggedJobOrder} (max retries: ${maxRetries})${RESET}`);\n\n const completedJobs = new Set<string>();\n const fixFile =\n !fixLoopDisabled && workflowEnv.WORKFLOW_RUN_DIR ? resolve(workflowEnv.WORKFLOW_RUN_DIR, FIX_FILENAME) : null;\n // Forward jumps only exist inside a repair, and repairs only exist while\n // the fix loop is on, so this file is inert under the same conditions.\n const proceedFile =\n !fixLoopDisabled && workflowEnv.WORKFLOW_RUN_DIR\n ? resolve(workflowEnv.WORKFLOW_RUN_DIR, PROCEED_FILENAME)\n : null;\n if (fixLoopDisabled) {\n this.logger.info(` ${DIM}fix-loop disabled by ${WORKFLOW_FIX_LOOP_DISABLED_ENV}${RESET}`);\n }\n let fixCycle = 0;\n\n let jobIndex = 0;\n let pendingStartJob = input.recovery?.startJob;\n let lastCompletedJob: string | undefined;\n while (!result) {\n workflow = this.parser.selectRunner(await this.parser.parseWorkflowFile(await currentWorkflowPath()), runner);\n this.useCommandSelection(workflow, input);\n input.onConfigChanged?.({\n runKey: registryRun.runKey,\n runId: registryRun.runId,\n workspace: registryRun.workspace,\n runDir: registryRun.runDir,\n displayName: registryRun.displayName,\n ...configuration(),\n });\n jobOrder = this.parser.resolveJobOrder(workflow.jobs, jobOrderTarget);\n const currentJobOrder = jobOrder.join(' -> ');\n if (currentJobOrder !== loggedJobOrder) {\n loggedJobOrder = currentJobOrder;\n this.logger.info(` ${DIM}Workflow file reloaded; job order: ${loggedJobOrder}${RESET}`);\n }\n\n if (activeRepair?.status === 'pending' && workflow.repair) {\n activeJob = REPAIR_TRIAGE_JOB_NAME;\n workflowEnv[WORKFLOW_PHASE_ENV] = REPAIR_TRIAGE_JOB_NAME;\n this.setRepairEnvironment(workflowEnv, registryRun.runDir, activeRepair);\n const repairIssueContent = getOrThrow(\n await this.runtime.fs.readTextFile(\n resolve(registryRun.runDir, activeRepair.issueFile),\n this.runtime.ioContext,\n ),\n );\n\n let triageFailureReason: string | undefined;\n const repair = workflow.repair;\n const stopRequestPath = registryRun.stopRequestPath;\n // Recorded like pre and post: triage is not in the job order, and a\n // triage the progress log never saw start or finish reads as running.\n const triageOk = await this.recordPhase(progress, REPAIR_TRIAGE_JOB_NAME, () =>\n this.jobRunner.runJob(\n REPAIR_TRIAGE_JOB_NAME,\n repair,\n {\n onFailed: (reason) => {\n triageFailureReason = reason;\n },\n inputs,\n secrets,\n workflowEnv,\n workflowSystemPrompt: workflow['system-prompt'],\n jobOrder,\n allJobs: {\n ...workflow.jobs,\n [REPAIR_TRIAGE_JOB_NAME]: repair,\n },\n repairTriage: true,\n activeRepairIssue: repairIssueContent,\n runDirectory: workflow['run-directory'],\n },\n {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n stopRequestPath,\n workflowDir,\n maxRetries,\n onStepStarted,\n onExecutionStateChange,\n },\n ),\n );\n\n if (this.isInterrupted()) {\n failedJob ??= REPAIR_TRIAGE_JOB_NAME;\n failureReason ??= `Workflow interrupted at job \"${REPAIR_TRIAGE_JOB_NAME}\"`;\n result = this.createInterruptedResult();\n } else if (!triageOk) {\n failedJob = REPAIR_TRIAGE_JOB_NAME;\n failureReason = triageFailureReason ?? `${WORKFLOW_FAILED_AT_JOB_PREFIX} \"${REPAIR_TRIAGE_JOB_NAME}\"`;\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_FAILED_AT_JOB_PREFIX} \"${REPAIR_TRIAGE_JOB_NAME}\"${RESET}`);\n await this.serviceManager.stopAll();\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n\n if (result) {\n continue;\n }\n\n if (fixFile && (await this.pathExists(fixFile)) && !dryRun) {\n const triageFixContent = getOrThrow(await this.runtime.fs.readTextFile(fixFile, this.runtime.ioContext));\n const { terminal } = this.parseFixRestartFrom(triageFixContent, jobOrder, true);\n failedJob = REPAIR_TRIAGE_JOB_NAME;\n failureReason = terminal\n ? `Terminal fix requested after \"${REPAIR_TRIAGE_JOB_NAME}\" with status \"${FIX_TERMINAL_TARGET}\".`\n : `Repair triage wrote fix.md without terminal status \"${FIX_TERMINAL_TARGET}\".`;\n this.logger.error(`\\n${RED}${BOLD}${failureReason}${RESET}`);\n await this.serviceManager.stopAll();\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n continue;\n }\n\n // Triage decides whether a repair runs at all; it is not inside the\n // repair scope, so it has nothing to jump forward past. Consume any\n // proceed.md it wrote so a scope job later does not inherit it.\n if (proceedFile && (await this.pathExists(proceedFile)) && !dryRun) {\n getOrThrow(await this.runtime.fs.remove(proceedFile, undefined, this.runtime.ioContext));\n this.logger.warn(`${YELLOW}Ignored ${PROCEED_FILENAME} written during repair triage.${RESET}`);\n }\n\n if (!dryRun) {\n activeRepair = await this.repairService.activateRepair(registryRun.runDir, activeRepair);\n if (workflowEnv.CONTEXT_FILE && (await this.pathExists(workflowEnv.CONTEXT_FILE))) {\n await this.updateRepairReferenceStatus(\n workflowEnv.CONTEXT_FILE,\n activeRepair.repairId,\n activeRepair.status,\n );\n }\n await this.logger.event?.('info', 'workflow.repair.triaged', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.repair.id': activeRepair.repairId,\n 'workflow.repair.status': activeRepair.status,\n }),\n });\n }\n activeJob = undefined;\n }\n\n if (pendingStartJob) {\n jobIndex = jobOrder.indexOf(pendingStartJob);\n if (jobIndex < 0) {\n throw new Error(`Start job not found in workflow order: ${pendingStartJob}`);\n }\n pendingStartJob = undefined;\n lastCompletedJob = undefined;\n } else if (lastCompletedJob) {\n const lastCompletedIndex = jobOrder.indexOf(lastCompletedJob);\n if (lastCompletedIndex >= 0) {\n jobIndex = lastCompletedIndex + 1;\n }\n }\n\n if (jobIndex >= jobOrder.length) {\n break;\n }\n\n const jobName = jobOrder[jobIndex];\n const job = workflow.jobs[jobName];\n activeJob = jobName;\n workflowEnv[WORKFLOW_PHASE_ENV] = 'job';\n await progress.jobStarted(jobName, jobIndex, jobOrder.length);\n await persistExecutionCursor({\n job: jobName,\n phase: 'job',\n stepIndex: undefined,\n stepName: undefined,\n });\n const jobUsesRepair = activeRepair?.scopeJobs.includes(jobName) ?? false;\n if (jobUsesRepair && activeRepair) {\n const repairWasPending = activeRepair.status === 'pending';\n if (!dryRun) {\n activeRepair = await this.repairService.activateRepair(registryRun.runDir, activeRepair);\n if (repairWasPending && workflowEnv.CONTEXT_FILE && (await this.pathExists(workflowEnv.CONTEXT_FILE))) {\n await this.updateRepairReferenceStatus(\n workflowEnv.CONTEXT_FILE,\n activeRepair.repairId,\n activeRepair.status,\n );\n }\n }\n this.setRepairEnvironment(workflowEnv, registryRun.runDir, activeRepair);\n if (!dryRun) {\n activeRepair = await this.repairService.startJob(\n registryRun.runDir,\n activeRepair,\n jobName,\n registryRun.runId,\n );\n }\n } else {\n this.clearRepairEnvironment(workflowEnv);\n }\n const repairIssueContent =\n jobUsesRepair && activeRepair\n ? getOrThrow(\n await this.runtime.fs.readTextFile(\n resolve(registryRun.runDir, activeRepair.issueFile),\n this.runtime.ioContext,\n ),\n )\n : undefined;\n\n let jobFailureReason: string | undefined;\n const ok = await this.jobRunner.runJob(\n jobName,\n job,\n {\n onFailed: (reason) => {\n jobFailureReason = reason;\n },\n inputs,\n secrets,\n workflowEnv,\n workflowSystemPrompt: workflow['system-prompt'],\n jobOrder,\n allJobs: workflow.jobs,\n activeRepairIssue: repairIssueContent,\n activeRepairVerificationJob: jobUsesRepair && activeRepair ? activeRepair.verificationJob : undefined,\n allowRepairTerminalStop: jobUsesRepair && !workflow.repair,\n fixLoop: { cycle: fixCycle, maxCycles: maxFixCycles },\n runDirectory: workflow['run-directory'],\n onPromptAssembled: dryRun\n ? (assembly) => {\n dryRunPromptAssemblies.push(assembly);\n }\n : undefined,\n },\n {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n stopRequestPath: registryRun.stopRequestPath,\n workflowDir,\n maxRetries,\n onStepStarted,\n onExecutionStateChange,\n },\n );\n if (this.isInterrupted()) {\n if (jobUsesRepair && activeRepair && !dryRun) {\n activeRepair = await this.repairService.finishJob(registryRun.runDir, activeRepair, jobName, 'interrupted');\n }\n failedJob ??= jobName;\n failureReason ??= `Workflow interrupted at job \"${jobName}\"`;\n result = this.createInterruptedResult();\n }\n\n if (!result && !ok) {\n if (jobUsesRepair && activeRepair && !dryRun) {\n activeRepair = await this.repairService.finishJob(registryRun.runDir, activeRepair, jobName, 'failed');\n }\n failedJob = jobName;\n failureReason = jobFailureReason ?? `${WORKFLOW_FAILED_AT_JOB_PREFIX} \"${jobName}\"`;\n await progress.jobFinished(jobName, 'failed', failureReason);\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_FAILED_AT_JOB_PREFIX} \"${jobName}\"${RESET}`);\n await this.serviceManager.stopAll();\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n\n if (result) {\n continue;\n }\n if (jobUsesRepair && activeRepair && !dryRun) {\n activeRepair = await this.repairService.finishJob(registryRun.runDir, activeRepair, jobName, 'completed');\n }\n completedJobs.add(jobName);\n await progress.jobFinished(jobName, 'completed');\n\n // Archive a transient fix.md as a durable, job-scoped repair before recycling.\n if (fixFile && (await this.pathExists(fixFile)) && !dryRun) {\n const fixContent = getOrThrow(await this.runtime.fs.readTextFile(fixFile, this.runtime.ioContext));\n const { restartFrom, invalidTarget, terminal, terminalRequested } = this.parseFixRestartFrom(\n fixContent,\n jobOrder,\n jobUsesRepair && !workflow.repair,\n );\n if (terminal) {\n failedJob = jobName;\n failureReason = `Terminal fix requested after \"${jobName}\" with status \"${FIX_TERMINAL_TARGET}\".`;\n this.logger.error(`\\n${RED}${BOLD}${failureReason}${RESET}`);\n await this.serviceManager.stopAll();\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n continue;\n }\n if (terminalRequested) {\n this.logger.warn(\n `${YELLOW}Ignored unauthorized terminal stop after \"${jobName}\"; processing fix.md as a repair.${RESET}`,\n );\n }\n fixCycle++;\n persistedFixLoopCycle = fixCycle;\n const nextRepair = await this.repairService.createRepair({\n emittingJob: jobName,\n fixContent,\n fixCycle,\n invalidTarget,\n jobOrder,\n restartFrom,\n runDir: registryRun.runDir,\n });\n getOrThrow(await this.runtime.fs.remove(fixFile, undefined, this.runtime.ioContext));\n // A job that reports a new defect and asks to skip ahead is asking for\n // two contradictory things. The defect wins: skipping ahead would\n // leave it unaddressed.\n if (proceedFile && (await this.pathExists(proceedFile))) {\n getOrThrow(await this.runtime.fs.remove(proceedFile, undefined, this.runtime.ioContext));\n this.logger.warn(\n `${YELLOW}Ignored ${PROCEED_FILENAME} after \"${jobName}\": ${FIX_FILENAME} takes precedence.${RESET}`,\n );\n }\n\n this.logger.info(\n `\\n${YELLOW}${BOLD}fix.md detected after \"${jobName}\" (cycle ${fixCycle}/${maxFixCycles})${RESET}`,\n );\n this.logger.info(`${DIM}Archived as ${nextRepair.issueFile} (repair ${nextRepair.repairId})${RESET}`);\n\n if (nextRepair.routingFallback) {\n this.logger.warn(\n `${YELLOW}fix.md routing used ${nextRepair.routingFallback.reason} fallback to \"${nextRepair.restartFrom}\"${RESET}`,\n );\n }\n\n if (workflowEnv.CONTEXT_FILE && (await this.pathExists(workflowEnv.CONTEXT_FILE))) {\n await this.appendRepairReferenceToContext(workflowEnv.CONTEXT_FILE, nextRepair);\n }\n\n await this.logger.event?.(nextRepair.status === 'rejected' ? 'error' : 'info', 'workflow.repair.created', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.repair.id': nextRepair.repairId,\n 'workflow.repair.requested_target': nextRepair.routingFallback?.requestedTarget ?? nextRepair.restartFrom,\n 'workflow.repair.resolved_target': nextRepair.routingFallback?.resolvedTarget ?? nextRepair.restartFrom,\n 'workflow.repair.restart_from': nextRepair.restartFrom,\n 'workflow.repair.routing_fallback_reason': nextRepair.routingFallback?.reason ?? 'none',\n 'workflow.repair.status': nextRepair.status,\n 'workflow.repair.verifier': nextRepair.verificationJob,\n }),\n });\n\n if (nextRepair.status === 'rejected') {\n await this.registry.updateRepairState(registryRun, { fixLoopCycle: fixCycle });\n failedJob = jobName;\n const requestedTarget = nextRepair.routingFallback?.requestedTarget;\n failureReason =\n nextRepair.routingFallback?.reason === 'unknown' && requestedTarget\n ? `Repair ${nextRepair.repairId} restart target \"${requestedTarget}\" is not in the workflow job order.`\n : `Repair ${nextRepair.repairId} restart target \"${nextRepair.restartFrom}\" occurs after verifier \"${jobName}\".`;\n this.logger.error(`\\n${RED}${BOLD}${failureReason}${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n continue;\n }\n\n if (activeRepair) {\n const supersededRepair = await this.repairService.supersedeRepair(\n registryRun.runDir,\n activeRepair,\n nextRepair.repairId,\n );\n if (workflowEnv.CONTEXT_FILE && (await this.pathExists(workflowEnv.CONTEXT_FILE))) {\n await this.updateRepairReferenceStatus(\n workflowEnv.CONTEXT_FILE,\n supersededRepair.repairId,\n supersededRepair.status,\n );\n }\n await this.logger.event?.('info', 'workflow.repair.superseded', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.repair.id': supersededRepair.repairId,\n 'workflow.repair.status': supersededRepair.status,\n 'workflow.repair.superseded_by': nextRepair.repairId,\n }),\n });\n }\n\n activeRepair = nextRepair;\n await this.registry.updateRepairState(registryRun, {\n activeRepairId: activeRepair.repairId,\n fixLoopCycle: fixCycle,\n });\n\n if (fixCycle > maxFixCycles) {\n failedJob = jobName;\n failureReason = `Fix loop limit reached (${maxFixCycles} cycles).`;\n this.logger.error(`\\n${RED}${BOLD}Fix loop limit reached (${maxFixCycles} cycles). Aborting.${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n continue;\n }\n\n pendingStartJob = activeRepair.restartFrom;\n lastCompletedJob = undefined;\n this.logger.info(`${YELLOW}Restarting from job \"${pendingStartJob}\"${RESET}\\n`);\n continue;\n }\n\n // A repair replays its whole scope by default, which re-runs jobs whose\n // work the fix did not invalidate. A scope job that knows the fix is\n // complete can jump ahead — at most as far as the job that raised the\n // fix, so the verifier always gets to judge the result.\n if (proceedFile && (await this.pathExists(proceedFile)) && !dryRun) {\n const proceedContent = getOrThrow(await this.runtime.fs.readTextFile(proceedFile, this.runtime.ioContext));\n // Consumed whether or not it is honored: a request left on disk would\n // fire again after an unrelated job.\n getOrThrow(await this.runtime.fs.remove(proceedFile, undefined, this.runtime.ioContext));\n\n const { target, invalidTarget } = this.parseProceedTo(proceedContent, jobOrder);\n const verifierIndex = activeRepair ? jobOrder.indexOf(activeRepair.verificationJob) : -1;\n const targetIndex = target ? jobOrder.indexOf(target) : -1;\n const ignoredReason = this.proceedRejectionReason({\n activeRepair,\n invalidTarget,\n jobName,\n jobUsesRepair,\n target,\n targetIndex,\n currentIndex: jobIndex,\n verifierIndex,\n });\n\n if (ignoredReason) {\n this.logger.warn(\n `${YELLOW}Ignored ${PROCEED_FILENAME} after \"${jobName}\": ${ignoredReason}. Continuing in job order.${RESET}`,\n );\n await this.logger.event?.('warn', 'workflow.repair.proceed_ignored', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.repair.id': activeRepair?.repairId ?? 'none',\n 'workflow.repair.proceed_from': jobName,\n 'workflow.repair.proceed_reason': ignoredReason,\n 'workflow.repair.proceed_requested_target': target ?? invalidTarget ?? 'none',\n }),\n });\n } else if (target && activeRepair) {\n const skippedJobs = jobOrder.slice(jobIndex + 1, targetIndex);\n if (skippedJobs.length > 0) {\n activeRepair = await this.repairService.skipJobs(registryRun.runDir, activeRepair, skippedJobs);\n for (const skippedJob of skippedJobs) {\n await progress.jobSkipped(skippedJob, `Skipped by ${PROCEED_FILENAME} from \"${jobName}\"`);\n }\n }\n if (workflowEnv.CONTEXT_FILE && (await this.pathExists(workflowEnv.CONTEXT_FILE))) {\n await this.appendProceedNoteToContext(\n workflowEnv.CONTEXT_FILE,\n activeRepair.repairId,\n jobName,\n target,\n skippedJobs,\n );\n }\n await this.logger.event?.('info', 'workflow.repair.proceeded', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.repair.id': activeRepair.repairId,\n 'workflow.repair.proceed_from': jobName,\n 'workflow.repair.proceed_skipped_count': skippedJobs.length,\n 'workflow.repair.proceed_to': target,\n }),\n });\n this.logger.info(\n `${YELLOW}Proceeding to job \"${target}\" (skipped: ${skippedJobs.join(', ') || 'none'})${RESET}\\n`,\n );\n pendingStartJob = target;\n lastCompletedJob = undefined;\n continue;\n }\n }\n\n if (jobUsesRepair && activeRepair?.verificationJob === jobName && !dryRun) {\n activeRepair = await this.repairService.resolveRepair(registryRun.runDir, activeRepair);\n if (workflowEnv.CONTEXT_FILE && (await this.pathExists(workflowEnv.CONTEXT_FILE))) {\n await this.updateRepairReferenceStatus(\n workflowEnv.CONTEXT_FILE,\n activeRepair.repairId,\n activeRepair.status,\n );\n }\n await this.registry.updateRepairState(registryRun, { activeRepairId: null });\n await this.logger.event?.('info', 'workflow.repair.resolved', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.repair.id': activeRepair.repairId,\n 'workflow.repair.status': activeRepair.status,\n 'workflow.repair.verifier': activeRepair.verificationJob,\n }),\n });\n this.clearRepairEnvironment(workflowEnv);\n activeRepair = null;\n }\n\n lastCompletedJob = jobName;\n jobIndex++;\n activeJob = undefined;\n }\n\n if (!result && this.isInterrupted()) {\n result = this.createInterruptedResult();\n }\n\n if (!result) {\n if (dryRun) {\n const artifactPath = await this.writeDryRunWorkflowArtifact(workflow, jobOrder, dryRunPromptAssemblies);\n this.logger.info(`\\n ${DIM}Assembled workflow: ${artifactPath}${RESET}`);\n }\n shouldRunSuccessCompletionHooks = true;\n this.logger.info(`\\n${BOLD}${'═'.repeat(60)}${RESET}`);\n this.logger.info(` ${GREEN}${BOLD}${WORKFLOW_SUCCESS_TEXT}${RESET}`);\n this.logger.info(` Jobs run: ${[...completedJobs].join(', ')}`);\n if (worktreePath) {\n this.logger.info(` Worktree: ${worktreePath}`);\n }\n this.logger.info(`${BOLD}${'═'.repeat(60)}${RESET}\\n`);\n\n result = { exitCode: 0, output: this.outputLines.join('\\n') };\n }\n } catch (error) {\n runError = error;\n const activeRepairJob = activeRepair?.jobs.find((job) => job.jobName === activeJob);\n if (registryRun && activeRepair && activeJob && activeRepairJob?.status === 'running' && !dryRun) {\n await this.repairService.finishJob(\n registryRun.runDir,\n activeRepair,\n activeJob,\n error instanceof WorkflowInterruptedError || this.isInterrupted() ? 'interrupted' : 'failed',\n );\n }\n if (error instanceof WorkflowInterruptedError || this.isInterrupted()) {\n if (activeJob) {\n failedJob ??= activeJob;\n failureReason ??= `Workflow interrupted at job \"${activeJob}\"`;\n }\n result = this.createInterruptedResult();\n } else {\n throw error;\n }\n } finally {\n if (registryRun && !(dryRun && input.recovery)) {\n await this.registry.markFinalizing(registryRun);\n }\n\n if (\n shouldRunSuccessCompletionHooks &&\n result?.exitCode === 0 &&\n useWorktree &&\n workflow.worktree?.beforeCompleted &&\n !dryRun &&\n worktreePath\n ) {\n workflowEnv[WORKFLOW_PHASE_ENV] = 'worktree-before-completed';\n this.logger.info(`\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}beforeCompleted${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n const hookOk = await this.worktreeService.runHook(\n workflow.worktree.beforeCompleted,\n worktreePath,\n workflowEnv,\n inputs,\n secrets,\n { runner, cliAgent: input.cliAgent, dryRun, continueOnError },\n );\n\n if (!hookOk) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n } else {\n this.logger.error(`\\n${RED}${BOLD}worktree beforeCompleted hook failed${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n }\n }\n\n // Not for a delegating process. It started nothing: the run it handed to\n // the launcher registers, works and cleans up on its own, in its own\n // terminal. Running cleanup here fires every `post:` step against a run\n // that has barely begun, seconds after launch, on whatever stdio this\n // process happens to own -- which for the Pi extension is the user's TUI.\n if (workflow.post && !delegated) {\n // The workflow-level interruption remains authoritative for the final\n // outcome, but cleanup steps are a new execution phase and must not\n // inherit the cancelled job's StepRunner state.\n this.stepRunner.resetInterruption();\n // Post cleanup runs in `finally`, so it must be told how the run settled.\n // run.json is not finalized until after this block, so env is the only source.\n const settled = this.resolveRunOutcome(result, runError);\n workflowEnv[WORKFLOW_PHASE_ENV] = 'post';\n workflowEnv[WORKFLOW_EXIT_CODE_ENV] = String(settled.exitCode);\n workflowEnv[WORKFLOW_OUTCOME_ENV] = settled.outcome;\n workflowEnv[WORKFLOW_FAILED_JOB_ENV] = failedJob ?? '';\n const postBlock = workflow.post;\n try {\n const postResult = await this.recordPhase(progress, POST_PHASE_JOB, () =>\n this.runPostBlock(postBlock, workflowEnv, inputs, secrets, {\n runner,\n cliAgent: input.cliAgent,\n dryRun,\n continueOnError,\n progress,\n workflowDir,\n }),\n );\n\n if (!postResult) {\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_POST_FAILED_TEXT}${RESET}`);\n if (!result || result.exitCode === 0 || result.exitCode === WORKFLOW_SKIPPED_EXIT_CODE) {\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n }\n } catch (postError) {\n runError ??= postError;\n this.logger.error(`\\n${RED}${BOLD}${WORKFLOW_POST_FAILED_TEXT}${RESET}`);\n if (!result || result.exitCode === 0 || result.exitCode === WORKFLOW_SKIPPED_EXIT_CODE) {\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n }\n }\n\n if (\n shouldRunSuccessCompletionHooks &&\n result?.exitCode === 0 &&\n useWorktree &&\n workflow.worktree?.afterCompleted &&\n !dryRun &&\n !keepWorktree\n ) {\n workflowEnv[WORKFLOW_PHASE_ENV] = 'worktree-after-completed';\n this.logger.info(`\\n ${BLUE}${BOLD}worktree${RESET} ${BOLD}afterCompleted${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n const hookOk = await this.worktreeService.runHook(\n workflow.worktree.afterCompleted,\n originalDir,\n workflowEnv,\n inputs,\n secrets,\n { runner, cliAgent: input.cliAgent, dryRun, continueOnError },\n );\n\n if (!hookOk) {\n if (this.isInterrupted()) {\n result = this.createInterruptedResult();\n } else {\n this.logger.error(`\\n${RED}${BOLD}worktree afterCompleted hook failed${RESET}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n }\n }\n\n if (shouldRemoveWorktreeOnExit && worktreePath) {\n await this.worktreeService.removeWorktree(originalDir, worktreePath);\n }\n\n if (result) {\n result = { ...result, output: this.outputLines.join('\\n') };\n }\n\n if (registryRun && !(dryRun && input.recovery)) {\n const finalizedRecord = await this.finalizeRegistryRun(registryRun, result, runError, {\n failedJob,\n failureReason,\n fixLoopCycle: persistedFixLoopCycle,\n originalRepoPath: worktreePath ? originalDir : undefined,\n worktreeBranch: worktreeBranch ?? undefined,\n worktreePath: worktreePath ?? undefined,\n });\n workflowEnv[WORKFLOW_PHASE_ENV] = 'terminal';\n await this.logger.event?.(finalizedRecord.stage === ERROR_STAGE ? 'error' : 'info', 'workflow.run.finished', {\n attributes: this.buildLifecycleAttributes(workflowEnv, {\n 'workflow.duration_ms': Math.max(\n 0,\n Date.parse(finalizedRecord.finishedAt ?? finalizedRecord.startedAt) -\n Date.parse(finalizedRecord.startedAt),\n ),\n 'workflow.exit_code': finalizedRecord.exitCode ?? WORKFLOW_FAILED_EXIT_CODE,\n 'workflow.outcome': finalizedRecord.outcome ?? OUTCOME_FAILED,\n }),\n exception: runError instanceof Error ? runError : undefined,\n });\n\n if (input.statusFile) {\n try {\n await this.writeWorkflowStatusFile(input.statusFile, finalizedRecord);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger.error(`\\n${RED}${BOLD}Workflow status-file write failed${RESET}: ${message}`);\n result = { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n }\n }\n }\n\n return result ?? { exitCode: WORKFLOW_FAILED_EXIT_CODE, output: this.outputLines.join('\\n') };\n }\n\n /**\n * Ephemeral paths let recovery dry runs assemble prompts against copied\n * evidence without moving or writing the terminal registry directory.\n */\n private async createRecoveryDryRunHandle(input: RunWorkflowInput, workspace: string): Promise<WorkflowRunHandle> {\n if (!input.recovery) throw new Error('Recovery dry-run state is missing.');\n const runDir = getOrThrow(await this.runtime.fs.createTempDir(DRY_RUN_ARTIFACT_PREFIX, this.runtime.ioContext));\n return {\n changelogPath: resolve(runDir, 'changelog.md'),\n contextPath: resolve(runDir, 'context.md'),\n displayName: input.name ?? input.recovery.runKey,\n pauseRequestPath: resolve(runDir, 'pause-request.json'),\n recordPath: resolve(runDir, 'run.json'),\n runDir,\n runId: `dry-run-${input.recovery.runKey}`,\n runKey: input.recovery.runKey,\n stopRequestPath: resolve(runDir, 'stop-request.json'),\n workspace,\n };\n }\n\n private async writeDryRunWorkflowArtifact(\n workflow: Workflow,\n jobOrder: string[],\n promptAssemblies: DryRunPromptAssembly[],\n ): Promise<string> {\n const promptsByJob = new Map<string, DryRunPromptAssembly[]>();\n for (const assembly of promptAssemblies) {\n const existing = promptsByJob.get(assembly.jobName) ?? [];\n existing.push(assembly);\n promptsByJob.set(assembly.jobName, existing);\n }\n\n const jobs = Object.fromEntries(\n Object.entries(workflow.jobs).map(([jobName, job]) => {\n const assemblies = promptsByJob.get(jobName);\n if (!assemblies?.length) {\n return [jobName, job];\n }\n\n return [\n jobName,\n {\n ...job,\n 'system-prompt': assemblies[0].prompt,\n 'x-dry-run-prompt-variants': assemblies.map(({ matrix, prompt }) => ({ matrix, prompt })),\n },\n ];\n }),\n );\n const artifact = {\n ...workflow,\n 'x-dry-run': {\n 'selected-job-order': jobOrder,\n },\n jobs,\n };\n const artifactDir = getOrThrow(\n await this.runtime.fs.createTempDir(DRY_RUN_ARTIFACT_PREFIX, this.runtime.ioContext),\n );\n const artifactPath = resolve(artifactDir, DRY_RUN_ARTIFACT_FILENAME);\n getOrThrow(\n await this.runtime.fs.writeFile(\n artifactPath,\n serializeYaml(artifact, { lineWidth: -1, noRefs: true }),\n this.runtime.ioContext,\n ),\n );\n await this.runtime.workflowHost.setMode(artifactPath, 0o600);\n return artifactPath;\n }\n\n /**\n * Resolve the effective exit code and outcome for a settled run.\n * Shared by the post block env and registry finalization so they cannot drift.\n */\n private resolveRunOutcome(\n result: RunWorkflowResult | null,\n runError: unknown,\n ): { exitCode: number; outcome: WorkflowOutcome } {\n const interrupted = result?.exitCode === INTERRUPTED_EXIT_CODE || runError instanceof WorkflowInterruptedError;\n const exitCode = result?.exitCode ?? (interrupted ? INTERRUPTED_EXIT_CODE : WORKFLOW_FAILED_EXIT_CODE);\n const outcome =\n exitCode === 0\n ? OUTCOME_SUCCESS\n : exitCode === WORKFLOW_SKIPPED_EXIT_CODE\n ? OUTCOME_SKIPPED\n : interrupted || this.isInterrupted()\n ? OUTCOME_INTERRUPTED\n : OUTCOME_FAILED;\n return { exitCode, outcome };\n }\n\n /**\n * Persist the terminal stage for a workflow run after execution completes.\n */\n private async finalizeRegistryRun(\n registryRun: WorkflowRunHandle,\n result: RunWorkflowResult | null,\n runError: unknown,\n recoveryMetadata: {\n failedJob?: string;\n failureReason?: string;\n fixLoopCycle?: number;\n originalRepoPath?: string;\n worktreeBranch?: string;\n worktreePath?: string;\n } = {},\n ): Promise<WorkflowRunRecord> {\n const { exitCode, outcome } = this.resolveRunOutcome(result, runError);\n const stage = exitCode === 0 || exitCode === WORKFLOW_SKIPPED_EXIT_CODE ? COMPLETED_STAGE : ERROR_STAGE;\n // A failed run says why when it knows, such as the outputs a job did not\n // write; its last output line only names the job.\n const errorMessage =\n runError instanceof Error\n ? runError.message\n : exitCode === WORKFLOW_FAILED_EXIT_CODE\n ? (recoveryMetadata.failureReason ?? this.lastMeaningfulOutputLine())\n : undefined;\n\n const finalizedRun = await this.registry.finalizeRun(registryRun, {\n errorMessage,\n exitCode,\n ...recoveryMetadata,\n outcome,\n stage,\n });\n\n return await this.registry.readRunRecord(finalizedRun.recordPath);\n }\n\n private buildLifecycleAttributes(\n workflowEnv: Record<string, string>,\n attributes: Record<string, string | number | boolean> = {},\n ): Record<string, string | number | boolean> {\n return {\n 'workflow.id': workflowEnv.WORKFLOW_ID ?? '',\n 'workflow.name': workflowEnv.WORKFLOW_NAME ?? '',\n 'workflow.workspace': workflowEnv.WORKFLOW_WORKSPACE ?? DEFAULT_WORKSPACE,\n 'workflow.run.id': workflowEnv.WORKFLOW_RUN_ID ?? '',\n 'workflow.run.key': workflowEnv.WORKFLOW_RUN_KEY ?? '',\n 'workflow.phase': workflowEnv[WORKFLOW_PHASE_ENV] ?? WORKFLOW_PHASE,\n ...attributes,\n };\n }\n\n /**\n * Write a terminal workflow record to a caller-provided completion file.\n */\n private async writeWorkflowStatusFile(statusFile: string, record: WorkflowRunRecord): Promise<void> {\n const targetPath = resolve(statusFile);\n const tempPath = `${targetPath}.${this.runtime.workflowHost.processId}.${Date.now()}.tmp`;\n\n try {\n getOrThrow(await this.runtime.fs.createDir(dirname(targetPath), { recursive: true }, this.runtime.ioContext));\n getOrThrow(\n await this.runtime.fs.writeFile(tempPath, `${JSON.stringify(record, null, 2)}\\n`, this.runtime.ioContext),\n );\n getOrThrow(await this.runtime.fs.renameFile(tempPath, targetPath, this.runtime.ioContext));\n } catch (error) {\n try {\n getOrThrow(await this.runtime.fs.remove(tempPath, undefined, this.runtime.ioContext));\n } catch (cleanupError) {\n this.logger.warn(\n `${YELLOW}warn${RESET} status-file temp cleanup failed: ${\n cleanupError instanceof Error ? cleanupError.message : String(cleanupError)\n }`,\n );\n }\n throw error;\n }\n }\n\n private async appendRepairReferenceToContext(contextPath: string, repair: WorkflowRepairRecord): Promise<void> {\n const existing = getOrThrow(await this.runtime.fs.readTextFile(contextPath, this.runtime.ioContext));\n const scope = repair.scopeJobs.length > 0 ? repair.scopeJobs.join(' -> ') : '(none)';\n const repairBlock = [\n '---',\n `## Repair ${repair.repairId} (cycle ${repair.fixCycle})`,\n `- Issue: ${repair.issueFile}`,\n `- Repair: issues/${repair.repairId}/repair.json`,\n `- Status: ${repair.status}`,\n `- Restart from: ${repair.restartFrom}`,\n `- Verifier: ${repair.verificationJob}`,\n `- Scope: ${scope}`,\n ].join('\\n');\n getOrThrow(await this.runtime.fs.writeFile(contextPath, `${existing}\\n\\n${repairBlock}`, this.runtime.ioContext));\n }\n\n /**\n * Why a proceed.md request cannot be honored, or undefined when it can.\n *\n * Every rejection is advisory: the run falls back to plain job order, which is\n * always a correct way to finish a repair. Failing the run over a bad forward\n * jump would turn an optimization into a hazard.\n */\n private proceedRejectionReason(request: {\n activeRepair: WorkflowRepairRecord | null;\n currentIndex: number;\n invalidTarget?: string;\n jobName: string;\n jobUsesRepair: boolean;\n target?: string;\n targetIndex: number;\n verifierIndex: number;\n }): string | undefined {\n if (!request.jobUsesRepair || !request.activeRepair) {\n return 'no repair is active for this job';\n }\n if (request.jobName === request.activeRepair.verificationJob) {\n return 'the verifying job has no forward targets';\n }\n if (request.invalidTarget) {\n return `\"${request.invalidTarget}\" is not in the workflow job order`;\n }\n if (!request.target) {\n return `no \"${PROCEED_TO_KEY}\" frontmatter field`;\n }\n if (request.targetIndex <= request.currentIndex) {\n return `\"${request.target}\" does not come after \"${request.jobName}\"`;\n }\n if (request.targetIndex > request.verifierIndex) {\n return `\"${request.target}\" comes after the verifying job \"${request.activeRepair.verificationJob}\"`;\n }\n return undefined;\n }\n\n private async appendProceedNoteToContext(\n contextPath: string,\n repairId: string,\n fromJob: string,\n toJob: string,\n skippedJobs: string[],\n ): Promise<void> {\n const existing = getOrThrow(await this.runtime.fs.readTextFile(contextPath, this.runtime.ioContext));\n const skipped = skippedJobs.length > 0 ? skippedJobs.join(', ') : '(none)';\n const note = `- Proceeded: \"${fromJob}\" -> \"${toJob}\" (repair ${repairId}, skipped: ${skipped})`;\n getOrThrow(await this.runtime.fs.writeFile(contextPath, `${existing}\\n${note}`, this.runtime.ioContext));\n }\n\n private setRepairEnvironment(\n workflowEnv: Record<string, string>,\n runDir: string,\n repair: WorkflowRepairRecord,\n ): void {\n const repairDir = resolve(runDir, 'issues', repair.repairId);\n workflowEnv[WORKFLOW_ACTIVE_REPAIR_ID_ENV] = repair.repairId;\n workflowEnv[WORKFLOW_ACTIVE_REPAIR_DIR_ENV] = repairDir;\n workflowEnv[WORKFLOW_ACTIVE_REPAIR_FILE_ENV] = resolve(repairDir, 'repair.json');\n workflowEnv[WORKFLOW_ACTIVE_ISSUE_FILE_ENV] = resolve(runDir, repair.issueFile);\n }\n\n private clearRepairEnvironment(workflowEnv: Record<string, string>): void {\n delete workflowEnv[WORKFLOW_ACTIVE_REPAIR_ID_ENV];\n delete workflowEnv[WORKFLOW_ACTIVE_REPAIR_DIR_ENV];\n delete workflowEnv[WORKFLOW_ACTIVE_REPAIR_FILE_ENV];\n delete workflowEnv[WORKFLOW_ACTIVE_ISSUE_FILE_ENV];\n }\n\n private async updateRepairReferenceStatus(\n contextPath: string,\n repairId: string,\n status: WorkflowRepairRecord['status'],\n ): Promise<void> {\n const content = getOrThrow(await this.runtime.fs.readTextFile(contextPath, this.runtime.ioContext));\n const heading = `## Repair ${repairId} `;\n const start = content.indexOf(heading);\n if (start < 0) {\n return;\n }\n const nextBlock = content.indexOf('\\n---\\n', start);\n const end = nextBlock < 0 ? content.length : nextBlock;\n const block = content.slice(start, end);\n const updatedBlock = block.replace(/^- Status: .*$/m, `- Status: ${status}`);\n if (block !== updatedBlock) {\n getOrThrow(\n await this.runtime.fs.writeFile(\n contextPath,\n `${content.slice(0, start)}${updatedBlock}${content.slice(end)}`,\n this.runtime.ioContext,\n ),\n );\n }\n }\n\n /**\n * Put a `workflow-mcp` launcher in the run directory, first on the run's\n * PATH, so agents record step decisions with this engine whatever their\n * shell's PATH and wherever the engine is installed. The decision\n * instructions also name it by path, for harnesses that reset PATH.\n */\n private async installStepCli(runDir: string, workflowEnv: Record<string, string>): Promise<void> {\n let cliPath: string;\n try {\n cliPath = this.resolveCliPath();\n } catch (error) {\n this.logger.warn(\n `${YELLOW}workflow-mcp step launcher not installed${RESET}: ${error instanceof Error ? error.message : String(error)}`,\n );\n return;\n }\n const binDir = resolve(runDir, STEP_CLI_DIRECTORY);\n const launcher = resolve(binDir, STEP_CLI_NAME);\n const runAsNode = this.runtime.workflowHost.isElectron ? 'ELECTRON_RUN_AS_NODE=1 ' : '';\n getOrThrow(await this.runtime.fs.createDir(binDir, { recursive: true }, this.runtime.ioContext));\n getOrThrow(\n await this.runtime.fs.writeFile(\n launcher,\n `#!/bin/sh\\n${runAsNode}exec ${escapeShellArg(this.runtime.workflowHost.executablePath)} ${escapeShellArg(cliPath)} \"$@\"\\n`,\n this.runtime.ioContext,\n ),\n );\n await this.runtime.workflowHost.setMode(launcher, 0o755);\n workflowEnv.PATH = `${binDir}:${workflowEnv.PATH ?? this.runtime.baseEnvironment.PATH ?? ''}`;\n }\n\n private resolveCliPath(): string {\n const cliPath = this.runtime.workflowHost.cliPath;\n if (!cliPath) throw new Error('The workflow CLI entry was not admitted by this host.');\n return cliPath;\n }\n\n private buildLaunchEnvironment(launcher?: WorkflowLauncherType): NodeJS.ProcessEnv {\n const env = { ...this.runtime.baseEnvironment };\n delete env[CMUX_SURFACE_ID_ENV];\n delete env[CMUX_WORKSPACE_ID_ENV];\n delete env[TMUX_PANE_ENV];\n delete env[WORKFLOW_LAUNCHER_TYPE_ENV];\n delete env[WORKFLOW_TMUX_SESSION_NAME_ENV];\n if (launcher) env[WORKFLOW_LAUNCHER_ENV] = launcher;\n // A delegated runner re-issues its own per-step status files; never pass a parent's through.\n delete env[WORKFLOW_STATUS_FILE_ENV];\n return env;\n }\n\n /**\n * Create a short command for launcher integrations such as cmux.\n *\n * The real invocation is written to a temp script so user-controlled values\n * like prompts are parsed by only the script shell, not by every launch layer.\n */\n private async createLaunchScriptCommand(\n input: RunWorkflowInput,\n workflowPath: string,\n workflow: Workflow,\n ): Promise<string> {\n const launchDir = getOrThrow(await this.runtime.fs.createTempDir('workflow-mcp-launch-', this.runtime.ioContext));\n const scriptPath = resolve(launchDir, 'run-workflow.sh');\n const innerCommand = this.buildLaunchCliCommand(input, workflowPath, workflow);\n const script = [\n '#!/bin/sh',\n ...(await this.buildLauncherOriginExports()),\n 'script_path=$0',\n 'rm -f \"$script_path\"',\n 'rmdir \"$(dirname \"$script_path\")\" 2>/dev/null || true',\n `exec ${innerCommand}`,\n '',\n ].join('\\n');\n\n await this.runtime.workflowHost.writeExclusive(scriptPath, script);\n return `sh ${escapeShellArg(scriptPath)}`;\n }\n\n private async buildLauncherOriginExports(): Promise<string[]> {\n const exports: string[] = [];\n if (this.runtime.baseEnvironment[CMUX_WORKSPACE_ID_ENV]) {\n exports.push(\n `export ${WORKFLOW_LAUNCHER_ORIGIN_WORKSPACE_ID_ENV}=${escapeShellArg(this.runtime.baseEnvironment[CMUX_WORKSPACE_ID_ENV])}`,\n );\n }\n if (this.runtime.baseEnvironment[CMUX_SURFACE_ID_ENV]) {\n exports.push(\n `export ${WORKFLOW_LAUNCHER_ORIGIN_SURFACE_ID_ENV}=${escapeShellArg(this.runtime.baseEnvironment[CMUX_SURFACE_ID_ENV])}`,\n );\n }\n const paneId = this.runtime.baseEnvironment[TMUX_PANE_ENV];\n if (paneId) {\n exports.push(`export ${WORKFLOW_LAUNCHER_ORIGIN_PANE_ID_ENV}=${escapeShellArg(paneId)}`);\n const identity = await this.readTmuxIdentity(paneId);\n if (identity?.sessionId) {\n exports.push(`export ${WORKFLOW_LAUNCHER_ORIGIN_SESSION_ID_ENV}=${escapeShellArg(identity.sessionId)}`);\n }\n }\n return exports;\n }\n\n private async resolveLauncherMetadata(): Promise<WorkflowLauncherMetadata | undefined> {\n // RMUX hosting keeps the legacy native discriminator and socket contract,\n // so the run records its detached host pid rather than an internal RMUX target.\n if (this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_TYPE_ENV] === NATIVE_LAUNCHER_TYPE) {\n return { pid: this.runtime.workflowHost.processId, type: NATIVE_LAUNCHER_TYPE };\n }\n if (this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_TYPE_ENV] === 'tmux') {\n const paneId = this.runtime.baseEnvironment[TMUX_PANE_ENV];\n const identity = paneId ? await this.readTmuxIdentity(paneId) : undefined;\n const sessionName = identity?.sessionName ?? this.runtime.baseEnvironment[WORKFLOW_TMUX_SESSION_NAME_ENV];\n if (!sessionName) return undefined;\n return {\n originPaneId: this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_ORIGIN_PANE_ID_ENV],\n originSessionId: this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_ORIGIN_SESSION_ID_ENV],\n originSurfaceId: this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_ORIGIN_SURFACE_ID_ENV],\n originWorkspaceId: this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_ORIGIN_WORKSPACE_ID_ENV],\n paneId: identity?.paneId ?? paneId,\n sessionId: identity?.sessionId,\n sessionName,\n type: 'tmux',\n windowId: identity?.windowId,\n };\n }\n\n const workspaceId = this.runtime.baseEnvironment[CMUX_WORKSPACE_ID_ENV];\n if (!workspaceId) return undefined;\n return {\n originSurfaceId: this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_ORIGIN_SURFACE_ID_ENV],\n originWorkspaceId: this.runtime.baseEnvironment[WORKFLOW_LAUNCHER_ORIGIN_WORKSPACE_ID_ENV],\n surfaceId: this.runtime.baseEnvironment[CMUX_SURFACE_ID_ENV],\n type: 'cmux',\n workspaceId,\n };\n }\n\n private async readTmuxIdentity(\n paneId: string,\n ): Promise<{ paneId: string; sessionId: string; sessionName: string; windowId: string } | undefined> {\n try {\n const output = (\n await workflowShellOutput(\n this.runtime,\n `tmux display-message -p -t ${escapeShellArg(paneId)} ${escapeShellArg('#{session_id}\\t#{session_name}\\t#{window_id}\\t#{pane_id}')}`,\n )\n ).trim();\n const [sessionId, sessionName, windowId, resolvedPaneId] = output.split('\\t');\n if (!sessionId || !sessionName || !windowId || !resolvedPaneId) return undefined;\n return { paneId: resolvedPaneId, sessionId, sessionName, windowId };\n } catch (error) {\n this.logger.warn(`Unable to resolve tmux identity for ${paneId}: ${String(error)}`);\n return undefined;\n }\n }\n\n /**\n * Reconstruct the CLI command string for launch-command delegation,\n * adding --skip-launch to prevent infinite recursion.\n */\n private buildLaunchCliCommand(input: RunWorkflowInput, workflowPath: string, workflow: Workflow): string {\n const cliPath = this.resolveCliPath();\n const parts = ['node', escapeShellArg(cliPath), 'run-workflow', escapeShellArg(workflowPath), '--skip-launch'];\n const runner = this.resolveRunner(input, workflow);\n if (input.job) parts.push('--job', escapeShellArg(input.job));\n if (runner) parts.push('--runner', escapeShellArg(runner));\n if (input.command) parts.push('--command', escapeShellArg(input.command));\n if (input.choice) parts.push('--choice', escapeShellArg(input.choice));\n if (input.dryRun) parts.push('--dry-run');\n if (input.continueOnError) parts.push('--continue-on-error');\n if (input.keepWorktree) parts.push('--keep-worktree');\n if (input.prompt) parts.push('--prompt', escapeShellArg(input.prompt));\n if (input.name) parts.push('--name', escapeShellArg(input.name));\n if (input.workspace) parts.push('--workspace', escapeShellArg(input.workspace));\n if (input.secretFile) parts.push('--secret-file', escapeShellArg(input.secretFile));\n if (input.statusFile) parts.push('--status-file', escapeShellArg(input.statusFile));\n if (input.inputs) {\n for (const [key, val] of Object.entries(input.inputs)) {\n parts.push('--input', escapeShellArg(`${key}=${val}`));\n }\n }\n if (input.env) {\n for (const [key, val] of Object.entries(input.env)) {\n parts.push('--env', escapeShellArg(`${key}=${val}`));\n }\n }\n return parts.join(' ');\n }\n\n /**\n * Return the last non-empty log line for failed run metadata.\n */\n private lastMeaningfulOutputLine(): string | undefined {\n return [...this.outputLines].reverse().find((line) => line.trim().length > 0);\n }\n\n /**\n * Run pre-services and setup steps before job execution begins.\n */\n /**\n * Run the `launch-command` delegation and wait for it to settle.\n *\n * Asynchronous rather than `execSync` because this is not always the CLI. In\n * the Pi extension the workflow engine runs inside the TUI's own process, and\n * a synchronous spawn freezes its event loop for the whole launch: measured at\n * roughly a second, most of it `pnpm exec` resolution, during which nothing\n * repaints and no keystroke is read. `run()` is already async, so blocking\n * bought nothing to begin with.\n */\n private spawnLaunchCommand(\n shell: string,\n options: { cwd: string; env: NodeJS.ProcessEnv },\n ): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n return new Promise((settle) => {\n // `shell: true` keeps `execSync`'s contract: the launch-command is a shell\n // string with its own quoting and substitutions, not an argv vector.\n const child = this.runtime.workflowHost.spawn(shell, [], {\n shell: true,\n cwd: options.cwd,\n env: options.env,\n stdio: this.launchStdio,\n });\n let stdout = '';\n let stderr = '';\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n child.on('error', (error) => {\n settle({ exitCode: WORKFLOW_FAILED_EXIT_CODE, stdout: stdout.trim(), stderr: error.message });\n });\n child.on('close', (code, signal) => {\n // A signalled launcher has no exit code; treat it as a failed launch\n // rather than reporting the success that `code ?? 0` would imply.\n const exitCode = code ?? (signal ? WORKFLOW_FAILED_EXIT_CODE : 0);\n settle({ exitCode, stdout: stdout.trim(), stderr: stderr.trim() });\n });\n });\n }\n\n /**\n * Run a phase block, recording its start and however it settles.\n *\n * Wraps rather than annotating each exit: between them the two blocks return\n * from six places and can also throw, and a phase that starts without ever\n * finishing reads as permanently running to everything downstream.\n */\n private async recordPhase(\n progress: WorkflowProgressService | undefined,\n name: string,\n run: () => Promise<boolean>,\n ): Promise<boolean> {\n // `record` rather than `jobStarted`: a phase has no position in the job\n // order, and passing 0-of-1 would render a counter that means nothing.\n await progress?.record({ type: 'job', status: 'running', job: name });\n try {\n const ok = await run();\n await progress?.jobFinished(name, ok ? 'completed' : 'failed');\n return ok;\n } catch (error) {\n await progress?.jobFinished(name, 'failed', error instanceof Error ? error.message : String(error));\n throw error;\n }\n }\n\n private async runPreBlock(\n pre: import('../../schemas/workflowEngine').PreBlock,\n baseEnv: Record<string, string>,\n inputs: Map<string, string>,\n secrets: Map<string, string>,\n options: {\n cliAgent?: string;\n runner?: string;\n dryRun: boolean;\n continueOnError: boolean;\n progress?: WorkflowProgressService;\n stopRequestPath?: string;\n workflowDir: string;\n onStepStarted?: (stepName: string, index: number, total: number) => Promise<void> | void;\n onExecutionStateChange?: (state: 'paused' | 'resumed', stepName: string) => Promise<void> | void;\n },\n ): Promise<boolean> {\n this.logger.info(`\\n ${BLUE}${BOLD}pre${RESET} ${BOLD}Pre-conditions${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n // Ensure context dir exists\n if (baseEnv.CONTEXT_FILE) {\n const contextDir = dirname(resolve(options.workflowDir, baseEnv.CONTEXT_FILE));\n getOrThrow(await this.runtime.fs.createDir(contextDir, { recursive: true }, this.runtime.ioContext));\n }\n\n // Start background services\n if (pre.services && pre.services.length > 0) {\n this.logger.info(`\\n ${BLUE}${BOLD}services${RESET}`);\n\n for (const service of pre.services) {\n const svc = await this.serviceManager.startService(service, baseEnv, options.workflowDir, options.dryRun);\n if (svc) {\n if (service['ready-check'] && !options.dryRun) {\n const ready = await this.serviceManager.waitForServiceReady(\n service,\n options.workflowDir,\n baseEnv,\n () => this.interruptedSignal !== null,\n );\n if (this.isInterrupted()) {\n return false;\n }\n if (!ready && !options.continueOnError) {\n await this.serviceManager.stopAll();\n return false;\n }\n }\n }\n }\n\n // Brief pause to let services initialize\n if (!options.dryRun && this.serviceManager.getRunningServices().length > 0) {\n await this.waitForServiceStartup();\n }\n }\n\n // Run setup steps\n if (pre.steps && pre.steps.length > 0) {\n this.logger.info(`\\n ${BLUE}${BOLD}setup${RESET}`);\n\n const stepContext = {\n inputs,\n matrix: {} as import('../../schemas/workflowEngine').MatrixEntry,\n secrets,\n env: baseEnv,\n };\n\n for (const [index, step] of pre.steps.entries()) {\n const stepName = step.name ?? `step ${index + 1}`;\n await options.onStepStarted?.(stepName, index, pre.steps.length);\n await options.progress?.stepStarted(PRE_PHASE_JOB, stepName, index, pre.steps.length);\n let failure: string | undefined;\n const stepOptions = {\n ...options,\n onExecutionStateChange: async (state: 'paused' | 'resumed', pausedStepName: string) => {\n await options.onExecutionStateChange?.(state, pausedStepName);\n await options.progress?.stepFinished(PRE_PHASE_JOB, pausedStepName, state);\n },\n onFailure: (reason: string) => {\n failure = reason;\n },\n onExecutionStarted: (ref: StepExecutionRef) =>\n options.progress?.stepExecutionStarted(PRE_PHASE_JOB, stepName, ref),\n };\n const ok = await this.stepRunner.runStep(step, stepContext, stepOptions);\n await options.progress?.stepFinished(\n PRE_PHASE_JOB,\n stepName,\n ok ? 'completed' : 'failed',\n ok ? undefined : failure,\n );\n if (!ok) {\n this.logger.error(`\\n ${RED}Pre-condition step failed${RESET}`);\n await this.serviceManager.stopAll();\n return false;\n }\n }\n }\n\n this.logger.info(`\\n ${GREEN}Pre-conditions ready${RESET}`);\n return true;\n }\n\n /**\n * Run post-cleanup services and steps after the main workflow path settles.\n */\n private async runPostBlock(\n post: import('../../schemas/workflowEngine').PreBlock,\n baseEnv: Record<string, string>,\n inputs: Map<string, string>,\n secrets: Map<string, string>,\n options: {\n cliAgent?: string;\n runner?: string;\n dryRun: boolean;\n continueOnError: boolean;\n progress?: WorkflowProgressService;\n workflowDir: string;\n },\n ): Promise<boolean> {\n this.logger.info(`\\n ${BLUE}${BOLD}post${RESET} ${BOLD}Cleanup${RESET}`);\n this.logger.info(` ${'─'.repeat(50)}`);\n\n await this.serviceManager.stopAll();\n\n try {\n if (post.services && post.services.length > 0) {\n this.logger.info(`\\n ${BLUE}${BOLD}services${RESET}`);\n\n for (const service of post.services) {\n const svc = await this.serviceManager.startService(service, baseEnv, options.workflowDir, options.dryRun);\n if (svc && service['ready-check'] && !options.dryRun) {\n const ready = await this.serviceManager.waitForServiceReady(\n service,\n options.workflowDir,\n baseEnv,\n () => false,\n );\n if (!ready && !options.continueOnError) {\n return false;\n }\n }\n }\n\n if (!options.dryRun && this.serviceManager.getRunningServices().length > 0) {\n await this.waitForServiceStartup();\n }\n }\n\n if (post.steps && post.steps.length > 0) {\n this.logger.info(`\\n ${BLUE}${BOLD}cleanup${RESET}`);\n\n const stepContext = {\n inputs,\n matrix: {} as import('../../schemas/workflowEngine').MatrixEntry,\n secrets,\n env: baseEnv,\n };\n\n for (const [index, step] of post.steps.entries()) {\n const stepName = step.name ?? `step ${index + 1}`;\n await options.progress?.stepStarted(POST_PHASE_JOB, stepName, index, post.steps.length);\n let failure: string | undefined;\n const ok = await this.stepRunner.runStep(step, stepContext, {\n ...options,\n onFailure: (reason: string) => {\n failure = reason;\n },\n onExecutionStarted: (ref: StepExecutionRef) =>\n options.progress?.stepExecutionStarted(POST_PHASE_JOB, stepName, ref),\n });\n await options.progress?.stepFinished(\n POST_PHASE_JOB,\n stepName,\n ok ? 'completed' : 'failed',\n ok ? undefined : failure,\n );\n if (!ok) {\n this.logger.error(`\\n ${RED}Post-cleanup step failed${RESET}`);\n return false;\n }\n }\n }\n\n this.logger.info(`\\n ${GREEN}Cleanup complete${RESET}`);\n return true;\n } finally {\n await this.serviceManager.stopAll();\n }\n }\n}\n\n/**\n * Build a runner safe to embed in a process whose stdout belongs to something\n * else: the Pi extension, where stdout is the TUI's screen and stdin its\n * keyboard, or the stdio MCP server, where stdout is the JSON-RPC stream.\n *\n * Silencing the console costs nothing. Every line still reaches `outputLines`,\n * which is what `RunWorkflowResult.output` returns, so the caller sees the same\n * text it always did; it just arrives as a value instead of as a side effect on\n * a shared terminal.\n *\n * A host that keeps its own record of the run passes `logger`, and gets every\n * line as it is written, including why a step failed. Its telemetry events\n * still reach the engine's own telemetry unless the host logger records them.\n */\nexport function createEmbeddedRunWorkflowService(\n dependencies: RunWorkflowDependencies,\n logger?: Logger,\n): RunWorkflowService {\n const silent = createWorkflowLogger({\n info: () => {},\n error: () => {},\n warn: () => {},\n });\n const host: Logger = logger\n ? {\n ...logger,\n ...(logger.event ? {} : silent.event ? { event: silent.event } : {}),\n ...(logger.flush ? {} : silent.flush ? { flush: silent.flush } : {}),\n }\n : silent;\n return new RunWorkflowService(host, {\n ...dependencies,\n launcherMetadata: dependencies.launcherMetadata ?? {\n pid: dependencies.runtime.workflowHost.processId,\n type: 'native',\n },\n launchStdio: 'pipe',\n ownsTerminal: false,\n });\n}\n","/**\n * RecoverWorkflowService\n *\n * DESIGN PATTERNS:\n * - Service pattern for business logic encapsulation\n * - Single responsibility principle\n *\n * CODING STANDARDS:\n * - Use async/await for asynchronous operations\n * - Throw descriptive errors for error cases\n * - Keep methods focused and well-named\n * - Document complex logic with comments\n *\n * AVOID:\n * - Mixing concerns (keep focused on single domain)\n * - Direct tool implementation (services should be tool-agnostic)\n */\n\nimport { pathExists } from '@agimon-ai/po-core/platform';\n\nimport { RunWorkflowService } from '../RunWorkflowService';\nimport { WorkflowParserService } from '../WorkflowParserService';\nimport { WorkflowRegistryService } from '../WorkflowRegistryService';\nimport { WorkflowRepairService } from '../WorkflowRepairService';\nimport type { WorkflowRuntimeContext } from '../workflowRuntime/type';\nimport type { RecoverWorkflowInput, RecoverWorkflowResult } from './types';\n\nconst ERROR_STAGE = 'error';\nconst FIX_FRONTMATTER_DELIMITER = '---';\nconst FIX_RESTART_FROM_KEY = 'restart-from';\nconst FIX_STATUS_KEY = 'status';\nconst FIX_TERMINAL_TARGET = 'stop';\nconst REPAIR_TRIAGE_JOB_NAME = 'repair-triage';\nconst PI_SESSION_ENV = 'PI_SESSION_ID';\n\n/**\n * RecoverWorkflowService reconstructs and replays failed workflow runs.\n */\nexport class RecoverWorkflowService {\n /**\n * Creates a new RecoverWorkflowService instance.\n *\n * A delegated replay gets the owner from its registry-issued recovery claim,\n * so a CLI caller cannot choose another Pi session's identity.\n */\n constructor(\n readonly runtime: WorkflowRuntimeContext,\n private registry = new WorkflowRegistryService(runtime),\n private runner = new RunWorkflowService(undefined, { registry, runtime }),\n private parser = new WorkflowParserService(runtime),\n private repairService = new WorkflowRepairService(runtime),\n ) {}\n\n /**\n * Recover a failed workflow run from registry metadata.\n */\n async recover(input: RecoverWorkflowInput): Promise<RecoverWorkflowResult> {\n return await this.recoverWithOwner(input);\n }\n\n /** Trusted embedding entry point; owner identity is never part of MCP/CLI input. */\n async recoverForSession(input: RecoverWorkflowInput, ownerSessionId: string): Promise<RecoverWorkflowResult> {\n return await this.recoverWithOwner(input, ownerSessionId);\n }\n\n private async recoverWithOwner(input: RecoverWorkflowInput, ownerSessionId?: string): Promise<RecoverWorkflowResult> {\n const record = await this.registry.readRunByKey(input.workspace, ERROR_STAGE, input.runKey);\n if (input.dryRun || record.dryRun) return await this.recoverClaimed(input, undefined, undefined, record);\n\n const claim = input.recoveryClaimId\n ? await this.registry.adoptRunRecoveryClaim(record.workspace, record.runKey, input.recoveryClaimId)\n : await this.registry.claimRunRecovery(record.workspace, record.runKey, ownerSessionId);\n try {\n if (!input.recoveryClaimId) {\n await this.registry.adoptRunRecoveryClaim(record.workspace, record.runKey, claim.claimId);\n }\n return await this.recoverClaimed(input, claim.claimId, claim.ownerSessionId, record);\n } catch (error) {\n await this.registry.releaseRunRecoveryClaim(record.workspace, record.runKey, claim.claimId);\n throw error;\n }\n }\n\n private async recoverClaimed(\n input: RecoverWorkflowInput,\n recoveryClaimId?: string,\n claimedOwnerSessionId?: string,\n failedRecord?: Awaited<ReturnType<WorkflowRegistryService['readRunByKey']>>,\n ): Promise<RecoverWorkflowResult> {\n const record = failedRecord ?? (await this.registry.readRunByKey(input.workspace, ERROR_STAGE, input.runKey));\n const activeRepair = record.activeRepairId\n ? await this.registry.readRunRepair(record.workspace, ERROR_STAGE, record.runKey, record.activeRepairId)\n : undefined;\n if (activeRepair && !['pending', 'active'].includes(activeRepair.status)) {\n throw new Error(\n `Workflow run \"${record.workspace}/${record.runKey}\" points to non-active repair ${activeRepair.repairId} (${activeRepair.status})`,\n );\n }\n\n const workflow = await this.parser.parseWorkflowFile(record.workflowPath);\n const repairTriageFailed = record.failedJob === REPAIR_TRIAGE_JOB_NAME && Boolean(workflow.repair);\n const fallbackRepairFailed = Boolean(\n activeRepair && !workflow.repair && record.failedJob && activeRepair.scopeJobs.includes(record.failedJob),\n );\n const terminalStopAuthorized = repairTriageFailed || fallbackRepairFailed;\n const terminalFixContent =\n activeRepair && !terminalStopAuthorized\n ? null\n : await this.registry.readRunFixContent(record.workspace, ERROR_STAGE, record.runKey);\n const terminalFix = terminalFixContent ? this.parseTerminalFix(terminalFixContent, terminalStopAuthorized) : {};\n if (terminalFix.terminal) {\n throw new Error(\n `Workflow run \"${record.workspace}/${record.runKey}\" has a terminal fix request and cannot be recovered`,\n );\n }\n const fixRestartFrom = terminalFix.restartFrom;\n const recoveredJob = activeRepair\n ? this.repairService.resolveRecoveryStart(activeRepair)\n : (fixRestartFrom ?? record.failedJob);\n\n if (!recoveredJob) {\n throw new Error(`Workflow run \"${record.workspace}/${record.runKey}\" does not include a recoverable failed job`);\n }\n\n if (record.worktreePath && !(await pathExists(this.runtime.fs, record.worktreePath, this.runtime.ioContext))) {\n throw new Error(`Recoverable worktree not found: ${record.worktreePath}`);\n }\n\n const runner = input.runner ?? record.runner ?? record.cliAgent;\n const cliAgent = runner === record.cliAgent ? record.cliAgent : undefined;\n const originalJob = fixRestartFrom && !activeRepair ? undefined : record.job;\n const jobOrder = this.parser.resolveJobOrder(workflow.jobs, originalJob ?? null);\n if (!jobOrder.includes(recoveredJob)) {\n throw new Error(\n `Workflow run \"${record.workspace}/${record.runKey}\" recovery target \"${recoveredJob}\" is not in the workflow job order`,\n );\n }\n\n const ownerSessionId = claimedOwnerSessionId?.trim();\n const envOverrides = ownerSessionId ? { [PI_SESSION_ENV]: ownerSessionId } : undefined;\n return await this.runner.run({\n cliAgent,\n runner,\n command: record.command,\n choice: record.choice,\n workflowPath: record.workflowPath,\n job: recoveredJob,\n inputs: record.inputs,\n env: envOverrides ? { ...record.env, ...envOverrides } : record.env,\n secretFile: record.secretFile,\n dryRun: input.dryRun ?? record.dryRun,\n continueOnError: record.continueOnError,\n keepWorktree: record.keepWorktree,\n prompt: record.prompt,\n name: record.displayName,\n workspace: record.workspace,\n skipLaunch: true,\n recovery: {\n activeRepairId: activeRepair?.repairId,\n claimId: recoveryClaimId,\n originalJob,\n originalRepoPath: record.originalRepoPath,\n runKey: record.runKey,\n startJob: recoveredJob,\n worktreeBranch: record.worktreeBranch,\n worktreePath: record.worktreePath,\n },\n });\n }\n\n private parseTerminalFix(\n fixContent: string,\n allowTerminalStop: boolean,\n ): { restartFrom?: string; terminal?: boolean } {\n if (!fixContent.startsWith(FIX_FRONTMATTER_DELIMITER)) {\n return {};\n }\n\n const endIndex = fixContent.indexOf(FIX_FRONTMATTER_DELIMITER, FIX_FRONTMATTER_DELIMITER.length);\n if (endIndex < 0) {\n return {};\n }\n\n const frontmatter = fixContent.slice(FIX_FRONTMATTER_DELIMITER.length, endIndex);\n let restartFrom: string | undefined;\n let terminalRequested = false;\n for (const line of frontmatter.split('\\n')) {\n const separatorIndex = line.indexOf(':');\n if (separatorIndex < 0) {\n continue;\n }\n const key = line.slice(0, separatorIndex).trim().toLowerCase();\n const value = line.slice(separatorIndex + 1).trim();\n if (key === FIX_STATUS_KEY && value.toLowerCase() === FIX_TERMINAL_TARGET) {\n terminalRequested = true;\n }\n if (key === FIX_RESTART_FROM_KEY) {\n if (value.toLowerCase() === FIX_TERMINAL_TARGET) {\n terminalRequested = true;\n continue;\n }\n restartFrom = value || undefined;\n }\n }\n\n return terminalRequested && allowTerminalStop ? { terminal: true } : { restartFrom };\n }\n}\n"],"ignoreList":[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,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