@sverka/sdk 0.2.28 → 0.2.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -6
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/planner/bind.ts","../src/planner/planner.ts","../src/planner/errors.ts","../src/planner/matrix.ts","../src/errors.ts","../src/types.ts","../src/compat/config.ts","../src/sverka.ts","../src/compat/helpers.ts","../src/dollar.ts","../src/shell.ts","../src/artifact.ts","../src/pipeline.ts","../src/call-pipeline.ts","../src/component.ts","../src/when.ts","../src/expr.ts","../src/status.ts","../src/images.ts","../src/context.ts","../src/agent.ts","../src/markdown.ts","../src/markdown-errors.ts"],"mappings":";;;;UAeiB;WACN,OAAO;WACP;WACA,SAAS,SAAS,eAAe;;;;;;wBAS5B,YAAY,SAAS,qBAAqB;;;;;;;wBAiO1C,sBACd,gBAAgB,kBAChB,oCACU;;;;;;UChNK;EACf,SAAS,SAAS,kBAAkB,QAAQ;EAC5C,KAAK,SAAS,iBAAiB,QAAQ;EACvC,YAAY,SAAS,qBAAqB;;wBAG5B,iBAAiB;UAIhB;EACf;EACA;EACA;;;;;;;;EAQA;;UAGe;EACf,SAAS;EACT,iBAAiB;EACjB;EACA;;;;;;;;qBCvEW,uBAAuB;WACzB,MAAM;WACG;EACN,YAAA,iBAAiB,MAAM,oBAAoB;;KAQ7C;;;;qBAUC,qBAAqB;WACvB,MAAM;WACG;EACN,YAAA,iBAAiB,MAAM,kBAAkB;;KAQ3C;;;;;;;;;;;;;;;wBCVI,kBACd,gBAAgB,4BACN;;;KC1BA;qBAeC,iBAAiB;WACV;WACT,MAAM;EAEH,YAAA,iBAAiB,MAAM,cAAc;;;;;;;UCVlC;;EAEf;;EAEA,
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["Workflow","Operation","PolicyConfig","CheckResolver","Plan","OperationSpec","Finding","PolicyResult","Verdict","OperationOutcome","Plan","Operation","Runtime","pipeline","Runtime","Runtime","when","Expression","run","matrix"],"sources":["../src/planner/bind.ts","../src/planner/planner.ts","../src/planner/errors.ts","../src/planner/matrix.ts","../src/errors.ts","../src/types.ts","../src/compat/config.ts","../src/sverka.ts","../src/compat/helpers.ts","../src/dollar.ts","../src/shell.ts","../src/artifact.ts","../src/pipeline.ts","../src/call-pipeline.ts","../src/component.ts","../src/when.ts","../src/expr.ts","../src/status.ts","../src/images.ts","../src/context.ts","../src/agent.ts","../src/markdown.ts","../src/markdown-errors.ts"],"mappings":";;;;UAeiB;WACN,OAAO;WACP;WACA,SAAS,SAAS,eAAe;;;;;;wBAS5B,YAAY,SAAS,qBAAqB;;;;;;;wBAiO1C,sBACd,gBAAgB,kBAChB,oCACU;;;;;;UChNK;EACf,SAAS,SAAS,kBAAkB,QAAQ;EAC5C,KAAK,SAAS,iBAAiB,QAAQ;EACvC,YAAY,SAAS,qBAAqB;;wBAG5B,iBAAiB;UAIhB;EACf;EACA;EACA;;;;;;;;EAQA;;UAGe;EACf,SAAS;EACT,iBAAiB;EACjB;EACA;;;;;;;;qBCvEW,uBAAuB;WACzB,MAAM;WACG;EACN,YAAA,iBAAiB,MAAM,oBAAoB;;KAQ7C;;;;qBAUC,qBAAqB;WACvB,MAAM;WACG;EACN,YAAA,iBAAiB,MAAM,kBAAkB;;KAQ3C;;;;;;;;;;;;;;;wBCVI,kBACd,gBAAgB,4BACN;;;KC1BA;qBAeC,iBAAiB;WACV;WACT,MAAM;EAEH,YAAA,iBAAiB,MAAM,cAAc;;;;;;;UCVlC;;EAEf;;EAEA,UAAUA,aAAWC;;EAErB,SAASC;;;UAIM;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,WAAWC;;;UAII;EACf,KAAK,UAAU,gBAAgB,QAAQ;EACvC,OAAO,UAAU,gBAAgB,QAAQC;EACzC,QAA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;;wBAY5C,iBAAiB,eAAe,QAAQ;;;KC/ElD;;qBAOC,2BAA2B;WACrB,MAAM;EAEX,YAAA,iBAAiB,MAAM,wBAAwB"}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["basename","bindRunPlanImpl","computePlanId","createBuiltinResolver","validatePlan","extractFindings","loadBaseline","filterOnlyNew","createPolicy","DEFAULT_POLICY","evaluatePolicy","workflow","pipeline","when","run","matrix","parseYaml"],"sources":["../src/planner/internal/git-cli.ts","../src/planner/detect.ts","../src/planner/explain.ts","../src/planner/errors.ts","../src/planner/bind.ts","../src/planner/planner.ts","../src/planner/matrix.ts","../src/errors.ts","../src/compat/config.ts","../src/compat/convert.ts","../src/compat/internal/plan-runtime.ts","../src/sverka.ts","../src/compat/helpers.ts","../src/internal/is-reference.ts","../src/dollar.ts","../src/shell.ts","../src/artifact.ts","../src/pipeline.ts","../src/call-pipeline.ts","../src/component.ts","../src/when.ts","../src/expr.ts","../src/status.ts","../src/internal/proxy-props.ts","../src/images.ts","../src/context.ts","../src/agent.ts","../src/markdown-errors.ts","../src/markdown.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * A mockable seam over the `git` CLI. Unit tests mock this via `vi.mock`;\n * integration tests use the real implementation.\n *\n * NOT exported from the public API.\n */\nexport interface GitCli {\n /**\n * Run a git command in `cwd`, returning stdout. Rejects with an Error\n * whose `cause` carries stderr when the exit code is non-zero.\n */\n run(args: readonly string[], cwd: string): Promise<string>;\n}\n\n/**\n * Resolve the absolute path to the `git` executable by searching `PATH`\n * at this trusted parent level. The spawned child receives a minimal\n * environment without `PATH`, mitigating PATH-injection hotspots.\n */\nfunction resolveGitBinary(): string {\n const pathEnv = process.env.PATH ?? \"\";\n for (const dir of pathEnv.split(path.delimiter)) {\n if (!dir) continue;\n const candidate = path.join(dir, \"git\");\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n return \"git\";\n}\n\nconst GIT_BINARY = resolveGitBinary();\n\n/**\n * Default `GitCli` implementation backed by `node:child_process.spawn`.\n */\nexport function createGitCli(): GitCli {\n return {\n run(args, cwd) {\n return new Promise<string>((resolvePromise, reject) => {\n // Spawn the resolved git binary with a minimal, explicit environment\n // that does not propagate PATH into the child subprocess.\n const env: NodeJS.ProcessEnv = {\n HOME: process.env.HOME,\n GIT_TERMINAL_PROMPT: \"0\",\n };\n const child = spawn(GIT_BINARY, [...args], {\n cwd,\n env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.on(\"data\", (data: Buffer) => {\n stdout += data.toString();\n });\n child.stderr?.on(\"data\", (data: Buffer) => {\n stderr += data.toString();\n });\n child.on(\"error\", (err) => {\n reject(err);\n });\n child.on(\"close\", (code) => {\n if (code === 0) {\n resolvePromise(stdout);\n } else {\n reject(\n new Error(\n `git ${args.join(\" \")} exited ${code ?? -1}`,\n stderr.trim() ? { cause: stderr.trim() } : undefined,\n ),\n );\n }\n });\n });\n },\n };\n}\n","import type {\n LocalSignal,\n DetectedLanguage,\n DetectedPackageManager,\n PackageManagerName,\n MonorepoMarker,\n MonorepoTool,\n} from \"./planner.js\";\n\n// --- manifest / lockfile / dockerfile / ci / monorepo-marker rules ---\n\nconst MANIFEST_FILES: ReadonlySet<string> = new Set([\n \"package.json\",\n \"pyproject.toml\",\n \"Cargo.toml\",\n \"go.mod\",\n \"pom.xml\",\n \"build.gradle\",\n \"composer.json\",\n]);\n\nconst LOCKFILE_MAP: Readonly<Record<string, PackageManagerName>> = {\n \"bun.lock\": \"bun\",\n \"bun.lockb\": \"bun\",\n \"package-lock.json\": \"npm\",\n \"yarn.lock\": \"yarn\",\n \"pnpm-lock.yaml\": \"pnpm\",\n \"poetry.lock\": \"poetry\",\n \"Cargo.lock\": \"cargo\",\n \"go.sum\": \"go\",\n};\n\nconst MONOREPO_MARKER_FILES: Readonly<Record<string, MonorepoTool>> = {\n \"nx.json\": \"nx\",\n \"turbo.json\": \"turborepo\",\n \"lerna.json\": \"lerna\",\n \"pnpm-workspace.yaml\": \"pnpm-workspace\",\n};\n\n/**\n * Detect local signals from a file list. Pure: no I/O.\n */\nexport function detectSignals(files: readonly string[]): LocalSignal[] {\n const signals: LocalSignal[] = [];\n for (const file of files) {\n const base = basename(file);\n // manifest\n if (MANIFEST_FILES.has(base)) {\n signals.push({\n type: \"manifest\",\n path: file,\n detail: null,\n confidence: 1.0,\n });\n continue;\n }\n // lockfile\n if (Object.hasOwn(LOCKFILE_MAP, base)) {\n signals.push({\n type: \"lockfile\",\n path: file,\n detail: null,\n confidence: 1.0,\n });\n continue;\n }\n // dockerfile\n if (base === \"Dockerfile\" || base.endsWith(\".Dockerfile\")) {\n signals.push({\n type: \"dockerfile\",\n path: file,\n detail: null,\n confidence: 1.0,\n });\n continue;\n }\n // docker-compose\n if (base === \"docker-compose.yml\" || base === \"docker-compose.yaml\") {\n signals.push({\n type: \"docker-compose\",\n path: file,\n detail: null,\n confidence: 1.0,\n });\n continue;\n }\n // ci-definition\n if (isCiDefinition(file, base)) {\n signals.push({\n type: \"ci-definition\",\n path: file,\n detail: null,\n confidence: 1.0,\n });\n continue;\n }\n // monorepo-marker (file-based only; package.json workspaces handled in detectMonorepo)\n if (Object.hasOwn(MONOREPO_MARKER_FILES, base)) {\n signals.push({\n type: \"monorepo-marker\",\n path: file,\n detail: null,\n confidence: 1.0,\n });\n }\n }\n return signals;\n}\n\nfunction isCiDefinition(file: string, base: string): boolean {\n if (\n base === \".gitlab-ci.yml\" ||\n base === \"azure-pipelines.yml\" ||\n base === \"Jenkinsfile\"\n ) {\n return true;\n }\n if (\n file.startsWith(\".github/workflows/\") &&\n (base.endsWith(\".yml\") || base.endsWith(\".yaml\"))\n ) {\n return true;\n }\n if (file.startsWith(\".circleci/\")) {\n return true;\n }\n return false;\n}\n\n// --- language detection ---\n\nconst EXTENSION_MAP: Readonly<Record<string, string>> = {\n \".ts\": \"TypeScript\",\n \".tsx\": \"TypeScript\",\n \".js\": \"JavaScript\",\n \".jsx\": \"JavaScript\",\n \".mjs\": \"JavaScript\",\n \".cjs\": \"JavaScript\",\n \".py\": \"Python\",\n \".rs\": \"Rust\",\n \".go\": \"Go\",\n \".java\": \"Java\",\n \".kt\": \"Kotlin\",\n \".rb\": \"Ruby\",\n \".php\": \"PHP\",\n \".cs\": \"C#\",\n \".cpp\": \"C++\",\n \".cc\": \"C++\",\n \".cxx\": \"C++\",\n \".c\": \"C\",\n \".h\": \"C\",\n \".hpp\": \"C++\",\n \".swift\": \"Swift\",\n \".scala\": \"Scala\",\n \".sh\": \"Shell\",\n \".bash\": \"Shell\",\n};\n\nexport function detectLanguages(files: readonly string[]): DetectedLanguage[] {\n const counts = new Map<string, string[]>();\n for (const file of files) {\n const ext = extname(file);\n const lang = EXTENSION_MAP[ext];\n if (!lang) continue;\n const entry = counts.get(lang);\n if (entry) {\n entry.push(ext);\n } else {\n counts.set(lang, [ext]);\n }\n }\n const out: DetectedLanguage[] = [];\n for (const [name, exts] of counts) {\n const fileCount = exts.length;\n const confidence = Math.min(1.0, fileCount / 10);\n out.push({\n name,\n confidence,\n evidence: [...new Set(exts)],\n fileCount,\n });\n }\n out.sort((a, b) => b.fileCount - a.fileCount || a.name.localeCompare(b.name));\n return out;\n}\n\n// --- package manager detection ---\n\nconst MANIFEST_PACKAGE_MANAGER: Readonly<Record<string, PackageManagerName>> = {\n \"go.mod\": \"go\",\n \"Cargo.toml\": \"cargo\",\n};\n\nexport function detectPackageManagers(\n signals: readonly LocalSignal[],\n rootPkgJson: Record<string, unknown> | null,\n): DetectedPackageManager[] {\n const byName = new Map<PackageManagerName, DetectedPackageManager>();\n collectLockfilePackageManagers(signals, byName);\n collectManifestPackageManagers(signals, byName);\n applyPackageManagerField(rootPkgJson, byName);\n return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/** Populate `byName` from lockfile signals. */\nfunction collectLockfilePackageManagers(\n signals: readonly LocalSignal[],\n byName: Map<PackageManagerName, DetectedPackageManager>,\n): void {\n for (const sig of signals) {\n if (sig.type !== \"lockfile\") continue;\n const base = basename(sig.path);\n const name = LOCKFILE_MAP[base];\n if (!name) {\n // Unknown lockfile → \"other\"\n const other = byName.get(\"other\");\n if (other) {\n other.evidence.push(sig.path);\n } else {\n byName.set(\"other\", {\n name: \"other\",\n version: null,\n lockfile: sig.path,\n evidence: [sig.path],\n });\n }\n continue;\n }\n const existing = byName.get(name);\n if (existing) {\n if (!existing.evidence.includes(sig.path)) {\n existing.evidence.push(sig.path);\n }\n } else {\n byName.set(name, {\n name,\n version: null,\n lockfile: sig.path,\n evidence: [sig.path],\n });\n }\n }\n}\n\n/** Populate `byName` from manifest signals for ecosystems without a lockfile or when the manifest is the primary signal. */\nfunction collectManifestPackageManagers(\n signals: readonly LocalSignal[],\n byName: Map<PackageManagerName, DetectedPackageManager>,\n): void {\n for (const sig of signals) {\n if (sig.type !== \"manifest\") continue;\n const base = basename(sig.path);\n const name = MANIFEST_PACKAGE_MANAGER[base];\n if (!name || byName.has(name)) continue;\n byName.set(name, {\n name,\n version: null,\n lockfile: null,\n evidence: [sig.path],\n });\n }\n}\n\n/** Apply the `packageManager` field override from the root package.json. */\nfunction applyPackageManagerField(\n rootPkgJson: Record<string, unknown> | null,\n byName: Map<PackageManagerName, DetectedPackageManager>,\n): void {\n if (!rootPkgJson) return;\n const pm = rootPkgJson[\"packageManager\"];\n if (typeof pm !== \"string\") return;\n const { tool, version } = parsePackageManager(pm);\n if (!tool) return;\n const existing = byName.get(tool);\n if (existing) {\n existing.version = version;\n if (!existing.evidence.includes(\"package.json#packageManager\")) {\n existing.evidence.push(\"package.json#packageManager\");\n }\n } else {\n byName.set(tool, {\n name: tool,\n version,\n lockfile: null,\n evidence: [\"package.json#packageManager\"],\n });\n }\n}\n\nfunction parsePackageManager(pm: string): {\n tool: PackageManagerName | null;\n version: string | null;\n} {\n // e.g. \"bun@1.3.14\", \"pnpm@9.12.0\"\n const atIdx = pm.indexOf(\"@\");\n if (atIdx <= 0) return { tool: null, version: null };\n const toolName = pm.slice(0, atIdx);\n const version = pm.slice(atIdx + 1) || null;\n const valid: PackageManagerName[] = [\n \"npm\",\n \"yarn\",\n \"pnpm\",\n \"bun\",\n \"pip\",\n \"poetry\",\n \"uv\",\n \"pipenv\",\n \"cargo\",\n \"go\",\n \"maven\",\n \"gradle\",\n \"composer\",\n \"other\",\n ];\n if (!valid.includes(toolName as PackageManagerName)) {\n return { tool: null, version };\n }\n return { tool: toolName as PackageManagerName, version };\n}\n\n// --- monorepo detection ---\n\nexport function detectMonorepo(\n signals: readonly LocalSignal[],\n rootPkgJson: Record<string, unknown> | null,\n): MonorepoMarker | null {\n const globs = rootPkgJson\n ? extractWorkspaceGlobs(rootPkgJson[\"workspaces\"])\n : [];\n const workspaces = resolveWorkspaceDirs(signals, globs);\n\n // File-based markers first.\n for (const sig of signals) {\n if (sig.type !== \"monorepo-marker\") continue;\n const base = basename(sig.path);\n const tool = MONOREPO_MARKER_FILES[base];\n if (tool) {\n return {\n tool,\n workspaces,\n evidence:\n globs.length > 0 ? [sig.path, \"package.json#workspaces\"] : [sig.path],\n };\n }\n }\n\n // Root package.json with workspaces field.\n if (globs.length > 0 && rootPkgJson) {\n const tool: MonorepoTool = isBunWorkspace(rootPkgJson)\n ? \"bun-workspace\"\n : \"custom\";\n return {\n tool,\n workspaces,\n evidence: [\"package.json#workspaces\"],\n };\n }\n\n return null;\n}\n\n/**\n * Resolve workspace globs to concrete workspace dirs using manifest signals.\n * A dir is a workspace when `<dir>/package.json` appears as a manifest and\n * `<dir>` matches a workspace glob (`*` = one path segment, `**` = any depth).\n */\nfunction resolveWorkspaceDirs(\n signals: readonly LocalSignal[],\n globs: readonly string[],\n): string[] {\n const positive = globs.filter((g) => !g.startsWith(\"!\"));\n const negative = globs\n .filter((g) => g.startsWith(\"!\"))\n .map((g) => g.slice(1));\n const dirs = new Set<string>();\n for (const sig of signals) {\n if (sig.type !== \"manifest\" || !sig.path.endsWith(\"/package.json\"))\n continue;\n const dir = sig.path.slice(0, sig.path.length - \"/package.json\".length);\n if (\n positive.some((g) => matchesWorkspaceGlob(dir, g)) &&\n !negative.some((g) => matchesWorkspaceGlob(dir, g))\n ) {\n dirs.add(dir);\n }\n }\n return [...dirs].sort((a, b) => a.localeCompare(b));\n}\n\nfunction matchesWorkspaceGlob(dir: string, glob: string): boolean {\n const d = dir.split(\"/\");\n const g = glob.split(\"/\");\n const memo = new Map<string, boolean>();\n const match = (di: number, gi: number): boolean => {\n const key = `${di}:${gi}`;\n const cached = memo.get(key);\n if (cached !== undefined) return cached;\n let result: boolean;\n if (gi === g.length) {\n result = di === d.length;\n } else if (g[gi] === \"**\") {\n result = false;\n for (let k = di; k <= d.length && !result; k++) {\n result = match(k, gi + 1);\n }\n } else {\n result =\n di < d.length &&\n matchesGlobSegment(d[di] as string, g[gi] as string) &&\n match(di + 1, gi + 1);\n }\n memo.set(key, result);\n return result;\n };\n return match(0, 0);\n}\n\nfunction matchesGlobSegment(segment: string, pattern: string): boolean {\n let s = 0;\n let p = 0;\n let starP = -1;\n let starS = -1;\n while (s < segment.length) {\n if (\n p < pattern.length &&\n (pattern[p] === \"?\" || pattern[p] === segment[s])\n ) {\n s++;\n p++;\n } else if (p < pattern.length && pattern[p] === \"*\") {\n starP = p++;\n starS = s;\n } else if (starP !== -1) {\n p = starP + 1;\n s = ++starS;\n } else {\n return false;\n }\n }\n while (p < pattern.length && pattern[p] === \"*\") p++;\n return p === pattern.length;\n}\n\nfunction extractWorkspaceGlobs(ws: unknown): string[] {\n if (Array.isArray(ws)) {\n return ws.filter((g): g is string => typeof g === \"string\");\n }\n if (typeof ws === \"object\" && ws !== null) {\n const packages = (ws as Record<string, unknown>)[\"packages\"];\n if (Array.isArray(packages)) {\n return packages.filter((g): g is string => typeof g === \"string\");\n }\n }\n return [];\n}\n\nfunction isBunWorkspace(pkgJson: Record<string, unknown>): boolean {\n const pm = pkgJson[\"packageManager\"];\n return typeof pm === \"string\" && pm.startsWith(\"bun\");\n}\n\n// --- helpers ---\n\nfunction basename(path: string): string {\n const idx = path.lastIndexOf(\"/\");\n return idx >= 0 ? path.slice(idx + 1) : path;\n}\n\nfunction extname(path: string): string {\n const base = basename(path);\n const idx = base.lastIndexOf(\".\");\n return idx >= 0 ? base.slice(idx) : \"\";\n}\n","import type {\n LocalSignal,\n LocalSignalType,\n DiscoveryExplanation,\n} from \"./planner.js\";\n\nconst SIGNAL_TYPES: readonly LocalSignalType[] = [\n \"manifest\",\n \"lockfile\",\n \"dockerfile\",\n \"docker-compose\",\n \"ci-definition\",\n \"monorepo-marker\",\n \"git-metadata\",\n];\n\n/**\n * Build a `DiscoveryExplanation` from the collected signals. Pure.\n */\nexport function buildExplanation(\n signals: readonly LocalSignal[],\n opts: { hasBaseRef: boolean; dirty: boolean },\n): DiscoveryExplanation {\n const counts = {} as Record<LocalSignalType, number>;\n for (const t of SIGNAL_TYPES) {\n counts[t] = 0;\n }\n for (const sig of signals) {\n counts[sig.type] = (counts[sig.type] ?? 0) + 1;\n }\n\n const parts: string[] = [];\n const total = signals.length;\n parts.push(`${total} signal${total === 1 ? \"\" : \"s\"}`);\n const nonzero = SIGNAL_TYPES.filter((t) => counts[t] > 0);\n if (nonzero.length) {\n parts.push(`(${formatSignalCounts(nonzero, counts)})`);\n }\n if (opts.dirty) {\n parts.push(\"working tree dirty\");\n } else {\n parts.push(\"working tree clean\");\n }\n if (!opts.hasBaseRef) {\n parts.push(\"no baseRef provided\");\n }\n\n return {\n summary: parts.join(\" \"),\n signalCounts: counts,\n };\n}\n\n/** Format non-zero signal counts as \"type=count, type=count\". */\nfunction formatSignalCounts(\n types: readonly LocalSignalType[],\n counts: Readonly<Record<LocalSignalType, number>>,\n): string {\n return types.map((t) => t + \"=\" + counts[t]).join(\", \");\n}\n","/**\n * Base error class for the planner package. All discovery failures throw a\n * `DiscoveryError` with one of the four `DiscoveryErrorCode` values.\n */\nexport class DiscoveryError extends Error {\n readonly code: DiscoveryErrorCode;\n override readonly cause: unknown;\n constructor(message: string, code: DiscoveryErrorCode, cause?: unknown) {\n super(message);\n this.name = \"DiscoveryError\";\n this.code = code;\n this.cause = cause;\n }\n}\n\nexport type DiscoveryErrorCode =\n | \"ROOT_NOT_FOUND\"\n | \"GIT_UNAVAILABLE\"\n | \"GIT_NOT_A_REPO\"\n | \"TRAVERSAL_FAILED\"\n | \"INVALID_BASE_REF\";\n\n/**\n * Planner error for Run Plan binding failures. Spec 13 — Error handling.\n */\nexport class PlannerError extends Error {\n readonly code: PlannerErrorCode;\n override readonly cause: unknown;\n constructor(message: string, code: PlannerErrorCode, cause?: unknown) {\n super(message);\n this.name = \"PlannerError\";\n this.code = code;\n this.cause = cause;\n }\n}\n\nexport type PlannerErrorCode =\n | \"ENTRY_NOT_FOUND\"\n | \"ROOT_NOT_FOUND\"\n | \"MISSING_INPUT\"\n | \"INVALID_INPUT\"\n | \"INVALID_GRAPH\"\n | \"INVALID_MATRIX\";\n","// Run Plan binding — binds a Definition Graph's Entry + inputs into a RunPlan.\n// Spec 13 — §22.1 component 1. Architecture spec §10, §22.\n\nimport type {\n DefinitionGraph,\n StepDefinition,\n PipelineDefinition,\n EntryDefinition,\n Input,\n} from \"@sverka/workflow\";\nimport { validateGraph, expandPipelineCalls } from \"@sverka/workflow\";\nimport type { RunPlan, InputValue, BoundEntry } from \"@sverka/workflow\";\nimport { computeGraphId, computeRunPlanId } from \"@sverka/workflow\";\nimport { PlannerError } from \"./errors.js\";\n\nexport interface BindRunPlanOptions {\n readonly graph: DefinitionGraph;\n readonly entryId: string;\n readonly inputs?: Readonly<Record<string, InputValue>>;\n}\n\nconst INPUT_TYPES = new Set<Input[\"type\"]>([\"string\", \"number\", \"boolean\"]);\n\n/**\n * Bind a Definition Graph's Entry + user inputs into a concrete RunPlan\n * that the native engine can execute.\n */\nexport function bindRunPlan(options: BindRunPlanOptions): RunPlan {\n const { graph, entryId, inputs } = options;\n\n validateGraphShape(graph);\n\n if (graph.project.pipelines.length === 0) {\n throw new PlannerError(\"graph has no pipelines\", \"INVALID_GRAPH\");\n }\n\n const { pipeline, entry } = findEntry(graph, entryId);\n validateRoots(pipeline, entry);\n validatePipeline(graph, pipeline);\n\n const reachableSteps = computeReachableSteps(pipeline.steps, entry.roots);\n // Expand pipeline-call steps into inline callee steps for the native engine.\n const expandedSteps = expandPipelineCalls(graph, reachableSteps);\n const boundInputs = bindInputs(pipeline.inputs, inputs);\n\n const graphId = computeGraphId(graph);\n\n const boundEntry: BoundEntry = {\n id: entry.id,\n trigger: entry.trigger,\n };\n\n const planBody = {\n apiVersion: \"sverka.dev/v1run\" as const,\n graphId,\n entry: boundEntry,\n inputs: boundInputs,\n steps: expandedSteps,\n };\n\n const id = computeRunPlanId(planBody as Omit<RunPlan, \"id\" | \"createdAt\">);\n\n const createdAt = new Date().toISOString();\n\n return {\n apiVersion: \"sverka.dev/v1run\",\n id,\n graphId,\n entry: boundEntry,\n inputs: boundInputs,\n steps: expandedSteps,\n createdAt,\n };\n}\n\n/**\n * Validate that the runtime value has the shape of a DefinitionGraph before\n * any field is dereferenced. Malformed values become PlannerError(INVALID_GRAPH)\n * instead of TypeError.\n */\nfunction validateGraphShape(value: DefinitionGraph): void {\n const graph = value as unknown as Record<string, unknown>;\n\n if (typeof graph !== \"object\" || graph === null) {\n throw new PlannerError(\"graph must be an object\", \"INVALID_GRAPH\");\n }\n\n const project = graph.project;\n if (typeof project !== \"object\" || project === null) {\n throw new PlannerError(\"graph.project must be an object\", \"INVALID_GRAPH\");\n }\n\n const pipelines = (project as Record<string, unknown>).pipelines;\n if (!Array.isArray(pipelines)) {\n throw new PlannerError(\n \"graph.project.pipelines must be an array\",\n \"INVALID_GRAPH\",\n );\n }\n\n for (let i = 0; i < pipelines.length; i++) {\n const pipeline = pipelines[i] as Record<string, unknown>;\n validatePipelineShape(pipeline, i);\n }\n}\n\nfunction validatePipelineShape(value: unknown, index: number): void {\n const pipeline = value as Record<string, unknown>;\n if (typeof pipeline !== \"object\" || pipeline === null) {\n throw new PlannerError(\n `graph.project.pipelines[${index}] must be an object`,\n \"INVALID_GRAPH\",\n );\n }\n validatePipelineFields(pipeline, index);\n validatePipelineChildren(pipeline, index);\n}\n\nfunction validatePipelineFields(\n pipeline: Record<string, unknown>,\n index: number,\n): void {\n if (typeof pipeline.id !== \"string\") {\n throw new PlannerError(\n `graph.project.pipelines[${index}].id must be a string`,\n \"INVALID_GRAPH\",\n );\n }\n if (!Array.isArray(pipeline.entries)) {\n throw new PlannerError(\n `graph.project.pipelines[${index}].entries must be an array`,\n \"INVALID_GRAPH\",\n );\n }\n if (!Array.isArray(pipeline.steps)) {\n throw new PlannerError(\n `graph.project.pipelines[${index}].steps must be an array`,\n \"INVALID_GRAPH\",\n );\n }\n if (\n typeof pipeline.inputs !== \"object\" ||\n pipeline.inputs === null ||\n Array.isArray(pipeline.inputs)\n ) {\n throw new PlannerError(\n `graph.project.pipelines[${index}].inputs must be an object`,\n \"INVALID_GRAPH\",\n );\n }\n}\n\nfunction validatePipelineChildren(\n pipeline: Record<string, unknown>,\n index: number,\n): void {\n const inputs = pipeline.inputs as Record<string, unknown>;\n for (const [name, descriptor] of Object.entries(inputs)) {\n validateInputDescriptor(descriptor, index, name);\n }\n const entries = pipeline.entries;\n if (!Array.isArray(entries)) return;\n const steps = pipeline.steps;\n if (!Array.isArray(steps)) return;\n for (let j = 0; j < entries.length; j++) {\n validateEntryShape(entries[j], index, j);\n }\n for (let j = 0; j < steps.length; j++) {\n validateStepShape(steps[j], index, j);\n }\n}\n\nfunction validateInputDescriptor(\n value: unknown,\n pipelineIndex: number,\n name: string,\n): void {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].inputs.${name} must be an object`,\n \"INVALID_GRAPH\",\n );\n }\n\n const descriptor = value as Record<string, unknown>;\n const type = descriptor.type;\n if (type !== undefined && !INPUT_TYPES.has(type as Input[\"type\"])) {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].inputs.${name} has invalid type`,\n \"INVALID_GRAPH\",\n );\n }\n}\n\nfunction validateEntryShape(\n value: unknown,\n pipelineIndex: number,\n index: number,\n): void {\n const entry = value as Record<string, unknown>;\n if (typeof entry !== \"object\" || entry === null) {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].entries[${index}] must be an object`,\n \"INVALID_GRAPH\",\n );\n }\n if (typeof entry.id !== \"string\") {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].entries[${index}].id must be a string`,\n \"INVALID_GRAPH\",\n );\n }\n if (!Array.isArray(entry.roots)) {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].entries[${index}].roots must be an array`,\n \"INVALID_GRAPH\",\n );\n }\n}\n\nfunction validateStepShape(\n value: unknown,\n pipelineIndex: number,\n index: number,\n): void {\n const step = value as Record<string, unknown>;\n if (typeof step !== \"object\" || step === null) {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].steps[${index}] must be an object`,\n \"INVALID_GRAPH\",\n );\n }\n if (typeof step.id !== \"string\") {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].steps[${index}].id must be a string`,\n \"INVALID_GRAPH\",\n );\n }\n if (!Array.isArray(step.dependencies)) {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].steps[${index}].dependencies must be an array`,\n \"INVALID_GRAPH\",\n );\n }\n}\n\n/**\n * Compute the transitive closure of reachable steps from the given roots.\n * A step is reachable if it is connected to a root by following\n * `dependencies[].producer` edges backward (i.e. the root's prerequisites).\n * Returns steps in the original graph order, filtered to reachable steps.\n */\nexport function computeReachableSteps(\n steps: readonly StepDefinition[],\n roots: readonly string[],\n): readonly StepDefinition[] {\n const producerMap = buildProducerMap(steps);\n\n const reachable = new Set<string>();\n const queue: string[] = [];\n\n for (const id of roots) {\n if (!reachable.has(id)) {\n reachable.add(id);\n queue.push(id);\n }\n }\n\n let head = 0;\n while (head < queue.length) {\n const id = queue[head]!;\n head++;\n for (const producer of producerMap.get(id) ?? []) {\n if (!reachable.has(producer)) {\n reachable.add(producer);\n queue.push(producer);\n }\n }\n }\n\n return steps.filter((s) => reachable.has(s.id));\n}\n\n/**\n * Build a map from each step id to the list of producer step ids it depends on.\n */\nfunction buildProducerMap(\n steps: readonly StepDefinition[],\n): Map<string, string[]> {\n const map = new Map<string, string[]>();\n for (const step of steps) {\n const producers: string[] = [];\n map.set(step.id, producers);\n for (const dep of step.dependencies) {\n producers.push(dep.producer);\n }\n }\n return map;\n}\n\nfunction findEntry(\n graph: DefinitionGraph,\n entryId: string,\n): { pipeline: PipelineDefinition; entry: EntryDefinition } {\n for (const pipeline of graph.project.pipelines) {\n const entry = pipeline.entries.find((e) => e.id === entryId);\n if (entry) return { pipeline, entry };\n }\n throw new PlannerError(`entry \"${entryId}\" not found`, \"ENTRY_NOT_FOUND\");\n}\n\nfunction validateRoots(\n pipeline: PipelineDefinition,\n entry: EntryDefinition,\n): void {\n const stepIds = new Set(pipeline.steps.map((s) => s.id));\n for (const root of entry.roots) {\n if (!stepIds.has(root)) {\n throw new PlannerError(\n `entry root \"${root}\" not found in pipeline steps`,\n \"ROOT_NOT_FOUND\",\n );\n }\n }\n}\n\nfunction validatePipeline(\n graph: DefinitionGraph,\n pipeline: PipelineDefinition,\n): void {\n try {\n validateGraph({\n project: {\n id: graph.project.id,\n pipelines: [pipeline],\n },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new PlannerError(message, \"INVALID_GRAPH\", err);\n }\n}\n\nfunction bindInputs(\n pipelineInputs: Readonly<Record<string, Input>>,\n userInputs: Readonly<Record<string, InputValue>> | undefined,\n): Readonly<Record<string, InputValue>> {\n const result: Record<string, InputValue> = {};\n\n for (const [name, input] of Object.entries(pipelineInputs)) {\n const type = input.type as Input[\"type\"] | undefined;\n validateInputType(name, type);\n\n if (input.secret) {\n // Secret values are not embedded in the RunPlan. They are resolved at\n // runtime from a secrets context by name.\n continue;\n }\n\n const userValue = userInputs?.[name];\n if (userValue !== undefined) {\n assertInputValue(userValue, type, name);\n result[name] = userValue;\n continue;\n }\n\n if (input.default !== undefined) {\n assertInputValue(input.default, type, name);\n result[name] = input.default;\n continue;\n }\n\n if (input.required ?? true) {\n throw new PlannerError(\n `required input \"${name}\" has no value and no default`,\n \"MISSING_INPUT\",\n );\n }\n }\n\n return result;\n}\n\nfunction validateInputType(\n name: string,\n type: Input[\"type\"] | undefined,\n): asserts type is Input[\"type\"] {\n if (type === undefined || !INPUT_TYPES.has(type)) {\n throw new PlannerError(\n `input \"${name}\" has no valid declared type`,\n \"INVALID_GRAPH\",\n );\n }\n}\n\nfunction assertInputValue(\n value: InputValue,\n type: Input[\"type\"],\n name: string,\n): void {\n if (type === \"array\") {\n if (\n !Array.isArray(value) ||\n !value.every((item) => typeof item === \"string\")\n ) {\n throw new PlannerError(\n `input \"${name}\" value ${JSON.stringify(value)} does not match declared type \"array\" (expected string array)`,\n \"INVALID_INPUT\",\n );\n }\n return;\n }\n const expected = type === \"choice\" ? \"string\" : type;\n const actual = typeof value;\n if (actual !== expected) {\n throw new PlannerError(\n `input \"${name}\" value ${JSON.stringify(value)} does not match declared type \"${type}\"`,\n \"INVALID_INPUT\",\n );\n }\n}\n","import type {\n ProjectContext,\n ChangedFile,\n DetectedLanguage,\n PackageManagerName,\n DetectedPackageManager,\n MonorepoTool,\n MonorepoMarker,\n LocalSignalType,\n LocalSignal,\n ProposedCheck,\n DiscoveryExplanation,\n} from \"@sverka/workflow\";\nexport type {\n ProjectContext,\n ChangedFile,\n DetectedLanguage,\n PackageManagerName,\n DetectedPackageManager,\n MonorepoTool,\n MonorepoMarker,\n LocalSignalType,\n LocalSignal,\n ProposedCheck,\n DiscoveryExplanation,\n};\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { createGitCli, type GitCli } from \"./internal/git-cli.js\";\nimport {\n detectSignals,\n detectLanguages,\n detectPackageManagers,\n detectMonorepo,\n} from \"./detect.js\";\nimport { buildExplanation } from \"./explain.js\";\nimport { DiscoveryError } from \"./errors.js\";\nimport {\n bindRunPlan as bindRunPlanImpl,\n type BindRunPlanOptions,\n} from \"./bind.js\";\nimport type { RunPlan } from \"@sverka/workflow\";\n\n/**\n * Top-level entry point for discovery and plan synthesis.\n */\nexport interface Planner {\n discover(options: DiscoverOptions): Promise<ProjectContext>;\n plan(context: ProjectContext): Promise<PlanProposal>;\n bindRunPlan(options: BindRunPlanOptions): RunPlan;\n}\n\nexport function createPlanner(): Planner {\n return new PlannerImpl();\n}\n\nexport interface DiscoverOptions {\n root: string;\n baseRef?: string;\n maxDepth?: number;\n /**\n * When true and `root` is a subdirectory of the git repository, detection\n * signals, languages, and package managers are computed from the subtree\n * under `root` instead of the whole repository. Use for commands whose\n * generated steps execute with cwd=`root` (e.g. `init --detect`). Git\n * metadata (commit, dirty, changedFiles) stays repository-wide.\n */\n scopeToRoot?: boolean;\n}\n\nexport interface PlanProposal {\n context: ProjectContext;\n checks: readonly ProposedCheck[];\n workflowPath: string | null;\n notes: readonly string[];\n}\n\nconst DEFAULT_MAX_DEPTH = 10;\n\nclass PlannerImpl implements Planner {\n private readonly git: GitCli;\n\n constructor() {\n this.git = createGitCli();\n }\n\n async discover(options: DiscoverOptions): Promise<ProjectContext> {\n const root = options.root;\n if (!existsSync(root)) {\n throw new DiscoveryError(\n `root directory not found: ${root}`,\n \"ROOT_NOT_FOUND\",\n );\n }\n await assertGitAvailable(this.git, root);\n const toplevel = await resolveToplevel(this.git, root);\n const { tracked, untracked, porcelain } = await collectGitFiles(\n this.git,\n toplevel,\n );\n const allFiles = [...new Set([...tracked, ...untracked])];\n const scoped =\n options.scopeToRoot === true\n ? scopeFilesToRoot(allFiles, toplevel, root)\n : null;\n const projectRoot = scoped?.dir ?? toplevel;\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;\n const filtered = applyMaxDepth(scoped?.files ?? allFiles, maxDepth);\n\n const signals = detectSignals(filtered);\n const languages = detectLanguages(filtered);\n const rootPkgJson = readRootPackageJson(projectRoot);\n const packageManagers = detectPackageManagers(signals, rootPkgJson);\n const monorepo = detectMonorepo(signals, rootPkgJson);\n const hasContainerBuild = signals.some(\n (s) => s.type === \"dockerfile\" || s.type === \"docker-compose\",\n );\n const hasCiDefinition = signals.some((s) => s.type === \"ci-definition\");\n\n const commit = await resolveHeadCommit(this.git, toplevel);\n const dirty = porcelain.length > 0;\n const changedFiles = await collectChangedFiles(\n this.git,\n toplevel,\n options.baseRef,\n );\n\n const gitSignal: LocalSignal = {\n type: \"git-metadata\",\n path: \".git\",\n detail: commit ? `HEAD=${commit.slice(0, 12)}` : \"no commits\",\n confidence: 1.0,\n };\n const allSignals = [...signals, gitSignal];\n\n const explanation = buildExplanation(allSignals, {\n hasBaseRef: Boolean(options.baseRef),\n dirty,\n });\n\n return {\n root: projectRoot,\n commit,\n dirty,\n changedFiles,\n languages,\n packageManagers,\n hasContainerBuild,\n hasCiDefinition,\n monorepo,\n localSignals: allSignals,\n explanation,\n };\n }\n\n async plan(context: ProjectContext): Promise<PlanProposal> {\n return synthesizePlan(context);\n }\n\n bindRunPlan(options: BindRunPlanOptions): RunPlan {\n return bindRunPlanImpl(options);\n }\n}\n\nfunction applyMaxDepth(files: string[], maxDepth: number): string[] {\n return files.filter((f) => f.split(\"/\").length <= maxDepth);\n}\n\n/**\n * Restrict repo-relative `files` to the subtree under `root`, re-rooting\n * paths relative to `root`. Returns null when `root` is not inside the\n * repository (should not happen — toplevel is resolved from `root`).\n */\nfunction scopeFilesToRoot(\n files: readonly string[],\n toplevel: string,\n root: string,\n): { dir: string; files: string[] } | null {\n const dir = realpathSync(resolve(root));\n // Git paths are always slash-separated — normalize for Windows.\n const prefix = relative(toplevel, dir).split(sep).join(\"/\");\n if (prefix.startsWith(\"..\") || isAbsolute(prefix)) return null;\n if (prefix === \"\") return { dir, files: [...files] };\n const scoped = files\n .filter((f) => f.startsWith(prefix + \"/\"))\n .map((f) => f.slice(prefix.length + 1));\n return { dir, files: scoped };\n}\n\n/** Throw `GIT_UNAVAILABLE` if git is not on PATH. */\nasync function assertGitAvailable(git: GitCli, root: string): Promise<void> {\n try {\n await git.run([\"--version\"], root);\n } catch (err) {\n throw new DiscoveryError(\n \"git is not installed or not on PATH\",\n \"GIT_UNAVAILABLE\",\n err,\n );\n }\n}\n\n/** Resolve the repository toplevel, throwing `GIT_NOT_A_REPO` on failure. */\nasync function resolveToplevel(git: GitCli, root: string): Promise<string> {\n try {\n const out = await git.run([\"rev-parse\", \"--show-toplevel\"], root);\n return out.trim();\n } catch (err) {\n throw new DiscoveryError(\n `not a git repository: ${root}`,\n \"GIT_NOT_A_REPO\",\n err,\n );\n }\n}\n\n/** Collect tracked files, untracked files, and porcelain lines from git. */\nasync function collectGitFiles(\n git: GitCli,\n toplevel: string,\n): Promise<{ tracked: string[]; untracked: string[]; porcelain: string[] }> {\n let trackedRaw: string;\n let porcelainRaw: string;\n try {\n trackedRaw = await git.run([\"ls-files\"], toplevel);\n porcelainRaw = await git.run([\"status\", \"--porcelain\", \"-uall\"], toplevel);\n } catch (err) {\n throw new DiscoveryError(\n \"filesystem traversal failed\",\n \"TRAVERSAL_FAILED\",\n err,\n );\n }\n const tracked = trackedRaw.split(\"\\n\").filter(Boolean);\n const porcelain = porcelainRaw.split(\"\\n\").filter(Boolean);\n const untracked = extractUntracked(porcelain);\n return { tracked, untracked, porcelain };\n}\n\n/** Extract untracked file paths from porcelain status lines. */\nfunction extractUntracked(porcelain: readonly string[]): string[] {\n const untracked: string[] = [];\n for (const line of porcelain) {\n const status = line.slice(0, 2);\n const path = line.slice(3).trim();\n if (status.includes(\"??\")) {\n untracked.push(path);\n }\n }\n return untracked;\n}\n\n/** Resolve the HEAD commit SHA, returning \"\" on failure. */\nasync function resolveHeadCommit(\n git: GitCli,\n toplevel: string,\n): Promise<string> {\n try {\n const out = await git.run([\"rev-parse\", \"HEAD\"], toplevel);\n return out.trim();\n } catch {\n return \"\";\n }\n}\n\nconst REF_RE = /^[A-Za-z0-9_./~^\\-@{}]+$/;\n\nfunction validateBaseRef(baseRef: string): void {\n if (baseRef.startsWith(\"-\") || !REF_RE.test(baseRef)) {\n throw new DiscoveryError(`invalid baseRef: ${baseRef}`, \"INVALID_BASE_REF\");\n }\n}\n\n/** Collect changed files against `baseRef` when provided. */\nasync function collectChangedFiles(\n git: GitCli,\n toplevel: string,\n baseRef: string | undefined,\n): Promise<ChangedFile[]> {\n if (!baseRef) return [];\n validateBaseRef(baseRef);\n try {\n const diff = await git.run(\n [\"diff\", \"--name-status\", `${baseRef}...HEAD`, \"--\"],\n toplevel,\n );\n return parseDiffNameStatus(diff);\n } catch (err) {\n throw new DiscoveryError(\n `failed to diff against baseRef \"${baseRef}\"`,\n \"TRAVERSAL_FAILED\",\n err,\n );\n }\n}\n\nfunction readRootPackageJson(root: string): Record<string, unknown> | null {\n try {\n const raw = readFileSync(`${root}/package.json`, \"utf8\");\n return JSON.parse(raw) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\nfunction parseDiffNameStatus(diff: string): ChangedFile[] {\n const out: ChangedFile[] = [];\n for (const line of diff.split(\"\\n\").filter(Boolean)) {\n const parts = line.split(\"\\t\");\n const code = parts[0] ?? \"\";\n // Rename records have the format \"R<score>\\told\\tnew\"; use the new path.\n const path = code.startsWith(\"R\") ? (parts[2] ?? \"\") : (parts[1] ?? \"\");\n if (!path) continue;\n out.push({ path, status: diffStatusCode(code) });\n }\n return out;\n}\n\n/** Map a git diff --name-status code to a `ChangedFile` status. */\nfunction diffStatusCode(code: string): ChangedFile[\"status\"] {\n if (code.startsWith(\"A\")) return \"added\";\n if (code.startsWith(\"M\")) return \"modified\";\n if (code.startsWith(\"D\")) return \"deleted\";\n if (code.startsWith(\"R\")) return \"renamed\";\n return \"modified\";\n}\n\ninterface PlanDriver {\n checkId: string;\n reason: string;\n languages: string[];\n packageManagers: PackageManagerName[];\n}\n\nconst PLAN_DRIVERS: readonly PlanDriver[] = [\n {\n checkId: \"typecheck\",\n reason: \"Node project defaults\",\n languages: [\"TypeScript\", \"JavaScript\"],\n packageManagers: [\"npm\", \"yarn\", \"pnpm\", \"bun\"],\n },\n {\n checkId: \"lint\",\n reason: \"Node project defaults\",\n languages: [\"TypeScript\", \"JavaScript\"],\n packageManagers: [\"npm\", \"yarn\", \"pnpm\", \"bun\"],\n },\n {\n checkId: \"test\",\n reason: \"Node project defaults\",\n languages: [\"TypeScript\", \"JavaScript\"],\n packageManagers: [\"npm\", \"yarn\", \"pnpm\", \"bun\"],\n },\n {\n checkId: \"lint\",\n reason: \"Python project defaults\",\n languages: [\"Python\"],\n packageManagers: [\"pip\", \"poetry\", \"uv\", \"pipenv\"],\n },\n {\n checkId: \"test\",\n reason: \"Python project defaults\",\n languages: [\"Python\"],\n packageManagers: [\"pip\", \"poetry\", \"uv\", \"pipenv\"],\n },\n {\n checkId: \"fmt-check\",\n reason: \"Rust project defaults\",\n languages: [\"Rust\"],\n packageManagers: [\"cargo\"],\n },\n {\n checkId: \"clippy\",\n reason: \"Rust project defaults\",\n languages: [\"Rust\"],\n packageManagers: [\"cargo\"],\n },\n {\n checkId: \"test\",\n reason: \"Rust project defaults\",\n languages: [\"Rust\"],\n packageManagers: [\"cargo\"],\n },\n {\n checkId: \"vet\",\n reason: \"Go project defaults\",\n languages: [\"Go\"],\n packageManagers: [\"go\"],\n },\n {\n checkId: \"test\",\n reason: \"Go project defaults\",\n languages: [\"Go\"],\n packageManagers: [\"go\"],\n },\n];\n\nfunction synthesizePlan(context: ProjectContext): PlanProposal {\n const langNames = context.languages.map((l) => l.name);\n const pmNames = context.packageManagers.map((p) => p.name);\n const signalRef = resolveSignalRef(context.localSignals);\n const checks = collectDefaultChecks(\n PLAN_DRIVERS,\n langNames,\n pmNames,\n signalRef,\n );\n const notes = buildPlanNotes(checks, langNames, pmNames);\n return { context, checks, workflowPath: null, notes };\n}\n\n/** Resolve the signal reference for the first manifest/lockfile signal. */\nfunction resolveSignalRef(signals: readonly LocalSignal[]): string | null {\n const manifestSignal =\n signals.find((s) => s.type === \"manifest\" || s.type === \"lockfile\") ?? null;\n return manifestSignal\n ? `${manifestSignal.type}:${manifestSignal.path}`\n : null;\n}\n\n/** Collect deduplicated default checks that match the detected languages/package managers. */\nfunction collectDefaultChecks(\n drivers: readonly PlanDriver[],\n langNames: readonly string[],\n pmNames: readonly PackageManagerName[],\n signalRef: string | null,\n): ProposedCheck[] {\n const checks: ProposedCheck[] = [];\n const seen = new Set<string>();\n for (const driver of drivers) {\n const langMatch = driver.languages.some((l) => langNames.includes(l));\n const pmMatch = driver.packageManagers.some((p) => pmNames.includes(p));\n if (!langMatch || !pmMatch) continue;\n const key = `${driver.checkId}:${driver.reason}`;\n if (seen.has(key)) continue;\n seen.add(key);\n const id = makeCheckId(driver.checkId, driver.reason);\n checks.push({\n id,\n checkId: driver.checkId,\n reason: driver.reason,\n signalRef,\n priority: 2,\n });\n }\n return checks;\n}\n\n/** Build a stable proposed-check id from its checkId and reason. */\nfunction makeCheckId(checkId: string, reason: string): string {\n const digest = createHash(\"sha256\")\n .update(checkId + reason)\n .digest(\"hex\")\n .slice(0, 16);\n return \"prop-\" + digest;\n}\n\n/** Build human-readable notes describing the selected checks. */\nfunction buildPlanNotes(\n checks: readonly ProposedCheck[],\n langNames: readonly string[],\n pmNames: readonly PackageManagerName[],\n): string[] {\n if (checks.length === 0) {\n return [\n \"No default checks applied: no recognized languages or package managers detected.\",\n ];\n }\n const drivers: string[] = [];\n if (langNames.length) drivers.push(`languages=[${langNames.join(\",\")}]`);\n if (pmNames.length) drivers.push(`packageManagers=[${pmNames.join(\",\")}]`);\n return [\n `Selected ${checks.length} default checks from ${drivers.join(\" \")}.`,\n ];\n}\n","// Matrix expansion — expands matrix steps into concrete step instances.\n// F-15 — plan-time expansion for the native engine.\n\nimport type {\n StepDefinition,\n Dependency,\n MatrixSpec,\n MatrixValue,\n Reference,\n} from \"@sverka/workflow\";\nimport { PlannerError } from \"./errors.js\";\n\ntype MatrixCombination = Record<string, MatrixValue>;\n\n/**\n * Expand all matrix steps in a step list into concrete step instances.\n * Non-matrix steps pass through unchanged.\n *\n * - Each matrix step becomes N steps, one per combination (cross-product of\n * dimensions, minus exclude, plus include).\n * - Each expanded step gets `matrixValues` (the concrete bindings) and\n * `matrix: undefined` (the spec is consumed).\n * - Expanded step IDs: `<originalId>[key=val,key=val]` (keys sorted alphabetically).\n * - Dependencies are rewired: a dependency on a matrix step maps to ALL\n * expanded instances (all-to-all, no correlation matching in M1).\n */\nexport function expandMatrixSteps(\n steps: readonly StepDefinition[],\n): readonly StepDefinition[] {\n const expansionMap = new Map<string, StepDefinition[]>();\n let hasMatrix = false;\n for (const step of steps) {\n if (step.matrix) {\n hasMatrix = true;\n expansionMap.set(step.id, expandStep(step));\n } else {\n expansionMap.set(step.id, [step]);\n }\n }\n\n if (!hasMatrix) {\n return steps;\n }\n\n const result: StepDefinition[] = [];\n for (const step of steps) {\n const expanded = expansionMap.get(step.id)!;\n for (const expStep of expanded) {\n result.push(rewireDependencies(expStep, expansionMap));\n }\n }\n return result;\n}\n\nfunction expandStep(step: StepDefinition): StepDefinition[] {\n const spec = step.matrix!;\n\n if (spec.maxParallel !== undefined) {\n if (!Number.isInteger(spec.maxParallel) || spec.maxParallel < 1) {\n throw new PlannerError(\n `matrix on step '${step.id}' has invalid maxParallel: must be a positive integer (got ${spec.maxParallel})`,\n \"INVALID_MATRIX\",\n );\n }\n }\n\n const combinations = computeCombinations(spec);\n\n if (combinations.length === 0) {\n throw new PlannerError(\n `matrix on step '${step.id}' produced no combinations (check exclude rules)`,\n \"INVALID_MATRIX\",\n );\n }\n\n return combinations.map((combo) => {\n const { matrix: _consumed, ...rest } = step;\n return {\n ...rest,\n id: formatExpandedId(step.id, combo),\n matrixValues: combo,\n dependencies: step.dependencies,\n ...(spec.failFast !== undefined ? { matrixFailFast: spec.failFast } : {}),\n ...(spec.maxParallel !== undefined\n ? { matrixMaxParallel: spec.maxParallel }\n : {}),\n };\n });\n}\n\nfunction computeCombinations(spec: MatrixSpec): readonly MatrixCombination[] {\n const keys = Object.keys(spec.dimensions);\n if (keys.length === 0) {\n return (spec.include ?? []).map((e) => ({ ...e }));\n }\n\n const combinations = applyExcludes(\n crossProduct(spec.dimensions, keys),\n spec.exclude ?? [],\n );\n return mergeIncludes(combinations, spec.include ?? []);\n}\n\n/**\n * Compute the cross-product of all matrix dimensions.\n * Throws INVALID_MATRIX if any dimension has no values.\n */\nfunction crossProduct(\n dimensions: Readonly<Record<string, readonly MatrixValue[]>>,\n keys: readonly string[],\n): MatrixCombination[] {\n let combinations: MatrixCombination[] = [{}];\n for (const key of keys) {\n const values = dimensions[key];\n if (!values || values.length === 0) {\n throw new PlannerError(\n `matrix dimension '${key}' has no values`,\n \"INVALID_MATRIX\",\n );\n }\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 return combinations;\n}\n\n/** Filter out combinations matching any exclude rule (partial match). */\nfunction applyExcludes(\n combinations: readonly MatrixCombination[],\n exclude: readonly Readonly<Record<string, MatrixValue>>[],\n): MatrixCombination[] {\n if (exclude.length === 0) return [...combinations];\n return combinations.filter((c) => !matchesAnyRule(c, exclude));\n}\n\n/** Merge include entries, deduplicating against existing combinations. */\nfunction mergeIncludes(\n combinations: readonly MatrixCombination[],\n include: readonly Readonly<Record<string, MatrixValue>>[],\n): readonly MatrixCombination[] {\n const includeEntries = include.map((e) => ({ ...e }));\n const existingKeys = new Set(combinations.map(comboKey));\n const uniqueIncludes = includeEntries.filter(\n (e) => !existingKeys.has(comboKey(e)),\n );\n return [...combinations, ...uniqueIncludes];\n}\n\nfunction matchesAnyRule(\n combo: MatrixCombination,\n rules: readonly Readonly<Record<string, MatrixValue>>[],\n): boolean {\n for (const rule of rules) {\n const entries = Object.entries(rule);\n if (entries.length === 0) continue;\n if (entries.every(([k, v]) => combo[k] === v)) return true;\n }\n return false;\n}\n\n/** Produce a deterministic string key for a combination (sorted key=value pairs). */\nfunction comboKey(combo: MatrixCombination): string {\n return Object.keys(combo)\n .sort((a, b) => a.localeCompare(b))\n .map((k) => `${k}=${String(combo[k])}`)\n .join(\",\");\n}\n\nfunction formatExpandedId(id: string, combo: MatrixCombination): string {\n const parts = Object.keys(combo)\n .sort((a, b) => a.localeCompare(b))\n .map((k) => `${k}=${combo[k]}`);\n return `${id}[${parts.join(\",\")}]`;\n}\n\nfunction rewireDependencies(\n step: StepDefinition,\n expansionMap: Map<string, StepDefinition[]>,\n): StepDefinition {\n const hasDeps = step.dependencies.length > 0;\n const hasInputs = step.inputs.length > 0;\n if (!hasDeps && !hasInputs) return step;\n\n const newDeps = hasDeps\n ? rewireDeps(step.dependencies, expansionMap)\n : step.dependencies;\n const newInputs = hasInputs\n ? rewireInputs(step.inputs, expansionMap)\n : step.inputs;\n\n return { ...step, dependencies: newDeps, inputs: newInputs };\n}\n\nfunction rewireDeps(\n deps: readonly Dependency[],\n expansionMap: Map<string, StepDefinition[]>,\n): Dependency[] {\n const newDeps: Dependency[] = [];\n const seen = new Set<string>();\n\n for (const dep of deps) {\n const expanded = expansionMap.get(dep.producer);\n if (!expanded) {\n addDep(newDeps, seen, dep);\n continue;\n }\n // Rewire to all expanded instances — even when there's only one,\n // because the expanded step has a new ID (e.g. \"step[node=18]\").\n for (const expStep of expanded) {\n addDep(newDeps, seen, { ...dep, producer: expStep.id });\n }\n }\n return newDeps;\n}\n\nfunction rewireInputs(\n inputs: readonly Reference[],\n expansionMap: Map<string, StepDefinition[]>,\n): Reference[] {\n const newInputs: Reference[] = [];\n const seen = new Set<string>();\n\n for (const ref of inputs) {\n if (ref.kind !== \"step\") {\n newInputs.push(ref);\n continue;\n }\n const expanded = expansionMap.get(ref.step);\n if (!expanded) {\n newInputs.push(ref);\n continue;\n }\n // Rewire to all expanded instances — even when there's only one,\n // because the expanded step has a new ID (e.g. \"step[node=18]\").\n for (const expStep of expanded) {\n const rewired = { ...ref, step: expStep.id };\n const key = `${rewired.step}:${rewired.output}`;\n if (seen.has(key)) continue;\n seen.add(key);\n newInputs.push(rewired);\n }\n }\n return newInputs;\n}\n\nfunction addDep(deps: Dependency[], seen: Set<string>, dep: Dependency): void {\n const key =\n dep.kind === \"control\"\n ? `control:${dep.producer}`\n : `${dep.kind}:${dep.producer}:${dep.output}`;\n if (seen.has(key)) return;\n seen.add(key);\n deps.push(dep);\n}\n","// Error classes for @sverka/sdk. Spec 03 — Error handling.\n\nexport type SdkErrorCode =\n | \"INVALID_INTERPOLATION\"\n | \"INVALID_IMAGE\"\n // Legacy config-discovery codes retained while CLI migrates to the new SDK API.\n | \"CONFIG_NOT_FOUND\"\n | \"CONFIG_INVALID\"\n | \"CONFIG_LOAD_FAILED\"\n | \"CONFIG_PATH_ESCAPE\"\n | \"EXECUTION_FAILED\"\n // Markdown authoring (Spec 37/54).\n | \"INVALID_FRONTMATTER\"\n | \"INVALID_STEP\"\n | \"INVALID_TRIGGER\"\n | \"EXTENDS_NOT_FOUND\";\n\nexport class SdkError extends Error {\n override readonly cause?: unknown;\n readonly code: SdkErrorCode;\n\n constructor(message: string, code: SdkErrorCode, cause?: unknown) {\n super(message);\n this.name = \"SdkError\";\n this.code = code;\n if (cause !== undefined) {\n this.cause = cause;\n }\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { resolve, dirname, basename, isAbsolute, relative } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { WorkflowDefinition } from \"./types.js\";\nimport { SdkError } from \"../errors.js\";\n\nconst CONFIG_NAMES = [\"sverka.config.ts\", \"sverka.config.js\"];\nconst MAX_PARENTS = 5;\n\n/**\n * Search upward from `root` for sverka.config.ts (then .js). Returns the\n * path or null. Searches up to 5 parent directories.\n */\nexport async function findConfig(root: string): Promise<string | null> {\n let dir = resolve(root);\n for (let i = 0; i <= MAX_PARENTS; i++) {\n for (const name of CONFIG_NAMES) {\n const candidate = resolve(dir, name);\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n const parent = dirname(dir);\n if (parent === dir) break; // reached filesystem root\n dir = parent;\n }\n return null;\n}\n\n/**\n * Dynamically import a sverka.config.ts file and return its default\n * export as a WorkflowDefinition. Validates the shape.\n *\n * Under Bun, .ts files import natively. Under Node, use the .js fallback\n * (findConfig searches .ts first, then .js).\n */\nexport async function loadWorkflow(\n configPath: string,\n root?: string,\n): Promise<WorkflowDefinition> {\n const resolved = isAbsolute(configPath)\n ? resolve(configPath)\n : resolve(root ?? process.cwd(), configPath);\n\n if (!existsSync(resolved)) {\n throw new SdkError(\n `config file not found: ${configPath}`,\n \"CONFIG_NOT_FOUND\",\n );\n }\n\n if (root !== undefined) {\n const rel = relative(resolve(root), resolved);\n if (rel === \"\" || rel.startsWith(\"..\") || isAbsolute(rel)) {\n throw new SdkError(\n `config path escapes root: ${configPath}`,\n \"CONFIG_PATH_ESCAPE\",\n );\n }\n }\n\n let mod: unknown;\n try {\n const url = pathToFileURL(resolved).href;\n mod = await import(url);\n } catch (e) {\n throw new SdkError(\n `failed to load config: ${basename(configPath)}`,\n \"CONFIG_LOAD_FAILED\",\n e,\n );\n }\n\n const def = (mod as { default?: unknown }).default;\n validateDefaultExport(def);\n validateWorkflowShape(def.workflow as Record<string, unknown>);\n\n return def as unknown as WorkflowDefinition;\n}\n\nfunction validateDefaultExport(\n def: unknown,\n): asserts def is Record<string, unknown> {\n if (!isPlainObject(def)) {\n throw new SdkError(\n \"config default export must be an object\",\n \"CONFIG_INVALID\",\n );\n }\n\n if (typeof def.name !== \"string\" || def.name.length === 0) {\n throw new SdkError(\n \"config default export must have a non-empty 'name' string\",\n \"CONFIG_INVALID\",\n );\n }\n\n if (!isPlainObject(def.workflow)) {\n throw new SdkError(\n \"config default export must have a 'workflow' object\",\n \"CONFIG_INVALID\",\n );\n }\n}\n\n// Accept either a Workflow (has 'roots' array and 'plan' function) or\n// a bare Operation (has 'kind' and 'spec'). The SDK normalizes Operations\n// to Workflows at runtime.\nfunction validateWorkflowShape(wf: Record<string, unknown>): void {\n const isWorkflow = Array.isArray(wf.roots) && typeof wf.plan === \"function\";\n const isOperation = typeof wf.kind === \"string\" && isPlainObject(wf.spec);\n if (!isWorkflow && !isOperation) {\n throw new SdkError(\n \"config 'workflow' must be a Workflow (with 'roots' and 'plan') or an Operation (with 'kind' and 'spec')\",\n \"CONFIG_INVALID\",\n );\n }\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n","import { createHash } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { canonicalStringify } from \"@sverka/workflow\";\nimport type {\n OperationSpec,\n CacheDeclaration as CoreCacheDeclaration,\n ArtifactDeclaration as CoreArtifactDeclaration,\n} from \"@sverka/workflow\";\nimport type {\n Plan,\n PlanOperation,\n PlanMetadata,\n ExecutorSpec,\n ResourceLimits,\n PlanRetryPolicy,\n PlanCacheDeclaration,\n PlanArtifactDeclaration,\n} from \"@sverka/workflow\";\nimport { computePlanId } from \"@sverka/workflow\";\nimport type { ProjectContext } from \"../planner/index.js\";\nimport { SdkError } from \"../errors.js\";\n\nconst SVERKA_VERSION: string = ((): string => {\n let raw: string = \"\";\n try {\n raw = readFileSync(new URL(\"../package.json\", import.meta.url), \"utf-8\");\n } catch {\n try {\n raw = readFileSync(\n new URL(\"../../package.json\", import.meta.url),\n \"utf-8\",\n );\n } catch {\n return \"0.0.0\";\n }\n }\n const parsed: unknown = JSON.parse(raw);\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n \"version\" in parsed &&\n typeof (parsed as Record<string, unknown>).version === \"string\"\n ) {\n return (parsed as { version: string }).version;\n }\n return \"0.0.0\";\n})();\n\nexport interface ConvertOptions {\n /** Plan name (from WorkflowDefinition.name or default). */\n name: string;\n /** Executor type to fill for operations without an image. */\n executor: \"host\" | \"docker\";\n /** Project context for sourceContextHash. */\n context?: ProjectContext;\n}\n\n/**\n * Convert an array of OperationSpecs into a validated IR Plan with all\n * defaults filled per the spec's conversion table.\n */\nexport function convertToPlan(\n operations: readonly OperationSpec[],\n opts: ConvertOptions,\n): Plan {\n const planOps = operations.map((spec) => convertOperation(spec, opts));\n\n const sourceContextHash = computeSourceContextHash(opts.context);\n const metadata: PlanMetadata = {\n sverkaVersion: SVERKA_VERSION,\n generatedBy: \"manual\",\n };\n\n const body: Omit<Plan, \"id\" | \"createdAt\"> = {\n apiVersion: \"sverka.dev/v1\",\n name: opts.name,\n sourceContextHash,\n operations: planOps,\n metadata,\n };\n\n const id = computePlanId(body);\n const createdAt = new Date().toISOString();\n\n return { ...body, id, createdAt };\n}\n\nfunction convertOperation(\n spec: OperationSpec,\n opts: ConvertOptions,\n): PlanOperation {\n if (!spec.id || spec.id.length === 0) {\n throw new SdkError(\n `operation has empty id (kind=${spec.kind}, name=${spec.name})`,\n \"EXECUTION_FAILED\",\n );\n }\n\n const executor = buildExecutor(spec, opts);\n const resources = buildResources(spec);\n const retry = buildRetry(spec);\n const artifacts = (spec.artifacts ?? []).map(convertArtifact);\n const cache = spec.cache ? convertCache(spec.cache) : undefined;\n\n return buildPlanOperation(spec, executor, resources, retry, artifacts, cache);\n}\n\nfunction buildExecutor(\n spec: OperationSpec,\n opts: ConvertOptions,\n): ExecutorSpec {\n return {\n type: opts.executor,\n ...(spec.image !== undefined ? { image: spec.image } : {}),\n ...(spec.imageDigest !== undefined\n ? { imageDigest: spec.imageDigest }\n : {}),\n };\n}\n\nfunction buildResources(spec: OperationSpec): ResourceLimits {\n return {\n cpu: spec.cpuLimit ?? \"1\",\n memory: spec.memoryLimit ?? \"512Mi\",\n };\n}\n\nfunction buildRetry(spec: OperationSpec): PlanRetryPolicy {\n const retries = spec.retries ?? 0;\n return {\n maxAttempts: Math.max(1, retries + 1),\n backoffSeconds: 0,\n retryOn: [\"failure\", \"timeout\"],\n };\n}\n\nfunction buildPlanOperation(\n spec: OperationSpec,\n executor: ExecutorSpec,\n resources: ResourceLimits,\n retry: PlanRetryPolicy,\n artifacts: PlanArtifactDeclaration[],\n cache: PlanCacheDeclaration | undefined,\n): PlanOperation {\n return {\n id: spec.id,\n kind: spec.kind,\n name: spec.name,\n ...optionalFields(spec),\n ...resolveDefaults(spec),\n executor,\n resources,\n ...(cache !== undefined ? { cache } : {}),\n artifacts,\n retry,\n };\n}\n\ntype DefaultedField =\n | \"dependsOn\"\n | \"network\"\n | \"credentials\"\n | \"timeoutSeconds\"\n | \"continueOnError\";\n\nfunction valueOrDefault<T>(value: T | undefined, defaultValue: T): T {\n return value === undefined ? defaultValue : value;\n}\n\n/** Resolve fields with default values to reduce buildPlanOperation complexity. */\nfunction resolveDefaults(\n spec: OperationSpec,\n): Required<Pick<PlanOperation, DefaultedField>> {\n return {\n dependsOn: valueOrDefault(spec.dependsOn, []),\n network: valueOrDefault(spec.network, \"deny\"),\n credentials: valueOrDefault(spec.credentials, []),\n timeoutSeconds: valueOrDefault(spec.timeoutSeconds, 300),\n continueOnError: valueOrDefault(spec.continueOnError, false),\n };\n}\n\nfunction optionalFields(spec: OperationSpec): Partial<PlanOperation> {\n return {\n ...(spec.description !== undefined\n ? { description: spec.description }\n : {}),\n ...(spec.command !== undefined ? { command: spec.command } : {}),\n ...(spec.args !== undefined ? { args: spec.args } : {}),\n ...(spec.env !== undefined ? { env: spec.env } : {}),\n ...(spec.workingDir !== undefined ? { workingDir: spec.workingDir } : {}),\n ...(spec.condition !== undefined ? { condition: spec.condition } : {}),\n };\n}\n\nfunction convertArtifact(a: CoreArtifactDeclaration): PlanArtifactDeclaration {\n return {\n path: a.path,\n ...(a.name !== undefined ? { name: a.name } : {}),\n retain: a.retain ?? false,\n };\n}\n\nfunction convertCache(c: CoreCacheDeclaration): PlanCacheDeclaration {\n return {\n inputs: c.inputs,\n outputs: c.outputs ?? [],\n key: c.key ?? computeCacheKey(c.inputs),\n };\n}\n\nfunction computeCacheKey(inputs: readonly string[]): string {\n // Use 32 hex chars (128 bits) to keep keys compact while avoiding\n // the higher collision risk of a 64-bit truncation.\n return createHash(\"sha256\")\n .update(inputs.join(\",\"))\n .digest(\"hex\")\n .slice(0, 32);\n}\n\nfunction computeSourceContextHash(context?: ProjectContext): string {\n const changedFiles = context\n ? [...context.changedFiles.map((f) => f.path)].sort((a, b) =>\n a.localeCompare(b),\n )\n : [];\n const value = {\n commit: context?.commit ?? \"\",\n dirty: context?.dirty ?? false,\n changedFiles,\n };\n return createHash(\"sha256\").update(canonicalStringify(value)).digest(\"hex\");\n}\n","import type {\n PlanRuntime as IPlanRuntime,\n RuntimeMode,\n RuntimeResult,\n OperationOutcome,\n OperationSpec,\n} from \"@sverka/workflow\";\n\n/**\n * A plan-mode Runtime that records operations without side effects.\n * Used by the SDK to evaluate a workflow graph into an OperationSpec[]\n * without executing any commands.\n */\nexport class PlanRuntime implements IPlanRuntime {\n readonly mode: RuntimeMode = \"plan\";\n private readonly recorded: OperationSpec[] = [];\n private readonly start: number;\n\n constructor() {\n this.start = Date.now();\n }\n\n async evaluate(operation: OperationSpec): Promise<OperationOutcome> {\n this.recorded.push(operation);\n return {\n operationId: operation.id,\n status: \"planned\",\n durationMs: 0,\n };\n }\n\n async finalize(): Promise<RuntimeResult> {\n return {\n mode: \"plan\",\n operations: this.recorded,\n outcomes: [],\n durationMs: Date.now() - this.start,\n };\n }\n}\n","import { join } from \"node:path\";\nimport { mkdtempSync } from \"node:fs\";\nimport { rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\n\nimport type {\n OperationSpec,\n Workflow,\n Operation,\n ArtifactDeclaration,\n} from \"@sverka/workflow\";\nimport { workflow } from \"@sverka/workflow\";\nimport type { Plan } from \"@sverka/workflow\";\nimport { validatePlan } from \"@sverka/workflow\";\nimport type { OperationOutcome } from \"@sverka/runtime\";\nimport { createPlanner } from \"./planner/index.js\";\nimport type { ProjectContext } from \"./planner/index.js\";\nimport {\n DEFAULT_POLICY,\n createPolicy,\n evaluatePolicy,\n} from \"@sverka/verification\";\nimport type { Policy } from \"@sverka/verification\";\nimport { loadBaseline, filterOnlyNew } from \"@sverka/verification\";\nimport type { Finding } from \"@sverka/verification\";\nimport { createBuiltinResolver, extractFindings } from \"@sverka/verification\";\nimport type { CheckResolver, ResolvedCheck } from \"@sverka/verification\";\n\nimport type {\n SverkaOptions,\n Sverka,\n PlanResult,\n ExecutionResult,\n WorkflowDefinition,\n} from \"./types.js\";\nimport { SdkError } from \"./errors.js\";\nimport { findConfig, loadWorkflow } from \"./compat/config.js\";\nimport { convertToPlan } from \"./compat/convert.js\";\nimport { PlanRuntime } from \"./compat/internal/plan-runtime.js\";\n\n// Lazy types for runtime packages that may not exist on all waves.\n// These are dynamically imported in runPlan() to avoid hard deps.\ntype Scheduler = {\n execute(plan: Plan): Promise<RuntimeExecutionResult>;\n dispose(): Promise<void>;\n};\ntype Executor = unknown;\ntype RuntimeExecutionResult = {\n planId: string;\n status: \"success\" | \"failure\" | \"partial\";\n outcomes: ReadonlyMap<string, OperationOutcome>;\n durationMs: number;\n cancelledOperations: readonly string[];\n runtimeFailure?: boolean;\n};\n\n/**\n * Create a Sverka instance with default options pre-applied. Per-call\n * options override defaults.\n */\nexport function createSverka(defaultOptions?: SverkaOptions): Sverka {\n return {\n async plan(options?: SverkaOptions): Promise<PlanResult> {\n return doPlan(mergeOptions(defaultOptions, options));\n },\n async toPlan(options?: SverkaOptions): Promise<Plan> {\n return buildPlan(mergeOptions(defaultOptions, options));\n },\n async execute(options?: SverkaOptions): Promise<ExecutionResult> {\n return doExecute(mergeOptions(defaultOptions, options));\n },\n };\n}\n\n/** Top-level plan convenience function. */\nexport async function plan(options?: SverkaOptions): Promise<PlanResult> {\n return doPlan(options ?? {});\n}\n\n/** Top-level toPlan convenience function. Returns the canonical Plan IR. */\nexport async function toPlan(options?: SverkaOptions): Promise<Plan> {\n return buildPlan(options ?? {});\n}\n\n/** Top-level execute convenience function. */\nexport async function execute(\n options?: SverkaOptions,\n): Promise<ExecutionResult> {\n return doExecute(options ?? {});\n}\n\n// ---------------------------------------------------------------------------\n// Plan mode\n// ---------------------------------------------------------------------------\n\nasync function doPlan(options: SverkaOptions): Promise<PlanResult> {\n const root = options.root ?? process.cwd();\n const planner = createPlanner();\n const context = await planner.discover({\n root,\n ...(options.baseRef !== undefined ? { baseRef: options.baseRef } : {}),\n });\n\n const configPath = await resolveConfigPath(options, root);\n if (configPath !== null) {\n const def = await loadWorkflow(configPath, root);\n const operations = await evaluateWorkflow(def);\n const plan = buildPlanFromOps(operations, def.name, context);\n return { context, operations, proposal: null, plan };\n }\n\n // Auto-discovery mode.\n const proposal = await planner.plan(context);\n const resolver = options.resolver ?? createBuiltinResolver();\n const operations: OperationSpec[] = [];\n for (const check of proposal.checks) {\n try {\n const r = resolver.resolve(check, context);\n if (r !== null) operations.push(r.operation);\n } catch {\n // Skip checks whose custom resolver fails and continue with the rest.\n }\n }\n const plan = buildPlanFromOps(operations, \"sverka-plan\", context);\n return { context, operations, proposal, plan };\n}\n\n/** Build a canonical Plan IR from resolved operations. */\nasync function buildPlan(options: SverkaOptions): Promise<Plan> {\n const result = await doPlan(options);\n return result.plan;\n}\n\n/** Convert operations into a validated Plan with host executor defaults. */\nfunction buildPlanFromOps(\n operations: readonly OperationSpec[],\n name: string,\n context: ProjectContext,\n): Plan {\n const plan = convertToPlan(operations, {\n name,\n executor: \"host\",\n context,\n });\n\n if (operations.length > 0) {\n const validation = validatePlan(plan);\n if (!validation.valid) {\n throw new SdkError(\n `plan validation failed: ${validation.errors.map((e) => e.message).join(\"; \")}`,\n \"EXECUTION_FAILED\",\n );\n }\n }\n\n return plan;\n}\n\n// ---------------------------------------------------------------------------\n// Execute mode\n// ---------------------------------------------------------------------------\n\nasync function doExecute(options: SverkaOptions): Promise<ExecutionResult> {\n const root = options.root ?? process.cwd();\n const executorType: \"host\" | \"docker\" = options.executor ?? \"host\";\n const planner = createPlanner();\n const context: ProjectContext = await planner.discover({\n root,\n ...(options.baseRef !== undefined ? { baseRef: options.baseRef } : {}),\n });\n\n const { def, operations, resolvedChecks, planName } = await resolveOperations(\n options,\n root,\n context,\n executorType,\n );\n const plan = buildAndValidatePlan(\n operations,\n planName,\n executorType,\n context,\n );\n const { runtimeResult, findings } = await runPlan(\n plan,\n resolvedChecks,\n root,\n executorType,\n );\n return buildExecutionResult(runtimeResult, findings, options, def);\n}\n\n/** Load or auto-discover the operations to execute. */\nasync function resolveOperations(\n options: SverkaOptions,\n root: string,\n context: ProjectContext,\n executorType: \"host\" | \"docker\",\n): Promise<{\n def: WorkflowDefinition | null;\n operations: readonly OperationSpec[];\n resolvedChecks: readonly ResolvedCheck[];\n planName: string;\n}> {\n const configPath = await resolveConfigPath(options, root);\n\n if (configPath !== null) {\n const def = await loadWorkflow(configPath, root);\n const operations = await evaluateWorkflow(def);\n return { def, operations, resolvedChecks: [], planName: def.name };\n }\n\n const proposal = await createPlanner().plan(context);\n const resolver = options.resolver ?? createBuiltinResolver();\n const tmpChecks: ResolvedCheck[] = [];\n for (const check of proposal.checks) {\n try {\n const r = resolver.resolve(check, context);\n if (r !== null) tmpChecks.push(r);\n } catch {\n // Skip checks whose custom resolver fails and continue with the rest.\n }\n }\n\n if (\n executorType === \"docker\" &&\n tmpChecks.some((r) => r.operation.image === undefined)\n ) {\n throw new SdkError(\n \"docker executor requires container images; every operation must declare an image\",\n \"EXECUTION_FAILED\",\n );\n }\n\n const operations = tmpChecks.map((r) => buildOperationWithOutputs(r));\n if (operations.length === 0) {\n throw new SdkError(\n \"no config found and auto-discovery produced no resolvable checks\",\n \"CONFIG_NOT_FOUND\",\n );\n }\n\n return {\n def: null,\n operations,\n resolvedChecks: tmpChecks,\n planName: \"sverka-plan\",\n };\n}\n\n/** Convert operations into a Plan and validate it. */\nfunction buildAndValidatePlan(\n operations: readonly OperationSpec[],\n planName: string,\n executorType: \"host\" | \"docker\",\n context: ProjectContext,\n): Plan {\n const plan = convertToPlan(operations, {\n name: planName,\n executor: executorType,\n context,\n });\n\n // Validate (skip for empty operations — auto-discovery with no commands).\n if (operations.length > 0) {\n const validation = validatePlan(plan);\n if (!validation.valid) {\n throw new SdkError(\n `plan validation failed: ${validation.errors.map((e) => e.message).join(\"; \")}`,\n \"EXECUTION_FAILED\",\n );\n }\n }\n\n return plan;\n}\n\n/** Execute a Plan and extract findings from resolved checks. */\nasync function runPlan(\n plan: Plan,\n resolvedChecks: readonly ResolvedCheck[],\n root: string,\n executorType: \"host\" | \"docker\",\n): Promise<{\n runtimeResult: RuntimeExecutionResult;\n findings: readonly Finding[];\n}> {\n const artifactDir = mkdtempSync(join(tmpdir(), \"sverka-artifacts-\"));\n const cacheDir = mkdtempSync(join(tmpdir(), \"sverka-cache-\"));\n\n try {\n // Lazy import: @sverka/runtime may not exist on later waves (replaced\n // by @sverka/engine-native). The execute path dynamically imports it.\n const { Scheduler } = await import(\"@sverka/runtime\");\n const executor = await createExecutor(\n executorType,\n cacheDir,\n plan.operations,\n );\n const scheduler: Scheduler = new Scheduler({\n executors: [executor],\n maxConcurrent: 4,\n workspace: root,\n artifactDir,\n cacheDir,\n credentials: {},\n resume: false,\n } as unknown as ConstructorParameters<typeof Scheduler>[0]);\n\n try {\n const runtimeResult = (await scheduler.execute(\n plan,\n )) as RuntimeExecutionResult;\n const findings = await extractResolvedFindings(\n resolvedChecks,\n artifactDir,\n );\n return { runtimeResult, findings };\n } catch (e) {\n throw new SdkError(\n `execution failed: ${e instanceof Error ? e.message : String(e)}`,\n \"EXECUTION_FAILED\",\n e,\n );\n } finally {\n await scheduler.dispose().catch(() => {});\n }\n } finally {\n await Promise.all([\n rm(artifactDir, { recursive: true, force: true }).catch(() => {}),\n rm(cacheDir, { recursive: true, force: true }).catch(() => {}),\n ]);\n }\n}\n\n/** Extract findings from resolved checks' SARIF output artifacts. */\nasync function extractResolvedFindings(\n resolvedChecks: readonly ResolvedCheck[],\n artifactDir: string,\n): Promise<readonly Finding[]> {\n const all: Finding[] = [];\n for (const r of resolvedChecks) {\n if (r.outputs.length === 0) continue;\n const extracted = await extractFindings(r.outputs, artifactDir, r.checkId);\n all.push(...extracted);\n }\n return all;\n}\n\n/** Build the final ExecutionResult from runtime output and user options. */\nasync function buildExecutionResult(\n runtimeResult: RuntimeExecutionResult,\n findings: readonly Finding[],\n options: SverkaOptions,\n def: WorkflowDefinition | null,\n): Promise<ExecutionResult> {\n let baselineFingerprints: readonly string[] = [];\n let filteredFindings: readonly Finding[] = findings;\n if (options.baselinePath) {\n const baseline = await loadBaseline(options.baselinePath);\n baselineFingerprints = baseline.fingerprints;\n filteredFindings = options.onlyNew\n ? filterOnlyNew(findings, baseline)\n : findings;\n }\n\n const policy: Policy = def?.policy\n ? createPolicy(def.policy)\n : DEFAULT_POLICY;\n const policyResult = evaluatePolicy(\n filteredFindings,\n policy,\n baselineFingerprints,\n );\n\n const verdict =\n runtimeResult.status === \"success\" ? policyResult.verdict : \"fail\";\n\n return {\n findings: filteredFindings,\n policyResult,\n verdict,\n status: runtimeResult.status,\n ...(runtimeResult.runtimeFailure\n ? { runtimeFailure: runtimeResult.runtimeFailure }\n : {}),\n outcomes: runtimeResult.outcomes,\n durationMs: runtimeResult.durationMs,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction mergeOptions(\n defaults: SverkaOptions | undefined,\n callOpts: SverkaOptions | undefined,\n): SverkaOptions {\n return { ...defaults, ...callOpts };\n}\n\nasync function resolveConfigPath(\n options: SverkaOptions,\n root: string,\n): Promise<string | null> {\n if (options.configPath) {\n return options.configPath;\n }\n return findConfig(root);\n}\n\nasync function evaluateWorkflow(\n def: WorkflowDefinition,\n): Promise<readonly OperationSpec[]> {\n const wf = normalizeWorkflow(def.name, def.workflow);\n const runtime = new PlanRuntime();\n const result = await wf.plan(runtime);\n return result.operations;\n}\n\n/**\n * Normalize a WorkflowDefinition's workflow field to a Workflow.\n * If it's already a Workflow (has `roots` and `plan`), return as-is.\n * If it's a bare Operation, wrap it with `workflow(name, op)`.\n */\nfunction normalizeWorkflow(name: string, wf: Workflow | Operation): Workflow {\n if (isWorkflow(wf)) {\n return wf;\n }\n // It's an Operation — wrap it.\n return workflow(name, wf);\n}\n\nfunction isWorkflow(wf: Workflow | Operation): wf is Workflow {\n return \"roots\" in wf && \"plan\" in wf;\n}\n\nasync function createExecutor(\n type: \"host\" | \"docker\",\n cacheDir: string,\n operations: readonly { command?: string }[],\n): Promise<Executor> {\n if (type === \"docker\") {\n const { DockerExecutor } = await import(\"@sverka/runtime\");\n return new DockerExecutor({\n runAs: `${process.getuid?.() ?? 1000}:${process.getgid?.() ?? 1000}`,\n cacheDir,\n });\n }\n const { HostExecutor, createAllowlist } = await import(\"@sverka/runtime\");\n const commands = operations\n .map((op) => op.command)\n .filter((c): c is string => typeof c === \"string\" && c.length > 0);\n return new HostExecutor({\n enabled: true,\n allowlist: createAllowlist(commands),\n envAllowlist: [\"PATH\"],\n });\n}\n\n/** Merge resolved-check outputs into the operation's artifact declarations. */\nfunction buildOperationWithOutputs(r: ResolvedCheck): OperationSpec {\n if (r.outputs.length === 0) {\n return r.operation;\n }\n const artifacts: ArtifactDeclaration[] = [\n ...(r.operation.artifacts ?? []),\n ...r.outputs.map((o) => ({ path: o.path, retain: false })),\n ];\n return { ...r.operation, artifacts };\n}\n","// Standalone helpers that don't depend on runtime packages.\nimport type { Operation } from \"@sverka/workflow\";\nimport type { WorkflowDefinition } from \"./types.js\";\n\n/** Name an operation. Sugar for `op.named(name)`. */\nexport function task(name: string, op: Operation): Operation {\n return op.named(name);\n}\n\n/** Type-safe helper for sverka.config.ts. Identity function. */\nexport function defineWorkflow(\n definition: WorkflowDefinition,\n): WorkflowDefinition {\n return definition;\n}\n","import type { Reference, StepRef, ContextRef } from \"@sverka/workflow\";\n\nconst OUTPUT_TYPES = new Set<string>([\n \"string\",\n \"number\",\n \"boolean\",\n \"artifact\",\n]);\nconst CONTEXT_NAMESPACES = new Set<string>([\n \"env\",\n \"secrets\",\n \"git\",\n \"change\",\n \"event\",\n \"run\",\n \"inputs\",\n \"matrix\",\n]);\n\n/**\n * Type guard for Reference values.\n * Shared between expr.ts and sh.ts to avoid duplication.\n * Validates that type and namespace values are within their finite unions.\n */\nexport function isReference(value: unknown): value is Reference {\n if (typeof value !== \"object\" || value === null || !(\"kind\" in value)) {\n return false;\n }\n const ref = value as { kind: string };\n if (ref.kind === \"step\") return isStepRef(value);\n if (ref.kind === \"context\") return isContextRef(value);\n return false;\n}\n\nfunction isStepRef(value: object): boolean {\n const s = value as Partial<StepRef>;\n return (\n typeof s.step === \"string\" &&\n typeof s.output === \"string\" &&\n typeof s.type === \"string\" &&\n OUTPUT_TYPES.has(s.type)\n );\n}\n\nfunction isContextRef(value: object): boolean {\n const c = value as Partial<ContextRef>;\n return (\n typeof c.namespace === \"string\" &&\n typeof c.field === \"string\" &&\n CONTEXT_NAMESPACES.has(c.namespace)\n );\n}\n","// $ tagged template — shell command step builder.\n// Spec 03 — §9.2, §15. Architecture spec §9.2.\n\nimport { ShellStep, Pipeline } from \"@sverka/workflow\";\nimport type {\n Reference,\n Runtime,\n OutputDeclaration,\n MatrixSpec,\n Condition,\n OperationDefinition,\n} from \"@sverka/workflow\";\nimport { SdkError } from \"./errors.js\";\nimport { isReference } from \"./internal/is-reference.js\";\n\nexport interface StepBuilder {\n outputs(outputs: Readonly<Record<string, OutputDeclaration>>): StepBuilder;\n inputs(inputs: readonly Reference[]): StepBuilder;\n dependsOn(steps: readonly string[]): StepBuilder;\n runtime(runtime: Runtime): StepBuilder;\n timeout(ms: number): StepBuilder;\n condition(ref: Condition): StepBuilder;\n matrix(spec: MatrixSpec): StepBuilder;\n interruptible(value?: boolean): StepBuilder;\n compensate(command: string): StepBuilder;\n build(pipeline: Pipeline, id: string): ShellStep;\n}\n\ninterface StepBuilderState {\n command: string;\n collectedInputs: Reference[];\n outputs?: Readonly<Record<string, OutputDeclaration>>;\n inputs?: readonly Reference[];\n dependsOn?: readonly string[];\n runtime?: Runtime;\n timeout?: number;\n condition?: Condition;\n matrix?: MatrixSpec;\n interruptible?: boolean;\n compensation?: OperationDefinition;\n}\n\nfunction createBuilder(state: StepBuilderState): StepBuilder {\n const builder: StepBuilder = {\n outputs(outputs: Readonly<Record<string, OutputDeclaration>>): StepBuilder {\n state.outputs = outputs;\n return builder;\n },\n inputs(inputs: readonly Reference[]): StepBuilder {\n state.inputs = inputs;\n return builder;\n },\n dependsOn(steps: readonly string[]): StepBuilder {\n state.dependsOn = steps;\n return builder;\n },\n runtime(runtime: Runtime): StepBuilder {\n state.runtime = runtime;\n return builder;\n },\n timeout(ms: number): StepBuilder {\n state.timeout = ms;\n return builder;\n },\n condition(ref: Condition): StepBuilder {\n state.condition = ref;\n return builder;\n },\n matrix(spec: MatrixSpec): StepBuilder {\n state.matrix = spec;\n return builder;\n },\n interruptible(value?: boolean): StepBuilder {\n state.interruptible = value ?? true;\n return builder;\n },\n compensate(command: string): StepBuilder {\n state.compensation = { kind: \"shell\", command };\n return builder;\n },\n build(pipeline: Pipeline, id: string): ShellStep {\n // Merge collected inputs (from interpolation) with explicit inputs.\n const explicitInputs = state.inputs ? [...state.inputs] : [];\n const allInputs = [...explicitInputs, ...state.collectedInputs];\n return new ShellStep(pipeline, id, {\n command: state.command,\n ...(state.outputs ? { outputs: state.outputs } : {}),\n ...(allInputs.length > 0 ? { inputs: allInputs } : {}),\n ...(state.dependsOn ? { dependsOn: state.dependsOn } : {}),\n ...(state.runtime ? { runtime: state.runtime } : {}),\n ...(state.timeout !== undefined ? { timeout: state.timeout } : {}),\n ...(state.condition !== undefined\n ? { condition: state.condition }\n : {}),\n ...(state.matrix !== undefined ? { matrix: state.matrix } : {}),\n ...(state.interruptible !== undefined\n ? { interruptible: state.interruptible }\n : {}),\n ...(state.compensation !== undefined\n ? { compensation: state.compensation }\n : {}),\n });\n },\n };\n return builder;\n}\n\n/**\n * Create a shell command step builder from a tagged template.\n * References interpolated in the template are collected and added to the\n * step's inputs automatically.\n */\nexport function $(\n strings: TemplateStringsArray,\n ...values: readonly (string | Reference)[]\n): StepBuilder {\n let command = \"\";\n const collectedInputs: Reference[] = [];\n\n for (let i = 0; i < strings.length; i++) {\n command += strings[i];\n if (i < values.length) {\n const v = values[i]!;\n if (typeof v === \"string\") {\n command += v;\n } else if (isReference(v)) {\n // It's a Reference — add to inputs and interpolate a placeholder.\n const ref = v;\n collectedInputs.push(ref);\n if (ref.kind === \"step\") {\n command += `\\${${ref.step}.${ref.output}}`;\n } else {\n command += `\\${${ref.namespace}.${ref.field}}`;\n }\n } else {\n throw new SdkError(\n `invalid interpolation value at position ${i}: expected string or Reference`,\n \"INVALID_INTERPOLATION\",\n );\n }\n }\n }\n\n return createBuilder({ command, collectedInputs });\n}\n","// Shell proxy: command-prefix + shell-selector API.\n// Spec 03 — §9.2. Issue sv-kbu6.\n\nimport type { Runtime, Reference } from \"@sverka/workflow\";\nimport type { StepBuilder } from \"./dollar.js\";\nimport { $ } from \"./dollar.js\";\n\n/**\n * ShellProxy — callable tagged template + property access (command prefix)\n * + callable with interpreter string (shell selector).\n *\n * - `shell.git`push origin`` → command \"git push origin\"\n * - `shell(\"bash\").git`push`` → command \"git push\" + runtime.shell=\"bash\"\n * - `shell(\"pwsh\")`Write-Host hi`` → command \"Write-Host hi\" + runtime.shell=\"pwsh\"\n */\nexport interface ShellProxy {\n // Tagged template: bare shell`command` → StepBuilder (no prefix).\n (strings: TemplateStringsArray, ...values: readonly unknown[]): StepBuilder;\n // Shell selector: shell(\"bash\") → new ShellProxy with shell preset.\n (interpreter: string): ShellProxy;\n // Common command prefixes — named properties avoid | undefined under\n // noUncheckedIndexedAccess and provide autocomplete. The index signature\n // below covers any other string prefix dynamically.\n readonly git: ShellProxy;\n readonly npm: ShellProxy;\n readonly npx: ShellProxy;\n readonly bun: ShellProxy;\n readonly pnpm: ShellProxy;\n readonly yarn: ShellProxy;\n readonly docker: ShellProxy;\n readonly make: ShellProxy;\n readonly cargo: ShellProxy;\n readonly go: ShellProxy;\n readonly python: ShellProxy;\n readonly pip: ShellProxy;\n // Command prefix: shell.git`push` → StepBuilder with \"git push\".\n readonly [key: string]: ShellProxy;\n}\n\n/**\n * Create a ShellProxy bound to an optional command prefix and shell interpreter.\n * - prefix: accumulated property-access chain (e.g. \"git\" for shell.git)\n * - shellOpt: interpreter string from shell(\"bash\"), applied as runtime.shell\n */\nfunction createShellProxy(prefix: string, shellOpt?: string): ShellProxy {\n const proxy: ShellProxy = function (\n stringsOrInterpreter: TemplateStringsArray | string,\n ...values: readonly unknown[]\n ): StepBuilder | ShellProxy {\n // Function call with interpreter string: shell(\"bash\") → new proxy.\n if (typeof stringsOrInterpreter === \"string\") {\n return createShellProxy(prefix, stringsOrInterpreter);\n }\n\n // Tagged template: build the command.\n // $ validates interpolation values at runtime (throws INVALID_INTERPOLATION);\n // cast to satisfy its (string | Reference) signature.\n const builder = $(\n stringsOrInterpreter,\n ...(values as readonly (string | Reference)[]),\n );\n\n // Prepend command prefix if set (e.g. \"git \" for shell.git`push`).\n if (prefix) {\n return wrapBuilder(builder, (step) =>\n applyPrefixAndShell(step, prefix, shellOpt),\n );\n }\n\n // No prefix — bare shell`command` or shell(\"bash\")`command`.\n if (shellOpt) {\n return wrapBuilder(builder, (step) => applyShell(step, shellOpt));\n }\n return builder;\n } as ShellProxy;\n\n // Property access: shell.git → new ShellProxy with prefix \"git\".\n return new Proxy(proxy, {\n get(_target, prop: string | symbol): ShellProxy | undefined {\n // Guard against thenable/introspection props (then, toJSON, etc.)\n if (typeof prop !== \"string\") return undefined;\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"toString\")\n return undefined;\n const newPrefix = prefix ? `${prefix} ${prop}` : prop;\n return createShellProxy(newPrefix, shellOpt);\n },\n });\n}\n\n/**\n * Apply a command prefix and optional shell interpreter to a built step.\n * Mutates the step in-place to preserve pipeline registration.\n */\nfunction applyPrefixAndShell(\n step: ReturnType<StepBuilder[\"build\"]>,\n prefix: string,\n shellOpt?: string,\n): ReturnType<StepBuilder[\"build\"]> {\n const runtime = shellOpt\n ? { ...step.runtime, shell: shellOpt }\n : step.runtime;\n Object.assign(step, { command: `${prefix} ${step.command}`, runtime });\n return step;\n}\n\n/**\n * Apply a shell interpreter to a built step (no prefix).\n * Mutates the step in-place to preserve pipeline registration.\n */\nfunction applyShell(\n step: ReturnType<StepBuilder[\"build\"]>,\n interpreter: string,\n): ReturnType<StepBuilder[\"build\"]> {\n const runtime: Runtime = { ...step.runtime, shell: interpreter };\n Object.assign(step, { runtime });\n return step;\n}\n\n/**\n * Wrap a StepBuilder so `build()` applies a transform to the final step.\n * Chain methods delegate to the original builder and return the wrapper.\n */\nfunction wrapBuilder(\n builder: StepBuilder,\n transform: (\n step: ReturnType<StepBuilder[\"build\"]>,\n ) => ReturnType<StepBuilder[\"build\"]>,\n): StepBuilder {\n const origBuild = builder.build.bind(builder);\n const wrapped: StepBuilder = {\n outputs(o) {\n builder.outputs(o);\n return wrapped;\n },\n inputs(i) {\n builder.inputs(i);\n return wrapped;\n },\n dependsOn(s) {\n builder.dependsOn(s);\n return wrapped;\n },\n runtime(r) {\n builder.runtime(r);\n return wrapped;\n },\n timeout(ms) {\n builder.timeout(ms);\n return wrapped;\n },\n condition(ref) {\n builder.condition(ref);\n return wrapped;\n },\n matrix(spec) {\n builder.matrix(spec);\n return wrapped;\n },\n interruptible(value) {\n builder.interruptible(value);\n return wrapped;\n },\n compensate(command) {\n builder.compensate(command);\n return wrapped;\n },\n build(pipeline, id) {\n return transform(origBuild(pipeline, id));\n },\n };\n return wrapped;\n}\n\n/**\n * Shell proxy export. Provides command-prefix and shell-selector DX.\n *\n * @example\n * const { git, npm, bun, make, docker } = shell;\n * git`push origin main`.build(p, \"push\") // → \"git push origin main\"\n * bun`run build`.build(p, \"build\") // → \"bun run build\"\n *\n * @example\n * const bash = shell(\"bash\");\n * bash.git`push`.build(p, \"push\") // → \"git push\" + runtime.shell=\"bash\"\n * shell(\"pwsh\")`Write-Host hello`.build(p, \"greet\") // → \"Write-Host hello\" + runtime.shell=\"pwsh\"\n */\nexport const shell: ShellProxy = createShellProxy(\"\");\n","// artifact() — output declaration factory for artifact outputs.\n// Spec 03 — §12.2.\n\nimport type { OutputDeclaration } from \"@sverka/workflow\";\n\n/** Create an artifact output declaration with the given path. */\nexport function artifact(path: string): OutputDeclaration {\n return { type: \"artifact\", path };\n}\n","// pipeline() factory — creates a Pipeline and runs step/entry functions.\n// Spec 03 — §9.2.\n\nimport { Project, Pipeline, Entry } from \"@sverka/workflow\";\nimport type { Input } from \"@sverka/workflow\";\n\nexport interface PipelineConfig {\n inputs?: Readonly<Record<string, Input>>;\n steps?: ReadonlyArray<(pipeline: Pipeline) => void>;\n entries?: ReadonlyArray<(pipeline: Pipeline) => Entry>;\n}\n\n/** Create a Pipeline, run step functions, then entry functions. */\nexport function pipeline(\n project: Project,\n id: string,\n config: PipelineConfig,\n): Pipeline {\n const p = new Pipeline(project, id, {\n ...(config.inputs ? { inputs: config.inputs } : {}),\n });\n\n if (config.steps) {\n for (const stepFn of config.steps) {\n stepFn(p);\n }\n }\n\n if (config.entries) {\n for (const entryFn of config.entries) {\n entryFn(p);\n }\n }\n\n return p;\n}\n","// callPipeline() builder — invokes a callee pipeline as a step (F-31).\n// Returns a builder that creates a PipelineCallStep when .build() is called.\n\nimport { PipelineCallStep, Pipeline } from \"@sverka/workflow\";\nimport type {\n Reference,\n InputLiteral,\n Runtime,\n OutputDeclaration,\n} from \"@sverka/workflow\";\n\nexport interface CallPipelineBuilder {\n outputs(\n outputs: Readonly<Record<string, OutputDeclaration>>,\n ): CallPipelineBuilder;\n dependsOn(steps: readonly string[]): CallPipelineBuilder;\n runtime(runtime: Runtime): CallPipelineBuilder;\n timeout(ms: number): CallPipelineBuilder;\n condition(ref: Reference): CallPipelineBuilder;\n interruptible(value: boolean): CallPipelineBuilder;\n build(pipeline: Pipeline, id: string): PipelineCallStep;\n}\n\ninterface CallBuilderState {\n callee: string;\n callInputs: Record<string, Reference | InputLiteral>;\n outputs?: Readonly<Record<string, OutputDeclaration>>;\n dependsOn?: readonly string[];\n runtime?: Runtime;\n timeout?: number;\n condition?: Reference;\n interruptible?: boolean;\n}\n\nfunction createCallBuilder(state: CallBuilderState): CallPipelineBuilder {\n const builder: CallPipelineBuilder = {\n outputs(\n outputs: Readonly<Record<string, OutputDeclaration>>,\n ): CallPipelineBuilder {\n state.outputs = outputs;\n return builder;\n },\n dependsOn(steps: readonly string[]): CallPipelineBuilder {\n state.dependsOn = steps;\n return builder;\n },\n runtime(runtime: Runtime): CallPipelineBuilder {\n state.runtime = runtime;\n return builder;\n },\n timeout(ms: number): CallPipelineBuilder {\n state.timeout = ms;\n return builder;\n },\n condition(ref: Reference): CallPipelineBuilder {\n state.condition = ref;\n return builder;\n },\n interruptible(value: boolean): CallPipelineBuilder {\n state.interruptible = value;\n return builder;\n },\n build(pipeline: Pipeline, id: string): PipelineCallStep {\n return new PipelineCallStep(pipeline, id, {\n callee: state.callee,\n callInputs: state.callInputs,\n ...(state.outputs ? { outputs: state.outputs } : {}),\n ...(state.dependsOn ? { dependsOn: state.dependsOn } : {}),\n ...(state.runtime ? { runtime: state.runtime } : {}),\n ...(state.timeout !== undefined ? { timeout: state.timeout } : {}),\n ...(state.condition !== undefined\n ? { condition: state.condition }\n : {}),\n ...(state.interruptible !== undefined\n ? { interruptible: state.interruptible }\n : {}),\n });\n },\n };\n return builder;\n}\n\n/**\n * Create a pipeline-call step builder.\n * @param callee The callee pipeline id (within the same Project).\n * @param callInputs Bound inputs for the callee pipeline.\n */\nexport function callPipeline(\n callee: string,\n callInputs?: Readonly<Record<string, Reference | InputLiteral>>,\n): CallPipelineBuilder {\n return createCallBuilder({\n callee,\n callInputs: callInputs ? { ...callInputs } : {},\n });\n}\n","// component() builder — invokes a versioned component as a step (F-32).\n// Returns a builder that creates a ComponentStep when .build() is called.\n\nimport { ComponentStep, Pipeline } from \"@sverka/workflow\";\nimport type {\n Reference,\n InputLiteral,\n ComponentRef,\n Runtime,\n OutputDeclaration,\n} from \"@sverka/workflow\";\n\nexport interface ComponentBuilder {\n outputs(\n outputs: Readonly<Record<string, OutputDeclaration>>,\n ): ComponentBuilder;\n dependsOn(steps: readonly string[]): ComponentBuilder;\n runtime(runtime: Runtime): ComponentBuilder;\n timeout(ms: number): ComponentBuilder;\n condition(ref: Reference): ComponentBuilder;\n interruptible(value: boolean): ComponentBuilder;\n build(pipeline: Pipeline, id: string): ComponentStep;\n}\n\ninterface ComponentBuilderState {\n component: ComponentRef;\n outputs?: Readonly<Record<string, OutputDeclaration>>;\n dependsOn?: readonly string[];\n runtime?: Runtime;\n timeout?: number;\n condition?: Reference;\n interruptible?: boolean;\n}\n\nfunction createComponentBuilder(\n state: ComponentBuilderState,\n): ComponentBuilder {\n const builder: ComponentBuilder = {\n outputs(\n outputs: Readonly<Record<string, OutputDeclaration>>,\n ): ComponentBuilder {\n state.outputs = outputs;\n return builder;\n },\n dependsOn(steps: readonly string[]): ComponentBuilder {\n state.dependsOn = steps;\n return builder;\n },\n runtime(runtime: Runtime): ComponentBuilder {\n state.runtime = runtime;\n return builder;\n },\n timeout(ms: number): ComponentBuilder {\n state.timeout = ms;\n return builder;\n },\n condition(ref: Reference): ComponentBuilder {\n state.condition = ref;\n return builder;\n },\n interruptible(value: boolean): ComponentBuilder {\n state.interruptible = value;\n return builder;\n },\n build(pipeline: Pipeline, id: string): ComponentStep {\n return new ComponentStep(pipeline, id, {\n component: state.component,\n ...(state.outputs ? { outputs: state.outputs } : {}),\n ...(state.dependsOn ? { dependsOn: state.dependsOn } : {}),\n ...(state.runtime ? { runtime: state.runtime } : {}),\n ...(state.timeout !== undefined ? { timeout: state.timeout } : {}),\n ...(state.condition !== undefined\n ? { condition: state.condition }\n : {}),\n ...(state.interruptible !== undefined\n ? { interruptible: state.interruptible }\n : {}),\n });\n },\n };\n return builder;\n}\n\n/**\n * Create a component step builder.\n * @param name The component name (e.g. \"deploy\").\n * @param version The component version (e.g. \"1.0.0\").\n * @param inputs Bound inputs for the component.\n */\nexport function component(\n name: string,\n version: string,\n inputs?: Readonly<Record<string, Reference | InputLiteral>>,\n): ComponentBuilder {\n return createComponentBuilder({\n component: {\n name,\n version,\n inputs: inputs ? { ...inputs } : {},\n },\n });\n}\n","// when() — condition helper.\n// Spec 03 — §10 (StepDefinition.condition). In v0, conditions are\n// boolean-producing References, Expressions, or StatusConditions. `when` is\n// an identity function that marks a value as a condition for readability.\n\nimport type { Condition } from \"@sverka/workflow\";\n\n/** Mark a reference, expression, or status condition as a step condition. Returns it unchanged. */\nexport function when(cond: Condition): Condition {\n return cond;\n}\n","// expr tagged template — symbolic expression builder.\n// Spec 03 — §12.3. Architecture spec §11.1, §12.3.\n\nimport type { Reference, Expression } from \"@sverka/workflow\";\nimport { SdkError } from \"./errors.js\";\nimport { isReference } from \"./internal/is-reference.js\";\n\n/**\n * Create a symbolic expression from a tagged template.\n * Context references produce `${namespace.field}` placeholders while step\n * references produce `${step.output}` placeholders; both are collected into\n * `refs` for dependency inference.\n * String, number, and boolean values are inlined into the template.\n */\nexport function expr(\n strings: TemplateStringsArray,\n ...values: readonly (string | number | boolean | Reference)[]\n): Expression {\n let template = \"\";\n const refs: Reference[] = [];\n\n for (let i = 0; i < strings.length; i++) {\n template += strings[i];\n if (i < values.length) {\n const v = values[i]!;\n if (\n typeof v === \"string\" ||\n typeof v === \"number\" ||\n typeof v === \"boolean\"\n ) {\n template += String(v);\n } else if (isReference(v)) {\n refs.push(v);\n if (v.kind === \"step\") {\n template += `\\${${v.step}.${v.output}}`;\n } else {\n template += `\\${${v.namespace}.${v.field}}`;\n }\n } else {\n throw new SdkError(\n `invalid interpolation value at position ${i}: expected string, number, boolean, or Reference`,\n \"INVALID_INTERPOLATION\",\n );\n }\n }\n }\n\n return { kind: \"expression\", template, refs };\n}\n","// status() factory — creates a StatusCondition for step conditions.\n// F-11 — §conditions.\n\nimport type { StepStatus, StatusCondition } from \"@sverka/workflow\";\n\n/**\n * Create a status-based condition.\n * @example\n * sh`notify-slack`.condition(status(\"failure\"))\n */\nexport function status(s: StepStatus): StatusCondition {\n return { kind: \"status\", status: s };\n}\n","// Shared set of protected Proxy properties to avoid accidental access\n// to Promise/JSON/inspection internals when using dynamic property proxies.\n\nexport const PROTECTED_PROXY_PROPS = new Set<string | symbol>([\n \"then\",\n \"toJSON\",\n \"inspect\",\n \"constructor\",\n \"valueOf\",\n Symbol.toPrimitive,\n Symbol.iterator,\n Symbol.toStringTag,\n]);\n\n/**\n * Create a dynamic Proxy that delegates protected/symbol properties to\n * Reflect.get and calls `resolve(prop)` for everything else.\n *\n * This shared factory eliminates duplication between context namespace\n * proxies and image reference proxies.\n */\nexport function createDynamicProxy<T>(\n resolve: (prop: string) => T,\n): Record<string, T> {\n return new Proxy({} as Record<string, T>, {\n get(target, prop: string | symbol): T | unknown {\n if (typeof prop === \"symbol\" || PROTECTED_PROXY_PROPS.has(prop)) {\n return Reflect.get(target, prop);\n }\n return resolve(prop);\n },\n });\n}\n","// Image value helpers — typed OCI image references.\n// Spec 03 — §14.2. Architecture spec §14.2.\n\nimport { SdkError } from \"./errors.js\";\nimport { createDynamicProxy } from \"./internal/proxy-props.js\";\n\nexport interface ImageRef {\n readonly ref: string;\n}\n\n/** Create an ImageRef from a raw OCI reference string. */\nexport function image(ref: string): ImageRef {\n if (typeof ref !== \"string\") {\n throw new SdkError(\"image reference must be a string\", \"INVALID_IMAGE\");\n }\n if (ref.length === 0) {\n throw new SdkError(\n \"image reference must be a non-empty string\",\n \"INVALID_IMAGE\",\n );\n }\n return { ref };\n}\n\n/** Create a Proxy that maps property access to `image(prefix:prop)`. */\nfunction createImageProxy(\n prefix: string,\n): Record<string, ImageRef> & { readonly latest: ImageRef } {\n return createDynamicProxy((prop) => image(`${prefix}:${prop}`)) as Record<\n string,\n ImageRef\n > & { readonly latest: ImageRef };\n}\n\n/** Node image proxy — images.node[22] → { ref: \"node:22\" }, images.node.latest → { ref: \"node:latest\" }. */\nconst nodeImages = createImageProxy(\"node\") as Record<string, ImageRef> & {\n readonly latest: ImageRef;\n readonly [version: number]: ImageRef;\n};\n\n/** Ubuntu image proxy — images.ubuntu.latest → { ref: \"ubuntu:latest\" }. */\nconst ubuntuImages = createImageProxy(\"ubuntu\");\n\nexport const images = {\n node: nodeImages,\n ubuntu: ubuntuImages,\n};\n","// Context namespaces — typed references to context values.\n// Spec 03 — §12.3. Architecture spec §12.3.\n\nimport type { ContextRef, ContextNamespace } from \"@sverka/workflow\";\nimport { createDynamicProxy } from \"./internal/proxy-props.js\";\n\n/** Create a ContextRef for a namespace + field. */\nfunction ctx(namespace: ContextNamespace, field: string): ContextRef {\n return { kind: \"context\", namespace, field };\n}\n\n/** Dynamic namespace proxy — any property access returns a ContextRef. */\nfunction dynamicNamespace(\n namespace: ContextNamespace,\n): Record<string, ContextRef> {\n return createDynamicProxy((prop) => ctx(namespace, prop));\n}\n\n/** Environment variable references: env.CI_TRACE, env.MY_VAR. */\nexport const env: Record<string, ContextRef> = dynamicNamespace(\"env\");\n\n/** Secret references: secrets.NPM_TOKEN. */\nexport const secrets: Record<string, ContextRef> = dynamicNamespace(\"secrets\");\n\n/** Git metadata references: git.sha, git.branch, git.tag. */\nexport const git = {\n sha: ctx(\"git\", \"sha\"),\n branch: ctx(\"git\", \"branch\"),\n tag: ctx(\"git\", \"tag\"),\n};\n\n/** Change request metadata: change.id, change.source, change.target, change.draft. */\nexport const change = {\n id: ctx(\"change\", \"id\"),\n source: ctx(\"change\", \"source\"),\n target: ctx(\"change\", \"target\"),\n draft: ctx(\"change\", \"draft\"),\n};\n\n/** Event metadata: event.type. */\nexport const event = {\n type: ctx(\"event\", \"type\"),\n};\n\n/** Run metadata: run.id, run.attempt. */\nexport const run = {\n id: ctx(\"run\", \"id\"),\n attempt: ctx(\"run\", \"attempt\"),\n};\n\n/** Pipeline input references: inputs.environment. */\nexport const inputs: Record<string, ContextRef> = dynamicNamespace(\"inputs\");\n\n/** Matrix variable references: matrix.node, matrix.os. */\nexport const matrix: Record<string, ContextRef> = dynamicNamespace(\"matrix\");\n","// agent tagged template — AI agent step builder.\n// Spec 27 — §9.2 (SDK). Mirrors $ for shell, but creates an AgentStep.\n\nimport { AgentStep, Pipeline } from \"@sverka/workflow\";\nimport type {\n Reference,\n OutputDeclaration,\n AgentToolRef,\n} from \"@sverka/workflow\";\nimport { SdkError } from \"./errors.js\";\nimport { isReference } from \"./internal/is-reference.js\";\n\nexport interface AgentStepBuilder {\n outputs(\n outputs: Readonly<Record<string, OutputDeclaration>>,\n ): AgentStepBuilder;\n inputs(inputs: readonly Reference[]): AgentStepBuilder;\n dependsOn(steps: readonly string[]): AgentStepBuilder;\n tools(...tools: readonly AgentToolRef[]): AgentStepBuilder;\n engine(engine: string): AgentStepBuilder;\n model(model: string): AgentStepBuilder;\n maxTokens(n: number): AgentStepBuilder;\n build(pipeline: Pipeline, id: string): AgentStep;\n}\n\ninterface AgentBuilderState {\n prompt: string;\n engine: string;\n model?: string;\n tools: AgentToolRef[];\n collectedInputs: Reference[];\n outputs?: Readonly<Record<string, OutputDeclaration>>;\n inputs?: readonly Reference[];\n dependsOn?: readonly string[];\n maxTokens?: number;\n}\n\nfunction createAgentBuilder(state: AgentBuilderState): AgentStepBuilder {\n const builder: AgentStepBuilder = {\n outputs(\n outputs: Readonly<Record<string, OutputDeclaration>>,\n ): AgentStepBuilder {\n state.outputs = outputs;\n return builder;\n },\n inputs(inputs: readonly Reference[]): AgentStepBuilder {\n state.inputs = inputs;\n return builder;\n },\n dependsOn(steps: readonly string[]): AgentStepBuilder {\n state.dependsOn = steps;\n return builder;\n },\n tools(...tools: readonly AgentToolRef[]): AgentStepBuilder {\n state.tools = [...state.tools, ...tools];\n return builder;\n },\n engine(engine: string): AgentStepBuilder {\n state.engine = engine;\n return builder;\n },\n model(model: string): AgentStepBuilder {\n state.model = model;\n return builder;\n },\n maxTokens(n: number): AgentStepBuilder {\n state.maxTokens = n;\n return builder;\n },\n build(pipeline: Pipeline, id: string): AgentStep {\n const explicitInputs = state.inputs ? [...state.inputs] : [];\n const allInputs = [...explicitInputs, ...state.collectedInputs];\n return new AgentStep(pipeline, id, {\n engine: state.engine,\n prompt: state.prompt,\n ...(state.model !== undefined ? { model: state.model } : {}),\n ...(state.tools.length > 0 ? { tools: state.tools } : {}),\n ...(state.maxTokens !== undefined\n ? { maxTokens: state.maxTokens }\n : {}),\n ...(state.outputs ? { outputs: state.outputs } : {}),\n ...(allInputs.length > 0 ? { inputs: allInputs } : {}),\n ...(state.dependsOn ? { dependsOn: state.dependsOn } : {}),\n });\n },\n };\n return builder;\n}\n\n/**\n * Create an AI agent step builder from a tagged template.\n * `agent\\`Build and test\\`` creates a builder with `engine: \"default\"`.\n * References interpolated in the template are collected and added to the\n * step's inputs automatically (same as `$`).\n */\nexport function agent(\n strings: TemplateStringsArray,\n ...values: readonly (string | Reference)[]\n): AgentStepBuilder {\n let prompt = \"\";\n const collectedInputs: Reference[] = [];\n\n for (let i = 0; i < strings.length; i++) {\n prompt += strings[i];\n if (i < values.length) {\n const v = values[i]!;\n if (typeof v === \"string\") {\n prompt += v;\n } else if (isReference(v)) {\n const ref = v;\n collectedInputs.push(ref);\n if (ref.kind === \"step\") {\n prompt += `\\${${ref.step}.${ref.output}}`;\n } else {\n prompt += `\\${${ref.namespace}.${ref.field}}`;\n }\n } else {\n throw new SdkError(\n `invalid interpolation value at position ${i}: expected string or Reference`,\n \"INVALID_INTERPOLATION\",\n );\n }\n }\n }\n\n return createAgentBuilder({\n prompt,\n engine: \"default\",\n tools: [],\n collectedInputs,\n });\n}\n","// Markdown authoring errors (Spec 37, extended by Spec 54).\n\nimport { SdkError } from \"./errors.js\";\n\nexport type MarkdownParseErrorCode =\n | \"INVALID_FRONTMATTER\"\n | \"INVALID_STEP\"\n | \"INVALID_TRIGGER\"\n | \"EXTENDS_NOT_FOUND\";\n\n/** Raised when a `.sverka.md` file cannot be parsed into a Project. */\nexport class MarkdownParseError extends SdkError {\n declare readonly code: MarkdownParseErrorCode;\n\n constructor(message: string, code: MarkdownParseErrorCode, cause?: unknown) {\n super(message, code, cause);\n this.name = \"MarkdownParseError\";\n }\n}\n","// Markdown authoring (Spec 37) — `.sverka.md` files: YAML frontmatter\n// (pipeline metadata, triggers, inputs, `extends`) + `## step` sections\n// with `- command:` bullets. Compiles through the same Construct API as\n// sverka.config.ts — the produced graph is identical, not approximate.\n//\n// Spec 54 extends the trigger set with `comment` and `issue` kinds and\n// accepts gh-aw-style `on:` shorthand so the same frontmatter shape works\n// for agentic GitLab workflows.\n//\n// Deliberate subset (per Spec 37 non-goals): shell steps only — agent\n// steps, safe-outputs, matrices and conditions use `extends` + TS.\n\nimport { readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { parse as parseYaml } from \"yaml\";\nimport {\n Construct,\n Project,\n Pipeline,\n ShellStep,\n Entry,\n} from \"@sverka/workflow\";\nimport type {\n Input,\n OutputDeclaration,\n Trigger,\n TriggerFilter,\n} from \"@sverka/workflow\";\nimport { MarkdownParseError } from \"./markdown-errors.js\";\n\n/** Frontmatter shape (Spec 37 + Spec 54 `on:` alias and event kinds). */\nexport interface MarkdownFrontmatter {\n readonly pipeline: string;\n readonly triggers?: readonly MarkdownTrigger[];\n /** gh-aw-style shorthand for `triggers`. */\n readonly on?: string | readonly string[] | Record<string, unknown>;\n readonly extends?: string;\n readonly inputs?: Readonly<Record<string, Input>>;\n}\n\n/** A single frontmatter trigger entry. */\nexport interface MarkdownTrigger {\n readonly kind:\n \"push\" | \"changeRequest\" | \"manual\" | \"schedule\" | \"comment\" | \"issue\";\n readonly branches?: readonly string[];\n readonly tags?: readonly string[];\n readonly paths?: readonly string[];\n readonly cron?: string;\n readonly timezone?: string;\n readonly mention?: string;\n readonly on?: \"mergeRequest\" | \"issue\" | \"commit\";\n readonly action?: \"opened\" | \"reopened\" | \"labeled\";\n readonly labels?: readonly string[];\n}\n\ninterface ParsedStep {\n readonly id: string;\n readonly command: string;\n readonly dependsOn?: readonly string[];\n readonly image?: string;\n readonly timeout?: number;\n readonly outputs?: Readonly<Record<string, OutputDeclaration>>;\n}\n\n/**\n * Parse a `.sverka.md` source string into a Project construct.\n * `filePath` anchors `extends` resolution and error messages; without it\n * `extends` cannot resolve and throws EXTENDS_NOT_FOUND.\n */\nexport function parseMarkdown(source: string, filePath?: string): Project {\n const { frontmatter, body } = splitFrontmatter(source, filePath);\n const project = new Project(frontmatter.pipeline);\n buildMarkdownPipeline(project, frontmatter, body, filePath);\n return project;\n}\n\n/**\n * Read + parse a `.sverka.md` file. When frontmatter declares `extends`,\n * the referenced config module is imported and the markdown pipeline is\n * merged into that Project (Spec 37 escape hatch).\n */\nexport async function loadMarkdownFile(path: string): Promise<Project> {\n const abs = isAbsolute(path) ? path : resolve(process.cwd(), path);\n let source: string;\n try {\n source = await readFile(abs, \"utf-8\");\n } catch (e) {\n throw new MarkdownParseError(\n `cannot read markdown file: ${abs}`,\n \"INVALID_FRONTMATTER\",\n e,\n );\n }\n const { frontmatter, body } = splitFrontmatter(source, abs);\n\n if (frontmatter.extends !== undefined) {\n const base = await loadExtends(frontmatter.extends, abs);\n buildMarkdownPipeline(base, frontmatter, body, abs);\n return base;\n }\n\n const project = new Project(frontmatter.pipeline);\n buildMarkdownPipeline(project, frontmatter, body, abs);\n return project;\n}\n\n// ---------------------------------------------------------------------------\n// Frontmatter\n// ---------------------------------------------------------------------------\n\nfunction splitFrontmatter(\n source: string,\n filePath?: string,\n): { frontmatter: MarkdownFrontmatter; body: string } {\n const where = filePath !== undefined ? ` in ${filePath}` : \"\";\n const m = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/.exec(source);\n if (m === null) {\n throw new MarkdownParseError(\n `invalid .sverka.md${where}: missing YAML frontmatter (expected '---' delimiters)`,\n \"INVALID_FRONTMATTER\",\n );\n }\n let parsed: unknown;\n try {\n parsed = parseYaml(m[1]!);\n } catch (e) {\n throw new MarkdownParseError(\n `invalid .sverka.md frontmatter${where}: ${e instanceof Error ? e.message : String(e)}`,\n \"INVALID_FRONTMATTER\",\n e,\n );\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new MarkdownParseError(\n `invalid .sverka.md frontmatter${where}: expected a mapping`,\n \"INVALID_FRONTMATTER\",\n );\n }\n const fm = parsed as Record<string, unknown>;\n if (typeof fm.pipeline !== \"string\" || fm.pipeline === \"\") {\n throw new MarkdownParseError(\n `invalid .sverka.md frontmatter${where}: missing required 'pipeline' field`,\n \"INVALID_FRONTMATTER\",\n );\n }\n return {\n frontmatter: fm as unknown as MarkdownFrontmatter,\n body: m[2]!,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Triggers\n// ---------------------------------------------------------------------------\n\nfunction frontmatterTriggers(fm: MarkdownFrontmatter): readonly Trigger[] {\n const raw = collectTriggerEntries(fm);\n return raw.map((entry, i) => toTrigger(entry, i));\n}\n\ninterface TriggerEntry {\n readonly kind: string;\n readonly opts: Record<string, unknown>;\n}\n\n/**\n * Normalize `triggers:` (array of objects) and `on:` (gh-aw shorthand:\n * string, list of kind strings, or map of kind → options) into uniform\n * entries. `triggers` wins when both are present.\n */\nfunction collectTriggerEntries(\n fm: MarkdownFrontmatter,\n): readonly TriggerEntry[] {\n if (fm.triggers !== undefined) {\n if (!Array.isArray(fm.triggers)) {\n throw new MarkdownParseError(\n \"invalid .sverka.md frontmatter: 'triggers' must be an array\",\n \"INVALID_TRIGGER\",\n );\n }\n return (fm.triggers as readonly Record<string, unknown>[]).map((t) => {\n if (typeof t !== \"object\" || t === null || typeof t.kind !== \"string\") {\n throw new MarkdownParseError(\n \"invalid .sverka.md trigger: each entry needs a string 'kind'\",\n \"INVALID_TRIGGER\",\n );\n }\n const { kind, ...opts } = t;\n return { kind, opts };\n });\n }\n if (fm.on === undefined) return [];\n const on = fm.on;\n if (typeof on === \"string\") return [{ kind: on, opts: {} }];\n if (Array.isArray(on)) {\n return on.map((kind) => {\n if (typeof kind !== \"string\") {\n throw new MarkdownParseError(\n \"invalid .sverka.md 'on': entries must be trigger kind strings\",\n \"INVALID_TRIGGER\",\n );\n }\n return { kind, opts: {} };\n });\n }\n if (typeof on === \"object\" && on !== null) {\n return Object.entries(on).map(([kind, opts]) => ({\n kind,\n opts:\n typeof opts === \"object\" && opts !== null\n ? (opts as Record<string, unknown>)\n : {},\n }));\n }\n throw new MarkdownParseError(\n \"invalid .sverka.md 'on': expected a trigger kind, list of kinds, or kind→options map\",\n \"INVALID_TRIGGER\",\n );\n}\n\nconst FILTER_KEYS = [\"branches\", \"tags\", \"paths\"] as const;\n\nfunction toTrigger(entry: TriggerEntry, index: number): Trigger {\n const { kind, opts } = entry;\n const at = `trigger[${index}] (${kind})`;\n const filter = buildFilter(opts, at);\n switch (kind) {\n case \"push\":\n return filter !== undefined ? { kind: \"push\", filter } : { kind: \"push\" };\n case \"changeRequest\":\n return filter !== undefined\n ? { kind: \"changeRequest\", filter }\n : { kind: \"changeRequest\" };\n case \"manual\":\n return filter !== undefined\n ? { kind: \"manual\", filter }\n : { kind: \"manual\" };\n case \"schedule\":\n return toScheduleTrigger(opts, at);\n case \"comment\":\n return toCommentTrigger(opts, at);\n case \"issue\":\n return toIssueTrigger(opts, at);\n default:\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: unknown trigger kind '${kind}'`,\n \"INVALID_TRIGGER\",\n );\n }\n}\n\nfunction toScheduleTrigger(opts: Record<string, unknown>, at: string): Trigger {\n if (typeof opts.cron !== \"string\" || opts.cron === \"\") {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: schedule trigger requires a 'cron' string`,\n \"INVALID_TRIGGER\",\n );\n }\n if (opts.timezone !== undefined && typeof opts.timezone !== \"string\") {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: schedule 'timezone' must be a string`,\n \"INVALID_TRIGGER\",\n );\n }\n return {\n kind: \"schedule\",\n cron: opts.cron,\n ...(opts.timezone !== undefined ? { timezone: opts.timezone } : {}),\n };\n}\n\nfunction toCommentTrigger(opts: Record<string, unknown>, at: string): Trigger {\n const on = opts.on;\n if (\n on !== undefined &&\n on !== \"mergeRequest\" &&\n on !== \"issue\" &&\n on !== \"commit\"\n ) {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: comment 'on' must be mergeRequest|issue|commit`,\n \"INVALID_TRIGGER\",\n );\n }\n // A dropped non-string mention silently widens a restricted trigger\n // into an unrestricted one — reject it instead.\n if (opts.mention !== undefined && typeof opts.mention !== \"string\") {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: comment 'mention' must be a string`,\n \"INVALID_TRIGGER\",\n );\n }\n return {\n kind: \"comment\",\n ...(opts.mention !== undefined ? { mention: opts.mention } : {}),\n ...(on !== undefined ? { on } : {}),\n };\n}\n\nfunction toIssueTrigger(opts: Record<string, unknown>, at: string): Trigger {\n const action = opts.action;\n if (\n action !== undefined &&\n action !== \"opened\" &&\n action !== \"reopened\" &&\n action !== \"labeled\"\n ) {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: issue 'action' must be opened|reopened|labeled`,\n \"INVALID_TRIGGER\",\n );\n }\n const labels = opts.labels;\n if (\n labels !== undefined &&\n (!Array.isArray(labels) || !labels.every((l) => typeof l === \"string\"))\n ) {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: issue 'labels' must be an array of strings`,\n \"INVALID_TRIGGER\",\n );\n }\n return {\n kind: \"issue\",\n ...(action !== undefined ? { action } : {}),\n ...(labels !== undefined ? { labels: labels as readonly string[] } : {}),\n };\n}\n\nfunction buildFilter(\n opts: Record<string, unknown>,\n at: string,\n): TriggerFilter | undefined {\n const filter: Record<string, readonly string[]> = {};\n for (const key of FILTER_KEYS) {\n const v = opts[key];\n if (v === undefined) continue;\n if (!Array.isArray(v) || !v.every((s) => typeof s === \"string\")) {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: '${key}' must be an array of strings`,\n \"INVALID_TRIGGER\",\n );\n }\n filter[key] = v as readonly string[];\n }\n return Object.keys(filter).length > 0 ? (filter as TriggerFilter) : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Steps\n// ---------------------------------------------------------------------------\n\nconst STEP_HEADING = /^##\\s+(\\S+)\\s*$/;\n\nfunction parseSteps(body: string): readonly ParsedStep[] {\n const steps: ParsedStep[] = [];\n const lines = body.split(\"\\n\");\n let i = 0;\n while (i < lines.length) {\n const heading = STEP_HEADING.exec(lines[i]!);\n if (heading === null) {\n i++;\n continue;\n }\n const id = heading[1]!;\n const section: string[] = [];\n let j = i + 1;\n while (j < lines.length && !STEP_HEADING.test(lines[j]!)) {\n section.push(lines[j]!);\n j++;\n }\n steps.push(parseStepSection(id, section));\n i = j;\n }\n return steps;\n}\n\n/**\n * Parse one `- key: value` bullet line. Hand-rolled linear scan — a regex\n * over uncontrolled markdown is a ReDoS vector.\n */\nfunction parseBulletLine(\n line: string,\n): { readonly key: string; readonly rest: string } | null {\n const isSpace = (c: string | undefined) => c !== undefined && /\\s/.test(c);\n const isKeyChar = (c: string | undefined) =>\n c !== undefined && /[\\w-]/.test(c);\n if (!line.startsWith(\"-\") || !isSpace(line[1])) return null;\n let i = skipWhile(line, 1, isSpace);\n if (!isKeyStart(line[i])) return null;\n const keyStart = i;\n i = skipWhile(line, i, isKeyChar);\n const key = line.slice(keyStart, i);\n i = skipWhile(line, i, isSpace);\n if (line[i] !== \":\") return null;\n return { key, rest: line.slice(i + 1).trimStart() };\n}\n\nfunction skipWhile(\n line: string,\n from: number,\n pred: (c: string | undefined) => boolean,\n): number {\n let i = from;\n while (i < line.length && pred(line[i])) i++;\n return i;\n}\n\nfunction isKeyStart(c: string | undefined): boolean {\n return c !== undefined && /[a-zA-Z_]/.test(c);\n}\n\n/**\n * Parse one `## step` section: `- key: value` bullets (indented blocks\n * belong to the preceding bullet). Non-bullet prose is ignored so a step\n * can carry documentation.\n */\nfunction parseStepSection(id: string, lines: readonly string[]): ParsedStep {\n return toParsedStep(id, collectStepProps(id, lines));\n}\n\n/** Validate collected props and build the ParsedStep. */\nfunction toParsedStep(id: string, props: Record<string, unknown>): ParsedStep {\n if (typeof props.command !== \"string\" || props.command === \"\") {\n throw new MarkdownParseError(\n `invalid .sverka.md step '${id}': missing required '- command:' line`,\n \"INVALID_STEP\",\n );\n }\n const dependsOn = props.dependsOn ?? props[\"depends_on\"];\n if (\n dependsOn !== undefined &&\n (!Array.isArray(dependsOn) ||\n !dependsOn.every((d) => typeof d === \"string\"))\n ) {\n throw new MarkdownParseError(\n `invalid .sverka.md step '${id}': 'dependsOn' must be an array of step ids`,\n \"INVALID_STEP\",\n );\n }\n if (\n props.timeout !== undefined &&\n (typeof props.timeout !== \"number\" || !Number.isFinite(props.timeout))\n ) {\n throw new MarkdownParseError(\n `invalid .sverka.md step '${id}': 'timeout' must be a number (ms)`,\n \"INVALID_STEP\",\n );\n }\n if (props.image !== undefined && typeof props.image !== \"string\") {\n throw new MarkdownParseError(\n `invalid .sverka.md step '${id}': 'image' must be a string`,\n \"INVALID_STEP\",\n );\n }\n\n return {\n id,\n command: props.command,\n ...(dependsOn !== undefined\n ? { dependsOn: dependsOn as readonly string[] }\n : {}),\n ...(props.image !== undefined ? { image: props.image as string } : {}),\n ...(props.timeout !== undefined\n ? { timeout: props.timeout as number }\n : {}),\n ...(props.outputs !== undefined\n ? {\n outputs: props.outputs as Readonly<Record<string, OutputDeclaration>>,\n }\n : {}),\n };\n}\n\n/**\n * Collect `- key: value` bullets (with indented continuation blocks) into\n * a props map. Non-bullet prose is ignored.\n */\nfunction collectStepProps(\n id: string,\n lines: readonly string[],\n): Record<string, unknown> {\n const props: Record<string, unknown> = {};\n let i = 0;\n while (i < lines.length) {\n const bullet = parseBulletLine(lines[i]!);\n if (bullet === null) {\n i++;\n continue;\n }\n const { key, rest } = bullet;\n if (rest === \"\") {\n // Nested block: collect the indented continuation lines.\n const block: string[] = [];\n let j = i + 1;\n while (j < lines.length && /^\\s+\\S/.test(lines[j]!)) {\n block.push(lines[j]!);\n j++;\n }\n props[key] =\n block.length > 0 ? parseYamlScalar(block.join(\"\\n\"), id, key) : null;\n i = j;\n } else {\n props[key] = parseYamlScalar(rest, id, key);\n i++;\n }\n }\n return props;\n}\n\nfunction parseYamlScalar(rest: string, stepId: string, key: string): unknown {\n try {\n return parseYaml(rest);\n } catch (e) {\n throw new MarkdownParseError(\n `invalid .sverka.md step '${stepId}': cannot parse '${key}' value: ${e instanceof Error ? e.message : String(e)}`,\n \"INVALID_STEP\",\n e,\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// Construct assembly\n// ---------------------------------------------------------------------------\n\nfunction buildMarkdownPipeline(\n scope: Project,\n fm: MarkdownFrontmatter,\n body: string,\n _filePath?: string,\n): void {\n const pipeline = new Pipeline(scope, fm.pipeline, {\n ...(fm.inputs !== undefined ? { inputs: fm.inputs } : {}),\n });\n const steps = parseSteps(body);\n // Construct registers into `pipeline` on construction — handles are kept\n // to read back the registered step ids as entry roots.\n const shellSteps = steps.map(\n (step) =>\n new ShellStep(pipeline, step.id, {\n command: step.command,\n ...(step.dependsOn !== undefined ? { dependsOn: step.dependsOn } : {}),\n ...(step.image !== undefined\n ? { runtime: { mode: \"container\", image: step.image } }\n : {}),\n ...(step.timeout !== undefined ? { timeout: step.timeout } : {}),\n ...(step.outputs !== undefined ? { outputs: step.outputs } : {}),\n }),\n );\n // Entry roots: every step — `on:` triggers the whole pipeline, matching\n // gh-aw semantics (reachability walks dependencies back to producers).\n const roots = shellSteps.map((s) => s.node.id);\n const triggers = frontmatterTriggers(fm);\n const usedIds = new Set<string>();\n for (const trigger of triggers) {\n const base = `on-${trigger.kind}`;\n let id = base;\n let n = 2;\n while (usedIds.has(id)) {\n id = `${base}-${n}`;\n n++;\n }\n const entry = new Entry(pipeline, id, { trigger, roots });\n usedIds.add(entry.node.id);\n }\n}\n\n// ---------------------------------------------------------------------------\n// extends\n// ---------------------------------------------------------------------------\n\nasync function loadExtends(\n extendsPath: string,\n mdPath: string,\n): Promise<Project> {\n const resolved = resolve(dirname(mdPath), extendsPath);\n if (!existsSync(resolved)) {\n throw new MarkdownParseError(\n `extends path does not resolve: ${extendsPath} (from ${mdPath})`,\n \"EXTENDS_NOT_FOUND\",\n );\n }\n let mod: Record<string, unknown>;\n try {\n mod = await import(pathToFileURL(resolved).href);\n } catch (e) {\n throw new MarkdownParseError(\n `failed to load extends config ${extendsPath}: ${e instanceof Error ? e.message : String(e)}`,\n \"EXTENDS_NOT_FOUND\",\n e,\n );\n }\n const construct = mod.project ?? mod.default;\n if (\n typeof construct !== \"object\" ||\n construct === null ||\n !(\"node\" in construct)\n ) {\n throw new MarkdownParseError(\n `extends config ${extendsPath} must export a Project or Pipeline`,\n \"EXTENDS_NOT_FOUND\",\n );\n }\n const node = (construct as Construct).node;\n // A bare Pipeline's scope is its implicitly-created Project — add the\n // markdown pipeline alongside it.\n return (node.scope ?? construct) as unknown as Project;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,SAAS,mBAA2B;CAClC,MAAM,UAAU,QAAQ,IAAI,QAAQ;CACpC,KAAK,MAAM,OAAO,QAAQ,MAAM,KAAK,SAAS,GAAG;EAC/C,IAAI,CAAC,KAAK;EACV,MAAM,YAAY,KAAK,KAAK,KAAK,KAAK;EACtC,IAAI,WAAW,SAAS,GACtB,OAAO;CAEX;CACA,OAAO;AACT;AAEA,MAAM,aAAa,iBAAiB;;;;AAKpC,SAAgB,eAAuB;CACrC,OAAO,EACL,IAAI,MAAM,KAAK;EACb,OAAO,IAAI,SAAiB,gBAAgB,WAAW;GAGrD,MAAM,MAAyB;IAC7B,MAAM,QAAQ,IAAI;IAClB,qBAAqB;GACvB;GACA,MAAM,QAAQ,MAAM,YAAY,CAAC,GAAG,IAAI,GAAG;IACzC;IACA;IACA,OAAO;KAAC;KAAU;KAAQ;IAAM;GAClC,CAAC;GACD,IAAI,SAAS;GACb,IAAI,SAAS;GACb,MAAM,QAAQ,GAAG,SAAS,SAAiB;IACzC,UAAU,KAAK,SAAS;GAC1B,CAAC;GACD,MAAM,QAAQ,GAAG,SAAS,SAAiB;IAC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AC9D,GAAI,KAAK,YAAY,SAAY,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;CAChE,CAAC,CAIS,CAAA,CAAW,KAAK,MAAM,EAAE,KAAK,EAAE;CAC7C,MAAM,WAAW,oBAAoB,EAAE;CACvC,MAAM,0BAAU,IAAI,IAAY;CAChC,KAAK,MAAM,WAAW,UAAU;EAC9B,MAAM,OAAO,MAAM,QAAQ;EAC3B,IAAI,KAAK;EACT,IAAI,IAAI;EACR,OAAO,QAAQ,IAAI,EAAE,GAAG;GACtB,KAAK,GAAG,KAAK,GAAG;GAChB;EACF;EACA,MAAM,QAAQ,IAAI,MAAM,UAAU,IAAI;GAAE;GAAS;EAAM,CAAC;EACxD,QAAQ,IAAI,MAAM,KAAK,EAAE;CAC3B;AACF;AAMA,eAAe,YACb,aACA,QACkB;CAClB,MAAM,WAAW,QAAQ,QAAQ,MAAM,GAAG,WAAW;CACrD,IAAI,CAAC,WAAW,QAAQ,GACtB,MAAM,IAAI,mBACR,kCAAkC,YAAY,SAAS,OAAO,IAC9D,mBACF;CAEF,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,OAAO,cAAc,QAAQ,CAAC,CAAC;CAC7C,SAAS,GAAG;EACV,MAAM,IAAI,mBACR,iCAAiC,YAAY,IAAI,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,KAC1F,qBACA,CACF;CACF;CACA,MAAM,YAAY,IAAI,WAAW,IAAI;CACrC,IACE,OAAO,cAAc,YACrB,cAAc,QACd,EAAE,UAAU,YAEZ,MAAM,IAAI,mBACR,kBAAkB,YAAY,qCAC9B,mBACF;CAKF,OAHc,UAAwB,KAGzB,SAAS;AACxB"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["basename","bindRunPlanImpl","computePlanId","createBuiltinResolver","validatePlan","extractFindings","loadBaseline","filterOnlyNew","createPolicy","DEFAULT_POLICY","evaluatePolicy","workflow","pipeline","when","run","matrix","parseYaml","descriptor"],"sources":["../src/planner/internal/git-cli.ts","../src/planner/detect.ts","../src/planner/explain.ts","../src/planner/errors.ts","../src/planner/bind.ts","../src/planner/planner.ts","../src/planner/matrix.ts","../src/errors.ts","../src/compat/config.ts","../src/compat/convert.ts","../src/compat/internal/plan-runtime.ts","../src/sverka.ts","../src/compat/helpers.ts","../src/internal/is-reference.ts","../src/dollar.ts","../src/shell.ts","../src/artifact.ts","../src/pipeline.ts","../src/call-pipeline.ts","../src/component.ts","../src/when.ts","../src/expr.ts","../src/status.ts","../src/internal/proxy-props.ts","../src/images.ts","../src/context.ts","../src/agent.ts","../src/markdown-errors.ts","../src/markdown.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * A mockable seam over the `git` CLI. Unit tests mock this via `vi.mock`;\n * integration tests use the real implementation.\n *\n * NOT exported from the public API.\n */\nexport interface GitCli {\n /**\n * Run a git command in `cwd`, returning stdout. Rejects with an Error\n * whose `cause` carries stderr when the exit code is non-zero.\n */\n run(args: readonly string[], cwd: string): Promise<string>;\n}\n\n/**\n * Resolve the absolute path to the `git` executable by searching `PATH`\n * at this trusted parent level. The spawned child receives a minimal\n * environment without `PATH`, mitigating PATH-injection hotspots.\n */\nfunction resolveGitBinary(): string {\n const pathEnv = process.env.PATH ?? \"\";\n for (const dir of pathEnv.split(path.delimiter)) {\n if (!dir) continue;\n const candidate = path.join(dir, \"git\");\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n return \"git\";\n}\n\nconst GIT_BINARY = resolveGitBinary();\n\n/**\n * Default `GitCli` implementation backed by `node:child_process.spawn`.\n */\nexport function createGitCli(): GitCli {\n return {\n run(args, cwd) {\n return new Promise<string>((resolvePromise, reject) => {\n // Spawn the resolved git binary with a minimal, explicit environment\n // that does not propagate PATH into the child subprocess.\n const env: NodeJS.ProcessEnv = {\n HOME: process.env.HOME,\n GIT_TERMINAL_PROMPT: \"0\",\n };\n const child = spawn(GIT_BINARY, [...args], {\n cwd,\n env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.on(\"data\", (data: Buffer) => {\n stdout += data.toString();\n });\n child.stderr?.on(\"data\", (data: Buffer) => {\n stderr += data.toString();\n });\n child.on(\"error\", (err) => {\n reject(err);\n });\n child.on(\"close\", (code) => {\n if (code === 0) {\n resolvePromise(stdout);\n } else {\n reject(\n new Error(\n `git ${args.join(\" \")} exited ${code ?? -1}`,\n stderr.trim() ? { cause: stderr.trim() } : undefined,\n ),\n );\n }\n });\n });\n },\n };\n}\n","import type {\n LocalSignal,\n DetectedLanguage,\n DetectedPackageManager,\n PackageManagerName,\n MonorepoMarker,\n MonorepoTool,\n} from \"./planner.js\";\n\n// --- manifest / lockfile / dockerfile / ci / monorepo-marker rules ---\n\nconst MANIFEST_FILES: ReadonlySet<string> = new Set([\n \"package.json\",\n \"pyproject.toml\",\n \"Cargo.toml\",\n \"go.mod\",\n \"pom.xml\",\n \"build.gradle\",\n \"composer.json\",\n]);\n\nconst LOCKFILE_MAP: Readonly<Record<string, PackageManagerName>> = {\n \"bun.lock\": \"bun\",\n \"bun.lockb\": \"bun\",\n \"package-lock.json\": \"npm\",\n \"yarn.lock\": \"yarn\",\n \"pnpm-lock.yaml\": \"pnpm\",\n \"poetry.lock\": \"poetry\",\n \"Cargo.lock\": \"cargo\",\n \"go.sum\": \"go\",\n};\n\nconst MONOREPO_MARKER_FILES: Readonly<Record<string, MonorepoTool>> = {\n \"nx.json\": \"nx\",\n \"turbo.json\": \"turborepo\",\n \"lerna.json\": \"lerna\",\n \"pnpm-workspace.yaml\": \"pnpm-workspace\",\n};\n\n/**\n * Detect local signals from a file list. Pure: no I/O.\n */\nexport function detectSignals(files: readonly string[]): LocalSignal[] {\n const signals: LocalSignal[] = [];\n for (const file of files) {\n const base = basename(file);\n // manifest\n if (MANIFEST_FILES.has(base)) {\n signals.push({\n type: \"manifest\",\n path: file,\n detail: null,\n confidence: 1.0,\n });\n continue;\n }\n // lockfile\n if (Object.hasOwn(LOCKFILE_MAP, base)) {\n signals.push({\n type: \"lockfile\",\n path: file,\n detail: null,\n confidence: 1.0,\n });\n continue;\n }\n // dockerfile\n if (base === \"Dockerfile\" || base.endsWith(\".Dockerfile\")) {\n signals.push({\n type: \"dockerfile\",\n path: file,\n detail: null,\n confidence: 1.0,\n });\n continue;\n }\n // docker-compose\n if (base === \"docker-compose.yml\" || base === \"docker-compose.yaml\") {\n signals.push({\n type: \"docker-compose\",\n path: file,\n detail: null,\n confidence: 1.0,\n });\n continue;\n }\n // ci-definition\n if (isCiDefinition(file, base)) {\n signals.push({\n type: \"ci-definition\",\n path: file,\n detail: null,\n confidence: 1.0,\n });\n continue;\n }\n // monorepo-marker (file-based only; package.json workspaces handled in detectMonorepo)\n if (Object.hasOwn(MONOREPO_MARKER_FILES, base)) {\n signals.push({\n type: \"monorepo-marker\",\n path: file,\n detail: null,\n confidence: 1.0,\n });\n }\n }\n return signals;\n}\n\nfunction isCiDefinition(file: string, base: string): boolean {\n if (\n base === \".gitlab-ci.yml\" ||\n base === \"azure-pipelines.yml\" ||\n base === \"Jenkinsfile\"\n ) {\n return true;\n }\n if (\n file.startsWith(\".github/workflows/\") &&\n (base.endsWith(\".yml\") || base.endsWith(\".yaml\"))\n ) {\n return true;\n }\n if (file.startsWith(\".circleci/\")) {\n return true;\n }\n return false;\n}\n\n// --- language detection ---\n\nconst EXTENSION_MAP: Readonly<Record<string, string>> = {\n \".ts\": \"TypeScript\",\n \".tsx\": \"TypeScript\",\n \".js\": \"JavaScript\",\n \".jsx\": \"JavaScript\",\n \".mjs\": \"JavaScript\",\n \".cjs\": \"JavaScript\",\n \".py\": \"Python\",\n \".rs\": \"Rust\",\n \".go\": \"Go\",\n \".java\": \"Java\",\n \".kt\": \"Kotlin\",\n \".rb\": \"Ruby\",\n \".php\": \"PHP\",\n \".cs\": \"C#\",\n \".cpp\": \"C++\",\n \".cc\": \"C++\",\n \".cxx\": \"C++\",\n \".c\": \"C\",\n \".h\": \"C\",\n \".hpp\": \"C++\",\n \".swift\": \"Swift\",\n \".scala\": \"Scala\",\n \".sh\": \"Shell\",\n \".bash\": \"Shell\",\n};\n\nexport function detectLanguages(files: readonly string[]): DetectedLanguage[] {\n const counts = new Map<string, string[]>();\n for (const file of files) {\n const ext = extname(file);\n const lang = EXTENSION_MAP[ext];\n if (!lang) continue;\n const entry = counts.get(lang);\n if (entry) {\n entry.push(ext);\n } else {\n counts.set(lang, [ext]);\n }\n }\n const out: DetectedLanguage[] = [];\n for (const [name, exts] of counts) {\n const fileCount = exts.length;\n const confidence = Math.min(1.0, fileCount / 10);\n out.push({\n name,\n confidence,\n evidence: [...new Set(exts)],\n fileCount,\n });\n }\n out.sort((a, b) => b.fileCount - a.fileCount || a.name.localeCompare(b.name));\n return out;\n}\n\n// --- package manager detection ---\n\nconst MANIFEST_PACKAGE_MANAGER: Readonly<Record<string, PackageManagerName>> = {\n \"go.mod\": \"go\",\n \"Cargo.toml\": \"cargo\",\n};\n\nexport function detectPackageManagers(\n signals: readonly LocalSignal[],\n rootPkgJson: Record<string, unknown> | null,\n): DetectedPackageManager[] {\n const byName = new Map<PackageManagerName, DetectedPackageManager>();\n collectLockfilePackageManagers(signals, byName);\n collectManifestPackageManagers(signals, byName);\n applyPackageManagerField(rootPkgJson, byName);\n return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/** Populate `byName` from lockfile signals. */\nfunction collectLockfilePackageManagers(\n signals: readonly LocalSignal[],\n byName: Map<PackageManagerName, DetectedPackageManager>,\n): void {\n for (const sig of signals) {\n if (sig.type !== \"lockfile\") continue;\n const base = basename(sig.path);\n const name = LOCKFILE_MAP[base];\n if (!name) {\n // Unknown lockfile → \"other\"\n const other = byName.get(\"other\");\n if (other) {\n other.evidence.push(sig.path);\n } else {\n byName.set(\"other\", {\n name: \"other\",\n version: null,\n lockfile: sig.path,\n evidence: [sig.path],\n });\n }\n continue;\n }\n const existing = byName.get(name);\n if (existing) {\n if (!existing.evidence.includes(sig.path)) {\n existing.evidence.push(sig.path);\n }\n } else {\n byName.set(name, {\n name,\n version: null,\n lockfile: sig.path,\n evidence: [sig.path],\n });\n }\n }\n}\n\n/** Populate `byName` from manifest signals for ecosystems without a lockfile or when the manifest is the primary signal. */\nfunction collectManifestPackageManagers(\n signals: readonly LocalSignal[],\n byName: Map<PackageManagerName, DetectedPackageManager>,\n): void {\n for (const sig of signals) {\n if (sig.type !== \"manifest\") continue;\n const base = basename(sig.path);\n const name = MANIFEST_PACKAGE_MANAGER[base];\n if (!name || byName.has(name)) continue;\n byName.set(name, {\n name,\n version: null,\n lockfile: null,\n evidence: [sig.path],\n });\n }\n}\n\n/** Apply the `packageManager` field override from the root package.json. */\nfunction applyPackageManagerField(\n rootPkgJson: Record<string, unknown> | null,\n byName: Map<PackageManagerName, DetectedPackageManager>,\n): void {\n if (!rootPkgJson) return;\n const pm = rootPkgJson[\"packageManager\"];\n if (typeof pm !== \"string\") return;\n const { tool, version } = parsePackageManager(pm);\n if (!tool) return;\n const existing = byName.get(tool);\n if (existing) {\n existing.version = version;\n if (!existing.evidence.includes(\"package.json#packageManager\")) {\n existing.evidence.push(\"package.json#packageManager\");\n }\n } else {\n byName.set(tool, {\n name: tool,\n version,\n lockfile: null,\n evidence: [\"package.json#packageManager\"],\n });\n }\n}\n\nfunction parsePackageManager(pm: string): {\n tool: PackageManagerName | null;\n version: string | null;\n} {\n // e.g. \"bun@1.3.14\", \"pnpm@9.12.0\"\n const atIdx = pm.indexOf(\"@\");\n if (atIdx <= 0) return { tool: null, version: null };\n const toolName = pm.slice(0, atIdx);\n const version = pm.slice(atIdx + 1) || null;\n const valid: PackageManagerName[] = [\n \"npm\",\n \"yarn\",\n \"pnpm\",\n \"bun\",\n \"pip\",\n \"poetry\",\n \"uv\",\n \"pipenv\",\n \"cargo\",\n \"go\",\n \"maven\",\n \"gradle\",\n \"composer\",\n \"other\",\n ];\n if (!valid.includes(toolName as PackageManagerName)) {\n return { tool: null, version };\n }\n return { tool: toolName as PackageManagerName, version };\n}\n\n// --- monorepo detection ---\n\nexport function detectMonorepo(\n signals: readonly LocalSignal[],\n rootPkgJson: Record<string, unknown> | null,\n): MonorepoMarker | null {\n const globs = rootPkgJson\n ? extractWorkspaceGlobs(rootPkgJson[\"workspaces\"])\n : [];\n const workspaces = resolveWorkspaceDirs(signals, globs);\n\n // File-based markers first.\n for (const sig of signals) {\n if (sig.type !== \"monorepo-marker\") continue;\n const base = basename(sig.path);\n const tool = MONOREPO_MARKER_FILES[base];\n if (tool) {\n return {\n tool,\n workspaces,\n evidence:\n globs.length > 0 ? [sig.path, \"package.json#workspaces\"] : [sig.path],\n };\n }\n }\n\n // Root package.json with workspaces field.\n if (globs.length > 0 && rootPkgJson) {\n const tool: MonorepoTool = isBunWorkspace(rootPkgJson)\n ? \"bun-workspace\"\n : \"custom\";\n return {\n tool,\n workspaces,\n evidence: [\"package.json#workspaces\"],\n };\n }\n\n return null;\n}\n\n/**\n * Resolve workspace globs to concrete workspace dirs using manifest signals.\n * A dir is a workspace when `<dir>/package.json` appears as a manifest and\n * `<dir>` matches a workspace glob (`*` = one path segment, `**` = any depth).\n */\nfunction resolveWorkspaceDirs(\n signals: readonly LocalSignal[],\n globs: readonly string[],\n): string[] {\n const positive = globs.filter((g) => !g.startsWith(\"!\"));\n const negative = globs\n .filter((g) => g.startsWith(\"!\"))\n .map((g) => g.slice(1));\n const dirs = new Set<string>();\n for (const sig of signals) {\n if (sig.type !== \"manifest\" || !sig.path.endsWith(\"/package.json\"))\n continue;\n const dir = sig.path.slice(0, sig.path.length - \"/package.json\".length);\n if (\n positive.some((g) => matchesWorkspaceGlob(dir, g)) &&\n !negative.some((g) => matchesWorkspaceGlob(dir, g))\n ) {\n dirs.add(dir);\n }\n }\n return [...dirs].sort((a, b) => a.localeCompare(b));\n}\n\nfunction matchesWorkspaceGlob(dir: string, glob: string): boolean {\n const d = dir.split(\"/\");\n const g = glob.split(\"/\");\n const memo = new Map<string, boolean>();\n const match = (di: number, gi: number): boolean => {\n const key = `${di}:${gi}`;\n const cached = memo.get(key);\n if (cached !== undefined) return cached;\n let result: boolean;\n if (gi === g.length) {\n result = di === d.length;\n } else if (g[gi] === \"**\") {\n result = false;\n for (let k = di; k <= d.length && !result; k++) {\n result = match(k, gi + 1);\n }\n } else {\n result =\n di < d.length &&\n matchesGlobSegment(d[di] as string, g[gi] as string) &&\n match(di + 1, gi + 1);\n }\n memo.set(key, result);\n return result;\n };\n return match(0, 0);\n}\n\nfunction matchesGlobSegment(segment: string, pattern: string): boolean {\n let s = 0;\n let p = 0;\n let starP = -1;\n let starS = -1;\n while (s < segment.length) {\n if (\n p < pattern.length &&\n (pattern[p] === \"?\" || pattern[p] === segment[s])\n ) {\n s++;\n p++;\n } else if (p < pattern.length && pattern[p] === \"*\") {\n starP = p++;\n starS = s;\n } else if (starP !== -1) {\n p = starP + 1;\n s = ++starS;\n } else {\n return false;\n }\n }\n while (p < pattern.length && pattern[p] === \"*\") p++;\n return p === pattern.length;\n}\n\nfunction extractWorkspaceGlobs(ws: unknown): string[] {\n if (Array.isArray(ws)) {\n return ws.filter((g): g is string => typeof g === \"string\");\n }\n if (typeof ws === \"object\" && ws !== null) {\n const packages = (ws as Record<string, unknown>)[\"packages\"];\n if (Array.isArray(packages)) {\n return packages.filter((g): g is string => typeof g === \"string\");\n }\n }\n return [];\n}\n\nfunction isBunWorkspace(pkgJson: Record<string, unknown>): boolean {\n const pm = pkgJson[\"packageManager\"];\n return typeof pm === \"string\" && pm.startsWith(\"bun\");\n}\n\n// --- helpers ---\n\nfunction basename(path: string): string {\n const idx = path.lastIndexOf(\"/\");\n return idx >= 0 ? path.slice(idx + 1) : path;\n}\n\nfunction extname(path: string): string {\n const base = basename(path);\n const idx = base.lastIndexOf(\".\");\n return idx >= 0 ? base.slice(idx) : \"\";\n}\n","import type {\n LocalSignal,\n LocalSignalType,\n DiscoveryExplanation,\n} from \"./planner.js\";\n\nconst SIGNAL_TYPES: readonly LocalSignalType[] = [\n \"manifest\",\n \"lockfile\",\n \"dockerfile\",\n \"docker-compose\",\n \"ci-definition\",\n \"monorepo-marker\",\n \"git-metadata\",\n];\n\n/**\n * Build a `DiscoveryExplanation` from the collected signals. Pure.\n */\nexport function buildExplanation(\n signals: readonly LocalSignal[],\n opts: { hasBaseRef: boolean; dirty: boolean },\n): DiscoveryExplanation {\n const counts = {} as Record<LocalSignalType, number>;\n for (const t of SIGNAL_TYPES) {\n counts[t] = 0;\n }\n for (const sig of signals) {\n counts[sig.type] = (counts[sig.type] ?? 0) + 1;\n }\n\n const parts: string[] = [];\n const total = signals.length;\n parts.push(`${total} signal${total === 1 ? \"\" : \"s\"}`);\n const nonzero = SIGNAL_TYPES.filter((t) => counts[t] > 0);\n if (nonzero.length) {\n parts.push(`(${formatSignalCounts(nonzero, counts)})`);\n }\n if (opts.dirty) {\n parts.push(\"working tree dirty\");\n } else {\n parts.push(\"working tree clean\");\n }\n if (!opts.hasBaseRef) {\n parts.push(\"no baseRef provided\");\n }\n\n return {\n summary: parts.join(\" \"),\n signalCounts: counts,\n };\n}\n\n/** Format non-zero signal counts as \"type=count, type=count\". */\nfunction formatSignalCounts(\n types: readonly LocalSignalType[],\n counts: Readonly<Record<LocalSignalType, number>>,\n): string {\n return types.map((t) => t + \"=\" + counts[t]).join(\", \");\n}\n","/**\n * Base error class for the planner package. All discovery failures throw a\n * `DiscoveryError` with one of the four `DiscoveryErrorCode` values.\n */\nexport class DiscoveryError extends Error {\n readonly code: DiscoveryErrorCode;\n override readonly cause: unknown;\n constructor(message: string, code: DiscoveryErrorCode, cause?: unknown) {\n super(message);\n this.name = \"DiscoveryError\";\n this.code = code;\n this.cause = cause;\n }\n}\n\nexport type DiscoveryErrorCode =\n | \"ROOT_NOT_FOUND\"\n | \"GIT_UNAVAILABLE\"\n | \"GIT_NOT_A_REPO\"\n | \"TRAVERSAL_FAILED\"\n | \"INVALID_BASE_REF\";\n\n/**\n * Planner error for Run Plan binding failures. Spec 13 — Error handling.\n */\nexport class PlannerError extends Error {\n readonly code: PlannerErrorCode;\n override readonly cause: unknown;\n constructor(message: string, code: PlannerErrorCode, cause?: unknown) {\n super(message);\n this.name = \"PlannerError\";\n this.code = code;\n this.cause = cause;\n }\n}\n\nexport type PlannerErrorCode =\n | \"ENTRY_NOT_FOUND\"\n | \"ROOT_NOT_FOUND\"\n | \"MISSING_INPUT\"\n | \"INVALID_INPUT\"\n | \"INVALID_GRAPH\"\n | \"INVALID_MATRIX\";\n","// Run Plan binding — binds a Definition Graph's Entry + inputs into a RunPlan.\n// Spec 13 — §22.1 component 1. Architecture spec §10, §22.\n\nimport type {\n DefinitionGraph,\n StepDefinition,\n PipelineDefinition,\n EntryDefinition,\n Input,\n} from \"@sverka/workflow\";\nimport { validateGraph, expandPipelineCalls } from \"@sverka/workflow\";\nimport type { RunPlan, InputValue, BoundEntry } from \"@sverka/workflow\";\nimport { computeGraphId, computeRunPlanId } from \"@sverka/workflow\";\nimport { PlannerError } from \"./errors.js\";\n\nexport interface BindRunPlanOptions {\n readonly graph: DefinitionGraph;\n readonly entryId: string;\n readonly inputs?: Readonly<Record<string, InputValue>>;\n}\n\nconst INPUT_TYPES = new Set<Input[\"type\"]>([\"string\", \"number\", \"boolean\"]);\n\n/**\n * Bind a Definition Graph's Entry + user inputs into a concrete RunPlan\n * that the native engine can execute.\n */\nexport function bindRunPlan(options: BindRunPlanOptions): RunPlan {\n const { graph, entryId, inputs } = options;\n\n validateGraphShape(graph);\n\n if (graph.project.pipelines.length === 0) {\n throw new PlannerError(\"graph has no pipelines\", \"INVALID_GRAPH\");\n }\n\n const { pipeline, entry } = findEntry(graph, entryId);\n validateRoots(pipeline, entry);\n validatePipeline(graph, pipeline);\n\n const reachableSteps = computeReachableSteps(pipeline.steps, entry.roots);\n // Expand pipeline-call steps into inline callee steps for the native engine.\n const expandedSteps = expandPipelineCalls(graph, reachableSteps);\n const boundInputs = bindInputs(pipeline.inputs, inputs);\n\n const graphId = computeGraphId(graph);\n\n const boundEntry: BoundEntry = {\n id: entry.id,\n trigger: entry.trigger,\n };\n\n const planBody = {\n apiVersion: \"sverka.dev/v1run\" as const,\n graphId,\n entry: boundEntry,\n inputs: boundInputs,\n steps: expandedSteps,\n };\n\n const id = computeRunPlanId(planBody as Omit<RunPlan, \"id\" | \"createdAt\">);\n\n const createdAt = new Date().toISOString();\n\n return {\n apiVersion: \"sverka.dev/v1run\",\n id,\n graphId,\n entry: boundEntry,\n inputs: boundInputs,\n steps: expandedSteps,\n createdAt,\n };\n}\n\n/**\n * Validate that the runtime value has the shape of a DefinitionGraph before\n * any field is dereferenced. Malformed values become PlannerError(INVALID_GRAPH)\n * instead of TypeError.\n */\nfunction validateGraphShape(value: DefinitionGraph): void {\n const graph = value as unknown as Record<string, unknown>;\n\n if (typeof graph !== \"object\" || graph === null) {\n throw new PlannerError(\"graph must be an object\", \"INVALID_GRAPH\");\n }\n\n const project = graph.project;\n if (typeof project !== \"object\" || project === null) {\n throw new PlannerError(\"graph.project must be an object\", \"INVALID_GRAPH\");\n }\n\n const pipelines = (project as Record<string, unknown>).pipelines;\n if (!Array.isArray(pipelines)) {\n throw new PlannerError(\n \"graph.project.pipelines must be an array\",\n \"INVALID_GRAPH\",\n );\n }\n\n for (let i = 0; i < pipelines.length; i++) {\n const pipeline = pipelines[i] as Record<string, unknown>;\n validatePipelineShape(pipeline, i);\n }\n}\n\nfunction validatePipelineShape(value: unknown, index: number): void {\n const pipeline = value as Record<string, unknown>;\n if (typeof pipeline !== \"object\" || pipeline === null) {\n throw new PlannerError(\n `graph.project.pipelines[${index}] must be an object`,\n \"INVALID_GRAPH\",\n );\n }\n validatePipelineFields(pipeline, index);\n validatePipelineChildren(pipeline, index);\n}\n\nfunction validatePipelineFields(\n pipeline: Record<string, unknown>,\n index: number,\n): void {\n if (typeof pipeline.id !== \"string\") {\n throw new PlannerError(\n `graph.project.pipelines[${index}].id must be a string`,\n \"INVALID_GRAPH\",\n );\n }\n if (!Array.isArray(pipeline.entries)) {\n throw new PlannerError(\n `graph.project.pipelines[${index}].entries must be an array`,\n \"INVALID_GRAPH\",\n );\n }\n if (!Array.isArray(pipeline.steps)) {\n throw new PlannerError(\n `graph.project.pipelines[${index}].steps must be an array`,\n \"INVALID_GRAPH\",\n );\n }\n if (\n typeof pipeline.inputs !== \"object\" ||\n pipeline.inputs === null ||\n Array.isArray(pipeline.inputs)\n ) {\n throw new PlannerError(\n `graph.project.pipelines[${index}].inputs must be an object`,\n \"INVALID_GRAPH\",\n );\n }\n}\n\nfunction validatePipelineChildren(\n pipeline: Record<string, unknown>,\n index: number,\n): void {\n const inputs = pipeline.inputs as Record<string, unknown>;\n for (const [name, descriptor] of Object.entries(inputs)) {\n validateInputDescriptor(descriptor, index, name);\n }\n const entries = pipeline.entries;\n if (!Array.isArray(entries)) return;\n const steps = pipeline.steps;\n if (!Array.isArray(steps)) return;\n for (let j = 0; j < entries.length; j++) {\n validateEntryShape(entries[j], index, j);\n }\n for (let j = 0; j < steps.length; j++) {\n validateStepShape(steps[j], index, j);\n }\n}\n\nfunction validateInputDescriptor(\n value: unknown,\n pipelineIndex: number,\n name: string,\n): void {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].inputs.${name} must be an object`,\n \"INVALID_GRAPH\",\n );\n }\n\n const descriptor = value as Record<string, unknown>;\n const type = descriptor.type;\n if (type !== undefined && !INPUT_TYPES.has(type as Input[\"type\"])) {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].inputs.${name} has invalid type`,\n \"INVALID_GRAPH\",\n );\n }\n}\n\nfunction validateEntryShape(\n value: unknown,\n pipelineIndex: number,\n index: number,\n): void {\n const entry = value as Record<string, unknown>;\n if (typeof entry !== \"object\" || entry === null) {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].entries[${index}] must be an object`,\n \"INVALID_GRAPH\",\n );\n }\n if (typeof entry.id !== \"string\") {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].entries[${index}].id must be a string`,\n \"INVALID_GRAPH\",\n );\n }\n if (!Array.isArray(entry.roots)) {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].entries[${index}].roots must be an array`,\n \"INVALID_GRAPH\",\n );\n }\n}\n\nfunction validateStepShape(\n value: unknown,\n pipelineIndex: number,\n index: number,\n): void {\n const step = value as Record<string, unknown>;\n if (typeof step !== \"object\" || step === null) {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].steps[${index}] must be an object`,\n \"INVALID_GRAPH\",\n );\n }\n if (typeof step.id !== \"string\") {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].steps[${index}].id must be a string`,\n \"INVALID_GRAPH\",\n );\n }\n if (!Array.isArray(step.dependencies)) {\n throw new PlannerError(\n `graph.project.pipelines[${pipelineIndex}].steps[${index}].dependencies must be an array`,\n \"INVALID_GRAPH\",\n );\n }\n}\n\n/**\n * Compute the transitive closure of reachable steps from the given roots.\n * A step is reachable if it is connected to a root by following\n * `dependencies[].producer` edges backward (i.e. the root's prerequisites).\n * Returns steps in the original graph order, filtered to reachable steps.\n */\nexport function computeReachableSteps(\n steps: readonly StepDefinition[],\n roots: readonly string[],\n): readonly StepDefinition[] {\n const producerMap = buildProducerMap(steps);\n\n const reachable = new Set<string>();\n const queue: string[] = [];\n\n for (const id of roots) {\n if (!reachable.has(id)) {\n reachable.add(id);\n queue.push(id);\n }\n }\n\n let head = 0;\n while (head < queue.length) {\n const id = queue[head]!;\n head++;\n for (const producer of producerMap.get(id) ?? []) {\n if (!reachable.has(producer)) {\n reachable.add(producer);\n queue.push(producer);\n }\n }\n }\n\n return steps.filter((s) => reachable.has(s.id));\n}\n\n/**\n * Build a map from each step id to the list of producer step ids it depends on.\n */\nfunction buildProducerMap(\n steps: readonly StepDefinition[],\n): Map<string, string[]> {\n const map = new Map<string, string[]>();\n for (const step of steps) {\n const producers: string[] = [];\n map.set(step.id, producers);\n for (const dep of step.dependencies) {\n producers.push(dep.producer);\n }\n }\n return map;\n}\n\nfunction findEntry(\n graph: DefinitionGraph,\n entryId: string,\n): { pipeline: PipelineDefinition; entry: EntryDefinition } {\n for (const pipeline of graph.project.pipelines) {\n const entry = pipeline.entries.find((e) => e.id === entryId);\n if (entry) return { pipeline, entry };\n }\n throw new PlannerError(`entry \"${entryId}\" not found`, \"ENTRY_NOT_FOUND\");\n}\n\nfunction validateRoots(\n pipeline: PipelineDefinition,\n entry: EntryDefinition,\n): void {\n const stepIds = new Set(pipeline.steps.map((s) => s.id));\n for (const root of entry.roots) {\n if (!stepIds.has(root)) {\n throw new PlannerError(\n `entry root \"${root}\" not found in pipeline steps`,\n \"ROOT_NOT_FOUND\",\n );\n }\n }\n}\n\nfunction validatePipeline(\n graph: DefinitionGraph,\n pipeline: PipelineDefinition,\n): void {\n try {\n validateGraph({\n project: {\n id: graph.project.id,\n pipelines: [pipeline],\n },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new PlannerError(message, \"INVALID_GRAPH\", err);\n }\n}\n\nfunction bindInputs(\n pipelineInputs: Readonly<Record<string, Input>>,\n userInputs: Readonly<Record<string, InputValue>> | undefined,\n): Readonly<Record<string, InputValue>> {\n const result: Record<string, InputValue> = {};\n\n for (const [name, input] of Object.entries(pipelineInputs)) {\n const type = input.type as Input[\"type\"] | undefined;\n validateInputType(name, type);\n\n if (input.secret) {\n // Secret values are not embedded in the RunPlan. They are resolved at\n // runtime from a secrets context by name.\n continue;\n }\n\n const userValue = userInputs?.[name];\n if (userValue !== undefined) {\n assertInputValue(userValue, type, name);\n result[name] = userValue;\n continue;\n }\n\n if (input.default !== undefined) {\n assertInputValue(input.default, type, name);\n result[name] = input.default;\n continue;\n }\n\n if (input.required ?? true) {\n throw new PlannerError(\n `required input \"${name}\" has no value and no default`,\n \"MISSING_INPUT\",\n );\n }\n }\n\n return result;\n}\n\nfunction validateInputType(\n name: string,\n type: Input[\"type\"] | undefined,\n): asserts type is Input[\"type\"] {\n if (type === undefined || !INPUT_TYPES.has(type)) {\n throw new PlannerError(\n `input \"${name}\" has no valid declared type`,\n \"INVALID_GRAPH\",\n );\n }\n}\n\nfunction assertInputValue(\n value: InputValue,\n type: Input[\"type\"],\n name: string,\n): void {\n if (type === \"array\") {\n if (\n !Array.isArray(value) ||\n !value.every((item) => typeof item === \"string\")\n ) {\n throw new PlannerError(\n `input \"${name}\" value ${JSON.stringify(value)} does not match declared type \"array\" (expected string array)`,\n \"INVALID_INPUT\",\n );\n }\n return;\n }\n const expected = type === \"choice\" ? \"string\" : type;\n const actual = typeof value;\n if (actual !== expected) {\n throw new PlannerError(\n `input \"${name}\" value ${JSON.stringify(value)} does not match declared type \"${type}\"`,\n \"INVALID_INPUT\",\n );\n }\n}\n","import type {\n ProjectContext,\n ChangedFile,\n DetectedLanguage,\n PackageManagerName,\n DetectedPackageManager,\n MonorepoTool,\n MonorepoMarker,\n LocalSignalType,\n LocalSignal,\n ProposedCheck,\n DiscoveryExplanation,\n} from \"@sverka/workflow\";\nexport type {\n ProjectContext,\n ChangedFile,\n DetectedLanguage,\n PackageManagerName,\n DetectedPackageManager,\n MonorepoTool,\n MonorepoMarker,\n LocalSignalType,\n LocalSignal,\n ProposedCheck,\n DiscoveryExplanation,\n};\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { createGitCli, type GitCli } from \"./internal/git-cli.js\";\nimport {\n detectSignals,\n detectLanguages,\n detectPackageManagers,\n detectMonorepo,\n} from \"./detect.js\";\nimport { buildExplanation } from \"./explain.js\";\nimport { DiscoveryError } from \"./errors.js\";\nimport {\n bindRunPlan as bindRunPlanImpl,\n type BindRunPlanOptions,\n} from \"./bind.js\";\nimport type { RunPlan } from \"@sverka/workflow\";\n\n/**\n * Top-level entry point for discovery and plan synthesis.\n */\nexport interface Planner {\n discover(options: DiscoverOptions): Promise<ProjectContext>;\n plan(context: ProjectContext): Promise<PlanProposal>;\n bindRunPlan(options: BindRunPlanOptions): RunPlan;\n}\n\nexport function createPlanner(): Planner {\n return new PlannerImpl();\n}\n\nexport interface DiscoverOptions {\n root: string;\n baseRef?: string;\n maxDepth?: number;\n /**\n * When true and `root` is a subdirectory of the git repository, detection\n * signals, languages, and package managers are computed from the subtree\n * under `root` instead of the whole repository. Use for commands whose\n * generated steps execute with cwd=`root` (e.g. `init --detect`). Git\n * metadata (commit, dirty, changedFiles) stays repository-wide.\n */\n scopeToRoot?: boolean;\n}\n\nexport interface PlanProposal {\n context: ProjectContext;\n checks: readonly ProposedCheck[];\n workflowPath: string | null;\n notes: readonly string[];\n}\n\nconst DEFAULT_MAX_DEPTH = 10;\n\nclass PlannerImpl implements Planner {\n private readonly git: GitCli;\n\n constructor() {\n this.git = createGitCli();\n }\n\n async discover(options: DiscoverOptions): Promise<ProjectContext> {\n const root = options.root;\n if (!existsSync(root)) {\n throw new DiscoveryError(\n `root directory not found: ${root}`,\n \"ROOT_NOT_FOUND\",\n );\n }\n await assertGitAvailable(this.git, root);\n const toplevel = await resolveToplevel(this.git, root);\n const { tracked, untracked, porcelain } = await collectGitFiles(\n this.git,\n toplevel,\n );\n const allFiles = [...new Set([...tracked, ...untracked])];\n const scoped =\n options.scopeToRoot === true\n ? scopeFilesToRoot(allFiles, toplevel, root)\n : null;\n const projectRoot = scoped?.dir ?? toplevel;\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;\n const filtered = applyMaxDepth(scoped?.files ?? allFiles, maxDepth);\n\n const signals = detectSignals(filtered);\n const languages = detectLanguages(filtered);\n const rootPkgJson = readRootPackageJson(projectRoot);\n const packageManagers = detectPackageManagers(signals, rootPkgJson);\n const monorepo = detectMonorepo(signals, rootPkgJson);\n const hasContainerBuild = signals.some(\n (s) => s.type === \"dockerfile\" || s.type === \"docker-compose\",\n );\n const hasCiDefinition = signals.some((s) => s.type === \"ci-definition\");\n\n const commit = await resolveHeadCommit(this.git, toplevel);\n const dirty = porcelain.length > 0;\n const changedFiles = await collectChangedFiles(\n this.git,\n toplevel,\n options.baseRef,\n );\n\n const gitSignal: LocalSignal = {\n type: \"git-metadata\",\n path: \".git\",\n detail: commit ? `HEAD=${commit.slice(0, 12)}` : \"no commits\",\n confidence: 1.0,\n };\n const allSignals = [...signals, gitSignal];\n\n const explanation = buildExplanation(allSignals, {\n hasBaseRef: Boolean(options.baseRef),\n dirty,\n });\n\n return {\n root: projectRoot,\n commit,\n dirty,\n changedFiles,\n languages,\n packageManagers,\n hasContainerBuild,\n hasCiDefinition,\n monorepo,\n localSignals: allSignals,\n explanation,\n };\n }\n\n async plan(context: ProjectContext): Promise<PlanProposal> {\n return synthesizePlan(context);\n }\n\n bindRunPlan(options: BindRunPlanOptions): RunPlan {\n return bindRunPlanImpl(options);\n }\n}\n\nfunction applyMaxDepth(files: string[], maxDepth: number): string[] {\n return files.filter((f) => f.split(\"/\").length <= maxDepth);\n}\n\n/**\n * Restrict repo-relative `files` to the subtree under `root`, re-rooting\n * paths relative to `root`. Returns null when `root` is not inside the\n * repository (should not happen — toplevel is resolved from `root`).\n */\nfunction scopeFilesToRoot(\n files: readonly string[],\n toplevel: string,\n root: string,\n): { dir: string; files: string[] } | null {\n const dir = realpathSync(resolve(root));\n // Git paths are always slash-separated — normalize for Windows.\n const prefix = relative(toplevel, dir).split(sep).join(\"/\");\n if (prefix.startsWith(\"..\") || isAbsolute(prefix)) return null;\n if (prefix === \"\") return { dir, files: [...files] };\n const scoped = files\n .filter((f) => f.startsWith(prefix + \"/\"))\n .map((f) => f.slice(prefix.length + 1));\n return { dir, files: scoped };\n}\n\n/** Throw `GIT_UNAVAILABLE` if git is not on PATH. */\nasync function assertGitAvailable(git: GitCli, root: string): Promise<void> {\n try {\n await git.run([\"--version\"], root);\n } catch (err) {\n throw new DiscoveryError(\n \"git is not installed or not on PATH\",\n \"GIT_UNAVAILABLE\",\n err,\n );\n }\n}\n\n/** Resolve the repository toplevel, throwing `GIT_NOT_A_REPO` on failure. */\nasync function resolveToplevel(git: GitCli, root: string): Promise<string> {\n try {\n const out = await git.run([\"rev-parse\", \"--show-toplevel\"], root);\n return out.trim();\n } catch (err) {\n throw new DiscoveryError(\n `not a git repository: ${root}`,\n \"GIT_NOT_A_REPO\",\n err,\n );\n }\n}\n\n/** Collect tracked files, untracked files, and porcelain lines from git. */\nasync function collectGitFiles(\n git: GitCli,\n toplevel: string,\n): Promise<{ tracked: string[]; untracked: string[]; porcelain: string[] }> {\n let trackedRaw: string;\n let porcelainRaw: string;\n try {\n trackedRaw = await git.run([\"ls-files\"], toplevel);\n porcelainRaw = await git.run([\"status\", \"--porcelain\", \"-uall\"], toplevel);\n } catch (err) {\n throw new DiscoveryError(\n \"filesystem traversal failed\",\n \"TRAVERSAL_FAILED\",\n err,\n );\n }\n const tracked = trackedRaw.split(\"\\n\").filter(Boolean);\n const porcelain = porcelainRaw.split(\"\\n\").filter(Boolean);\n const untracked = extractUntracked(porcelain);\n return { tracked, untracked, porcelain };\n}\n\n/** Extract untracked file paths from porcelain status lines. */\nfunction extractUntracked(porcelain: readonly string[]): string[] {\n const untracked: string[] = [];\n for (const line of porcelain) {\n const status = line.slice(0, 2);\n const path = line.slice(3).trim();\n if (status.includes(\"??\")) {\n untracked.push(path);\n }\n }\n return untracked;\n}\n\n/** Resolve the HEAD commit SHA, returning \"\" on failure. */\nasync function resolveHeadCommit(\n git: GitCli,\n toplevel: string,\n): Promise<string> {\n try {\n const out = await git.run([\"rev-parse\", \"HEAD\"], toplevel);\n return out.trim();\n } catch {\n return \"\";\n }\n}\n\nconst REF_RE = /^[A-Za-z0-9_./~^\\-@{}]+$/;\n\nfunction validateBaseRef(baseRef: string): void {\n if (baseRef.startsWith(\"-\") || !REF_RE.test(baseRef)) {\n throw new DiscoveryError(`invalid baseRef: ${baseRef}`, \"INVALID_BASE_REF\");\n }\n}\n\n/** Collect changed files against `baseRef` when provided. */\nasync function collectChangedFiles(\n git: GitCli,\n toplevel: string,\n baseRef: string | undefined,\n): Promise<ChangedFile[]> {\n if (!baseRef) return [];\n validateBaseRef(baseRef);\n try {\n const diff = await git.run(\n [\"diff\", \"--name-status\", `${baseRef}...HEAD`, \"--\"],\n toplevel,\n );\n return parseDiffNameStatus(diff);\n } catch (err) {\n throw new DiscoveryError(\n `failed to diff against baseRef \"${baseRef}\"`,\n \"TRAVERSAL_FAILED\",\n err,\n );\n }\n}\n\nfunction readRootPackageJson(root: string): Record<string, unknown> | null {\n try {\n const raw = readFileSync(`${root}/package.json`, \"utf8\");\n return JSON.parse(raw) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\nfunction parseDiffNameStatus(diff: string): ChangedFile[] {\n const out: ChangedFile[] = [];\n for (const line of diff.split(\"\\n\").filter(Boolean)) {\n const parts = line.split(\"\\t\");\n const code = parts[0] ?? \"\";\n // Rename records have the format \"R<score>\\told\\tnew\"; use the new path.\n const path = code.startsWith(\"R\") ? (parts[2] ?? \"\") : (parts[1] ?? \"\");\n if (!path) continue;\n out.push({ path, status: diffStatusCode(code) });\n }\n return out;\n}\n\n/** Map a git diff --name-status code to a `ChangedFile` status. */\nfunction diffStatusCode(code: string): ChangedFile[\"status\"] {\n if (code.startsWith(\"A\")) return \"added\";\n if (code.startsWith(\"M\")) return \"modified\";\n if (code.startsWith(\"D\")) return \"deleted\";\n if (code.startsWith(\"R\")) return \"renamed\";\n return \"modified\";\n}\n\ninterface PlanDriver {\n checkId: string;\n reason: string;\n languages: string[];\n packageManagers: PackageManagerName[];\n}\n\nconst PLAN_DRIVERS: readonly PlanDriver[] = [\n {\n checkId: \"typecheck\",\n reason: \"Node project defaults\",\n languages: [\"TypeScript\", \"JavaScript\"],\n packageManagers: [\"npm\", \"yarn\", \"pnpm\", \"bun\"],\n },\n {\n checkId: \"lint\",\n reason: \"Node project defaults\",\n languages: [\"TypeScript\", \"JavaScript\"],\n packageManagers: [\"npm\", \"yarn\", \"pnpm\", \"bun\"],\n },\n {\n checkId: \"test\",\n reason: \"Node project defaults\",\n languages: [\"TypeScript\", \"JavaScript\"],\n packageManagers: [\"npm\", \"yarn\", \"pnpm\", \"bun\"],\n },\n {\n checkId: \"lint\",\n reason: \"Python project defaults\",\n languages: [\"Python\"],\n packageManagers: [\"pip\", \"poetry\", \"uv\", \"pipenv\"],\n },\n {\n checkId: \"test\",\n reason: \"Python project defaults\",\n languages: [\"Python\"],\n packageManagers: [\"pip\", \"poetry\", \"uv\", \"pipenv\"],\n },\n {\n checkId: \"fmt-check\",\n reason: \"Rust project defaults\",\n languages: [\"Rust\"],\n packageManagers: [\"cargo\"],\n },\n {\n checkId: \"clippy\",\n reason: \"Rust project defaults\",\n languages: [\"Rust\"],\n packageManagers: [\"cargo\"],\n },\n {\n checkId: \"test\",\n reason: \"Rust project defaults\",\n languages: [\"Rust\"],\n packageManagers: [\"cargo\"],\n },\n {\n checkId: \"vet\",\n reason: \"Go project defaults\",\n languages: [\"Go\"],\n packageManagers: [\"go\"],\n },\n {\n checkId: \"test\",\n reason: \"Go project defaults\",\n languages: [\"Go\"],\n packageManagers: [\"go\"],\n },\n];\n\nfunction synthesizePlan(context: ProjectContext): PlanProposal {\n const langNames = context.languages.map((l) => l.name);\n const pmNames = context.packageManagers.map((p) => p.name);\n const signalRef = resolveSignalRef(context.localSignals);\n const checks = collectDefaultChecks(\n PLAN_DRIVERS,\n langNames,\n pmNames,\n signalRef,\n );\n const notes = buildPlanNotes(checks, langNames, pmNames);\n return { context, checks, workflowPath: null, notes };\n}\n\n/** Resolve the signal reference for the first manifest/lockfile signal. */\nfunction resolveSignalRef(signals: readonly LocalSignal[]): string | null {\n const manifestSignal =\n signals.find((s) => s.type === \"manifest\" || s.type === \"lockfile\") ?? null;\n return manifestSignal\n ? `${manifestSignal.type}:${manifestSignal.path}`\n : null;\n}\n\n/** Collect deduplicated default checks that match the detected languages/package managers. */\nfunction collectDefaultChecks(\n drivers: readonly PlanDriver[],\n langNames: readonly string[],\n pmNames: readonly PackageManagerName[],\n signalRef: string | null,\n): ProposedCheck[] {\n const checks: ProposedCheck[] = [];\n const seen = new Set<string>();\n for (const driver of drivers) {\n const langMatch = driver.languages.some((l) => langNames.includes(l));\n const pmMatch = driver.packageManagers.some((p) => pmNames.includes(p));\n if (!langMatch || !pmMatch) continue;\n const key = `${driver.checkId}:${driver.reason}`;\n if (seen.has(key)) continue;\n seen.add(key);\n const id = makeCheckId(driver.checkId, driver.reason);\n checks.push({\n id,\n checkId: driver.checkId,\n reason: driver.reason,\n signalRef,\n priority: 2,\n });\n }\n return checks;\n}\n\n/** Build a stable proposed-check id from its checkId and reason. */\nfunction makeCheckId(checkId: string, reason: string): string {\n const digest = createHash(\"sha256\")\n .update(checkId + reason)\n .digest(\"hex\")\n .slice(0, 16);\n return \"prop-\" + digest;\n}\n\n/** Build human-readable notes describing the selected checks. */\nfunction buildPlanNotes(\n checks: readonly ProposedCheck[],\n langNames: readonly string[],\n pmNames: readonly PackageManagerName[],\n): string[] {\n if (checks.length === 0) {\n return [\n \"No default checks applied: no recognized languages or package managers detected.\",\n ];\n }\n const drivers: string[] = [];\n if (langNames.length) drivers.push(`languages=[${langNames.join(\",\")}]`);\n if (pmNames.length) drivers.push(`packageManagers=[${pmNames.join(\",\")}]`);\n return [\n `Selected ${checks.length} default checks from ${drivers.join(\" \")}.`,\n ];\n}\n","// Matrix expansion — expands matrix steps into concrete step instances.\n// F-15 — plan-time expansion for the native engine.\n\nimport type {\n StepDefinition,\n Dependency,\n MatrixSpec,\n MatrixValue,\n Reference,\n} from \"@sverka/workflow\";\nimport { PlannerError } from \"./errors.js\";\n\ntype MatrixCombination = Record<string, MatrixValue>;\n\n/**\n * Expand all matrix steps in a step list into concrete step instances.\n * Non-matrix steps pass through unchanged.\n *\n * - Each matrix step becomes N steps, one per combination (cross-product of\n * dimensions, minus exclude, plus include).\n * - Each expanded step gets `matrixValues` (the concrete bindings) and\n * `matrix: undefined` (the spec is consumed).\n * - Expanded step IDs: `<originalId>[key=val,key=val]` (keys sorted alphabetically).\n * - Dependencies are rewired: a dependency on a matrix step maps to ALL\n * expanded instances (all-to-all, no correlation matching in M1).\n */\nexport function expandMatrixSteps(\n steps: readonly StepDefinition[],\n): readonly StepDefinition[] {\n const expansionMap = new Map<string, StepDefinition[]>();\n let hasMatrix = false;\n for (const step of steps) {\n if (step.matrix) {\n hasMatrix = true;\n expansionMap.set(step.id, expandStep(step));\n } else {\n expansionMap.set(step.id, [step]);\n }\n }\n\n if (!hasMatrix) {\n return steps;\n }\n\n const result: StepDefinition[] = [];\n for (const step of steps) {\n const expanded = expansionMap.get(step.id)!;\n for (const expStep of expanded) {\n result.push(rewireDependencies(expStep, expansionMap));\n }\n }\n return result;\n}\n\nfunction expandStep(step: StepDefinition): StepDefinition[] {\n const spec = step.matrix!;\n\n if (spec.maxParallel !== undefined) {\n if (!Number.isInteger(spec.maxParallel) || spec.maxParallel < 1) {\n throw new PlannerError(\n `matrix on step '${step.id}' has invalid maxParallel: must be a positive integer (got ${spec.maxParallel})`,\n \"INVALID_MATRIX\",\n );\n }\n }\n\n const combinations = computeCombinations(spec);\n\n if (combinations.length === 0) {\n throw new PlannerError(\n `matrix on step '${step.id}' produced no combinations (check exclude rules)`,\n \"INVALID_MATRIX\",\n );\n }\n\n return combinations.map((combo) => {\n const { matrix: _consumed, ...rest } = step;\n return {\n ...rest,\n id: formatExpandedId(step.id, combo),\n matrixValues: combo,\n dependencies: step.dependencies,\n ...(spec.failFast !== undefined ? { matrixFailFast: spec.failFast } : {}),\n ...(spec.maxParallel !== undefined\n ? { matrixMaxParallel: spec.maxParallel }\n : {}),\n };\n });\n}\n\nfunction computeCombinations(spec: MatrixSpec): readonly MatrixCombination[] {\n const keys = Object.keys(spec.dimensions);\n if (keys.length === 0) {\n return (spec.include ?? []).map((e) => ({ ...e }));\n }\n\n const combinations = applyExcludes(\n crossProduct(spec.dimensions, keys),\n spec.exclude ?? [],\n );\n return mergeIncludes(combinations, spec.include ?? []);\n}\n\n/**\n * Compute the cross-product of all matrix dimensions.\n * Throws INVALID_MATRIX if any dimension has no values.\n */\nfunction crossProduct(\n dimensions: Readonly<Record<string, readonly MatrixValue[]>>,\n keys: readonly string[],\n): MatrixCombination[] {\n let combinations: MatrixCombination[] = [{}];\n for (const key of keys) {\n const values = dimensions[key];\n if (!values || values.length === 0) {\n throw new PlannerError(\n `matrix dimension '${key}' has no values`,\n \"INVALID_MATRIX\",\n );\n }\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 return combinations;\n}\n\n/** Filter out combinations matching any exclude rule (partial match). */\nfunction applyExcludes(\n combinations: readonly MatrixCombination[],\n exclude: readonly Readonly<Record<string, MatrixValue>>[],\n): MatrixCombination[] {\n if (exclude.length === 0) return [...combinations];\n return combinations.filter((c) => !matchesAnyRule(c, exclude));\n}\n\n/** Merge include entries, deduplicating against existing combinations. */\nfunction mergeIncludes(\n combinations: readonly MatrixCombination[],\n include: readonly Readonly<Record<string, MatrixValue>>[],\n): readonly MatrixCombination[] {\n const includeEntries = include.map((e) => ({ ...e }));\n const existingKeys = new Set(combinations.map(comboKey));\n const uniqueIncludes = includeEntries.filter(\n (e) => !existingKeys.has(comboKey(e)),\n );\n return [...combinations, ...uniqueIncludes];\n}\n\nfunction matchesAnyRule(\n combo: MatrixCombination,\n rules: readonly Readonly<Record<string, MatrixValue>>[],\n): boolean {\n for (const rule of rules) {\n const entries = Object.entries(rule);\n if (entries.length === 0) continue;\n if (entries.every(([k, v]) => combo[k] === v)) return true;\n }\n return false;\n}\n\n/** Produce a deterministic string key for a combination (sorted key=value pairs). */\nfunction comboKey(combo: MatrixCombination): string {\n return Object.keys(combo)\n .sort((a, b) => a.localeCompare(b))\n .map((k) => `${k}=${String(combo[k])}`)\n .join(\",\");\n}\n\nfunction formatExpandedId(id: string, combo: MatrixCombination): string {\n const parts = Object.keys(combo)\n .sort((a, b) => a.localeCompare(b))\n .map((k) => `${k}=${combo[k]}`);\n return `${id}[${parts.join(\",\")}]`;\n}\n\nfunction rewireDependencies(\n step: StepDefinition,\n expansionMap: Map<string, StepDefinition[]>,\n): StepDefinition {\n const hasDeps = step.dependencies.length > 0;\n const hasInputs = step.inputs.length > 0;\n if (!hasDeps && !hasInputs) return step;\n\n const newDeps = hasDeps\n ? rewireDeps(step.dependencies, expansionMap)\n : step.dependencies;\n const newInputs = hasInputs\n ? rewireInputs(step.inputs, expansionMap)\n : step.inputs;\n\n return { ...step, dependencies: newDeps, inputs: newInputs };\n}\n\nfunction rewireDeps(\n deps: readonly Dependency[],\n expansionMap: Map<string, StepDefinition[]>,\n): Dependency[] {\n const newDeps: Dependency[] = [];\n const seen = new Set<string>();\n\n for (const dep of deps) {\n const expanded = expansionMap.get(dep.producer);\n if (!expanded) {\n addDep(newDeps, seen, dep);\n continue;\n }\n // Rewire to all expanded instances — even when there's only one,\n // because the expanded step has a new ID (e.g. \"step[node=18]\").\n for (const expStep of expanded) {\n addDep(newDeps, seen, { ...dep, producer: expStep.id });\n }\n }\n return newDeps;\n}\n\nfunction rewireInputs(\n inputs: readonly Reference[],\n expansionMap: Map<string, StepDefinition[]>,\n): Reference[] {\n const newInputs: Reference[] = [];\n const seen = new Set<string>();\n\n for (const ref of inputs) {\n if (ref.kind !== \"step\") {\n newInputs.push(ref);\n continue;\n }\n const expanded = expansionMap.get(ref.step);\n if (!expanded) {\n newInputs.push(ref);\n continue;\n }\n // Rewire to all expanded instances — even when there's only one,\n // because the expanded step has a new ID (e.g. \"step[node=18]\").\n for (const expStep of expanded) {\n const rewired = { ...ref, step: expStep.id };\n const key = `${rewired.step}:${rewired.output}`;\n if (seen.has(key)) continue;\n seen.add(key);\n newInputs.push(rewired);\n }\n }\n return newInputs;\n}\n\nfunction addDep(deps: Dependency[], seen: Set<string>, dep: Dependency): void {\n const key =\n dep.kind === \"control\"\n ? `control:${dep.producer}`\n : `${dep.kind}:${dep.producer}:${dep.output}`;\n if (seen.has(key)) return;\n seen.add(key);\n deps.push(dep);\n}\n","// Error classes for @sverka/sdk. Spec 03 — Error handling.\n\nexport type SdkErrorCode =\n | \"INVALID_INTERPOLATION\"\n | \"INVALID_IMAGE\"\n // Legacy config-discovery codes retained while CLI migrates to the new SDK API.\n | \"CONFIG_NOT_FOUND\"\n | \"CONFIG_INVALID\"\n | \"CONFIG_LOAD_FAILED\"\n | \"CONFIG_PATH_ESCAPE\"\n | \"EXECUTION_FAILED\"\n // Markdown authoring (Spec 37/54).\n | \"INVALID_FRONTMATTER\"\n | \"INVALID_STEP\"\n | \"INVALID_TRIGGER\"\n | \"EXTENDS_NOT_FOUND\";\n\nexport class SdkError extends Error {\n override readonly cause?: unknown;\n readonly code: SdkErrorCode;\n\n constructor(message: string, code: SdkErrorCode, cause?: unknown) {\n super(message);\n this.name = \"SdkError\";\n this.code = code;\n if (cause !== undefined) {\n this.cause = cause;\n }\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { resolve, dirname, basename, isAbsolute, relative } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { WorkflowDefinition } from \"./types.js\";\nimport { SdkError } from \"../errors.js\";\n\nconst CONFIG_NAMES = [\"sverka.config.ts\", \"sverka.config.js\"];\nconst MAX_PARENTS = 5;\n\n/**\n * Search upward from `root` for sverka.config.ts (then .js). Returns the\n * path or null. Searches up to 5 parent directories.\n */\nexport async function findConfig(root: string): Promise<string | null> {\n let dir = resolve(root);\n for (let i = 0; i <= MAX_PARENTS; i++) {\n for (const name of CONFIG_NAMES) {\n const candidate = resolve(dir, name);\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n const parent = dirname(dir);\n if (parent === dir) break; // reached filesystem root\n dir = parent;\n }\n return null;\n}\n\n/**\n * Dynamically import a sverka.config.ts file and return its default\n * export as a WorkflowDefinition. Validates the shape.\n *\n * Under Bun, .ts files import natively. Under Node, use the .js fallback\n * (findConfig searches .ts first, then .js).\n */\nexport async function loadWorkflow(\n configPath: string,\n root?: string,\n): Promise<WorkflowDefinition> {\n const resolved = isAbsolute(configPath)\n ? resolve(configPath)\n : resolve(root ?? process.cwd(), configPath);\n\n if (!existsSync(resolved)) {\n throw new SdkError(\n `config file not found: ${configPath}`,\n \"CONFIG_NOT_FOUND\",\n );\n }\n\n if (root !== undefined) {\n const rel = relative(resolve(root), resolved);\n if (rel === \"\" || rel.startsWith(\"..\") || isAbsolute(rel)) {\n throw new SdkError(\n `config path escapes root: ${configPath}`,\n \"CONFIG_PATH_ESCAPE\",\n );\n }\n }\n\n let mod: unknown;\n try {\n const url = pathToFileURL(resolved).href;\n mod = await import(url);\n } catch (e) {\n throw new SdkError(\n `failed to load config: ${basename(configPath)}`,\n \"CONFIG_LOAD_FAILED\",\n e,\n );\n }\n\n const def = (mod as { default?: unknown }).default;\n validateDefaultExport(def);\n validateWorkflowShape(def.workflow as Record<string, unknown>);\n\n return def as unknown as WorkflowDefinition;\n}\n\nfunction validateDefaultExport(\n def: unknown,\n): asserts def is Record<string, unknown> {\n if (!isPlainObject(def)) {\n throw new SdkError(\n \"config default export must be an object\",\n \"CONFIG_INVALID\",\n );\n }\n\n if (typeof def.name !== \"string\" || def.name.length === 0) {\n throw new SdkError(\n \"config default export must have a non-empty 'name' string\",\n \"CONFIG_INVALID\",\n );\n }\n\n if (!isPlainObject(def.workflow)) {\n throw new SdkError(\n \"config default export must have a 'workflow' object\",\n \"CONFIG_INVALID\",\n );\n }\n}\n\n// Accept either a Workflow (has 'roots' array and 'plan' function) or\n// a bare Operation (has 'kind' and 'spec'). The SDK normalizes Operations\n// to Workflows at runtime.\nfunction validateWorkflowShape(wf: Record<string, unknown>): void {\n const isWorkflow = Array.isArray(wf.roots) && typeof wf.plan === \"function\";\n const isOperation = typeof wf.kind === \"string\" && isPlainObject(wf.spec);\n if (!isWorkflow && !isOperation) {\n throw new SdkError(\n \"config 'workflow' must be a Workflow (with 'roots' and 'plan') or an Operation (with 'kind' and 'spec')\",\n \"CONFIG_INVALID\",\n );\n }\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n","import { createHash } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { canonicalStringify } from \"@sverka/workflow\";\nimport type {\n OperationSpec,\n CacheDeclaration as CoreCacheDeclaration,\n ArtifactDeclaration as CoreArtifactDeclaration,\n} from \"@sverka/workflow\";\nimport type {\n Plan,\n PlanOperation,\n PlanMetadata,\n ExecutorSpec,\n ResourceLimits,\n PlanRetryPolicy,\n PlanCacheDeclaration,\n PlanArtifactDeclaration,\n} from \"@sverka/workflow\";\nimport { computePlanId } from \"@sverka/workflow\";\nimport type { ProjectContext } from \"../planner/index.js\";\nimport { SdkError } from \"../errors.js\";\n\nconst SVERKA_VERSION: string = ((): string => {\n let raw: string = \"\";\n try {\n raw = readFileSync(new URL(\"../package.json\", import.meta.url), \"utf-8\");\n } catch {\n try {\n raw = readFileSync(\n new URL(\"../../package.json\", import.meta.url),\n \"utf-8\",\n );\n } catch {\n return \"0.0.0\";\n }\n }\n const parsed: unknown = JSON.parse(raw);\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n \"version\" in parsed &&\n typeof (parsed as Record<string, unknown>).version === \"string\"\n ) {\n return (parsed as { version: string }).version;\n }\n return \"0.0.0\";\n})();\n\nexport interface ConvertOptions {\n /** Plan name (from WorkflowDefinition.name or default). */\n name: string;\n /** Executor type to fill for operations without an image. */\n executor: \"host\" | \"docker\";\n /** Project context for sourceContextHash. */\n context?: ProjectContext;\n}\n\n/**\n * Convert an array of OperationSpecs into a validated IR Plan with all\n * defaults filled per the spec's conversion table.\n */\nexport function convertToPlan(\n operations: readonly OperationSpec[],\n opts: ConvertOptions,\n): Plan {\n const planOps = operations.map((spec) => convertOperation(spec, opts));\n\n const sourceContextHash = computeSourceContextHash(opts.context);\n const metadata: PlanMetadata = {\n sverkaVersion: SVERKA_VERSION,\n generatedBy: \"manual\",\n };\n\n const body: Omit<Plan, \"id\" | \"createdAt\"> = {\n apiVersion: \"sverka.dev/v1\",\n name: opts.name,\n sourceContextHash,\n operations: planOps,\n metadata,\n };\n\n const id = computePlanId(body);\n const createdAt = new Date().toISOString();\n\n return { ...body, id, createdAt };\n}\n\nfunction convertOperation(\n spec: OperationSpec,\n opts: ConvertOptions,\n): PlanOperation {\n if (!spec.id || spec.id.length === 0) {\n throw new SdkError(\n `operation has empty id (kind=${spec.kind}, name=${spec.name})`,\n \"EXECUTION_FAILED\",\n );\n }\n\n const executor = buildExecutor(spec, opts);\n const resources = buildResources(spec);\n const retry = buildRetry(spec);\n const artifacts = (spec.artifacts ?? []).map(convertArtifact);\n const cache = spec.cache ? convertCache(spec.cache) : undefined;\n\n return buildPlanOperation(spec, executor, resources, retry, artifacts, cache);\n}\n\nfunction buildExecutor(\n spec: OperationSpec,\n opts: ConvertOptions,\n): ExecutorSpec {\n return {\n type: opts.executor,\n ...(spec.image !== undefined ? { image: spec.image } : {}),\n ...(spec.imageDigest !== undefined\n ? { imageDigest: spec.imageDigest }\n : {}),\n };\n}\n\nfunction buildResources(spec: OperationSpec): ResourceLimits {\n return {\n cpu: spec.cpuLimit ?? \"1\",\n memory: spec.memoryLimit ?? \"512Mi\",\n };\n}\n\nfunction buildRetry(spec: OperationSpec): PlanRetryPolicy {\n const retries = spec.retries ?? 0;\n return {\n maxAttempts: Math.max(1, retries + 1),\n backoffSeconds: 0,\n retryOn: [\"failure\", \"timeout\"],\n };\n}\n\nfunction buildPlanOperation(\n spec: OperationSpec,\n executor: ExecutorSpec,\n resources: ResourceLimits,\n retry: PlanRetryPolicy,\n artifacts: PlanArtifactDeclaration[],\n cache: PlanCacheDeclaration | undefined,\n): PlanOperation {\n return {\n id: spec.id,\n kind: spec.kind,\n name: spec.name,\n ...optionalFields(spec),\n ...resolveDefaults(spec),\n executor,\n resources,\n ...(cache !== undefined ? { cache } : {}),\n artifacts,\n retry,\n };\n}\n\ntype DefaultedField =\n | \"dependsOn\"\n | \"network\"\n | \"credentials\"\n | \"timeoutSeconds\"\n | \"continueOnError\";\n\nfunction valueOrDefault<T>(value: T | undefined, defaultValue: T): T {\n return value === undefined ? defaultValue : value;\n}\n\n/** Resolve fields with default values to reduce buildPlanOperation complexity. */\nfunction resolveDefaults(\n spec: OperationSpec,\n): Required<Pick<PlanOperation, DefaultedField>> {\n return {\n dependsOn: valueOrDefault(spec.dependsOn, []),\n network: valueOrDefault(spec.network, \"deny\"),\n credentials: valueOrDefault(spec.credentials, []),\n timeoutSeconds: valueOrDefault(spec.timeoutSeconds, 300),\n continueOnError: valueOrDefault(spec.continueOnError, false),\n };\n}\n\nfunction optionalFields(spec: OperationSpec): Partial<PlanOperation> {\n return {\n ...(spec.description !== undefined\n ? { description: spec.description }\n : {}),\n ...(spec.command !== undefined ? { command: spec.command } : {}),\n ...(spec.args !== undefined ? { args: spec.args } : {}),\n ...(spec.env !== undefined ? { env: spec.env } : {}),\n ...(spec.workingDir !== undefined ? { workingDir: spec.workingDir } : {}),\n ...(spec.condition !== undefined ? { condition: spec.condition } : {}),\n };\n}\n\nfunction convertArtifact(a: CoreArtifactDeclaration): PlanArtifactDeclaration {\n return {\n path: a.path,\n ...(a.name !== undefined ? { name: a.name } : {}),\n retain: a.retain ?? false,\n };\n}\n\nfunction convertCache(c: CoreCacheDeclaration): PlanCacheDeclaration {\n return {\n inputs: c.inputs,\n outputs: c.outputs ?? [],\n key: c.key ?? computeCacheKey(c.inputs),\n };\n}\n\nfunction computeCacheKey(inputs: readonly string[]): string {\n // Use 32 hex chars (128 bits) to keep keys compact while avoiding\n // the higher collision risk of a 64-bit truncation.\n return createHash(\"sha256\")\n .update(inputs.join(\",\"))\n .digest(\"hex\")\n .slice(0, 32);\n}\n\nfunction computeSourceContextHash(context?: ProjectContext): string {\n const changedFiles = context\n ? [...context.changedFiles.map((f) => f.path)].sort((a, b) =>\n a.localeCompare(b),\n )\n : [];\n const value = {\n commit: context?.commit ?? \"\",\n dirty: context?.dirty ?? false,\n changedFiles,\n };\n return createHash(\"sha256\").update(canonicalStringify(value)).digest(\"hex\");\n}\n","import type {\n PlanRuntime as IPlanRuntime,\n RuntimeMode,\n RuntimeResult,\n OperationOutcome,\n OperationSpec,\n} from \"@sverka/workflow\";\n\n/**\n * A plan-mode Runtime that records operations without side effects.\n * Used by the SDK to evaluate a workflow graph into an OperationSpec[]\n * without executing any commands.\n */\nexport class PlanRuntime implements IPlanRuntime {\n readonly mode: RuntimeMode = \"plan\";\n private readonly recorded: OperationSpec[] = [];\n private readonly start: number;\n\n constructor() {\n this.start = Date.now();\n }\n\n async evaluate(operation: OperationSpec): Promise<OperationOutcome> {\n this.recorded.push(operation);\n return {\n operationId: operation.id,\n status: \"planned\",\n durationMs: 0,\n };\n }\n\n async finalize(): Promise<RuntimeResult> {\n return {\n mode: \"plan\",\n operations: this.recorded,\n outcomes: [],\n durationMs: Date.now() - this.start,\n };\n }\n}\n","import { join } from \"node:path\";\nimport { mkdtempSync } from \"node:fs\";\nimport { rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\n\nimport type {\n OperationSpec,\n Workflow,\n Operation,\n ArtifactDeclaration,\n} from \"@sverka/workflow\";\nimport { workflow } from \"@sverka/workflow\";\nimport type { Plan } from \"@sverka/workflow\";\nimport { validatePlan } from \"@sverka/workflow\";\nimport type { OperationOutcome } from \"@sverka/runtime\";\nimport { createPlanner } from \"./planner/index.js\";\nimport type { ProjectContext } from \"./planner/index.js\";\nimport {\n DEFAULT_POLICY,\n createPolicy,\n evaluatePolicy,\n} from \"@sverka/verification\";\nimport type { Policy } from \"@sverka/verification\";\nimport { loadBaseline, filterOnlyNew } from \"@sverka/verification\";\nimport type { Finding } from \"@sverka/verification\";\nimport { createBuiltinResolver, extractFindings } from \"@sverka/verification\";\nimport type { CheckResolver, ResolvedCheck } from \"@sverka/verification\";\n\nimport type {\n SverkaOptions,\n Sverka,\n PlanResult,\n ExecutionResult,\n WorkflowDefinition,\n} from \"./types.js\";\nimport { SdkError } from \"./errors.js\";\nimport { findConfig, loadWorkflow } from \"./compat/config.js\";\nimport { convertToPlan } from \"./compat/convert.js\";\nimport { PlanRuntime } from \"./compat/internal/plan-runtime.js\";\n\n// Lazy types for runtime packages that may not exist on all waves.\n// These are dynamically imported in runPlan() to avoid hard deps.\ntype Scheduler = {\n execute(plan: Plan): Promise<RuntimeExecutionResult>;\n dispose(): Promise<void>;\n};\ntype Executor = unknown;\ntype RuntimeExecutionResult = {\n planId: string;\n status: \"success\" | \"failure\" | \"partial\";\n outcomes: ReadonlyMap<string, OperationOutcome>;\n durationMs: number;\n cancelledOperations: readonly string[];\n runtimeFailure?: boolean;\n};\n\n/**\n * Create a Sverka instance with default options pre-applied. Per-call\n * options override defaults.\n */\nexport function createSverka(defaultOptions?: SverkaOptions): Sverka {\n return {\n async plan(options?: SverkaOptions): Promise<PlanResult> {\n return doPlan(mergeOptions(defaultOptions, options));\n },\n async toPlan(options?: SverkaOptions): Promise<Plan> {\n return buildPlan(mergeOptions(defaultOptions, options));\n },\n async execute(options?: SverkaOptions): Promise<ExecutionResult> {\n return doExecute(mergeOptions(defaultOptions, options));\n },\n };\n}\n\n/** Top-level plan convenience function. */\nexport async function plan(options?: SverkaOptions): Promise<PlanResult> {\n return doPlan(options ?? {});\n}\n\n/** Top-level toPlan convenience function. Returns the canonical Plan IR. */\nexport async function toPlan(options?: SverkaOptions): Promise<Plan> {\n return buildPlan(options ?? {});\n}\n\n/** Top-level execute convenience function. */\nexport async function execute(\n options?: SverkaOptions,\n): Promise<ExecutionResult> {\n return doExecute(options ?? {});\n}\n\n// ---------------------------------------------------------------------------\n// Plan mode\n// ---------------------------------------------------------------------------\n\nasync function doPlan(options: SverkaOptions): Promise<PlanResult> {\n const root = options.root ?? process.cwd();\n const planner = createPlanner();\n const context = await planner.discover({\n root,\n ...(options.baseRef !== undefined ? { baseRef: options.baseRef } : {}),\n });\n\n const configPath = await resolveConfigPath(options, root);\n if (configPath !== null) {\n const def = await loadWorkflow(configPath, root);\n const operations = await evaluateWorkflow(def);\n const plan = buildPlanFromOps(operations, def.name, context);\n return { context, operations, proposal: null, plan };\n }\n\n // Auto-discovery mode.\n const proposal = await planner.plan(context);\n const resolver = options.resolver ?? createBuiltinResolver();\n const operations: OperationSpec[] = [];\n for (const check of proposal.checks) {\n try {\n const r = resolver.resolve(check, context);\n if (r !== null) operations.push(r.operation);\n } catch {\n // Skip checks whose custom resolver fails and continue with the rest.\n }\n }\n const plan = buildPlanFromOps(operations, \"sverka-plan\", context);\n return { context, operations, proposal, plan };\n}\n\n/** Build a canonical Plan IR from resolved operations. */\nasync function buildPlan(options: SverkaOptions): Promise<Plan> {\n const result = await doPlan(options);\n return result.plan;\n}\n\n/** Convert operations into a validated Plan with host executor defaults. */\nfunction buildPlanFromOps(\n operations: readonly OperationSpec[],\n name: string,\n context: ProjectContext,\n): Plan {\n const plan = convertToPlan(operations, {\n name,\n executor: \"host\",\n context,\n });\n\n if (operations.length > 0) {\n const validation = validatePlan(plan);\n if (!validation.valid) {\n throw new SdkError(\n `plan validation failed: ${validation.errors.map((e) => e.message).join(\"; \")}`,\n \"EXECUTION_FAILED\",\n );\n }\n }\n\n return plan;\n}\n\n// ---------------------------------------------------------------------------\n// Execute mode\n// ---------------------------------------------------------------------------\n\nasync function doExecute(options: SverkaOptions): Promise<ExecutionResult> {\n const root = options.root ?? process.cwd();\n const executorType: \"host\" | \"docker\" = options.executor ?? \"host\";\n const planner = createPlanner();\n const context: ProjectContext = await planner.discover({\n root,\n ...(options.baseRef !== undefined ? { baseRef: options.baseRef } : {}),\n });\n\n const { def, operations, resolvedChecks, planName } = await resolveOperations(\n options,\n root,\n context,\n executorType,\n );\n const plan = buildAndValidatePlan(\n operations,\n planName,\n executorType,\n context,\n );\n const { runtimeResult, findings } = await runPlan(\n plan,\n resolvedChecks,\n root,\n executorType,\n );\n return buildExecutionResult(runtimeResult, findings, options, def);\n}\n\n/** Load or auto-discover the operations to execute. */\nasync function resolveOperations(\n options: SverkaOptions,\n root: string,\n context: ProjectContext,\n executorType: \"host\" | \"docker\",\n): Promise<{\n def: WorkflowDefinition | null;\n operations: readonly OperationSpec[];\n resolvedChecks: readonly ResolvedCheck[];\n planName: string;\n}> {\n const configPath = await resolveConfigPath(options, root);\n\n if (configPath !== null) {\n const def = await loadWorkflow(configPath, root);\n const operations = await evaluateWorkflow(def);\n return { def, operations, resolvedChecks: [], planName: def.name };\n }\n\n const proposal = await createPlanner().plan(context);\n const resolver = options.resolver ?? createBuiltinResolver();\n const tmpChecks: ResolvedCheck[] = [];\n for (const check of proposal.checks) {\n try {\n const r = resolver.resolve(check, context);\n if (r !== null) tmpChecks.push(r);\n } catch {\n // Skip checks whose custom resolver fails and continue with the rest.\n }\n }\n\n if (\n executorType === \"docker\" &&\n tmpChecks.some((r) => r.operation.image === undefined)\n ) {\n throw new SdkError(\n \"docker executor requires container images; every operation must declare an image\",\n \"EXECUTION_FAILED\",\n );\n }\n\n const operations = tmpChecks.map((r) => buildOperationWithOutputs(r));\n if (operations.length === 0) {\n throw new SdkError(\n \"no config found and auto-discovery produced no resolvable checks\",\n \"CONFIG_NOT_FOUND\",\n );\n }\n\n return {\n def: null,\n operations,\n resolvedChecks: tmpChecks,\n planName: \"sverka-plan\",\n };\n}\n\n/** Convert operations into a Plan and validate it. */\nfunction buildAndValidatePlan(\n operations: readonly OperationSpec[],\n planName: string,\n executorType: \"host\" | \"docker\",\n context: ProjectContext,\n): Plan {\n const plan = convertToPlan(operations, {\n name: planName,\n executor: executorType,\n context,\n });\n\n // Validate (skip for empty operations — auto-discovery with no commands).\n if (operations.length > 0) {\n const validation = validatePlan(plan);\n if (!validation.valid) {\n throw new SdkError(\n `plan validation failed: ${validation.errors.map((e) => e.message).join(\"; \")}`,\n \"EXECUTION_FAILED\",\n );\n }\n }\n\n return plan;\n}\n\n/** Execute a Plan and extract findings from resolved checks. */\nasync function runPlan(\n plan: Plan,\n resolvedChecks: readonly ResolvedCheck[],\n root: string,\n executorType: \"host\" | \"docker\",\n): Promise<{\n runtimeResult: RuntimeExecutionResult;\n findings: readonly Finding[];\n}> {\n const artifactDir = mkdtempSync(join(tmpdir(), \"sverka-artifacts-\"));\n const cacheDir = mkdtempSync(join(tmpdir(), \"sverka-cache-\"));\n\n try {\n // Lazy import: @sverka/runtime may not exist on later waves (replaced\n // by @sverka/engine-native). The execute path dynamically imports it.\n const { Scheduler } = await import(\"@sverka/runtime\");\n const executor = await createExecutor(\n executorType,\n cacheDir,\n plan.operations,\n );\n const scheduler: Scheduler = new Scheduler({\n executors: [executor],\n maxConcurrent: 4,\n workspace: root,\n artifactDir,\n cacheDir,\n credentials: {},\n resume: false,\n } as unknown as ConstructorParameters<typeof Scheduler>[0]);\n\n try {\n const runtimeResult = (await scheduler.execute(\n plan,\n )) as RuntimeExecutionResult;\n const findings = await extractResolvedFindings(\n resolvedChecks,\n artifactDir,\n );\n return { runtimeResult, findings };\n } catch (e) {\n throw new SdkError(\n `execution failed: ${e instanceof Error ? e.message : String(e)}`,\n \"EXECUTION_FAILED\",\n e,\n );\n } finally {\n await scheduler.dispose().catch(() => {});\n }\n } finally {\n await Promise.all([\n rm(artifactDir, { recursive: true, force: true }).catch(() => {}),\n rm(cacheDir, { recursive: true, force: true }).catch(() => {}),\n ]);\n }\n}\n\n/** Extract findings from resolved checks' SARIF output artifacts. */\nasync function extractResolvedFindings(\n resolvedChecks: readonly ResolvedCheck[],\n artifactDir: string,\n): Promise<readonly Finding[]> {\n const all: Finding[] = [];\n for (const r of resolvedChecks) {\n if (r.outputs.length === 0) continue;\n const extracted = await extractFindings(r.outputs, artifactDir, r.checkId);\n all.push(...extracted);\n }\n return all;\n}\n\n/** Build the final ExecutionResult from runtime output and user options. */\nasync function buildExecutionResult(\n runtimeResult: RuntimeExecutionResult,\n findings: readonly Finding[],\n options: SverkaOptions,\n def: WorkflowDefinition | null,\n): Promise<ExecutionResult> {\n let baselineFingerprints: readonly string[] = [];\n let filteredFindings: readonly Finding[] = findings;\n if (options.baselinePath) {\n const baseline = await loadBaseline(options.baselinePath);\n baselineFingerprints = baseline.fingerprints;\n filteredFindings = options.onlyNew\n ? filterOnlyNew(findings, baseline)\n : findings;\n }\n\n const policy: Policy = def?.policy\n ? createPolicy(def.policy)\n : DEFAULT_POLICY;\n const policyResult = evaluatePolicy(\n filteredFindings,\n policy,\n baselineFingerprints,\n );\n\n const verdict =\n runtimeResult.status === \"success\" ? policyResult.verdict : \"fail\";\n\n return {\n findings: filteredFindings,\n policyResult,\n verdict,\n status: runtimeResult.status,\n ...(runtimeResult.runtimeFailure\n ? { runtimeFailure: runtimeResult.runtimeFailure }\n : {}),\n outcomes: runtimeResult.outcomes,\n durationMs: runtimeResult.durationMs,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction mergeOptions(\n defaults: SverkaOptions | undefined,\n callOpts: SverkaOptions | undefined,\n): SverkaOptions {\n return { ...defaults, ...callOpts };\n}\n\nasync function resolveConfigPath(\n options: SverkaOptions,\n root: string,\n): Promise<string | null> {\n if (options.configPath) {\n return options.configPath;\n }\n return findConfig(root);\n}\n\nasync function evaluateWorkflow(\n def: WorkflowDefinition,\n): Promise<readonly OperationSpec[]> {\n const wf = normalizeWorkflow(def.name, def.workflow);\n const runtime = new PlanRuntime();\n const result = await wf.plan(runtime);\n return result.operations;\n}\n\n/**\n * Normalize a WorkflowDefinition's workflow field to a Workflow.\n * If it's already a Workflow (has `roots` and `plan`), return as-is.\n * If it's a bare Operation, wrap it with `workflow(name, op)`.\n */\nfunction normalizeWorkflow(name: string, wf: Workflow | Operation): Workflow {\n if (isWorkflow(wf)) {\n return wf;\n }\n // It's an Operation — wrap it.\n return workflow(name, wf);\n}\n\nfunction isWorkflow(wf: Workflow | Operation): wf is Workflow {\n return \"roots\" in wf && \"plan\" in wf;\n}\n\nasync function createExecutor(\n type: \"host\" | \"docker\",\n cacheDir: string,\n operations: readonly { command?: string }[],\n): Promise<Executor> {\n if (type === \"docker\") {\n const { DockerExecutor } = await import(\"@sverka/runtime\");\n return new DockerExecutor({\n runAs: `${process.getuid?.() ?? 1000}:${process.getgid?.() ?? 1000}`,\n cacheDir,\n });\n }\n const { HostExecutor, createAllowlist } = await import(\"@sverka/runtime\");\n const commands = operations\n .map((op) => op.command)\n .filter((c): c is string => typeof c === \"string\" && c.length > 0);\n return new HostExecutor({\n enabled: true,\n allowlist: createAllowlist(commands),\n envAllowlist: [\"PATH\"],\n });\n}\n\n/** Merge resolved-check outputs into the operation's artifact declarations. */\nfunction buildOperationWithOutputs(r: ResolvedCheck): OperationSpec {\n if (r.outputs.length === 0) {\n return r.operation;\n }\n const artifacts: ArtifactDeclaration[] = [\n ...(r.operation.artifacts ?? []),\n ...r.outputs.map((o) => ({ path: o.path, retain: false })),\n ];\n return { ...r.operation, artifacts };\n}\n","// Standalone helpers that don't depend on runtime packages.\nimport type { Operation } from \"@sverka/workflow\";\nimport type { WorkflowDefinition } from \"./types.js\";\n\n/** Name an operation. Sugar for `op.named(name)`. */\nexport function task(name: string, op: Operation): Operation {\n return op.named(name);\n}\n\n/** Type-safe helper for sverka.config.ts. Identity function. */\nexport function defineWorkflow(\n definition: WorkflowDefinition,\n): WorkflowDefinition {\n return definition;\n}\n","import type { Reference, StepRef, ContextRef } from \"@sverka/workflow\";\n\nconst OUTPUT_TYPES = new Set<string>([\n \"string\",\n \"number\",\n \"boolean\",\n \"artifact\",\n]);\nconst CONTEXT_NAMESPACES = new Set<string>([\n \"env\",\n \"secrets\",\n \"git\",\n \"change\",\n \"event\",\n \"run\",\n \"inputs\",\n \"matrix\",\n]);\n\n/**\n * Type guard for Reference values.\n * Shared between expr.ts and sh.ts to avoid duplication.\n * Validates that type and namespace values are within their finite unions.\n */\nexport function isReference(value: unknown): value is Reference {\n if (typeof value !== \"object\" || value === null || !(\"kind\" in value)) {\n return false;\n }\n const ref = value as { kind: string };\n if (ref.kind === \"step\") return isStepRef(value);\n if (ref.kind === \"context\") return isContextRef(value);\n return false;\n}\n\nfunction isStepRef(value: object): boolean {\n const s = value as Partial<StepRef>;\n return (\n typeof s.step === \"string\" &&\n typeof s.output === \"string\" &&\n typeof s.type === \"string\" &&\n OUTPUT_TYPES.has(s.type)\n );\n}\n\nfunction isContextRef(value: object): boolean {\n const c = value as Partial<ContextRef>;\n return (\n typeof c.namespace === \"string\" &&\n typeof c.field === \"string\" &&\n CONTEXT_NAMESPACES.has(c.namespace)\n );\n}\n","// $ tagged template — shell command step builder.\n// Spec 03 — §9.2, §15. Architecture spec §9.2.\n\nimport { ShellStep, Pipeline } from \"@sverka/workflow\";\nimport type {\n Reference,\n Runtime,\n OutputDeclaration,\n MatrixSpec,\n Condition,\n OperationDefinition,\n} from \"@sverka/workflow\";\nimport { SdkError } from \"./errors.js\";\nimport { isReference } from \"./internal/is-reference.js\";\n\nexport interface StepBuilder {\n outputs(outputs: Readonly<Record<string, OutputDeclaration>>): StepBuilder;\n inputs(inputs: readonly Reference[]): StepBuilder;\n dependsOn(steps: readonly string[]): StepBuilder;\n runtime(runtime: Runtime): StepBuilder;\n timeout(ms: number): StepBuilder;\n condition(ref: Condition): StepBuilder;\n matrix(spec: MatrixSpec): StepBuilder;\n interruptible(value?: boolean): StepBuilder;\n compensate(command: string): StepBuilder;\n build(pipeline: Pipeline, id: string): ShellStep;\n}\n\ninterface StepBuilderState {\n command: string;\n collectedInputs: Reference[];\n outputs?: Readonly<Record<string, OutputDeclaration>>;\n inputs?: readonly Reference[];\n dependsOn?: readonly string[];\n runtime?: Runtime;\n timeout?: number;\n condition?: Condition;\n matrix?: MatrixSpec;\n interruptible?: boolean;\n compensation?: OperationDefinition;\n}\n\nfunction createBuilder(state: StepBuilderState): StepBuilder {\n const builder: StepBuilder = {\n outputs(outputs: Readonly<Record<string, OutputDeclaration>>): StepBuilder {\n state.outputs = outputs;\n return builder;\n },\n inputs(inputs: readonly Reference[]): StepBuilder {\n state.inputs = inputs;\n return builder;\n },\n dependsOn(steps: readonly string[]): StepBuilder {\n state.dependsOn = steps;\n return builder;\n },\n runtime(runtime: Runtime): StepBuilder {\n state.runtime = runtime;\n return builder;\n },\n timeout(ms: number): StepBuilder {\n state.timeout = ms;\n return builder;\n },\n condition(ref: Condition): StepBuilder {\n state.condition = ref;\n return builder;\n },\n matrix(spec: MatrixSpec): StepBuilder {\n state.matrix = spec;\n return builder;\n },\n interruptible(value?: boolean): StepBuilder {\n state.interruptible = value ?? true;\n return builder;\n },\n compensate(command: string): StepBuilder {\n state.compensation = { kind: \"shell\", command };\n return builder;\n },\n build(pipeline: Pipeline, id: string): ShellStep {\n // Merge collected inputs (from interpolation) with explicit inputs.\n const explicitInputs = state.inputs ? [...state.inputs] : [];\n const allInputs = [...explicitInputs, ...state.collectedInputs];\n return new ShellStep(pipeline, id, {\n command: state.command,\n ...(state.outputs ? { outputs: state.outputs } : {}),\n ...(allInputs.length > 0 ? { inputs: allInputs } : {}),\n ...(state.dependsOn ? { dependsOn: state.dependsOn } : {}),\n ...(state.runtime ? { runtime: state.runtime } : {}),\n ...(state.timeout !== undefined ? { timeout: state.timeout } : {}),\n ...(state.condition !== undefined\n ? { condition: state.condition }\n : {}),\n ...(state.matrix !== undefined ? { matrix: state.matrix } : {}),\n ...(state.interruptible !== undefined\n ? { interruptible: state.interruptible }\n : {}),\n ...(state.compensation !== undefined\n ? { compensation: state.compensation }\n : {}),\n });\n },\n };\n return builder;\n}\n\n/**\n * Create a shell command step builder from a tagged template.\n * References interpolated in the template are collected and added to the\n * step's inputs automatically.\n */\nexport function $(\n strings: TemplateStringsArray,\n ...values: readonly (string | Reference)[]\n): StepBuilder {\n let command = \"\";\n const collectedInputs: Reference[] = [];\n\n for (let i = 0; i < strings.length; i++) {\n command += strings[i];\n if (i < values.length) {\n const v = values[i]!;\n if (typeof v === \"string\") {\n command += v;\n } else if (isReference(v)) {\n // It's a Reference — add to inputs and interpolate a placeholder.\n const ref = v;\n collectedInputs.push(ref);\n if (ref.kind === \"step\") {\n command += `\\${${ref.step}.${ref.output}}`;\n } else {\n command += `\\${${ref.namespace}.${ref.field}}`;\n }\n } else {\n throw new SdkError(\n `invalid interpolation value at position ${i}: expected string or Reference`,\n \"INVALID_INTERPOLATION\",\n );\n }\n }\n }\n\n return createBuilder({ command, collectedInputs });\n}\n","// Shell proxy: command-prefix + shell-selector API.\n// Spec 03 — §9.2. Issue sv-kbu6.\n\nimport type { Runtime, Reference } from \"@sverka/workflow\";\nimport type { StepBuilder } from \"./dollar.js\";\nimport { $ } from \"./dollar.js\";\n\n/**\n * ShellProxy — callable tagged template + property access (command prefix)\n * + callable with interpreter string (shell selector).\n *\n * - `shell.git`push origin`` → command \"git push origin\"\n * - `shell(\"bash\").git`push`` → command \"git push\" + runtime.shell=\"bash\"\n * - `shell(\"pwsh\")`Write-Host hi`` → command \"Write-Host hi\" + runtime.shell=\"pwsh\"\n */\nexport interface ShellProxy {\n // Tagged template: bare shell`command` → StepBuilder (no prefix).\n (strings: TemplateStringsArray, ...values: readonly unknown[]): StepBuilder;\n // Shell selector: shell(\"bash\") → new ShellProxy with shell preset.\n (interpreter: string): ShellProxy;\n // Common command prefixes — named properties avoid | undefined under\n // noUncheckedIndexedAccess and provide autocomplete. The index signature\n // below covers any other string prefix dynamically.\n readonly git: ShellProxy;\n readonly npm: ShellProxy;\n readonly npx: ShellProxy;\n readonly bun: ShellProxy;\n readonly pnpm: ShellProxy;\n readonly yarn: ShellProxy;\n readonly docker: ShellProxy;\n readonly make: ShellProxy;\n readonly cargo: ShellProxy;\n readonly go: ShellProxy;\n readonly python: ShellProxy;\n readonly pip: ShellProxy;\n // Command prefix: shell.git`push` → StepBuilder with \"git push\".\n readonly [key: string]: ShellProxy;\n}\n\n/**\n * Create a ShellProxy bound to an optional command prefix and shell interpreter.\n * - prefix: accumulated property-access chain (e.g. \"git\" for shell.git)\n * - shellOpt: interpreter string from shell(\"bash\"), applied as runtime.shell\n */\nfunction createShellProxy(prefix: string, shellOpt?: string): ShellProxy {\n const proxy: ShellProxy = function (\n stringsOrInterpreter: TemplateStringsArray | string,\n ...values: readonly unknown[]\n ): StepBuilder | ShellProxy {\n // Function call with interpreter string: shell(\"bash\") → new proxy.\n if (typeof stringsOrInterpreter === \"string\") {\n return createShellProxy(prefix, stringsOrInterpreter);\n }\n\n // Tagged template: build the command.\n // $ validates interpolation values at runtime (throws INVALID_INTERPOLATION);\n // cast to satisfy its (string | Reference) signature.\n const builder = $(\n stringsOrInterpreter,\n ...(values as readonly (string | Reference)[]),\n );\n\n // Prepend command prefix if set (e.g. \"git \" for shell.git`push`).\n if (prefix) {\n return wrapBuilder(builder, (step) =>\n applyPrefixAndShell(step, prefix, shellOpt),\n );\n }\n\n // No prefix — bare shell`command` or shell(\"bash\")`command`.\n if (shellOpt) {\n return wrapBuilder(builder, (step) => applyShell(step, shellOpt));\n }\n return builder;\n } as ShellProxy;\n\n // Property access: shell.git → new ShellProxy with prefix \"git\".\n return new Proxy(proxy, {\n get(_target, prop: string | symbol): ShellProxy | undefined {\n // Guard against thenable/introspection props (then, toJSON, etc.)\n if (typeof prop !== \"string\") return undefined;\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"toString\")\n return undefined;\n const newPrefix = prefix ? `${prefix} ${prop}` : prop;\n return createShellProxy(newPrefix, shellOpt);\n },\n });\n}\n\n/**\n * Apply a command prefix and optional shell interpreter to a built step.\n * Mutates the step in-place to preserve pipeline registration.\n */\nfunction applyPrefixAndShell(\n step: ReturnType<StepBuilder[\"build\"]>,\n prefix: string,\n shellOpt?: string,\n): ReturnType<StepBuilder[\"build\"]> {\n const runtime = shellOpt\n ? { ...step.runtime, shell: shellOpt }\n : step.runtime;\n Object.assign(step, { command: `${prefix} ${step.command}`, runtime });\n return step;\n}\n\n/**\n * Apply a shell interpreter to a built step (no prefix).\n * Mutates the step in-place to preserve pipeline registration.\n */\nfunction applyShell(\n step: ReturnType<StepBuilder[\"build\"]>,\n interpreter: string,\n): ReturnType<StepBuilder[\"build\"]> {\n const runtime: Runtime = { ...step.runtime, shell: interpreter };\n Object.assign(step, { runtime });\n return step;\n}\n\n/**\n * Wrap a StepBuilder so `build()` applies a transform to the final step.\n * Chain methods delegate to the original builder and return the wrapper.\n */\nfunction wrapBuilder(\n builder: StepBuilder,\n transform: (\n step: ReturnType<StepBuilder[\"build\"]>,\n ) => ReturnType<StepBuilder[\"build\"]>,\n): StepBuilder {\n const origBuild = builder.build.bind(builder);\n const wrapped: StepBuilder = {\n outputs(o) {\n builder.outputs(o);\n return wrapped;\n },\n inputs(i) {\n builder.inputs(i);\n return wrapped;\n },\n dependsOn(s) {\n builder.dependsOn(s);\n return wrapped;\n },\n runtime(r) {\n builder.runtime(r);\n return wrapped;\n },\n timeout(ms) {\n builder.timeout(ms);\n return wrapped;\n },\n condition(ref) {\n builder.condition(ref);\n return wrapped;\n },\n matrix(spec) {\n builder.matrix(spec);\n return wrapped;\n },\n interruptible(value) {\n builder.interruptible(value);\n return wrapped;\n },\n compensate(command) {\n builder.compensate(command);\n return wrapped;\n },\n build(pipeline, id) {\n return transform(origBuild(pipeline, id));\n },\n };\n return wrapped;\n}\n\n/**\n * Shell proxy export. Provides command-prefix and shell-selector DX.\n *\n * @example\n * const { git, npm, bun, make, docker } = shell;\n * git`push origin main`.build(p, \"push\") // → \"git push origin main\"\n * bun`run build`.build(p, \"build\") // → \"bun run build\"\n *\n * @example\n * const bash = shell(\"bash\");\n * bash.git`push`.build(p, \"push\") // → \"git push\" + runtime.shell=\"bash\"\n * shell(\"pwsh\")`Write-Host hello`.build(p, \"greet\") // → \"Write-Host hello\" + runtime.shell=\"pwsh\"\n */\nexport const shell: ShellProxy = createShellProxy(\"\");\n","// artifact() — output declaration factory for artifact outputs.\n// Spec 03 — §12.2.\n\nimport type { OutputDeclaration } from \"@sverka/workflow\";\n\n/** Create an artifact output declaration with the given path. */\nexport function artifact(path: string): OutputDeclaration {\n return { type: \"artifact\", path };\n}\n","// pipeline() factory — creates a Pipeline and runs step/entry functions.\n// Spec 03 — §9.2.\n\nimport { Project, Pipeline, Entry } from \"@sverka/workflow\";\nimport type { Input } from \"@sverka/workflow\";\n\nexport interface PipelineConfig {\n inputs?: Readonly<Record<string, Input>>;\n steps?: ReadonlyArray<(pipeline: Pipeline) => void>;\n entries?: ReadonlyArray<(pipeline: Pipeline) => Entry>;\n}\n\n/** Create a Pipeline, run step functions, then entry functions. */\nexport function pipeline(\n project: Project,\n id: string,\n config: PipelineConfig,\n): Pipeline {\n const p = new Pipeline(project, id, {\n ...(config.inputs ? { inputs: config.inputs } : {}),\n });\n\n if (config.steps) {\n for (const stepFn of config.steps) {\n stepFn(p);\n }\n }\n\n if (config.entries) {\n for (const entryFn of config.entries) {\n entryFn(p);\n }\n }\n\n return p;\n}\n","// callPipeline() builder — invokes a callee pipeline as a step (F-31).\n// Returns a builder that creates a PipelineCallStep when .build() is called.\n\nimport { PipelineCallStep, Pipeline } from \"@sverka/workflow\";\nimport type {\n Reference,\n InputLiteral,\n Runtime,\n OutputDeclaration,\n} from \"@sverka/workflow\";\n\nexport interface CallPipelineBuilder {\n outputs(\n outputs: Readonly<Record<string, OutputDeclaration>>,\n ): CallPipelineBuilder;\n dependsOn(steps: readonly string[]): CallPipelineBuilder;\n runtime(runtime: Runtime): CallPipelineBuilder;\n timeout(ms: number): CallPipelineBuilder;\n condition(ref: Reference): CallPipelineBuilder;\n interruptible(value: boolean): CallPipelineBuilder;\n build(pipeline: Pipeline, id: string): PipelineCallStep;\n}\n\ninterface CallBuilderState {\n callee: string;\n callInputs: Record<string, Reference | InputLiteral>;\n outputs?: Readonly<Record<string, OutputDeclaration>>;\n dependsOn?: readonly string[];\n runtime?: Runtime;\n timeout?: number;\n condition?: Reference;\n interruptible?: boolean;\n}\n\nfunction createCallBuilder(state: CallBuilderState): CallPipelineBuilder {\n const builder: CallPipelineBuilder = {\n outputs(\n outputs: Readonly<Record<string, OutputDeclaration>>,\n ): CallPipelineBuilder {\n state.outputs = outputs;\n return builder;\n },\n dependsOn(steps: readonly string[]): CallPipelineBuilder {\n state.dependsOn = steps;\n return builder;\n },\n runtime(runtime: Runtime): CallPipelineBuilder {\n state.runtime = runtime;\n return builder;\n },\n timeout(ms: number): CallPipelineBuilder {\n state.timeout = ms;\n return builder;\n },\n condition(ref: Reference): CallPipelineBuilder {\n state.condition = ref;\n return builder;\n },\n interruptible(value: boolean): CallPipelineBuilder {\n state.interruptible = value;\n return builder;\n },\n build(pipeline: Pipeline, id: string): PipelineCallStep {\n return new PipelineCallStep(pipeline, id, {\n callee: state.callee,\n callInputs: state.callInputs,\n ...(state.outputs ? { outputs: state.outputs } : {}),\n ...(state.dependsOn ? { dependsOn: state.dependsOn } : {}),\n ...(state.runtime ? { runtime: state.runtime } : {}),\n ...(state.timeout !== undefined ? { timeout: state.timeout } : {}),\n ...(state.condition !== undefined\n ? { condition: state.condition }\n : {}),\n ...(state.interruptible !== undefined\n ? { interruptible: state.interruptible }\n : {}),\n });\n },\n };\n return builder;\n}\n\n/**\n * Create a pipeline-call step builder.\n * @param callee The callee pipeline id (within the same Project).\n * @param callInputs Bound inputs for the callee pipeline.\n */\nexport function callPipeline(\n callee: string,\n callInputs?: Readonly<Record<string, Reference | InputLiteral>>,\n): CallPipelineBuilder {\n return createCallBuilder({\n callee,\n callInputs: callInputs ? { ...callInputs } : {},\n });\n}\n","// component() builder — invokes a versioned component as a step (F-32).\n// Returns a builder that creates a ComponentStep when .build() is called.\n\nimport { ComponentStep, Pipeline } from \"@sverka/workflow\";\nimport type {\n Reference,\n InputLiteral,\n ComponentRef,\n Runtime,\n OutputDeclaration,\n} from \"@sverka/workflow\";\n\nexport interface ComponentBuilder {\n outputs(\n outputs: Readonly<Record<string, OutputDeclaration>>,\n ): ComponentBuilder;\n dependsOn(steps: readonly string[]): ComponentBuilder;\n runtime(runtime: Runtime): ComponentBuilder;\n timeout(ms: number): ComponentBuilder;\n condition(ref: Reference): ComponentBuilder;\n interruptible(value: boolean): ComponentBuilder;\n build(pipeline: Pipeline, id: string): ComponentStep;\n}\n\ninterface ComponentBuilderState {\n component: ComponentRef;\n outputs?: Readonly<Record<string, OutputDeclaration>>;\n dependsOn?: readonly string[];\n runtime?: Runtime;\n timeout?: number;\n condition?: Reference;\n interruptible?: boolean;\n}\n\nfunction createComponentBuilder(\n state: ComponentBuilderState,\n): ComponentBuilder {\n const builder: ComponentBuilder = {\n outputs(\n outputs: Readonly<Record<string, OutputDeclaration>>,\n ): ComponentBuilder {\n state.outputs = outputs;\n return builder;\n },\n dependsOn(steps: readonly string[]): ComponentBuilder {\n state.dependsOn = steps;\n return builder;\n },\n runtime(runtime: Runtime): ComponentBuilder {\n state.runtime = runtime;\n return builder;\n },\n timeout(ms: number): ComponentBuilder {\n state.timeout = ms;\n return builder;\n },\n condition(ref: Reference): ComponentBuilder {\n state.condition = ref;\n return builder;\n },\n interruptible(value: boolean): ComponentBuilder {\n state.interruptible = value;\n return builder;\n },\n build(pipeline: Pipeline, id: string): ComponentStep {\n return new ComponentStep(pipeline, id, {\n component: state.component,\n ...(state.outputs ? { outputs: state.outputs } : {}),\n ...(state.dependsOn ? { dependsOn: state.dependsOn } : {}),\n ...(state.runtime ? { runtime: state.runtime } : {}),\n ...(state.timeout !== undefined ? { timeout: state.timeout } : {}),\n ...(state.condition !== undefined\n ? { condition: state.condition }\n : {}),\n ...(state.interruptible !== undefined\n ? { interruptible: state.interruptible }\n : {}),\n });\n },\n };\n return builder;\n}\n\n/**\n * Create a component step builder.\n * @param name The component name (e.g. \"deploy\").\n * @param version The component version (e.g. \"1.0.0\").\n * @param inputs Bound inputs for the component.\n */\nexport function component(\n name: string,\n version: string,\n inputs?: Readonly<Record<string, Reference | InputLiteral>>,\n): ComponentBuilder {\n return createComponentBuilder({\n component: {\n name,\n version,\n inputs: inputs ? { ...inputs } : {},\n },\n });\n}\n","// when() — condition helper.\n// Spec 03 — §10 (StepDefinition.condition). In v0, conditions are\n// boolean-producing References, Expressions, or StatusConditions. `when` is\n// an identity function that marks a value as a condition for readability.\n\nimport type { Condition } from \"@sverka/workflow\";\n\n/** Mark a reference, expression, or status condition as a step condition. Returns it unchanged. */\nexport function when(cond: Condition): Condition {\n return cond;\n}\n","// expr tagged template — symbolic expression builder.\n// Spec 03 — §12.3. Architecture spec §11.1, §12.3.\n\nimport type { Reference, Expression } from \"@sverka/workflow\";\nimport { SdkError } from \"./errors.js\";\nimport { isReference } from \"./internal/is-reference.js\";\n\n/**\n * Create a symbolic expression from a tagged template.\n * Context references produce `${namespace.field}` placeholders while step\n * references produce `${step.output}` placeholders; both are collected into\n * `refs` for dependency inference.\n * String, number, and boolean values are inlined into the template.\n */\nexport function expr(\n strings: TemplateStringsArray,\n ...values: readonly (string | number | boolean | Reference)[]\n): Expression {\n let template = \"\";\n const refs: Reference[] = [];\n\n for (let i = 0; i < strings.length; i++) {\n template += strings[i];\n if (i < values.length) {\n const v = values[i]!;\n if (\n typeof v === \"string\" ||\n typeof v === \"number\" ||\n typeof v === \"boolean\"\n ) {\n template += String(v);\n } else if (isReference(v)) {\n refs.push(v);\n if (v.kind === \"step\") {\n template += `\\${${v.step}.${v.output}}`;\n } else {\n template += `\\${${v.namespace}.${v.field}}`;\n }\n } else {\n throw new SdkError(\n `invalid interpolation value at position ${i}: expected string, number, boolean, or Reference`,\n \"INVALID_INTERPOLATION\",\n );\n }\n }\n }\n\n return { kind: \"expression\", template, refs };\n}\n","// status() factory — creates a StatusCondition for step conditions.\n// F-11 — §conditions.\n\nimport type { StepStatus, StatusCondition } from \"@sverka/workflow\";\n\n/**\n * Create a status-based condition.\n * @example\n * sh`notify-slack`.condition(status(\"failure\"))\n */\nexport function status(s: StepStatus): StatusCondition {\n return { kind: \"status\", status: s };\n}\n","// Shared set of protected Proxy properties to avoid accidental access\n// to Promise/JSON/inspection internals when using dynamic property proxies.\n\nexport const PROTECTED_PROXY_PROPS = new Set<string | symbol>([\n \"then\",\n \"toJSON\",\n \"inspect\",\n \"constructor\",\n \"valueOf\",\n Symbol.toPrimitive,\n Symbol.iterator,\n Symbol.toStringTag,\n]);\n\n/**\n * Create a dynamic Proxy that delegates protected/symbol properties to\n * Reflect.get and calls `resolve(prop)` for everything else.\n *\n * This shared factory eliminates duplication between context namespace\n * proxies and image reference proxies.\n */\nexport function createDynamicProxy<T>(\n resolve: (prop: string) => T,\n): Record<string, T> {\n return new Proxy({} as Record<string, T>, {\n get(target, prop: string | symbol): T | unknown {\n if (typeof prop === \"symbol\" || PROTECTED_PROXY_PROPS.has(prop)) {\n return Reflect.get(target, prop);\n }\n return resolve(prop);\n },\n });\n}\n","// Image value helpers — typed OCI image references.\n// Spec 03 — §14.2. Architecture spec §14.2.\n\nimport { SdkError } from \"./errors.js\";\nimport { createDynamicProxy } from \"./internal/proxy-props.js\";\n\nexport interface ImageRef {\n readonly ref: string;\n}\n\n/** Create an ImageRef from a raw OCI reference string. */\nexport function image(ref: string): ImageRef {\n if (typeof ref !== \"string\") {\n throw new SdkError(\"image reference must be a string\", \"INVALID_IMAGE\");\n }\n if (ref.length === 0) {\n throw new SdkError(\n \"image reference must be a non-empty string\",\n \"INVALID_IMAGE\",\n );\n }\n return { ref };\n}\n\n/** Create a Proxy that maps property access to `image(prefix:prop)`. */\nfunction createImageProxy(\n prefix: string,\n): Record<string, ImageRef> & { readonly latest: ImageRef } {\n return createDynamicProxy((prop) => image(`${prefix}:${prop}`)) as Record<\n string,\n ImageRef\n > & { readonly latest: ImageRef };\n}\n\n/** Node image proxy — images.node[22] → { ref: \"node:22\" }, images.node.latest → { ref: \"node:latest\" }. */\nconst nodeImages = createImageProxy(\"node\") as Record<string, ImageRef> & {\n readonly latest: ImageRef;\n readonly [version: number]: ImageRef;\n};\n\n/** Ubuntu image proxy — images.ubuntu.latest → { ref: \"ubuntu:latest\" }. */\nconst ubuntuImages = createImageProxy(\"ubuntu\");\n\nexport const images = {\n node: nodeImages,\n ubuntu: ubuntuImages,\n};\n","// Context namespaces — typed references to context values.\n// Spec 03 — §12.3. Architecture spec §12.3.\n\nimport type { ContextRef, ContextNamespace } from \"@sverka/workflow\";\nimport { createDynamicProxy } from \"./internal/proxy-props.js\";\n\n/** Create a ContextRef for a namespace + field. */\nfunction ctx(namespace: ContextNamespace, field: string): ContextRef {\n return { kind: \"context\", namespace, field };\n}\n\n/** Dynamic namespace proxy — any property access returns a ContextRef. */\nfunction dynamicNamespace(\n namespace: ContextNamespace,\n): Record<string, ContextRef> {\n return createDynamicProxy((prop) => ctx(namespace, prop));\n}\n\n/** Environment variable references: env.CI_TRACE, env.MY_VAR. */\nexport const env: Record<string, ContextRef> = dynamicNamespace(\"env\");\n\n/** Secret references: secrets.NPM_TOKEN. */\nexport const secrets: Record<string, ContextRef> = dynamicNamespace(\"secrets\");\n\n/** Git metadata references: git.sha, git.branch, git.tag. */\nexport const git = {\n sha: ctx(\"git\", \"sha\"),\n branch: ctx(\"git\", \"branch\"),\n tag: ctx(\"git\", \"tag\"),\n};\n\n/** Change request metadata: change.id, change.source, change.target, change.draft. */\nexport const change = {\n id: ctx(\"change\", \"id\"),\n source: ctx(\"change\", \"source\"),\n target: ctx(\"change\", \"target\"),\n draft: ctx(\"change\", \"draft\"),\n};\n\n/** Event metadata: event.type. */\nexport const event = {\n type: ctx(\"event\", \"type\"),\n};\n\n/** Run metadata: run.id, run.attempt. */\nexport const run = {\n id: ctx(\"run\", \"id\"),\n attempt: ctx(\"run\", \"attempt\"),\n};\n\n/** Pipeline input references: inputs.environment. */\nexport const inputs: Record<string, ContextRef> = dynamicNamespace(\"inputs\");\n\n/** Matrix variable references: matrix.node, matrix.os. */\nexport const matrix: Record<string, ContextRef> = dynamicNamespace(\"matrix\");\n","// agent tagged template — AI agent step builder.\n// Spec 27 — §9.2 (SDK). Mirrors $ for shell, but creates an AgentStep.\n\nimport { AgentStep, Pipeline } from \"@sverka/workflow\";\nimport type {\n Reference,\n OutputDeclaration,\n AgentToolRef,\n} from \"@sverka/workflow\";\nimport { SdkError } from \"./errors.js\";\nimport { isReference } from \"./internal/is-reference.js\";\n\nexport interface AgentStepBuilder {\n outputs(\n outputs: Readonly<Record<string, OutputDeclaration>>,\n ): AgentStepBuilder;\n inputs(inputs: readonly Reference[]): AgentStepBuilder;\n dependsOn(steps: readonly string[]): AgentStepBuilder;\n tools(...tools: readonly AgentToolRef[]): AgentStepBuilder;\n engine(engine: string): AgentStepBuilder;\n model(model: string): AgentStepBuilder;\n maxTokens(n: number): AgentStepBuilder;\n build(pipeline: Pipeline, id: string): AgentStep;\n}\n\ninterface AgentBuilderState {\n prompt: string;\n engine: string;\n model?: string;\n tools: AgentToolRef[];\n collectedInputs: Reference[];\n outputs?: Readonly<Record<string, OutputDeclaration>>;\n inputs?: readonly Reference[];\n dependsOn?: readonly string[];\n maxTokens?: number;\n}\n\nfunction createAgentBuilder(state: AgentBuilderState): AgentStepBuilder {\n const builder: AgentStepBuilder = {\n outputs(\n outputs: Readonly<Record<string, OutputDeclaration>>,\n ): AgentStepBuilder {\n state.outputs = outputs;\n return builder;\n },\n inputs(inputs: readonly Reference[]): AgentStepBuilder {\n state.inputs = inputs;\n return builder;\n },\n dependsOn(steps: readonly string[]): AgentStepBuilder {\n state.dependsOn = steps;\n return builder;\n },\n tools(...tools: readonly AgentToolRef[]): AgentStepBuilder {\n state.tools = [...state.tools, ...tools];\n return builder;\n },\n engine(engine: string): AgentStepBuilder {\n state.engine = engine;\n return builder;\n },\n model(model: string): AgentStepBuilder {\n state.model = model;\n return builder;\n },\n maxTokens(n: number): AgentStepBuilder {\n state.maxTokens = n;\n return builder;\n },\n build(pipeline: Pipeline, id: string): AgentStep {\n const explicitInputs = state.inputs ? [...state.inputs] : [];\n const allInputs = [...explicitInputs, ...state.collectedInputs];\n return new AgentStep(pipeline, id, {\n engine: state.engine,\n prompt: state.prompt,\n ...(state.model !== undefined ? { model: state.model } : {}),\n ...(state.tools.length > 0 ? { tools: state.tools } : {}),\n ...(state.maxTokens !== undefined\n ? { maxTokens: state.maxTokens }\n : {}),\n ...(state.outputs ? { outputs: state.outputs } : {}),\n ...(allInputs.length > 0 ? { inputs: allInputs } : {}),\n ...(state.dependsOn ? { dependsOn: state.dependsOn } : {}),\n });\n },\n };\n return builder;\n}\n\n/**\n * Create an AI agent step builder from a tagged template.\n * `agent\\`Build and test\\`` creates a builder with `engine: \"default\"`.\n * References interpolated in the template are collected and added to the\n * step's inputs automatically (same as `$`).\n */\nexport function agent(\n strings: TemplateStringsArray,\n ...values: readonly (string | Reference)[]\n): AgentStepBuilder {\n let prompt = \"\";\n const collectedInputs: Reference[] = [];\n\n for (let i = 0; i < strings.length; i++) {\n prompt += strings[i];\n if (i < values.length) {\n const v = values[i]!;\n if (typeof v === \"string\") {\n prompt += v;\n } else if (isReference(v)) {\n const ref = v;\n collectedInputs.push(ref);\n if (ref.kind === \"step\") {\n prompt += `\\${${ref.step}.${ref.output}}`;\n } else {\n prompt += `\\${${ref.namespace}.${ref.field}}`;\n }\n } else {\n throw new SdkError(\n `invalid interpolation value at position ${i}: expected string or Reference`,\n \"INVALID_INTERPOLATION\",\n );\n }\n }\n }\n\n return createAgentBuilder({\n prompt,\n engine: \"default\",\n tools: [],\n collectedInputs,\n });\n}\n","// Markdown authoring errors (Spec 37, extended by Spec 54).\n\nimport { SdkError } from \"./errors.js\";\n\nexport type MarkdownParseErrorCode =\n | \"INVALID_FRONTMATTER\"\n | \"INVALID_STEP\"\n | \"INVALID_TRIGGER\"\n | \"EXTENDS_NOT_FOUND\";\n\n/** Raised when a `.sverka.md` file cannot be parsed into a Project. */\nexport class MarkdownParseError extends SdkError {\n declare readonly code: MarkdownParseErrorCode;\n\n constructor(message: string, code: MarkdownParseErrorCode, cause?: unknown) {\n super(message, code, cause);\n this.name = \"MarkdownParseError\";\n }\n}\n","// Markdown authoring (Spec 37) — `.sverka.md` files: YAML frontmatter\n// (pipeline metadata, triggers, inputs, `extends`) + `## step` sections\n// with `- command:` bullets. Compiles through the same Construct API as\n// sverka.config.ts — the produced graph is identical, not approximate.\n//\n// Spec 54 extends the trigger set with `comment` and `issue` kinds and\n// accepts gh-aw-style `on:` shorthand so the same frontmatter shape works\n// for agentic GitLab workflows.\n//\n// Deliberate subset (per Spec 37 non-goals): shell steps only — agent\n// steps, safe-outputs, matrices and conditions use `extends` + TS.\n\nimport { readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { parse as parseYaml } from \"yaml\";\nimport {\n Construct,\n Project,\n Pipeline,\n ShellStep,\n Entry,\n} from \"@sverka/workflow\";\nimport type {\n Input,\n OutputDeclaration,\n Trigger,\n TriggerFilter,\n} from \"@sverka/workflow\";\nimport { MarkdownParseError } from \"./markdown-errors.js\";\n\n/** Frontmatter shape (Spec 37 + Spec 54 `on:` alias and event kinds). */\nexport interface MarkdownFrontmatter {\n readonly pipeline: string;\n readonly triggers?: readonly MarkdownTrigger[];\n /** gh-aw-style shorthand for `triggers`. */\n readonly on?: string | readonly string[] | Record<string, unknown>;\n readonly extends?: string;\n readonly inputs?: Readonly<Record<string, Input>>;\n}\n\n/** A single frontmatter trigger entry. */\nexport interface MarkdownTrigger {\n readonly kind:\n \"push\" | \"changeRequest\" | \"manual\" | \"schedule\" | \"comment\" | \"issue\";\n readonly branches?: readonly string[];\n readonly tags?: readonly string[];\n readonly paths?: readonly string[];\n readonly cron?: string;\n readonly timezone?: string;\n readonly mention?: string;\n readonly on?: \"mergeRequest\" | \"issue\" | \"commit\";\n readonly action?: \"opened\" | \"reopened\" | \"labeled\";\n readonly labels?: readonly string[];\n}\n\ninterface ParsedStep {\n readonly id: string;\n readonly command: string;\n readonly dependsOn?: readonly string[];\n readonly image?: string;\n readonly timeout?: number;\n readonly outputs?: Readonly<Record<string, OutputDeclaration>>;\n}\n\n/**\n * Parse a `.sverka.md` source string into a Project construct.\n * `filePath` anchors `extends` resolution and error messages; without it\n * `extends` cannot resolve and throws EXTENDS_NOT_FOUND.\n */\nexport function parseMarkdown(source: string, filePath?: string): Project {\n const { frontmatter, body } = splitFrontmatter(source, filePath);\n const project = new Project(frontmatter.pipeline);\n buildMarkdownPipeline(project, frontmatter, body, filePath);\n return project;\n}\n\n/**\n * Read + parse a `.sverka.md` file. When frontmatter declares `extends`,\n * the referenced config module is imported and the markdown pipeline is\n * merged into that Project (Spec 37 escape hatch).\n */\nexport async function loadMarkdownFile(path: string): Promise<Project> {\n const abs = isAbsolute(path) ? path : resolve(process.cwd(), path);\n let source: string;\n try {\n source = await readFile(abs, \"utf-8\");\n } catch (e) {\n throw new MarkdownParseError(\n `cannot read markdown file: ${abs}`,\n \"INVALID_FRONTMATTER\",\n e,\n );\n }\n const { frontmatter, body } = splitFrontmatter(source, abs);\n\n if (frontmatter.extends !== undefined) {\n const base = await loadExtends(frontmatter.extends, abs);\n buildMarkdownPipeline(base, frontmatter, body, abs);\n return base;\n }\n\n const project = new Project(frontmatter.pipeline);\n buildMarkdownPipeline(project, frontmatter, body, abs);\n return project;\n}\n\n// ---------------------------------------------------------------------------\n// Frontmatter\n// ---------------------------------------------------------------------------\n\nfunction splitFrontmatter(\n source: string,\n filePath?: string,\n): { frontmatter: MarkdownFrontmatter; body: string } {\n const where = filePath !== undefined ? ` in ${filePath}` : \"\";\n const m = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/.exec(source);\n if (m === null) {\n throw new MarkdownParseError(\n `invalid .sverka.md${where}: missing YAML frontmatter (expected '---' delimiters)`,\n \"INVALID_FRONTMATTER\",\n );\n }\n let parsed: unknown;\n try {\n parsed = parseYaml(m[1]!);\n } catch (e) {\n throw new MarkdownParseError(\n `invalid .sverka.md frontmatter${where}: ${e instanceof Error ? e.message : String(e)}`,\n \"INVALID_FRONTMATTER\",\n e,\n );\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new MarkdownParseError(\n `invalid .sverka.md frontmatter${where}: expected a mapping`,\n \"INVALID_FRONTMATTER\",\n );\n }\n const fm = parsed as Record<string, unknown>;\n if (typeof fm.pipeline !== \"string\" || fm.pipeline === \"\") {\n throw new MarkdownParseError(\n `invalid .sverka.md frontmatter${where}: missing required 'pipeline' field`,\n \"INVALID_FRONTMATTER\",\n );\n }\n return {\n frontmatter: fm as unknown as MarkdownFrontmatter,\n body: m[2]!,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Triggers\n// ---------------------------------------------------------------------------\n\nfunction frontmatterTriggers(fm: MarkdownFrontmatter): readonly Trigger[] {\n const raw = collectTriggerEntries(fm);\n return raw.map((entry, i) => toTrigger(entry, i));\n}\n\ninterface TriggerEntry {\n readonly kind: string;\n readonly opts: Record<string, unknown>;\n}\n\n/**\n * Normalize `triggers:` (array of objects) and `on:` (gh-aw shorthand:\n * string, list of kind strings, or map of kind → options) into uniform\n * entries. `triggers` wins when both are present.\n */\nfunction collectTriggerEntries(\n fm: MarkdownFrontmatter,\n): readonly TriggerEntry[] {\n if (fm.triggers !== undefined) {\n if (!Array.isArray(fm.triggers)) {\n throw new MarkdownParseError(\n \"invalid .sverka.md frontmatter: 'triggers' must be an array\",\n \"INVALID_TRIGGER\",\n );\n }\n return (fm.triggers as readonly Record<string, unknown>[]).map((t) => {\n if (typeof t !== \"object\" || t === null || typeof t.kind !== \"string\") {\n throw new MarkdownParseError(\n \"invalid .sverka.md trigger: each entry needs a string 'kind'\",\n \"INVALID_TRIGGER\",\n );\n }\n const { kind, ...opts } = t;\n return { kind, opts };\n });\n }\n if (fm.on === undefined) return [];\n const on = fm.on;\n if (typeof on === \"string\") return [{ kind: on, opts: {} }];\n if (Array.isArray(on)) {\n return on.map((kind) => {\n if (typeof kind !== \"string\") {\n throw new MarkdownParseError(\n \"invalid .sverka.md 'on': entries must be trigger kind strings\",\n \"INVALID_TRIGGER\",\n );\n }\n return { kind, opts: {} };\n });\n }\n if (typeof on === \"object\" && on !== null) {\n return Object.entries(on).map(([kind, opts]) => ({\n kind,\n opts:\n typeof opts === \"object\" && opts !== null\n ? (opts as Record<string, unknown>)\n : {},\n }));\n }\n throw new MarkdownParseError(\n \"invalid .sverka.md 'on': expected a trigger kind, list of kinds, or kind→options map\",\n \"INVALID_TRIGGER\",\n );\n}\n\nconst FILTER_KEYS = [\"branches\", \"tags\", \"paths\"] as const;\n\nfunction toTrigger(entry: TriggerEntry, index: number): Trigger {\n const { kind, opts } = entry;\n const at = `trigger[${index}] (${kind})`;\n const filter = buildFilter(opts, at);\n switch (kind) {\n case \"push\":\n return filter !== undefined ? { kind: \"push\", filter } : { kind: \"push\" };\n case \"changeRequest\":\n return filter !== undefined\n ? { kind: \"changeRequest\", filter }\n : { kind: \"changeRequest\" };\n case \"manual\":\n return filter !== undefined\n ? { kind: \"manual\", filter }\n : { kind: \"manual\" };\n case \"schedule\":\n return toScheduleTrigger(opts, at);\n case \"comment\":\n return toCommentTrigger(opts, at);\n case \"issue\":\n return toIssueTrigger(opts, at);\n default:\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: unknown trigger kind '${kind}'`,\n \"INVALID_TRIGGER\",\n );\n }\n}\n\nfunction toScheduleTrigger(opts: Record<string, unknown>, at: string): Trigger {\n if (typeof opts.cron !== \"string\" || opts.cron === \"\") {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: schedule trigger requires a 'cron' string`,\n \"INVALID_TRIGGER\",\n );\n }\n if (opts.timezone !== undefined && typeof opts.timezone !== \"string\") {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: schedule 'timezone' must be a string`,\n \"INVALID_TRIGGER\",\n );\n }\n return {\n kind: \"schedule\",\n cron: opts.cron,\n ...(opts.timezone !== undefined ? { timezone: opts.timezone } : {}),\n };\n}\n\nfunction toCommentTrigger(opts: Record<string, unknown>, at: string): Trigger {\n const on = opts.on;\n if (\n on !== undefined &&\n on !== \"mergeRequest\" &&\n on !== \"issue\" &&\n on !== \"commit\"\n ) {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: comment 'on' must be mergeRequest|issue|commit`,\n \"INVALID_TRIGGER\",\n );\n }\n // A dropped non-string mention silently widens a restricted trigger\n // into an unrestricted one — reject it instead.\n if (opts.mention !== undefined && typeof opts.mention !== \"string\") {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: comment 'mention' must be a string`,\n \"INVALID_TRIGGER\",\n );\n }\n return {\n kind: \"comment\",\n ...(opts.mention !== undefined ? { mention: opts.mention } : {}),\n ...(on !== undefined ? { on } : {}),\n };\n}\n\nfunction toIssueTrigger(opts: Record<string, unknown>, at: string): Trigger {\n const action = opts.action;\n if (\n action !== undefined &&\n action !== \"opened\" &&\n action !== \"reopened\" &&\n action !== \"labeled\"\n ) {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: issue 'action' must be opened|reopened|labeled`,\n \"INVALID_TRIGGER\",\n );\n }\n const labels = opts.labels;\n if (\n labels !== undefined &&\n (!Array.isArray(labels) || !labels.every((l) => typeof l === \"string\"))\n ) {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: issue 'labels' must be an array of strings`,\n \"INVALID_TRIGGER\",\n );\n }\n return {\n kind: \"issue\",\n ...(action !== undefined ? { action } : {}),\n ...(labels !== undefined ? { labels: labels as readonly string[] } : {}),\n };\n}\n\nfunction buildFilter(\n opts: Record<string, unknown>,\n at: string,\n): TriggerFilter | undefined {\n const filter: Record<string, readonly string[]> = {};\n for (const key of FILTER_KEYS) {\n const v = opts[key];\n if (v === undefined) continue;\n if (!Array.isArray(v) || !v.every((s) => typeof s === \"string\")) {\n throw new MarkdownParseError(\n `invalid .sverka.md ${at}: '${key}' must be an array of strings`,\n \"INVALID_TRIGGER\",\n );\n }\n filter[key] = v as readonly string[];\n }\n return Object.keys(filter).length > 0 ? (filter as TriggerFilter) : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Steps\n// ---------------------------------------------------------------------------\n\nconst STEP_HEADING = /^##\\s+(\\S+)\\s*$/;\n\nfunction parseSteps(body: string): readonly ParsedStep[] {\n const steps: ParsedStep[] = [];\n const lines = body.split(\"\\n\");\n let i = 0;\n while (i < lines.length) {\n const heading = STEP_HEADING.exec(lines[i]!);\n if (heading === null) {\n i++;\n continue;\n }\n const id = heading[1]!;\n const section: string[] = [];\n let j = i + 1;\n while (j < lines.length && !STEP_HEADING.test(lines[j]!)) {\n section.push(lines[j]!);\n j++;\n }\n steps.push(parseStepSection(id, section));\n i = j;\n }\n return steps;\n}\n\n/**\n * Parse one `- key: value` bullet line. Hand-rolled linear scan — a regex\n * over uncontrolled markdown is a ReDoS vector.\n */\nfunction parseBulletLine(\n line: string,\n): { readonly key: string; readonly rest: string } | null {\n const isSpace = (c: string | undefined) => c !== undefined && /\\s/.test(c);\n const isKeyChar = (c: string | undefined) =>\n c !== undefined && /[\\w-]/.test(c);\n if (!line.startsWith(\"-\") || !isSpace(line[1])) return null;\n let i = skipWhile(line, 1, isSpace);\n if (!isKeyStart(line[i])) return null;\n const keyStart = i;\n i = skipWhile(line, i, isKeyChar);\n const key = line.slice(keyStart, i);\n i = skipWhile(line, i, isSpace);\n if (line[i] !== \":\") return null;\n return { key, rest: line.slice(i + 1).trimStart() };\n}\n\nfunction skipWhile(\n line: string,\n from: number,\n pred: (c: string | undefined) => boolean,\n): number {\n let i = from;\n while (i < line.length && pred(line[i])) i++;\n return i;\n}\n\nfunction isKeyStart(c: string | undefined): boolean {\n return c !== undefined && /[a-zA-Z_]/.test(c);\n}\n\n/**\n * Parse one `## step` section: `- key: value` bullets (indented blocks\n * belong to the preceding bullet). Non-bullet prose is ignored so a step\n * can carry documentation.\n */\nfunction parseStepSection(id: string, lines: readonly string[]): ParsedStep {\n return toParsedStep(id, collectStepProps(id, lines));\n}\n\n/** Validate collected props and build the ParsedStep. */\nfunction toParsedStep(id: string, props: Record<string, unknown>): ParsedStep {\n if (typeof props.command !== \"string\" || props.command === \"\") {\n throw new MarkdownParseError(\n `invalid .sverka.md step '${id}': missing required '- command:' line`,\n \"INVALID_STEP\",\n );\n }\n const dependsOn = props.dependsOn ?? props[\"depends_on\"];\n if (\n dependsOn !== undefined &&\n (!Array.isArray(dependsOn) ||\n !dependsOn.every((d) => typeof d === \"string\"))\n ) {\n throw new MarkdownParseError(\n `invalid .sverka.md step '${id}': 'dependsOn' must be an array of step ids`,\n \"INVALID_STEP\",\n );\n }\n if (\n props.timeout !== undefined &&\n (typeof props.timeout !== \"number\" || !Number.isFinite(props.timeout))\n ) {\n throw new MarkdownParseError(\n `invalid .sverka.md step '${id}': 'timeout' must be a number (ms)`,\n \"INVALID_STEP\",\n );\n }\n if (props.image !== undefined && typeof props.image !== \"string\") {\n throw new MarkdownParseError(\n `invalid .sverka.md step '${id}': 'image' must be a string`,\n \"INVALID_STEP\",\n );\n }\n\n return {\n id,\n command: props.command,\n ...(dependsOn !== undefined\n ? { dependsOn: dependsOn as readonly string[] }\n : {}),\n ...(props.image !== undefined ? { image: props.image as string } : {}),\n ...(props.timeout !== undefined\n ? { timeout: props.timeout as number }\n : {}),\n ...(props.outputs !== undefined\n ? {\n outputs: props.outputs as Readonly<Record<string, OutputDeclaration>>,\n }\n : {}),\n };\n}\n\n/**\n * Collect `- key: value` bullets (with indented continuation blocks) into\n * a props map. Non-bullet prose is ignored.\n */\nfunction collectStepProps(\n id: string,\n lines: readonly string[],\n): Record<string, unknown> {\n const props: Record<string, unknown> = {};\n let i = 0;\n while (i < lines.length) {\n const bullet = parseBulletLine(lines[i]!);\n if (bullet === null) {\n i++;\n continue;\n }\n const { key, rest } = bullet;\n if (rest === \"\") {\n // Nested block: collect the indented continuation lines.\n const block: string[] = [];\n let j = i + 1;\n while (j < lines.length && /^\\s+\\S/.test(lines[j]!)) {\n block.push(lines[j]!);\n j++;\n }\n props[key] =\n block.length > 0 ? parseYamlScalar(block.join(\"\\n\"), id, key) : null;\n i = j;\n } else {\n props[key] = parseYamlScalar(rest, id, key);\n i++;\n }\n }\n return props;\n}\n\nfunction parseYamlScalar(rest: string, stepId: string, key: string): unknown {\n try {\n return parseYaml(rest);\n } catch (e) {\n throw new MarkdownParseError(\n `invalid .sverka.md step '${stepId}': cannot parse '${key}' value: ${e instanceof Error ? e.message : String(e)}`,\n \"INVALID_STEP\",\n e,\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// Construct assembly\n// ---------------------------------------------------------------------------\n\nfunction buildMarkdownPipeline(\n scope: Project,\n fm: MarkdownFrontmatter,\n body: string,\n _filePath?: string,\n): void {\n const pipeline = new Pipeline(scope, fm.pipeline, {\n ...(fm.inputs !== undefined ? { inputs: fm.inputs } : {}),\n });\n const steps = parseSteps(body);\n // Construct registers into `pipeline` on construction — handles are kept\n // to read back the registered step ids as entry roots.\n const shellSteps = steps.map(\n (step) =>\n new ShellStep(pipeline, step.id, {\n command: step.command,\n ...(step.dependsOn !== undefined ? { dependsOn: step.dependsOn } : {}),\n ...(step.image !== undefined\n ? { runtime: { mode: \"container\", image: step.image } }\n : {}),\n ...(step.timeout !== undefined ? { timeout: step.timeout } : {}),\n ...(step.outputs !== undefined ? { outputs: step.outputs } : {}),\n }),\n );\n // Entry roots: every step — `on:` triggers the whole pipeline, matching\n // gh-aw semantics (reachability walks dependencies back to producers).\n const roots = shellSteps.map((s) => s.node.id);\n const triggers = frontmatterTriggers(fm);\n const usedIds = new Set<string>();\n for (const trigger of triggers) {\n const base = `on-${trigger.kind}`;\n let id = base;\n let n = 2;\n while (usedIds.has(id)) {\n id = `${base}-${n}`;\n n++;\n }\n const entry = new Entry(pipeline, id, { trigger, roots });\n usedIds.add(entry.node.id);\n }\n}\n\n// ---------------------------------------------------------------------------\n// extends\n// ---------------------------------------------------------------------------\n\nasync function loadExtends(\n extendsPath: string,\n mdPath: string,\n): Promise<Project> {\n const resolved = resolve(dirname(mdPath), extendsPath);\n if (!existsSync(resolved)) {\n throw new MarkdownParseError(\n `extends path does not resolve: ${extendsPath} (from ${mdPath})`,\n \"EXTENDS_NOT_FOUND\",\n );\n }\n let mod: Record<string, unknown>;\n try {\n mod = await import(pathToFileURL(resolved).href);\n } catch (e) {\n throw new MarkdownParseError(\n `failed to load extends config ${extendsPath}: ${e instanceof Error ? e.message : String(e)}`,\n \"EXTENDS_NOT_FOUND\",\n e,\n );\n }\n const construct = mod.project ?? mod.default;\n if (\n typeof construct !== \"object\" ||\n construct === null ||\n !(\"node\" in construct)\n ) {\n throw new MarkdownParseError(\n `extends config ${extendsPath} must export a Project or Pipeline`,\n \"EXTENDS_NOT_FOUND\",\n );\n }\n const node = (construct as Construct).node;\n // A bare Pipeline's scope is its implicitly-created Project — add the\n // markdown pipeline alongside it.\n return (node.scope ?? construct) as unknown as Project;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,SAAS,mBAA2B;CAClC,MAAM,UAAU,QAAQ,IAAI,QAAQ;CACpC,KAAK,MAAM,OAAO,QAAQ,MAAM,KAAK,SAAS,GAAG;EAC/C,IAAI,CAAC,KAAK;EACV,MAAM,YAAY,KAAK,KAAK,KAAK,KAAK;EACtC,IAAI,WAAW,SAAS,GACtB,OAAO;CAEX;CACA,OAAO;AACT;AAEA,MAAM,aAAa,iBAAiB;;;;AAKpC,SAAgB,eAAuB;CACrC,OAAO,EACL,IAAI,MAAM,KAAK;EACb,OAAO,IAAI,SAAiB,gBAAgB,WAAW;GAGrD,MAAM,MAAyB;IAC7B,MAAM,QAAQ,IAAI;IAClB,qBAAqB;GACvB;GACA,MAAM,QAAQ,MAAM,YAAY,CAAC,GAAG,IAAI,GAAG;IACzC;IACA;IACA,OAAO;KAAC;KAAU;KAAQ;IAAM;GAClC,CAAC;GACD,IAAI,SAAS;GACb,IAAI,SAAS;GACb,MAAM,QAAQ,GAAG,SAAS,SAAiB;IACzC,UAAU,KAAK,SAAS;GAC1B,CAAC;GACD,MAAM,QAAQ,GAAG,SAAS,SAAiB;IACzC,UAAU,KAAK,SAAS;GAC1B,CAAC;GACD,MAAM,GAAG,UAAU,QAAQ;IACzB,OAAO,GAAG;GACZ,CAAC;GACD,MAAM,GAAG,UAAU,SAAS;IAC1B,IAAI,SAAS,GACX,eAAe,MAAM;SAErB,OACE,IAAI,MACF,OAAO,KAAK,KAAK,GAAG,EAAE,UAAU,QAAQ,MACxC,OAAO,KAAK,IAAI,EAAE,OAAO,OAAO,KAAK,EAAE,IAAI,MAC7C,CACF;GAEJ,CAAC;EACH,CAAC;CACH,EACF;AACF;;;ACtEA,M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G,KAAK,GAAG;GAChB;EACF;EACA,MAAM,QAAQ,IAAI,MAAM,UAAU,IAAI;GAAE;GAAS;EAAM,CAAC;EACxD,QAAQ,IAAI,MAAM,KAAK,EAAE;CAC3B;AACF;AAMA,eAAe,YACb,aACA,QACkB;CAClB,MAAM,WAAW,QAAQ,QAAQ,MAAM,GAAG,WAAW;CACrD,IAAI,CAAC,WAAW,QAAQ,GACtB,MAAM,IAAI,mBACR,kCAAkC,YAAY,SAAS,OAAO,IAC9D,mBACF;CAEF,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,OAAO,cAAc,QAAQ,CAAC,CAAC;CAC7C,SAAS,GAAG;EACV,MAAM,IAAI,mBACR,iCAAiC,YAAY,IAAI,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,KAC1F,qBACA,CACF;CACF;CACA,MAAM,YAAY,IAAI,WAAW,IAAI;CACrC,IACE,OAAO,cAAc,YACrB,cAAc,QACd,EAAE,UAAU,YAEZ,MAAM,IAAI,mBACR,kBAAkB,YAAY,qCAC9B,mBACF;CAKF,OAHc,UAAwB,KAGzB,SAAS;AACxB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sverka/sdk",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.30",
|
|
4
4
|
"description": "Sverka SDK — public TypeScript API for authoring and running workflows",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -34,14 +34,14 @@
|
|
|
34
34
|
"typecheck": "tsc --noEmit"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@sverka/workflow": "^0.2.
|
|
38
|
-
"@sverka/runtime": "^0.2.
|
|
39
|
-
"@sverka/verification": "^0.2.
|
|
37
|
+
"@sverka/workflow": "^0.2.30",
|
|
38
|
+
"@sverka/runtime": "^0.2.30",
|
|
39
|
+
"@sverka/verification": "^0.2.30",
|
|
40
40
|
"yaml": "^2.9.1"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"tsdown": "^0.23.
|
|
43
|
+
"tsdown": "^0.23.1",
|
|
44
44
|
"typescript": "^5.8.0",
|
|
45
|
-
"vitest": "^5.0.
|
|
45
|
+
"vitest": "^5.0.5"
|
|
46
46
|
}
|
|
47
47
|
}
|