@sverka/compiler 0.1.13 → 0.1.15

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["filterReachableSteps","lowerTriggers","lowerChildPipelineStep","lowerDownstreamStep","lowerStep","lowerDependencies","lowerOperations","lowerOperation","lowerReport","lowerDeployPages","stringifyTargetGraph","jobToYaml","SHA_RE","bundledRegistry"],"sources":["../src/plugin/errors.ts","../src/plugin/capabilities.ts","../src/plugin/factory.ts","../src/github/capabilities.ts","../src/github/errors.ts","../src/job-ids.ts","../src/stdout-capture.ts","../src/github/lower.ts","../src/github/emit.ts","../src/github/pinned-actions.json","../src/github/pinning.ts","../src/github/target.ts","../src/gitlab/capabilities.ts","../src/gitlab/errors.ts","../src/gitlab/lower.ts","../src/gitlab/emit.ts","../src/gitlab/target.ts"],"sourcesContent":["// Plugin error class. Spec 07.\n\nexport type PluginErrorCode =\n \"INVALID_PLUGIN\" | \"DUPLICATE_PLUGIN\" | \"INVALID_CAPABILITY\";\n\nexport class PluginError extends Error {\n readonly code: PluginErrorCode;\n override readonly cause: unknown;\n\n constructor(message: string, code: PluginErrorCode, cause?: unknown) {\n super(message);\n this.name = \"PluginError\";\n this.code = code;\n this.cause = cause;\n }\n}\n","// Capability analysis. Spec 07 — §24.\n// Inspects a Definition Graph to detect used capabilities, then checks\n// against provided manifests to produce diagnostics.\n\nimport type { DefinitionGraph } from \"@sverka/workflow\";\nimport type {\n CapabilityManifest,\n CapabilitySupport,\n CapabilityDetail,\n CapabilityDiagnostic,\n} from \"./types.js\";\nimport { PluginError } from \"./errors.js\";\n\nconst SUPPORT_LEVELS: readonly CapabilitySupport[] = [\n \"native\",\n \"lowered\",\n \"emulated\",\n \"connector\",\n \"partial\",\n \"unsupported\",\n];\n\nconst PRIORITY: Record<CapabilitySupport, number> = {\n native: 6,\n lowered: 5,\n connector: 4,\n emulated: 3,\n partial: 2,\n unsupported: 1,\n};\n\n/**\n * Shape of a step used for capability detection.\n */\ninterface CapabilityStep {\n runtime?: {\n mode?: string;\n workingDir?: string;\n shell?: string;\n env?: Readonly<Record<string, string>>;\n secrets?: readonly string[];\n };\n operations: readonly CapabilityOperation[];\n outputs: readonly { type: string }[];\n dependencies: readonly unknown[];\n matrix?: {\n dimensions?: unknown;\n include?: readonly unknown[];\n exclude?: readonly unknown[];\n failFast?: boolean;\n maxParallel?: number;\n };\n beforeScript?: readonly unknown[];\n afterScript?: readonly unknown[];\n continueOnError?: unknown;\n retry?: { max?: number };\n interruptible?: boolean;\n runner?: { labels?: readonly string[]; group?: string };\n identity?: { tokens?: Readonly<Record<string, { audience: string }>> };\n rules?: readonly {\n changes?: readonly string[];\n exists?: readonly string[];\n }[];\n services?: readonly { ports?: readonly number[] }[];\n environment?: { name?: string; action?: string; tier?: string };\n cache?: { policy?: string; restoreKeys?: readonly string[] };\n concurrency?: { group?: string; cancelInProgress?: boolean };\n call?: unknown;\n component?: unknown;\n childPipeline?: unknown;\n downstream?: unknown;\n delay?: string;\n condition?: unknown;\n}\n\ninterface CapabilityOperation {\n kind: string;\n spec?: { type?: string };\n retention?: string;\n access?: string;\n}\n\ninterface OutputFlags {\n scalar: boolean;\n artifact: boolean;\n}\n\n/**\n * Validate that a value is a valid capability support level.\n */\nexport function validateSupport(value: unknown): CapabilitySupport {\n if (\n typeof value !== \"string\" ||\n !SUPPORT_LEVELS.includes(value as CapabilitySupport)\n ) {\n throw new PluginError(\n `invalid capability support level: ${String(value)}`,\n \"INVALID_CAPABILITY\",\n );\n }\n return value as CapabilitySupport;\n}\n\n/**\n * Validate a capability manifest object.\n */\nexport function validateCapabilityManifest(\n manifest: unknown,\n): asserts manifest is CapabilityManifest {\n if (\n typeof manifest !== \"object\" ||\n manifest === null ||\n Array.isArray(manifest)\n ) {\n throw new PluginError(\n \"capability manifest must be an object\",\n \"INVALID_CAPABILITY\",\n );\n }\n const obj = manifest as Record<string, unknown>;\n for (const [key, value] of Object.entries(obj)) {\n validateManifestEntry(key, value);\n }\n}\n\nfunction validateManifestEntry(key: string, value: unknown): void {\n if (typeof value === \"string\") {\n validateSupport(value);\n return;\n }\n if (typeof value === \"object\" && value !== null) {\n validateManifestDetail(key, value as Record<string, unknown>);\n return;\n }\n throw new PluginError(\n `capability '${key}' must be a support string or CapabilityDetail object`,\n \"INVALID_CAPABILITY\",\n );\n}\n\nfunction validateManifestDetail(\n key: string,\n detail: Record<string, unknown>,\n): void {\n validateSupport(detail.support);\n if (detail.via !== undefined && typeof detail.via !== \"string\") {\n throw new PluginError(\n `capability '${key}' has invalid via: must be a string`,\n \"INVALID_CAPABILITY\",\n );\n }\n if (detail.notes !== undefined && typeof detail.notes !== \"string\") {\n throw new PluginError(\n `capability '${key}' has invalid notes: must be a string`,\n \"INVALID_CAPABILITY\",\n );\n }\n}\n\n/**\n * Detect capabilities used by a single step.\n */\nfunction detectStepCapabilities(step: CapabilityStep, caps: Set<string>): void {\n detectRuntimeCapabilities(step, caps);\n detectRunnerCapabilities(step, caps);\n detectIdentityCapabilities(step, caps);\n detectRuleCapabilities(step, caps);\n detectServiceCapabilities(step, caps);\n detectEnvironmentCapabilities(step, caps);\n detectCacheCapabilities(step, caps);\n detectConcurrencyCapabilities(step, caps);\n detectSpecialStepCapabilities(step, caps);\n\n const outputFlags: OutputFlags = { scalar: false, artifact: false };\n for (const op of step.operations) {\n detectOperationCapabilities(op, caps, outputFlags);\n }\n detectOutputTypeCapabilities(step.outputs, outputFlags);\n\n if (step.dependencies.length > 0) caps.add(\"graph.dependencies\");\n if (step.condition !== undefined) caps.add(\"graph.conditions\");\n if (outputFlags.scalar) caps.add(\"output.scalar\");\n if (outputFlags.artifact) caps.add(\"output.artifact\");\n\n detectMatrixCapabilities(step.matrix, caps);\n detectScriptCapabilities(step, caps);\n}\n\n/**\n * Detect capabilities for special step kinds: call, component, child pipeline,\n * downstream, and delay.\n */\nfunction detectSpecialStepCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.call !== undefined) caps.add(\"reusable.pipeline\");\n if (step.component !== undefined) caps.add(\"reusable.component\");\n if (step.childPipeline !== undefined) caps.add(\"reusable.childPipeline\");\n if (step.downstream !== undefined) caps.add(\"reusable.downstream\");\n if (step.delay !== undefined) caps.add(\"scheduling.delay\");\n}\n\nfunction detectMatrixCapabilities(\n matrix:\n | {\n dimensions?: unknown;\n include?: readonly unknown[];\n exclude?: readonly unknown[];\n failFast?: boolean;\n maxParallel?: number;\n }\n | undefined,\n caps: Set<string>,\n): void {\n if (!matrix) return;\n caps.add(\"graph.matrix\");\n if (matrix.include && matrix.include.length > 0) caps.add(\"matrix.include\");\n if (matrix.exclude && matrix.exclude.length > 0) caps.add(\"matrix.exclude\");\n if (matrix.failFast !== undefined) caps.add(\"matrix.failFast\");\n if (matrix.maxParallel !== undefined) caps.add(\"matrix.maxParallel\");\n}\n\nfunction detectScriptCapabilities(\n step: {\n beforeScript?: readonly unknown[];\n afterScript?: readonly unknown[];\n continueOnError?: unknown;\n retry?: { max?: number };\n timeout?: unknown;\n },\n caps: Set<string>,\n): void {\n if (step.beforeScript && step.beforeScript.length > 0)\n caps.add(\"step.beforeScript\");\n if (step.afterScript && step.afterScript.length > 0)\n caps.add(\"step.afterScript\");\n if (step.continueOnError !== undefined) caps.add(\"step.continueOnError\");\n if (step.retry !== undefined) caps.add(\"policy.retry\");\n if (step.timeout !== undefined) caps.add(\"policy.timeout\");\n}\n\nfunction detectRuntimeCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n const mode = step.runtime?.mode ?? \"host\";\n caps.add(`runtime.${mode}`);\n if (step.runtime?.workingDir) caps.add(\"execution.workdir\");\n if (step.runtime?.shell) caps.add(\"execution.shell\");\n if (step.runtime?.env && Object.keys(step.runtime.env).length > 0)\n caps.add(\"environment.variables\");\n if (step.runtime?.secrets && step.runtime.secrets.length > 0)\n caps.add(\"secrets.runtime\");\n if (step.interruptible === true) caps.add(\"concurrency.interruptible\");\n}\n\nfunction detectRunnerCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.runner === undefined) return;\n caps.add(\"runner.selection\");\n if (step.runner.group !== undefined) caps.add(\"runner.group\");\n}\n\nfunction detectIdentityCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.identity === undefined) return;\n caps.add(\"secrets.oidc\");\n const audiences = new Set<string>();\n for (const token of Object.values(step.identity.tokens ?? {})) {\n audiences.add(token.audience);\n }\n if (audiences.size > 1) {\n caps.add(\"secrets.oidc.multiAudience\");\n }\n}\n\nfunction detectRuleCapabilities(step: CapabilityStep, caps: Set<string>): void {\n if (step.rules === undefined || step.rules.length === 0) return;\n caps.add(\"workflow.rules\");\n for (const rule of step.rules) {\n if (rule.changes !== undefined) caps.add(\"workflow.rules.changes\");\n if (rule.exists !== undefined) caps.add(\"workflow.rules.exists\");\n }\n}\n\nfunction detectServiceCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.services === undefined || step.services.length === 0) return;\n caps.add(\"environment.services\");\n for (const service of step.services) {\n if (service.ports !== undefined && service.ports.length > 0) {\n caps.add(\"environment.services.ports\");\n }\n }\n}\n\nfunction detectEnvironmentCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.environment === undefined) return;\n caps.add(\"deployment.environment\");\n if (step.environment.action !== undefined)\n caps.add(\"deployment.environment.action\");\n if (step.environment.tier !== undefined)\n caps.add(\"deployment.environment.tier\");\n}\n\nfunction detectCacheCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.cache === undefined) return;\n caps.add(\"cache\");\n if (step.cache.policy !== undefined) caps.add(\"cache.policy\");\n if (step.cache.restoreKeys !== undefined && step.cache.restoreKeys.length > 0)\n caps.add(\"cache.fallbackKeys\");\n}\n\nfunction detectConcurrencyCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.concurrency === undefined) return;\n caps.add(\"concurrency.group\");\n if (step.concurrency.cancelInProgress !== undefined)\n caps.add(\"concurrency.cancelInProgress\");\n}\n\nfunction detectOperationCapabilities(\n op: CapabilityOperation,\n caps: Set<string>,\n outputFlags: OutputFlags,\n): void {\n switch (op.kind) {\n case \"shell\":\n caps.add(\"operation.shell\");\n break;\n case \"exportOutput\":\n outputFlags.scalar = true;\n break;\n case \"exportArtifact\":\n detectExportArtifactCapabilities(op, caps, outputFlags);\n break;\n case \"importArtifact\":\n caps.add(\"operation.import\");\n break;\n case \"report\":\n detectReportCapabilities(op, caps);\n break;\n }\n}\n\nfunction detectExportArtifactCapabilities(\n op: CapabilityOperation,\n caps: Set<string>,\n outputFlags: OutputFlags,\n): void {\n outputFlags.artifact = true;\n if (op.retention !== undefined) caps.add(\"artifact.retention\");\n if (op.access !== undefined) caps.add(\"artifact.access\");\n}\n\nfunction detectReportCapabilities(\n op: CapabilityOperation,\n caps: Set<string>,\n): void {\n caps.add(\"artifact.report\");\n if (op.spec?.type !== undefined) {\n caps.add(`artifact.report.${op.spec.type}`);\n }\n}\n\nfunction detectOutputTypeCapabilities(\n outputs: readonly { type: string }[],\n outputFlags: OutputFlags,\n): void {\n for (const output of outputs) {\n if (output.type === \"artifact\") outputFlags.artifact = true;\n else outputFlags.scalar = true;\n }\n}\n\n/**\n * Detect capabilities used by a single pipeline.\n */\nfunction detectPipelineCapabilities(\n pipeline: {\n entries: readonly { trigger: { kind: string } }[];\n steps: readonly CapabilityStep[];\n permissions?: unknown;\n defaults?: {\n shell?: unknown;\n workdir?: unknown;\n env?: unknown;\n beforeScript?: unknown;\n afterScript?: unknown;\n timeout?: unknown;\n retry?: unknown;\n interruptible?: unknown;\n };\n inputs?: Readonly<\n Record<\n string,\n {\n type?: string;\n options?: readonly string[];\n pattern?: string;\n secret?: boolean;\n }\n >\n >;\n concurrency?: { group?: string; cancelInProgress?: boolean };\n rules?: readonly unknown[];\n },\n caps: Set<string>,\n): void {\n detectTriggerCapabilities(pipeline.entries, caps);\n if (pipeline.permissions !== undefined) {\n caps.add(\"environment.permissions\");\n }\n detectInputCapabilities(pipeline.inputs, caps);\n if (pipeline.defaults !== undefined) {\n detectDefaultCapabilities(pipeline.defaults, caps);\n }\n if (pipeline.concurrency !== undefined) {\n caps.add(\"concurrency.group\");\n if (pipeline.concurrency.cancelInProgress !== undefined)\n caps.add(\"concurrency.cancelInProgress\");\n }\n if (pipeline.rules !== undefined && pipeline.rules.length > 0) {\n caps.add(\"workflow.rules\");\n }\n for (const step of pipeline.steps) {\n detectStepCapabilities(step, caps);\n }\n}\n\nfunction detectTriggerCapabilities(\n entries: readonly { trigger: { kind: string } }[],\n caps: Set<string>,\n): void {\n for (const entry of entries) {\n caps.add(`trigger.${entry.trigger.kind}`);\n }\n}\n\nfunction detectInputCapabilities(\n inputs:\n | Readonly<\n Record<\n string,\n {\n type?: string;\n options?: readonly string[];\n pattern?: string;\n secret?: boolean;\n }\n >\n >\n | undefined,\n caps: Set<string>,\n): void {\n if (inputs === undefined || Object.keys(inputs).length === 0) return;\n caps.add(\"workflow.inputs\");\n for (const input of Object.values(inputs)) {\n if (input.secret) caps.add(\"secrets.pipeline-input\");\n if (input.type === \"choice\") caps.add(\"workflow.inputs.choice\");\n if (input.type === \"array\") caps.add(\"workflow.inputs.array\");\n if (input.pattern !== undefined) caps.add(\"workflow.inputs.pattern\");\n }\n}\n\nfunction detectDefaultCapabilities(\n defaults: {\n shell?: unknown;\n workdir?: unknown;\n env?: unknown;\n beforeScript?: unknown;\n afterScript?: unknown;\n timeout?: unknown;\n retry?: unknown;\n interruptible?: unknown;\n },\n caps: Set<string>,\n): void {\n caps.add(\"workflow.defaults\");\n const defaultCaps: ReadonlyArray<[unknown, string]> = [\n [defaults.shell, \"workflow.defaults.shell\"],\n [defaults.workdir, \"workflow.defaults.workdir\"],\n [defaults.env, \"workflow.defaults.env\"],\n [defaults.beforeScript, \"workflow.defaults.beforeScript\"],\n [defaults.afterScript, \"workflow.defaults.afterScript\"],\n [defaults.timeout, \"workflow.defaults.timeout\"],\n [defaults.retry, \"workflow.defaults.retry\"],\n [defaults.interruptible, \"workflow.defaults.interruptible\"],\n ];\n for (const [value, cap] of defaultCaps) {\n if (value !== undefined) caps.add(cap);\n }\n}\n\n/**\n * Detect capabilities used by a Definition Graph.\n * Returns a set of capability identifiers (e.g., \"trigger.push\").\n */\nexport function detectCapabilities(graph: DefinitionGraph): Set<string> {\n const caps = new Set<string>();\n for (const pipeline of graph.project.pipelines) {\n detectPipelineCapabilities(pipeline, caps);\n }\n return caps;\n}\n\n/**\n * Get the support level from a manifest entry.\n */\nfunction getSupportLevel(\n entry: CapabilitySupport | CapabilityDetail,\n): CapabilitySupport {\n if (typeof entry === \"string\") return validateSupport(entry);\n if (entry === null || typeof entry !== \"object\") {\n throw new PluginError(\n \"capability entry must be a string or CapabilityDetail\",\n \"INVALID_CAPABILITY\",\n );\n }\n return validateSupport((entry as CapabilityDetail).support);\n}\n\n/**\n * Find the best support level for a capability across all manifests.\n * \"native\" > \"lowered\" > \"connector\" > \"emulated\" > \"partial\" > \"unsupported\".\n */\nfunction findBestSupport(\n capability: string,\n manifests: readonly CapabilityManifest[],\n): CapabilitySupport {\n let best: CapabilitySupport = \"unsupported\";\n for (const manifest of manifests) {\n const entry = manifest[capability];\n if (entry === undefined) continue;\n const level = getSupportLevel(entry);\n if (PRIORITY[level] > PRIORITY[best]) {\n best = level;\n }\n }\n return best;\n}\n\n/**\n * Map a support level to a diagnostic severity.\n */\nfunction severityFor(support: CapabilitySupport): \"error\" | \"warning\" | \"info\" {\n switch (support) {\n case \"unsupported\":\n return \"error\";\n case \"emulated\":\n case \"partial\":\n return \"warning\";\n case \"connector\":\n return \"info\";\n default:\n return \"info\";\n }\n}\n\n/**\n * Analyze a Definition Graph against capability manifests.\n * Returns diagnostics for capabilities that are not natively or lowered\n * supported.\n */\nexport function analyzeCapabilities(\n graph: DefinitionGraph,\n manifests: readonly CapabilityManifest[],\n): readonly CapabilityDiagnostic[] {\n for (const manifest of manifests) {\n validateCapabilityManifest(manifest);\n }\n const used = detectCapabilities(graph);\n const diagnostics: CapabilityDiagnostic[] = [];\n\n for (const capability of used) {\n const support = findBestSupport(capability, manifests);\n if (support === \"native\" || support === \"lowered\") continue;\n\n diagnostics.push({\n capability,\n support,\n severity: severityFor(support),\n message: `capability '${capability}' is ${support}`,\n });\n }\n\n return diagnostics;\n}\n","// Plugin factory and registry. Spec 07 — §17.1.\n\nimport type {\n SverkaPlugin,\n PluginOptions,\n PluginMeta,\n PluginRegistry,\n CapabilityManifest,\n} from \"./types.js\";\nimport { validateCapabilityManifest } from \"./capabilities.js\";\nimport { PluginError } from \"./errors.js\";\n\n/**\n * Define a Sverka plugin. The factory function receives optional options\n * and meta, and returns a SverkaPlugin object.\n *\n * @example\n * const plugin = defineSverkaPlugin(() => ({\n * name: \"github\",\n * apiVersion: \"sverka.dev/v1\",\n * capabilities: { \"trigger.push\": \"native\" },\n * }));\n */\nexport function defineSverkaPlugin(\n factory: (options?: PluginOptions, meta?: PluginMeta) => SverkaPlugin,\n options?: PluginOptions,\n): SverkaPlugin {\n const meta: PluginMeta = { version: \"1.0.0\" };\n const plugin = factory(options, meta);\n validatePlugin(plugin);\n return snapshotPlugin(plugin);\n}\n\n/**\n * Store a validated, defensive copy of a plugin so callers cannot mutate\n * the registry's internal state after registration.\n */\nfunction snapshotPlugin(plugin: SverkaPlugin): SverkaPlugin {\n const copy: Record<string, unknown> = {\n name: plugin.name,\n apiVersion: plugin.apiVersion,\n };\n if (plugin.capabilities) {\n copy.capabilities = snapshotCapabilityManifest(plugin.capabilities);\n }\n if (plugin.model) copy.model = [...plugin.model];\n if (plugin.transforms) copy.transforms = [...plugin.transforms];\n if (plugin.validators) copy.validators = [...plugin.validators];\n if (plugin.targets) copy.targets = [...plugin.targets];\n if (plugin.importers) copy.importers = [...plugin.importers];\n if (plugin.engines) copy.engines = [...plugin.engines];\n if (plugin.connectors) copy.connectors = [...plugin.connectors];\n if (plugin.extensions) copy.extensions = [...plugin.extensions];\n // Tools facet is a live runtime object (ToolProvider); shallow-copy the\n // reference so the registry snapshot preserves the facet without trying to\n // deep-clone stateful connections (Spec 23).\n if (plugin.tools) copy.tools = plugin.tools;\n return copy as unknown as SverkaPlugin;\n}\n\nfunction snapshotCapabilityManifest(\n manifest: CapabilityManifest,\n): CapabilityManifest {\n const copy: CapabilityManifest = {};\n for (const [capability, value] of Object.entries(manifest)) {\n copy[capability] = typeof value === \"string\" ? value : { ...value };\n }\n return copy;\n}\n\n/**\n * Validate a plugin has required fields and a valid capabilities manifest.\n */\nfunction validatePlugin(plugin: SverkaPlugin): void {\n if (!plugin || typeof plugin !== \"object\") {\n throw new PluginError(\"plugin must be an object\", \"INVALID_PLUGIN\");\n }\n if (typeof plugin.name !== \"string\" || plugin.name.length === 0) {\n throw new PluginError(\n \"plugin must have a non-empty name\",\n \"INVALID_PLUGIN\",\n );\n }\n if (typeof plugin.apiVersion !== \"string\" || plugin.apiVersion.length === 0) {\n throw new PluginError(\"plugin must have an apiVersion\", \"INVALID_PLUGIN\");\n }\n if (plugin.capabilities !== undefined) {\n validateCapabilityManifest(plugin.capabilities);\n }\n}\n\n/**\n * Create a plugin registry.\n */\nexport function createPluginRegistry(): PluginRegistry {\n const plugins: SverkaPlugin[] = [];\n const names = new Set<string>();\n\n return {\n register(plugin: SverkaPlugin): void {\n validatePlugin(plugin);\n if (names.has(plugin.name)) {\n throw new PluginError(\n `plugin '${plugin.name}' is already registered`,\n \"DUPLICATE_PLUGIN\",\n );\n }\n names.add(plugin.name);\n plugins.push(snapshotPlugin(plugin));\n },\n get plugins(): readonly SverkaPlugin[] {\n return plugins.map((p) => snapshotPlugin(p));\n },\n getCapabilities(): CapabilityManifest[] {\n return plugins\n .filter((p) => p.capabilities !== undefined)\n .map((p) =>\n snapshotCapabilityManifest(p.capabilities as CapabilityManifest),\n );\n },\n };\n}\n","// GitHub capability manifest. Spec 08 — §24.\nimport type { CapabilityManifest } from \"../plugin/index.js\";\n\nexport const githubCapabilities: CapabilityManifest = {\n \"trigger.push\": \"native\",\n \"trigger.changeRequest\": \"native\",\n \"trigger.manual\": \"native\",\n \"runtime.host\": \"native\",\n \"runtime.container\": \"native\",\n \"operation.shell\": \"native\",\n \"operation.import\": \"lowered\",\n \"output.scalar\": \"lowered\",\n \"output.artifact\": \"native\",\n \"graph.dependencies\": \"native\",\n \"graph.conditions\": \"native\",\n \"graph.matrix\": \"native\",\n \"matrix.include\": \"native\",\n \"matrix.exclude\": \"native\",\n \"matrix.failFast\": \"native\",\n \"matrix.maxParallel\": \"native\",\n \"trigger.schedule\": \"native\",\n \"step.beforeScript\": \"native\",\n \"step.afterScript\": \"native\",\n \"step.continueOnError\": \"native\",\n \"policy.retry\": \"emulated\",\n \"policy.compensation\": \"emulated\",\n \"execution.workdir\": \"native\",\n \"execution.shell\": \"native\",\n \"environment.variables\": \"native\",\n \"secrets.runtime\": \"native\",\n \"secrets.pipeline-input\": \"native\",\n \"concurrency.interruptible\": \"partial\",\n \"environment.permissions\": \"native\",\n \"runner.selection\": \"native\",\n \"runner.group\": \"native\",\n \"secrets.oidc\": \"native\",\n \"secrets.oidc.multiAudience\": \"unsupported\",\n \"workflow.rules\": \"partial\",\n \"workflow.rules.changes\": \"unsupported\",\n \"workflow.rules.exists\": \"unsupported\",\n \"workflow.defaults\": \"native\",\n \"workflow.defaults.shell\": \"native\",\n \"workflow.defaults.workdir\": \"native\",\n \"workflow.defaults.env\": \"unsupported\",\n \"workflow.defaults.beforeScript\": \"lowered\",\n \"workflow.defaults.afterScript\": \"lowered\",\n \"workflow.defaults.timeout\": \"unsupported\",\n \"workflow.defaults.retry\": \"unsupported\",\n \"workflow.defaults.interruptible\": \"unsupported\",\n \"artifact.report\": \"emulated\",\n \"artifact.report.junit\": \"emulated\",\n \"artifact.report.coverage\": \"emulated\",\n \"artifact.report.dotenv\": \"emulated\",\n \"artifact.report.sast\": \"emulated\",\n \"artifact.report.dast\": \"emulated\",\n \"artifact.report.dependencyScanning\": \"emulated\",\n \"artifact.report.containerScanning\": \"emulated\",\n \"artifact.report.licenseScanning\": \"emulated\",\n \"artifact.report.performance\": \"emulated\",\n \"artifact.report.metrics\": \"emulated\",\n \"artifact.report.terraform\": \"emulated\",\n \"artifact.report.quality\": \"emulated\",\n \"artifact.report.sarif\": \"emulated\",\n \"workflow.inputs\": \"native\",\n \"workflow.inputs.choice\": \"native\",\n \"workflow.inputs.array\": \"unsupported\",\n \"workflow.inputs.pattern\": \"unsupported\",\n \"environment.services\": \"native\",\n \"environment.services.ports\": \"native\",\n \"deployment.environment\": \"native\",\n \"deployment.environment.action\": \"unsupported\",\n \"deployment.environment.tier\": \"unsupported\",\n \"artifact.retention\": \"native\",\n \"artifact.access\": \"unsupported\",\n cache: \"lowered\",\n \"cache.policy\": \"lowered\",\n \"cache.fallbackKeys\": \"lowered\",\n \"concurrency.group\": \"native\",\n \"concurrency.cancelInProgress\": \"native\",\n \"reusable.pipeline\": \"native\",\n \"reusable.pipeline.inputs\": \"native\",\n \"reusable.pipeline.outputs\": \"native\",\n \"reusable.component\": \"native\",\n \"reusable.component.versioning\": \"native\",\n \"reusable.childPipeline\": \"unsupported\",\n \"reusable.downstream\": \"emulated\",\n \"deployment.release\": \"emulated\",\n \"deployment.pages\": \"native\",\n \"import.github\": \"native\",\n \"import.include\": \"emulated\",\n \"scheduling.delay\": \"emulated\",\n \"execution.background\": \"emulated\",\n \"runtime.network\": \"emulated\",\n \"step.permissions\": \"native\",\n \"agent.step\": \"emulated\",\n \"run.query\": \"emulated\",\n};\n","// GitHub target error class. Spec 08.\n\nexport type GithubTargetErrorCode =\n | \"INVALID_GRAPH\"\n | \"UNSUPPORTED_TRIGGER\"\n | \"UNSUPPORTED_FEATURE\"\n | \"LOWER_FAILED\"\n | \"LOWERING_ERROR\"\n | \"IMPORT_FAILED\"\n | \"INVALID_MATRIX\";\n\nexport class GithubTargetError extends Error {\n readonly code: GithubTargetErrorCode;\n override readonly cause: unknown;\n\n constructor(message: string, code: GithubTargetErrorCode, cause?: unknown) {\n super(message);\n this.name = \"GithubTargetError\";\n this.code = code;\n this.cause = cause;\n }\n}\n","// Shared helpers for CI target lowering (github/ + gitlab/).\nimport type { StepDefinition } from \"@sverka/workflow\";\n\n/**\n * Build a mapping from full step IDs (e.g., \"ci/lint\") to CI-safe\n * job IDs (e.g., \"lint\"). If there are collisions, append a suffix.\n */\nexport function buildJobIdMap(\n steps: readonly StepDefinition[],\n): Map<string, string> {\n const map = new Map<string, string>();\n const used = new Set<string>();\n\n for (const step of steps) {\n // Use the last segment of the path as the job ID.\n const shortId = step.id.includes(\"/\") ? step.id.split(\"/\").pop()! : step.id;\n let jobId = shortId;\n let suffix = 1;\n while (used.has(jobId)) {\n jobId = `${shortId}-${suffix}`;\n suffix++;\n }\n used.add(jobId);\n map.set(step.id, jobId);\n }\n\n return map;\n}\n","// Shared lowering helper for exportStdout operations.\n// Both the GitHub and GitLab lowers bind a `fromStdout` artifact output to\n// the most recent shell op's captured stdout.\n\n/**\n * Quote a literal string using single quotes for a POSIX shell.\n */\nexport function shellQuoteSingle(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/**\n * Wrap a shell command line so its stdout is also written to the declared\n * artifact file(s), matching the runtime's exportStdout semantics. The\n * capture must work under POSIX sh (no pipefail), so the command's stdout is\n * redirected to the file and replayed with cat; the original exit code is\n * re-raised so a failing check still fails the job.\n *\n * Background commands (`cmd &`) detach before stdout can be captured; the\n * runtime records an empty artifact for them, so empty files are created.\n */\nexport function wrapStdoutCaptureLine(\n command: string,\n names: readonly string[],\n): string {\n const quoted = names.map(shellQuoteSingle);\n if (command.endsWith(\" &\")) {\n return [command, `touch ${quoted.join(\" \")}`].join(\"\\n\");\n }\n const [first, ...rest] = quoted;\n const teeRest = rest.length > 0 ? ` | tee ${rest.join(\" \")}` : \"\";\n return [\n \"sverka_rc=0\",\n `{ ${command}`,\n `} > ${first} || sverka_rc=$?`,\n `cat ${first}${teeRest}`,\n `if [ \"$sverka_rc\" -gt 0 ]; then exit \"$sverka_rc\"; fi`,\n ].join(\"\\n\");\n}\n","// Native lowering: Definition Graph → GithubTargetGraph[].\n// Spec 08 — §18.1, §19. F-31: multi-pipeline reusable workflows.\n\nimport type {\n DefinitionGraph,\n PipelineDefinition,\n StepDefinition,\n EntryDefinition,\n OperationDefinition,\n Dependency,\n Reference,\n Expression,\n Input,\n} from \"@sverka/workflow\";\nimport type {\n Trigger,\n MatrixSpec,\n StepRef,\n StatusCondition,\n PipelineDefaults,\n ReportSpec,\n ServiceContainer,\n CacheSpec,\n Rule,\n} from \"@sverka/workflow\";\nimport type {\n GithubTargetGraph,\n GithubTriggers,\n GithubJob,\n GithubStep,\n GithubRunsOn,\n GithubDefaults,\n GithubDefaultsRun,\n GithubInput,\n GithubService,\n GithubTargetConfig,\n} from \"./types.js\";\nimport { GithubTargetError } from \"./errors.js\";\nimport { buildJobIdMap } from \"../job-ids.js\";\nimport { wrapStdoutCaptureLine } from \"../stdout-capture.js\";\n\n/**\n * Lower a Definition Graph to one or more GithubTargetGraphs.\n * - Each pipeline with entries → a root workflow with its triggers.\n * - Each pipeline referenced by a call step → a reusable workflow with\n * `on: workflow_call` (+ its own triggers if it also has entries).\n * - Call steps become `uses:` jobs.\n * Single-pipeline graphs (no calls) are unchanged (backward compat).\n */\nexport function lowerGithub(\n graph: DefinitionGraph,\n config?: GithubTargetConfig,\n): GithubTargetGraph | readonly GithubTargetGraph[] {\n if (graph.project.pipelines.length === 0) {\n throw new GithubTargetError(\"graph has no pipelines\", \"INVALID_GRAPH\");\n }\n\n // Single-pipeline, no special steps → backward compat.\n if (graph.project.pipelines.length === 1) {\n const pipeline = graph.project.pipelines[0]!;\n const hasSpecial = pipeline.steps.some(\n (s) => s.call || s.component || s.childPipeline || s.downstream,\n );\n if (!hasSpecial) {\n return lowerSinglePipeline(pipeline, config);\n }\n }\n\n // Multi-pipeline or has special steps → lower all pipelines.\n return lowerMultiPipeline(graph, config);\n}\n\n/**\n * The Checkout step shared by every job, with optional `with:` inputs\n * (e.g. `submodules: recursive`) from {@link GithubTargetConfig.checkoutWith}.\n */\nfunction checkoutStep(config?: GithubTargetConfig): GithubStep {\n return {\n name: \"Checkout\",\n uses: \"actions/checkout@v4\",\n ...(config?.checkoutWith ? { with: config.checkoutWith } : {}),\n };\n}\n\n/**\n * Toolchain/dependency setup steps injected after Checkout in every job\n * that executes user commands (shell and component steps).\n */\nfunction setupSteps(config?: GithubTargetConfig): readonly GithubStep[] {\n return config?.setup ?? [];\n}\n\n/**\n * Lower a single pipeline (no calls) — original v0 behavior.\n */\nfunction lowerSinglePipeline(\n pipeline: PipelineDefinition,\n config?: GithubTargetConfig,\n): GithubTargetGraph {\n const reachableSteps = filterReachableSteps(pipeline);\n const jobIdMap = buildJobIdMap(reachableSteps);\n\n const triggers = lowerTriggers(pipeline.entries, pipeline.inputs);\n const jobs = lowerStepsWithCalls(\n reachableSteps,\n jobIdMap,\n pipeline.id,\n config,\n );\n\n return assemblePipelineTarget(pipeline, triggers, jobs);\n}\n\n/**\n * Assemble a GithubTargetGraph from a pipeline, its triggers, and jobs.\n * Shared by lowerSinglePipeline and lowerMultiPipeline.\n */\nfunction assemblePipelineTarget(\n pipeline: PipelineDefinition,\n triggers: GithubTriggers,\n jobs: readonly GithubJob[],\n): GithubTargetGraph {\n // Least privilege (S8264): pipeline permissions become per-job grants and\n // the workflow-level default is deny-all. Jobs with explicit permissions\n // (e.g. deploys, safe-outputs) keep theirs.\n const grants = pipeline.permissions;\n const jobsWithPermissions =\n grants === undefined\n ? jobs\n : jobs.map((job): GithubJob => {\n if (job.permissions !== undefined) return job;\n const permissions: Readonly<Record<string, string>> = job.steps.some(\n (s) => s.uses?.startsWith(\"github/codeql-action/upload-sarif@\"),\n )\n ? { ...grants, \"security-events\": \"write\" }\n : grants;\n return { ...job, permissions };\n });\n return {\n name: pipeline.id,\n on: triggers,\n jobs: jobsWithPermissions,\n env: collectEnv(pipeline),\n ...(pipeline.permissions !== undefined ? { permissions: {} } : {}),\n ...(pipeline.defaults !== undefined\n ? { defaults: lowerDefaults(pipeline.defaults) }\n : {}),\n ...(pipeline.concurrency !== undefined\n ? { concurrency: pipeline.concurrency }\n : {}),\n };\n}\n\n/**\n * Lower pipeline defaults to GitHub defaults.run (shell + working-directory only).\n */\nfunction lowerDefaults(defaults: PipelineDefaults): GithubDefaults {\n const run: GithubDefaultsRun = {\n ...(defaults.shell !== undefined ? { shell: defaults.shell } : {}),\n ...(defaults.workdir !== undefined\n ? { \"working-directory\": defaults.workdir }\n : {}),\n };\n return { run };\n}\n\n/**\n * Lower a multi-pipeline graph. Each pipeline that has entries OR is referenced\n * by a call step gets its own workflow file.\n */\nfunction lowerMultiPipeline(\n graph: DefinitionGraph,\n config?: GithubTargetConfig,\n): readonly GithubTargetGraph[] {\n const pipelines = graph.project.pipelines;\n const calledPipelineIds = collectCalledPipelineIds(pipelines);\n\n const result: GithubTargetGraph[] = [];\n for (const pipeline of pipelines) {\n const target = lowerPipelineInGraph(\n pipeline,\n calledPipelineIds.has(pipeline.id),\n config,\n );\n if (target !== undefined) result.push(target);\n }\n return result;\n}\n\n/**\n * Collect the set of pipeline IDs that are referenced by at least one call step.\n */\nfunction collectCalledPipelineIds(\n pipelines: readonly PipelineDefinition[],\n): Set<string> {\n const called = new Set<string>();\n for (const p of pipelines) {\n for (const step of p.steps) {\n if (step.call) {\n called.add(step.call.callee);\n }\n }\n }\n return called;\n}\n\n/**\n * Lower a single pipeline within a multi-pipeline graph.\n * Returns undefined if the pipeline is neither a root nor a callee.\n */\nfunction lowerPipelineInGraph(\n pipeline: PipelineDefinition,\n isCalled: boolean,\n config?: GithubTargetConfig,\n): GithubTargetGraph | undefined {\n const hasEntries = pipeline.entries.length > 0;\n if (!hasEntries && !isCalled) return undefined;\n\n // For callees, all steps are reachable (no entries needed).\n // For roots, filter by entry reachability.\n const reachableSteps = hasEntries\n ? filterReachableSteps(pipeline)\n : pipeline.steps;\n const jobIdMap = buildJobIdMap(reachableSteps);\n\n // Triggers: root triggers + workflow_call if called.\n let triggers = lowerTriggers(pipeline.entries, pipeline.inputs);\n if (isCalled) {\n triggers = addWorkflowCall(triggers, pipeline.inputs);\n }\n\n const jobs = lowerStepsWithCalls(\n reachableSteps,\n jobIdMap,\n pipeline.id,\n config,\n );\n return assemblePipelineTarget(pipeline, triggers, jobs);\n}\n\n/**\n * Add workflow_call trigger with inputs to a GithubTriggers object.\n */\nfunction addWorkflowCall(\n triggers: GithubTriggers,\n inputs: Readonly<Record<string, Input>>,\n): GithubTriggers {\n const inputEntries = Object.entries(inputs);\n if (inputEntries.length === 0) {\n return { ...triggers, workflow_call: null };\n }\n\n const workflowInputs: Record<string, unknown> = {};\n for (const [name, input] of inputEntries) {\n let type = \"string\";\n if (input.type === \"number\") {\n type = \"number\";\n } else if (input.type === \"boolean\") {\n type = \"boolean\";\n }\n const ghInput: Record<string, unknown> = {\n type,\n required: input.required ?? false,\n };\n if (input.default !== undefined) {\n ghInput.default = input.default;\n }\n if (input.description !== undefined) {\n ghInput.description = input.description;\n }\n workflowInputs[name] = ghInput;\n }\n\n return { ...triggers, workflow_call: { inputs: workflowInputs } };\n}\n\n/**\n * Return the steps reachable from any entry root by following dependencies.\n */\nfunction filterReachableSteps(\n pipeline: PipelineDefinition,\n): readonly StepDefinition[] {\n if (pipeline.steps.length === 0) {\n const invalidRoot = pipeline.entries\n .flatMap((e) => e.roots)\n .find((root) => root.length > 0);\n if (invalidRoot) {\n throw new GithubTargetError(\n `entry references unknown root step '${invalidRoot}'`,\n \"INVALID_GRAPH\",\n );\n }\n return [];\n }\n\n const byId = new Map(pipeline.steps.map((step) => [step.id, step]));\n const reachable = new Set<string>();\n const queue: string[] = [];\n\n for (const entry of pipeline.entries) {\n enqueueRoots(entry.roots, byId, reachable, queue);\n }\n\n while (queue.length > 0) {\n const id = queue.shift()!;\n const step = byId.get(id);\n if (!step) continue;\n enqueueDependencies(step, byId, reachable, queue);\n }\n\n return pipeline.steps.filter((step) => reachable.has(step.id));\n}\n\nfunction enqueueRoots(\n roots: readonly string[],\n byId: Map<string, StepDefinition>,\n reachable: Set<string>,\n queue: string[],\n): void {\n for (const root of roots) {\n if (!byId.has(root)) {\n throw new GithubTargetError(\n `entry references unknown root step '${root}'`,\n \"INVALID_GRAPH\",\n );\n }\n enqueueIfNew(root, reachable, queue);\n }\n}\n\nfunction enqueueDependencies(\n step: StepDefinition,\n byId: Map<string, StepDefinition>,\n reachable: Set<string>,\n queue: string[],\n): void {\n for (const dep of step.dependencies) {\n const producer = dep.producer;\n if (!byId.has(producer)) {\n throw new GithubTargetError(\n `step depends on unknown producer '${producer}'`,\n \"INVALID_GRAPH\",\n );\n }\n enqueueIfNew(producer, reachable, queue);\n }\n}\n\nfunction enqueueIfNew(\n id: string,\n reachable: Set<string>,\n queue: string[],\n): void {\n if (!reachable.has(id)) {\n reachable.add(id);\n queue.push(id);\n }\n}\n\n/**\n * Map Sverka triggers to GitHub triggers.\n * Multiple entries of the same kind have their filters merged.\n */\nfunction lowerTriggers(\n entries: readonly EntryDefinition[],\n inputs: Readonly<Record<string, Input>>,\n): GithubTriggers {\n const pushBranches = new Set<string>();\n const pushTags = new Set<string>();\n const pushPaths = new Set<string>();\n let pushAll = false;\n const prBranches = new Set<string>();\n const prPaths = new Set<string>();\n let prAll = false;\n let hasManual = false;\n const scheduleEntries: { cron: string; timezone?: string }[] = [];\n\n for (const entry of entries) {\n const t = entry.trigger;\n switch (t.kind) {\n case \"push\":\n collectFilters(\n t,\n pushBranches,\n pushTags,\n pushPaths,\n () => (pushAll = true),\n );\n break;\n case \"changeRequest\":\n collectFilters(t, prBranches, undefined, prPaths, () => (prAll = true));\n break;\n case \"manual\":\n hasManual = true;\n break;\n case \"schedule\":\n scheduleEntries.push({\n cron: t.cron,\n ...(t.timezone ? { timezone: t.timezone } : {}),\n });\n break;\n default:\n throw new GithubTargetError(\n `unsupported trigger kind: ${JSON.stringify((t as Trigger).kind)}`,\n \"UNSUPPORTED_TRIGGER\",\n );\n }\n }\n\n return assembleTriggers({\n pushAll,\n pushBranches,\n pushTags,\n pushPaths,\n prAll,\n prBranches,\n prPaths,\n hasManual,\n scheduleEntries,\n inputs,\n });\n}\n\nfunction collectFilters(\n t: Trigger,\n branches: Set<string>,\n tags: Set<string> | undefined,\n paths: Set<string>,\n markAll: () => void,\n): void {\n if (t.kind === \"schedule\") {\n markAll();\n return;\n }\n const filter = t.filter;\n const hasBranches = filter?.branches && filter.branches.length > 0;\n const hasTags = filter?.tags && filter.tags.length > 0;\n const hasPaths = filter?.paths && filter.paths.length > 0;\n\n // Tag filters are not meaningful on change-request triggers (PRs don't have tags).\n if (hasTags && tags === undefined) {\n throw new GithubTargetError(\n \"tag filters are not supported on change-request triggers\",\n \"UNSUPPORTED_TRIGGER\",\n );\n }\n\n if (hasBranches) addAll(branches, filter!.branches!);\n if (hasTags && tags) addAll(tags, filter!.tags!);\n if (hasPaths) addAll(paths, filter!.paths!);\n\n // If no filter at all, mark as \"fire on all\"\n if (!hasBranches && !hasTags && !hasPaths) {\n markAll();\n }\n}\n\n/** Add all items from a readonly array to a Set. */\nfunction addAll<T>(set: Set<T>, items: readonly T[]): void {\n for (const item of items) set.add(item);\n}\n\ninterface TriggerFilters {\n readonly pushAll: boolean;\n readonly pushBranches: Set<string>;\n readonly pushTags: Set<string>;\n readonly pushPaths: Set<string>;\n readonly prAll: boolean;\n readonly prBranches: Set<string>;\n readonly prPaths: Set<string>;\n readonly hasManual: boolean;\n readonly scheduleEntries: readonly { cron: string; timezone?: string }[];\n readonly inputs: Readonly<Record<string, Input>>;\n}\n\nfunction assembleTriggers(f: TriggerFilters): GithubTriggers {\n const triggers: Record<string, unknown> = {};\n const push = assemblePushTrigger(f);\n if (push) triggers.push = push;\n const pr = assemblePullRequestTrigger(f);\n if (pr) triggers.pull_request = pr;\n if (f.hasManual) {\n const loweredInputs = lowerInputs(f.inputs);\n triggers.workflow_dispatch =\n loweredInputs !== undefined ? { inputs: loweredInputs } : null;\n }\n if (f.scheduleEntries.length > 0) triggers.schedule = f.scheduleEntries;\n return triggers as GithubTriggers;\n}\n\nfunction assemblePushTrigger(\n f: TriggerFilters,\n): Record<string, string[]> | null {\n if (f.pushAll) return {};\n if (\n f.pushBranches.size === 0 &&\n f.pushTags.size === 0 &&\n f.pushPaths.size === 0\n )\n return null;\n const push: Record<string, string[]> = {};\n if (f.pushBranches.size > 0) push.branches = [...f.pushBranches];\n if (f.pushTags.size > 0) push.tags = [...f.pushTags];\n if (f.pushPaths.size > 0) push.paths = [...f.pushPaths];\n return push;\n}\n\nfunction assemblePullRequestTrigger(\n f: TriggerFilters,\n): Record<string, string[]> | null {\n if (f.prAll) return {};\n if (f.prBranches.size === 0 && f.prPaths.size === 0) return null;\n const pr: Record<string, string[]> = {};\n if (f.prBranches.size > 0) pr.branches = [...f.prBranches];\n if (f.prPaths.size > 0) pr.paths = [...f.prPaths];\n return pr;\n}\n\n/**\n * Lower pipeline inputs to GitHub workflow_dispatch inputs.\n * Returns undefined if no inputs are present.\n * Maps Sverka types to GitHub types: choice→choice, array→unsupported (dropped),\n * others map directly. pattern is dropped (unsupported on GitHub).\n */\nfunction lowerInputs(\n inputs: Readonly<Record<string, Input>>,\n): Readonly<Record<string, GithubInput>> | undefined {\n if (Object.keys(inputs).length === 0) return undefined;\n const result: Record<string, GithubInput> = {};\n for (const [name, input] of Object.entries(inputs)) {\n const ghInput: GithubInput = {\n type: input.type === \"array\" ? \"string\" : input.type,\n ...(input.description !== undefined\n ? { description: input.description }\n : {}),\n ...(input.required !== undefined ? { required: input.required } : {}),\n ...(input.default !== undefined && typeof input.default !== \"object\"\n ? { default: input.default as string | number | boolean }\n : {}),\n ...(input.options !== undefined ? { options: input.options } : {}),\n };\n result[name] = ghInput;\n }\n return result;\n}\n\n/**\n * Lower reachable steps to GitHub jobs. One job per step.\n * Call steps become `uses:` jobs (reusable workflow calls).\n * Component steps become `uses:` jobs (composite action calls).\n */\nfunction lowerStepsWithCalls(\n steps: readonly StepDefinition[],\n jobIdMap: Map<string, string>,\n pipelineId: string,\n config?: GithubTargetConfig,\n): readonly GithubJob[] {\n return steps.map((step) => {\n if (step.call) {\n return lowerCallStep(step, jobIdMap, pipelineId);\n }\n if (step.component) {\n return lowerComponentStep(step, jobIdMap, config);\n }\n if (step.childPipeline) {\n return lowerChildPipelineStep(step, jobIdMap);\n }\n if (step.downstream) {\n return lowerDownstreamStep(step, jobIdMap);\n }\n return lowerStep(step, jobIdMap, config);\n });\n}\n\n/**\n * Lower a Reference value to a GitHub expression string.\n * Returns the expression if `value` is a Reference, otherwise `undefined`\n * (meaning the value is a literal the caller should handle itself).\n * Context references are mapped through GITHUB_CONTEXT_MAP so that Sverka\n * namespaces (e.g. `git.sha`) become valid GitHub expressions (e.g.\n * `github.sha`).\n *\n * Secret references are sink-specific:\n * - In `with:` inputs (`forWithInput = true`): `${{ secrets.FIELD }}`.\n * GitHub Actions does not expand `$FIELD` in `with:` values — it treats it\n * as a literal string. The `secrets` context is the correct syntax here.\n * - In `run:` commands (`forWithInput = false`, default): `$FIELD`.\n * The shell expands the env var, and this avoids exposing the secret value\n * in workflow logs.\n */\nfunction lowerReferenceExpr(\n value: unknown,\n jobIdMap: Map<string, string>,\n forWithInput = false,\n): string | undefined {\n if (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n \"kind\" in value\n ) {\n const ref = value as Reference;\n if (ref.kind === \"step\") {\n const producerJobId = jobIdMap.get(ref.step) ?? ref.step;\n return `\\${{ needs.${producerJobId}.outputs.${ref.output} }}`;\n }\n if (ref.kind === \"context\") {\n return translateContextRef(ref.namespace, ref.field, false, forWithInput);\n }\n }\n return undefined;\n}\n\n/**\n * Lower a call step to a GitHub reusable workflow call job.\n */\nfunction lowerCallStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n pipelineId: string,\n): GithubJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const needs = lowerDependencies(step.dependencies, jobIdMap);\n const call = step.call!;\n const callee = call.callee;\n\n // Build `with:` from bound inputs.\n // Secrets in `with:` inputs must use ${{ secrets.FIELD }} — GitHub Actions\n // does not expand $FIELD in with: values (it treats it as a literal string).\n const withMap: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(call.inputs)) {\n withMap[name] = lowerReferenceExpr(value, jobIdMap, true) ?? value;\n }\n\n return {\n id: jobId,\n name: jobId,\n runsOn: \"ubuntu-latest\",\n needs,\n steps: [],\n uses: `./.github/workflows/${callee}.yml`,\n ...(Object.keys(withMap).length > 0 ? { with: withMap } : {}),\n secrets: \"inherit\",\n };\n}\n\n/**\n * Lower a component step to a GitHub composite action call job.\n * F-32: component → uses: org/component@version with `with:` inputs.\n */\nfunction lowerComponentStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n config?: GithubTargetConfig,\n): GithubJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const needs = lowerDependencies(step.dependencies, jobIdMap);\n const comp = step.component!;\n\n // Build `with:` from bound inputs.\n // Secrets in `with:` inputs must use ${{ secrets.FIELD }} — GitHub Actions\n // does not expand $FIELD in with: values (it treats it as a literal string).\n const withMap: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(comp.inputs)) {\n withMap[name] = lowerReferenceExpr(value, jobIdMap, true) ?? value;\n }\n\n // Component references that look like GitHub Actions (org/repo@ref) are\n // emitted as normal jobs with an action step. Reusable workflow references\n // (./.github/workflows/*.yml) remain as `uses:` jobs.\n const isAction = !comp.name.startsWith(\"./\");\n if (isAction) {\n return {\n id: jobId,\n name: jobId,\n runsOn: resolveRunsOn(step),\n needs,\n steps: [\n checkoutStep(config),\n ...setupSteps(config),\n {\n name: `Component ${comp.name}`,\n uses: `${comp.name}@${comp.version}`,\n ...(Object.keys(withMap).length > 0 ? { with: withMap } : {}),\n },\n ],\n };\n }\n\n return {\n id: jobId,\n name: jobId,\n runsOn: \"ubuntu-latest\",\n needs,\n steps: [],\n uses: `${comp.name}@${comp.version}`,\n ...(Object.keys(withMap).length > 0 ? { with: withMap } : {}),\n };\n}\n\n/**\n * Lower a child pipeline step to a GitHub job.\n * F-33: GitHub does not natively support dynamic child pipelines.\n * We emit a no-op job with a warning comment. The native engine handles\n * the actual dynamic generation.\n */\nfunction lowerChildPipelineStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n): GithubJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const needs = lowerDependencies(step.dependencies, jobIdMap);\n return {\n id: jobId,\n name: jobId,\n runsOn: resolveRunsOn(step),\n needs,\n steps: [\n {\n name: \"Dynamic child pipeline (not natively supported on GitHub)\",\n run: `echo \"WARNING: Dynamic child pipelines are not supported by GitHub Actions. Generator: ${step.childPipeline!.generator}, artifact: ${step.childPipeline!.artifact}\"`,\n },\n ],\n };\n}\n\n/**\n * Lower a downstream step to a GitHub job.\n * F-34: GitHub emulates downstream project triggers via repository_dispatch API.\n */\nfunction lowerDownstreamStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n): GithubJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const needs = lowerDependencies(step.dependencies, jobIdMap);\n const ds = step.downstream!;\n // Build client_payload from inputs using JSON.stringify for valid JSON.\n const payloadObj: Record<string, string> = {};\n if (ds.inputs) {\n for (const [name, value] of Object.entries(ds.inputs)) {\n payloadObj[name] = lowerReferenceExpr(value, jobIdMap) ?? String(value);\n }\n }\n const payload = JSON.stringify(payloadObj);\n // Pass the payload and optional branch through step env vars, then expand\n // them as quoted shell variables. JSON.stringify does not escape apostrophes\n // for a POSIX shell — embedding the payload in a single-quoted command would\n // break if a runtime value (after GitHub expression expansion) contains a\n // single quote. Env vars are expanded by the runner after GitHub expression\n // evaluation, so the shell receives the value as a single argument.\n const env: Record<string, string> = { CLIENT_PAYLOAD: payload };\n if (ds.branch) {\n env.DOWNSTREAM_BRANCH = ds.branch;\n }\n const refPart = ds.branch ? ` -f ref=\"$DOWNSTREAM_BRANCH\"` : \"\";\n return {\n id: jobId,\n name: jobId,\n runsOn: resolveRunsOn(step),\n needs,\n steps: [\n {\n name: `Trigger downstream: ${ds.project}`,\n env,\n run: `gh api repos/${ds.project}/dispatches -f event_type=sverka-trigger -f client_payload=\"$CLIENT_PAYLOAD\"${refPart}`,\n },\n ],\n };\n}\n\n/**\n * Lower a single Step to a GitHub job.\n */\nfunction lowerStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n config?: GithubTargetConfig,\n): GithubJob {\n const needs = lowerDependencies(step.dependencies, jobIdMap);\n const rawSteps = lowerOperations(step, jobIdMap, config);\n\n // GitHub only supports boolean continue-on-error, not exit-code mapping.\n if (\n step.continueOnError !== undefined &&\n typeof step.continueOnError !== \"boolean\"\n ) {\n throw new GithubTargetError(\n \"GitHub does not support exit-code continueOnError; use a boolean value\",\n \"UNSUPPORTED_FEATURE\",\n );\n }\n\n const steps = applyContinueOnError(rawSteps, step, config);\n\n const jobId = jobIdMap.get(step.id) ?? step.id;\n\n const runtime = step.runtime;\n const mode = runtime.mode ?? \"host\";\n const runsOn = resolveRunsOn(step);\n const container = resolveContainer(step, mode);\n const jobEnv = collectJobEnv(runtime);\n\n return assembleGithubJob({\n jobId,\n steps,\n needs,\n step,\n runsOn,\n container,\n jobEnv,\n jobIdMap,\n });\n}\n\n/**\n * Apply continueOnError to the step's own run commands. Injected setup\n * stays fail-fast — a failed dependency install must not be ignored.\n */\nfunction applyContinueOnError(\n rawSteps: readonly GithubStep[],\n step: StepDefinition,\n config?: GithubTargetConfig,\n): GithubStep[] {\n const infraSteps = new Set<GithubStep>(setupSteps(config));\n return rawSteps.map((s) =>\n step.continueOnError !== undefined &&\n s.run !== undefined &&\n !infraSteps.has(s)\n ? {\n ...s,\n continueOnError:\n typeof step.continueOnError === \"boolean\"\n ? step.continueOnError\n : true,\n }\n : s,\n );\n}\n\n/**\n * Insert a sleep step to emulate delay (GitHub has no native delayed execution).\n * Called after checkout + setup steps are pushed, so the delay precedes the\n * step's own work but does not postpone toolchain setup.\n */\nfunction applyDelay(steps: GithubStep[], step: StepDefinition): void {\n if (!step.delay) return;\n const sleepSeconds = parseDurationToSeconds(step.delay);\n steps.push({\n name: `Delay (${step.delay})`,\n run: `sleep ${sleepSeconds}`,\n });\n}\n\n/**\n * Collect scalar output names for the job's `outputs:` mapping.\n * GitHub Actions requires outputs to be declared at the job level for\n * `needs.<job>.outputs.<name>` expressions to work.\n */\nfunction collectJobOutputs(step: StepDefinition): Record<string, string> {\n const jobOutputs: Record<string, string> = {};\n for (const op of step.operations) {\n if (op.kind === \"exportOutput\") {\n jobOutputs[op.name] = `\\${{ steps.output.outputs.${op.name} }}`;\n }\n }\n return jobOutputs;\n}\n\n/**\n * Build the job's `steps` array, inserting a cache step after checkout when\n * caching is enabled. Checkout is always the first step.\n */\nfunction resolveJobSteps(\n steps: GithubStep[],\n step: StepDefinition,\n): GithubStep[] {\n if (step.cache === undefined) return steps;\n // Cache step goes after checkout (always first) and before other steps.\n return [steps[0]!, lowerCacheStep(step.cache), ...steps.slice(1)];\n}\n\n/**\n * Resolve the job-level `if` expression.\n *\n * Rules take precedence over condition when both are present, matching\n * GitHub's behavior where workflow rules override step conditions. Multiple\n * rules are OR'd: GitHub's job-level `if` is a single expression, so we\n * combine all rule `if` conditions with `||`.\n */\nfunction resolveJobIf(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n): Record<string, string> {\n if (step.rules !== undefined && step.rules.length > 0) {\n return { if: lowerRulesIf(step.rules) };\n }\n if (step.condition !== undefined) {\n return { if: lowerCondition(step.condition, jobIdMap) };\n }\n return {};\n}\n\n/**\n * Resolve job-level permissions and environment for Pages deploys and\n * identity-token requests.\n *\n * GitHub Pages jobs need pages:write and id-token:write permissions.\n * Safe-outputs (Spec 25): steps with permissions.write get a scoped\n * permissions block from write kinds. Steps without writes get\n * permissions: {} (read-only). deployPages/identity take precedence.\n */\nconst WRITE_KIND_TO_GHA_PERMISSION: Readonly<Record<string, string>> = {\n \"pull-request\": \"pull-requests: write\",\n comment: \"issues: write\",\n deploy: \"deployments: write\",\n push: \"contents: write\",\n \"id-token\": \"id-token: write\",\n pages: \"pages: write\",\n};\n\nfunction resolveJobPermissions(step: StepDefinition): Record<string, unknown> {\n if (step.operations.some((op) => op.kind === \"deployPages\")) {\n return {\n permissions: { pages: \"write\", \"id-token\": \"write\" },\n environment: { name: \"github-pages\" },\n };\n }\n if (step.identity !== undefined) {\n return { permissions: { \"id-token\": \"write\" } };\n }\n // Safe-outputs: derive permissions from write declarations.\n // Only emit a permissions block when step.permissions is explicitly set.\n if (step.permissions !== undefined) {\n const writes = step.permissions.write;\n if (writes && writes.length > 0) {\n const perms: Record<string, string> = {};\n for (const decl of writes) {\n const mapped = WRITE_KIND_TO_GHA_PERMISSION[decl.kind];\n if (mapped !== undefined) {\n const [scope, level] = mapped.split(\": \");\n perms[scope!] = level!;\n } else {\n // Unknown kind → safe default\n perms[\"contents\"] = \"read\";\n }\n }\n return { permissions: perms };\n }\n // permissions set but no writes → explicit read-only\n return { permissions: {} };\n }\n // No permissions set → backward compatible (no permissions key)\n return {};\n}\n\n/**\n * Constituent parts for assembling a GithubJob.\n */\ninterface GithubJobParts {\n readonly jobId: string;\n readonly steps: GithubStep[];\n readonly needs: readonly string[];\n readonly step: StepDefinition;\n readonly runsOn: GithubRunsOn;\n readonly container: string | undefined;\n readonly jobEnv: Record<string, string>;\n readonly jobIdMap: Map<string, string>;\n}\n\n/**\n * Assemble the final GithubJob object from its constituent parts.\n */\nfunction assembleGithubJob(parts: GithubJobParts): GithubJob {\n const { jobId, steps, needs, step, runsOn, container, jobEnv, jobIdMap } =\n parts;\n const jobOutputs = collectJobOutputs(step);\n const jobIf = resolveJobIf(step, jobIdMap);\n const jobPermissions = resolveJobPermissions(step);\n\n return {\n id: jobId,\n name: jobId,\n runsOn,\n needs,\n ...(Object.keys(jobOutputs).length > 0 ? { outputs: jobOutputs } : {}),\n steps: resolveJobSteps(steps, step),\n ...(step.timeout !== undefined\n ? { timeoutMinutes: Math.ceil(step.timeout / 60000) }\n : {}),\n ...(Object.keys(jobEnv).length > 0 ? { env: jobEnv } : {}),\n ...(container ? { container } : {}),\n ...(step.matrix !== undefined\n ? { strategy: lowerStrategy(step.matrix) }\n : {}),\n ...jobIf,\n ...jobPermissions,\n ...resolveJobServices(step),\n ...resolveJobEnvironment(step),\n ...(step.concurrency !== undefined\n ? { concurrency: step.concurrency }\n : {}),\n };\n}\n\n/** Resolve job-level services field from step services. */\nfunction resolveJobServices(step: StepDefinition): Partial<GithubJob> {\n if (step.services === undefined || step.services.length === 0) return {};\n return { services: lowerServices(step.services) };\n}\n\n/** Resolve job-level environment field from step environment spec. */\nfunction resolveJobEnvironment(step: StepDefinition): Partial<GithubJob> {\n if (step.environment === undefined) return {};\n return {\n environment: {\n name: step.environment.name,\n ...(step.environment.url !== undefined\n ? { url: step.environment.url }\n : {}),\n },\n };\n}\n\n/**\n * Lower a cache spec to a GitHub cache step.\n * pull-push → actions/cache@v4\n * pull → actions/cache/restore@v4\n * push → actions/cache/save@v4\n */\nfunction lowerCacheStep(cache: CacheSpec): GithubStep {\n const policy = cache.policy ?? \"pull-push\";\n let action = \"actions/cache@v4\";\n if (policy === \"pull\") {\n action = \"actions/cache/restore@v4\";\n } else if (policy === \"push\") {\n action = \"actions/cache/save@v4\";\n }\n const withMap: Record<string, unknown> = {\n path: cache.paths.length === 1 ? cache.paths[0] : cache.paths.join(\"\\n\"),\n key: cache.key,\n };\n if (cache.restoreKeys !== undefined && cache.restoreKeys.length > 0) {\n withMap[\"restore-keys\"] =\n cache.restoreKeys.length === 1\n ? cache.restoreKeys[0]\n : cache.restoreKeys.join(\"\\n\");\n }\n return {\n name: \"Restore cache\",\n uses: action,\n with: withMap,\n };\n}\n\n/**\n * Lower service containers to GitHub services map (keyed by name).\n */\nfunction lowerServices(\n services: readonly ServiceContainer[],\n): Readonly<Record<string, GithubService>> {\n const result: Record<string, GithubService> = {};\n for (const svc of services) {\n // GitHub Actions does not support `entrypoint` or `command` on services.\n // Translate them to Docker `options` as a best-effort emulation.\n const options: string[] = [];\n if (svc.entrypoint !== undefined) {\n options.push(`--entrypoint=${svc.entrypoint[0] ?? \"\"}`);\n }\n const service: GithubService = {\n image: svc.image,\n ...(svc.env !== undefined ? { env: { ...svc.env } } : {}),\n ...(svc.ports !== undefined\n ? { ports: svc.ports.map((p) => `${p}:${p}`) }\n : {}),\n ...(options.length > 0 ? { options: options.join(\" \") } : {}),\n };\n result[svc.name] = service;\n }\n return result;\n}\n\nfunction resolveRunsOn(step: StepDefinition): GithubRunsOn {\n if (step.runner === undefined) {\n return \"ubuntu-latest\";\n }\n const { labels, group } = step.runner;\n if (group !== undefined) {\n return { group, labels };\n }\n if (labels.length === 1) {\n return labels[0]!;\n }\n return labels;\n}\n\n/**\n * Parse a duration string (e.g. \"5m\", \"30s\", \"1h\") to seconds.\n * F-48: used for GitHub sleep emulation.\n */\nfunction parseDurationToSeconds(duration: string): number {\n const match = /^(\\d+)\\s*(s|m|h|seconds?|minutes?|hours?)?$/i.exec(duration);\n if (!match) {\n throw new GithubTargetError(\n `invalid delay duration '${duration}'`,\n \"LOWER_FAILED\",\n );\n }\n const value = Number.parseInt(match[1]!, 10);\n const unit = (match[2] ?? \"s\").toLowerCase();\n if (unit.startsWith(\"h\")) return value * 3600;\n if (unit.startsWith(\"m\")) return value * 60;\n return value;\n}\n\nfunction resolveContainer(\n step: StepDefinition,\n mode: string,\n): string | undefined {\n if (mode === \"container\" && !step.runtime.image) {\n throw new GithubTargetError(\n `step '${step.id}' uses container mode without an image`,\n \"LOWER_FAILED\",\n );\n }\n return mode === \"container\" ? step.runtime.image : undefined;\n}\n\nfunction collectJobEnv(\n runtime: StepDefinition[\"runtime\"],\n): Record<string, string> {\n const jobEnv: Record<string, string> = {};\n if (runtime.env) {\n Object.assign(jobEnv, runtime.env);\n }\n if (runtime.secrets) {\n for (const secret of runtime.secrets) {\n jobEnv[secret] = `\\${{ secrets.${secret} }}`;\n }\n }\n return jobEnv;\n}\n\n/**\n * Map dependencies to job needs.\n * All dependency kinds create needs (GitHub jobs can't share values without artifacts).\n */\nfunction lowerDependencies(\n deps: readonly Dependency[],\n jobIdMap: Map<string, string>,\n): readonly string[] {\n const needs = new Set<string>();\n for (const dep of deps) {\n // Map full step ID to GitHub job ID.\n const jobId = jobIdMap.get(dep.producer);\n if (!jobId) {\n throw new GithubTargetError(\n `step depends on unknown producer '${dep.producer}'`,\n \"INVALID_GRAPH\",\n );\n }\n needs.add(jobId);\n }\n return [...needs];\n}\n\n/**\n * Map operations to GitHub steps in original order.\n * Consecutive shell/exportOutput operations are combined into one run step.\n */\nfunction lowerOperations(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n config?: GithubTargetConfig,\n): readonly GithubStep[] {\n const steps: GithubStep[] = [];\n const shortStepId = step.id.includes(\"/\")\n ? step.id.split(\"/\").pop()!\n : step.id;\n\n // Every job needs the repository checked out, then toolchain/dependency\n // setup runs before everything else.\n steps.push(checkoutStep(config), ...setupSteps(config));\n\n // F-48: delay → sleep after toolchain setup, before the step's own work.\n applyDelay(steps, step);\n\n // Spec 26: network allowlist annotation (GHA has no native per-job egress control).\n if (step.runtime.network && step.runtime.network.allowed.length > 0) {\n steps.push({\n name: \"Sverka network allowlist\",\n run: `echo \"# sverka:network-allowlist: ${step.runtime.network.allowed.join(\",\")}\"`,\n });\n }\n\n // beforeScript → run steps before main operations.\n if (step.beforeScript) {\n for (const cmd of step.beforeScript) {\n steps.push({ run: cmd });\n }\n }\n\n let runLines: string[] = [];\n let runHasOutput = false;\n // exportStdout ops bind to the most recent shell op's captured stdout.\n // stdoutTargetIndex marks that op's line inside runLines; stdoutNames are\n // the artifact names declared against it; stdoutUploadNames collects every\n // name whose upload-artifact step follows the flushed run step.\n let stdoutTargetIndex: number | undefined;\n let stdoutNames: string[] = [];\n let stdoutUploadNames: string[] = [];\n\n function sealStdoutCapture(): void {\n if (stdoutTargetIndex === undefined || stdoutNames.length === 0) return;\n runLines[stdoutTargetIndex] = wrapStdoutCaptureLine(\n runLines[stdoutTargetIndex]!,\n stdoutNames,\n );\n stdoutUploadNames.push(...stdoutNames);\n stdoutNames = [];\n }\n\n function flushRun(): void {\n sealStdoutCapture();\n if (runLines.length === 0) return;\n const combined = runLines.join(\"\\n\");\n const translated = translateCommand(combined, step.inputs, jobIdMap);\n steps.push({\n // Give the step an id when it contains exportOutput so job-level outputs can reference it.\n ...(runHasOutput ? { id: \"output\" } : {}),\n run: translated,\n ...(step.runtime.workingDir\n ? { workingDirectory: step.runtime.workingDir }\n : {}),\n ...(step.runtime.shell ? { shell: step.runtime.shell } : {}),\n });\n for (const name of stdoutUploadNames) {\n // The runtime persists stdout artifacts even when the shell command\n // fails, so the upload must run unconditionally. The capture writes\n // the file inside the step's working directory when one is set.\n steps.push({\n name: `Upload ${name}`,\n if: \"always()\",\n uses: \"actions/upload-artifact@v7\",\n with: {\n name: artifactName(shortStepId, name),\n path: step.runtime.workingDir\n ? `${step.runtime.workingDir}/${name}`\n : name,\n },\n });\n }\n runLines = [];\n runHasOutput = false;\n stdoutTargetIndex = undefined;\n stdoutUploadNames = [];\n }\n\n for (const op of step.operations) {\n if (op.kind === \"exportOutput\") runHasOutput = true;\n switch (op.kind) {\n case \"shell\":\n // Seal any pending stdout capture before the new command becomes the\n // most recent shell op.\n sealStdoutCapture();\n // F-49: background shell → append & for async execution.\n runLines.push(op.background ? `${op.command} &` : op.command);\n stdoutTargetIndex = runLines.length - 1;\n break;\n case \"exportStdout\":\n if (stdoutTargetIndex === undefined) {\n throw new GithubTargetError(\n `step '${step.id}' declares stdout artifact '${op.name}' but no shell output was captured`,\n \"LOWER_FAILED\",\n );\n }\n if (\n step.runtime.shell !== undefined &&\n !isPosixShell(step.runtime.shell)\n ) {\n throw new GithubTargetError(\n `step '${step.id}' declares stdout artifact '${op.name}' but shell '${step.runtime.shell}' is not POSIX-compatible`,\n \"LOWER_FAILED\",\n );\n }\n stdoutNames.push(op.name);\n break;\n default:\n lowerOperation(op, shortStepId, steps, runLines, flushRun);\n }\n }\n\n flushRun();\n\n // afterScript → run steps after main operations with if: always().\n if (step.afterScript) {\n for (const cmd of step.afterScript) {\n steps.push({ run: cmd, if: \"always()\" });\n }\n }\n\n return steps;\n}\n\n/** Shells whose run scripts understand POSIX syntax (brace groups, `||`, `[ ]`). */\nconst POSIX_SHELLS = new Set([\"sh\", \"bash\", \"dash\", \"ash\", \"zsh\", \"ksh\"]);\n\nfunction isPosixShell(shell: string): boolean {\n const space = shell.indexOf(\" \");\n return POSIX_SHELLS.has(space === -1 ? shell : shell.slice(0, space));\n}\n\nfunction lowerOperation(\n op: OperationDefinition,\n shortStepId: string,\n steps: GithubStep[],\n runLines: string[],\n flushRun: () => void,\n): void {\n switch (op.kind) {\n case \"exportOutput\":\n runLines.push(`echo \"${op.name}=\\${${op.name}}\" >> \"$GITHUB_OUTPUT\"`);\n break;\n case \"exportArtifact\":\n flushRun();\n steps.push({\n name: `Upload ${op.name}`,\n uses: \"actions/upload-artifact@v7\",\n with: {\n name: artifactName(shortStepId, op.name),\n path: op.path,\n ...(op.retention !== undefined\n ? { \"retention-days\": parseRetentionDays(op.retention) }\n : {}),\n },\n });\n break;\n case \"importArtifact\":\n lowerImportArtifact(op, steps, flushRun);\n break;\n case \"diagnostic\":\n lowerDiagnostic(op, steps, flushRun);\n break;\n case \"report\":\n flushRun();\n steps.push(lowerReport(op.spec));\n break;\n case \"release\":\n lowerRelease(op, steps, flushRun);\n break;\n case \"deployPages\":\n lowerDeployPages(op, steps, flushRun);\n break;\n default:\n throw new GithubTargetError(\n `unsupported operation kind: ${JSON.stringify((op as OperationDefinition).kind)}`,\n \"LOWER_FAILED\",\n );\n }\n}\n\n/**\n * Lower a release operation to a GitHub release step.\n * F-39: uses softprops/action-gh-release@v2.\n */\nfunction lowerRelease(\n op: Extract<OperationDefinition, { kind: \"release\" }>,\n steps: GithubStep[],\n flushRun: () => void,\n): void {\n flushRun();\n const withMap: Record<string, unknown> = {\n tag_name: op.tag,\n };\n if (op.name) withMap.name = op.name;\n if (op.description) withMap.body = op.description;\n if (op.assets && op.assets.length > 0) withMap.files = op.assets.join(\"\\n\");\n if (op.draft !== undefined) withMap.draft = op.draft;\n if (op.prerelease !== undefined) withMap.prerelease = op.prerelease;\n steps.push({\n name: `Release ${op.tag}`,\n uses: \"softprops/action-gh-release@v2\",\n with: withMap,\n });\n}\n\n/**\n * Lower a deployPages operation to GitHub Pages deployment steps.\n * F-40: uses actions/upload-pages-artifact + actions/deploy-pages.\n */\nfunction lowerDeployPages(\n op: Extract<OperationDefinition, { kind: \"deployPages\" }>,\n steps: GithubStep[],\n flushRun: () => void,\n): void {\n flushRun();\n // Upload the pages artifact, then deploy.\n steps.push(\n {\n name: \"Upload Pages artifact\",\n uses: \"actions/upload-pages-artifact@v3\",\n with: { path: op.path },\n },\n {\n name: \"Deploy to GitHub Pages\",\n uses: \"actions/deploy-pages@v4\",\n id: \"deployment\",\n },\n );\n}\n\nfunction lowerImportArtifact(\n op: Extract<OperationDefinition, { kind: \"importArtifact\" }>,\n steps: GithubStep[],\n flushRun: () => void,\n): void {\n flushRun();\n const fromShort = op.from.includes(\"/\") ? op.from.split(\"/\").pop()! : op.from;\n steps.push({\n name: `Download ${op.output}`,\n uses: \"actions/download-artifact@v8\",\n with: { name: artifactName(fromShort, op.output), path: op.output },\n });\n}\n\nfunction lowerDiagnostic(\n op: Extract<OperationDefinition, { kind: \"diagnostic\" }>,\n steps: GithubStep[],\n flushRun: () => void,\n): void {\n flushRun();\n const severityFlag = severityFlagFor(op.severity);\n const escapedMessage = op.message\n .replace(/%/g, \"%25\")\n .replace(/\\r\\n/g, \"%0D%0A\")\n .replace(/\\n/g, \"%0A\")\n .replace(/\\r/g, \"%0D\");\n steps.push({\n env: { SVERKA_DIAGNOSTIC_MESSAGE: escapedMessage },\n run: String.raw`printf '%s\\n' \"::${severityFlag}::$SVERKA_DIAGNOSTIC_MESSAGE\"`,\n });\n}\n\n/**\n * Generate a deterministic artifact name from step ID and output name.\n */\nfunction artifactName(stepId: string, outputName: string): string {\n return `${stepId}-${outputName}`;\n}\n\n/**\n * Parse a duration string (e.g., \"7d\", \"1h\", \"30m\", \"never\") into days.\n * Returns undefined for \"never\" (no retention limit).\n */\nfunction parseRetentionDays(retention: string): number | undefined {\n if (retention === \"never\") return undefined;\n const match = /^(\\d+)([dhm])$/.exec(retention);\n if (match === null) return undefined;\n const value = Number.parseInt(match[1]!, 10);\n const unit = match[2];\n if (unit === \"d\") return value;\n if (unit === \"h\") return Math.ceil(value / 24);\n if (unit === \"m\") return Math.ceil(value / (60 * 24));\n return undefined;\n}\n\n/**\n * Lower a report spec to a GitHub action step.\n * Maps report types to known GitHub actions.\n */\nfunction lowerReport(spec: ReportSpec): GithubStep {\n switch (spec.type) {\n case \"junit\":\n return {\n name: `Report ${spec.type}`,\n uses: \"dorny/test-reporter@v1\",\n with: {\n name: \"Tests\",\n path: spec.path,\n reporter: \"java-junit\",\n },\n };\n case \"sarif\":\n case \"sast\":\n return {\n name: `Upload ${spec.type}`,\n uses: \"github/codeql-action/upload-sarif@v3\",\n with: { sarif_file: spec.path },\n };\n default:\n // No standard action — upload as generic artifact\n return {\n name: `Upload ${spec.type} report`,\n uses: \"actions/upload-artifact@v7\",\n with: { name: `${spec.type}-report`, path: spec.path },\n };\n }\n}\n\n/**\n * Collect pipeline-level env vars from inputs.\n * Secret inputs are referenced via `${{ secrets.<name> }}` instead of\n * literal defaults.\n */\nfunction collectEnv(pipeline: PipelineDefinition): Record<string, string> {\n const env: Record<string, string> = {};\n for (const [name, input] of Object.entries(pipeline.inputs)) {\n if (input.secret) {\n env[name] = `\\${{ secrets.${name} }}`;\n } else if (input.default !== undefined) {\n env[name] = String(input.default);\n }\n }\n return env;\n}\n\nfunction severityFlagFor(severity: string): string {\n if (severity === \"error\") return \"error\";\n if (severity === \"warn\") return \"warning\";\n return \"notice\";\n}\n\n// ---------------------------------------------------------------------------\n// Matrix lowering (F-15, F-16)\n// ---------------------------------------------------------------------------\n\n/**\n * Lower a MatrixSpec to a GitHub strategy object.\n * dimensions → matrix variables, include → include:, exclude → exclude:.\n * failFast → fail-fast, maxParallel → max-parallel.\n */\nfunction lowerStrategy(spec: MatrixSpec): {\n readonly matrix: Record<string, unknown>;\n readonly failFast?: boolean;\n readonly maxParallel?: number;\n} {\n const matrix: Record<string, unknown> = {};\n for (const [key, values] of Object.entries(spec.dimensions)) {\n matrix[key] = [...values];\n }\n if (spec.include && spec.include.length > 0) {\n matrix.include = spec.include.map((entry) => ({ ...entry }));\n }\n if (spec.exclude && spec.exclude.length > 0) {\n matrix.exclude = spec.exclude.map((entry) => ({ ...entry }));\n }\n return {\n matrix,\n ...(spec.failFast !== undefined ? { failFast: spec.failFast } : {}),\n ...(spec.maxParallel !== undefined\n ? (() => {\n if (!Number.isInteger(spec.maxParallel) || spec.maxParallel <= 0) {\n throw new GithubTargetError(\n `maxParallel must be a positive integer, got ${spec.maxParallel}`,\n \"INVALID_MATRIX\",\n );\n }\n return { maxParallel: spec.maxParallel };\n })()\n : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Context ref translation (F-35)\n// ---------------------------------------------------------------------------\n\nconst GITHUB_CONTEXT_MAP: Readonly<Record<string, string>> = {\n \"git.sha\": \"github.sha\",\n \"git.branch\": \"github.ref_name\",\n \"git.tag\": \"github.ref_name\",\n \"change.id\": \"github.event.pull_request.number\",\n \"change.source\": \"github.event_name\",\n \"change.target\": \"github.base_ref\",\n \"change.draft\": \"github.event.pull_request.draft\",\n \"event.type\": \"github.event_name\",\n \"run.id\": \"github.run_id\",\n \"run.attempt\": \"github.run_attempt\",\n};\n\n/**\n * Translate a context ref (namespace.field) to GitHub expression syntax.\n * Secrets are sink-specific:\n * - In `with:` inputs (`forWithInput = true`): `${{ secrets.FIELD }}`.\n * GitHub Actions does not expand `$FIELD` in `with:` values — it treats it\n * as a literal string. The `secrets` context is the correct syntax here.\n * - In `run:` commands (`forWithInput = false`): `$FIELD` (env var, avoids\n * exposing secret values in run logs).\n * In conditions, secrets are not supported by GitHub's if: context and are\n * emitted as env var references instead.\n */\nfunction translateContextRef(\n namespace: string,\n field: string,\n inCondition = false,\n forWithInput = false,\n): string {\n const key = `${namespace}.${field}`;\n const mapped = GITHUB_CONTEXT_MAP[key];\n if (mapped) return `\\${{ ${mapped} }}`;\n // env.X → ${{ env.FIELD }} (GitHub env context)\n if (namespace === \"env\") {\n return `\\${{ env.${field} }}`;\n }\n if (namespace === \"matrix\") {\n return `\\${{ matrix.${field} }}`;\n }\n // inputs.X → ${{ env.FIELD }} (pipeline inputs are lowered to workflow env)\n if (namespace === \"inputs\") {\n return `\\${{ env.${field} }}`;\n }\n // secrets.X in with: inputs → ${{ secrets.FIELD }} (GitHub expands the\n // secrets context in with: values, but does NOT expand $FIELD there).\n // secrets.X in commands → $FIELD (env var, avoids exposing value in logs)\n // secrets.X in conditions → not supported by GitHub if: context\n if (namespace === \"secrets\") {\n if (inCondition) {\n // GitHub does not support secrets context in if: expressions.\n // Use env var reference instead (secret is injected as env var).\n return `\\${{ env.${field} }}`;\n }\n if (forWithInput) {\n return `\\${{ secrets.${field} }}`;\n }\n return `$${field}`;\n }\n // Unknown namespace — fail lowering rather than emit invalid expression\n throw new GithubTargetError(\n `unsupported context namespace '${namespace}' in GitHub lowering`,\n \"LOWER_FAILED\",\n );\n}\n\n/**\n * Translate a step ref to GitHub needs.<jobId>.outputs.<output> syntax.\n * Each Sverka step is lowered to a separate GitHub job, so cross-step\n * references must use the 'needs' context, not 'steps'.\n */\nfunction translateStepRef(ref: StepRef, jobIdMap: Map<string, string>): string {\n const jobId = jobIdMap.get(ref.step) ?? ref.step;\n return `\\${{ needs.${jobId}.outputs.${ref.output} }}`;\n}\n\n/**\n * Build a lookup map from placeholder key (\"namespace.field\" or \"step.output\")\n * to the Reference from the step's inputs array.\n */\nfunction buildInputLookup(\n inputs: readonly Reference[],\n): Map<string, Reference> {\n const map = new Map<string, Reference>();\n for (const ref of inputs) {\n if (ref.kind === \"context\") {\n map.set(`${ref.namespace}.${ref.field}`, ref);\n } else if (ref.kind === \"step\") {\n map.set(`${ref.step}.${ref.output}`, ref);\n }\n }\n return map;\n}\n\n/**\n * Translate ${...} placeholders in a command string to GitHub expression syntax.\n * Placeholders matching a known input ref are translated; others are left as-is.\n */\nfunction translateCommand(\n command: string,\n inputs: readonly Reference[],\n jobIdMap: Map<string, string>,\n): string {\n const lookup = buildInputLookup(inputs);\n return command.replace(/\\$\\{([^{}]+)\\}/g, (_, key: string) => {\n const ref = lookup.get(key);\n if (ref === undefined) {\n // Not a known ref — leave as literal shell variable\n return `\\${${key}}`;\n }\n if (ref.kind === \"context\") {\n return translateContextRef(ref.namespace, ref.field, false);\n }\n return translateStepRef(ref, jobIdMap);\n });\n}\n\n/**\n * Lower step rules to a single GitHub `if:` expression.\n * Multiple rules are OR'd with `||`. Rules with `when: never` produce `false`.\n * Rules without an `if` but with `when: always` produce `true`.\n */\nfunction lowerRulesIf(rules: readonly Rule[]): string {\n const parts: string[] = [];\n for (const rule of rules) {\n if (rule.when === \"never\") {\n parts.push(\"${{ false }}\");\n } else if (rule.if !== undefined) {\n parts.push(rule.if);\n } else if (rule.when === \"always\") {\n parts.push(\"${{ true }}\");\n }\n }\n if (parts.length === 0) return \"${{ true }}\";\n if (parts.length === 1) return parts[0]!;\n return parts.map((p) => p.replace(/^\\$\\{\\{|\\}\\}$/g, \"\").trim()).join(\" || \");\n}\n\n/**\n * Lower a step condition to a GitHub if: expression.\n */\nfunction lowerCondition(\n condition: Reference | Expression | StatusCondition,\n jobIdMap: Map<string, string>,\n): string {\n if (condition.kind === \"status\") {\n // GitHub status conditions map to built-in condition functions\n if (condition.status === \"always\") return \"${{ always() }}\";\n if (condition.status === \"never\") return \"${{ false }}\";\n if (condition.status === \"failure\") return \"${{ failure() }}\";\n return \"${{ success() }}\";\n }\n if (condition.kind === \"context\") {\n return `\\${{ ${stripBraces(translateContextRef(condition.namespace, condition.field, true))} }}`;\n }\n if (condition.kind === \"step\") {\n return translateStepRef(condition, jobIdMap);\n }\n // Expression — translate each ${...} placeholder\n const lookup = buildInputLookup(condition.refs);\n const translated = condition.template.replace(\n /\\$\\{([^{}]+)\\}/g,\n (_, key: string) => {\n const ref = lookup.get(key);\n if (ref === undefined) return `\\${${key}}`;\n if (ref.kind === \"context\") {\n return stripBraces(translateContextRef(ref.namespace, ref.field, true));\n }\n return stripBraces(translateStepRef(ref, jobIdMap));\n },\n );\n return `\\${{ ${translated} }}`;\n}\n\n/** Strip the `${{ ... }}` wrapper, returning the inner expression. */\nfunction stripBraces(s: string): string {\n // Match ${{ ... }} and extract inner content, trimming whitespace.\n // Uses anchored pattern without nested quantifiers to avoid ReDoS.\n if (!s.startsWith(\"${{\") || !s.endsWith(\"}}\")) return s;\n return s.slice(3, -2).trim();\n}\n","// Emit: GithubTargetGraph → YAML artifacts.\n// Spec 08 — §19. F-31: multi-workflow emission. Spec 22 — action pinning.\n\nimport { stringify } from \"yaml\";\nimport type {\n GithubTargetGraph,\n GithubJob,\n GithubStep,\n GeneratedArtifact,\n} from \"./types.js\";\n\n/** Optional emit-time transforms (spec 22: action SHA pinning). */\nexport interface EmitOptions {\n /** When set, every emitted `uses:` ref is routed through this function. */\n readonly pinUses?: (ref: string) => string;\n}\n\n/**\n * Emit one or more GithubTargetGraphs as YAML artifacts.\n * Produces one .github/workflows/<name>.yml file per target graph.\n */\nexport function emitGithub(\n targetGraph: GithubTargetGraph | readonly GithubTargetGraph[],\n options?: EmitOptions,\n): readonly GeneratedArtifact[] {\n const graphs = Array.isArray(targetGraph) ? targetGraph : [targetGraph];\n return graphs.map((g) => ({\n path: `.github/workflows/${sanitizeWorkflowName(g.name)}.yml`,\n content: stringifyTargetGraph(g, options),\n }));\n}\n\n/**\n * Sanitize a graph name for use as a workflow filename.\n * GitHub workflow filenames must be valid path segments; replace\n * characters that could break path resolution.\n */\nfunction sanitizeWorkflowName(name: string): string {\n return name.replace(/[^a-zA-Z0-9._-]/g, \"-\");\n}\n\n/**\n * Convert a GithubTargetGraph to a YAML string.\n */\nfunction stringifyTargetGraph(\n graph: GithubTargetGraph,\n options?: EmitOptions,\n): string {\n const doc: Record<string, unknown> = {\n name: graph.name,\n on: graph.on,\n };\n\n if (Object.keys(graph.env).length > 0) {\n doc.env = graph.env;\n }\n\n if (graph.permissions) {\n doc.permissions = graph.permissions;\n }\n\n if (graph.defaults) {\n doc.defaults = graph.defaults;\n }\n\n if (graph.concurrency) {\n doc.concurrency = concurrencyToYaml(graph.concurrency);\n }\n\n const jobs: Record<string, unknown> = {};\n for (const job of graph.jobs) {\n jobs[job.id] = jobToYaml(job, options);\n }\n doc.jobs = jobs;\n\n // GitHub Actions does not support YAML anchors — never alias repeated\n // objects (e.g. identical `with:` maps injected into every job).\n let yaml = stringify(doc, {\n sortMapEntries: false,\n aliasDuplicateObjects: false,\n });\n\n // Pinned refs carry the original tag as a trailing YAML comment\n // (`org/name@<sha> # v4`). The serializer quotes such scalars, which would\n // make GitHub treat the whole string — comment included — as the ref.\n // Unquote `uses:` lines so the ` # ` part stays a real comment.\n yaml = yaml.replaceAll(\n /^(\\s*uses:\\s*)[\"']([^\"']+@[0-9a-f]{40}) # ([^\"']+)[\"']$/gm,\n \"$1$2 # $3\",\n );\n return yaml;\n}\n\n/**\n * Convert a GithubJob to a YAML-compatible object.\n */\nfunction jobToYaml(\n job: GithubJob,\n options?: EmitOptions,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {\n name: job.name,\n };\n\n // Reusable workflow call job: uses/with/secrets (no runs-on/steps).\n if (job.uses) {\n return reusableJobToYaml(job, result, options);\n }\n\n // Normal job.\n result[\"runs-on\"] = job.runsOn;\n\n if (job.needs.length > 0) {\n result.needs = job.needs.length === 1 ? job.needs[0] : [...job.needs];\n }\n\n if (job.timeoutMinutes !== undefined) {\n result[\"timeout-minutes\"] = job.timeoutMinutes;\n }\n\n if (job.container) {\n result.container = job.container;\n }\n\n if (job.env) {\n result.env = job.env;\n }\n\n if (job.strategy) {\n result.strategy = strategyToYaml(job.strategy);\n }\n\n if (job.permissions) {\n result.permissions = job.permissions;\n }\n\n if (job.if) {\n result.if = job.if;\n }\n\n if (job.services) {\n result.services = job.services;\n }\n\n if (job.environment) {\n result.environment = job.environment;\n }\n\n if (job.concurrency) {\n result.concurrency = concurrencyToYaml(job.concurrency);\n }\n\n result.steps = job.steps.map((step, i) => stepToYaml(step, i, options));\n\n return result;\n}\n\n/**\n * Convert a job strategy spec to a YAML-compatible object.\n */\nfunction strategyToYaml(\n strategy: NonNullable<GithubJob[\"strategy\"]>,\n): Record<string, unknown> {\n const strat: Record<string, unknown> = { matrix: strategy.matrix };\n if (strategy.failFast !== undefined) {\n strat[\"fail-fast\"] = strategy.failFast;\n }\n if (strategy.maxParallel !== undefined) {\n strat[\"max-parallel\"] = strategy.maxParallel;\n }\n return strat;\n}\n\n/**\n * Convert a reusable workflow call job (uses) to a YAML-compatible object.\n */\nfunction reusableJobToYaml(\n job: GithubJob,\n result: Record<string, unknown>,\n options?: EmitOptions,\n): Record<string, unknown> {\n result.uses = options?.pinUses ? options.pinUses(job.uses!) : job.uses;\n if (job.needs.length > 0) {\n result.needs = job.needs.length === 1 ? job.needs[0] : [...job.needs];\n }\n if (job.with && Object.keys(job.with).length > 0) {\n result.with = job.with;\n }\n if (job.secrets) {\n result.secrets = job.secrets;\n }\n return result;\n}\n\n/**\n * Convert a concurrency spec to a YAML-compatible object.\n */\nfunction concurrencyToYaml(conc: {\n readonly group: string;\n readonly cancelInProgress?: boolean;\n}): Record<string, unknown> {\n const result: Record<string, unknown> = { group: conc.group };\n if (conc.cancelInProgress !== undefined) {\n result[\"cancel-in-progress\"] = conc.cancelInProgress;\n }\n return result;\n}\n\n/**\n * Convert a GithubStep to a YAML-compatible object.\n */\nfunction stepToYaml(\n step: GithubStep,\n index: number,\n options?: EmitOptions,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n // GitHub steps require a name or uses or run.\n if (step.id) {\n result.id = step.id;\n }\n if (step.name) {\n result.name = step.name;\n } else if (!step.uses && !step.run) {\n result.name = `Step ${index + 1}`;\n }\n\n if (step.uses) {\n result.uses = options?.pinUses ? options.pinUses(step.uses) : step.uses;\n }\n if (step.run) {\n result.run = step.run;\n }\n if (step.with) {\n result.with = step.with;\n }\n if (step.env) {\n result.env = step.env;\n }\n if (step.workingDirectory) {\n result[\"working-directory\"] = step.workingDirectory;\n }\n if (step.shell) {\n result.shell = step.shell;\n }\n\n if (step.if) {\n result.if = step.if;\n }\n\n if (step.continueOnError !== undefined) {\n result[\"continue-on-error\"] = step.continueOnError;\n }\n\n return result;\n}\n","","// GHA action SHA pinning. Spec 22 — §19, §31.3, §26.\n//\n// Pins third-party `uses:` refs to immutable commit SHAs sourced from a\n// bundled registry (no network access at compile time — §31.3). Pinned\n// output embeds the original version as a comment for auditability:\n// `actions/checkout@<sha> # v4`.\n\nimport bundledRegistry from \"./pinned-actions.json\" with { type: \"json\" };\n\n/** Registry mapping `org/name@vN` refs to 40-char commit SHAs. */\nexport interface PinRegistry {\n readonly [ref: string]: string;\n}\n\n/** Pinning configuration for {@link GithubTarget}. */\nexport interface PinningConfig {\n /** `\"strict\"` pins known refs and errors on missing entries; `\"off\"` leaves refs unchanged. */\n readonly mode: \"strict\" | \"off\";\n /** Custom registry; defaults to the bundled `pinned-actions.json`. */\n readonly registry?: PinRegistry;\n}\n\nconst SHA_RE = /^[0-9a-f]{40}$/;\n\n/**\n * Pin a single `uses:` ref to its commit SHA.\n *\n * Rules (spec 22 §\"Data models\"):\n * 1. Local action (`./…`) → unchanged.\n * 2. Already pinned (`@<40 hex>`) → unchanged.\n * 3. `org/name@vN` in registry → `org/name@<sha> # vN`.\n * 4. `org/name@vN` not in registry → unchanged (caller emits a diagnostic).\n *\n * Refs without `@` (malformed) are returned unchanged.\n */\nexport function pinActionRef(ref: string, registry: PinRegistry): string {\n // Rule 1: local action.\n if (ref.startsWith(\"./\")) return ref;\n\n const at = ref.lastIndexOf(\"@\");\n if (at < 0) return ref; // malformed — no @\n\n const head = ref.slice(0, at);\n const tail = ref.slice(at + 1);\n\n // Rule 2: already pinned to a 40-hex SHA.\n if (SHA_RE.test(tail)) return ref;\n\n const sha = registry[ref];\n // Rule 4: not in registry — unchanged.\n if (!sha) return ref;\n\n // Rule 3: pin and embed the version as a comment.\n return `${head}@${sha} # ${tail}`;\n}\n\n/**\n * Load the bundled `pinned-actions.json` registry.\n */\nexport function loadBundledRegistry(): PinRegistry {\n return bundledRegistry as PinRegistry;\n}\n","// GithubTarget — implements the Target contract (§19).\n// Spec 08 — §18.1, §19. Spec 22 — action SHA pinning.\n\nimport type { DefinitionGraph } from \"@sverka/workflow\";\nimport type { CapabilityManifest, Target } from \"../plugin/index.js\";\nimport { analyzeCapabilities } from \"../plugin/index.js\";\nimport { githubCapabilities } from \"./capabilities.js\";\nimport { lowerGithub } from \"./lower.js\";\nimport { emitGithub } from \"./emit.js\";\nimport { pinActionRef, loadBundledRegistry } from \"./pinning.js\";\nimport type { PinRegistry } from \"./pinning.js\";\nimport type {\n GithubTargetGraph,\n GithubTargetConfig,\n GeneratedArtifact,\n TargetDiagnostic,\n CompilationResult,\n GithubJob,\n} from \"./types.js\";\n\nconst SHA_RE = /^[0-9a-f]{40}$/;\n\n/**\n * GitHub Actions target — native lowering from Definition Graph.\n * Implements the Target contract: analyze → lower → emit.\n */\nexport class GithubTarget implements Target {\n readonly name = \"github\";\n readonly capabilities: CapabilityManifest = githubCapabilities;\n\n private readonly pinningMode: \"strict\" | \"off\";\n private readonly pinningRegistry: PinRegistry;\n private readonly config: GithubTargetConfig | undefined;\n\n constructor(config?: GithubTargetConfig) {\n const pinning = config?.pinning;\n this.pinningMode = pinning?.mode ?? \"off\";\n this.pinningRegistry = pinning?.registry ?? loadBundledRegistry();\n this.config = config;\n }\n\n /**\n * Analyze a Definition Graph against the GitHub capability manifest.\n * Returns diagnostics for unsupported or emulated capabilities, plus\n * `unpinned-action` diagnostics (spec 22) for third-party `uses:` refs\n * that are not pinned in the emitted output.\n */\n analyze(graph: DefinitionGraph): readonly TargetDiagnostic[] {\n const capDiags = analyzeCapabilities(graph, [\n this.capabilities,\n ]) as readonly TargetDiagnostic[];\n const targetGraph = this.lower(graph);\n const pinDiags = this.pinningDiagnostics(targetGraph);\n return [...capDiags, ...pinDiags];\n }\n\n /**\n * Lower a Definition Graph to one or more GithubTargetGraphs.\n * Single-pipeline graphs return one target graph; multi-pipeline graphs\n * with reusable workflow calls return one per pipeline.\n */\n lower(\n graph: DefinitionGraph,\n ): GithubTargetGraph | readonly GithubTargetGraph[] {\n return lowerGithub(graph, this.config);\n }\n\n /**\n * Emit one or more GithubTargetGraphs as YAML artifacts.\n * Produces .github/workflows/<name>.yml files. When pinning is on (strict),\n * every `uses:` ref is routed through `pinActionRef`.\n */\n emit(\n targetGraph: GithubTargetGraph | readonly GithubTargetGraph[],\n ): readonly GeneratedArtifact[] {\n const options =\n this.pinningMode === \"strict\"\n ? { pinUses: (ref: string) => pinActionRef(ref, this.pinningRegistry) }\n : undefined;\n return emitGithub(targetGraph, options);\n }\n\n /**\n * Compile a Definition Graph to generated artifacts and diagnostics.\n */\n compile(graph: DefinitionGraph): CompilationResult {\n const targetGraph = this.lower(graph);\n const capDiags = analyzeCapabilities(graph, [\n this.capabilities,\n ]) as readonly TargetDiagnostic[];\n const pinDiags = this.pinningDiagnostics(targetGraph);\n const artifacts = this.emit(targetGraph);\n return { artifacts, diagnostics: [...capDiags, ...pinDiags] };\n }\n\n /**\n * Scan a lowered target graph for third-party `uses:` refs and emit\n * `unpinned-action` diagnostics (spec 22). A ref is \"unpinned\" when it\n * remains on a mutable version tag in the emitted output:\n * - strict mode + missing registry entry → error\n * - off mode + missing registry entry → warning\n * - malformed ref (no `@`) → warning (both modes)\n * Refs in the registry produce no diagnostic (they are pinnable; strict\n * pins them, off leaves them unchanged by choice).\n */\n private pinningDiagnostics(\n targetGraph: GithubTargetGraph | readonly GithubTargetGraph[],\n ): readonly TargetDiagnostic[] {\n const diags: TargetDiagnostic[] = [];\n const graphs = Array.isArray(targetGraph) ? targetGraph : [targetGraph];\n const seen = new Set<string>();\n for (const g of graphs) {\n for (const job of g.jobs) {\n for (const ref of collectUsesRefs(job)) {\n if (seen.has(ref)) continue;\n seen.add(ref);\n const diag = this.diagnosticFor(ref, job.id);\n if (diag) diags.push(diag);\n }\n }\n }\n return diags;\n }\n\n private diagnosticFor(\n ref: string,\n jobId: string,\n ): TargetDiagnostic | undefined {\n // Local actions and already-pinned refs are fine.\n if (ref.startsWith(\"./\")) return undefined;\n const at = ref.lastIndexOf(\"@\");\n if (at < 0) {\n return {\n capability: \"unpinned-action\",\n support: \"unsupported\",\n severity: \"warning\",\n message: `Action ref \"${ref}\" is malformed (no @version) and cannot be pinned.`,\n stepId: jobId,\n };\n }\n const tail = ref.slice(at + 1);\n if (SHA_RE.test(tail)) return undefined; // already pinned\n if (this.pinningRegistry[ref]) return undefined; // pinnable — no diagnostic\n const severity = this.pinningMode === \"strict\" ? \"error\" : \"warning\";\n return {\n capability: \"unpinned-action\",\n support: \"unsupported\",\n severity,\n message: `Action \"${ref}\" is not pinned to a commit SHA (no registry entry).`,\n stepId: jobId,\n };\n }\n}\n\n/** Collect every `uses:` ref from a job (step-level + reusable-job-level). */\nfunction collectUsesRefs(job: GithubJob): readonly string[] {\n const refs: string[] = [];\n if (job.uses) refs.push(job.uses);\n for (const step of job.steps) {\n if (step.uses) refs.push(step.uses);\n }\n return refs;\n}\n\n/**\n * Convenience function: analyze → lower → emit in one call.\n */\nexport function compileGithub(\n graph: DefinitionGraph,\n config?: GithubTargetConfig,\n): CompilationResult {\n return new GithubTarget(config).compile(graph);\n}\n","// GitLab capability manifest. Spec 09 — §24.\nimport type { CapabilityManifest } from \"../plugin/index.js\";\n\nexport const gitlabCapabilities: CapabilityManifest = {\n \"trigger.push\": \"native\",\n \"trigger.changeRequest\": \"native\",\n \"trigger.manual\": \"native\",\n \"runtime.host\": \"native\",\n \"runtime.container\": \"native\",\n \"operation.shell\": \"native\",\n \"operation.import\": \"lowered\",\n \"output.scalar\": \"lowered\",\n \"output.artifact\": \"native\",\n \"graph.dependencies\": \"native\",\n \"graph.conditions\": \"partial\",\n \"graph.matrix\": \"native\",\n \"matrix.include\": \"lowered\",\n \"matrix.exclude\": \"emulated\",\n \"matrix.failFast\": \"unsupported\",\n \"matrix.maxParallel\": \"unsupported\",\n \"trigger.schedule\": \"native\",\n \"step.beforeScript\": \"native\",\n \"step.afterScript\": \"native\",\n \"step.continueOnError\": \"native\",\n \"policy.retry\": \"native\",\n \"policy.compensation\": \"emulated\",\n \"execution.workdir\": \"emulated\",\n \"execution.shell\": \"unsupported\",\n \"environment.variables\": \"native\",\n \"secrets.runtime\": \"native\",\n \"secrets.pipeline-input\": \"native\",\n \"concurrency.interruptible\": \"native\",\n \"environment.permissions\": \"unsupported\",\n \"runner.selection\": \"native\",\n \"runner.group\": \"unsupported\",\n \"secrets.oidc\": \"native\",\n \"secrets.oidc.multiAudience\": \"native\",\n \"workflow.rules\": \"native\",\n \"workflow.rules.changes\": \"native\",\n \"workflow.rules.exists\": \"native\",\n \"workflow.defaults\": \"native\",\n \"workflow.defaults.shell\": \"unsupported\",\n \"workflow.defaults.workdir\": \"unsupported\",\n \"workflow.defaults.env\": \"unsupported\",\n \"workflow.defaults.beforeScript\": \"native\",\n \"workflow.defaults.afterScript\": \"native\",\n \"workflow.defaults.timeout\": \"native\",\n \"workflow.defaults.retry\": \"native\",\n \"workflow.defaults.interruptible\": \"native\",\n \"workflow.inputs\": \"native\",\n \"workflow.inputs.choice\": \"native\",\n \"workflow.inputs.array\": \"native\",\n \"workflow.inputs.pattern\": \"native\",\n \"environment.services\": \"native\",\n \"environment.services.ports\": \"unsupported\",\n \"deployment.environment\": \"native\",\n \"deployment.environment.action\": \"native\",\n \"deployment.environment.tier\": \"native\",\n \"artifact.retention\": \"native\",\n \"artifact.access\": \"native\",\n cache: \"native\",\n \"cache.policy\": \"native\",\n \"cache.fallbackKeys\": \"native\",\n \"concurrency.group\": \"native\",\n \"concurrency.cancelInProgress\": \"unsupported\",\n \"reusable.pipeline\": \"lowered\",\n \"reusable.pipeline.inputs\": \"native\",\n \"reusable.pipeline.outputs\": \"native\",\n \"reusable.component\": \"native\",\n \"reusable.component.versioning\": \"native\",\n \"reusable.childPipeline\": \"native\",\n \"reusable.downstream\": \"native\",\n \"deployment.release\": \"native\",\n \"deployment.pages\": \"native\",\n \"import.gitlab\": \"native\",\n \"import.include\": \"native\",\n \"scheduling.delay\": \"native\",\n \"execution.background\": \"emulated\",\n \"runtime.network\": \"emulated\",\n \"step.permissions\": \"native\",\n \"agent.step\": \"emulated\",\n \"run.query\": \"emulated\",\n};\n","// GitLab target error class. Spec 09.\n\nexport type GitlabTargetErrorCode =\n | \"INVALID_GRAPH\"\n | \"UNSUPPORTED_TRIGGER\"\n | \"LOWER_FAILED\"\n | \"EMIT_FAILED\"\n | \"IMPORT_FAILED\"\n | \"MATRIX_TOO_LARGE\"\n | \"INVALID_MATRIX\";\n\nexport class GitlabTargetError extends Error {\n readonly code: GitlabTargetErrorCode;\n override readonly cause: unknown;\n\n constructor(message: string, code: GitlabTargetErrorCode, cause?: unknown) {\n super(message);\n this.name = \"GitlabTargetError\";\n this.code = code;\n this.cause = cause;\n }\n}\n","// Native lowering: Definition Graph → GitlabTargetGraph.\n// Spec 09 — §18.2, §19.\n\nimport type {\n DefinitionGraph,\n PipelineDefinition,\n StepDefinition,\n EntryDefinition,\n OperationDefinition,\n Dependency,\n Trigger,\n Reference,\n Expression,\n ComponentRef,\n} from \"@sverka/workflow\";\nimport { expandPipelineCalls } from \"@sverka/workflow\";\nimport type {\n MatrixSpec,\n MatrixValue,\n StepRef,\n StatusCondition,\n StepStatus,\n Input,\n ServiceContainer,\n EnvironmentSpec,\n CacheSpec,\n ConcurrencySpec,\n InputLiteral,\n} from \"@sverka/workflow\";\nimport type {\n GitlabTargetGraph,\n GitlabJob,\n GitlabRule,\n GitlabDefault,\n GitlabSpecInput,\n GitlabService,\n GitlabEnvironment,\n GitlabCache,\n GitlabComponentInclude,\n GitlabLocalInclude,\n GitlabTrigger,\n GitlabRelease,\n GitlabPages,\n GitlabWorkflowRule,\n} from \"./types.js\";\nimport { GitlabTargetError } from \"./errors.js\";\nimport { buildJobIdMap } from \"../job-ids.js\";\nimport { shellQuoteSingle, wrapStdoutCaptureLine } from \"../stdout-capture.js\";\n\nconst DOTENV_REPORT_FILE = \"sverka.env\";\n\n/**\n * Lower a Definition Graph to a GitlabTargetGraph.\n * One GitLab job per reachable Step. Stages derived from dependency depth.\n * F-31: pipeline-call steps are inlined as namespaced jobs (v1; include:\n * file-reuse deferred).\n */\nexport function lowerGitlab(graph: DefinitionGraph): GitlabTargetGraph {\n if (graph.project.pipelines.length === 0) {\n throw new GitlabTargetError(\"graph has no pipelines\", \"INVALID_GRAPH\");\n }\n\n // Multi-pipeline: lower each root pipeline (has entries), inlining call steps.\n // Single-pipeline: original behavior (with call expansion if present).\n const rootPipelines = graph.project.pipelines.filter(\n (p) => p.entries.length > 0,\n );\n if (rootPipelines.length === 0) {\n throw new GitlabTargetError(\n \"graph has no root pipelines (with entries)\",\n \"INVALID_GRAPH\",\n );\n }\n\n // For v1, lower the first root pipeline (single .gitlab-ci.yml).\n // Multi-root GitLab is a follow-up. Report dropped roots via console warning.\n if (rootPipelines.length > 1) {\n const dropped = rootPipelines.slice(1).map((p) => p.id);\n console.warn(\n `GitLab lowering: dropping ${dropped.length} additional root pipeline(s): ${dropped.join(\", \")}. Multi-root GitLab support is not yet implemented.`,\n );\n }\n const pipeline = rootPipelines[0]!;\n const reachableSteps = filterReachableSteps(pipeline);\n // Expand pipeline-call steps into inline namespaced jobs.\n const expandedSteps = expandPipelineCalls(graph, reachableSteps);\n\n // Collect component includes (F-32). Component steps become include entries,\n // not jobs. Filter them out of the job-producing step list.\n const includes: GitlabComponentInclude[] = [];\n const stepsForJobs = expandedSteps.filter((step) => {\n if (step.component) {\n includes.push(lowerComponentInclude(step.component));\n return false;\n }\n return true;\n });\n\n const jobIdMap = buildJobIdMap(stepsForJobs);\n\n // Compute stages from topological levels.\n const { stageMap, stages } = computeStages(stepsForJobs, jobIdMap);\n\n // Derive per-job rules from the entries whose closure reaches that job.\n const jobRulesMap = buildJobRulesMap(pipeline, stepsForJobs, jobIdMap);\n\n const jobs = lowerSteps(stepsForJobs, jobIdMap, stageMap, jobRulesMap);\n\n // F-42: lower pipeline rules to workflow rules.\n const workflowRules = lowerWorkflowRules(pipeline);\n\n // F-44: lower pipeline includes to local includes.\n const localIncludes = lowerLocalIncludes(pipeline);\n\n // Apply pipeline-level concurrency to all jobs as resource_group.\n if (pipeline.concurrency !== undefined) {\n const group = pipeline.concurrency.group;\n for (const job of jobs) {\n if (job.resourceGroup === undefined) {\n (job as { resourceGroup?: string }).resourceGroup = group;\n }\n }\n }\n\n // Emit workflow:auto_cancel when any reachable step is interruptible.\n const autoCancel = jobs.some((job) => job.interruptible === true);\n\n return {\n name: pipeline.id,\n stages,\n jobs,\n variables: collectVariables(pipeline),\n ...(autoCancel ? { autoCancel: true } : {}),\n ...(pipeline.defaults !== undefined\n ? { default: lowerDefault(pipeline.defaults) }\n : {}),\n ...(Object.keys(pipeline.inputs).length > 0\n ? { specInputs: lowerSpecInputs(pipeline.inputs) }\n : {}),\n includes,\n ...(localIncludes.length > 0 ? { localIncludes } : {}),\n ...(workflowRules.length > 0 ? { workflowRules } : {}),\n };\n}\n\n/**\n * Lower pipeline inputs to GitLab spec:inputs.\n * choice type → type: string with options.\n */\nfunction lowerSpecInputs(\n inputs: Readonly<Record<string, Input>>,\n): Readonly<Record<string, GitlabSpecInput>> {\n const result: Record<string, GitlabSpecInput> = {};\n for (const [name, input] of Object.entries(inputs)) {\n result[name] = {\n type: input.type === \"choice\" ? \"string\" : input.type,\n ...(input.description !== undefined\n ? { description: input.description }\n : {}),\n // Omit defaults for secret inputs — they must not appear in the YAML.\n ...(input.default !== undefined && !input.secret\n ? { default: input.default }\n : {}),\n ...(input.options !== undefined ? { options: input.options } : {}),\n // GitLab spec:inputs uses `regex`, not `pattern`.\n ...(input.pattern !== undefined ? { regex: input.pattern } : {}),\n };\n }\n return result;\n}\n\n/**\n * Lower pipeline defaults to GitLab default keyword.\n * shell/workdir are not supported by GitLab and are dropped.\n */\nfunction lowerDefault(defaults: {\n beforeScript?: readonly string[];\n afterScript?: readonly string[];\n timeout?: number;\n retry?: { max: number; exitCodes?: readonly number[] };\n interruptible?: boolean;\n}): GitlabDefault {\n return {\n ...(defaults.beforeScript !== undefined\n ? { beforeScript: defaults.beforeScript }\n : {}),\n ...(defaults.afterScript !== undefined\n ? { afterScript: defaults.afterScript }\n : {}),\n ...(defaults.timeout !== undefined\n ? { timeout: `${Math.ceil(defaults.timeout / 60000)}m` }\n : {}),\n ...(defaults.retry !== undefined ? { retry: defaults.retry } : {}),\n ...(defaults.interruptible !== undefined\n ? { interruptible: defaults.interruptible }\n : {}),\n };\n}\n\n/**\n * Lower pipeline-level includes to GitLab local include directives.\n * F-44: includes → include: - local: <path>\n */\nfunction lowerLocalIncludes(\n pipeline: PipelineDefinition,\n): readonly GitlabLocalInclude[] {\n if (!pipeline.includes || pipeline.includes.length === 0) return [];\n return pipeline.includes.map((inc) => ({\n local: inc.path,\n ...(inc.inputs ? { inputs: { ...inc.inputs } } : {}),\n }));\n}\n\n/**\n * Lower pipeline-level rules to GitLab workflow:rules.\n * F-42: direct 1:1 mapping since GitLab has native support.\n */\nfunction lowerWorkflowRules(\n pipeline: PipelineDefinition,\n): readonly GitlabWorkflowRule[] {\n if (!pipeline.rules || pipeline.rules.length === 0) return [];\n return pipeline.rules.map((rule) => ({\n ...(rule.if ? { if: rule.if } : {}),\n ...(rule.changes ? { changes: [...rule.changes] } : {}),\n ...(rule.exists ? { exists: [...rule.exists] } : {}),\n ...(rule.variables ? { variables: { ...rule.variables } } : {}),\n ...(rule.when ? { when: rule.when } : {}),\n }));\n}\n\n/**\n * Lower a ComponentRef to a GitLab CI/CD component include entry.\n */\nfunction lowerComponentInclude(ref: ComponentRef): GitlabComponentInclude {\n const inputs: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(ref.inputs)) {\n if (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n \"kind\" in value\n ) {\n // Reference bindings — GitLab uses variable interpolation.\n const r = value as Reference;\n if (r.kind === \"step\") {\n inputs[name] =\n `$CI_JOB_${r.step.replace(/-/g, \"_\").toUpperCase()}_OUTPUT_${r.output}`;\n } else if (r.kind === \"context\") {\n inputs[name] = `$${r.field.toUpperCase()}`;\n }\n } else {\n inputs[name] = value;\n }\n }\n return {\n component: `${ref.name}@${ref.version}`,\n inputs,\n };\n}\n\n/**\n * Return the ids of all producer steps referenced by a step, including\n * explicit dependencies and artifact imports.\n */\nfunction producerIds(step: StepDefinition): readonly string[] {\n const ids: string[] = [];\n for (const dep of step.dependencies) {\n ids.push(dep.producer);\n }\n for (const op of step.operations) {\n if (op.kind === \"importArtifact\") {\n ids.push(op.from);\n }\n }\n return ids;\n}\n\n/**\n * Compute the set of step IDs reachable from the given roots.\n * Throws INVALID_GRAPH for unknown roots or producers.\n */\nfunction reachableStepIds(\n roots: readonly string[],\n pipeline: PipelineDefinition,\n): Set<string> {\n const byId = new Map(pipeline.steps.map((step) => [step.id, step]));\n const reachable = new Set<string>();\n const queue: string[] = [];\n\n for (const root of roots) {\n if (!byId.has(root)) {\n throw new GitlabTargetError(\n `entry references unknown root step '${root}'`,\n \"INVALID_GRAPH\",\n );\n }\n if (!reachable.has(root)) {\n reachable.add(root);\n queue.push(root);\n }\n }\n\n let head = 0;\n while (head < queue.length) {\n const id = queue[head]!;\n head++;\n const step = byId.get(id);\n if (!step) continue;\n\n for (const producer of producerIds(step)) {\n if (!byId.has(producer)) {\n throw new GitlabTargetError(\n `step '${step.id}' references unknown producer '${producer}'`,\n \"INVALID_GRAPH\",\n );\n }\n if (!reachable.has(producer)) {\n reachable.add(producer);\n queue.push(producer);\n }\n }\n }\n\n return reachable;\n}\n\n/**\n * Return the steps reachable from any entry root by following dependencies\n * and artifact imports.\n */\nfunction filterReachableSteps(\n pipeline: PipelineDefinition,\n): readonly StepDefinition[] {\n if (pipeline.steps.length === 0) {\n for (const entry of pipeline.entries) {\n if (entry.roots.length > 0) {\n throw new GitlabTargetError(\n `entry '${entry.id}' references root steps but pipeline has no steps`,\n \"INVALID_GRAPH\",\n );\n }\n }\n return [];\n }\n\n const allRoots = pipeline.entries.flatMap((entry) => [...entry.roots]);\n const reachable = reachableStepIds(allRoots, pipeline);\n return pipeline.steps.filter((step) => reachable.has(step.id));\n}\n\n/**\n * Build a map from each job ID to the rules of entries that reach that job.\n */\nfunction buildJobRulesMap(\n pipeline: PipelineDefinition,\n reachableSteps: readonly StepDefinition[],\n jobIdMap: ReadonlyMap<string, string>,\n): ReadonlyMap<string, readonly GitlabRule[]> {\n const map = new Map<string, readonly GitlabRule[]>();\n const entryReachable = new Map<string, Set<string>>();\n\n for (const entry of pipeline.entries) {\n entryReachable.set(entry.id, reachableStepIds(entry.roots, pipeline));\n }\n\n for (const step of reachableSteps) {\n const rules: GitlabRule[] = [];\n for (const entry of pipeline.entries) {\n if (entryReachable.get(entry.id)?.has(step.id)) {\n rules.push(...lowerTriggers([entry]));\n }\n }\n const jobId = jobIdMap.get(step.id)!;\n map.set(jobId, rules);\n }\n\n return map;\n}\n\ninterface StageResult {\n readonly stageMap: ReadonlyMap<string, string>;\n readonly stages: readonly string[];\n}\n\n/**\n * Compute stages by topological level.\n * Level 0 → \"build\", Level N → \"stage-N\".\n * Returns stages in dependency order (build first, then stage-1, etc.).\n * Throws when a dependency cycle is detected.\n */\nfunction computeStages(\n steps: readonly StepDefinition[],\n jobIdMap: Map<string, string>,\n): StageResult {\n const depsByJob = buildDepsByJob(steps, jobIdMap);\n const levels = computeAllLevels(steps, jobIdMap, depsByJob);\n return deriveStageResult(levels);\n}\n\nfunction buildDepsByJob(\n steps: readonly StepDefinition[],\n jobIdMap: Map<string, string>,\n): Map<string, string[]> {\n // Build dependency graph using job IDs.\n const depsByJob = new Map<string, string[]>();\n for (const step of steps) {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const deps = producerIds(step).map((id) => jobIdMap.get(id) ?? id);\n depsByJob.set(jobId, deps);\n }\n return depsByJob;\n}\n\nfunction computeAllLevels(\n steps: readonly StepDefinition[],\n jobIdMap: Map<string, string>,\n depsByJob: Map<string, string[]>,\n): Map<string, number> {\n const levels = new Map<string, number>();\n // Compute levels iteratively.\n for (const step of steps) {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const level = computeLevel(jobId, depsByJob, levels, new Set());\n levels.set(jobId, level);\n }\n return levels;\n}\n\nfunction stageNameForLevel(level: number): string {\n return level === 0 ? \"build\" : `stage-${level}`;\n}\n\nfunction deriveStageResult(levels: Map<string, number>): StageResult {\n // Derive ordered stage list from used levels.\n const maxLevel = Math.max(0, ...levels.values());\n const usedLevels = new Set(levels.values());\n const stages: string[] = [];\n for (let level = 0; level <= maxLevel; level++) {\n if (usedLevels.has(level)) {\n stages.push(stageNameForLevel(level));\n }\n }\n // Map job IDs to stage names.\n const stageMap = new Map<string, string>();\n for (const [jobId, level] of levels) {\n stageMap.set(jobId, stageNameForLevel(level));\n }\n return { stageMap, stages };\n}\n\nfunction computeLevel(\n jobId: string,\n depsByJob: Map<string, string[]>,\n levels: Map<string, number>,\n visiting: Set<string>,\n): number {\n if (levels.has(jobId)) return levels.get(jobId)!;\n if (visiting.has(jobId)) {\n throw new GitlabTargetError(\n `dependency cycle detected involving job '${jobId}'`,\n \"LOWER_FAILED\",\n );\n }\n visiting.add(jobId);\n\n const deps = depsByJob.get(jobId) ?? [];\n if (deps.length === 0) {\n visiting.delete(jobId);\n return 0;\n }\n\n let maxDepLevel = 0;\n for (const dep of deps) {\n const depLevel = computeLevel(dep, depsByJob, levels, visiting);\n maxDepLevel = Math.max(maxDepLevel, depLevel);\n }\n\n visiting.delete(jobId);\n return maxDepLevel + 1;\n}\n\n/**\n * Map Sverka triggers to GitLab rules.\n * Branch filters are preserved in the generated `if` expressions.\n */\nfunction lowerTriggers(\n entries: readonly EntryDefinition[],\n): readonly GitlabRule[] {\n const rules: GitlabRule[] = [];\n\n for (const entry of entries) {\n const t = entry.trigger;\n switch (t.kind) {\n case \"push\":\n rules.push(\n buildFilterRule('$CI_PIPELINE_SOURCE == \"push\"', t.filter, false),\n );\n break;\n case \"changeRequest\":\n // For MR triggers, $CI_COMMIT_BRANCH is not populated.\n // Use $CI_MERGE_REQUEST_TARGET_BRANCH_NAME for branch filters.\n rules.push(\n buildFilterRule(\n '$CI_PIPELINE_SOURCE == \"merge_request_event\"',\n t.filter,\n true,\n ),\n );\n break;\n case \"manual\":\n rules.push({ if: '$CI_PIPELINE_SOURCE == \"web\"' });\n break;\n case \"schedule\":\n rules.push({ if: '$CI_PIPELINE_SOURCE == \"schedule\"' });\n break;\n default:\n throw new GitlabTargetError(\n `unsupported trigger kind: ${JSON.stringify((t as Trigger).kind)}`,\n \"UNSUPPORTED_TRIGGER\",\n );\n }\n }\n\n return rules;\n}\n\n/**\n * Build a GitLab rule from a source condition and a trigger filter.\n * For push triggers: branches → $CI_COMMIT_BRANCH, tags → $CI_COMMIT_TAG\n * For MR triggers: branches → $CI_MERGE_REQUEST_TARGET_BRANCH_NAME (target branch)\n * Paths → changes: [paths] on the rule\n */\nfunction buildFilterRule(\n sourceCondition: string,\n filter:\n | {\n readonly branches?: readonly string[];\n readonly tags?: readonly string[];\n readonly paths?: readonly string[];\n }\n | undefined,\n isMergeRequest: boolean,\n): GitlabRule {\n // Source condition (push/MR/web) is always required.\n const conditions: string[] = [sourceCondition];\n\n // Branch and tag filters are OR'd: a push to a matching branch OR a matching tag.\n // For MR triggers, only branch (target) filters apply; tags are not relevant.\n const refConditions: string[] = [];\n if (filter?.branches && filter.branches.length > 0) {\n const branchRef = isMergeRequest\n ? \"$CI_MERGE_REQUEST_TARGET_BRANCH_NAME\"\n : \"$CI_COMMIT_BRANCH\";\n refConditions.push(buildRefCondition(branchRef, filter.branches));\n }\n if (filter?.tags && filter.tags.length > 0 && !isMergeRequest) {\n refConditions.push(buildRefCondition(\"$CI_COMMIT_TAG\", filter.tags));\n }\n if (refConditions.length === 1) {\n conditions.push(refConditions[0]!);\n } else if (refConditions.length > 1) {\n conditions.push(`(${refConditions.join(\" || \")})`);\n }\n\n const rule: GitlabRule = { if: conditions.join(\" && \") };\n if (filter?.paths && filter.paths.length > 0) {\n return { ...rule, changes: [...filter.paths] };\n }\n return rule;\n}\n\nfunction buildRefCondition(ref: string, values: readonly string[]): string {\n if (values.length === 1) {\n return `${ref} == ${quoteJsonString(values[0]!)}`;\n }\n const parts = values.map((v) => `${ref} == ${quoteJsonString(v)}`);\n return `(${parts.join(\" || \")})`;\n}\n\n/**\n * Lower steps to GitLab jobs.\n */\nfunction lowerSteps(\n steps: readonly StepDefinition[],\n jobIdMap: Map<string, string>,\n stageMap: ReadonlyMap<string, string>,\n rulesMap: ReadonlyMap<string, readonly GitlabRule[]>,\n): readonly GitlabJob[] {\n return steps.map((step) => {\n if (step.childPipeline) {\n return lowerChildPipelineStep(step, jobIdMap, stageMap, rulesMap);\n }\n if (step.downstream) {\n return lowerDownstreamStep(step, jobIdMap, stageMap, rulesMap);\n }\n return lowerStep(step, jobIdMap, stageMap, rulesMap);\n });\n}\n\n/**\n * Lower a child pipeline step to a GitLab trigger job.\n * F-33: childPipeline → trigger: include: [{ artifact: <path>, job: <generator> }]\n */\nfunction lowerChildPipelineStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n stageMap: ReadonlyMap<string, string>,\n rulesMap: ReadonlyMap<string, readonly GitlabRule[]>,\n): GitlabJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const stage = stageMap.get(jobId) ?? \"build\";\n const rules = rulesMap.get(jobId) ?? [];\n const needs = step.dependencies\n .filter((d) => d.kind === \"control\")\n .map((d) => jobIdMap.get(d.producer) ?? d.producer);\n const cp = step.childPipeline!;\n const generatorJobId =\n jobIdMap.get(\n `${step.id.split(\"/\").slice(0, -1).join(\"/\")}/${cp.generator}`,\n ) ?? cp.generator;\n const trigger: GitlabTrigger = {\n include: [{ artifact: cp.artifact, job: generatorJobId }],\n };\n return {\n id: jobId,\n stage,\n needs,\n script: [],\n ...(rules.length > 0 ? { rules } : {}),\n trigger,\n };\n}\n\n/**\n * Lower a downstream step to a GitLab multi-project trigger job.\n * F-34: downstream → trigger: project: <project>, branch: <branch>, strategy: depend\n */\nfunction lowerDownstreamStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n stageMap: ReadonlyMap<string, string>,\n rulesMap: ReadonlyMap<string, readonly GitlabRule[]>,\n): GitlabJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const stage = stageMap.get(jobId) ?? \"build\";\n const rules = rulesMap.get(jobId) ?? [];\n const needs = step.dependencies\n .filter((d) => d.kind === \"control\")\n .map((d) => jobIdMap.get(d.producer) ?? d.producer);\n const ds = step.downstream!;\n const trigger: GitlabTrigger = {\n project: ds.project,\n ...(ds.branch ? { branch: ds.branch } : {}),\n strategy: \"depend\",\n };\n // Inputs become variables on the trigger job.\n const variables = lowerDownstreamVariables(ds.inputs);\n return {\n id: jobId,\n stage,\n needs,\n script: [],\n ...(rules.length > 0 ? { rules } : {}),\n trigger,\n ...(Object.keys(variables).length > 0 ? { variables } : {}),\n };\n}\n\n/**\n * Lower downstream step inputs to GitLab trigger variables.\n */\nfunction lowerDownstreamVariables(\n inputs: Readonly<Record<string, Reference | InputLiteral>> | undefined,\n): Record<string, string> {\n const variables: Record<string, string> = {};\n if (!inputs) return variables;\n for (const [name, value] of Object.entries(inputs)) {\n variables[name] = lowerReferenceOrLiteral(value);\n }\n return variables;\n}\n\n/**\n * Lower a reference binding or literal value to a GitLab variable string.\n * Reference bindings use GitLab variable interpolation; literals are stringified.\n */\nfunction lowerReferenceOrLiteral(value: Reference | InputLiteral): string {\n if (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n \"kind\" in value\n ) {\n const r = value as Reference;\n if (r.kind === \"step\") {\n return `$CI_JOB_${r.step.replace(/-/g, \"_\").toUpperCase()}_OUTPUT_${r.output}`;\n }\n if (r.kind === \"context\") {\n return `$${r.field.toUpperCase()}`;\n }\n }\n return String(value);\n}\n\n/**\n * Lower a single Step to a GitLab job.\n */\nfunction lowerStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n stageMap: ReadonlyMap<string, string>,\n rulesMap: ReadonlyMap<string, readonly GitlabRule[]>,\n): GitlabJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const stage = stageMap.get(jobId) ?? \"build\";\n const triggerRules = rulesMap.get(jobId) ?? [];\n const mergedRules = mergeRules(triggerRules, step.rules);\n const {\n script,\n artifacts,\n needs: importNeeds,\n variables,\n release,\n pages,\n } = lowerOperations(step, jobId, jobIdMap);\n\n const needs = mergeNeeds(step, jobIdMap, importNeeds);\n\n if (script.length === 0) {\n script.push(\"echo 'no operations'\");\n }\n\n const { image, variables: jobVariables } = lowerRuntime(step, variables);\n const rules = applyStepCondition(mergedRules, step, jobIdMap);\n const writeVariables = lowerWriteVariables(step);\n\n return {\n id: jobId,\n stage,\n needs,\n script,\n ...buildJobFields({\n image,\n artifacts,\n variables: { ...jobVariables, ...writeVariables },\n rules,\n timeout: step.timeout,\n interruptible: step.interruptible,\n runner: step.runner,\n identity: step.identity,\n services: step.services,\n environment: step.environment,\n cache: step.cache,\n concurrency: step.concurrency,\n }),\n ...(step.matrix !== undefined\n ? { parallel: { matrix: lowerGitlabMatrix(step.matrix) } }\n : {}),\n ...(step.beforeScript ? { beforeScript: step.beforeScript } : {}),\n ...(step.afterScript ? { afterScript: step.afterScript } : {}),\n ...resolveContinueOnError(step),\n ...resolveRetryConfig(step),\n ...(release ? { release } : {}),\n ...(pages ? { pages } : {}),\n ...(step.delay ? { when: \"delayed\" as const, start_in: step.delay } : {}),\n };\n}\n\n/**\n * If the step has a condition, apply it to the merged rules.\n *\n * Status conditions (success/failure/always/never) map to GitLab `when`\n * values, not `if:` expressions. GitLab's `if:` does not have equivalents for\n * `on_success`/`on_failure` — those are `when` semantics. Emitting empty `if:`\n * strings (as the previous code did for success/failure) produces invalid YAML.\n *\n * Step-output conditions reference dotenv variables from a producer job's\n * artifacts. GitLab evaluates all job rules during pipeline creation, before\n * any job runs — so dotenv variables are not available at that point. Reject\n * step-output conditions with an error until runtime-safe handling exists.\n *\n * Context and expression conditions are AND'd with each rule's `if` expression.\n * GitLab evaluates rules in order and stops at the first match, so appending\n * the condition as a separate rule would bypass it when a trigger rule matches.\n */\nfunction applyStepCondition(\n mergedRules: readonly GitlabRule[],\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n): readonly GitlabRule[] {\n if (step.condition === undefined) return mergedRules;\n\n // Status conditions → map to GitLab rules `when` values.\n if (step.condition.kind === \"status\") {\n const when = statusToGitlabWhen(step.condition.status);\n if (mergedRules.length === 0) {\n return [{ when }];\n }\n return mergedRules.map((rule) => ({ ...rule, when }));\n }\n\n // Step-output conditions → reject. Producer outputs are dotenv variables\n // that GitLab cannot evaluate during pipeline creation (when rules are\n // evaluated). Runtime-safe handling does not yet exist.\n if (step.condition.kind === \"step\") {\n throw new GitlabTargetError(\n `step '${step.id}' has a step-output condition (${step.condition.step}.${step.condition.output}), which GitLab cannot evaluate during pipeline creation — dotenv variables from producer jobs are not available when rules are evaluated`,\n \"LOWER_FAILED\",\n );\n }\n\n // Context and expression conditions → AND with each rule's if expression.\n const condExpr = lowerGitlabConditionExpr(step.condition, jobIdMap);\n let rules = mergedRules.map((rule) => {\n if (condExpr === undefined) return rule;\n const ifExpr =\n rule.if !== undefined ? `(${rule.if}) && (${condExpr})` : condExpr;\n return { ...rule, if: ifExpr };\n });\n if (rules.length === 0 && condExpr !== undefined) {\n rules = [{ if: condExpr }];\n }\n return rules;\n}\n\n/**\n * Map a Sverka step status condition to a GitLab rules `when` value.\n * - success → on_success (run only if all parent jobs succeed — GitLab default)\n * - failure → on_failure (run only if at least one parent job fails)\n * - always → always\n * - never → never\n */\nfunction statusToGitlabWhen(status: StepStatus): string {\n switch (status) {\n case \"always\":\n return \"always\";\n case \"never\":\n return \"never\";\n case \"success\":\n return \"on_success\";\n case \"failure\":\n return \"on_failure\";\n }\n}\n\n/** Resolve continueOnError to GitLab allowFailure field. */\nfunction resolveContinueOnError(step: StepDefinition): Partial<GitlabJob> {\n if (step.continueOnError === undefined) return {};\n return {\n allowFailure:\n typeof step.continueOnError === \"boolean\"\n ? step.continueOnError\n : { exitCodes: step.continueOnError.exitCodes },\n };\n}\n\n/** Resolve retry configuration to GitLab retry field. */\nfunction resolveRetryConfig(step: StepDefinition): Partial<GitlabJob> {\n if (step.retry === undefined) return {};\n return {\n retry: {\n max: step.retry.max,\n ...(step.retry.when ? { when: step.retry.when } : {}),\n ...(step.retry.exitCodes ? { exitCodes: step.retry.exitCodes } : {}),\n },\n };\n}\n\nfunction mergeNeeds(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n importNeeds: readonly string[],\n): string[] {\n // Merge explicit scheduling dependencies with artifact-import dependencies.\n return [\n ...new Set([\n ...lowerDependencies(step.dependencies, jobIdMap),\n ...importNeeds,\n ]),\n ];\n}\n\nfunction lowerRuntime(\n step: StepDefinition,\n baseVariables: Record<string, string>,\n): { image?: string; variables: Record<string, string> } {\n const runtime = step.runtime;\n const mode = runtime.mode ?? \"host\";\n\n if (mode === \"container\" && !runtime.image) {\n throw new GitlabTargetError(\n `step '${step.id}' uses container mode without an image`,\n \"LOWER_FAILED\",\n );\n }\n const image = mode === \"container\" ? runtime.image : undefined;\n\n const variables: Record<string, string> = { ...baseVariables };\n if (runtime.env) {\n Object.assign(variables, runtime.env);\n }\n if (runtime.secrets) {\n for (const secret of runtime.secrets) {\n variables[secret] = `$${secret}`;\n }\n }\n // Spec 26: network allowlist annotation (GitLab has no native per-job egress control).\n if (runtime.network && runtime.network.allowed.length > 0) {\n variables[\"SVERKA_NETWORK_ALLOWLIST\"] = runtime.network.allowed.join(\",\");\n }\n\n return { ...(image ? { image } : {}), variables };\n}\n\n/**\n * Safe-outputs (Spec 25): GitLab has no per-job permission block.\n * Steps with declared writes receive CI variables corresponding to their\n * declared write kinds (e.g. SV_WRITE_DEPLOY=true). Steps without writes\n * receive no SV_WRITE_* variables.\n */\nfunction lowerWriteVariables(step: StepDefinition): Record<string, string> {\n const writes = step.permissions?.write;\n if (!writes || writes.length === 0) return {};\n const vars: Record<string, string> = {};\n for (const decl of writes) {\n const varName = `SV_WRITE_${decl.kind.toUpperCase().replace(/-/g, \"_\")}`;\n vars[varName] = \"true\";\n }\n return vars;\n}\n\ninterface JobFieldContext {\n image: string | undefined;\n artifacts:\n | {\n paths?: string[];\n reports?: Record<string, unknown>;\n expireIn?: string;\n access?: string;\n when?: string;\n }\n | undefined;\n variables: Record<string, string>;\n rules: readonly GitlabRule[];\n timeout: number | undefined;\n interruptible: boolean | undefined;\n runner: { labels: readonly string[]; group?: string } | undefined;\n identity:\n { tokens: Readonly<Record<string, { audience: string }>> } | undefined;\n services: readonly ServiceContainer[] | undefined;\n environment: EnvironmentSpec | undefined;\n cache: CacheSpec | undefined;\n concurrency: ConcurrencySpec | undefined;\n}\n\n/** Build core job fields: image, artifacts, variables, rules. */\nfunction buildJobCoreFields(ctx: JobFieldContext): Partial<GitlabJob> {\n return {\n ...(ctx.image ? { image: ctx.image } : {}),\n ...(ctx.artifacts ? { artifacts: ctx.artifacts } : {}),\n ...(Object.keys(ctx.variables).length > 0\n ? { variables: ctx.variables }\n : {}),\n ...(ctx.rules.length > 0 ? { rules: ctx.rules } : {}),\n };\n}\n\n/** Build runtime/execution fields: timeout, interruptible, runner tags, id_tokens. */\nfunction buildJobRuntimeFields(ctx: JobFieldContext): Partial<GitlabJob> {\n return {\n ...(ctx.timeout !== undefined\n ? { timeout: `${Math.ceil(ctx.timeout / 60000)}m` }\n : {}),\n ...(ctx.interruptible !== undefined\n ? { interruptible: ctx.interruptible }\n : {}),\n ...(ctx.runner !== undefined ? { tags: ctx.runner.labels } : {}),\n ...lowerIdTokens(ctx.identity),\n };\n}\n\n/** Build environment-related fields: services, environment, cache, concurrency. */\nfunction buildJobEnvFields(ctx: JobFieldContext): Partial<GitlabJob> {\n return {\n ...(ctx.services !== undefined && ctx.services.length > 0\n ? { services: lowerGitlabServices(ctx.services) }\n : {}),\n ...(ctx.environment !== undefined\n ? { environment: lowerGitlabEnvironment(ctx.environment) }\n : {}),\n ...(ctx.cache !== undefined ? { cache: lowerGitlabCache(ctx.cache) } : {}),\n ...(ctx.concurrency !== undefined\n ? { resourceGroup: ctx.concurrency.group }\n : {}),\n };\n}\n\nfunction buildJobFields(ctx: JobFieldContext): Partial<GitlabJob> {\n return {\n ...buildJobCoreFields(ctx),\n ...buildJobRuntimeFields(ctx),\n ...buildJobEnvFields(ctx),\n };\n}\n\n/** Lower identity tokens to GitLab id_tokens field. */\nfunction lowerIdTokens(\n identity: JobFieldContext[\"identity\"],\n): Partial<Pick<GitlabJob, \"idTokens\">> {\n if (identity === undefined) return {};\n const idTokens: Record<string, { aud: string }> = {};\n for (const [name, spec] of Object.entries(identity.tokens)) {\n idTokens[name] = { aud: spec.audience };\n }\n return Object.keys(idTokens).length > 0 ? { idTokens } : {};\n}\n\n/**\n * Lower cache spec to GitLab cache keyword.\n */\nfunction lowerGitlabCache(cache: CacheSpec): GitlabCache {\n return {\n paths: cache.paths,\n key: cache.key,\n ...(cache.policy !== undefined ? { policy: cache.policy } : {}),\n ...(cache.restoreKeys !== undefined\n ? { fallbackKeys: cache.restoreKeys }\n : {}),\n };\n}\n\n/**\n * Lower environment spec to GitLab environment map.\n */\nfunction lowerGitlabEnvironment(env: EnvironmentSpec): GitlabEnvironment {\n return {\n name: env.name,\n ...(env.url !== undefined ? { url: env.url } : {}),\n ...(env.action !== undefined ? { action: env.action } : {}),\n ...(env.tier !== undefined ? { deploymentTier: env.tier } : {}),\n };\n}\n\n/**\n * Lower service containers to GitLab services array.\n * ports are not supported by GitLab and are dropped.\n */\nfunction lowerGitlabServices(\n services: readonly ServiceContainer[],\n): readonly GitlabService[] {\n return services.map((svc) => ({\n name: svc.image,\n // Fall back to the portable service name so scripts can reach it by its declared name.\n alias: svc.alias ?? svc.name,\n ...(svc.entrypoint !== undefined\n ? { entrypoint: [...svc.entrypoint] }\n : {}),\n ...(svc.command !== undefined ? { command: [...svc.command] } : {}),\n ...(svc.env !== undefined ? { variables: { ...svc.env } } : {}),\n }));\n}\n\n/**\n * Merge trigger-derived rules with step-level rules.\n * Step-level rules are appended after trigger rules.\n */\nfunction mergeRules(\n triggerRules: readonly GitlabRule[],\n stepRules:\n | readonly {\n if?: string;\n changes?: readonly string[];\n exists?: readonly string[];\n when?: string;\n variables?: Readonly<Record<string, string>>;\n }[]\n | undefined,\n): readonly GitlabRule[] {\n if (stepRules === undefined || stepRules.length === 0) {\n return triggerRules;\n }\n const result: GitlabRule[] = [...triggerRules];\n for (const rule of stepRules) {\n const gitlabRule: GitlabRule = {\n ...(rule.if !== undefined ? { if: rule.if } : {}),\n ...(rule.when !== undefined ? { when: rule.when } : {}),\n ...(rule.changes !== undefined ? { changes: rule.changes } : {}),\n ...(rule.exists !== undefined ? { exists: rule.exists } : {}),\n ...(rule.variables !== undefined ? { variables: rule.variables } : {}),\n };\n result.push(gitlabRule);\n }\n return result;\n}\n\n/**\n * Map dependencies to job needs.\n */\nfunction lowerDependencies(\n deps: readonly Dependency[],\n jobIdMap: Map<string, string>,\n): readonly string[] {\n const needs = new Set<string>();\n for (const dep of deps) {\n const jobId = jobIdMap.get(dep.producer) ?? dep.producer;\n needs.add(jobId);\n }\n return [...needs];\n}\n\n/**\n * Mutable accumulator for lowering operations.\n */\ninterface OperationAccumulator {\n readonly script: string[];\n readonly artifactPaths: string[];\n readonly importNeeds: string[];\n readonly reportEntries: Record<string, unknown>;\n readonly inputs: readonly Reference[];\n hasDotenv: boolean;\n artifactRetention: string | undefined;\n artifactAccess: string | undefined;\n release: GitlabRelease | undefined;\n pages: GitlabPages | undefined;\n // exportStdout ops bind to the most recent shell op's captured stdout.\n // stdoutTargetIndex marks that op's entry inside script; stdoutNames are\n // the artifact names declared against it; stdoutArtifacts flips\n // artifacts:when to \"always\" because the runtime writes the file even on\n // step failure.\n stdoutTargetIndex: number | undefined;\n stdoutNames: string[];\n stdoutArtifacts: boolean;\n readonly workingDir: string | undefined;\n}\n\n/**\n * Map operations to script entries, artifacts, and dependencies.\n * Scalar outputs are written to a dotenv report file.\n */\nfunction lowerOperations(\n step: StepDefinition,\n jobId: string,\n jobIdMap: Map<string, string>,\n): {\n script: string[];\n artifacts?: {\n paths?: string[];\n reports?: Record<string, unknown>;\n expireIn?: string;\n access?: string;\n when?: string;\n };\n needs: string[];\n variables: Record<string, string>;\n release?: GitlabRelease;\n pages?: GitlabPages;\n} {\n const acc: OperationAccumulator = {\n script: [],\n artifactPaths: [],\n importNeeds: [],\n reportEntries: {},\n inputs: step.inputs,\n hasDotenv: false,\n artifactRetention: undefined,\n artifactAccess: undefined,\n release: undefined,\n pages: undefined,\n stdoutTargetIndex: undefined,\n stdoutNames: [],\n stdoutArtifacts: false,\n workingDir: step.runtime.workingDir,\n };\n\n for (const op of step.operations) {\n lowerOperation(op, jobId, acc, jobIdMap);\n }\n\n return assembleOperationResult(acc, step);\n}\n\n/**\n * Lower a shell operation, handling background execution.\n */\nfunction lowerShellOp(\n op: Extract<OperationDefinition, { kind: \"shell\" }>,\n acc: OperationAccumulator,\n jobIdMap: Map<string, string>,\n): void {\n // Seal any pending stdout capture before the new command becomes the most\n // recent shell op.\n sealStdoutCapture(acc);\n const translated = translateGitlabCommand(op.command, acc.inputs, jobIdMap);\n // F-49: background shell → append & for async execution.\n acc.script.push(op.background ? `${translated} &` : translated);\n acc.stdoutTargetIndex = acc.script.length - 1;\n}\n\n/**\n * Bind the pending stdout artifact names to the most recent shell op: wrap\n * that op's script line so its stdout is also written to the declared file(s)\n * and record the files as job artifacts.\n */\nfunction sealStdoutCapture(acc: OperationAccumulator): void {\n if (acc.stdoutTargetIndex === undefined || acc.stdoutNames.length === 0) {\n return;\n }\n acc.script[acc.stdoutTargetIndex] = wrapStdoutCaptureLine(\n acc.script[acc.stdoutTargetIndex]!,\n acc.stdoutNames,\n );\n // The capture writes the file inside the step's working directory when one\n // is set (the script cds there first); artifacts:paths is repo-relative.\n acc.artifactPaths.push(\n ...acc.stdoutNames.map((name) =>\n acc.workingDir ? `${acc.workingDir}/${name}` : name,\n ),\n );\n acc.stdoutArtifacts = true;\n acc.stdoutNames = [];\n}\n\n/**\n * Lower a single operation, mutating the accumulator.\n */\nfunction lowerOperation(\n op: OperationDefinition,\n stepId: string,\n acc: OperationAccumulator,\n jobIdMap: Map<string, string>,\n): void {\n switch (op.kind) {\n case \"shell\":\n lowerShellOp(op, acc, jobIdMap);\n break;\n case \"exportOutput\":\n lowerExportOutput(op, stepId, acc);\n break;\n case \"exportArtifact\":\n lowerExportArtifact(op, acc);\n break;\n case \"exportStdout\":\n if (acc.stdoutTargetIndex === undefined) {\n throw new GitlabTargetError(\n `step '${stepId}' declares stdout artifact '${op.name}' but no shell output was captured`,\n \"LOWER_FAILED\",\n );\n }\n acc.stdoutNames.push(op.name);\n break;\n case \"importArtifact\":\n acc.importNeeds.push(jobIdMap.get(op.from) ?? op.from);\n break;\n case \"diagnostic\":\n acc.script.push(`echo ${shellQuoteSingle(op.message)}`);\n break;\n case \"report\":\n lowerReport(op, acc);\n break;\n case \"release\":\n acc.release = lowerReleaseOp(op);\n break;\n case \"deployPages\":\n lowerDeployPages(op, acc);\n break;\n default:\n throw new GitlabTargetError(\n `unsupported operation kind: ${JSON.stringify((op as OperationDefinition).kind)}`,\n \"LOWER_FAILED\",\n );\n }\n}\n\n/**\n * Lower an exportOutput operation into a dotenv echo line.\n */\nfunction lowerExportOutput(\n op: Extract<OperationDefinition, { kind: \"exportOutput\" }>,\n stepId: string,\n acc: OperationAccumulator,\n): void {\n const key = `${stepId}_${op.name}`;\n const name = shellEscapeDoubleQuoted(key);\n acc.script.push(`echo \"${name}=\\${${op.name}}\" >> ${DOTENV_REPORT_FILE}`);\n acc.hasDotenv = true;\n}\n\n/**\n * Lower an exportArtifact operation, recording paths and retention metadata.\n */\nfunction lowerExportArtifact(\n op: Extract<OperationDefinition, { kind: \"exportArtifact\" }>,\n acc: OperationAccumulator,\n): void {\n acc.artifactPaths.push(op.path);\n if (op.retention !== undefined) acc.artifactRetention = op.retention;\n if (op.access !== undefined) acc.artifactAccess = op.access;\n}\n\n/**\n * Lower a report operation into a GitLab artifacts:reports entry.\n */\nfunction lowerReport(\n op: Extract<OperationDefinition, { kind: \"report\" }>,\n acc: OperationAccumulator,\n): void {\n const key = gitlabReportKey(op.spec.type);\n if (op.spec.type === \"coverage\") {\n acc.reportEntries[key] = {\n coverage_format: op.spec.format ?? \"cobertura\",\n path: op.spec.path,\n };\n } else {\n acc.reportEntries[key] = op.spec.path;\n }\n}\n\n/**\n * Lower a release operation to a GitLab release keyword.\n * Assets are file paths → emit as links with placeholder URLs\n * (GitLab requires URLs, not file paths).\n */\nfunction lowerReleaseOp(\n op: Extract<OperationDefinition, { kind: \"release\" }>,\n): GitlabRelease {\n const links = (op.assets ?? []).map((path) => ({\n name: path.split(\"/\").pop() ?? path,\n // Use GitLab CI job artifact URL variables so links resolve to the actual artifact.\n url: `$CI_PROJECT_URL/-/jobs/$CI_JOB_ID/artifacts/file/${path}`,\n }));\n return {\n tag_name: op.tag,\n ...(op.name ? { name: op.name } : {}),\n ...(op.description ? { description: op.description } : {}),\n ...(links.length > 0 ? { assets: { links } } : {}),\n ...(op.draft !== undefined ? { draft: op.draft } : {}),\n };\n}\n\n/**\n * Lower a deployPages operation to a GitLab pages keyword.\n * GitLab 17.6+ accepts any job name when the job sets the `pages` keyword.\n * The path is also added as an artifact.\n */\nfunction lowerDeployPages(\n op: Extract<OperationDefinition, { kind: \"deployPages\" }>,\n acc: OperationAccumulator,\n): void {\n acc.pages = {\n publish: op.path,\n ...(op.prefix ? { path_prefix: op.prefix } : {}),\n };\n // GitLab pages requires the path as an artifact.\n acc.artifactPaths.push(op.path);\n}\n\n/**\n * Assemble the final lowerOperations result from the accumulator.\n */\nfunction assembleOperationResult(\n acc: OperationAccumulator,\n step: StepDefinition,\n): {\n script: string[];\n artifacts?: {\n paths?: string[];\n reports?: Record<string, unknown>;\n expireIn?: string;\n access?: string;\n when?: string;\n };\n needs: string[];\n variables: Record<string, string>;\n release?: GitlabRelease;\n pages?: GitlabPages;\n} {\n sealStdoutCapture(acc);\n const artifacts: {\n paths?: string[];\n reports?: Record<string, unknown>;\n expireIn?: string;\n access?: string;\n when?: string;\n } = {};\n if (acc.artifactPaths.length > 0) {\n artifacts.paths = acc.artifactPaths;\n }\n if (acc.stdoutArtifacts) {\n // Stdout artifacts are written even when the shell command fails, so\n // the upload must not be limited to on_success.\n artifacts.when = \"always\";\n }\n if (acc.hasDotenv) {\n acc.reportEntries.dotenv = DOTENV_REPORT_FILE;\n }\n if (Object.keys(acc.reportEntries).length > 0) {\n artifacts.reports = acc.reportEntries;\n }\n if (acc.artifactRetention !== undefined) {\n artifacts.expireIn = parseGitlabExpireIn(acc.artifactRetention);\n }\n if (acc.artifactAccess !== undefined) {\n artifacts.access = acc.artifactAccess;\n }\n\n if (step.runtime.workingDir && acc.script.length > 0) {\n // Shell-quote the directory to prevent injection and handle spaces\n const escapedDir = shellQuoteSingle(step.runtime.workingDir);\n acc.script.unshift(`cd ${escapedDir}`);\n }\n\n return {\n script: acc.script,\n ...(Object.keys(artifacts).length > 0 ? { artifacts } : {}),\n needs: acc.importNeeds,\n variables: {},\n ...(acc.release ? { release: acc.release } : {}),\n ...(acc.pages ? { pages: acc.pages } : {}),\n };\n}\n\n/**\n * Convert Sverka retention duration to GitLab expire_in format.\n * \"7d\" → \"7 days\", \"1h\" → \"1 hours\", \"30m\" → \"30 minutes\", \"never\" → \"never\".\n */\nfunction parseGitlabExpireIn(retention: string): string {\n if (retention === \"never\") return \"never\";\n const match = /^(\\d+)([dhm])$/.exec(retention);\n if (match === null) return retention;\n const value = match[1]!;\n const unit = match[2];\n if (unit === \"d\") return `${value} days`;\n if (unit === \"h\") return `${value} hours`;\n if (unit === \"m\") return `${value} minutes`;\n return retention;\n}\n\n/**\n * Map Sverka report type to GitLab artifacts:reports key.\n */\nfunction gitlabReportKey(type: string): string {\n const map: Record<string, string> = {\n junit: \"junit\",\n coverage: \"coverage_report\",\n dotenv: \"dotenv\",\n sast: \"sast\",\n dast: \"dast\",\n dependencyScanning: \"dependency_scanning\",\n containerScanning: \"container_scanning\",\n licenseScanning: \"license_scanning\",\n performance: \"performance\",\n metrics: \"metrics\",\n terraform: \"terraform\",\n quality: \"quality\",\n sarif: \"sast\",\n };\n return map[type] ?? type;\n}\n\n/**\n * Produce a deterministic JSON string literal (quoted) for a value.\n */\nfunction quoteJsonString(value: string): string {\n return `\"${value.replace(/[\\\\\"\\n\\r\\t\\b\\f\\u0000-\\u001f]/g, (ch) => {\n const mapped = JSON_STRING_ESCAPES[ch];\n return mapped ?? `\\\\u${ch.charCodeAt(0).toString(16).padStart(4, \"0\")}`;\n })}\"`;\n}\n\nconst JSON_STRING_ESCAPES: Readonly<Record<string, string>> = {\n '\"': '\\\\\"',\n \"\\\\\": \"\\\\\\\\\",\n \"\\n\": \"\\\\n\",\n \"\\r\": \"\\\\r\",\n \"\\t\": \"\\\\t\",\n \"\\b\": \"\\\\b\",\n \"\\f\": \"\\\\f\",\n};\n\n/**\n * Escape a string for use inside double quotes in a POSIX shell.\n */\nfunction shellEscapeDoubleQuoted(value: string): string {\n return value.replace(/[\\\\\"`$]/g, \"\\\\$&\");\n}\n\n/**\n * Collect pipeline-level variables from inputs.\n * Secret inputs are omitted from the generated variables block.\n */\nfunction collectVariables(\n pipeline: PipelineDefinition,\n): Record<string, string> {\n const vars: Record<string, string> = {};\n for (const [name, input] of Object.entries(pipeline.inputs)) {\n if (input.secret) {\n continue;\n }\n if (input.default !== undefined) {\n vars[name] = String(input.default);\n }\n }\n return vars;\n}\n\n// ---------------------------------------------------------------------------\n// Matrix lowering (F-15)\n// ---------------------------------------------------------------------------\n\ntype MatrixCombination = Record<string, MatrixValue>;\n\n/**\n * Lower a MatrixSpec to a GitLab parallel:matrix array.\n * GitLab has no native include/exclude — exclude is emulated by filtering\n * combinations at synthesis time, include is appended to the array.\n */\nfunction lowerGitlabMatrix(\n spec: MatrixSpec,\n): readonly Record<string, unknown>[] {\n validateMatrixKeys(spec);\n const combinations = computeMatrixCombinations(\n spec.dimensions,\n spec.exclude ?? [],\n );\n const totalRows = combinations.length + (spec.include?.length ?? 0);\n if (totalRows > 200) {\n throw new GitlabTargetError(\n `GitLab matrix has ${totalRows} rows, exceeding the 200-row limit`,\n \"MATRIX_TOO_LARGE\",\n );\n }\n const includeEntries = (spec.include ?? []).map((entry) => ({ ...entry }));\n return [...combinations.map((c) => ({ ...c })), ...includeEntries];\n}\n\n/**\n * Validate that matrix dimension and include keys contain only valid\n * GitLab variable name characters: letters, digits, underscores.\n */\nfunction validateMatrixKeys(spec: MatrixSpec): void {\n const validKey = /^[A-Za-z_]\\w*$/;\n for (const key of Object.keys(spec.dimensions)) {\n if (!validKey.test(key)) {\n throw new GitlabTargetError(\n String.raw`invalid matrix dimension key '${key}': must match [A-Za-z_]\\w*`,\n \"INVALID_MATRIX\",\n );\n }\n }\n if (spec.include) {\n for (const entry of spec.include) {\n for (const key of Object.keys(entry)) {\n if (!validKey.test(key)) {\n throw new GitlabTargetError(\n String.raw`invalid matrix include key '${key}': must match [A-Za-z_]\\w*`,\n \"INVALID_MATRIX\",\n );\n }\n }\n }\n }\n}\n\n/**\n * Compute the cross-product of matrix dimensions, then filter out\n * combinations matching any exclude rule (partial match).\n */\nfunction computeMatrixCombinations(\n dimensions: Readonly<Record<string, readonly MatrixValue[]>>,\n exclude: readonly Readonly<Record<string, MatrixValue>>[],\n): readonly MatrixCombination[] {\n const keys = Object.keys(dimensions);\n if (keys.length === 0) return [];\n\n let combinations: MatrixCombination[] = [{}];\n for (const key of keys) {\n const values = dimensions[key];\n if (!values || values.length === 0) continue;\n const next: MatrixCombination[] = [];\n for (const combo of combinations) {\n for (const v of values) {\n next.push({ ...combo, [key]: v });\n }\n }\n combinations = next;\n }\n\n if (exclude.length === 0) return combinations;\n return combinations.filter((combo) => !matchesAny(combo, exclude));\n}\n\n/**\n * Check if a combination matches any exclude rule (partial match).\n */\nfunction matchesAny(\n combo: MatrixCombination,\n rules: readonly Readonly<Record<string, MatrixValue>>[],\n): boolean {\n for (const rule of rules) {\n const ruleEntries = Object.entries(rule);\n if (ruleEntries.length === 0) continue;\n if (ruleEntries.every(([k, v]) => combo[k] === v)) return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Context ref translation (F-35)\n// ---------------------------------------------------------------------------\n\nconst GITLAB_CONTEXT_MAP: Readonly<Record<string, string>> = {\n \"git.sha\": \"$CI_COMMIT_SHA\",\n \"git.branch\": \"$CI_COMMIT_BRANCH\",\n \"git.tag\": \"$CI_COMMIT_TAG\",\n \"change.id\": \"$CI_MERGE_REQUEST_IID\",\n \"change.source\": \"$CI_PIPELINE_SOURCE\",\n \"change.target\": \"$CI_MERGE_REQUEST_TARGET_BRANCH_NAME\",\n \"change.draft\": \"$CI_MERGE_REQUEST_DRAFT\",\n \"event.type\": \"$CI_PIPELINE_SOURCE\",\n \"run.id\": \"$CI_PIPELINE_ID\",\n \"run.attempt\": \"$run_attempt\",\n};\n\n/**\n * Translate a context ref (namespace.field) to GitLab variable syntax.\n */\nfunction translateGitlabContextRef(namespace: string, field: string): string {\n const key = `${namespace}.${field}`;\n const mapped = GITLAB_CONTEXT_MAP[key];\n if (mapped) return mapped;\n // Dynamic namespaces: env.X, secrets.X, inputs.X → just $X\n if (namespace === \"env\" || namespace === \"secrets\") {\n return `$${field}`;\n }\n if (namespace === \"matrix\") {\n return `$${field.toUpperCase()}`;\n }\n // inputs.X → $[[ inputs.FIELD ]] (GitLab pipeline input syntax)\n if (namespace === \"inputs\") {\n return `$[[ inputs.${field} ]]`;\n }\n // Unknown — fail lowering rather than emit invalid expression\n throw new GitlabTargetError(\n `unsupported context namespace '${namespace}' in GitLab lowering`,\n \"LOWER_FAILED\",\n );\n}\n\n/**\n * Translate a step ref to GitLab variable syntax: $<output> (from dotenv artifact).\n */\nfunction translateGitlabStepRef(ref: StepRef): string {\n return `$${ref.output}`;\n}\n\n/**\n * Build a lookup map from placeholder key to Reference from the step's inputs.\n */\nfunction buildGitlabInputLookup(\n inputs: readonly Reference[],\n): Map<string, Reference> {\n const map = new Map<string, Reference>();\n for (const ref of inputs) {\n if (ref.kind === \"context\") {\n map.set(`${ref.namespace}.${ref.field}`, ref);\n } else if (ref.kind === \"step\") {\n map.set(`${ref.step}.${ref.output}`, ref);\n }\n }\n return map;\n}\n\n/**\n * Translate ${...} placeholders in a command string to GitLab variable syntax.\n */\nfunction translateGitlabCommand(\n command: string,\n inputs: readonly Reference[],\n _jobIdMap: Map<string, string>,\n): string {\n const lookup = buildGitlabInputLookup(inputs);\n return command.replace(/\\$\\{([^{}]+)\\}/g, (_, key: string) => {\n const ref = lookup.get(key);\n if (ref === undefined) {\n return `\\${${key}}`;\n }\n if (ref.kind === \"context\") {\n return translateGitlabContextRef(ref.namespace, ref.field);\n }\n return translateGitlabStepRef(ref);\n });\n}\n\n/**\n * Lower a step condition to a GitLab if: expression string (without wrapping in a rule).\n * Returns the raw expression that can be combined with trigger rule conditions.\n */\nfunction lowerGitlabConditionExpr(\n condition: Reference | Expression | StatusCondition,\n _jobIdMap: Map<string, string>,\n): string {\n if (condition.kind === \"status\") {\n // GitLab status conditions map to when: field, not if: expression.\n // Return a sentinel that the caller can use to set when: instead.\n // For if: expression purposes: success = no restriction, always = true, never = false.\n if (condition.status === \"always\") return \"true\";\n if (condition.status === \"never\") return \"false\";\n return \"\"; // success/failure — no if: restriction (when: handles it)\n }\n if (condition.kind === \"context\") {\n return translateGitlabContextRef(condition.namespace, condition.field);\n }\n if (condition.kind === \"step\") {\n // Step ref condition — truthiness check on the output variable\n return translateGitlabStepRef(condition);\n }\n // Expression — translate each ${...} placeholder, no single-quote wrapping\n const lookup = buildGitlabInputLookup(condition.refs);\n return condition.template.replace(/\\$\\{([^{}]+)\\}/g, (_, key: string) => {\n const ref = lookup.get(key);\n if (ref === undefined) return `\\${${key}}`;\n if (ref.kind === \"context\") {\n return translateGitlabContextRef(ref.namespace, ref.field);\n }\n return translateGitlabStepRef(ref);\n });\n}\n\n/**\n * Lower a step condition to a GitLab rule with an if: expression.\n */\nfunction lowerGitlabCondition(\n condition: Reference | Expression | StatusCondition,\n jobIdMap: Map<string, string>,\n): GitlabRule {\n return { if: lowerGitlabConditionExpr(condition, jobIdMap) };\n}\n","// Emit: GitlabTargetGraph → YAML artifacts.\n// Spec 09 — §19.\n\nimport { stringify } from \"yaml\";\nimport { GitlabTargetError } from \"./errors.js\";\nimport type {\n GitlabTargetGraph,\n GitlabJob,\n GitlabRule,\n GitlabService,\n GitlabEnvironment,\n GitlabCache,\n GeneratedArtifact,\n} from \"./types.js\";\n\nconst RESERVED_TOP_LEVEL_KEYS = new Set([\n \"stages\",\n \"variables\",\n \"workflow\",\n \"include\",\n \"default\",\n \"image\",\n \"services\",\n \"before_script\",\n \"after_script\",\n \"cache\",\n \"spec\",\n \"pages:deploy\",\n]);\n\n/**\n * Emit a GitlabTargetGraph as YAML artifacts.\n * Produces one .gitlab-ci.yml file.\n */\nexport function emitGitlab(\n targetGraph: GitlabTargetGraph,\n): readonly GeneratedArtifact[] {\n const yaml = stringifyTargetGraph(targetGraph);\n return [\n {\n path: \".gitlab-ci.yml\",\n content: yaml,\n },\n ];\n}\n\n/**\n * Convert a GitlabTargetGraph to a YAML string.\n */\nfunction stringifyTargetGraph(graph: GitlabTargetGraph): string {\n const doc: Record<string, unknown> = {\n stages: graph.stages,\n };\n\n if (graph.autoCancel) {\n doc.workflow = {\n auto_cancel: { on_new_commit: \"interruptible\" },\n };\n }\n\n if (Object.keys(graph.variables).length > 0) {\n doc.variables = graph.variables;\n }\n\n if (graph.default) {\n doc.default = defaultToYaml(graph.default);\n }\n\n if (graph.specInputs && Object.keys(graph.specInputs).length > 0) {\n doc.spec = { inputs: graph.specInputs };\n }\n\n // F-32: emit component includes.\n // F-44: emit local includes alongside component includes.\n const allIncludes = collectIncludes(graph);\n if (allIncludes.length > 0) {\n doc.include = allIncludes;\n }\n\n // F-42: emit workflow rules (merge with auto_cancel if both present).\n if (graph.workflowRules && graph.workflowRules.length > 0) {\n doc.workflow = {\n ...(doc.workflow as Record<string, unknown> | undefined),\n rules: graph.workflowRules.map(workflowRuleToYaml),\n };\n }\n\n for (const job of graph.jobs) {\n if (RESERVED_TOP_LEVEL_KEYS.has(job.id)) {\n throw new GitlabTargetError(\n `job id '${job.id}' conflicts with a reserved top-level GitLab CI key`,\n \"EMIT_FAILED\",\n );\n }\n doc[job.id] = jobToYaml(job);\n }\n\n return stringify(doc, { sortMapEntries: false });\n}\n\n/**\n * Convert a GitlabDefault to a YAML-compatible object.\n */\nfunction defaultToYaml(\n def: NonNullable<GitlabTargetGraph[\"default\"]>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n if (def.beforeScript !== undefined)\n result.before_script = [...def.beforeScript];\n if (def.afterScript !== undefined) result.after_script = [...def.afterScript];\n if (def.timeout !== undefined) result.timeout = def.timeout;\n if (def.retry !== undefined) {\n const retry: Record<string, unknown> = { max: def.retry.max };\n if (def.retry.exitCodes !== undefined) {\n retry.exit_codes = [...def.retry.exitCodes];\n }\n result.retry = retry;\n }\n if (def.interruptible !== undefined) result.interruptible = def.interruptible;\n return result;\n}\n\n/**\n * Collect all include entries (component + local) from a GitlabTargetGraph.\n */\nfunction collectIncludes(graph: GitlabTargetGraph): Record<string, unknown>[] {\n const allIncludes: Record<string, unknown>[] = [];\n for (const inc of graph.includes) {\n allIncludes.push({\n component: inc.component,\n ...(Object.keys(inc.inputs).length > 0 ? { inputs: inc.inputs } : {}),\n });\n }\n if (graph.localIncludes) {\n for (const inc of graph.localIncludes) {\n allIncludes.push({\n local: inc.local,\n ...(inc.inputs && Object.keys(inc.inputs).length > 0\n ? { inputs: inc.inputs }\n : {}),\n });\n }\n }\n return allIncludes;\n}\n\n/**\n * Convert a workflow rule to a YAML-compatible object.\n */\nfunction workflowRuleToYaml(\n rule: NonNullable<GitlabTargetGraph[\"workflowRules\"]>[number],\n): Record<string, unknown> {\n const r: Record<string, unknown> = {};\n if (rule.if) r.if = rule.if;\n if (rule.changes) r.changes = rule.changes;\n if (rule.exists) r.exists = rule.exists;\n if (rule.variables) r.variables = rule.variables;\n if (rule.when) r.when = rule.when;\n return r;\n}\n\n/**\n * Convert a GitlabJob to a YAML-compatible object.\n */\nfunction jobToYaml(job: GitlabJob): Record<string, unknown> {\n const result: Record<string, unknown> = {\n stage: job.stage,\n script: job.script,\n };\n\n // Simple field copies: [yamlKey, value]\n const simpleFields: Array<[string, unknown]> = [\n [\"image\", job.image],\n [\"timeout\", job.timeout],\n [\"interruptible\", job.interruptible],\n [\"resource_group\", job.resourceGroup],\n [\"trigger\", job.trigger],\n [\"release\", job.release],\n [\"pages\", job.pages],\n [\"when\", job.when],\n [\"start_in\", job.start_in],\n ];\n for (const [yamlKey, value] of simpleFields) {\n if (value !== undefined && value !== null) {\n result[yamlKey] = value;\n }\n }\n\n addComplexJobFields(result, job);\n return result;\n}\n\n/** Add artifacts, variables, and rules fields to the result object. */\nfunction assignJobArtifactsVarsRules(\n result: Record<string, unknown>,\n job: GitlabJob,\n): void {\n if (job.artifacts) {\n result.artifacts = artifactsToYaml(job.artifacts);\n }\n if (job.variables) {\n result.variables = job.variables;\n }\n if (job.rules && job.rules.length > 0) {\n result.rules = job.rules.map(ruleToYaml);\n }\n}\n\n/** Add parallel/matrix field to the result object. */\nfunction assignJobParallel(\n result: Record<string, unknown>,\n job: GitlabJob,\n): void {\n if (job.parallel?.matrix) {\n // GitLab parallel:matrix requires each variable value to be an array.\n result.parallel = {\n matrix: job.parallel.matrix.map((row: Record<string, unknown>) => {\n const wrapped: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(row)) {\n wrapped[k] = Array.isArray(v) ? v : [v];\n }\n return wrapped;\n }),\n };\n } else {\n assignOptional(result, \"parallel\", job.parallel);\n }\n}\n\n/** Add tags, id_tokens, services, environment, and cache fields. */\nfunction assignJobContainerFields(\n result: Record<string, unknown>,\n job: GitlabJob,\n): void {\n if (job.tags && job.tags.length > 0) {\n result.tags = [...job.tags];\n }\n if (job.idTokens && Object.keys(job.idTokens).length > 0) {\n result.id_tokens = idTokensToYaml(job.idTokens);\n }\n if (job.services && job.services.length > 0) {\n result.services = job.services.map(serviceToYaml);\n }\n if (job.environment) {\n result.environment = environmentToYaml(job.environment);\n }\n if (job.cache) {\n result.cache = cacheToYaml(job.cache);\n }\n}\n\n/** Add fields requiring transformation to the result object. */\nfunction addComplexJobFields(\n result: Record<string, unknown>,\n job: GitlabJob,\n): void {\n if (job.needs.length > 0) {\n result.needs = [...job.needs];\n }\n\n assignOptionalList(result, \"before_script\", job.beforeScript);\n assignOptionalList(result, \"after_script\", job.afterScript);\n\n assignJobArtifactsVarsRules(result, job);\n\n assignAllowFailure(result, job.allowFailure);\n assignRetry(result, job.retry);\n assignJobParallel(result, job);\n\n assignJobContainerFields(result, job);\n}\n\nfunction assignOptional(\n result: Record<string, unknown>,\n key: string,\n value: unknown,\n): void {\n if (value !== undefined) result[key] = value;\n}\n\nfunction assignOptionalList(\n result: Record<string, unknown>,\n key: string,\n value: readonly string[] | undefined,\n): void {\n if (value && value.length > 0) result[key] = [...value];\n}\n\nfunction assignAllowFailure(\n result: Record<string, unknown>,\n value: GitlabJob[\"allowFailure\"],\n): void {\n if (value === undefined) return;\n if (typeof value === \"boolean\") {\n result.allow_failure = value;\n } else {\n result.allow_failure = { exit_codes: [...value.exitCodes] };\n }\n}\n\nfunction assignRetry(\n result: Record<string, unknown>,\n value: GitlabJob[\"retry\"],\n): void {\n if (value === undefined) return;\n // GitLab enforces a maximum of 2 retries.\n const retry: Record<string, unknown> = { max: Math.min(value.max, 2) };\n if (value.when && value.when.length > 0) retry.when = [...value.when];\n if (value.exitCodes && value.exitCodes.length > 0)\n retry.exit_codes = [...value.exitCodes];\n result.retry = retry;\n}\n\n/**\n * Convert an artifacts spec to a YAML-compatible object.\n */\nfunction artifactsToYaml(\n artifacts: NonNullable<GitlabJob[\"artifacts\"]>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n if (artifacts.paths !== undefined) result.paths = [...artifacts.paths];\n if (artifacts.reports !== undefined) result.reports = artifacts.reports;\n if (artifacts.expireIn !== undefined) result.expire_in = artifacts.expireIn;\n if (artifacts.access !== undefined) result.access = artifacts.access;\n if (artifacts.when !== undefined) result.when = artifacts.when;\n return result;\n}\n\n/**\n * Convert a job rule to a YAML-compatible object.\n */\nfunction ruleToYaml(rule: GitlabRule): Record<string, unknown> {\n const r: Record<string, unknown> = {};\n if (rule.if !== undefined) r.if = rule.if;\n if (rule.when !== undefined) r.when = rule.when;\n if (rule.changes !== undefined) r.changes = [...rule.changes];\n if (rule.exists !== undefined) r.exists = [...rule.exists];\n if (rule.variables !== undefined) r.variables = rule.variables;\n return r;\n}\n\n/**\n * Convert id tokens to a YAML-compatible object.\n */\nfunction idTokensToYaml(\n idTokens: NonNullable<GitlabJob[\"idTokens\"]>,\n): Record<string, { aud: string }> {\n const result: Record<string, { aud: string }> = {};\n for (const [name, spec] of Object.entries(idTokens)) {\n result[name] = { aud: spec.aud };\n }\n return result;\n}\n\n/**\n * Convert a service to a YAML-compatible object.\n */\nfunction serviceToYaml(svc: GitlabService): Record<string, unknown> {\n const s: Record<string, unknown> = { name: svc.name };\n if (svc.alias !== undefined) s.alias = svc.alias;\n if (svc.entrypoint !== undefined) s.entrypoint = [...svc.entrypoint];\n if (svc.command !== undefined) s.command = [...svc.command];\n if (svc.variables !== undefined) s.variables = svc.variables;\n return s;\n}\n\n/**\n * Convert an environment spec to a YAML-compatible object.\n */\nfunction environmentToYaml(env: GitlabEnvironment): Record<string, unknown> {\n const result: Record<string, unknown> = { name: env.name };\n if (env.url !== undefined) result.url = env.url;\n if (env.action !== undefined) result.action = env.action;\n if (env.deploymentTier !== undefined)\n result.deployment_tier = env.deploymentTier;\n if (env.onStop !== undefined) result.on_stop = env.onStop;\n return result;\n}\n\n/**\n * Convert a cache spec to a YAML-compatible object.\n */\nfunction cacheToYaml(cache: GitlabCache): Record<string, unknown> {\n const result: Record<string, unknown> = {\n paths: [...cache.paths],\n key: cache.key,\n };\n if (cache.policy !== undefined) result.policy = cache.policy;\n if (cache.fallbackKeys !== undefined)\n result.fallback_keys = [...cache.fallbackKeys];\n return result;\n}\n","// GitlabTarget — implements the Target contract (§19).\n// Spec 09 — §18.2, §19.\n\nimport type { DefinitionGraph } from \"@sverka/workflow\";\nimport type { CapabilityManifest, Target } from \"../plugin/index.js\";\nimport { analyzeCapabilities } from \"../plugin/index.js\";\nimport { gitlabCapabilities } from \"./capabilities.js\";\nimport { lowerGitlab } from \"./lower.js\";\nimport { emitGitlab } from \"./emit.js\";\nimport type {\n GitlabTargetGraph,\n GeneratedArtifact,\n TargetDiagnostic,\n CompilationResult,\n} from \"./types.js\";\n\n/**\n * GitLab CI target — native lowering from Definition Graph.\n * Implements the Target contract: analyze → lower → emit.\n */\nexport class GitlabTarget implements Target {\n readonly name = \"gitlab\";\n readonly capabilities: CapabilityManifest = gitlabCapabilities;\n\n /**\n * Analyze a Definition Graph against the GitLab capability manifest.\n * Returns diagnostics for unsupported or emulated capabilities.\n */\n analyze(graph: DefinitionGraph): readonly TargetDiagnostic[] {\n const diags = analyzeCapabilities(graph, [this.capabilities]);\n return diags as readonly TargetDiagnostic[];\n }\n\n /**\n * Lower a Definition Graph to a GitlabTargetGraph.\n * One GitLab job per reachable Step with needs, stages, and operation mapping.\n */\n lower(graph: DefinitionGraph): GitlabTargetGraph {\n return lowerGitlab(graph);\n }\n\n /**\n * Emit a GitlabTargetGraph as YAML artifacts.\n * Produces one .gitlab-ci.yml file.\n */\n emit(targetGraph: GitlabTargetGraph): readonly GeneratedArtifact[] {\n return emitGitlab(targetGraph);\n }\n\n /**\n * Compile a Definition Graph to generated artifacts and diagnostics.\n */\n compile(graph: DefinitionGraph): CompilationResult {\n const diagnostics = this.analyze(graph);\n const targetGraph = this.lower(graph);\n const artifacts = this.emit(targetGraph);\n return { artifacts, diagnostics };\n }\n}\n\n/**\n * Convenience function: analyze → lower → emit in one call.\n */\nexport function compileGitlab(graph: DefinitionGraph): CompilationResult {\n return new GitlabTarget().compile(graph);\n}\n"],"mappings":";;;AAKA,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;CAEA,YAAY,SAAiB,MAAuB,OAAiB;EACnE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;;;ACFA,MAAM,iBAA+C;CACnD;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,WAA8C;CAClD,QAAQ;CACR,SAAS;CACT,WAAW;CACX,UAAU;CACV,SAAS;CACT,aAAa;AACf;;;;AA6DA,SAAgB,gBAAgB,OAAmC;CACjE,IACE,OAAO,UAAU,YACjB,CAAC,eAAe,SAAS,KAA0B,GAEnD,MAAM,IAAI,YACR,qCAAqC,OAAO,KAAK,KACjD,oBACF;CAEF,OAAO;AACT;;;;AAKA,SAAgB,2BACd,UACwC;CACxC,IACE,OAAO,aAAa,YACpB,aAAa,QACb,MAAM,QAAQ,QAAQ,GAEtB,MAAM,IAAI,YACR,yCACA,oBACF;CAEF,MAAM,MAAM;CACZ,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAC3C,sBAAsB,KAAK,KAAK;AAEpC;AAEA,SAAS,sBAAsB,KAAa,OAAsB;CAChE,IAAI,OAAO,UAAU,UAAU;EAC7B,gBAAgB,KAAK;EACrB;CACF;CACA,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;EAC/C,uBAAuB,KAAK,KAAgC;EAC5D;CACF;CACA,MAAM,IAAI,YACR,eAAe,IAAI,wDACnB,oBACF;AACF;AAEA,SAAS,uBACP,KACA,QACM;CACN,gBAAgB,OAAO,OAAO;CAC9B,IAAI,OAAO,QAAQ,KAAA,KAAa,OAAO,OAAO,QAAQ,UACpD,MAAM,IAAI,YACR,e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C;EACtC,OAAO,CAAC,GAAG,MAAM,KAAK;EACtB,KAAK,MAAM;CACb;CACA,IAAI,MAAM,WAAW,KAAA,GAAW,OAAO,SAAS,MAAM;CACtD,IAAI,MAAM,iBAAiB,KAAA,GACzB,OAAO,gBAAgB,CAAC,GAAG,MAAM,YAAY;CAC/C,OAAO;AACT;;;;;;;ACnXA,IAAa,eAAb,MAA4C;CAC1C,OAAgB;CAChB,eAA4C;;;;;CAM5C,QAAQ,OAAqD;EAE3D,OADc,oBAAoB,OAAO,CAAC,KAAK,YAAY,CAChD;CACb;;;;;CAMA,MAAM,OAA2C;EAC/C,OAAO,YAAY,KAAK;CAC1B;;;;;CAMA,KAAK,aAA8D;EACjE,OAAO,WAAW,WAAW;CAC/B;;;;CAKA,QAAQ,OAA2C;EACjD,MAAM,cAAc,KAAK,QAAQ,KAAK;EACtC,MAAM,cAAc,KAAK,MAAM,KAAK;EAEpC,OAAO;GAAE,WADS,KAAK,KAAK,WACX;GAAG;EAAY;CAClC;AACF;;;;AAKA,SAAgB,cAAc,OAA2C;CACvE,OAAO,IAAI,aAAa,CAAC,CAAC,QAAQ,KAAK;AACzC"}
1
+ {"version":3,"file":"index.mjs","names":["filterReachableSteps","lowerTriggers","lowerChildPipelineStep","lowerDownstreamStep","lowerStep","lowerDependencies","lowerOperations","lowerOperation","lowerReport","lowerDeployPages","stringifyTargetGraph","jobToYaml","SHA_RE","bundledRegistry","parseYaml","parseYaml"],"sources":["../src/plugin/errors.ts","../src/plugin/capabilities.ts","../src/plugin/factory.ts","../src/github/capabilities.ts","../src/github/errors.ts","../src/job-ids.ts","../src/stdout-capture.ts","../src/github/lower.ts","../src/github/emit.ts","../src/github/pinned-actions.json","../src/github/pinning.ts","../src/github/target.ts","../src/gitlab/capabilities.ts","../src/gitlab/errors.ts","../src/gitlab/lower.ts","../src/gitlab/emit.ts","../src/gitlab/target.ts","../src/github/importer.ts","../src/gitlab/importer.ts"],"sourcesContent":["// Plugin error class. Spec 07.\n\nexport type PluginErrorCode =\n \"INVALID_PLUGIN\" | \"DUPLICATE_PLUGIN\" | \"INVALID_CAPABILITY\";\n\nexport class PluginError extends Error {\n readonly code: PluginErrorCode;\n override readonly cause: unknown;\n\n constructor(message: string, code: PluginErrorCode, cause?: unknown) {\n super(message);\n this.name = \"PluginError\";\n this.code = code;\n this.cause = cause;\n }\n}\n","// Capability analysis. Spec 07 — §24.\n// Inspects a Definition Graph to detect used capabilities, then checks\n// against provided manifests to produce diagnostics.\n\nimport type { DefinitionGraph } from \"@sverka/workflow\";\nimport type {\n CapabilityManifest,\n CapabilitySupport,\n CapabilityDetail,\n CapabilityDiagnostic,\n} from \"./types.js\";\nimport { PluginError } from \"./errors.js\";\n\nconst SUPPORT_LEVELS: readonly CapabilitySupport[] = [\n \"native\",\n \"lowered\",\n \"emulated\",\n \"connector\",\n \"partial\",\n \"unsupported\",\n];\n\nconst PRIORITY: Record<CapabilitySupport, number> = {\n native: 6,\n lowered: 5,\n connector: 4,\n emulated: 3,\n partial: 2,\n unsupported: 1,\n};\n\n/**\n * Shape of a step used for capability detection.\n */\ninterface CapabilityStep {\n runtime?: {\n mode?: string;\n workingDir?: string;\n shell?: string;\n env?: Readonly<Record<string, string>>;\n secrets?: readonly string[];\n };\n operations: readonly CapabilityOperation[];\n outputs: readonly { type: string }[];\n dependencies: readonly unknown[];\n matrix?: {\n dimensions?: unknown;\n include?: readonly unknown[];\n exclude?: readonly unknown[];\n failFast?: boolean;\n maxParallel?: number;\n };\n beforeScript?: readonly unknown[];\n afterScript?: readonly unknown[];\n continueOnError?: unknown;\n retry?: { max?: number };\n interruptible?: boolean;\n runner?: { labels?: readonly string[]; group?: string };\n identity?: { tokens?: Readonly<Record<string, { audience: string }>> };\n rules?: readonly {\n changes?: readonly string[];\n exists?: readonly string[];\n }[];\n services?: readonly { ports?: readonly number[] }[];\n environment?: { name?: string; action?: string; tier?: string };\n cache?: { policy?: string; restoreKeys?: readonly string[] };\n concurrency?: { group?: string; cancelInProgress?: boolean };\n call?: unknown;\n component?: unknown;\n childPipeline?: unknown;\n downstream?: unknown;\n delay?: string;\n condition?: unknown;\n}\n\ninterface CapabilityOperation {\n kind: string;\n spec?: { type?: string };\n retention?: string;\n access?: string;\n}\n\ninterface OutputFlags {\n scalar: boolean;\n artifact: boolean;\n}\n\n/**\n * Validate that a value is a valid capability support level.\n */\nexport function validateSupport(value: unknown): CapabilitySupport {\n if (\n typeof value !== \"string\" ||\n !SUPPORT_LEVELS.includes(value as CapabilitySupport)\n ) {\n throw new PluginError(\n `invalid capability support level: ${String(value)}`,\n \"INVALID_CAPABILITY\",\n );\n }\n return value as CapabilitySupport;\n}\n\n/**\n * Validate a capability manifest object.\n */\nexport function validateCapabilityManifest(\n manifest: unknown,\n): asserts manifest is CapabilityManifest {\n if (\n typeof manifest !== \"object\" ||\n manifest === null ||\n Array.isArray(manifest)\n ) {\n throw new PluginError(\n \"capability manifest must be an object\",\n \"INVALID_CAPABILITY\",\n );\n }\n const obj = manifest as Record<string, unknown>;\n for (const [key, value] of Object.entries(obj)) {\n validateManifestEntry(key, value);\n }\n}\n\nfunction validateManifestEntry(key: string, value: unknown): void {\n if (typeof value === \"string\") {\n validateSupport(value);\n return;\n }\n if (typeof value === \"object\" && value !== null) {\n validateManifestDetail(key, value as Record<string, unknown>);\n return;\n }\n throw new PluginError(\n `capability '${key}' must be a support string or CapabilityDetail object`,\n \"INVALID_CAPABILITY\",\n );\n}\n\nfunction validateManifestDetail(\n key: string,\n detail: Record<string, unknown>,\n): void {\n validateSupport(detail.support);\n if (detail.via !== undefined && typeof detail.via !== \"string\") {\n throw new PluginError(\n `capability '${key}' has invalid via: must be a string`,\n \"INVALID_CAPABILITY\",\n );\n }\n if (detail.notes !== undefined && typeof detail.notes !== \"string\") {\n throw new PluginError(\n `capability '${key}' has invalid notes: must be a string`,\n \"INVALID_CAPABILITY\",\n );\n }\n}\n\n/**\n * Detect capabilities used by a single step.\n */\nfunction detectStepCapabilities(step: CapabilityStep, caps: Set<string>): void {\n detectRuntimeCapabilities(step, caps);\n detectRunnerCapabilities(step, caps);\n detectIdentityCapabilities(step, caps);\n detectRuleCapabilities(step, caps);\n detectServiceCapabilities(step, caps);\n detectEnvironmentCapabilities(step, caps);\n detectCacheCapabilities(step, caps);\n detectConcurrencyCapabilities(step, caps);\n detectSpecialStepCapabilities(step, caps);\n\n const outputFlags: OutputFlags = { scalar: false, artifact: false };\n for (const op of step.operations) {\n detectOperationCapabilities(op, caps, outputFlags);\n }\n detectOutputTypeCapabilities(step.outputs, outputFlags);\n\n if (step.dependencies.length > 0) caps.add(\"graph.dependencies\");\n if (step.condition !== undefined) caps.add(\"graph.conditions\");\n if (outputFlags.scalar) caps.add(\"output.scalar\");\n if (outputFlags.artifact) caps.add(\"output.artifact\");\n\n detectMatrixCapabilities(step.matrix, caps);\n detectScriptCapabilities(step, caps);\n}\n\n/**\n * Detect capabilities for special step kinds: call, component, child pipeline,\n * downstream, and delay.\n */\nfunction detectSpecialStepCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.call !== undefined) caps.add(\"reusable.pipeline\");\n if (step.component !== undefined) caps.add(\"reusable.component\");\n if (step.childPipeline !== undefined) caps.add(\"reusable.childPipeline\");\n if (step.downstream !== undefined) caps.add(\"reusable.downstream\");\n if (step.delay !== undefined) caps.add(\"scheduling.delay\");\n}\n\nfunction detectMatrixCapabilities(\n matrix:\n | {\n dimensions?: unknown;\n include?: readonly unknown[];\n exclude?: readonly unknown[];\n failFast?: boolean;\n maxParallel?: number;\n }\n | undefined,\n caps: Set<string>,\n): void {\n if (!matrix) return;\n caps.add(\"graph.matrix\");\n if (matrix.include && matrix.include.length > 0) caps.add(\"matrix.include\");\n if (matrix.exclude && matrix.exclude.length > 0) caps.add(\"matrix.exclude\");\n if (matrix.failFast !== undefined) caps.add(\"matrix.failFast\");\n if (matrix.maxParallel !== undefined) caps.add(\"matrix.maxParallel\");\n}\n\nfunction detectScriptCapabilities(\n step: {\n beforeScript?: readonly unknown[];\n afterScript?: readonly unknown[];\n continueOnError?: unknown;\n retry?: { max?: number };\n timeout?: unknown;\n },\n caps: Set<string>,\n): void {\n if (step.beforeScript && step.beforeScript.length > 0)\n caps.add(\"step.beforeScript\");\n if (step.afterScript && step.afterScript.length > 0)\n caps.add(\"step.afterScript\");\n if (step.continueOnError !== undefined) caps.add(\"step.continueOnError\");\n if (step.retry !== undefined) caps.add(\"policy.retry\");\n if (step.timeout !== undefined) caps.add(\"policy.timeout\");\n}\n\nfunction detectRuntimeCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n const mode = step.runtime?.mode ?? \"host\";\n caps.add(`runtime.${mode}`);\n if (step.runtime?.workingDir) caps.add(\"execution.workdir\");\n if (step.runtime?.shell) caps.add(\"execution.shell\");\n if (step.runtime?.env && Object.keys(step.runtime.env).length > 0)\n caps.add(\"environment.variables\");\n if (step.runtime?.secrets && step.runtime.secrets.length > 0)\n caps.add(\"secrets.runtime\");\n if (step.interruptible === true) caps.add(\"concurrency.interruptible\");\n}\n\nfunction detectRunnerCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.runner === undefined) return;\n caps.add(\"runner.selection\");\n if (step.runner.group !== undefined) caps.add(\"runner.group\");\n}\n\nfunction detectIdentityCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.identity === undefined) return;\n caps.add(\"secrets.oidc\");\n const audiences = new Set<string>();\n for (const token of Object.values(step.identity.tokens ?? {})) {\n audiences.add(token.audience);\n }\n if (audiences.size > 1) {\n caps.add(\"secrets.oidc.multiAudience\");\n }\n}\n\nfunction detectRuleCapabilities(step: CapabilityStep, caps: Set<string>): void {\n if (step.rules === undefined || step.rules.length === 0) return;\n caps.add(\"workflow.rules\");\n for (const rule of step.rules) {\n if (rule.changes !== undefined) caps.add(\"workflow.rules.changes\");\n if (rule.exists !== undefined) caps.add(\"workflow.rules.exists\");\n }\n}\n\nfunction detectServiceCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.services === undefined || step.services.length === 0) return;\n caps.add(\"environment.services\");\n for (const service of step.services) {\n if (service.ports !== undefined && service.ports.length > 0) {\n caps.add(\"environment.services.ports\");\n }\n }\n}\n\nfunction detectEnvironmentCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.environment === undefined) return;\n caps.add(\"deployment.environment\");\n if (step.environment.action !== undefined)\n caps.add(\"deployment.environment.action\");\n if (step.environment.tier !== undefined)\n caps.add(\"deployment.environment.tier\");\n}\n\nfunction detectCacheCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.cache === undefined) return;\n caps.add(\"cache\");\n if (step.cache.policy !== undefined) caps.add(\"cache.policy\");\n if (step.cache.restoreKeys !== undefined && step.cache.restoreKeys.length > 0)\n caps.add(\"cache.fallbackKeys\");\n}\n\nfunction detectConcurrencyCapabilities(\n step: CapabilityStep,\n caps: Set<string>,\n): void {\n if (step.concurrency === undefined) return;\n caps.add(\"concurrency.group\");\n if (step.concurrency.cancelInProgress !== undefined)\n caps.add(\"concurrency.cancelInProgress\");\n}\n\nfunction detectOperationCapabilities(\n op: CapabilityOperation,\n caps: Set<string>,\n outputFlags: OutputFlags,\n): void {\n switch (op.kind) {\n case \"shell\":\n caps.add(\"operation.shell\");\n break;\n case \"exportOutput\":\n outputFlags.scalar = true;\n break;\n case \"exportArtifact\":\n detectExportArtifactCapabilities(op, caps, outputFlags);\n break;\n case \"importArtifact\":\n caps.add(\"operation.import\");\n break;\n case \"report\":\n detectReportCapabilities(op, caps);\n break;\n }\n}\n\nfunction detectExportArtifactCapabilities(\n op: CapabilityOperation,\n caps: Set<string>,\n outputFlags: OutputFlags,\n): void {\n outputFlags.artifact = true;\n if (op.retention !== undefined) caps.add(\"artifact.retention\");\n if (op.access !== undefined) caps.add(\"artifact.access\");\n}\n\nfunction detectReportCapabilities(\n op: CapabilityOperation,\n caps: Set<string>,\n): void {\n caps.add(\"artifact.report\");\n if (op.spec?.type !== undefined) {\n caps.add(`artifact.report.${op.spec.type}`);\n }\n}\n\nfunction detectOutputTypeCapabilities(\n outputs: readonly { type: string }[],\n outputFlags: OutputFlags,\n): void {\n for (const output of outputs) {\n if (output.type === \"artifact\") outputFlags.artifact = true;\n else outputFlags.scalar = true;\n }\n}\n\n/**\n * Detect capabilities used by a single pipeline.\n */\nfunction detectPipelineCapabilities(\n pipeline: {\n entries: readonly { trigger: { kind: string } }[];\n steps: readonly CapabilityStep[];\n permissions?: unknown;\n defaults?: {\n shell?: unknown;\n workdir?: unknown;\n env?: unknown;\n beforeScript?: unknown;\n afterScript?: unknown;\n timeout?: unknown;\n retry?: unknown;\n interruptible?: unknown;\n };\n inputs?: Readonly<\n Record<\n string,\n {\n type?: string;\n options?: readonly string[];\n pattern?: string;\n secret?: boolean;\n }\n >\n >;\n concurrency?: { group?: string; cancelInProgress?: boolean };\n rules?: readonly unknown[];\n },\n caps: Set<string>,\n): void {\n detectTriggerCapabilities(pipeline.entries, caps);\n if (pipeline.permissions !== undefined) {\n caps.add(\"environment.permissions\");\n }\n detectInputCapabilities(pipeline.inputs, caps);\n if (pipeline.defaults !== undefined) {\n detectDefaultCapabilities(pipeline.defaults, caps);\n }\n if (pipeline.concurrency !== undefined) {\n caps.add(\"concurrency.group\");\n if (pipeline.concurrency.cancelInProgress !== undefined)\n caps.add(\"concurrency.cancelInProgress\");\n }\n if (pipeline.rules !== undefined && pipeline.rules.length > 0) {\n caps.add(\"workflow.rules\");\n }\n for (const step of pipeline.steps) {\n detectStepCapabilities(step, caps);\n }\n}\n\nfunction detectTriggerCapabilities(\n entries: readonly { trigger: { kind: string } }[],\n caps: Set<string>,\n): void {\n for (const entry of entries) {\n caps.add(`trigger.${entry.trigger.kind}`);\n }\n}\n\nfunction detectInputCapabilities(\n inputs:\n | Readonly<\n Record<\n string,\n {\n type?: string;\n options?: readonly string[];\n pattern?: string;\n secret?: boolean;\n }\n >\n >\n | undefined,\n caps: Set<string>,\n): void {\n if (inputs === undefined || Object.keys(inputs).length === 0) return;\n caps.add(\"workflow.inputs\");\n for (const input of Object.values(inputs)) {\n if (input.secret) caps.add(\"secrets.pipeline-input\");\n if (input.type === \"choice\") caps.add(\"workflow.inputs.choice\");\n if (input.type === \"array\") caps.add(\"workflow.inputs.array\");\n if (input.pattern !== undefined) caps.add(\"workflow.inputs.pattern\");\n }\n}\n\nfunction detectDefaultCapabilities(\n defaults: {\n shell?: unknown;\n workdir?: unknown;\n env?: unknown;\n beforeScript?: unknown;\n afterScript?: unknown;\n timeout?: unknown;\n retry?: unknown;\n interruptible?: unknown;\n },\n caps: Set<string>,\n): void {\n caps.add(\"workflow.defaults\");\n const defaultCaps: ReadonlyArray<[unknown, string]> = [\n [defaults.shell, \"workflow.defaults.shell\"],\n [defaults.workdir, \"workflow.defaults.workdir\"],\n [defaults.env, \"workflow.defaults.env\"],\n [defaults.beforeScript, \"workflow.defaults.beforeScript\"],\n [defaults.afterScript, \"workflow.defaults.afterScript\"],\n [defaults.timeout, \"workflow.defaults.timeout\"],\n [defaults.retry, \"workflow.defaults.retry\"],\n [defaults.interruptible, \"workflow.defaults.interruptible\"],\n ];\n for (const [value, cap] of defaultCaps) {\n if (value !== undefined) caps.add(cap);\n }\n}\n\n/**\n * Detect capabilities used by a Definition Graph.\n * Returns a set of capability identifiers (e.g., \"trigger.push\").\n */\nexport function detectCapabilities(graph: DefinitionGraph): Set<string> {\n const caps = new Set<string>();\n for (const pipeline of graph.project.pipelines) {\n detectPipelineCapabilities(pipeline, caps);\n }\n return caps;\n}\n\n/**\n * Get the support level from a manifest entry.\n */\nfunction getSupportLevel(\n entry: CapabilitySupport | CapabilityDetail,\n): CapabilitySupport {\n if (typeof entry === \"string\") return validateSupport(entry);\n if (entry === null || typeof entry !== \"object\") {\n throw new PluginError(\n \"capability entry must be a string or CapabilityDetail\",\n \"INVALID_CAPABILITY\",\n );\n }\n return validateSupport((entry as CapabilityDetail).support);\n}\n\n/**\n * Find the best support level for a capability across all manifests.\n * \"native\" > \"lowered\" > \"connector\" > \"emulated\" > \"partial\" > \"unsupported\".\n */\nfunction findBestSupport(\n capability: string,\n manifests: readonly CapabilityManifest[],\n): CapabilitySupport {\n let best: CapabilitySupport = \"unsupported\";\n for (const manifest of manifests) {\n const entry = manifest[capability];\n if (entry === undefined) continue;\n const level = getSupportLevel(entry);\n if (PRIORITY[level] > PRIORITY[best]) {\n best = level;\n }\n }\n return best;\n}\n\n/**\n * Map a support level to a diagnostic severity.\n */\nfunction severityFor(support: CapabilitySupport): \"error\" | \"warning\" | \"info\" {\n switch (support) {\n case \"unsupported\":\n return \"error\";\n case \"emulated\":\n case \"partial\":\n return \"warning\";\n case \"connector\":\n return \"info\";\n default:\n return \"info\";\n }\n}\n\n/**\n * Analyze a Definition Graph against capability manifests.\n * Returns diagnostics for capabilities that are not natively or lowered\n * supported.\n */\nexport function analyzeCapabilities(\n graph: DefinitionGraph,\n manifests: readonly CapabilityManifest[],\n): readonly CapabilityDiagnostic[] {\n for (const manifest of manifests) {\n validateCapabilityManifest(manifest);\n }\n const used = detectCapabilities(graph);\n const diagnostics: CapabilityDiagnostic[] = [];\n\n for (const capability of used) {\n const support = findBestSupport(capability, manifests);\n if (support === \"native\" || support === \"lowered\") continue;\n\n diagnostics.push({\n capability,\n support,\n severity: severityFor(support),\n message: `capability '${capability}' is ${support}`,\n });\n }\n\n return diagnostics;\n}\n","// Plugin factory and registry. Spec 07 — §17.1.\n\nimport type {\n SverkaPlugin,\n PluginOptions,\n PluginMeta,\n PluginRegistry,\n CapabilityManifest,\n} from \"./types.js\";\nimport { validateCapabilityManifest } from \"./capabilities.js\";\nimport { PluginError } from \"./errors.js\";\n\n/**\n * Define a Sverka plugin. The factory function receives optional options\n * and meta, and returns a SverkaPlugin object.\n *\n * @example\n * const plugin = defineSverkaPlugin(() => ({\n * name: \"github\",\n * apiVersion: \"sverka.dev/v1\",\n * capabilities: { \"trigger.push\": \"native\" },\n * }));\n */\nexport function defineSverkaPlugin(\n factory: (options?: PluginOptions, meta?: PluginMeta) => SverkaPlugin,\n options?: PluginOptions,\n): SverkaPlugin {\n const meta: PluginMeta = { version: \"1.0.0\" };\n const plugin = factory(options, meta);\n validatePlugin(plugin);\n return snapshotPlugin(plugin);\n}\n\n/**\n * Store a validated, defensive copy of a plugin so callers cannot mutate\n * the registry's internal state after registration.\n */\nfunction snapshotPlugin(plugin: SverkaPlugin): SverkaPlugin {\n const copy: Record<string, unknown> = {\n name: plugin.name,\n apiVersion: plugin.apiVersion,\n };\n if (plugin.capabilities) {\n copy.capabilities = snapshotCapabilityManifest(plugin.capabilities);\n }\n if (plugin.model) copy.model = [...plugin.model];\n if (plugin.transforms) copy.transforms = [...plugin.transforms];\n if (plugin.validators) copy.validators = [...plugin.validators];\n if (plugin.targets) copy.targets = [...plugin.targets];\n if (plugin.importers) copy.importers = [...plugin.importers];\n if (plugin.engines) copy.engines = [...plugin.engines];\n if (plugin.connectors) copy.connectors = [...plugin.connectors];\n if (plugin.extensions) copy.extensions = [...plugin.extensions];\n // Tools facet is a live runtime object (ToolProvider); shallow-copy the\n // reference so the registry snapshot preserves the facet without trying to\n // deep-clone stateful connections (Spec 23).\n if (plugin.tools) copy.tools = plugin.tools;\n return copy as unknown as SverkaPlugin;\n}\n\nfunction snapshotCapabilityManifest(\n manifest: CapabilityManifest,\n): CapabilityManifest {\n const copy: CapabilityManifest = {};\n for (const [capability, value] of Object.entries(manifest)) {\n copy[capability] = typeof value === \"string\" ? value : { ...value };\n }\n return copy;\n}\n\n/**\n * Validate a plugin has required fields and a valid capabilities manifest.\n */\nfunction validatePlugin(plugin: SverkaPlugin): void {\n if (!plugin || typeof plugin !== \"object\") {\n throw new PluginError(\"plugin must be an object\", \"INVALID_PLUGIN\");\n }\n if (typeof plugin.name !== \"string\" || plugin.name.length === 0) {\n throw new PluginError(\n \"plugin must have a non-empty name\",\n \"INVALID_PLUGIN\",\n );\n }\n if (typeof plugin.apiVersion !== \"string\" || plugin.apiVersion.length === 0) {\n throw new PluginError(\"plugin must have an apiVersion\", \"INVALID_PLUGIN\");\n }\n if (plugin.capabilities !== undefined) {\n validateCapabilityManifest(plugin.capabilities);\n }\n}\n\n/**\n * Create a plugin registry.\n */\nexport function createPluginRegistry(): PluginRegistry {\n const plugins: SverkaPlugin[] = [];\n const names = new Set<string>();\n\n return {\n register(plugin: SverkaPlugin): void {\n validatePlugin(plugin);\n if (names.has(plugin.name)) {\n throw new PluginError(\n `plugin '${plugin.name}' is already registered`,\n \"DUPLICATE_PLUGIN\",\n );\n }\n names.add(plugin.name);\n plugins.push(snapshotPlugin(plugin));\n },\n get plugins(): readonly SverkaPlugin[] {\n return plugins.map((p) => snapshotPlugin(p));\n },\n getCapabilities(): CapabilityManifest[] {\n return plugins\n .filter((p) => p.capabilities !== undefined)\n .map((p) =>\n snapshotCapabilityManifest(p.capabilities as CapabilityManifest),\n );\n },\n };\n}\n","// GitHub capability manifest. Spec 08 — §24.\nimport type { CapabilityManifest } from \"../plugin/index.js\";\n\nexport const githubCapabilities: CapabilityManifest = {\n \"trigger.push\": \"native\",\n \"trigger.changeRequest\": \"native\",\n \"trigger.manual\": \"native\",\n \"runtime.host\": \"native\",\n \"runtime.container\": \"native\",\n \"operation.shell\": \"native\",\n \"operation.import\": \"lowered\",\n \"output.scalar\": \"lowered\",\n \"output.artifact\": \"native\",\n \"graph.dependencies\": \"native\",\n \"graph.conditions\": \"native\",\n \"graph.matrix\": \"native\",\n \"matrix.include\": \"native\",\n \"matrix.exclude\": \"native\",\n \"matrix.failFast\": \"native\",\n \"matrix.maxParallel\": \"native\",\n \"trigger.schedule\": \"native\",\n \"step.beforeScript\": \"native\",\n \"step.afterScript\": \"native\",\n \"step.continueOnError\": \"native\",\n \"policy.retry\": \"emulated\",\n \"policy.compensation\": \"emulated\",\n \"execution.workdir\": \"native\",\n \"execution.shell\": \"native\",\n \"environment.variables\": \"native\",\n \"secrets.runtime\": \"native\",\n \"secrets.pipeline-input\": \"native\",\n \"concurrency.interruptible\": \"partial\",\n \"environment.permissions\": \"native\",\n \"runner.selection\": \"native\",\n \"runner.group\": \"native\",\n \"secrets.oidc\": \"native\",\n \"secrets.oidc.multiAudience\": \"unsupported\",\n \"workflow.rules\": \"partial\",\n \"workflow.rules.changes\": \"unsupported\",\n \"workflow.rules.exists\": \"unsupported\",\n \"workflow.defaults\": \"native\",\n \"workflow.defaults.shell\": \"native\",\n \"workflow.defaults.workdir\": \"native\",\n \"workflow.defaults.env\": \"unsupported\",\n \"workflow.defaults.beforeScript\": \"lowered\",\n \"workflow.defaults.afterScript\": \"lowered\",\n \"workflow.defaults.timeout\": \"unsupported\",\n \"workflow.defaults.retry\": \"unsupported\",\n \"workflow.defaults.interruptible\": \"unsupported\",\n \"artifact.report\": \"emulated\",\n \"artifact.report.junit\": \"emulated\",\n \"artifact.report.coverage\": \"emulated\",\n \"artifact.report.dotenv\": \"emulated\",\n \"artifact.report.sast\": \"emulated\",\n \"artifact.report.dast\": \"emulated\",\n \"artifact.report.dependencyScanning\": \"emulated\",\n \"artifact.report.containerScanning\": \"emulated\",\n \"artifact.report.licenseScanning\": \"emulated\",\n \"artifact.report.performance\": \"emulated\",\n \"artifact.report.metrics\": \"emulated\",\n \"artifact.report.terraform\": \"emulated\",\n \"artifact.report.quality\": \"emulated\",\n \"artifact.report.sarif\": \"emulated\",\n \"workflow.inputs\": \"native\",\n \"workflow.inputs.choice\": \"native\",\n \"workflow.inputs.array\": \"unsupported\",\n \"workflow.inputs.pattern\": \"unsupported\",\n \"environment.services\": \"native\",\n \"environment.services.ports\": \"native\",\n \"deployment.environment\": \"native\",\n \"deployment.environment.action\": \"unsupported\",\n \"deployment.environment.tier\": \"unsupported\",\n \"artifact.retention\": \"native\",\n \"artifact.access\": \"unsupported\",\n cache: \"lowered\",\n \"cache.policy\": \"lowered\",\n \"cache.fallbackKeys\": \"lowered\",\n \"concurrency.group\": \"native\",\n \"concurrency.cancelInProgress\": \"native\",\n \"reusable.pipeline\": \"native\",\n \"reusable.pipeline.inputs\": \"native\",\n \"reusable.pipeline.outputs\": \"native\",\n \"reusable.component\": \"native\",\n \"reusable.component.versioning\": \"native\",\n \"reusable.childPipeline\": \"unsupported\",\n \"reusable.downstream\": \"emulated\",\n \"deployment.release\": \"emulated\",\n \"deployment.pages\": \"native\",\n \"import.github\": \"native\",\n \"import.include\": \"emulated\",\n \"scheduling.delay\": \"emulated\",\n \"execution.background\": \"emulated\",\n \"runtime.network\": \"emulated\",\n \"step.permissions\": \"native\",\n \"agent.step\": \"emulated\",\n \"run.query\": \"emulated\",\n};\n","// GitHub target error class. Spec 08.\n\nexport type GithubTargetErrorCode =\n | \"INVALID_GRAPH\"\n | \"UNSUPPORTED_TRIGGER\"\n | \"UNSUPPORTED_FEATURE\"\n | \"LOWER_FAILED\"\n | \"LOWERING_ERROR\"\n | \"IMPORT_FAILED\"\n | \"INVALID_MATRIX\";\n\nexport class GithubTargetError extends Error {\n readonly code: GithubTargetErrorCode;\n override readonly cause: unknown;\n\n constructor(message: string, code: GithubTargetErrorCode, cause?: unknown) {\n super(message);\n this.name = \"GithubTargetError\";\n this.code = code;\n this.cause = cause;\n }\n}\n","// Shared helpers for CI target lowering (github/ + gitlab/).\nimport type { StepDefinition } from \"@sverka/workflow\";\n\n/**\n * Build a mapping from full step IDs (e.g., \"ci/lint\") to CI-safe\n * job IDs (e.g., \"lint\"). If there are collisions, append a suffix.\n */\nexport function buildJobIdMap(\n steps: readonly StepDefinition[],\n): Map<string, string> {\n const map = new Map<string, string>();\n const used = new Set<string>();\n\n for (const step of steps) {\n // Use the last segment of the path as the job ID.\n const shortId = step.id.includes(\"/\") ? step.id.split(\"/\").pop()! : step.id;\n let jobId = shortId;\n let suffix = 1;\n while (used.has(jobId)) {\n jobId = `${shortId}-${suffix}`;\n suffix++;\n }\n used.add(jobId);\n map.set(step.id, jobId);\n }\n\n return map;\n}\n","// Shared lowering helper for exportStdout operations.\n// Both the GitHub and GitLab lowers bind a `fromStdout` artifact output to\n// the most recent shell op's captured stdout.\n\n/**\n * Quote a literal string using single quotes for a POSIX shell.\n */\nexport function shellQuoteSingle(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/**\n * Wrap a shell command line so its stdout is also written to the declared\n * artifact file(s), matching the runtime's exportStdout semantics. The\n * capture must work under POSIX sh (no pipefail), so the command's stdout is\n * redirected to the file and replayed with cat; the original exit code is\n * re-raised so a failing check still fails the job.\n *\n * Background commands (`cmd &`) detach before stdout can be captured; the\n * runtime records an empty artifact for them, so empty files are created.\n */\nexport function wrapStdoutCaptureLine(\n command: string,\n names: readonly string[],\n): string {\n const quoted = names.map(shellQuoteSingle);\n if (command.endsWith(\" &\")) {\n return [command, `touch ${quoted.join(\" \")}`].join(\"\\n\");\n }\n const [first, ...rest] = quoted;\n const teeRest = rest.length > 0 ? ` | tee ${rest.join(\" \")}` : \"\";\n return [\n \"sverka_rc=0\",\n `{ ${command}`,\n `} > ${first} || sverka_rc=$?`,\n `cat ${first}${teeRest}`,\n `if [ \"$sverka_rc\" -gt 0 ]; then exit \"$sverka_rc\"; fi`,\n ].join(\"\\n\");\n}\n","// Native lowering: Definition Graph → GithubTargetGraph[].\n// Spec 08 — §18.1, §19. F-31: multi-pipeline reusable workflows.\n\nimport type {\n DefinitionGraph,\n PipelineDefinition,\n StepDefinition,\n EntryDefinition,\n OperationDefinition,\n Dependency,\n Reference,\n Expression,\n Input,\n} from \"@sverka/workflow\";\nimport type {\n Trigger,\n MatrixSpec,\n StepRef,\n StatusCondition,\n PipelineDefaults,\n ReportSpec,\n ServiceContainer,\n CacheSpec,\n Rule,\n} from \"@sverka/workflow\";\nimport type {\n GithubTargetGraph,\n GithubTriggers,\n GithubJob,\n GithubStep,\n GithubRunsOn,\n GithubDefaults,\n GithubDefaultsRun,\n GithubInput,\n GithubService,\n GithubTargetConfig,\n} from \"./types.js\";\nimport { GithubTargetError } from \"./errors.js\";\nimport { buildJobIdMap } from \"../job-ids.js\";\nimport { wrapStdoutCaptureLine } from \"../stdout-capture.js\";\n\n/**\n * Lower a Definition Graph to one or more GithubTargetGraphs.\n * - Each pipeline with entries → a root workflow with its triggers.\n * - Each pipeline referenced by a call step → a reusable workflow with\n * `on: workflow_call` (+ its own triggers if it also has entries).\n * - Call steps become `uses:` jobs.\n * Single-pipeline graphs (no calls) are unchanged (backward compat).\n */\nexport function lowerGithub(\n graph: DefinitionGraph,\n config?: GithubTargetConfig,\n): GithubTargetGraph | readonly GithubTargetGraph[] {\n if (graph.project.pipelines.length === 0) {\n throw new GithubTargetError(\"graph has no pipelines\", \"INVALID_GRAPH\");\n }\n\n // Single-pipeline, no special steps → backward compat.\n if (graph.project.pipelines.length === 1) {\n const pipeline = graph.project.pipelines[0]!;\n const hasSpecial = pipeline.steps.some(\n (s) => s.call || s.component || s.childPipeline || s.downstream,\n );\n if (!hasSpecial) {\n return lowerSinglePipeline(pipeline, config);\n }\n }\n\n // Multi-pipeline or has special steps → lower all pipelines.\n return lowerMultiPipeline(graph, config);\n}\n\n/**\n * The Checkout step shared by every job, with optional `with:` inputs\n * (e.g. `submodules: recursive`) from {@link GithubTargetConfig.checkoutWith}.\n */\nfunction checkoutStep(config?: GithubTargetConfig): GithubStep {\n return {\n name: \"Checkout\",\n uses: \"actions/checkout@v4\",\n ...(config?.checkoutWith ? { with: config.checkoutWith } : {}),\n };\n}\n\n/**\n * Toolchain/dependency setup steps injected after Checkout in every job\n * that executes user commands (shell and component steps).\n */\nfunction setupSteps(config?: GithubTargetConfig): readonly GithubStep[] {\n return config?.setup ?? [];\n}\n\n/**\n * Lower a single pipeline (no calls) — original v0 behavior.\n */\nfunction lowerSinglePipeline(\n pipeline: PipelineDefinition,\n config?: GithubTargetConfig,\n): GithubTargetGraph {\n const reachableSteps = filterReachableSteps(pipeline);\n const jobIdMap = buildJobIdMap(reachableSteps);\n\n const triggers = lowerTriggers(pipeline.entries, pipeline.inputs);\n const jobs = lowerStepsWithCalls(\n reachableSteps,\n jobIdMap,\n pipeline.id,\n config,\n );\n\n return assemblePipelineTarget(pipeline, triggers, jobs);\n}\n\n/**\n * Assemble a GithubTargetGraph from a pipeline, its triggers, and jobs.\n * Shared by lowerSinglePipeline and lowerMultiPipeline.\n */\nfunction assemblePipelineTarget(\n pipeline: PipelineDefinition,\n triggers: GithubTriggers,\n jobs: readonly GithubJob[],\n): GithubTargetGraph {\n // Least privilege (S8264): pipeline permissions become per-job grants and\n // the workflow-level default is deny-all. Jobs with explicit permissions\n // (e.g. deploys, safe-outputs) keep theirs.\n const grants = pipeline.permissions;\n const jobsWithPermissions =\n grants === undefined\n ? jobs\n : jobs.map((job): GithubJob => {\n if (job.permissions !== undefined) return job;\n const permissions: Readonly<Record<string, string>> = job.steps.some(\n (s) => s.uses?.startsWith(\"github/codeql-action/upload-sarif@\"),\n )\n ? { ...grants, \"security-events\": \"write\" }\n : grants;\n return { ...job, permissions };\n });\n return {\n name: pipeline.id,\n on: triggers,\n jobs: jobsWithPermissions,\n env: collectEnv(pipeline),\n ...(pipeline.permissions !== undefined ? { permissions: {} } : {}),\n ...(pipeline.defaults !== undefined\n ? { defaults: lowerDefaults(pipeline.defaults) }\n : {}),\n ...(pipeline.concurrency !== undefined\n ? { concurrency: pipeline.concurrency }\n : {}),\n };\n}\n\n/**\n * Lower pipeline defaults to GitHub defaults.run (shell + working-directory only).\n */\nfunction lowerDefaults(defaults: PipelineDefaults): GithubDefaults {\n const run: GithubDefaultsRun = {\n ...(defaults.shell !== undefined ? { shell: defaults.shell } : {}),\n ...(defaults.workdir !== undefined\n ? { \"working-directory\": defaults.workdir }\n : {}),\n };\n return { run };\n}\n\n/**\n * Lower a multi-pipeline graph. Each pipeline that has entries OR is referenced\n * by a call step gets its own workflow file.\n */\nfunction lowerMultiPipeline(\n graph: DefinitionGraph,\n config?: GithubTargetConfig,\n): readonly GithubTargetGraph[] {\n const pipelines = graph.project.pipelines;\n const calledPipelineIds = collectCalledPipelineIds(pipelines);\n\n const result: GithubTargetGraph[] = [];\n for (const pipeline of pipelines) {\n const target = lowerPipelineInGraph(\n pipeline,\n calledPipelineIds.has(pipeline.id),\n config,\n );\n if (target !== undefined) result.push(target);\n }\n return result;\n}\n\n/**\n * Collect the set of pipeline IDs that are referenced by at least one call step.\n */\nfunction collectCalledPipelineIds(\n pipelines: readonly PipelineDefinition[],\n): Set<string> {\n const called = new Set<string>();\n for (const p of pipelines) {\n for (const step of p.steps) {\n if (step.call) {\n called.add(step.call.callee);\n }\n }\n }\n return called;\n}\n\n/**\n * Lower a single pipeline within a multi-pipeline graph.\n * Returns undefined if the pipeline is neither a root nor a callee.\n */\nfunction lowerPipelineInGraph(\n pipeline: PipelineDefinition,\n isCalled: boolean,\n config?: GithubTargetConfig,\n): GithubTargetGraph | undefined {\n const hasEntries = pipeline.entries.length > 0;\n if (!hasEntries && !isCalled) return undefined;\n\n // For callees, all steps are reachable (no entries needed).\n // For roots, filter by entry reachability.\n const reachableSteps = hasEntries\n ? filterReachableSteps(pipeline)\n : pipeline.steps;\n const jobIdMap = buildJobIdMap(reachableSteps);\n\n // Triggers: root triggers + workflow_call if called.\n let triggers = lowerTriggers(pipeline.entries, pipeline.inputs);\n if (isCalled) {\n triggers = addWorkflowCall(triggers, pipeline.inputs);\n }\n\n const jobs = lowerStepsWithCalls(\n reachableSteps,\n jobIdMap,\n pipeline.id,\n config,\n );\n return assemblePipelineTarget(pipeline, triggers, jobs);\n}\n\n/**\n * Add workflow_call trigger with inputs to a GithubTriggers object.\n */\nfunction addWorkflowCall(\n triggers: GithubTriggers,\n inputs: Readonly<Record<string, Input>>,\n): GithubTriggers {\n const inputEntries = Object.entries(inputs);\n if (inputEntries.length === 0) {\n return { ...triggers, workflow_call: null };\n }\n\n const workflowInputs: Record<string, unknown> = {};\n for (const [name, input] of inputEntries) {\n let type = \"string\";\n if (input.type === \"number\") {\n type = \"number\";\n } else if (input.type === \"boolean\") {\n type = \"boolean\";\n }\n const ghInput: Record<string, unknown> = {\n type,\n required: input.required ?? false,\n };\n if (input.default !== undefined) {\n ghInput.default = input.default;\n }\n if (input.description !== undefined) {\n ghInput.description = input.description;\n }\n workflowInputs[name] = ghInput;\n }\n\n return { ...triggers, workflow_call: { inputs: workflowInputs } };\n}\n\n/**\n * Return the steps reachable from any entry root by following dependencies.\n */\nfunction filterReachableSteps(\n pipeline: PipelineDefinition,\n): readonly StepDefinition[] {\n if (pipeline.steps.length === 0) {\n const invalidRoot = pipeline.entries\n .flatMap((e) => e.roots)\n .find((root) => root.length > 0);\n if (invalidRoot) {\n throw new GithubTargetError(\n `entry references unknown root step '${invalidRoot}'`,\n \"INVALID_GRAPH\",\n );\n }\n return [];\n }\n\n const byId = new Map(pipeline.steps.map((step) => [step.id, step]));\n const reachable = new Set<string>();\n const queue: string[] = [];\n\n for (const entry of pipeline.entries) {\n enqueueRoots(entry.roots, byId, reachable, queue);\n }\n\n while (queue.length > 0) {\n const id = queue.shift()!;\n const step = byId.get(id);\n if (!step) continue;\n enqueueDependencies(step, byId, reachable, queue);\n }\n\n return pipeline.steps.filter((step) => reachable.has(step.id));\n}\n\nfunction enqueueRoots(\n roots: readonly string[],\n byId: Map<string, StepDefinition>,\n reachable: Set<string>,\n queue: string[],\n): void {\n for (const root of roots) {\n if (!byId.has(root)) {\n throw new GithubTargetError(\n `entry references unknown root step '${root}'`,\n \"INVALID_GRAPH\",\n );\n }\n enqueueIfNew(root, reachable, queue);\n }\n}\n\nfunction enqueueDependencies(\n step: StepDefinition,\n byId: Map<string, StepDefinition>,\n reachable: Set<string>,\n queue: string[],\n): void {\n for (const dep of step.dependencies) {\n const producer = dep.producer;\n if (!byId.has(producer)) {\n throw new GithubTargetError(\n `step depends on unknown producer '${producer}'`,\n \"INVALID_GRAPH\",\n );\n }\n enqueueIfNew(producer, reachable, queue);\n }\n}\n\nfunction enqueueIfNew(\n id: string,\n reachable: Set<string>,\n queue: string[],\n): void {\n if (!reachable.has(id)) {\n reachable.add(id);\n queue.push(id);\n }\n}\n\n/**\n * Map Sverka triggers to GitHub triggers.\n * Multiple entries of the same kind have their filters merged.\n */\nfunction lowerTriggers(\n entries: readonly EntryDefinition[],\n inputs: Readonly<Record<string, Input>>,\n): GithubTriggers {\n const pushBranches = new Set<string>();\n const pushTags = new Set<string>();\n const pushPaths = new Set<string>();\n let pushAll = false;\n const prBranches = new Set<string>();\n const prPaths = new Set<string>();\n let prAll = false;\n let hasManual = false;\n const scheduleEntries: { cron: string; timezone?: string }[] = [];\n\n for (const entry of entries) {\n const t = entry.trigger;\n switch (t.kind) {\n case \"push\":\n collectFilters(\n t,\n pushBranches,\n pushTags,\n pushPaths,\n () => (pushAll = true),\n );\n break;\n case \"changeRequest\":\n collectFilters(t, prBranches, undefined, prPaths, () => (prAll = true));\n break;\n case \"manual\":\n hasManual = true;\n break;\n case \"schedule\":\n scheduleEntries.push({\n cron: t.cron,\n ...(t.timezone ? { timezone: t.timezone } : {}),\n });\n break;\n default:\n throw new GithubTargetError(\n `unsupported trigger kind: ${JSON.stringify((t as Trigger).kind)}`,\n \"UNSUPPORTED_TRIGGER\",\n );\n }\n }\n\n return assembleTriggers({\n pushAll,\n pushBranches,\n pushTags,\n pushPaths,\n prAll,\n prBranches,\n prPaths,\n hasManual,\n scheduleEntries,\n inputs,\n });\n}\n\nfunction collectFilters(\n t: Trigger,\n branches: Set<string>,\n tags: Set<string> | undefined,\n paths: Set<string>,\n markAll: () => void,\n): void {\n if (t.kind === \"schedule\") {\n markAll();\n return;\n }\n const filter = t.filter;\n const hasBranches = filter?.branches && filter.branches.length > 0;\n const hasTags = filter?.tags && filter.tags.length > 0;\n const hasPaths = filter?.paths && filter.paths.length > 0;\n\n // Tag filters are not meaningful on change-request triggers (PRs don't have tags).\n if (hasTags && tags === undefined) {\n throw new GithubTargetError(\n \"tag filters are not supported on change-request triggers\",\n \"UNSUPPORTED_TRIGGER\",\n );\n }\n\n if (hasBranches) addAll(branches, filter!.branches!);\n if (hasTags && tags) addAll(tags, filter!.tags!);\n if (hasPaths) addAll(paths, filter!.paths!);\n\n // If no filter at all, mark as \"fire on all\"\n if (!hasBranches && !hasTags && !hasPaths) {\n markAll();\n }\n}\n\n/** Add all items from a readonly array to a Set. */\nfunction addAll<T>(set: Set<T>, items: readonly T[]): void {\n for (const item of items) set.add(item);\n}\n\ninterface TriggerFilters {\n readonly pushAll: boolean;\n readonly pushBranches: Set<string>;\n readonly pushTags: Set<string>;\n readonly pushPaths: Set<string>;\n readonly prAll: boolean;\n readonly prBranches: Set<string>;\n readonly prPaths: Set<string>;\n readonly hasManual: boolean;\n readonly scheduleEntries: readonly { cron: string; timezone?: string }[];\n readonly inputs: Readonly<Record<string, Input>>;\n}\n\nfunction assembleTriggers(f: TriggerFilters): GithubTriggers {\n const triggers: Record<string, unknown> = {};\n const push = assemblePushTrigger(f);\n if (push) triggers.push = push;\n const pr = assemblePullRequestTrigger(f);\n if (pr) triggers.pull_request = pr;\n if (f.hasManual) {\n const loweredInputs = lowerInputs(f.inputs);\n triggers.workflow_dispatch =\n loweredInputs !== undefined ? { inputs: loweredInputs } : null;\n }\n if (f.scheduleEntries.length > 0) triggers.schedule = f.scheduleEntries;\n return triggers as GithubTriggers;\n}\n\nfunction assemblePushTrigger(\n f: TriggerFilters,\n): Record<string, string[]> | null {\n if (f.pushAll) return {};\n if (\n f.pushBranches.size === 0 &&\n f.pushTags.size === 0 &&\n f.pushPaths.size === 0\n )\n return null;\n const push: Record<string, string[]> = {};\n if (f.pushBranches.size > 0) push.branches = [...f.pushBranches];\n if (f.pushTags.size > 0) push.tags = [...f.pushTags];\n if (f.pushPaths.size > 0) push.paths = [...f.pushPaths];\n return push;\n}\n\nfunction assemblePullRequestTrigger(\n f: TriggerFilters,\n): Record<string, string[]> | null {\n if (f.prAll) return {};\n if (f.prBranches.size === 0 && f.prPaths.size === 0) return null;\n const pr: Record<string, string[]> = {};\n if (f.prBranches.size > 0) pr.branches = [...f.prBranches];\n if (f.prPaths.size > 0) pr.paths = [...f.prPaths];\n return pr;\n}\n\n/**\n * Lower pipeline inputs to GitHub workflow_dispatch inputs.\n * Returns undefined if no inputs are present.\n * Maps Sverka types to GitHub types: choice→choice, array→unsupported (dropped),\n * others map directly. pattern is dropped (unsupported on GitHub).\n */\nfunction lowerInputs(\n inputs: Readonly<Record<string, Input>>,\n): Readonly<Record<string, GithubInput>> | undefined {\n if (Object.keys(inputs).length === 0) return undefined;\n const result: Record<string, GithubInput> = {};\n for (const [name, input] of Object.entries(inputs)) {\n const ghInput: GithubInput = {\n type: input.type === \"array\" ? \"string\" : input.type,\n ...(input.description !== undefined\n ? { description: input.description }\n : {}),\n ...(input.required !== undefined ? { required: input.required } : {}),\n ...(input.default !== undefined && typeof input.default !== \"object\"\n ? { default: input.default as string | number | boolean }\n : {}),\n ...(input.options !== undefined ? { options: input.options } : {}),\n };\n result[name] = ghInput;\n }\n return result;\n}\n\n/**\n * Lower reachable steps to GitHub jobs. One job per step.\n * Call steps become `uses:` jobs (reusable workflow calls).\n * Component steps become `uses:` jobs (composite action calls).\n */\nfunction lowerStepsWithCalls(\n steps: readonly StepDefinition[],\n jobIdMap: Map<string, string>,\n pipelineId: string,\n config?: GithubTargetConfig,\n): readonly GithubJob[] {\n return steps.map((step) => {\n if (step.call) {\n return lowerCallStep(step, jobIdMap, pipelineId);\n }\n if (step.component) {\n return lowerComponentStep(step, jobIdMap, config);\n }\n if (step.childPipeline) {\n return lowerChildPipelineStep(step, jobIdMap);\n }\n if (step.downstream) {\n return lowerDownstreamStep(step, jobIdMap);\n }\n return lowerStep(step, jobIdMap, config);\n });\n}\n\n/**\n * Lower a Reference value to a GitHub expression string.\n * Returns the expression if `value` is a Reference, otherwise `undefined`\n * (meaning the value is a literal the caller should handle itself).\n * Context references are mapped through GITHUB_CONTEXT_MAP so that Sverka\n * namespaces (e.g. `git.sha`) become valid GitHub expressions (e.g.\n * `github.sha`).\n *\n * Secret references are sink-specific:\n * - In `with:` inputs (`forWithInput = true`): `${{ secrets.FIELD }}`.\n * GitHub Actions does not expand `$FIELD` in `with:` values — it treats it\n * as a literal string. The `secrets` context is the correct syntax here.\n * - In `run:` commands (`forWithInput = false`, default): `$FIELD`.\n * The shell expands the env var, and this avoids exposing the secret value\n * in workflow logs.\n */\nfunction lowerReferenceExpr(\n value: unknown,\n jobIdMap: Map<string, string>,\n forWithInput = false,\n): string | undefined {\n if (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n \"kind\" in value\n ) {\n const ref = value as Reference;\n if (ref.kind === \"step\") {\n const producerJobId = jobIdMap.get(ref.step) ?? ref.step;\n return `\\${{ needs.${producerJobId}.outputs.${ref.output} }}`;\n }\n if (ref.kind === \"context\") {\n return translateContextRef(ref.namespace, ref.field, false, forWithInput);\n }\n }\n return undefined;\n}\n\n/**\n * Lower a call step to a GitHub reusable workflow call job.\n */\nfunction lowerCallStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n pipelineId: string,\n): GithubJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const needs = lowerDependencies(step.dependencies, jobIdMap);\n const call = step.call!;\n const callee = call.callee;\n\n // Build `with:` from bound inputs.\n // Secrets in `with:` inputs must use ${{ secrets.FIELD }} — GitHub Actions\n // does not expand $FIELD in with: values (it treats it as a literal string).\n const withMap: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(call.inputs)) {\n withMap[name] = lowerReferenceExpr(value, jobIdMap, true) ?? value;\n }\n\n return {\n id: jobId,\n name: jobId,\n runsOn: \"ubuntu-latest\",\n needs,\n steps: [],\n uses: `./.github/workflows/${callee}.yml`,\n ...(Object.keys(withMap).length > 0 ? { with: withMap } : {}),\n secrets: \"inherit\",\n };\n}\n\n/**\n * Lower a component step to a GitHub composite action call job.\n * F-32: component → uses: org/component@version with `with:` inputs.\n */\nfunction lowerComponentStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n config?: GithubTargetConfig,\n): GithubJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const needs = lowerDependencies(step.dependencies, jobIdMap);\n const comp = step.component!;\n\n // Build `with:` from bound inputs.\n // Secrets in `with:` inputs must use ${{ secrets.FIELD }} — GitHub Actions\n // does not expand $FIELD in with: values (it treats it as a literal string).\n const withMap: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(comp.inputs)) {\n withMap[name] = lowerReferenceExpr(value, jobIdMap, true) ?? value;\n }\n\n // Component references that look like GitHub Actions (org/repo@ref) are\n // emitted as normal jobs with an action step. Reusable workflow references\n // (./.github/workflows/*.yml) remain as `uses:` jobs.\n const isAction = !comp.name.startsWith(\"./\");\n if (isAction) {\n return {\n id: jobId,\n name: jobId,\n runsOn: resolveRunsOn(step),\n needs,\n steps: [\n checkoutStep(config),\n ...setupSteps(config),\n {\n name: `Component ${comp.name}`,\n uses: `${comp.name}@${comp.version}`,\n ...(Object.keys(withMap).length > 0 ? { with: withMap } : {}),\n },\n ],\n };\n }\n\n return {\n id: jobId,\n name: jobId,\n runsOn: \"ubuntu-latest\",\n needs,\n steps: [],\n uses: `${comp.name}@${comp.version}`,\n ...(Object.keys(withMap).length > 0 ? { with: withMap } : {}),\n };\n}\n\n/**\n * Lower a child pipeline step to a GitHub job.\n * F-33: GitHub does not natively support dynamic child pipelines.\n * We emit a no-op job with a warning comment. The native engine handles\n * the actual dynamic generation.\n */\nfunction lowerChildPipelineStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n): GithubJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const needs = lowerDependencies(step.dependencies, jobIdMap);\n return {\n id: jobId,\n name: jobId,\n runsOn: resolveRunsOn(step),\n needs,\n steps: [\n {\n name: \"Dynamic child pipeline (not natively supported on GitHub)\",\n run: `echo \"WARNING: Dynamic child pipelines are not supported by GitHub Actions. Generator: ${step.childPipeline!.generator}, artifact: ${step.childPipeline!.artifact}\"`,\n },\n ],\n };\n}\n\n/**\n * Lower a downstream step to a GitHub job.\n * F-34: GitHub emulates downstream project triggers via repository_dispatch API.\n */\nfunction lowerDownstreamStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n): GithubJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const needs = lowerDependencies(step.dependencies, jobIdMap);\n const ds = step.downstream!;\n // Build client_payload from inputs using JSON.stringify for valid JSON.\n const payloadObj: Record<string, string> = {};\n if (ds.inputs) {\n for (const [name, value] of Object.entries(ds.inputs)) {\n payloadObj[name] = lowerReferenceExpr(value, jobIdMap) ?? String(value);\n }\n }\n const payload = JSON.stringify(payloadObj);\n // Pass the payload and optional branch through step env vars, then expand\n // them as quoted shell variables. JSON.stringify does not escape apostrophes\n // for a POSIX shell — embedding the payload in a single-quoted command would\n // break if a runtime value (after GitHub expression expansion) contains a\n // single quote. Env vars are expanded by the runner after GitHub expression\n // evaluation, so the shell receives the value as a single argument.\n const env: Record<string, string> = { CLIENT_PAYLOAD: payload };\n if (ds.branch) {\n env.DOWNSTREAM_BRANCH = ds.branch;\n }\n const refPart = ds.branch ? ` -f ref=\"$DOWNSTREAM_BRANCH\"` : \"\";\n return {\n id: jobId,\n name: jobId,\n runsOn: resolveRunsOn(step),\n needs,\n steps: [\n {\n name: `Trigger downstream: ${ds.project}`,\n env,\n run: `gh api repos/${ds.project}/dispatches -f event_type=sverka-trigger -f client_payload=\"$CLIENT_PAYLOAD\"${refPart}`,\n },\n ],\n };\n}\n\n/**\n * Lower a single Step to a GitHub job.\n */\nfunction lowerStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n config?: GithubTargetConfig,\n): GithubJob {\n const needs = lowerDependencies(step.dependencies, jobIdMap);\n const rawSteps = lowerOperations(step, jobIdMap, config);\n\n // GitHub only supports boolean continue-on-error, not exit-code mapping.\n if (\n step.continueOnError !== undefined &&\n typeof step.continueOnError !== \"boolean\"\n ) {\n throw new GithubTargetError(\n \"GitHub does not support exit-code continueOnError; use a boolean value\",\n \"UNSUPPORTED_FEATURE\",\n );\n }\n\n const steps = applyContinueOnError(rawSteps, step, config);\n\n const jobId = jobIdMap.get(step.id) ?? step.id;\n\n const runtime = step.runtime;\n const mode = runtime.mode ?? \"host\";\n const runsOn = resolveRunsOn(step);\n const container = resolveContainer(step, mode);\n const jobEnv = collectJobEnv(runtime);\n\n return assembleGithubJob({\n jobId,\n steps,\n needs,\n step,\n runsOn,\n container,\n jobEnv,\n jobIdMap,\n });\n}\n\n/**\n * Apply continueOnError to the step's own run commands. Injected setup\n * stays fail-fast — a failed dependency install must not be ignored.\n */\nfunction applyContinueOnError(\n rawSteps: readonly GithubStep[],\n step: StepDefinition,\n config?: GithubTargetConfig,\n): GithubStep[] {\n const infraSteps = new Set<GithubStep>(setupSteps(config));\n return rawSteps.map((s) =>\n step.continueOnError !== undefined &&\n s.run !== undefined &&\n !infraSteps.has(s)\n ? {\n ...s,\n continueOnError:\n typeof step.continueOnError === \"boolean\"\n ? step.continueOnError\n : true,\n }\n : s,\n );\n}\n\n/**\n * Insert a sleep step to emulate delay (GitHub has no native delayed execution).\n * Called after checkout + setup steps are pushed, so the delay precedes the\n * step's own work but does not postpone toolchain setup.\n */\nfunction applyDelay(steps: GithubStep[], step: StepDefinition): void {\n if (!step.delay) return;\n const sleepSeconds = parseDurationToSeconds(step.delay);\n steps.push({\n name: `Delay (${step.delay})`,\n run: `sleep ${sleepSeconds}`,\n });\n}\n\n/**\n * Collect scalar output names for the job's `outputs:` mapping.\n * GitHub Actions requires outputs to be declared at the job level for\n * `needs.<job>.outputs.<name>` expressions to work.\n */\nfunction collectJobOutputs(step: StepDefinition): Record<string, string> {\n const jobOutputs: Record<string, string> = {};\n for (const op of step.operations) {\n if (op.kind === \"exportOutput\") {\n jobOutputs[op.name] = `\\${{ steps.output.outputs.${op.name} }}`;\n }\n }\n return jobOutputs;\n}\n\n/**\n * Build the job's `steps` array, inserting a cache step after checkout when\n * caching is enabled. Checkout is always the first step.\n */\nfunction resolveJobSteps(\n steps: GithubStep[],\n step: StepDefinition,\n): GithubStep[] {\n if (step.cache === undefined) return steps;\n // Cache step goes after checkout (always first) and before other steps.\n return [steps[0]!, lowerCacheStep(step.cache), ...steps.slice(1)];\n}\n\n/**\n * Resolve the job-level `if` expression.\n *\n * Rules take precedence over condition when both are present, matching\n * GitHub's behavior where workflow rules override step conditions. Multiple\n * rules are OR'd: GitHub's job-level `if` is a single expression, so we\n * combine all rule `if` conditions with `||`.\n */\nfunction resolveJobIf(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n): Record<string, string> {\n if (step.rules !== undefined && step.rules.length > 0) {\n return { if: lowerRulesIf(step.rules) };\n }\n if (step.condition !== undefined) {\n return { if: lowerCondition(step.condition, jobIdMap) };\n }\n return {};\n}\n\n/**\n * Resolve job-level permissions and environment for Pages deploys and\n * identity-token requests.\n *\n * GitHub Pages jobs need pages:write and id-token:write permissions.\n * Safe-outputs (Spec 25): steps with permissions.write get a scoped\n * permissions block from write kinds. Steps without writes get\n * permissions: {} (read-only). deployPages/identity take precedence.\n */\nconst WRITE_KIND_TO_GHA_PERMISSION: Readonly<Record<string, string>> = {\n \"pull-request\": \"pull-requests: write\",\n comment: \"issues: write\",\n deploy: \"deployments: write\",\n push: \"contents: write\",\n \"id-token\": \"id-token: write\",\n pages: \"pages: write\",\n};\n\nfunction resolveJobPermissions(step: StepDefinition): Record<string, unknown> {\n if (step.operations.some((op) => op.kind === \"deployPages\")) {\n return {\n permissions: { pages: \"write\", \"id-token\": \"write\" },\n environment: { name: \"github-pages\" },\n };\n }\n if (step.identity !== undefined) {\n return { permissions: { \"id-token\": \"write\" } };\n }\n // Safe-outputs: derive permissions from write declarations.\n // Only emit a permissions block when step.permissions is explicitly set.\n if (step.permissions !== undefined) {\n const writes = step.permissions.write;\n if (writes && writes.length > 0) {\n const perms: Record<string, string> = {};\n for (const decl of writes) {\n const mapped = WRITE_KIND_TO_GHA_PERMISSION[decl.kind];\n if (mapped !== undefined) {\n const [scope, level] = mapped.split(\": \");\n perms[scope!] = level!;\n } else {\n // Unknown kind → safe default\n perms[\"contents\"] = \"read\";\n }\n }\n return { permissions: perms };\n }\n // permissions set but no writes → explicit read-only\n return { permissions: {} };\n }\n // No permissions set → backward compatible (no permissions key)\n return {};\n}\n\n/**\n * Constituent parts for assembling a GithubJob.\n */\ninterface GithubJobParts {\n readonly jobId: string;\n readonly steps: GithubStep[];\n readonly needs: readonly string[];\n readonly step: StepDefinition;\n readonly runsOn: GithubRunsOn;\n readonly container: string | undefined;\n readonly jobEnv: Record<string, string>;\n readonly jobIdMap: Map<string, string>;\n}\n\n/**\n * Assemble the final GithubJob object from its constituent parts.\n */\nfunction assembleGithubJob(parts: GithubJobParts): GithubJob {\n const { jobId, steps, needs, step, runsOn, container, jobEnv, jobIdMap } =\n parts;\n const jobOutputs = collectJobOutputs(step);\n const jobIf = resolveJobIf(step, jobIdMap);\n const jobPermissions = resolveJobPermissions(step);\n\n return {\n id: jobId,\n name: jobId,\n runsOn,\n needs,\n ...(Object.keys(jobOutputs).length > 0 ? { outputs: jobOutputs } : {}),\n steps: resolveJobSteps(steps, step),\n ...(step.timeout !== undefined\n ? { timeoutMinutes: Math.ceil(step.timeout / 60000) }\n : {}),\n ...(Object.keys(jobEnv).length > 0 ? { env: jobEnv } : {}),\n ...(container ? { container } : {}),\n ...(step.matrix !== undefined\n ? { strategy: lowerStrategy(step.matrix) }\n : {}),\n ...jobIf,\n ...jobPermissions,\n ...resolveJobServices(step),\n ...resolveJobEnvironment(step),\n ...(step.concurrency !== undefined\n ? { concurrency: step.concurrency }\n : {}),\n };\n}\n\n/** Resolve job-level services field from step services. */\nfunction resolveJobServices(step: StepDefinition): Partial<GithubJob> {\n if (step.services === undefined || step.services.length === 0) return {};\n return { services: lowerServices(step.services) };\n}\n\n/** Resolve job-level environment field from step environment spec. */\nfunction resolveJobEnvironment(step: StepDefinition): Partial<GithubJob> {\n if (step.environment === undefined) return {};\n return {\n environment: {\n name: step.environment.name,\n ...(step.environment.url !== undefined\n ? { url: step.environment.url }\n : {}),\n },\n };\n}\n\n/**\n * Lower a cache spec to a GitHub cache step.\n * pull-push → actions/cache@v4\n * pull → actions/cache/restore@v4\n * push → actions/cache/save@v4\n */\nfunction lowerCacheStep(cache: CacheSpec): GithubStep {\n const policy = cache.policy ?? \"pull-push\";\n let action = \"actions/cache@v4\";\n if (policy === \"pull\") {\n action = \"actions/cache/restore@v4\";\n } else if (policy === \"push\") {\n action = \"actions/cache/save@v4\";\n }\n const withMap: Record<string, unknown> = {\n path: cache.paths.length === 1 ? cache.paths[0] : cache.paths.join(\"\\n\"),\n key: cache.key,\n };\n if (cache.restoreKeys !== undefined && cache.restoreKeys.length > 0) {\n withMap[\"restore-keys\"] =\n cache.restoreKeys.length === 1\n ? cache.restoreKeys[0]\n : cache.restoreKeys.join(\"\\n\");\n }\n return {\n name: \"Restore cache\",\n uses: action,\n with: withMap,\n };\n}\n\n/**\n * Lower service containers to GitHub services map (keyed by name).\n */\nfunction lowerServices(\n services: readonly ServiceContainer[],\n): Readonly<Record<string, GithubService>> {\n const result: Record<string, GithubService> = {};\n for (const svc of services) {\n // GitHub Actions does not support `entrypoint` or `command` on services.\n // Translate them to Docker `options` as a best-effort emulation.\n const options: string[] = [];\n if (svc.entrypoint !== undefined) {\n options.push(`--entrypoint=${svc.entrypoint[0] ?? \"\"}`);\n }\n const service: GithubService = {\n image: svc.image,\n ...(svc.env !== undefined ? { env: { ...svc.env } } : {}),\n ...(svc.ports !== undefined\n ? { ports: svc.ports.map((p) => `${p}:${p}`) }\n : {}),\n ...(options.length > 0 ? { options: options.join(\" \") } : {}),\n };\n result[svc.name] = service;\n }\n return result;\n}\n\nfunction resolveRunsOn(step: StepDefinition): GithubRunsOn {\n if (step.runner === undefined) {\n return \"ubuntu-latest\";\n }\n const { labels, group } = step.runner;\n if (group !== undefined) {\n return { group, labels };\n }\n if (labels.length === 1) {\n return labels[0]!;\n }\n return labels;\n}\n\n/**\n * Parse a duration string (e.g. \"5m\", \"30s\", \"1h\") to seconds.\n * F-48: used for GitHub sleep emulation.\n */\nfunction parseDurationToSeconds(duration: string): number {\n const match = /^(\\d+)\\s*(s|m|h|seconds?|minutes?|hours?)?$/i.exec(duration);\n if (!match) {\n throw new GithubTargetError(\n `invalid delay duration '${duration}'`,\n \"LOWER_FAILED\",\n );\n }\n const value = Number.parseInt(match[1]!, 10);\n const unit = (match[2] ?? \"s\").toLowerCase();\n if (unit.startsWith(\"h\")) return value * 3600;\n if (unit.startsWith(\"m\")) return value * 60;\n return value;\n}\n\nfunction resolveContainer(\n step: StepDefinition,\n mode: string,\n): string | undefined {\n if (mode === \"container\" && !step.runtime.image) {\n throw new GithubTargetError(\n `step '${step.id}' uses container mode without an image`,\n \"LOWER_FAILED\",\n );\n }\n return mode === \"container\" ? step.runtime.image : undefined;\n}\n\nfunction collectJobEnv(\n runtime: StepDefinition[\"runtime\"],\n): Record<string, string> {\n const jobEnv: Record<string, string> = {};\n if (runtime.env) {\n Object.assign(jobEnv, runtime.env);\n }\n if (runtime.secrets) {\n for (const secret of runtime.secrets) {\n jobEnv[secret] = `\\${{ secrets.${secret} }}`;\n }\n }\n return jobEnv;\n}\n\n/**\n * Map dependencies to job needs.\n * All dependency kinds create needs (GitHub jobs can't share values without artifacts).\n */\nfunction lowerDependencies(\n deps: readonly Dependency[],\n jobIdMap: Map<string, string>,\n): readonly string[] {\n const needs = new Set<string>();\n for (const dep of deps) {\n // Map full step ID to GitHub job ID.\n const jobId = jobIdMap.get(dep.producer);\n if (!jobId) {\n throw new GithubTargetError(\n `step depends on unknown producer '${dep.producer}'`,\n \"INVALID_GRAPH\",\n );\n }\n needs.add(jobId);\n }\n return [...needs];\n}\n\n/**\n * Map operations to GitHub steps in original order.\n * Consecutive shell/exportOutput operations are combined into one run step.\n */\nfunction lowerOperations(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n config?: GithubTargetConfig,\n): readonly GithubStep[] {\n const steps: GithubStep[] = [];\n const shortStepId = step.id.includes(\"/\")\n ? step.id.split(\"/\").pop()!\n : step.id;\n\n // Every job needs the repository checked out, then toolchain/dependency\n // setup runs before everything else.\n steps.push(checkoutStep(config), ...setupSteps(config));\n\n // F-48: delay → sleep after toolchain setup, before the step's own work.\n applyDelay(steps, step);\n\n // Spec 26: network allowlist annotation (GHA has no native per-job egress control).\n if (step.runtime.network && step.runtime.network.allowed.length > 0) {\n steps.push({\n name: \"Sverka network allowlist\",\n run: `echo \"# sverka:network-allowlist: ${step.runtime.network.allowed.join(\",\")}\"`,\n });\n }\n\n // beforeScript → run steps before main operations.\n if (step.beforeScript) {\n for (const cmd of step.beforeScript) {\n steps.push({ run: cmd });\n }\n }\n\n let runLines: string[] = [];\n let runHasOutput = false;\n // exportStdout ops bind to the most recent shell op's captured stdout.\n // stdoutTargetIndex marks that op's line inside runLines; stdoutNames are\n // the artifact names declared against it; stdoutUploadNames collects every\n // name whose upload-artifact step follows the flushed run step.\n let stdoutTargetIndex: number | undefined;\n let stdoutNames: string[] = [];\n let stdoutUploadNames: string[] = [];\n\n function sealStdoutCapture(): void {\n if (stdoutTargetIndex === undefined || stdoutNames.length === 0) return;\n runLines[stdoutTargetIndex] = wrapStdoutCaptureLine(\n runLines[stdoutTargetIndex]!,\n stdoutNames,\n );\n stdoutUploadNames.push(...stdoutNames);\n stdoutNames = [];\n }\n\n function flushRun(): void {\n sealStdoutCapture();\n if (runLines.length === 0) return;\n const combined = runLines.join(\"\\n\");\n const translated = translateCommand(combined, step.inputs, jobIdMap);\n steps.push({\n // Give the step an id when it contains exportOutput so job-level outputs can reference it.\n ...(runHasOutput ? { id: \"output\" } : {}),\n run: translated,\n ...(step.runtime.workingDir\n ? { workingDirectory: step.runtime.workingDir }\n : {}),\n ...(step.runtime.shell ? { shell: step.runtime.shell } : {}),\n });\n for (const name of stdoutUploadNames) {\n // The runtime persists stdout artifacts even when the shell command\n // fails, so the upload must run unconditionally. The capture writes\n // the file inside the step's working directory when one is set.\n steps.push({\n name: `Upload ${name}`,\n if: \"always()\",\n uses: \"actions/upload-artifact@v7\",\n with: {\n name: artifactName(shortStepId, name),\n path: step.runtime.workingDir\n ? `${step.runtime.workingDir}/${name}`\n : name,\n },\n });\n }\n runLines = [];\n runHasOutput = false;\n stdoutTargetIndex = undefined;\n stdoutUploadNames = [];\n }\n\n for (const op of step.operations) {\n if (op.kind === \"exportOutput\") runHasOutput = true;\n switch (op.kind) {\n case \"shell\":\n // Seal any pending stdout capture before the new command becomes the\n // most recent shell op.\n sealStdoutCapture();\n // F-49: background shell → append & for async execution.\n runLines.push(op.background ? `${op.command} &` : op.command);\n stdoutTargetIndex = runLines.length - 1;\n break;\n case \"exportStdout\":\n if (stdoutTargetIndex === undefined) {\n throw new GithubTargetError(\n `step '${step.id}' declares stdout artifact '${op.name}' but no shell output was captured`,\n \"LOWER_FAILED\",\n );\n }\n if (\n step.runtime.shell !== undefined &&\n !isPosixShell(step.runtime.shell)\n ) {\n throw new GithubTargetError(\n `step '${step.id}' declares stdout artifact '${op.name}' but shell '${step.runtime.shell}' is not POSIX-compatible`,\n \"LOWER_FAILED\",\n );\n }\n stdoutNames.push(op.name);\n break;\n default:\n lowerOperation(op, shortStepId, steps, runLines, flushRun);\n }\n }\n\n flushRun();\n\n // afterScript → run steps after main operations with if: always().\n if (step.afterScript) {\n for (const cmd of step.afterScript) {\n steps.push({ run: cmd, if: \"always()\" });\n }\n }\n\n return steps;\n}\n\n/** Shells whose run scripts understand POSIX syntax (brace groups, `||`, `[ ]`). */\nconst POSIX_SHELLS = new Set([\"sh\", \"bash\", \"dash\", \"ash\", \"zsh\", \"ksh\"]);\n\nfunction isPosixShell(shell: string): boolean {\n const space = shell.indexOf(\" \");\n return POSIX_SHELLS.has(space === -1 ? shell : shell.slice(0, space));\n}\n\nfunction lowerOperation(\n op: OperationDefinition,\n shortStepId: string,\n steps: GithubStep[],\n runLines: string[],\n flushRun: () => void,\n): void {\n switch (op.kind) {\n case \"exportOutput\":\n runLines.push(`echo \"${op.name}=\\${${op.name}}\" >> \"$GITHUB_OUTPUT\"`);\n break;\n case \"exportArtifact\":\n flushRun();\n steps.push({\n name: `Upload ${op.name}`,\n uses: \"actions/upload-artifact@v7\",\n with: {\n name: artifactName(shortStepId, op.name),\n path: op.path,\n ...(op.retention !== undefined\n ? { \"retention-days\": parseRetentionDays(op.retention) }\n : {}),\n },\n });\n break;\n case \"importArtifact\":\n lowerImportArtifact(op, steps, flushRun);\n break;\n case \"diagnostic\":\n lowerDiagnostic(op, steps, flushRun);\n break;\n case \"report\":\n flushRun();\n steps.push(lowerReport(op.spec));\n break;\n case \"release\":\n lowerRelease(op, steps, flushRun);\n break;\n case \"deployPages\":\n lowerDeployPages(op, steps, flushRun);\n break;\n default:\n throw new GithubTargetError(\n `unsupported operation kind: ${JSON.stringify((op as OperationDefinition).kind)}`,\n \"LOWER_FAILED\",\n );\n }\n}\n\n/**\n * Lower a release operation to a GitHub release step.\n * F-39: uses softprops/action-gh-release@v2.\n */\nfunction lowerRelease(\n op: Extract<OperationDefinition, { kind: \"release\" }>,\n steps: GithubStep[],\n flushRun: () => void,\n): void {\n flushRun();\n const withMap: Record<string, unknown> = {\n tag_name: op.tag,\n };\n if (op.name) withMap.name = op.name;\n if (op.description) withMap.body = op.description;\n if (op.assets && op.assets.length > 0) withMap.files = op.assets.join(\"\\n\");\n if (op.draft !== undefined) withMap.draft = op.draft;\n if (op.prerelease !== undefined) withMap.prerelease = op.prerelease;\n steps.push({\n name: `Release ${op.tag}`,\n uses: \"softprops/action-gh-release@v2\",\n with: withMap,\n });\n}\n\n/**\n * Lower a deployPages operation to GitHub Pages deployment steps.\n * F-40: uses actions/upload-pages-artifact + actions/deploy-pages.\n */\nfunction lowerDeployPages(\n op: Extract<OperationDefinition, { kind: \"deployPages\" }>,\n steps: GithubStep[],\n flushRun: () => void,\n): void {\n flushRun();\n // Upload the pages artifact, then deploy.\n steps.push(\n {\n name: \"Upload Pages artifact\",\n uses: \"actions/upload-pages-artifact@v3\",\n with: { path: op.path },\n },\n {\n name: \"Deploy to GitHub Pages\",\n uses: \"actions/deploy-pages@v4\",\n id: \"deployment\",\n },\n );\n}\n\nfunction lowerImportArtifact(\n op: Extract<OperationDefinition, { kind: \"importArtifact\" }>,\n steps: GithubStep[],\n flushRun: () => void,\n): void {\n flushRun();\n const fromShort = op.from.includes(\"/\") ? op.from.split(\"/\").pop()! : op.from;\n steps.push({\n name: `Download ${op.output}`,\n uses: \"actions/download-artifact@v8\",\n with: { name: artifactName(fromShort, op.output), path: op.output },\n });\n}\n\nfunction lowerDiagnostic(\n op: Extract<OperationDefinition, { kind: \"diagnostic\" }>,\n steps: GithubStep[],\n flushRun: () => void,\n): void {\n flushRun();\n const severityFlag = severityFlagFor(op.severity);\n const escapedMessage = op.message\n .replace(/%/g, \"%25\")\n .replace(/\\r\\n/g, \"%0D%0A\")\n .replace(/\\n/g, \"%0A\")\n .replace(/\\r/g, \"%0D\");\n steps.push({\n env: { SVERKA_DIAGNOSTIC_MESSAGE: escapedMessage },\n run: String.raw`printf '%s\\n' \"::${severityFlag}::$SVERKA_DIAGNOSTIC_MESSAGE\"`,\n });\n}\n\n/**\n * Generate a deterministic artifact name from step ID and output name.\n */\nfunction artifactName(stepId: string, outputName: string): string {\n return `${stepId}-${outputName}`;\n}\n\n/**\n * Parse a duration string (e.g., \"7d\", \"1h\", \"30m\", \"never\") into days.\n * Returns undefined for \"never\" (no retention limit).\n */\nfunction parseRetentionDays(retention: string): number | undefined {\n if (retention === \"never\") return undefined;\n const match = /^(\\d+)([dhm])$/.exec(retention);\n if (match === null) return undefined;\n const value = Number.parseInt(match[1]!, 10);\n const unit = match[2];\n if (unit === \"d\") return value;\n if (unit === \"h\") return Math.ceil(value / 24);\n if (unit === \"m\") return Math.ceil(value / (60 * 24));\n return undefined;\n}\n\n/**\n * Lower a report spec to a GitHub action step.\n * Maps report types to known GitHub actions.\n */\nfunction lowerReport(spec: ReportSpec): GithubStep {\n switch (spec.type) {\n case \"junit\":\n return {\n name: `Report ${spec.type}`,\n uses: \"dorny/test-reporter@v1\",\n with: {\n name: \"Tests\",\n path: spec.path,\n reporter: \"java-junit\",\n },\n };\n case \"sarif\":\n case \"sast\":\n return {\n name: `Upload ${spec.type}`,\n uses: \"github/codeql-action/upload-sarif@v3\",\n with: { sarif_file: spec.path },\n };\n default:\n // No standard action — upload as generic artifact\n return {\n name: `Upload ${spec.type} report`,\n uses: \"actions/upload-artifact@v7\",\n with: { name: `${spec.type}-report`, path: spec.path },\n };\n }\n}\n\n/**\n * Collect pipeline-level env vars from inputs.\n * Secret inputs are referenced via `${{ secrets.<name> }}` instead of\n * literal defaults.\n */\nfunction collectEnv(pipeline: PipelineDefinition): Record<string, string> {\n const env: Record<string, string> = {};\n for (const [name, input] of Object.entries(pipeline.inputs)) {\n if (input.secret) {\n env[name] = `\\${{ secrets.${name} }}`;\n } else if (input.default !== undefined) {\n env[name] = String(input.default);\n }\n }\n return env;\n}\n\nfunction severityFlagFor(severity: string): string {\n if (severity === \"error\") return \"error\";\n if (severity === \"warn\") return \"warning\";\n return \"notice\";\n}\n\n// ---------------------------------------------------------------------------\n// Matrix lowering (F-15, F-16)\n// ---------------------------------------------------------------------------\n\n/**\n * Lower a MatrixSpec to a GitHub strategy object.\n * dimensions → matrix variables, include → include:, exclude → exclude:.\n * failFast → fail-fast, maxParallel → max-parallel.\n */\nfunction lowerStrategy(spec: MatrixSpec): {\n readonly matrix: Record<string, unknown>;\n readonly failFast?: boolean;\n readonly maxParallel?: number;\n} {\n const matrix: Record<string, unknown> = {};\n for (const [key, values] of Object.entries(spec.dimensions)) {\n matrix[key] = [...values];\n }\n if (spec.include && spec.include.length > 0) {\n matrix.include = spec.include.map((entry) => ({ ...entry }));\n }\n if (spec.exclude && spec.exclude.length > 0) {\n matrix.exclude = spec.exclude.map((entry) => ({ ...entry }));\n }\n return {\n matrix,\n ...(spec.failFast !== undefined ? { failFast: spec.failFast } : {}),\n ...(spec.maxParallel !== undefined\n ? (() => {\n if (!Number.isInteger(spec.maxParallel) || spec.maxParallel <= 0) {\n throw new GithubTargetError(\n `maxParallel must be a positive integer, got ${spec.maxParallel}`,\n \"INVALID_MATRIX\",\n );\n }\n return { maxParallel: spec.maxParallel };\n })()\n : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Context ref translation (F-35)\n// ---------------------------------------------------------------------------\n\nconst GITHUB_CONTEXT_MAP: Readonly<Record<string, string>> = {\n \"git.sha\": \"github.sha\",\n \"git.branch\": \"github.ref_name\",\n \"git.tag\": \"github.ref_name\",\n \"change.id\": \"github.event.pull_request.number\",\n \"change.source\": \"github.event_name\",\n \"change.target\": \"github.base_ref\",\n \"change.draft\": \"github.event.pull_request.draft\",\n \"event.type\": \"github.event_name\",\n \"run.id\": \"github.run_id\",\n \"run.attempt\": \"github.run_attempt\",\n};\n\n/**\n * Translate a context ref (namespace.field) to GitHub expression syntax.\n * Secrets are sink-specific:\n * - In `with:` inputs (`forWithInput = true`): `${{ secrets.FIELD }}`.\n * GitHub Actions does not expand `$FIELD` in `with:` values — it treats it\n * as a literal string. The `secrets` context is the correct syntax here.\n * - In `run:` commands (`forWithInput = false`): `$FIELD` (env var, avoids\n * exposing secret values in run logs).\n * In conditions, secrets are not supported by GitHub's if: context and are\n * emitted as env var references instead.\n */\nfunction translateContextRef(\n namespace: string,\n field: string,\n inCondition = false,\n forWithInput = false,\n): string {\n const key = `${namespace}.${field}`;\n const mapped = GITHUB_CONTEXT_MAP[key];\n if (mapped) return `\\${{ ${mapped} }}`;\n // env.X → ${{ env.FIELD }} (GitHub env context)\n if (namespace === \"env\") {\n return `\\${{ env.${field} }}`;\n }\n if (namespace === \"matrix\") {\n return `\\${{ matrix.${field} }}`;\n }\n // inputs.X → ${{ env.FIELD }} (pipeline inputs are lowered to workflow env)\n if (namespace === \"inputs\") {\n return `\\${{ env.${field} }}`;\n }\n // secrets.X in with: inputs → ${{ secrets.FIELD }} (GitHub expands the\n // secrets context in with: values, but does NOT expand $FIELD there).\n // secrets.X in commands → $FIELD (env var, avoids exposing value in logs)\n // secrets.X in conditions → not supported by GitHub if: context\n if (namespace === \"secrets\") {\n if (inCondition) {\n // GitHub does not support secrets context in if: expressions.\n // Use env var reference instead (secret is injected as env var).\n return `\\${{ env.${field} }}`;\n }\n if (forWithInput) {\n return `\\${{ secrets.${field} }}`;\n }\n return `$${field}`;\n }\n // Unknown namespace — fail lowering rather than emit invalid expression\n throw new GithubTargetError(\n `unsupported context namespace '${namespace}' in GitHub lowering`,\n \"LOWER_FAILED\",\n );\n}\n\n/**\n * Translate a step ref to GitHub needs.<jobId>.outputs.<output> syntax.\n * Each Sverka step is lowered to a separate GitHub job, so cross-step\n * references must use the 'needs' context, not 'steps'.\n */\nfunction translateStepRef(ref: StepRef, jobIdMap: Map<string, string>): string {\n const jobId = jobIdMap.get(ref.step) ?? ref.step;\n return `\\${{ needs.${jobId}.outputs.${ref.output} }}`;\n}\n\n/**\n * Build a lookup map from placeholder key (\"namespace.field\" or \"step.output\")\n * to the Reference from the step's inputs array.\n */\nfunction buildInputLookup(\n inputs: readonly Reference[],\n): Map<string, Reference> {\n const map = new Map<string, Reference>();\n for (const ref of inputs) {\n if (ref.kind === \"context\") {\n map.set(`${ref.namespace}.${ref.field}`, ref);\n } else if (ref.kind === \"step\") {\n map.set(`${ref.step}.${ref.output}`, ref);\n }\n }\n return map;\n}\n\n/**\n * Translate ${...} placeholders in a command string to GitHub expression syntax.\n * Placeholders matching a known input ref are translated; others are left as-is.\n */\nfunction translateCommand(\n command: string,\n inputs: readonly Reference[],\n jobIdMap: Map<string, string>,\n): string {\n const lookup = buildInputLookup(inputs);\n return command.replace(/\\$\\{([^{}]+)\\}/g, (_, key: string) => {\n const ref = lookup.get(key);\n if (ref === undefined) {\n // Not a known ref — leave as literal shell variable\n return `\\${${key}}`;\n }\n if (ref.kind === \"context\") {\n return translateContextRef(ref.namespace, ref.field, false);\n }\n return translateStepRef(ref, jobIdMap);\n });\n}\n\n/**\n * Lower step rules to a single GitHub `if:` expression.\n * Multiple rules are OR'd with `||`. Rules with `when: never` produce `false`.\n * Rules without an `if` but with `when: always` produce `true`.\n */\nfunction lowerRulesIf(rules: readonly Rule[]): string {\n const parts: string[] = [];\n for (const rule of rules) {\n if (rule.when === \"never\") {\n parts.push(\"${{ false }}\");\n } else if (rule.if !== undefined) {\n parts.push(rule.if);\n } else if (rule.when === \"always\") {\n parts.push(\"${{ true }}\");\n }\n }\n if (parts.length === 0) return \"${{ true }}\";\n if (parts.length === 1) return parts[0]!;\n return parts.map((p) => p.replace(/^\\$\\{\\{|\\}\\}$/g, \"\").trim()).join(\" || \");\n}\n\n/**\n * Lower a step condition to a GitHub if: expression.\n */\nfunction lowerCondition(\n condition: Reference | Expression | StatusCondition,\n jobIdMap: Map<string, string>,\n): string {\n if (condition.kind === \"status\") {\n // GitHub status conditions map to built-in condition functions\n if (condition.status === \"always\") return \"${{ always() }}\";\n if (condition.status === \"never\") return \"${{ false }}\";\n if (condition.status === \"failure\") return \"${{ failure() }}\";\n return \"${{ success() }}\";\n }\n if (condition.kind === \"context\") {\n return `\\${{ ${stripBraces(translateContextRef(condition.namespace, condition.field, true))} }}`;\n }\n if (condition.kind === \"step\") {\n return translateStepRef(condition, jobIdMap);\n }\n // Expression — translate each ${...} placeholder\n const lookup = buildInputLookup(condition.refs);\n const translated = condition.template.replace(\n /\\$\\{([^{}]+)\\}/g,\n (_, key: string) => {\n const ref = lookup.get(key);\n if (ref === undefined) return `\\${${key}}`;\n if (ref.kind === \"context\") {\n return stripBraces(translateContextRef(ref.namespace, ref.field, true));\n }\n return stripBraces(translateStepRef(ref, jobIdMap));\n },\n );\n return `\\${{ ${translated} }}`;\n}\n\n/** Strip the `${{ ... }}` wrapper, returning the inner expression. */\nfunction stripBraces(s: string): string {\n // Match ${{ ... }} and extract inner content, trimming whitespace.\n // Uses anchored pattern without nested quantifiers to avoid ReDoS.\n if (!s.startsWith(\"${{\") || !s.endsWith(\"}}\")) return s;\n return s.slice(3, -2).trim();\n}\n","// Emit: GithubTargetGraph → YAML artifacts.\n// Spec 08 — §19. F-31: multi-workflow emission. Spec 22 — action pinning.\n\nimport { stringify } from \"yaml\";\nimport type {\n GithubTargetGraph,\n GithubJob,\n GithubStep,\n GeneratedArtifact,\n} from \"./types.js\";\n\n/** Optional emit-time transforms (spec 22: action SHA pinning). */\nexport interface EmitOptions {\n /** When set, every emitted `uses:` ref is routed through this function. */\n readonly pinUses?: (ref: string) => string;\n}\n\n/**\n * Emit one or more GithubTargetGraphs as YAML artifacts.\n * Produces one .github/workflows/<name>.yml file per target graph.\n */\nexport function emitGithub(\n targetGraph: GithubTargetGraph | readonly GithubTargetGraph[],\n options?: EmitOptions,\n): readonly GeneratedArtifact[] {\n const graphs = Array.isArray(targetGraph) ? targetGraph : [targetGraph];\n return graphs.map((g) => ({\n path: `.github/workflows/${sanitizeWorkflowName(g.name)}.yml`,\n content: stringifyTargetGraph(g, options),\n }));\n}\n\n/**\n * Sanitize a graph name for use as a workflow filename.\n * GitHub workflow filenames must be valid path segments; replace\n * characters that could break path resolution.\n */\nfunction sanitizeWorkflowName(name: string): string {\n return name.replace(/[^a-zA-Z0-9._-]/g, \"-\");\n}\n\n/**\n * Convert a GithubTargetGraph to a YAML string.\n */\nfunction stringifyTargetGraph(\n graph: GithubTargetGraph,\n options?: EmitOptions,\n): string {\n const doc: Record<string, unknown> = {\n name: graph.name,\n on: graph.on,\n };\n\n if (Object.keys(graph.env).length > 0) {\n doc.env = graph.env;\n }\n\n if (graph.permissions) {\n doc.permissions = graph.permissions;\n }\n\n if (graph.defaults) {\n doc.defaults = graph.defaults;\n }\n\n if (graph.concurrency) {\n doc.concurrency = concurrencyToYaml(graph.concurrency);\n }\n\n const jobs: Record<string, unknown> = {};\n for (const job of graph.jobs) {\n jobs[job.id] = jobToYaml(job, options);\n }\n doc.jobs = jobs;\n\n // GitHub Actions does not support YAML anchors — never alias repeated\n // objects (e.g. identical `with:` maps injected into every job).\n let yaml = stringify(doc, {\n sortMapEntries: false,\n aliasDuplicateObjects: false,\n });\n\n // Pinned refs carry the original tag as a trailing YAML comment\n // (`org/name@<sha> # v4`). The serializer quotes such scalars, which would\n // make GitHub treat the whole string — comment included — as the ref.\n // Unquote `uses:` lines so the ` # ` part stays a real comment.\n yaml = yaml.replaceAll(\n /^(\\s*uses:\\s*)[\"']([^\"']+@[0-9a-f]{40}) # ([^\"']+)[\"']$/gm,\n \"$1$2 # $3\",\n );\n return yaml;\n}\n\n/**\n * Convert a GithubJob to a YAML-compatible object.\n */\nfunction jobToYaml(\n job: GithubJob,\n options?: EmitOptions,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {\n name: job.name,\n };\n\n // Reusable workflow call job: uses/with/secrets (no runs-on/steps).\n if (job.uses) {\n return reusableJobToYaml(job, result, options);\n }\n\n // Normal job.\n result[\"runs-on\"] = job.runsOn;\n\n if (job.needs.length > 0) {\n result.needs = job.needs.length === 1 ? job.needs[0] : [...job.needs];\n }\n\n if (job.timeoutMinutes !== undefined) {\n result[\"timeout-minutes\"] = job.timeoutMinutes;\n }\n\n if (job.container) {\n result.container = job.container;\n }\n\n if (job.env) {\n result.env = job.env;\n }\n\n if (job.strategy) {\n result.strategy = strategyToYaml(job.strategy);\n }\n\n if (job.permissions) {\n result.permissions = job.permissions;\n }\n\n if (job.if) {\n result.if = job.if;\n }\n\n if (job.services) {\n result.services = job.services;\n }\n\n if (job.environment) {\n result.environment = job.environment;\n }\n\n if (job.concurrency) {\n result.concurrency = concurrencyToYaml(job.concurrency);\n }\n\n result.steps = job.steps.map((step, i) => stepToYaml(step, i, options));\n\n return result;\n}\n\n/**\n * Convert a job strategy spec to a YAML-compatible object.\n */\nfunction strategyToYaml(\n strategy: NonNullable<GithubJob[\"strategy\"]>,\n): Record<string, unknown> {\n const strat: Record<string, unknown> = { matrix: strategy.matrix };\n if (strategy.failFast !== undefined) {\n strat[\"fail-fast\"] = strategy.failFast;\n }\n if (strategy.maxParallel !== undefined) {\n strat[\"max-parallel\"] = strategy.maxParallel;\n }\n return strat;\n}\n\n/**\n * Convert a reusable workflow call job (uses) to a YAML-compatible object.\n */\nfunction reusableJobToYaml(\n job: GithubJob,\n result: Record<string, unknown>,\n options?: EmitOptions,\n): Record<string, unknown> {\n result.uses = options?.pinUses ? options.pinUses(job.uses!) : job.uses;\n if (job.needs.length > 0) {\n result.needs = job.needs.length === 1 ? job.needs[0] : [...job.needs];\n }\n if (job.with && Object.keys(job.with).length > 0) {\n result.with = job.with;\n }\n if (job.secrets) {\n result.secrets = job.secrets;\n }\n return result;\n}\n\n/**\n * Convert a concurrency spec to a YAML-compatible object.\n */\nfunction concurrencyToYaml(conc: {\n readonly group: string;\n readonly cancelInProgress?: boolean;\n}): Record<string, unknown> {\n const result: Record<string, unknown> = { group: conc.group };\n if (conc.cancelInProgress !== undefined) {\n result[\"cancel-in-progress\"] = conc.cancelInProgress;\n }\n return result;\n}\n\n/**\n * Convert a GithubStep to a YAML-compatible object.\n */\nfunction stepToYaml(\n step: GithubStep,\n index: number,\n options?: EmitOptions,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n // GitHub steps require a name or uses or run.\n if (step.id) {\n result.id = step.id;\n }\n if (step.name) {\n result.name = step.name;\n } else if (!step.uses && !step.run) {\n result.name = `Step ${index + 1}`;\n }\n\n if (step.uses) {\n result.uses = options?.pinUses ? options.pinUses(step.uses) : step.uses;\n }\n if (step.run) {\n result.run = step.run;\n }\n if (step.with) {\n result.with = step.with;\n }\n if (step.env) {\n result.env = step.env;\n }\n if (step.workingDirectory) {\n result[\"working-directory\"] = step.workingDirectory;\n }\n if (step.shell) {\n result.shell = step.shell;\n }\n\n if (step.if) {\n result.if = step.if;\n }\n\n if (step.continueOnError !== undefined) {\n result[\"continue-on-error\"] = step.continueOnError;\n }\n\n return result;\n}\n","","// GHA action SHA pinning. Spec 22 — §19, §31.3, §26.\n//\n// Pins third-party `uses:` refs to immutable commit SHAs sourced from a\n// bundled registry (no network access at compile time — §31.3). Pinned\n// output embeds the original version as a comment for auditability:\n// `actions/checkout@<sha> # v4`.\n\nimport bundledRegistry from \"./pinned-actions.json\" with { type: \"json\" };\n\n/** Registry mapping `org/name@vN` refs to 40-char commit SHAs. */\nexport interface PinRegistry {\n readonly [ref: string]: string;\n}\n\n/** Pinning configuration for {@link GithubTarget}. */\nexport interface PinningConfig {\n /** `\"strict\"` pins known refs and errors on missing entries; `\"off\"` leaves refs unchanged. */\n readonly mode: \"strict\" | \"off\";\n /** Custom registry; defaults to the bundled `pinned-actions.json`. */\n readonly registry?: PinRegistry;\n}\n\nconst SHA_RE = /^[0-9a-f]{40}$/;\n\n/**\n * Pin a single `uses:` ref to its commit SHA.\n *\n * Rules (spec 22 §\"Data models\"):\n * 1. Local action (`./…`) → unchanged.\n * 2. Already pinned (`@<40 hex>`) → unchanged.\n * 3. `org/name@vN` in registry → `org/name@<sha> # vN`.\n * 4. `org/name@vN` not in registry → unchanged (caller emits a diagnostic).\n *\n * Refs without `@` (malformed) are returned unchanged.\n */\nexport function pinActionRef(ref: string, registry: PinRegistry): string {\n // Rule 1: local action.\n if (ref.startsWith(\"./\")) return ref;\n\n const at = ref.lastIndexOf(\"@\");\n if (at < 0) return ref; // malformed — no @\n\n const head = ref.slice(0, at);\n const tail = ref.slice(at + 1);\n\n // Rule 2: already pinned to a 40-hex SHA.\n if (SHA_RE.test(tail)) return ref;\n\n const sha = registry[ref];\n // Rule 4: not in registry — unchanged.\n if (!sha) return ref;\n\n // Rule 3: pin and embed the version as a comment.\n return `${head}@${sha} # ${tail}`;\n}\n\n/**\n * Load the bundled `pinned-actions.json` registry.\n */\nexport function loadBundledRegistry(): PinRegistry {\n return bundledRegistry as PinRegistry;\n}\n","// GithubTarget — implements the Target contract (§19).\n// Spec 08 — §18.1, §19. Spec 22 — action SHA pinning.\n\nimport type { DefinitionGraph } from \"@sverka/workflow\";\nimport type { CapabilityManifest, Target } from \"../plugin/index.js\";\nimport { analyzeCapabilities } from \"../plugin/index.js\";\nimport { githubCapabilities } from \"./capabilities.js\";\nimport { lowerGithub } from \"./lower.js\";\nimport { emitGithub } from \"./emit.js\";\nimport { pinActionRef, loadBundledRegistry } from \"./pinning.js\";\nimport type { PinRegistry } from \"./pinning.js\";\nimport type {\n GithubTargetGraph,\n GithubTargetConfig,\n GeneratedArtifact,\n TargetDiagnostic,\n CompilationResult,\n GithubJob,\n} from \"./types.js\";\n\nconst SHA_RE = /^[0-9a-f]{40}$/;\n\n/**\n * GitHub Actions target — native lowering from Definition Graph.\n * Implements the Target contract: analyze → lower → emit.\n */\nexport class GithubTarget implements Target {\n readonly name = \"github\";\n readonly capabilities: CapabilityManifest = githubCapabilities;\n\n private readonly pinningMode: \"strict\" | \"off\";\n private readonly pinningRegistry: PinRegistry;\n private readonly config: GithubTargetConfig | undefined;\n\n constructor(config?: GithubTargetConfig) {\n const pinning = config?.pinning;\n this.pinningMode = pinning?.mode ?? \"off\";\n this.pinningRegistry = pinning?.registry ?? loadBundledRegistry();\n this.config = config;\n }\n\n /**\n * Analyze a Definition Graph against the GitHub capability manifest.\n * Returns diagnostics for unsupported or emulated capabilities, plus\n * `unpinned-action` diagnostics (spec 22) for third-party `uses:` refs\n * that are not pinned in the emitted output.\n */\n analyze(graph: DefinitionGraph): readonly TargetDiagnostic[] {\n const capDiags = analyzeCapabilities(graph, [\n this.capabilities,\n ]) as readonly TargetDiagnostic[];\n const targetGraph = this.lower(graph);\n const pinDiags = this.pinningDiagnostics(targetGraph);\n return [...capDiags, ...pinDiags];\n }\n\n /**\n * Lower a Definition Graph to one or more GithubTargetGraphs.\n * Single-pipeline graphs return one target graph; multi-pipeline graphs\n * with reusable workflow calls return one per pipeline.\n */\n lower(\n graph: DefinitionGraph,\n ): GithubTargetGraph | readonly GithubTargetGraph[] {\n return lowerGithub(graph, this.config);\n }\n\n /**\n * Emit one or more GithubTargetGraphs as YAML artifacts.\n * Produces .github/workflows/<name>.yml files. When pinning is on (strict),\n * every `uses:` ref is routed through `pinActionRef`.\n */\n emit(\n targetGraph: GithubTargetGraph | readonly GithubTargetGraph[],\n ): readonly GeneratedArtifact[] {\n const options =\n this.pinningMode === \"strict\"\n ? { pinUses: (ref: string) => pinActionRef(ref, this.pinningRegistry) }\n : undefined;\n return emitGithub(targetGraph, options);\n }\n\n /**\n * Compile a Definition Graph to generated artifacts and diagnostics.\n */\n compile(graph: DefinitionGraph): CompilationResult {\n const targetGraph = this.lower(graph);\n const capDiags = analyzeCapabilities(graph, [\n this.capabilities,\n ]) as readonly TargetDiagnostic[];\n const pinDiags = this.pinningDiagnostics(targetGraph);\n const artifacts = this.emit(targetGraph);\n return { artifacts, diagnostics: [...capDiags, ...pinDiags] };\n }\n\n /**\n * Scan a lowered target graph for third-party `uses:` refs and emit\n * `unpinned-action` diagnostics (spec 22). A ref is \"unpinned\" when it\n * remains on a mutable version tag in the emitted output:\n * - strict mode + missing registry entry → error\n * - off mode + missing registry entry → warning\n * - malformed ref (no `@`) → warning (both modes)\n * Refs in the registry produce no diagnostic (they are pinnable; strict\n * pins them, off leaves them unchanged by choice).\n */\n private pinningDiagnostics(\n targetGraph: GithubTargetGraph | readonly GithubTargetGraph[],\n ): readonly TargetDiagnostic[] {\n const diags: TargetDiagnostic[] = [];\n const graphs = Array.isArray(targetGraph) ? targetGraph : [targetGraph];\n const seen = new Set<string>();\n for (const g of graphs) {\n for (const job of g.jobs) {\n for (const ref of collectUsesRefs(job)) {\n if (seen.has(ref)) continue;\n seen.add(ref);\n const diag = this.diagnosticFor(ref, job.id);\n if (diag) diags.push(diag);\n }\n }\n }\n return diags;\n }\n\n private diagnosticFor(\n ref: string,\n jobId: string,\n ): TargetDiagnostic | undefined {\n // Local actions and already-pinned refs are fine.\n if (ref.startsWith(\"./\")) return undefined;\n const at = ref.lastIndexOf(\"@\");\n if (at < 0) {\n return {\n capability: \"unpinned-action\",\n support: \"unsupported\",\n severity: \"warning\",\n message: `Action ref \"${ref}\" is malformed (no @version) and cannot be pinned.`,\n stepId: jobId,\n };\n }\n const tail = ref.slice(at + 1);\n if (SHA_RE.test(tail)) return undefined; // already pinned\n if (this.pinningRegistry[ref]) return undefined; // pinnable — no diagnostic\n const severity = this.pinningMode === \"strict\" ? \"error\" : \"warning\";\n return {\n capability: \"unpinned-action\",\n support: \"unsupported\",\n severity,\n message: `Action \"${ref}\" is not pinned to a commit SHA (no registry entry).`,\n stepId: jobId,\n };\n }\n}\n\n/** Collect every `uses:` ref from a job (step-level + reusable-job-level). */\nfunction collectUsesRefs(job: GithubJob): readonly string[] {\n const refs: string[] = [];\n if (job.uses) refs.push(job.uses);\n for (const step of job.steps) {\n if (step.uses) refs.push(step.uses);\n }\n return refs;\n}\n\n/**\n * Convenience function: analyze → lower → emit in one call.\n */\nexport function compileGithub(\n graph: DefinitionGraph,\n config?: GithubTargetConfig,\n): CompilationResult {\n return new GithubTarget(config).compile(graph);\n}\n","// GitLab capability manifest. Spec 09 — §24.\nimport type { CapabilityManifest } from \"../plugin/index.js\";\n\nexport const gitlabCapabilities: CapabilityManifest = {\n \"trigger.push\": \"native\",\n \"trigger.changeRequest\": \"native\",\n \"trigger.manual\": \"native\",\n \"runtime.host\": \"native\",\n \"runtime.container\": \"native\",\n \"operation.shell\": \"native\",\n \"operation.import\": \"lowered\",\n \"output.scalar\": \"lowered\",\n \"output.artifact\": \"native\",\n \"graph.dependencies\": \"native\",\n \"graph.conditions\": \"partial\",\n \"graph.matrix\": \"native\",\n \"matrix.include\": \"lowered\",\n \"matrix.exclude\": \"emulated\",\n \"matrix.failFast\": \"unsupported\",\n \"matrix.maxParallel\": \"unsupported\",\n \"trigger.schedule\": \"native\",\n \"step.beforeScript\": \"native\",\n \"step.afterScript\": \"native\",\n \"step.continueOnError\": \"native\",\n \"policy.retry\": \"native\",\n \"policy.compensation\": \"emulated\",\n \"execution.workdir\": \"emulated\",\n \"execution.shell\": \"unsupported\",\n \"environment.variables\": \"native\",\n \"secrets.runtime\": \"native\",\n \"secrets.pipeline-input\": \"native\",\n \"concurrency.interruptible\": \"native\",\n \"environment.permissions\": \"unsupported\",\n \"runner.selection\": \"native\",\n \"runner.group\": \"unsupported\",\n \"secrets.oidc\": \"native\",\n \"secrets.oidc.multiAudience\": \"native\",\n \"workflow.rules\": \"native\",\n \"workflow.rules.changes\": \"native\",\n \"workflow.rules.exists\": \"native\",\n \"workflow.defaults\": \"native\",\n \"workflow.defaults.shell\": \"unsupported\",\n \"workflow.defaults.workdir\": \"unsupported\",\n \"workflow.defaults.env\": \"unsupported\",\n \"workflow.defaults.beforeScript\": \"native\",\n \"workflow.defaults.afterScript\": \"native\",\n \"workflow.defaults.timeout\": \"native\",\n \"workflow.defaults.retry\": \"native\",\n \"workflow.defaults.interruptible\": \"native\",\n \"workflow.inputs\": \"native\",\n \"workflow.inputs.choice\": \"native\",\n \"workflow.inputs.array\": \"native\",\n \"workflow.inputs.pattern\": \"native\",\n \"environment.services\": \"native\",\n \"environment.services.ports\": \"unsupported\",\n \"deployment.environment\": \"native\",\n \"deployment.environment.action\": \"native\",\n \"deployment.environment.tier\": \"native\",\n \"artifact.retention\": \"native\",\n \"artifact.access\": \"native\",\n cache: \"native\",\n \"cache.policy\": \"native\",\n \"cache.fallbackKeys\": \"native\",\n \"concurrency.group\": \"native\",\n \"concurrency.cancelInProgress\": \"unsupported\",\n \"reusable.pipeline\": \"lowered\",\n \"reusable.pipeline.inputs\": \"native\",\n \"reusable.pipeline.outputs\": \"native\",\n \"reusable.component\": \"native\",\n \"reusable.component.versioning\": \"native\",\n \"reusable.childPipeline\": \"native\",\n \"reusable.downstream\": \"native\",\n \"deployment.release\": \"native\",\n \"deployment.pages\": \"native\",\n \"import.gitlab\": \"native\",\n \"import.include\": \"native\",\n \"scheduling.delay\": \"native\",\n \"execution.background\": \"emulated\",\n \"runtime.network\": \"emulated\",\n \"step.permissions\": \"native\",\n \"agent.step\": \"emulated\",\n \"run.query\": \"emulated\",\n};\n","// GitLab target error class. Spec 09.\n\nexport type GitlabTargetErrorCode =\n | \"INVALID_GRAPH\"\n | \"UNSUPPORTED_TRIGGER\"\n | \"LOWER_FAILED\"\n | \"EMIT_FAILED\"\n | \"IMPORT_FAILED\"\n | \"MATRIX_TOO_LARGE\"\n | \"INVALID_MATRIX\";\n\nexport class GitlabTargetError extends Error {\n readonly code: GitlabTargetErrorCode;\n override readonly cause: unknown;\n\n constructor(message: string, code: GitlabTargetErrorCode, cause?: unknown) {\n super(message);\n this.name = \"GitlabTargetError\";\n this.code = code;\n this.cause = cause;\n }\n}\n","// Native lowering: Definition Graph → GitlabTargetGraph.\n// Spec 09 — §18.2, §19.\n\nimport type {\n DefinitionGraph,\n PipelineDefinition,\n StepDefinition,\n EntryDefinition,\n OperationDefinition,\n Dependency,\n Trigger,\n Reference,\n Expression,\n ComponentRef,\n} from \"@sverka/workflow\";\nimport { expandPipelineCalls } from \"@sverka/workflow\";\nimport type {\n MatrixSpec,\n MatrixValue,\n StepRef,\n StatusCondition,\n StepStatus,\n Input,\n ServiceContainer,\n EnvironmentSpec,\n CacheSpec,\n ConcurrencySpec,\n InputLiteral,\n} from \"@sverka/workflow\";\nimport type {\n GitlabTargetGraph,\n GitlabJob,\n GitlabRule,\n GitlabDefault,\n GitlabSpecInput,\n GitlabService,\n GitlabEnvironment,\n GitlabCache,\n GitlabComponentInclude,\n GitlabLocalInclude,\n GitlabTrigger,\n GitlabRelease,\n GitlabPages,\n GitlabWorkflowRule,\n} from \"./types.js\";\nimport { GitlabTargetError } from \"./errors.js\";\nimport { buildJobIdMap } from \"../job-ids.js\";\nimport { shellQuoteSingle, wrapStdoutCaptureLine } from \"../stdout-capture.js\";\n\nconst DOTENV_REPORT_FILE = \"sverka.env\";\n\n/**\n * Lower a Definition Graph to a GitlabTargetGraph.\n * One GitLab job per reachable Step. Stages derived from dependency depth.\n * F-31: pipeline-call steps are inlined as namespaced jobs (v1; include:\n * file-reuse deferred).\n */\nexport function lowerGitlab(graph: DefinitionGraph): GitlabTargetGraph {\n if (graph.project.pipelines.length === 0) {\n throw new GitlabTargetError(\"graph has no pipelines\", \"INVALID_GRAPH\");\n }\n\n // Multi-pipeline: lower each root pipeline (has entries), inlining call steps.\n // Single-pipeline: original behavior (with call expansion if present).\n const rootPipelines = graph.project.pipelines.filter(\n (p) => p.entries.length > 0,\n );\n if (rootPipelines.length === 0) {\n throw new GitlabTargetError(\n \"graph has no root pipelines (with entries)\",\n \"INVALID_GRAPH\",\n );\n }\n\n // For v1, lower the first root pipeline (single .gitlab-ci.yml).\n // Multi-root GitLab is a follow-up. Report dropped roots via console warning.\n if (rootPipelines.length > 1) {\n const dropped = rootPipelines.slice(1).map((p) => p.id);\n console.warn(\n `GitLab lowering: dropping ${dropped.length} additional root pipeline(s): ${dropped.join(\", \")}. Multi-root GitLab support is not yet implemented.`,\n );\n }\n const pipeline = rootPipelines[0]!;\n const reachableSteps = filterReachableSteps(pipeline);\n // Expand pipeline-call steps into inline namespaced jobs.\n const expandedSteps = expandPipelineCalls(graph, reachableSteps);\n\n // Collect component includes (F-32). Component steps become include entries,\n // not jobs. Filter them out of the job-producing step list.\n const includes: GitlabComponentInclude[] = [];\n const stepsForJobs = expandedSteps.filter((step) => {\n if (step.component) {\n includes.push(lowerComponentInclude(step.component));\n return false;\n }\n return true;\n });\n\n const jobIdMap = buildJobIdMap(stepsForJobs);\n\n // Compute stages from topological levels.\n const { stageMap, stages } = computeStages(stepsForJobs, jobIdMap);\n\n // Derive per-job rules from the entries whose closure reaches that job.\n const jobRulesMap = buildJobRulesMap(pipeline, stepsForJobs, jobIdMap);\n\n const jobs = lowerSteps(stepsForJobs, jobIdMap, stageMap, jobRulesMap);\n\n // F-42: lower pipeline rules to workflow rules.\n const workflowRules = lowerWorkflowRules(pipeline);\n\n // F-44: lower pipeline includes to local includes.\n const localIncludes = lowerLocalIncludes(pipeline);\n\n // Apply pipeline-level concurrency to all jobs as resource_group.\n if (pipeline.concurrency !== undefined) {\n const group = pipeline.concurrency.group;\n for (const job of jobs) {\n if (job.resourceGroup === undefined) {\n (job as { resourceGroup?: string }).resourceGroup = group;\n }\n }\n }\n\n // Emit workflow:auto_cancel when any reachable step is interruptible.\n const autoCancel = jobs.some((job) => job.interruptible === true);\n\n return {\n name: pipeline.id,\n stages,\n jobs,\n variables: collectVariables(pipeline),\n ...(autoCancel ? { autoCancel: true } : {}),\n ...(pipeline.defaults !== undefined\n ? { default: lowerDefault(pipeline.defaults) }\n : {}),\n ...(Object.keys(pipeline.inputs).length > 0\n ? { specInputs: lowerSpecInputs(pipeline.inputs) }\n : {}),\n includes,\n ...(localIncludes.length > 0 ? { localIncludes } : {}),\n ...(workflowRules.length > 0 ? { workflowRules } : {}),\n };\n}\n\n/**\n * Lower pipeline inputs to GitLab spec:inputs.\n * choice type → type: string with options.\n */\nfunction lowerSpecInputs(\n inputs: Readonly<Record<string, Input>>,\n): Readonly<Record<string, GitlabSpecInput>> {\n const result: Record<string, GitlabSpecInput> = {};\n for (const [name, input] of Object.entries(inputs)) {\n result[name] = {\n type: input.type === \"choice\" ? \"string\" : input.type,\n ...(input.description !== undefined\n ? { description: input.description }\n : {}),\n // Omit defaults for secret inputs — they must not appear in the YAML.\n ...(input.default !== undefined && !input.secret\n ? { default: input.default }\n : {}),\n ...(input.options !== undefined ? { options: input.options } : {}),\n // GitLab spec:inputs uses `regex`, not `pattern`.\n ...(input.pattern !== undefined ? { regex: input.pattern } : {}),\n };\n }\n return result;\n}\n\n/**\n * Lower pipeline defaults to GitLab default keyword.\n * shell/workdir are not supported by GitLab and are dropped.\n */\nfunction lowerDefault(defaults: {\n beforeScript?: readonly string[];\n afterScript?: readonly string[];\n timeout?: number;\n retry?: { max: number; exitCodes?: readonly number[] };\n interruptible?: boolean;\n}): GitlabDefault {\n return {\n ...(defaults.beforeScript !== undefined\n ? { beforeScript: defaults.beforeScript }\n : {}),\n ...(defaults.afterScript !== undefined\n ? { afterScript: defaults.afterScript }\n : {}),\n ...(defaults.timeout !== undefined\n ? { timeout: `${Math.ceil(defaults.timeout / 60000)}m` }\n : {}),\n ...(defaults.retry !== undefined ? { retry: defaults.retry } : {}),\n ...(defaults.interruptible !== undefined\n ? { interruptible: defaults.interruptible }\n : {}),\n };\n}\n\n/**\n * Lower pipeline-level includes to GitLab local include directives.\n * F-44: includes → include: - local: <path>\n */\nfunction lowerLocalIncludes(\n pipeline: PipelineDefinition,\n): readonly GitlabLocalInclude[] {\n if (!pipeline.includes || pipeline.includes.length === 0) return [];\n return pipeline.includes.map((inc) => ({\n local: inc.path,\n ...(inc.inputs ? { inputs: { ...inc.inputs } } : {}),\n }));\n}\n\n/**\n * Lower pipeline-level rules to GitLab workflow:rules.\n * F-42: direct 1:1 mapping since GitLab has native support.\n */\nfunction lowerWorkflowRules(\n pipeline: PipelineDefinition,\n): readonly GitlabWorkflowRule[] {\n if (!pipeline.rules || pipeline.rules.length === 0) return [];\n return pipeline.rules.map((rule) => ({\n ...(rule.if ? { if: rule.if } : {}),\n ...(rule.changes ? { changes: [...rule.changes] } : {}),\n ...(rule.exists ? { exists: [...rule.exists] } : {}),\n ...(rule.variables ? { variables: { ...rule.variables } } : {}),\n ...(rule.when ? { when: rule.when } : {}),\n }));\n}\n\n/**\n * Lower a ComponentRef to a GitLab CI/CD component include entry.\n */\nfunction lowerComponentInclude(ref: ComponentRef): GitlabComponentInclude {\n const inputs: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(ref.inputs)) {\n if (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n \"kind\" in value\n ) {\n // Reference bindings — GitLab uses variable interpolation.\n const r = value as Reference;\n if (r.kind === \"step\") {\n inputs[name] =\n `$CI_JOB_${r.step.replace(/-/g, \"_\").toUpperCase()}_OUTPUT_${r.output}`;\n } else if (r.kind === \"context\") {\n inputs[name] = `$${r.field.toUpperCase()}`;\n }\n } else {\n inputs[name] = value;\n }\n }\n return {\n component: `${ref.name}@${ref.version}`,\n inputs,\n };\n}\n\n/**\n * Return the ids of all producer steps referenced by a step, including\n * explicit dependencies and artifact imports.\n */\nfunction producerIds(step: StepDefinition): readonly string[] {\n const ids: string[] = [];\n for (const dep of step.dependencies) {\n ids.push(dep.producer);\n }\n for (const op of step.operations) {\n if (op.kind === \"importArtifact\") {\n ids.push(op.from);\n }\n }\n return ids;\n}\n\n/**\n * Compute the set of step IDs reachable from the given roots.\n * Throws INVALID_GRAPH for unknown roots or producers.\n */\nfunction reachableStepIds(\n roots: readonly string[],\n pipeline: PipelineDefinition,\n): Set<string> {\n const byId = new Map(pipeline.steps.map((step) => [step.id, step]));\n const reachable = new Set<string>();\n const queue: string[] = [];\n\n for (const root of roots) {\n if (!byId.has(root)) {\n throw new GitlabTargetError(\n `entry references unknown root step '${root}'`,\n \"INVALID_GRAPH\",\n );\n }\n if (!reachable.has(root)) {\n reachable.add(root);\n queue.push(root);\n }\n }\n\n let head = 0;\n while (head < queue.length) {\n const id = queue[head]!;\n head++;\n const step = byId.get(id);\n if (!step) continue;\n\n for (const producer of producerIds(step)) {\n if (!byId.has(producer)) {\n throw new GitlabTargetError(\n `step '${step.id}' references unknown producer '${producer}'`,\n \"INVALID_GRAPH\",\n );\n }\n if (!reachable.has(producer)) {\n reachable.add(producer);\n queue.push(producer);\n }\n }\n }\n\n return reachable;\n}\n\n/**\n * Return the steps reachable from any entry root by following dependencies\n * and artifact imports.\n */\nfunction filterReachableSteps(\n pipeline: PipelineDefinition,\n): readonly StepDefinition[] {\n if (pipeline.steps.length === 0) {\n for (const entry of pipeline.entries) {\n if (entry.roots.length > 0) {\n throw new GitlabTargetError(\n `entry '${entry.id}' references root steps but pipeline has no steps`,\n \"INVALID_GRAPH\",\n );\n }\n }\n return [];\n }\n\n const allRoots = pipeline.entries.flatMap((entry) => [...entry.roots]);\n const reachable = reachableStepIds(allRoots, pipeline);\n return pipeline.steps.filter((step) => reachable.has(step.id));\n}\n\n/**\n * Build a map from each job ID to the rules of entries that reach that job.\n */\nfunction buildJobRulesMap(\n pipeline: PipelineDefinition,\n reachableSteps: readonly StepDefinition[],\n jobIdMap: ReadonlyMap<string, string>,\n): ReadonlyMap<string, readonly GitlabRule[]> {\n const map = new Map<string, readonly GitlabRule[]>();\n const entryReachable = new Map<string, Set<string>>();\n\n for (const entry of pipeline.entries) {\n entryReachable.set(entry.id, reachableStepIds(entry.roots, pipeline));\n }\n\n for (const step of reachableSteps) {\n const rules: GitlabRule[] = [];\n for (const entry of pipeline.entries) {\n if (entryReachable.get(entry.id)?.has(step.id)) {\n rules.push(...lowerTriggers([entry]));\n }\n }\n const jobId = jobIdMap.get(step.id)!;\n map.set(jobId, rules);\n }\n\n return map;\n}\n\ninterface StageResult {\n readonly stageMap: ReadonlyMap<string, string>;\n readonly stages: readonly string[];\n}\n\n/**\n * Compute stages by topological level.\n * Level 0 → \"build\", Level N → \"stage-N\".\n * Returns stages in dependency order (build first, then stage-1, etc.).\n * Throws when a dependency cycle is detected.\n */\nfunction computeStages(\n steps: readonly StepDefinition[],\n jobIdMap: Map<string, string>,\n): StageResult {\n const depsByJob = buildDepsByJob(steps, jobIdMap);\n const levels = computeAllLevels(steps, jobIdMap, depsByJob);\n return deriveStageResult(levels);\n}\n\nfunction buildDepsByJob(\n steps: readonly StepDefinition[],\n jobIdMap: Map<string, string>,\n): Map<string, string[]> {\n // Build dependency graph using job IDs.\n const depsByJob = new Map<string, string[]>();\n for (const step of steps) {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const deps = producerIds(step).map((id) => jobIdMap.get(id) ?? id);\n depsByJob.set(jobId, deps);\n }\n return depsByJob;\n}\n\nfunction computeAllLevels(\n steps: readonly StepDefinition[],\n jobIdMap: Map<string, string>,\n depsByJob: Map<string, string[]>,\n): Map<string, number> {\n const levels = new Map<string, number>();\n // Compute levels iteratively.\n for (const step of steps) {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const level = computeLevel(jobId, depsByJob, levels, new Set());\n levels.set(jobId, level);\n }\n return levels;\n}\n\nfunction stageNameForLevel(level: number): string {\n return level === 0 ? \"build\" : `stage-${level}`;\n}\n\nfunction deriveStageResult(levels: Map<string, number>): StageResult {\n // Derive ordered stage list from used levels.\n const maxLevel = Math.max(0, ...levels.values());\n const usedLevels = new Set(levels.values());\n const stages: string[] = [];\n for (let level = 0; level <= maxLevel; level++) {\n if (usedLevels.has(level)) {\n stages.push(stageNameForLevel(level));\n }\n }\n // Map job IDs to stage names.\n const stageMap = new Map<string, string>();\n for (const [jobId, level] of levels) {\n stageMap.set(jobId, stageNameForLevel(level));\n }\n return { stageMap, stages };\n}\n\nfunction computeLevel(\n jobId: string,\n depsByJob: Map<string, string[]>,\n levels: Map<string, number>,\n visiting: Set<string>,\n): number {\n if (levels.has(jobId)) return levels.get(jobId)!;\n if (visiting.has(jobId)) {\n throw new GitlabTargetError(\n `dependency cycle detected involving job '${jobId}'`,\n \"LOWER_FAILED\",\n );\n }\n visiting.add(jobId);\n\n const deps = depsByJob.get(jobId) ?? [];\n if (deps.length === 0) {\n visiting.delete(jobId);\n return 0;\n }\n\n let maxDepLevel = 0;\n for (const dep of deps) {\n const depLevel = computeLevel(dep, depsByJob, levels, visiting);\n maxDepLevel = Math.max(maxDepLevel, depLevel);\n }\n\n visiting.delete(jobId);\n return maxDepLevel + 1;\n}\n\n/**\n * Map Sverka triggers to GitLab rules.\n * Branch filters are preserved in the generated `if` expressions.\n */\nfunction lowerTriggers(\n entries: readonly EntryDefinition[],\n): readonly GitlabRule[] {\n const rules: GitlabRule[] = [];\n\n for (const entry of entries) {\n const t = entry.trigger;\n switch (t.kind) {\n case \"push\":\n rules.push(\n buildFilterRule('$CI_PIPELINE_SOURCE == \"push\"', t.filter, false),\n );\n break;\n case \"changeRequest\":\n // For MR triggers, $CI_COMMIT_BRANCH is not populated.\n // Use $CI_MERGE_REQUEST_TARGET_BRANCH_NAME for branch filters.\n rules.push(\n buildFilterRule(\n '$CI_PIPELINE_SOURCE == \"merge_request_event\"',\n t.filter,\n true,\n ),\n );\n break;\n case \"manual\":\n rules.push({ if: '$CI_PIPELINE_SOURCE == \"web\"' });\n break;\n case \"schedule\":\n rules.push({ if: '$CI_PIPELINE_SOURCE == \"schedule\"' });\n break;\n default:\n throw new GitlabTargetError(\n `unsupported trigger kind: ${JSON.stringify((t as Trigger).kind)}`,\n \"UNSUPPORTED_TRIGGER\",\n );\n }\n }\n\n return rules;\n}\n\n/**\n * Build a GitLab rule from a source condition and a trigger filter.\n * For push triggers: branches → $CI_COMMIT_BRANCH, tags → $CI_COMMIT_TAG\n * For MR triggers: branches → $CI_MERGE_REQUEST_TARGET_BRANCH_NAME (target branch)\n * Paths → changes: [paths] on the rule\n */\nfunction buildFilterRule(\n sourceCondition: string,\n filter:\n | {\n readonly branches?: readonly string[];\n readonly tags?: readonly string[];\n readonly paths?: readonly string[];\n }\n | undefined,\n isMergeRequest: boolean,\n): GitlabRule {\n // Source condition (push/MR/web) is always required.\n const conditions: string[] = [sourceCondition];\n\n // Branch and tag filters are OR'd: a push to a matching branch OR a matching tag.\n // For MR triggers, only branch (target) filters apply; tags are not relevant.\n const refConditions: string[] = [];\n if (filter?.branches && filter.branches.length > 0) {\n const branchRef = isMergeRequest\n ? \"$CI_MERGE_REQUEST_TARGET_BRANCH_NAME\"\n : \"$CI_COMMIT_BRANCH\";\n refConditions.push(buildRefCondition(branchRef, filter.branches));\n }\n if (filter?.tags && filter.tags.length > 0 && !isMergeRequest) {\n refConditions.push(buildRefCondition(\"$CI_COMMIT_TAG\", filter.tags));\n }\n if (refConditions.length === 1) {\n conditions.push(refConditions[0]!);\n } else if (refConditions.length > 1) {\n conditions.push(`(${refConditions.join(\" || \")})`);\n }\n\n const rule: GitlabRule = { if: conditions.join(\" && \") };\n if (filter?.paths && filter.paths.length > 0) {\n return { ...rule, changes: [...filter.paths] };\n }\n return rule;\n}\n\nfunction buildRefCondition(ref: string, values: readonly string[]): string {\n if (values.length === 1) {\n return `${ref} == ${quoteJsonString(values[0]!)}`;\n }\n const parts = values.map((v) => `${ref} == ${quoteJsonString(v)}`);\n return `(${parts.join(\" || \")})`;\n}\n\n/**\n * Lower steps to GitLab jobs.\n */\nfunction lowerSteps(\n steps: readonly StepDefinition[],\n jobIdMap: Map<string, string>,\n stageMap: ReadonlyMap<string, string>,\n rulesMap: ReadonlyMap<string, readonly GitlabRule[]>,\n): readonly GitlabJob[] {\n return steps.map((step) => {\n if (step.childPipeline) {\n return lowerChildPipelineStep(step, jobIdMap, stageMap, rulesMap);\n }\n if (step.downstream) {\n return lowerDownstreamStep(step, jobIdMap, stageMap, rulesMap);\n }\n return lowerStep(step, jobIdMap, stageMap, rulesMap);\n });\n}\n\n/**\n * Lower a child pipeline step to a GitLab trigger job.\n * F-33: childPipeline → trigger: include: [{ artifact: <path>, job: <generator> }]\n */\nfunction lowerChildPipelineStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n stageMap: ReadonlyMap<string, string>,\n rulesMap: ReadonlyMap<string, readonly GitlabRule[]>,\n): GitlabJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const stage = stageMap.get(jobId) ?? \"build\";\n const rules = rulesMap.get(jobId) ?? [];\n const needs = step.dependencies\n .filter((d) => d.kind === \"control\")\n .map((d) => jobIdMap.get(d.producer) ?? d.producer);\n const cp = step.childPipeline!;\n const generatorJobId =\n jobIdMap.get(\n `${step.id.split(\"/\").slice(0, -1).join(\"/\")}/${cp.generator}`,\n ) ?? cp.generator;\n const trigger: GitlabTrigger = {\n include: [{ artifact: cp.artifact, job: generatorJobId }],\n };\n return {\n id: jobId,\n stage,\n needs,\n script: [],\n ...(rules.length > 0 ? { rules } : {}),\n trigger,\n };\n}\n\n/**\n * Lower a downstream step to a GitLab multi-project trigger job.\n * F-34: downstream → trigger: project: <project>, branch: <branch>, strategy: depend\n */\nfunction lowerDownstreamStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n stageMap: ReadonlyMap<string, string>,\n rulesMap: ReadonlyMap<string, readonly GitlabRule[]>,\n): GitlabJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const stage = stageMap.get(jobId) ?? \"build\";\n const rules = rulesMap.get(jobId) ?? [];\n const needs = step.dependencies\n .filter((d) => d.kind === \"control\")\n .map((d) => jobIdMap.get(d.producer) ?? d.producer);\n const ds = step.downstream!;\n const trigger: GitlabTrigger = {\n project: ds.project,\n ...(ds.branch ? { branch: ds.branch } : {}),\n strategy: \"depend\",\n };\n // Inputs become variables on the trigger job.\n const variables = lowerDownstreamVariables(ds.inputs);\n return {\n id: jobId,\n stage,\n needs,\n script: [],\n ...(rules.length > 0 ? { rules } : {}),\n trigger,\n ...(Object.keys(variables).length > 0 ? { variables } : {}),\n };\n}\n\n/**\n * Lower downstream step inputs to GitLab trigger variables.\n */\nfunction lowerDownstreamVariables(\n inputs: Readonly<Record<string, Reference | InputLiteral>> | undefined,\n): Record<string, string> {\n const variables: Record<string, string> = {};\n if (!inputs) return variables;\n for (const [name, value] of Object.entries(inputs)) {\n variables[name] = lowerReferenceOrLiteral(value);\n }\n return variables;\n}\n\n/**\n * Lower a reference binding or literal value to a GitLab variable string.\n * Reference bindings use GitLab variable interpolation; literals are stringified.\n */\nfunction lowerReferenceOrLiteral(value: Reference | InputLiteral): string {\n if (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n \"kind\" in value\n ) {\n const r = value as Reference;\n if (r.kind === \"step\") {\n return `$CI_JOB_${r.step.replace(/-/g, \"_\").toUpperCase()}_OUTPUT_${r.output}`;\n }\n if (r.kind === \"context\") {\n return `$${r.field.toUpperCase()}`;\n }\n }\n return String(value);\n}\n\n/**\n * Lower a single Step to a GitLab job.\n */\nfunction lowerStep(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n stageMap: ReadonlyMap<string, string>,\n rulesMap: ReadonlyMap<string, readonly GitlabRule[]>,\n): GitlabJob {\n const jobId = jobIdMap.get(step.id) ?? step.id;\n const stage = stageMap.get(jobId) ?? \"build\";\n const triggerRules = rulesMap.get(jobId) ?? [];\n const mergedRules = mergeRules(triggerRules, step.rules);\n const {\n script,\n artifacts,\n needs: importNeeds,\n variables,\n release,\n pages,\n } = lowerOperations(step, jobId, jobIdMap);\n\n const needs = mergeNeeds(step, jobIdMap, importNeeds);\n\n if (script.length === 0) {\n script.push(\"echo 'no operations'\");\n }\n\n const { image, variables: jobVariables } = lowerRuntime(step, variables);\n const rules = applyStepCondition(mergedRules, step, jobIdMap);\n const writeVariables = lowerWriteVariables(step);\n\n return {\n id: jobId,\n stage,\n needs,\n script,\n ...buildJobFields({\n image,\n artifacts,\n variables: { ...jobVariables, ...writeVariables },\n rules,\n timeout: step.timeout,\n interruptible: step.interruptible,\n runner: step.runner,\n identity: step.identity,\n services: step.services,\n environment: step.environment,\n cache: step.cache,\n concurrency: step.concurrency,\n }),\n ...(step.matrix !== undefined\n ? { parallel: { matrix: lowerGitlabMatrix(step.matrix) } }\n : {}),\n ...(step.beforeScript ? { beforeScript: step.beforeScript } : {}),\n ...(step.afterScript ? { afterScript: step.afterScript } : {}),\n ...resolveContinueOnError(step),\n ...resolveRetryConfig(step),\n ...(release ? { release } : {}),\n ...(pages ? { pages } : {}),\n ...(step.delay ? { when: \"delayed\" as const, start_in: step.delay } : {}),\n };\n}\n\n/**\n * If the step has a condition, apply it to the merged rules.\n *\n * Status conditions (success/failure/always/never) map to GitLab `when`\n * values, not `if:` expressions. GitLab's `if:` does not have equivalents for\n * `on_success`/`on_failure` — those are `when` semantics. Emitting empty `if:`\n * strings (as the previous code did for success/failure) produces invalid YAML.\n *\n * Step-output conditions reference dotenv variables from a producer job's\n * artifacts. GitLab evaluates all job rules during pipeline creation, before\n * any job runs — so dotenv variables are not available at that point. Reject\n * step-output conditions with an error until runtime-safe handling exists.\n *\n * Context and expression conditions are AND'd with each rule's `if` expression.\n * GitLab evaluates rules in order and stops at the first match, so appending\n * the condition as a separate rule would bypass it when a trigger rule matches.\n */\nfunction applyStepCondition(\n mergedRules: readonly GitlabRule[],\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n): readonly GitlabRule[] {\n if (step.condition === undefined) return mergedRules;\n\n // Status conditions → map to GitLab rules `when` values.\n if (step.condition.kind === \"status\") {\n const when = statusToGitlabWhen(step.condition.status);\n if (mergedRules.length === 0) {\n return [{ when }];\n }\n return mergedRules.map((rule) => ({ ...rule, when }));\n }\n\n // Step-output conditions → reject. Producer outputs are dotenv variables\n // that GitLab cannot evaluate during pipeline creation (when rules are\n // evaluated). Runtime-safe handling does not yet exist.\n if (step.condition.kind === \"step\") {\n throw new GitlabTargetError(\n `step '${step.id}' has a step-output condition (${step.condition.step}.${step.condition.output}), which GitLab cannot evaluate during pipeline creation — dotenv variables from producer jobs are not available when rules are evaluated`,\n \"LOWER_FAILED\",\n );\n }\n\n // Context and expression conditions → AND with each rule's if expression.\n const condExpr = lowerGitlabConditionExpr(step.condition, jobIdMap);\n let rules = mergedRules.map((rule) => {\n if (condExpr === undefined) return rule;\n const ifExpr =\n rule.if !== undefined ? `(${rule.if}) && (${condExpr})` : condExpr;\n return { ...rule, if: ifExpr };\n });\n if (rules.length === 0 && condExpr !== undefined) {\n rules = [{ if: condExpr }];\n }\n return rules;\n}\n\n/**\n * Map a Sverka step status condition to a GitLab rules `when` value.\n * - success → on_success (run only if all parent jobs succeed — GitLab default)\n * - failure → on_failure (run only if at least one parent job fails)\n * - always → always\n * - never → never\n */\nfunction statusToGitlabWhen(status: StepStatus): string {\n switch (status) {\n case \"always\":\n return \"always\";\n case \"never\":\n return \"never\";\n case \"success\":\n return \"on_success\";\n case \"failure\":\n return \"on_failure\";\n }\n}\n\n/** Resolve continueOnError to GitLab allowFailure field. */\nfunction resolveContinueOnError(step: StepDefinition): Partial<GitlabJob> {\n if (step.continueOnError === undefined) return {};\n return {\n allowFailure:\n typeof step.continueOnError === \"boolean\"\n ? step.continueOnError\n : { exitCodes: step.continueOnError.exitCodes },\n };\n}\n\n/** Resolve retry configuration to GitLab retry field. */\nfunction resolveRetryConfig(step: StepDefinition): Partial<GitlabJob> {\n if (step.retry === undefined) return {};\n return {\n retry: {\n max: step.retry.max,\n ...(step.retry.when ? { when: step.retry.when } : {}),\n ...(step.retry.exitCodes ? { exitCodes: step.retry.exitCodes } : {}),\n },\n };\n}\n\nfunction mergeNeeds(\n step: StepDefinition,\n jobIdMap: Map<string, string>,\n importNeeds: readonly string[],\n): string[] {\n // Merge explicit scheduling dependencies with artifact-import dependencies.\n return [\n ...new Set([\n ...lowerDependencies(step.dependencies, jobIdMap),\n ...importNeeds,\n ]),\n ];\n}\n\nfunction lowerRuntime(\n step: StepDefinition,\n baseVariables: Record<string, string>,\n): { image?: string; variables: Record<string, string> } {\n const runtime = step.runtime;\n const mode = runtime.mode ?? \"host\";\n\n if (mode === \"container\" && !runtime.image) {\n throw new GitlabTargetError(\n `step '${step.id}' uses container mode without an image`,\n \"LOWER_FAILED\",\n );\n }\n const image = mode === \"container\" ? runtime.image : undefined;\n\n const variables: Record<string, string> = { ...baseVariables };\n if (runtime.env) {\n Object.assign(variables, runtime.env);\n }\n if (runtime.secrets) {\n for (const secret of runtime.secrets) {\n variables[secret] = `$${secret}`;\n }\n }\n // Spec 26: network allowlist annotation (GitLab has no native per-job egress control).\n if (runtime.network && runtime.network.allowed.length > 0) {\n variables[\"SVERKA_NETWORK_ALLOWLIST\"] = runtime.network.allowed.join(\",\");\n }\n\n return { ...(image ? { image } : {}), variables };\n}\n\n/**\n * Safe-outputs (Spec 25): GitLab has no per-job permission block.\n * Steps with declared writes receive CI variables corresponding to their\n * declared write kinds (e.g. SV_WRITE_DEPLOY=true). Steps without writes\n * receive no SV_WRITE_* variables.\n */\nfunction lowerWriteVariables(step: StepDefinition): Record<string, string> {\n const writes = step.permissions?.write;\n if (!writes || writes.length === 0) return {};\n const vars: Record<string, string> = {};\n for (const decl of writes) {\n const varName = `SV_WRITE_${decl.kind.toUpperCase().replace(/-/g, \"_\")}`;\n vars[varName] = \"true\";\n }\n return vars;\n}\n\ninterface JobFieldContext {\n image: string | undefined;\n artifacts:\n | {\n paths?: string[];\n reports?: Record<string, unknown>;\n expireIn?: string;\n access?: string;\n when?: string;\n }\n | undefined;\n variables: Record<string, string>;\n rules: readonly GitlabRule[];\n timeout: number | undefined;\n interruptible: boolean | undefined;\n runner: { labels: readonly string[]; group?: string } | undefined;\n identity:\n { tokens: Readonly<Record<string, { audience: string }>> } | undefined;\n services: readonly ServiceContainer[] | undefined;\n environment: EnvironmentSpec | undefined;\n cache: CacheSpec | undefined;\n concurrency: ConcurrencySpec | undefined;\n}\n\n/** Build core job fields: image, artifacts, variables, rules. */\nfunction buildJobCoreFields(ctx: JobFieldContext): Partial<GitlabJob> {\n return {\n ...(ctx.image ? { image: ctx.image } : {}),\n ...(ctx.artifacts ? { artifacts: ctx.artifacts } : {}),\n ...(Object.keys(ctx.variables).length > 0\n ? { variables: ctx.variables }\n : {}),\n ...(ctx.rules.length > 0 ? { rules: ctx.rules } : {}),\n };\n}\n\n/** Build runtime/execution fields: timeout, interruptible, runner tags, id_tokens. */\nfunction buildJobRuntimeFields(ctx: JobFieldContext): Partial<GitlabJob> {\n return {\n ...(ctx.timeout !== undefined\n ? { timeout: `${Math.ceil(ctx.timeout / 60000)}m` }\n : {}),\n ...(ctx.interruptible !== undefined\n ? { interruptible: ctx.interruptible }\n : {}),\n ...(ctx.runner !== undefined ? { tags: ctx.runner.labels } : {}),\n ...lowerIdTokens(ctx.identity),\n };\n}\n\n/** Build environment-related fields: services, environment, cache, concurrency. */\nfunction buildJobEnvFields(ctx: JobFieldContext): Partial<GitlabJob> {\n return {\n ...(ctx.services !== undefined && ctx.services.length > 0\n ? { services: lowerGitlabServices(ctx.services) }\n : {}),\n ...(ctx.environment !== undefined\n ? { environment: lowerGitlabEnvironment(ctx.environment) }\n : {}),\n ...(ctx.cache !== undefined ? { cache: lowerGitlabCache(ctx.cache) } : {}),\n ...(ctx.concurrency !== undefined\n ? { resourceGroup: ctx.concurrency.group }\n : {}),\n };\n}\n\nfunction buildJobFields(ctx: JobFieldContext): Partial<GitlabJob> {\n return {\n ...buildJobCoreFields(ctx),\n ...buildJobRuntimeFields(ctx),\n ...buildJobEnvFields(ctx),\n };\n}\n\n/** Lower identity tokens to GitLab id_tokens field. */\nfunction lowerIdTokens(\n identity: JobFieldContext[\"identity\"],\n): Partial<Pick<GitlabJob, \"idTokens\">> {\n if (identity === undefined) return {};\n const idTokens: Record<string, { aud: string }> = {};\n for (const [name, spec] of Object.entries(identity.tokens)) {\n idTokens[name] = { aud: spec.audience };\n }\n return Object.keys(idTokens).length > 0 ? { idTokens } : {};\n}\n\n/**\n * Lower cache spec to GitLab cache keyword.\n */\nfunction lowerGitlabCache(cache: CacheSpec): GitlabCache {\n return {\n paths: cache.paths,\n key: cache.key,\n ...(cache.policy !== undefined ? { policy: cache.policy } : {}),\n ...(cache.restoreKeys !== undefined\n ? { fallbackKeys: cache.restoreKeys }\n : {}),\n };\n}\n\n/**\n * Lower environment spec to GitLab environment map.\n */\nfunction lowerGitlabEnvironment(env: EnvironmentSpec): GitlabEnvironment {\n return {\n name: env.name,\n ...(env.url !== undefined ? { url: env.url } : {}),\n ...(env.action !== undefined ? { action: env.action } : {}),\n ...(env.tier !== undefined ? { deploymentTier: env.tier } : {}),\n };\n}\n\n/**\n * Lower service containers to GitLab services array.\n * ports are not supported by GitLab and are dropped.\n */\nfunction lowerGitlabServices(\n services: readonly ServiceContainer[],\n): readonly GitlabService[] {\n return services.map((svc) => ({\n name: svc.image,\n // Fall back to the portable service name so scripts can reach it by its declared name.\n alias: svc.alias ?? svc.name,\n ...(svc.entrypoint !== undefined\n ? { entrypoint: [...svc.entrypoint] }\n : {}),\n ...(svc.command !== undefined ? { command: [...svc.command] } : {}),\n ...(svc.env !== undefined ? { variables: { ...svc.env } } : {}),\n }));\n}\n\n/**\n * Merge trigger-derived rules with step-level rules.\n * Step-level rules are appended after trigger rules.\n */\nfunction mergeRules(\n triggerRules: readonly GitlabRule[],\n stepRules:\n | readonly {\n if?: string;\n changes?: readonly string[];\n exists?: readonly string[];\n when?: string;\n variables?: Readonly<Record<string, string>>;\n }[]\n | undefined,\n): readonly GitlabRule[] {\n if (stepRules === undefined || stepRules.length === 0) {\n return triggerRules;\n }\n const result: GitlabRule[] = [...triggerRules];\n for (const rule of stepRules) {\n const gitlabRule: GitlabRule = {\n ...(rule.if !== undefined ? { if: rule.if } : {}),\n ...(rule.when !== undefined ? { when: rule.when } : {}),\n ...(rule.changes !== undefined ? { changes: rule.changes } : {}),\n ...(rule.exists !== undefined ? { exists: rule.exists } : {}),\n ...(rule.variables !== undefined ? { variables: rule.variables } : {}),\n };\n result.push(gitlabRule);\n }\n return result;\n}\n\n/**\n * Map dependencies to job needs.\n */\nfunction lowerDependencies(\n deps: readonly Dependency[],\n jobIdMap: Map<string, string>,\n): readonly string[] {\n const needs = new Set<string>();\n for (const dep of deps) {\n const jobId = jobIdMap.get(dep.producer) ?? dep.producer;\n needs.add(jobId);\n }\n return [...needs];\n}\n\n/**\n * Mutable accumulator for lowering operations.\n */\ninterface OperationAccumulator {\n readonly script: string[];\n readonly artifactPaths: string[];\n readonly importNeeds: string[];\n readonly reportEntries: Record<string, unknown>;\n readonly inputs: readonly Reference[];\n hasDotenv: boolean;\n artifactRetention: string | undefined;\n artifactAccess: string | undefined;\n release: GitlabRelease | undefined;\n pages: GitlabPages | undefined;\n // exportStdout ops bind to the most recent shell op's captured stdout.\n // stdoutTargetIndex marks that op's entry inside script; stdoutNames are\n // the artifact names declared against it; stdoutArtifacts flips\n // artifacts:when to \"always\" because the runtime writes the file even on\n // step failure.\n stdoutTargetIndex: number | undefined;\n stdoutNames: string[];\n stdoutArtifacts: boolean;\n readonly workingDir: string | undefined;\n}\n\n/**\n * Map operations to script entries, artifacts, and dependencies.\n * Scalar outputs are written to a dotenv report file.\n */\nfunction lowerOperations(\n step: StepDefinition,\n jobId: string,\n jobIdMap: Map<string, string>,\n): {\n script: string[];\n artifacts?: {\n paths?: string[];\n reports?: Record<string, unknown>;\n expireIn?: string;\n access?: string;\n when?: string;\n };\n needs: string[];\n variables: Record<string, string>;\n release?: GitlabRelease;\n pages?: GitlabPages;\n} {\n const acc: OperationAccumulator = {\n script: [],\n artifactPaths: [],\n importNeeds: [],\n reportEntries: {},\n inputs: step.inputs,\n hasDotenv: false,\n artifactRetention: undefined,\n artifactAccess: undefined,\n release: undefined,\n pages: undefined,\n stdoutTargetIndex: undefined,\n stdoutNames: [],\n stdoutArtifacts: false,\n workingDir: step.runtime.workingDir,\n };\n\n for (const op of step.operations) {\n lowerOperation(op, jobId, acc, jobIdMap);\n }\n\n return assembleOperationResult(acc, step);\n}\n\n/**\n * Lower a shell operation, handling background execution.\n */\nfunction lowerShellOp(\n op: Extract<OperationDefinition, { kind: \"shell\" }>,\n acc: OperationAccumulator,\n jobIdMap: Map<string, string>,\n): void {\n // Seal any pending stdout capture before the new command becomes the most\n // recent shell op.\n sealStdoutCapture(acc);\n const translated = translateGitlabCommand(op.command, acc.inputs, jobIdMap);\n // F-49: background shell → append & for async execution.\n acc.script.push(op.background ? `${translated} &` : translated);\n acc.stdoutTargetIndex = acc.script.length - 1;\n}\n\n/**\n * Bind the pending stdout artifact names to the most recent shell op: wrap\n * that op's script line so its stdout is also written to the declared file(s)\n * and record the files as job artifacts.\n */\nfunction sealStdoutCapture(acc: OperationAccumulator): void {\n if (acc.stdoutTargetIndex === undefined || acc.stdoutNames.length === 0) {\n return;\n }\n acc.script[acc.stdoutTargetIndex] = wrapStdoutCaptureLine(\n acc.script[acc.stdoutTargetIndex]!,\n acc.stdoutNames,\n );\n // The capture writes the file inside the step's working directory when one\n // is set (the script cds there first); artifacts:paths is repo-relative.\n acc.artifactPaths.push(\n ...acc.stdoutNames.map((name) =>\n acc.workingDir ? `${acc.workingDir}/${name}` : name,\n ),\n );\n acc.stdoutArtifacts = true;\n acc.stdoutNames = [];\n}\n\n/**\n * Lower a single operation, mutating the accumulator.\n */\nfunction lowerOperation(\n op: OperationDefinition,\n stepId: string,\n acc: OperationAccumulator,\n jobIdMap: Map<string, string>,\n): void {\n switch (op.kind) {\n case \"shell\":\n lowerShellOp(op, acc, jobIdMap);\n break;\n case \"exportOutput\":\n lowerExportOutput(op, stepId, acc);\n break;\n case \"exportArtifact\":\n lowerExportArtifact(op, acc);\n break;\n case \"exportStdout\":\n if (acc.stdoutTargetIndex === undefined) {\n throw new GitlabTargetError(\n `step '${stepId}' declares stdout artifact '${op.name}' but no shell output was captured`,\n \"LOWER_FAILED\",\n );\n }\n acc.stdoutNames.push(op.name);\n break;\n case \"importArtifact\":\n acc.importNeeds.push(jobIdMap.get(op.from) ?? op.from);\n break;\n case \"diagnostic\":\n acc.script.push(`echo ${shellQuoteSingle(op.message)}`);\n break;\n case \"report\":\n lowerReport(op, acc);\n break;\n case \"release\":\n acc.release = lowerReleaseOp(op);\n break;\n case \"deployPages\":\n lowerDeployPages(op, acc);\n break;\n default:\n throw new GitlabTargetError(\n `unsupported operation kind: ${JSON.stringify((op as OperationDefinition).kind)}`,\n \"LOWER_FAILED\",\n );\n }\n}\n\n/**\n * Lower an exportOutput operation into a dotenv echo line.\n */\nfunction lowerExportOutput(\n op: Extract<OperationDefinition, { kind: \"exportOutput\" }>,\n stepId: string,\n acc: OperationAccumulator,\n): void {\n const key = `${stepId}_${op.name}`;\n const name = shellEscapeDoubleQuoted(key);\n acc.script.push(`echo \"${name}=\\${${op.name}}\" >> ${DOTENV_REPORT_FILE}`);\n acc.hasDotenv = true;\n}\n\n/**\n * Lower an exportArtifact operation, recording paths and retention metadata.\n */\nfunction lowerExportArtifact(\n op: Extract<OperationDefinition, { kind: \"exportArtifact\" }>,\n acc: OperationAccumulator,\n): void {\n acc.artifactPaths.push(op.path);\n if (op.retention !== undefined) acc.artifactRetention = op.retention;\n if (op.access !== undefined) acc.artifactAccess = op.access;\n}\n\n/**\n * Lower a report operation into a GitLab artifacts:reports entry.\n */\nfunction lowerReport(\n op: Extract<OperationDefinition, { kind: \"report\" }>,\n acc: OperationAccumulator,\n): void {\n const key = gitlabReportKey(op.spec.type);\n if (op.spec.type === \"coverage\") {\n acc.reportEntries[key] = {\n coverage_format: op.spec.format ?? \"cobertura\",\n path: op.spec.path,\n };\n } else {\n acc.reportEntries[key] = op.spec.path;\n }\n}\n\n/**\n * Lower a release operation to a GitLab release keyword.\n * Assets are file paths → emit as links with placeholder URLs\n * (GitLab requires URLs, not file paths).\n */\nfunction lowerReleaseOp(\n op: Extract<OperationDefinition, { kind: \"release\" }>,\n): GitlabRelease {\n const links = (op.assets ?? []).map((path) => ({\n name: path.split(\"/\").pop() ?? path,\n // Use GitLab CI job artifact URL variables so links resolve to the actual artifact.\n url: `$CI_PROJECT_URL/-/jobs/$CI_JOB_ID/artifacts/file/${path}`,\n }));\n return {\n tag_name: op.tag,\n ...(op.name ? { name: op.name } : {}),\n ...(op.description ? { description: op.description } : {}),\n ...(links.length > 0 ? { assets: { links } } : {}),\n ...(op.draft !== undefined ? { draft: op.draft } : {}),\n };\n}\n\n/**\n * Lower a deployPages operation to a GitLab pages keyword.\n * GitLab 17.6+ accepts any job name when the job sets the `pages` keyword.\n * The path is also added as an artifact.\n */\nfunction lowerDeployPages(\n op: Extract<OperationDefinition, { kind: \"deployPages\" }>,\n acc: OperationAccumulator,\n): void {\n acc.pages = {\n publish: op.path,\n ...(op.prefix ? { path_prefix: op.prefix } : {}),\n };\n // GitLab pages requires the path as an artifact.\n acc.artifactPaths.push(op.path);\n}\n\n/**\n * Assemble the final lowerOperations result from the accumulator.\n */\nfunction assembleOperationResult(\n acc: OperationAccumulator,\n step: StepDefinition,\n): {\n script: string[];\n artifacts?: {\n paths?: string[];\n reports?: Record<string, unknown>;\n expireIn?: string;\n access?: string;\n when?: string;\n };\n needs: string[];\n variables: Record<string, string>;\n release?: GitlabRelease;\n pages?: GitlabPages;\n} {\n sealStdoutCapture(acc);\n const artifacts: {\n paths?: string[];\n reports?: Record<string, unknown>;\n expireIn?: string;\n access?: string;\n when?: string;\n } = {};\n if (acc.artifactPaths.length > 0) {\n artifacts.paths = acc.artifactPaths;\n }\n if (acc.stdoutArtifacts) {\n // Stdout artifacts are written even when the shell command fails, so\n // the upload must not be limited to on_success.\n artifacts.when = \"always\";\n }\n if (acc.hasDotenv) {\n acc.reportEntries.dotenv = DOTENV_REPORT_FILE;\n }\n if (Object.keys(acc.reportEntries).length > 0) {\n artifacts.reports = acc.reportEntries;\n }\n if (acc.artifactRetention !== undefined) {\n artifacts.expireIn = parseGitlabExpireIn(acc.artifactRetention);\n }\n if (acc.artifactAccess !== undefined) {\n artifacts.access = acc.artifactAccess;\n }\n\n if (step.runtime.workingDir && acc.script.length > 0) {\n // Shell-quote the directory to prevent injection and handle spaces\n const escapedDir = shellQuoteSingle(step.runtime.workingDir);\n acc.script.unshift(`cd ${escapedDir}`);\n }\n\n return {\n script: acc.script,\n ...(Object.keys(artifacts).length > 0 ? { artifacts } : {}),\n needs: acc.importNeeds,\n variables: {},\n ...(acc.release ? { release: acc.release } : {}),\n ...(acc.pages ? { pages: acc.pages } : {}),\n };\n}\n\n/**\n * Convert Sverka retention duration to GitLab expire_in format.\n * \"7d\" → \"7 days\", \"1h\" → \"1 hours\", \"30m\" → \"30 minutes\", \"never\" → \"never\".\n */\nfunction parseGitlabExpireIn(retention: string): string {\n if (retention === \"never\") return \"never\";\n const match = /^(\\d+)([dhm])$/.exec(retention);\n if (match === null) return retention;\n const value = match[1]!;\n const unit = match[2];\n if (unit === \"d\") return `${value} days`;\n if (unit === \"h\") return `${value} hours`;\n if (unit === \"m\") return `${value} minutes`;\n return retention;\n}\n\n/**\n * Map Sverka report type to GitLab artifacts:reports key.\n */\nfunction gitlabReportKey(type: string): string {\n const map: Record<string, string> = {\n junit: \"junit\",\n coverage: \"coverage_report\",\n dotenv: \"dotenv\",\n sast: \"sast\",\n dast: \"dast\",\n dependencyScanning: \"dependency_scanning\",\n containerScanning: \"container_scanning\",\n licenseScanning: \"license_scanning\",\n performance: \"performance\",\n metrics: \"metrics\",\n terraform: \"terraform\",\n quality: \"quality\",\n sarif: \"sast\",\n };\n return map[type] ?? type;\n}\n\n/**\n * Produce a deterministic JSON string literal (quoted) for a value.\n */\nfunction quoteJsonString(value: string): string {\n return `\"${value.replace(/[\\\\\"\\n\\r\\t\\b\\f\\u0000-\\u001f]/g, (ch) => {\n const mapped = JSON_STRING_ESCAPES[ch];\n return mapped ?? `\\\\u${ch.charCodeAt(0).toString(16).padStart(4, \"0\")}`;\n })}\"`;\n}\n\nconst JSON_STRING_ESCAPES: Readonly<Record<string, string>> = {\n '\"': '\\\\\"',\n \"\\\\\": \"\\\\\\\\\",\n \"\\n\": \"\\\\n\",\n \"\\r\": \"\\\\r\",\n \"\\t\": \"\\\\t\",\n \"\\b\": \"\\\\b\",\n \"\\f\": \"\\\\f\",\n};\n\n/**\n * Escape a string for use inside double quotes in a POSIX shell.\n */\nfunction shellEscapeDoubleQuoted(value: string): string {\n return value.replace(/[\\\\\"`$]/g, \"\\\\$&\");\n}\n\n/**\n * Collect pipeline-level variables from inputs.\n * Secret inputs are omitted from the generated variables block.\n */\nfunction collectVariables(\n pipeline: PipelineDefinition,\n): Record<string, string> {\n const vars: Record<string, string> = {};\n for (const [name, input] of Object.entries(pipeline.inputs)) {\n if (input.secret) {\n continue;\n }\n if (input.default !== undefined) {\n vars[name] = String(input.default);\n }\n }\n return vars;\n}\n\n// ---------------------------------------------------------------------------\n// Matrix lowering (F-15)\n// ---------------------------------------------------------------------------\n\ntype MatrixCombination = Record<string, MatrixValue>;\n\n/**\n * Lower a MatrixSpec to a GitLab parallel:matrix array.\n * GitLab has no native include/exclude — exclude is emulated by filtering\n * combinations at synthesis time, include is appended to the array.\n */\nfunction lowerGitlabMatrix(\n spec: MatrixSpec,\n): readonly Record<string, unknown>[] {\n validateMatrixKeys(spec);\n const combinations = computeMatrixCombinations(\n spec.dimensions,\n spec.exclude ?? [],\n );\n const totalRows = combinations.length + (spec.include?.length ?? 0);\n if (totalRows > 200) {\n throw new GitlabTargetError(\n `GitLab matrix has ${totalRows} rows, exceeding the 200-row limit`,\n \"MATRIX_TOO_LARGE\",\n );\n }\n const includeEntries = (spec.include ?? []).map((entry) => ({ ...entry }));\n return [...combinations.map((c) => ({ ...c })), ...includeEntries];\n}\n\n/**\n * Validate that matrix dimension and include keys contain only valid\n * GitLab variable name characters: letters, digits, underscores.\n */\nfunction validateMatrixKeys(spec: MatrixSpec): void {\n const validKey = /^[A-Za-z_]\\w*$/;\n for (const key of Object.keys(spec.dimensions)) {\n if (!validKey.test(key)) {\n throw new GitlabTargetError(\n String.raw`invalid matrix dimension key '${key}': must match [A-Za-z_]\\w*`,\n \"INVALID_MATRIX\",\n );\n }\n }\n if (spec.include) {\n for (const entry of spec.include) {\n for (const key of Object.keys(entry)) {\n if (!validKey.test(key)) {\n throw new GitlabTargetError(\n String.raw`invalid matrix include key '${key}': must match [A-Za-z_]\\w*`,\n \"INVALID_MATRIX\",\n );\n }\n }\n }\n }\n}\n\n/**\n * Compute the cross-product of matrix dimensions, then filter out\n * combinations matching any exclude rule (partial match).\n */\nfunction computeMatrixCombinations(\n dimensions: Readonly<Record<string, readonly MatrixValue[]>>,\n exclude: readonly Readonly<Record<string, MatrixValue>>[],\n): readonly MatrixCombination[] {\n const keys = Object.keys(dimensions);\n if (keys.length === 0) return [];\n\n let combinations: MatrixCombination[] = [{}];\n for (const key of keys) {\n const values = dimensions[key];\n if (!values || values.length === 0) continue;\n const next: MatrixCombination[] = [];\n for (const combo of combinations) {\n for (const v of values) {\n next.push({ ...combo, [key]: v });\n }\n }\n combinations = next;\n }\n\n if (exclude.length === 0) return combinations;\n return combinations.filter((combo) => !matchesAny(combo, exclude));\n}\n\n/**\n * Check if a combination matches any exclude rule (partial match).\n */\nfunction matchesAny(\n combo: MatrixCombination,\n rules: readonly Readonly<Record<string, MatrixValue>>[],\n): boolean {\n for (const rule of rules) {\n const ruleEntries = Object.entries(rule);\n if (ruleEntries.length === 0) continue;\n if (ruleEntries.every(([k, v]) => combo[k] === v)) return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Context ref translation (F-35)\n// ---------------------------------------------------------------------------\n\nconst GITLAB_CONTEXT_MAP: Readonly<Record<string, string>> = {\n \"git.sha\": \"$CI_COMMIT_SHA\",\n \"git.branch\": \"$CI_COMMIT_BRANCH\",\n \"git.tag\": \"$CI_COMMIT_TAG\",\n \"change.id\": \"$CI_MERGE_REQUEST_IID\",\n \"change.source\": \"$CI_PIPELINE_SOURCE\",\n \"change.target\": \"$CI_MERGE_REQUEST_TARGET_BRANCH_NAME\",\n \"change.draft\": \"$CI_MERGE_REQUEST_DRAFT\",\n \"event.type\": \"$CI_PIPELINE_SOURCE\",\n \"run.id\": \"$CI_PIPELINE_ID\",\n \"run.attempt\": \"$run_attempt\",\n};\n\n/**\n * Translate a context ref (namespace.field) to GitLab variable syntax.\n */\nfunction translateGitlabContextRef(namespace: string, field: string): string {\n const key = `${namespace}.${field}`;\n const mapped = GITLAB_CONTEXT_MAP[key];\n if (mapped) return mapped;\n // Dynamic namespaces: env.X, secrets.X, inputs.X → just $X\n if (namespace === \"env\" || namespace === \"secrets\") {\n return `$${field}`;\n }\n if (namespace === \"matrix\") {\n return `$${field.toUpperCase()}`;\n }\n // inputs.X → $[[ inputs.FIELD ]] (GitLab pipeline input syntax)\n if (namespace === \"inputs\") {\n return `$[[ inputs.${field} ]]`;\n }\n // Unknown — fail lowering rather than emit invalid expression\n throw new GitlabTargetError(\n `unsupported context namespace '${namespace}' in GitLab lowering`,\n \"LOWER_FAILED\",\n );\n}\n\n/**\n * Translate a step ref to GitLab variable syntax: $<output> (from dotenv artifact).\n */\nfunction translateGitlabStepRef(ref: StepRef): string {\n return `$${ref.output}`;\n}\n\n/**\n * Build a lookup map from placeholder key to Reference from the step's inputs.\n */\nfunction buildGitlabInputLookup(\n inputs: readonly Reference[],\n): Map<string, Reference> {\n const map = new Map<string, Reference>();\n for (const ref of inputs) {\n if (ref.kind === \"context\") {\n map.set(`${ref.namespace}.${ref.field}`, ref);\n } else if (ref.kind === \"step\") {\n map.set(`${ref.step}.${ref.output}`, ref);\n }\n }\n return map;\n}\n\n/**\n * Translate ${...} placeholders in a command string to GitLab variable syntax.\n */\nfunction translateGitlabCommand(\n command: string,\n inputs: readonly Reference[],\n _jobIdMap: Map<string, string>,\n): string {\n const lookup = buildGitlabInputLookup(inputs);\n return command.replace(/\\$\\{([^{}]+)\\}/g, (_, key: string) => {\n const ref = lookup.get(key);\n if (ref === undefined) {\n return `\\${${key}}`;\n }\n if (ref.kind === \"context\") {\n return translateGitlabContextRef(ref.namespace, ref.field);\n }\n return translateGitlabStepRef(ref);\n });\n}\n\n/**\n * Lower a step condition to a GitLab if: expression string (without wrapping in a rule).\n * Returns the raw expression that can be combined with trigger rule conditions.\n */\nfunction lowerGitlabConditionExpr(\n condition: Reference | Expression | StatusCondition,\n _jobIdMap: Map<string, string>,\n): string {\n if (condition.kind === \"status\") {\n // GitLab status conditions map to when: field, not if: expression.\n // Return a sentinel that the caller can use to set when: instead.\n // For if: expression purposes: success = no restriction, always = true, never = false.\n if (condition.status === \"always\") return \"true\";\n if (condition.status === \"never\") return \"false\";\n return \"\"; // success/failure — no if: restriction (when: handles it)\n }\n if (condition.kind === \"context\") {\n return translateGitlabContextRef(condition.namespace, condition.field);\n }\n if (condition.kind === \"step\") {\n // Step ref condition — truthiness check on the output variable\n return translateGitlabStepRef(condition);\n }\n // Expression — translate each ${...} placeholder, no single-quote wrapping\n const lookup = buildGitlabInputLookup(condition.refs);\n return condition.template.replace(/\\$\\{([^{}]+)\\}/g, (_, key: string) => {\n const ref = lookup.get(key);\n if (ref === undefined) return `\\${${key}}`;\n if (ref.kind === \"context\") {\n return translateGitlabContextRef(ref.namespace, ref.field);\n }\n return translateGitlabStepRef(ref);\n });\n}\n\n/**\n * Lower a step condition to a GitLab rule with an if: expression.\n */\nfunction lowerGitlabCondition(\n condition: Reference | Expression | StatusCondition,\n jobIdMap: Map<string, string>,\n): GitlabRule {\n return { if: lowerGitlabConditionExpr(condition, jobIdMap) };\n}\n","// Emit: GitlabTargetGraph → YAML artifacts.\n// Spec 09 — §19.\n\nimport { stringify } from \"yaml\";\nimport { GitlabTargetError } from \"./errors.js\";\nimport type {\n GitlabTargetGraph,\n GitlabJob,\n GitlabRule,\n GitlabService,\n GitlabEnvironment,\n GitlabCache,\n GeneratedArtifact,\n} from \"./types.js\";\n\nconst RESERVED_TOP_LEVEL_KEYS = new Set([\n \"stages\",\n \"variables\",\n \"workflow\",\n \"include\",\n \"default\",\n \"image\",\n \"services\",\n \"before_script\",\n \"after_script\",\n \"cache\",\n \"spec\",\n \"pages:deploy\",\n]);\n\n/**\n * Emit a GitlabTargetGraph as YAML artifacts.\n * Produces one .gitlab-ci.yml file.\n */\nexport function emitGitlab(\n targetGraph: GitlabTargetGraph,\n): readonly GeneratedArtifact[] {\n const yaml = stringifyTargetGraph(targetGraph);\n return [\n {\n path: \".gitlab-ci.yml\",\n content: yaml,\n },\n ];\n}\n\n/**\n * Convert a GitlabTargetGraph to a YAML string.\n */\nfunction stringifyTargetGraph(graph: GitlabTargetGraph): string {\n const doc: Record<string, unknown> = {\n stages: graph.stages,\n };\n\n if (graph.autoCancel) {\n doc.workflow = {\n auto_cancel: { on_new_commit: \"interruptible\" },\n };\n }\n\n if (Object.keys(graph.variables).length > 0) {\n doc.variables = graph.variables;\n }\n\n if (graph.default) {\n doc.default = defaultToYaml(graph.default);\n }\n\n if (graph.specInputs && Object.keys(graph.specInputs).length > 0) {\n doc.spec = { inputs: graph.specInputs };\n }\n\n // F-32: emit component includes.\n // F-44: emit local includes alongside component includes.\n const allIncludes = collectIncludes(graph);\n if (allIncludes.length > 0) {\n doc.include = allIncludes;\n }\n\n // F-42: emit workflow rules (merge with auto_cancel if both present).\n if (graph.workflowRules && graph.workflowRules.length > 0) {\n doc.workflow = {\n ...(doc.workflow as Record<string, unknown> | undefined),\n rules: graph.workflowRules.map(workflowRuleToYaml),\n };\n }\n\n for (const job of graph.jobs) {\n if (RESERVED_TOP_LEVEL_KEYS.has(job.id)) {\n throw new GitlabTargetError(\n `job id '${job.id}' conflicts with a reserved top-level GitLab CI key`,\n \"EMIT_FAILED\",\n );\n }\n doc[job.id] = jobToYaml(job);\n }\n\n return stringify(doc, { sortMapEntries: false });\n}\n\n/**\n * Convert a GitlabDefault to a YAML-compatible object.\n */\nfunction defaultToYaml(\n def: NonNullable<GitlabTargetGraph[\"default\"]>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n if (def.beforeScript !== undefined)\n result.before_script = [...def.beforeScript];\n if (def.afterScript !== undefined) result.after_script = [...def.afterScript];\n if (def.timeout !== undefined) result.timeout = def.timeout;\n if (def.retry !== undefined) {\n const retry: Record<string, unknown> = { max: def.retry.max };\n if (def.retry.exitCodes !== undefined) {\n retry.exit_codes = [...def.retry.exitCodes];\n }\n result.retry = retry;\n }\n if (def.interruptible !== undefined) result.interruptible = def.interruptible;\n return result;\n}\n\n/**\n * Collect all include entries (component + local) from a GitlabTargetGraph.\n */\nfunction collectIncludes(graph: GitlabTargetGraph): Record<string, unknown>[] {\n const allIncludes: Record<string, unknown>[] = [];\n for (const inc of graph.includes) {\n allIncludes.push({\n component: inc.component,\n ...(Object.keys(inc.inputs).length > 0 ? { inputs: inc.inputs } : {}),\n });\n }\n if (graph.localIncludes) {\n for (const inc of graph.localIncludes) {\n allIncludes.push({\n local: inc.local,\n ...(inc.inputs && Object.keys(inc.inputs).length > 0\n ? { inputs: inc.inputs }\n : {}),\n });\n }\n }\n return allIncludes;\n}\n\n/**\n * Convert a workflow rule to a YAML-compatible object.\n */\nfunction workflowRuleToYaml(\n rule: NonNullable<GitlabTargetGraph[\"workflowRules\"]>[number],\n): Record<string, unknown> {\n const r: Record<string, unknown> = {};\n if (rule.if) r.if = rule.if;\n if (rule.changes) r.changes = rule.changes;\n if (rule.exists) r.exists = rule.exists;\n if (rule.variables) r.variables = rule.variables;\n if (rule.when) r.when = rule.when;\n return r;\n}\n\n/**\n * Convert a GitlabJob to a YAML-compatible object.\n */\nfunction jobToYaml(job: GitlabJob): Record<string, unknown> {\n const result: Record<string, unknown> = {\n stage: job.stage,\n script: job.script,\n };\n\n // Simple field copies: [yamlKey, value]\n const simpleFields: Array<[string, unknown]> = [\n [\"image\", job.image],\n [\"timeout\", job.timeout],\n [\"interruptible\", job.interruptible],\n [\"resource_group\", job.resourceGroup],\n [\"trigger\", job.trigger],\n [\"release\", job.release],\n [\"pages\", job.pages],\n [\"when\", job.when],\n [\"start_in\", job.start_in],\n ];\n for (const [yamlKey, value] of simpleFields) {\n if (value !== undefined && value !== null) {\n result[yamlKey] = value;\n }\n }\n\n addComplexJobFields(result, job);\n return result;\n}\n\n/** Add artifacts, variables, and rules fields to the result object. */\nfunction assignJobArtifactsVarsRules(\n result: Record<string, unknown>,\n job: GitlabJob,\n): void {\n if (job.artifacts) {\n result.artifacts = artifactsToYaml(job.artifacts);\n }\n if (job.variables) {\n result.variables = job.variables;\n }\n if (job.rules && job.rules.length > 0) {\n result.rules = job.rules.map(ruleToYaml);\n }\n}\n\n/** Add parallel/matrix field to the result object. */\nfunction assignJobParallel(\n result: Record<string, unknown>,\n job: GitlabJob,\n): void {\n if (job.parallel?.matrix) {\n // GitLab parallel:matrix requires each variable value to be an array.\n result.parallel = {\n matrix: job.parallel.matrix.map((row: Record<string, unknown>) => {\n const wrapped: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(row)) {\n wrapped[k] = Array.isArray(v) ? v : [v];\n }\n return wrapped;\n }),\n };\n } else {\n assignOptional(result, \"parallel\", job.parallel);\n }\n}\n\n/** Add tags, id_tokens, services, environment, and cache fields. */\nfunction assignJobContainerFields(\n result: Record<string, unknown>,\n job: GitlabJob,\n): void {\n if (job.tags && job.tags.length > 0) {\n result.tags = [...job.tags];\n }\n if (job.idTokens && Object.keys(job.idTokens).length > 0) {\n result.id_tokens = idTokensToYaml(job.idTokens);\n }\n if (job.services && job.services.length > 0) {\n result.services = job.services.map(serviceToYaml);\n }\n if (job.environment) {\n result.environment = environmentToYaml(job.environment);\n }\n if (job.cache) {\n result.cache = cacheToYaml(job.cache);\n }\n}\n\n/** Add fields requiring transformation to the result object. */\nfunction addComplexJobFields(\n result: Record<string, unknown>,\n job: GitlabJob,\n): void {\n if (job.needs.length > 0) {\n result.needs = [...job.needs];\n }\n\n assignOptionalList(result, \"before_script\", job.beforeScript);\n assignOptionalList(result, \"after_script\", job.afterScript);\n\n assignJobArtifactsVarsRules(result, job);\n\n assignAllowFailure(result, job.allowFailure);\n assignRetry(result, job.retry);\n assignJobParallel(result, job);\n\n assignJobContainerFields(result, job);\n}\n\nfunction assignOptional(\n result: Record<string, unknown>,\n key: string,\n value: unknown,\n): void {\n if (value !== undefined) result[key] = value;\n}\n\nfunction assignOptionalList(\n result: Record<string, unknown>,\n key: string,\n value: readonly string[] | undefined,\n): void {\n if (value && value.length > 0) result[key] = [...value];\n}\n\nfunction assignAllowFailure(\n result: Record<string, unknown>,\n value: GitlabJob[\"allowFailure\"],\n): void {\n if (value === undefined) return;\n if (typeof value === \"boolean\") {\n result.allow_failure = value;\n } else {\n result.allow_failure = { exit_codes: [...value.exitCodes] };\n }\n}\n\nfunction assignRetry(\n result: Record<string, unknown>,\n value: GitlabJob[\"retry\"],\n): void {\n if (value === undefined) return;\n // GitLab enforces a maximum of 2 retries.\n const retry: Record<string, unknown> = { max: Math.min(value.max, 2) };\n if (value.when && value.when.length > 0) retry.when = [...value.when];\n if (value.exitCodes && value.exitCodes.length > 0)\n retry.exit_codes = [...value.exitCodes];\n result.retry = retry;\n}\n\n/**\n * Convert an artifacts spec to a YAML-compatible object.\n */\nfunction artifactsToYaml(\n artifacts: NonNullable<GitlabJob[\"artifacts\"]>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n if (artifacts.paths !== undefined) result.paths = [...artifacts.paths];\n if (artifacts.reports !== undefined) result.reports = artifacts.reports;\n if (artifacts.expireIn !== undefined) result.expire_in = artifacts.expireIn;\n if (artifacts.access !== undefined) result.access = artifacts.access;\n if (artifacts.when !== undefined) result.when = artifacts.when;\n return result;\n}\n\n/**\n * Convert a job rule to a YAML-compatible object.\n */\nfunction ruleToYaml(rule: GitlabRule): Record<string, unknown> {\n const r: Record<string, unknown> = {};\n if (rule.if !== undefined) r.if = rule.if;\n if (rule.when !== undefined) r.when = rule.when;\n if (rule.changes !== undefined) r.changes = [...rule.changes];\n if (rule.exists !== undefined) r.exists = [...rule.exists];\n if (rule.variables !== undefined) r.variables = rule.variables;\n return r;\n}\n\n/**\n * Convert id tokens to a YAML-compatible object.\n */\nfunction idTokensToYaml(\n idTokens: NonNullable<GitlabJob[\"idTokens\"]>,\n): Record<string, { aud: string }> {\n const result: Record<string, { aud: string }> = {};\n for (const [name, spec] of Object.entries(idTokens)) {\n result[name] = { aud: spec.aud };\n }\n return result;\n}\n\n/**\n * Convert a service to a YAML-compatible object.\n */\nfunction serviceToYaml(svc: GitlabService): Record<string, unknown> {\n const s: Record<string, unknown> = { name: svc.name };\n if (svc.alias !== undefined) s.alias = svc.alias;\n if (svc.entrypoint !== undefined) s.entrypoint = [...svc.entrypoint];\n if (svc.command !== undefined) s.command = [...svc.command];\n if (svc.variables !== undefined) s.variables = svc.variables;\n return s;\n}\n\n/**\n * Convert an environment spec to a YAML-compatible object.\n */\nfunction environmentToYaml(env: GitlabEnvironment): Record<string, unknown> {\n const result: Record<string, unknown> = { name: env.name };\n if (env.url !== undefined) result.url = env.url;\n if (env.action !== undefined) result.action = env.action;\n if (env.deploymentTier !== undefined)\n result.deployment_tier = env.deploymentTier;\n if (env.onStop !== undefined) result.on_stop = env.onStop;\n return result;\n}\n\n/**\n * Convert a cache spec to a YAML-compatible object.\n */\nfunction cacheToYaml(cache: GitlabCache): Record<string, unknown> {\n const result: Record<string, unknown> = {\n paths: [...cache.paths],\n key: cache.key,\n };\n if (cache.policy !== undefined) result.policy = cache.policy;\n if (cache.fallbackKeys !== undefined)\n result.fallback_keys = [...cache.fallbackKeys];\n return result;\n}\n","// GitlabTarget — implements the Target contract (§19).\n// Spec 09 — §18.2, §19.\n\nimport type { DefinitionGraph } from \"@sverka/workflow\";\nimport type { CapabilityManifest, Target } from \"../plugin/index.js\";\nimport { analyzeCapabilities } from \"../plugin/index.js\";\nimport { gitlabCapabilities } from \"./capabilities.js\";\nimport { lowerGitlab } from \"./lower.js\";\nimport { emitGitlab } from \"./emit.js\";\nimport type {\n GitlabTargetGraph,\n GeneratedArtifact,\n TargetDiagnostic,\n CompilationResult,\n} from \"./types.js\";\n\n/**\n * GitLab CI target — native lowering from Definition Graph.\n * Implements the Target contract: analyze → lower → emit.\n */\nexport class GitlabTarget implements Target {\n readonly name = \"gitlab\";\n readonly capabilities: CapabilityManifest = gitlabCapabilities;\n\n /**\n * Analyze a Definition Graph against the GitLab capability manifest.\n * Returns diagnostics for unsupported or emulated capabilities.\n */\n analyze(graph: DefinitionGraph): readonly TargetDiagnostic[] {\n const diags = analyzeCapabilities(graph, [this.capabilities]);\n return diags as readonly TargetDiagnostic[];\n }\n\n /**\n * Lower a Definition Graph to a GitlabTargetGraph.\n * One GitLab job per reachable Step with needs, stages, and operation mapping.\n */\n lower(graph: DefinitionGraph): GitlabTargetGraph {\n return lowerGitlab(graph);\n }\n\n /**\n * Emit a GitlabTargetGraph as YAML artifacts.\n * Produces one .gitlab-ci.yml file.\n */\n emit(targetGraph: GitlabTargetGraph): readonly GeneratedArtifact[] {\n return emitGitlab(targetGraph);\n }\n\n /**\n * Compile a Definition Graph to generated artifacts and diagnostics.\n */\n compile(graph: DefinitionGraph): CompilationResult {\n const diagnostics = this.analyze(graph);\n const targetGraph = this.lower(graph);\n const artifacts = this.emit(targetGraph);\n return { artifacts, diagnostics };\n }\n}\n\n/**\n * Convenience function: analyze → lower → emit in one call.\n */\nexport function compileGitlab(graph: DefinitionGraph): CompilationResult {\n return new GitlabTarget().compile(graph);\n}\n","// GitHub Actions importer: parse .github/workflows/*.yml → Definition Graph.\n// F-43 — reverse lowering. Spec §25.\n\nimport { parse as parseYaml } from \"yaml\";\nimport type {\n DefinitionGraph,\n ProjectDefinition,\n PipelineDefinition,\n StepDefinition,\n OperationDefinition,\n Dependency,\n EntryDefinition,\n} from \"@sverka/workflow\";\nimport type { Trigger, Runtime } from \"@sverka/workflow\";\nimport { GithubTargetError } from \"./errors.js\";\n\n/**\n * Diagnostic produced during import for unmappable constructs.\n */\nexport interface ImportDiagnostic {\n readonly severity: \"info\" | \"warn\" | \"error\";\n readonly message: string;\n readonly path?: string;\n}\n\nexport interface ImportResult {\n readonly graph: DefinitionGraph;\n readonly diagnostics: readonly ImportDiagnostic[];\n}\n\n/**\n * Import a GitHub Actions workflow YAML string into a Definition Graph.\n * Lossy: unmappable constructs produce diagnostics.\n */\nexport function importGithub(source: string): DefinitionGraph {\n return importGithubWithDiagnostics(source).graph;\n}\n\n/**\n * Import a GitHub Actions workflow YAML string with diagnostics.\n */\nexport function importGithubWithDiagnostics(source: string): ImportResult {\n const diagnostics: ImportDiagnostic[] = [];\n let doc: Record<string, unknown>;\n\n try {\n doc = parseYaml(source) as Record<string, unknown>;\n } catch (err) {\n throw new GithubTargetError(\n `failed to parse GitHub workflow YAML: ${err instanceof Error ? err.message : String(err)}`,\n \"IMPORT_FAILED\",\n );\n }\n\n if (!doc || typeof doc !== \"object\") {\n throw new GithubTargetError(\n \"GitHub workflow YAML is not a valid object\",\n \"IMPORT_FAILED\",\n );\n }\n\n const projectId = \"imported\";\n const steps: StepDefinition[] = [];\n const entries: EntryDefinition[] = [];\n\n // Extract triggers from `on:`.\n const trigger = parseTrigger(doc.on, diagnostics);\n\n // Extract jobs → steps.\n const jobs = doc.jobs as Record<string, unknown> | undefined;\n if (jobs) {\n for (const [jobId, job] of Object.entries(jobs)) {\n if (job === null || typeof job !== \"object\") {\n diagnostics.push({\n severity: \"warn\",\n message: `job '${jobId}' is not a valid object, skipping`,\n });\n continue;\n }\n steps.push(parseJob(jobId, job as Record<string, unknown>, diagnostics));\n }\n }\n\n // Create entry from trigger.\n if (steps.length > 0) {\n entries.push({ id: \"ci/default\", trigger, roots: steps.map((s) => s.id) });\n }\n\n const pipeline: PipelineDefinition = {\n id: \"ci\",\n inputs: {},\n entries,\n steps,\n outputs: [],\n };\n\n const project: ProjectDefinition = { id: projectId, pipelines: [pipeline] };\n\n return {\n graph: { project },\n diagnostics,\n };\n}\n\n/**\n * Parse the `on:` field of a GitHub workflow into a Sverka Trigger.\n */\nfunction parseTrigger(\n onField: unknown,\n diagnostics: ImportDiagnostic[],\n): Trigger {\n if (typeof onField === \"string\") {\n return parseStringTrigger(onField);\n }\n if (onField && typeof onField === \"object\") {\n return parseObjectTrigger(onField as Record<string, unknown>, diagnostics);\n }\n return { kind: \"push\" };\n}\n\nfunction parseStringTrigger(onField: string): Trigger {\n if (onField === \"push\") return { kind: \"push\" };\n if (onField === \"pull_request\") return { kind: \"changeRequest\" };\n return { kind: \"manual\" };\n}\n\nfunction parseObjectTrigger(\n on: Record<string, unknown>,\n diagnostics: ImportDiagnostic[],\n): Trigger {\n if (\"push\" in on) return { kind: \"push\" };\n if (\"pull_request\" in on) return { kind: \"changeRequest\" };\n if (\"workflow_dispatch\" in on) return { kind: \"manual\" };\n if (\"schedule\" in on) {\n diagnostics.push({\n severity: \"info\",\n message: \"schedule trigger imported as manual\",\n });\n return { kind: \"manual\" };\n }\n return { kind: \"manual\" };\n}\n\n/**\n * Parse a single GitHub job into a Sverka StepDefinition.\n */\nfunction parseJob(\n jobId: string,\n job: Record<string, unknown>,\n diagnostics: ImportDiagnostic[],\n): StepDefinition {\n const stepId = `ci/${jobId}`;\n const operations: OperationDefinition[] = [];\n const dependencies: Dependency[] = [];\n\n // needs → dependencies.\n parseJobNeeds(job, dependencies);\n\n // steps → operations.\n const jobSteps = job.steps as readonly Record<string, unknown>[] | undefined;\n if (jobSteps) {\n for (const step of jobSteps) {\n parseJobStep(jobId, step, operations, diagnostics);\n }\n }\n\n // Unmappable constructs → diagnostics.\n recordJobDiagnostics(jobId, job, diagnostics);\n\n const runtime: Runtime = {};\n\n // runs-on → runner spec\n const runner = parseRunsOn(job[\"runs-on\"]);\n\n return {\n id: stepId,\n runtime,\n operations,\n inputs: [],\n outputs: [],\n dependencies,\n ...(runner !== undefined ? { runner } : {}),\n };\n}\n\n/**\n * Parse a job's `needs` field into dependencies.\n */\nfunction parseJobNeeds(\n job: Record<string, unknown>,\n dependencies: Dependency[],\n): void {\n if (typeof job.needs === \"string\") {\n dependencies.push({ kind: \"control\", producer: `ci/${job.needs}` });\n } else if (Array.isArray(job.needs)) {\n for (const need of job.needs) {\n if (typeof need === \"string\") {\n dependencies.push({ kind: \"control\", producer: `ci/${need}` });\n }\n }\n }\n}\n\n/**\n * Parse a single GitHub step into one or more operations.\n */\nfunction parseJobStep(\n jobId: string,\n step: Record<string, unknown>,\n operations: OperationDefinition[],\n diagnostics: ImportDiagnostic[],\n): void {\n if (typeof step.run === \"string\") {\n operations.push({ kind: \"shell\", command: step.run });\n return;\n }\n if (typeof step.uses === \"string\") {\n parseUsesStep(jobId, step, step.uses, operations, diagnostics);\n }\n}\n\n/**\n * Parse a `uses:` step by dispatching to the appropriate action handler.\n */\nfunction parseUsesStep(\n jobId: string,\n step: Record<string, unknown>,\n uses: string,\n operations: OperationDefinition[],\n diagnostics: ImportDiagnostic[],\n): void {\n if (uses.includes(\"action-gh-release\")) {\n operations.push(parseReleaseAction(step));\n } else if (uses.includes(\"upload-pages-artifact\")) {\n operations.push(parseDeployPagesAction(step));\n } else if (uses.includes(\"actions/checkout\")) {\n // Skip checkout — it's implicit in Sverka.\n } else if (uses.includes(\"actions/upload-artifact\")) {\n operations.push(parseUploadArtifactAction(step));\n } else if (uses.includes(\"actions/download-artifact\")) {\n parseDownloadArtifactAction(jobId, step, operations, diagnostics);\n } else {\n diagnostics.push({\n severity: \"info\",\n message: `unmapped action '${uses}' in job '${jobId}' — skipped`,\n path: jobId,\n });\n }\n}\n\n/**\n * Parse a release action (softprops/action-gh-release) into a release operation.\n */\nfunction parseReleaseAction(\n step: Record<string, unknown>,\n): OperationDefinition {\n const withMap = (step.with as Record<string, unknown> | undefined) ?? {};\n return {\n kind: \"release\",\n tag: typeof withMap.tag_name === \"string\" ? withMap.tag_name : \"unknown\",\n ...(typeof withMap.name === \"string\" ? { name: withMap.name } : {}),\n ...(typeof withMap.body === \"string\" ? { description: withMap.body } : {}),\n ...(typeof withMap.assets === \"string\"\n ? { assets: withMap.assets.split(\"\\n\").filter((s) => s.length > 0) }\n : {}),\n ...(typeof withMap.draft === \"boolean\" ? { draft: withMap.draft } : {}),\n ...(typeof withMap.prerelease === \"boolean\"\n ? { prerelease: withMap.prerelease }\n : {}),\n };\n}\n\n/**\n * Parse an upload-pages-artifact action into a deployPages operation.\n */\nfunction parseDeployPagesAction(\n step: Record<string, unknown>,\n): OperationDefinition {\n const withMap = (step.with as Record<string, unknown> | undefined) ?? {};\n return {\n kind: \"deployPages\",\n path: typeof withMap.path === \"string\" ? withMap.path : \"dist/\",\n };\n // Note: deploy-pages action usually follows; we skip it since\n // the deployPages operation covers both upload and deploy.\n}\n\n/**\n * Parse an actions/upload-artifact action into an exportArtifact operation.\n */\nfunction parseUploadArtifactAction(\n step: Record<string, unknown>,\n): OperationDefinition {\n const withMap = (step.with as Record<string, unknown> | undefined) ?? {};\n return {\n kind: \"exportArtifact\",\n name: typeof withMap.name === \"string\" ? withMap.name : \"artifact\",\n path: typeof withMap.path === \"string\" ? withMap.path : \".\",\n };\n}\n\n/**\n * Parse an actions/download-artifact action into an importArtifact operation.\n */\nfunction parseDownloadArtifactAction(\n jobId: string,\n step: Record<string, unknown>,\n operations: OperationDefinition[],\n diagnostics: ImportDiagnostic[],\n): void {\n const withMap = (step.with as Record<string, unknown> | undefined) ?? {};\n const artifactName =\n typeof withMap.name === \"string\" ? withMap.name : \"artifact\";\n // Try to resolve the producing job from the artifact name.\n // Artifact names follow the pattern `<stepId>-<outputName>`.\n const from = resolveArtifactProducer(artifactName);\n operations.push({\n kind: \"importArtifact\",\n name: artifactName,\n from,\n output: artifactName,\n });\n if (from === \"ci/unknown\") {\n diagnostics.push({\n severity: \"warn\",\n message: `download-artifact in job '${jobId}' — producer could not be resolved from name '${artifactName}', may need manual correction`,\n path: jobId,\n });\n }\n}\n\n/**\n * Try to resolve the producing job from an artifact name.\n * Artifact names follow the pattern `<stepId>-<outputName>`, so the producer\n * is `ci/<stepId>`.\n */\nfunction resolveArtifactProducer(artifactName: string): string {\n const dashIdx = artifactName.lastIndexOf(\"-\");\n if (dashIdx > 0) {\n const stepId = artifactName.slice(0, dashIdx);\n return `ci/${stepId}`;\n }\n return \"ci/unknown\";\n}\n\n/**\n * Parse `runs-on` into a RunnerSpec.\n * Supports string, array, and object forms.\n */\nfunction parseRunsOn(\n runsOn: unknown,\n): { labels: readonly string[]; group?: string } | undefined {\n if (typeof runsOn === \"string\") {\n return { labels: [runsOn] };\n }\n if (Array.isArray(runsOn)) {\n const labels = runsOn.filter((v): v is string => typeof v === \"string\");\n if (labels.length > 0) return { labels };\n }\n if (runsOn && typeof runsOn === \"object\") {\n const obj = runsOn as Record<string, unknown>;\n const group = typeof obj.group === \"string\" ? obj.group : undefined;\n const labels = Array.isArray(obj.labels)\n ? obj.labels.filter((v): v is string => typeof v === \"string\")\n : [];\n if (labels.length > 0 || group !== undefined) {\n return { labels, ...(group !== undefined ? { group } : {}) };\n }\n }\n return undefined;\n}\n\n/**\n * Record diagnostics for unmappable job-level constructs.\n */\nfunction recordJobDiagnostics(\n jobId: string,\n job: Record<string, unknown>,\n diagnostics: ImportDiagnostic[],\n): void {\n if (job.strategy) {\n diagnostics.push({\n severity: \"warn\",\n message: `job '${jobId}' has strategy/matrix — not imported`,\n path: jobId,\n });\n }\n if (job.services) {\n diagnostics.push({\n severity: \"info\",\n message: `job '${jobId}' has services — not imported`,\n path: jobId,\n });\n }\n if (job.environment) {\n diagnostics.push({\n severity: \"info\",\n message: `job '${jobId}' has environment — not imported`,\n path: jobId,\n });\n }\n}\n","// GitLab CI importer: parse .gitlab-ci.yml → Definition Graph.\n// F-43 — reverse lowering. Spec §25.\n\nimport { parse as parseYaml } from \"yaml\";\nimport type {\n DefinitionGraph,\n ProjectDefinition,\n PipelineDefinition,\n StepDefinition,\n OperationDefinition,\n Dependency,\n EntryDefinition,\n} from \"@sverka/workflow\";\nimport type {\n Trigger,\n PipelineRule,\n Runtime,\n Rule,\n ReportType,\n} from \"@sverka/workflow\";\nimport { GitlabTargetError } from \"./errors.js\";\n\n/**\n * Diagnostic produced during import for unmappable constructs.\n */\nexport interface ImportDiagnostic {\n readonly severity: \"info\" | \"warn\" | \"error\";\n readonly message: string;\n readonly path?: string;\n}\n\nexport interface ImportResult {\n readonly graph: DefinitionGraph;\n readonly diagnostics: readonly ImportDiagnostic[];\n}\n\n/**\n * Import a GitLab CI YAML string into a Definition Graph.\n * Lossy: unmappable constructs produce diagnostics.\n */\nexport function importGitlab(source: string): DefinitionGraph {\n return importGitlabWithDiagnostics(source).graph;\n}\n\n/**\n * Import a GitLab CI YAML string with diagnostics for unmappable constructs.\n */\nexport function importGitlabWithDiagnostics(source: string): ImportResult {\n const diagnostics: ImportDiagnostic[] = [];\n const doc = parseGitlabDoc(source);\n\n const projectId = \"imported\";\n const steps: StepDefinition[] = [];\n const entries: EntryDefinition[] = [];\n const pipelineRules: PipelineRule[] = [];\n\n extractWorkflowRules(doc, pipelineRules);\n\n const reservedKeys = new Set([\n \"stages\",\n \"variables\",\n \"workflow\",\n \"include\",\n \"image\",\n \"before_script\",\n \"after_script\",\n \"cache\",\n \"services\",\n \"default\",\n ]);\n\n for (const [key, value] of Object.entries(doc)) {\n if (reservedKeys.has(key)) continue;\n // Skip hidden jobs (dot-prefixed keys like .base) — they are templates, not executable.\n if (key.startsWith(\".\")) continue;\n if (!value || typeof value !== \"object\") continue;\n const step = convertJobToStep(\n key,\n value as Record<string, unknown>,\n diagnostics,\n );\n steps.push(step);\n }\n\n if (steps.length > 0 && entries.length === 0) {\n const trigger: Trigger = { kind: \"push\" };\n entries.push({ id: \"ci/default\", trigger, roots: steps.map((s) => s.id) });\n }\n\n const pipeline: PipelineDefinition = {\n id: \"ci\",\n inputs: {},\n entries,\n steps,\n outputs: [],\n ...(pipelineRules.length > 0 ? { rules: pipelineRules } : {}),\n };\n\n const project: ProjectDefinition = { id: projectId, pipelines: [pipeline] };\n\n return {\n graph: { project },\n diagnostics,\n };\n}\n\n/**\n * Parse and validate the GitLab CI YAML source into a record.\n */\nfunction parseGitlabDoc(source: string): Record<string, unknown> {\n let doc: Record<string, unknown>;\n try {\n doc = parseYaml(source) as Record<string, unknown>;\n } catch (err) {\n throw new GitlabTargetError(\n `failed to parse GitLab CI YAML: ${err instanceof Error ? err.message : String(err)}`,\n \"IMPORT_FAILED\",\n );\n }\n if (!doc || typeof doc !== \"object\") {\n throw new GitlabTargetError(\n \"GitLab CI YAML is not a valid object\",\n \"IMPORT_FAILED\",\n );\n }\n return doc;\n}\n\n/**\n * Extract workflow:rules into pipeline rules.\n */\nfunction extractWorkflowRules(\n doc: Record<string, unknown>,\n pipelineRules: PipelineRule[],\n): void {\n const workflow = doc.workflow as\n { rules?: readonly Record<string, unknown>[] } | undefined;\n if (!workflow?.rules) return;\n for (const rule of workflow.rules) {\n pipelineRules.push(convertWorkflowRule(rule));\n }\n}\n\n/**\n * Extract string variables from a rule's `variables` field.\n */\nfunction extractRuleVariables(\n rule: Record<string, unknown>,\n): Record<string, string> | undefined {\n if (rule.variables && typeof rule.variables === \"object\") {\n return Object.fromEntries(\n Object.entries(rule.variables as Record<string, unknown>).filter(\n ([, v]) => typeof v === \"string\",\n ),\n ) as Record<string, string>;\n }\n return undefined;\n}\n\nfunction convertWorkflowRule(rule: Record<string, unknown>): PipelineRule {\n const pr: {\n if?: string;\n changes?: readonly string[];\n exists?: readonly string[];\n variables?: Record<string, string>;\n when?: \"always\" | \"never\";\n } = {};\n if (typeof rule.if === \"string\") pr.if = rule.if;\n if (Array.isArray(rule.changes))\n pr.changes = rule.changes as readonly string[];\n if (Array.isArray(rule.exists)) pr.exists = rule.exists as readonly string[];\n const variables = extractRuleVariables(rule);\n if (variables) pr.variables = variables;\n if (rule.when === \"always\" || rule.when === \"never\") pr.when = rule.when;\n return pr;\n}\n\n/**\n * Convert a single GitLab job into a StepDefinition.\n */\nfunction convertJobToStep(\n key: string,\n job: Record<string, unknown>,\n diagnostics: ImportDiagnostic[],\n): StepDefinition {\n const stepId = `ci/${key}`;\n const operations: OperationDefinition[] = [];\n const dependencies: Dependency[] = [];\n\n convertScript(job, operations);\n convertNeeds(job, dependencies);\n convertTrigger(key, job, operations, diagnostics);\n convertRelease(job, operations);\n convertPages(job, operations);\n convertArtifacts(job, operations);\n recordUnmappableConstructs(key, job, diagnostics);\n\n const runtime: Runtime =\n typeof job.image === \"string\"\n ? { mode: \"container\", image: job.image }\n : {};\n\n // Job-level rules → StepDefinition.rules\n const rules = convertJobRules(job);\n\n // Job-level before_script/after_script\n const beforeScript = convertScriptArray(job, \"before_script\");\n const afterScript = convertScriptArray(job, \"after_script\");\n\n // when: delayed + start_in → delay\n const delay = convertDelay(job);\n\n return {\n id: stepId,\n runtime,\n operations,\n inputs: [],\n outputs: [],\n dependencies,\n ...(rules.length > 0 ? { rules } : {}),\n ...(beforeScript !== undefined ? { beforeScript } : {}),\n ...(afterScript !== undefined ? { afterScript } : {}),\n ...(delay !== undefined ? { delay } : {}),\n };\n}\n\n/**\n * Convert `script` into shell operations.\n */\nfunction convertScript(\n job: Record<string, unknown>,\n operations: OperationDefinition[],\n): void {\n if (typeof job.script === \"string\") {\n operations.push({ kind: \"shell\", command: job.script });\n } else if (Array.isArray(job.script)) {\n for (const line of job.script) {\n if (typeof line === \"string\") {\n operations.push({ kind: \"shell\", command: line });\n }\n }\n }\n}\n\n/**\n * Convert `needs` into dependencies.\n */\nfunction convertNeeds(\n job: Record<string, unknown>,\n dependencies: Dependency[],\n): void {\n if (Array.isArray(job.needs)) {\n for (const need of job.needs) {\n if (typeof need === \"string\") {\n dependencies.push({ kind: \"control\", producer: `ci/${need}` });\n } else if (\n need &&\n typeof need === \"object\" &&\n typeof (need as Record<string, unknown>).job === \"string\"\n ) {\n const needJob = (need as Record<string, unknown>).job as string;\n dependencies.push({ kind: \"control\", producer: `ci/${needJob}` });\n }\n }\n } else if (typeof job.needs === \"string\") {\n dependencies.push({ kind: \"control\", producer: `ci/${job.needs}` });\n }\n}\n\n/**\n * Convert `trigger` into downstream/child pipeline diagnostics.\n */\nfunction convertTrigger(\n key: string,\n job: Record<string, unknown>,\n operations: OperationDefinition[],\n diagnostics: ImportDiagnostic[],\n): void {\n if (!job.trigger || typeof job.trigger !== \"object\") return;\n const trigger = job.trigger as Record<string, unknown>;\n if (typeof trigger.project === \"string\") {\n operations.push({\n kind: \"diagnostic\",\n message: `imported downstream trigger to project: ${trigger.project}`,\n severity: \"info\",\n });\n diagnostics.push({\n severity: \"warn\",\n message: `job '${key}' has a downstream project trigger — imported as diagnostic. Manual reconstruction needed.`,\n path: key,\n });\n } else if (Array.isArray(trigger.include)) {\n diagnostics.push({\n severity: \"warn\",\n message: `job '${key}' has a child pipeline trigger — imported as diagnostic. Manual reconstruction needed.`,\n path: key,\n });\n }\n}\n\n/**\n * Convert `release` into a release operation.\n */\nfunction convertRelease(\n job: Record<string, unknown>,\n operations: OperationDefinition[],\n): void {\n if (!job.release || typeof job.release !== \"object\") return;\n const release = job.release as Record<string, unknown>;\n const assets = release.assets as\n { links?: readonly { name?: string; url?: string }[] } | undefined;\n operations.push({\n kind: \"release\",\n tag: typeof release.tag_name === \"string\" ? release.tag_name : \"unknown\",\n ...(typeof release.name === \"string\" ? { name: release.name } : {}),\n ...(typeof release.description === \"string\"\n ? { description: release.description }\n : {}),\n ...(assets?.links\n ? { assets: assets.links.map((l) => l.url ?? l.name ?? \"unknown\") }\n : {}),\n });\n}\n\n/**\n * Convert `pages` into a deployPages operation.\n */\nfunction convertPages(\n job: Record<string, unknown>,\n operations: OperationDefinition[],\n): void {\n if (!job.pages || typeof job.pages !== \"object\") return;\n const pages = job.pages as Record<string, unknown>;\n operations.push({\n kind: \"deployPages\",\n path: typeof pages.publish === \"string\" ? pages.publish : \"public/\",\n ...(typeof pages.path_prefix === \"string\"\n ? { prefix: pages.path_prefix }\n : {}),\n });\n}\n\n/**\n * Record diagnostics for constructs that cannot be mapped to the IR.\n */\nfunction recordUnmappableConstructs(\n key: string,\n job: Record<string, unknown>,\n diagnostics: ImportDiagnostic[],\n): void {\n if (job.cache) {\n diagnostics.push({\n severity: \"info\",\n message: `job '${key}' has cache — not imported`,\n path: key,\n });\n }\n if (job.services) {\n diagnostics.push({\n severity: \"info\",\n message: `job '${key}' has services — not imported`,\n path: key,\n });\n }\n if (job.matrix) {\n diagnostics.push({\n severity: \"warn\",\n message: `job '${key}' has matrix — not imported`,\n path: key,\n });\n }\n}\n\n/**\n * Valid `when` values for job-level rules.\n */\nconst JOB_RULE_WHEN_VALUES = new Set([\n \"on_success\",\n \"on_failure\",\n \"always\",\n \"never\",\n \"manual\",\n]);\n\n/**\n * Convert a single raw rule object into a StepDefinition rule entry.\n */\nfunction convertJobRuleEntry(r: Record<string, unknown>): Rule {\n const ruleEntry: {\n if?: string;\n changes?: readonly string[];\n exists?: readonly string[];\n when?: Rule[\"when\"];\n variables?: Record<string, string>;\n } = {};\n if (typeof r.if === \"string\") ruleEntry.if = r.if;\n if (Array.isArray(r.changes))\n ruleEntry.changes = r.changes as readonly string[];\n if (Array.isArray(r.exists)) ruleEntry.exists = r.exists as readonly string[];\n if (typeof r.when === \"string\" && JOB_RULE_WHEN_VALUES.has(r.when)) {\n ruleEntry.when = r.when as Rule[\"when\"];\n }\n const variables = extractRuleVariables(r);\n if (variables) ruleEntry.variables = variables;\n return ruleEntry as Rule;\n}\n\n/**\n * Convert job-level `rules` into StepDefinition rules.\n */\nfunction convertJobRules(job: Record<string, unknown>): readonly Rule[] {\n if (!Array.isArray(job.rules)) return [];\n const rules: Rule[] = [];\n for (const rule of job.rules) {\n if (!rule || typeof rule !== \"object\") continue;\n rules.push(convertJobRuleEntry(rule as Record<string, unknown>));\n }\n return rules;\n}\n\n/**\n * Convert a script array field (before_script/after_script) from a job.\n */\nfunction convertScriptArray(\n job: Record<string, unknown>,\n field: string,\n): readonly string[] | undefined {\n const value = job[field];\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) {\n const lines = value.filter((v): v is string => typeof v === \"string\");\n if (lines.length > 0) return lines;\n }\n return undefined;\n}\n\n/**\n * Convert `when: delayed` + `start_in` to a delay string.\n */\nfunction convertDelay(job: Record<string, unknown>): string | undefined {\n if (job.when === \"delayed\" && typeof job.start_in === \"string\") {\n return job.start_in;\n }\n return undefined;\n}\n\n/**\n * Convert artifact `paths` into exportArtifact operations.\n */\nfunction convertArtifactPaths(\n artifacts: Record<string, unknown>,\n operations: OperationDefinition[],\n): void {\n const paths = artifacts.paths;\n if (!Array.isArray(paths)) return;\n for (const path of paths) {\n if (typeof path === \"string\") {\n operations.push({\n kind: \"exportArtifact\",\n name: path.split(\"/\").pop() ?? path,\n path,\n });\n }\n }\n}\n\n/**\n * Convert artifact `reports` into report operations.\n * Reports are noted but not fully mapped — they require spec types.\n * Unsupported report keys are silently skipped to avoid producing invalid\n * graph nodes that violate the CDK report-type contract.\n */\nconst SUPPORTED_REPORT_TYPES: ReadonlySet<string> = new Set([\n \"junit\",\n \"coverage\",\n \"dotenv\",\n \"sast\",\n \"dast\",\n \"dependencyScanning\",\n \"containerScanning\",\n \"licenseScanning\",\n \"performance\",\n \"metrics\",\n \"terraform\",\n \"quality\",\n \"sarif\",\n]);\n\nfunction convertArtifactReports(\n artifacts: Record<string, unknown>,\n operations: OperationDefinition[],\n): void {\n if (!artifacts.reports || typeof artifacts.reports !== \"object\") return;\n const reports = artifacts.reports as Record<string, unknown>;\n for (const [type, value] of Object.entries(reports)) {\n if (typeof value === \"string\" && SUPPORTED_REPORT_TYPES.has(type)) {\n operations.push({\n kind: \"report\",\n spec: { type: type as ReportType, path: value },\n });\n }\n }\n}\n\n/**\n * Convert `artifacts` into exportArtifact operations.\n */\nfunction convertArtifacts(\n job: Record<string, unknown>,\n operations: OperationDefinition[],\n): void {\n if (!job.artifacts || typeof job.artifacts !== \"object\") return;\n const artifacts = job.artifacts as Record<string, unknown>;\n convertArtifactPaths(artifacts, operations);\n convertArtifactReports(artifacts, operations);\n}\n"],"mappings":";;;AAKA,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;CAEA,YAAY,SAAiB,MAAuB,OAAiB;EACnE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;;;ACFA,MAAM,iBAA+C;CACn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