@pipelex/mthds-ui 0.27.0 → 0.29.0
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/README.md +19 -5
- package/dist/{chunk-VCO4GZDZ.js → chunk-3I3ZPYMW.js} +13 -1
- package/dist/chunk-3I3ZPYMW.js.map +1 -0
- package/dist/{chunk-XBHDA3PQ.js → chunk-Y46574OW.js} +2 -2
- package/dist/{chunk-K3BWHQVX.js → chunk-ZTXSDTVF.js} +81 -34
- package/dist/chunk-ZTXSDTVF.js.map +1 -0
- package/dist/form/react/RunPanel.css +1 -3
- package/dist/form/react/index.d.ts +5 -5
- package/dist/form/react/index.js +2 -2
- package/dist/form/react/index.js.map +1 -1
- package/dist/graph/index.d.ts +24 -9
- package/dist/graph/index.js +11 -3
- package/dist/graph/react/graph-core.css +12 -0
- package/dist/graph/react/index.d.ts +113 -45
- package/dist/graph/react/index.js +333 -283
- package/dist/graph/react/index.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +11 -3
- package/dist/standalone/graph-standalone.html +420 -114
- package/dist/standalone/graph-viewer.css +13 -1
- package/dist/standalone/graph-viewer.js +406 -112
- package/dist/static-graph/index.d.ts +32 -9
- package/dist/static-graph/index.js +709 -88
- package/dist/static-graph/index.js.map +1 -1
- package/dist/{types-DgqW3Jg4.d.ts → types-BaFWy56P.d.ts} +106 -13
- package/package.json +2 -2
- package/dist/chunk-K3BWHQVX.js.map +0 -1
- package/dist/chunk-VCO4GZDZ.js.map +0 -1
- /package/dist/{chunk-XBHDA3PQ.js.map → chunk-Y46574OW.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/static-graph/types.ts","../../src/static-graph/conceptRefs.ts","../../src/static-graph/parseMthdsBundle.ts","../../src/static-graph/normalizePipe.ts","../../src/static-graph/mergeBundles.ts","../../src/static-graph/buildStaticGraphSpec.ts","../../src/static-graph/validationIssues.ts","../../src/static-graph/sourceOrder.ts","../../src/static-graph/mthdsSourcesEmbed.ts"],"sourcesContent":["// ─── Static method-graph module: domain types ───────────────────────────────\n// Pure TypeScript, no React. This module parses raw `.mthds` TOML text into\n// blueprint-shaped bundles, reusing the `Pipe*Blueprint` registry types from\n// `@graph/types` so the parsed entries can feed a GraphSpec `pipe_registry`\n// directly. Parsing is lenient: half-written bundles produce partial results\n// plus non-fatal diagnostics, never exceptions.\n\nimport type { ConceptInfo, PipeBlueprintUnion } from \"@graph/types\";\n\n// ─── Diagnostics ─────────────────────────────────────────────────────────────\n\nexport type DiagnosticSeverity = \"error\" | \"warning\";\n\nexport type DiagnosticCode =\n | \"toml-parse-error\"\n | \"missing-domain\"\n | \"invalid-bundle-shape\"\n | \"invalid-concept-entry\"\n | \"invalid-pipe-entry\"\n | \"unknown-pipe-type\"\n | \"retired-signature-tag\"\n | \"invalid-concept-ref\"\n | \"unknown-input-slot-key\"\n | \"missing-pipe-output\"\n | \"invalid-sub-pipe\"\n | \"incomplete-batch-spec\"\n | \"duplicate-concept\"\n | \"duplicate-pipe\"\n | \"signature-type-mismatch\"\n | \"unresolved-pipe-ref\"\n | \"cyclic-pipe-ref\"\n | \"missing-main-pipe\"\n | \"no-entry-pipe\"\n | \"conflicting-input-concept\";\n\n/**\n * A non-fatal note collected while parsing or merging. `error` means a whole\n * unit could not be interpreted (unparseable TOML, a skipped pipe); `warning`\n * means something was tolerated with a fallback (missing output, bad ref).\n */\nexport interface Diagnostic {\n severity: DiagnosticSeverity;\n code: DiagnosticCode;\n message: string;\n /** TOML-style locator for the offending entry, e.g. `pipe.analyze_candidate.output`. */\n path?: string;\n /**\n * Domain of the bundle namespace the diagnostic belongs to — the declaring-file\n * identity a host needs to qualify a `pipe.<code>` locator into a full pipe ref\n * (`domain_code.pipe_code`). Stamped wherever the owning namespace is known:\n * per-file diagnostics get their bundle's domain ({@link UNKNOWN_DOMAIN} when\n * the bundle declares none), merge/walk diagnostics the namespace being\n * processed, and entry selection stamps the diagnostics it can attribute (a\n * missing or unresolvable `main_pipe` names its declaring domain). Absent only\n * when no owning bundle can be resolved: unparseable TOML, or entry selection\n * with no resolvable owner (no bundles, no pipes anywhere, or a host-supplied\n * entry ref that matches nothing).\n */\n domain_code?: string;\n}\n\n// ─── Parsed bundle ───────────────────────────────────────────────────────────\n\n/**\n * One `.mthds` file, parsed and normalized. Pipes are narrowed to the same\n * `PipeBlueprintUnion` shapes the pipelex runtime serializes into GraphSpec\n * `pipe_registry`, and concepts to `ConceptInfo` — no parallel type universe.\n * Field names mirror the TOML bundle header keys.\n */\nexport interface ParsedBundle {\n domain: string | null;\n description: string | null;\n main_pipe: string | null;\n system_prompt: string | null;\n /** Concepts declared in this bundle, keyed by bare concept code. */\n concepts: Record<string, ConceptInfo>;\n /** Pipes declared in this bundle, keyed by bare pipe code. */\n pipes: Record<string, PipeBlueprintUnion>;\n}\n\nexport interface ParseMthdsBundleResult {\n bundle: ParsedBundle;\n diagnostics: Diagnostic[];\n}\n\n// ─── Merged method set ───────────────────────────────────────────────────────\n\n/** Namespace of one domain after merging bundles: concepts and pipes by bare code. */\nexport interface DomainNamespace {\n domain: string;\n concepts: Record<string, ConceptInfo>;\n pipes: Record<string, PipeBlueprintUnion>;\n}\n\n/**\n * The merged namespace of a method package: every parsed bundle grouped by\n * domain, with duplicate codes resolved keep-first (plus a diagnostic).\n * `mainDomain` / `mainPipe` come as a pair from the first bundle declaring\n * `main_pipe` (falling back to the first domained bundle when none does) —\n * the walk entry point for the static graph builder. `description` comes from\n * the first bundle that declares it.\n */\nexport interface MergedMethodSet {\n domains: Record<string, DomainNamespace>;\n mainDomain: string | null;\n mainPipe: string | null;\n description: string | null;\n diagnostics: Diagnostic[];\n}\n\n/** Namespace used for bundles that declare no `domain` (a legal WIP state). */\nexport const UNKNOWN_DOMAIN = \"unknown\";\n\n// ─── Narrowing helpers (shared by the parsing modules) ───────────────────────\n\n/**\n * True for plain tables only — rejects arrays, class instances and dates\n * (smol-toml emits `TomlDate` objects for TOML datetime values).\n */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * An empty record for keys an author wrote.\n *\n * Every accumulator in this module is keyed by authored `.mthds` text — input\n * names, concept codes, pipe codes, domain names — and a plain `{}` hands those\n * keys `Object.prototype` to collide with. Three distinct failures follow, none\n * of which the author is told about: `record[name] = value` for a name of\n * `__proto__` invokes the prototype setter and creates no own key, so the entry\n * vanishes with no diagnostic; `record[code]` for a code of `toString` returns a\n * built-in function that reads as a declared entry; and `record[domain] ??= …`\n * for a domain of `__proto__` yields `Object.prototype` itself, whose missing\n * members then throw — breaking this module's contract that it never throws on\n * content. A null prototype has nothing to collide with, so all three stop\n * existing at once rather than needing a guard at every read and write.\n */\nexport function authoredRecord<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\nexport function strOrNull(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nexport function intOrNull(value: unknown): number | null {\n return typeof value === \"number\" && Number.isInteger(value) ? value : null;\n}\n\nexport function boolOrNull(value: unknown): boolean | null {\n return typeof value === \"boolean\" ? value : null;\n}\n","// ─── Concept reference parsing and resolution ────────────────────────────────\n// A concept ref in MTHDS TOML is `Code` or `domain.Code`, optionally suffixed\n// with a multiplicity marker — `Code[]` (many) or `Code[N]` (exactly N) — and\n// then a presence marker — `Code?` (optional) or `Code!` (force). The suffix\n// order is fixed, multiplicity before presence, mirroring the runtime's\n// `MULTIPLICITY_PATTERN` in `pipelex/core/pipes/variable_multiplicity.py`.\n// Resolution follows the spec's namespace rules: bare refs resolve in the\n// current bundle first, then the native domain; qualified refs name their\n// domain explicitly. Anything unresolved becomes a best-effort stub — this\n// module never throws on content.\n\nimport type { ConceptInfo, PresenceMarker, StuffSpecInfo } from \"@graph/types\";\n\nimport { isPlainObject } from \"./types\";\n\nexport const NATIVE_DOMAIN = \"native\";\n\n/**\n * The native concept catalog. Codes and descriptions are copied from the MTHDS\n * standard's pinned set — `docs/spec/native-concepts.md` in the sibling `mthds/`\n * repo — which pipelex mirrors in `pipelex/core/concepts/native/concept_native.py`\n * and `native/pinned_blueprints.py`. Structure class names follow the runtime's\n * `<Code>Content` rule. Keep this table in the spec's canonical order; a code\n * missing here silently degrades to a stub. See `docs/static-graph.md`.\n */\nconst NATIVE_CONCEPT_DESCRIPTIONS = {\n Dynamic: \"A dynamic concept\",\n Text: \"A text\",\n Image: \"An image\",\n Document: \"A document\",\n Html: \"HTML content\",\n TextAndImages: \"A text and an image\",\n Number: \"A number\",\n YesNo: \"The answer to a yes/no question\",\n Date: \"A calendar date, optionally with a time of day — as precise as its source states.\",\n Time: \"A time of day, optionally with a UTC offset — as precise as its source states.\",\n Page: \"The content of a page of a document, comprising text and linked images and an optional page view image\",\n JSON: \"A JSON object\",\n SearchResult: \"A search result with answer and sources\",\n Anything: \"Anything\",\n Composite: \"A named composition of contents\",\n} satisfies Record<string, string>;\n\n/** A code the catalog knows. Derived from the catalog so the two cannot disagree. */\nexport type NativeConceptCode = keyof typeof NATIVE_CONCEPT_DESCRIPTIONS;\n\nexport const NATIVE_CONCEPT_CODES: ReadonlySet<string> = new Set(\n Object.keys(NATIVE_CONCEPT_DESCRIPTIONS),\n);\n\n/** Narrow an arbitrary code to the catalog, so callers cannot mint a native the catalog lacks. */\nexport function isNativeConceptCode(code: string): code is NativeConceptCode {\n return Object.hasOwn(NATIVE_CONCEPT_DESCRIPTIONS, code);\n}\n\n// ─── Ref parsing ─────────────────────────────────────────────────────────────\n\nexport interface ConceptRefParts {\n /** Explicit domain qualifier (`recruitment` in `recruitment.Profile`), or null for bare refs. */\n domain: string | null;\n code: string;\n /** `[]` → true (many), `[N]` → N, no suffix → null (single). */\n multiplicity: number | boolean | null;\n /** `?` → \"optional\", `!` → \"force\", no suffix → \"plain\". */\n presence: PresenceMarker;\n}\n\nconst CONCEPT_REF_RE = /^(?:([A-Za-z0-9_][A-Za-z0-9_.]*)\\.)?([A-Za-z0-9_]+)(?:\\[(\\d*)\\])?([?!])?$/;\n\nfunction presenceFromSymbol(symbol: string | undefined): PresenceMarker {\n if (symbol === \"?\") return \"optional\";\n if (symbol === \"!\") return \"force\";\n return \"plain\";\n}\n\n/** Parse a concept ref string into its parts. Returns null when the ref is not interpretable. */\nexport function parseConceptRef(raw: unknown): ConceptRefParts | null {\n if (typeof raw !== \"string\") return null;\n const match = CONCEPT_REF_RE.exec(raw.trim());\n if (!match) return null;\n const [, domain, code, multiplicity, presence] = match;\n return {\n domain: domain ?? null,\n code,\n multiplicity:\n multiplicity === undefined\n ? null\n : multiplicity === \"\"\n ? true\n : Number.parseInt(multiplicity, 10),\n presence: presenceFromSymbol(presence),\n };\n}\n\n// ─── Input slot declarations ─────────────────────────────────────────────────\n// A value in a pipe's `inputs` table has two forms, and the standard states\n// them equivalent (`docs/spec/mthds-format.md`, \"Input slot declarations\"):\n// the string form `x = \"S\"`, and the expanded form `x = { concept = \"S\",\n// hints = { … } }`, whose `concept` carries exactly the same grammar. The\n// expanded form is inputs-only — an `output` is always a string — so this\n// layer sits beside `parseConceptRef` rather than inside it.\n\n/**\n * The keys the expanded slot table defines in this version of the standard.\n * The form is deliberately closed: the spec says an unknown key MUST be\n * rejected, which pipelex implements as `extra=\"forbid\"` on its\n * `InputSlotBlueprint`. This module renders rather than adjudicates, so it\n * reports the key and reads past it — see `parseInputSlot`.\n */\nconst INPUT_SLOT_KEYS: ReadonlySet<string> = new Set([\"concept\", \"hints\"]);\n\nexport interface InputSlotParts {\n /** The slot's concept ref parts, or null when the slot is not interpretable. */\n ref: ConceptRefParts | null;\n /**\n * True when an expanded slot table declares no `concept` at all. The key is\n * required, so there is no ref for a diagnostic to be about — the caller says\n * the key is missing rather than blaming a ref the author never wrote.\n */\n missingConcept: boolean;\n /** Keys of an expanded slot table this version of the standard does not define. */\n unknownKeys: string[];\n /**\n * True when the table is not a slot table at all but the wreckage of an\n * unquoted dotted input name — see {@link looksLikeUnquotedDottedName}.\n */\n dottedName: boolean;\n}\n\n/** A concept code as the standard pins it: `[A-Z][a-zA-Z0-9]*`. */\nconst CONCEPT_CODE_RE = /^[A-Z][A-Za-z0-9]*$/;\n\n/**\n * Recognize the slip the standard names explicitly: \"A dotted input name MUST\n * be written as a single quoted TOML key (`\"my_input.field_name\" = \"Text\"`),\n * never as an unquoted dotted path: TOML parses the latter as nested tables,\n * which the expanded slot form would misread as a slot table\"\n * (`docs/spec/mthds-format.md`, \"Input names\").\n *\n * `inputs = { my_input.field_name = \"Text\" }` arrives here as a slot named\n * `my_input` holding `{ field_name: \"Text\" }` — a table with no `concept` whose\n * every undefined key names a concept ref. Without this the author is told the\n * slot declares an undefined key and then that it has no `concept`, two true\n * sentences that between them never mention the quoting rule that is the fix.\n *\n * The concept-code rule is what keeps this apart from a genuine unknown key: a\n * code MUST be `PascalCase`, so `{ widget = \"textarea\" }` cannot be mistaken\n * for a nested field, while `{ field_name = \"Text\" }` can only be one.\n */\nfunction looksLikeUnquotedDottedName(raw: Record<string, unknown>, unknownKeys: string[]): boolean {\n if (raw.concept !== undefined || unknownKeys.length === 0) return false;\n return unknownKeys.every((key) => {\n const parts = parseConceptRef(raw[key]);\n return parts !== null && CONCEPT_CODE_RE.test(parts.code);\n });\n}\n\n/**\n * Read one `inputs` value, whichever form authored it.\n *\n * `hints` is parsed as a known key and then dropped: intent hints are\n * presentational, and the standard routes them to renderers through the\n * input-form descriptor, not the GraphSpec (see `docs/static-graph.md`).\n * Their shape is not checked here for the same reason — a malformed `hints`\n * table is content this module never reads, so it is the validator's to\n * report, not the renderer's. An unknown key is different: it may well be\n * where a future standard puts something that changes the slot, so it is\n * named rather than passed over.\n */\nexport function parseInputSlot(raw: unknown): InputSlotParts {\n if (!isPlainObject(raw)) {\n return {\n ref: parseConceptRef(raw),\n missingConcept: false,\n unknownKeys: [],\n dottedName: false,\n };\n }\n const unknownKeys = Object.keys(raw).filter((key) => !INPUT_SLOT_KEYS.has(key));\n return {\n ref: parseConceptRef(raw.concept),\n missingConcept: raw.concept === undefined,\n unknownKeys,\n dottedName: looksLikeUnquotedDottedName(raw, unknownKeys),\n };\n}\n\n// ─── Resolution to ConceptInfo ───────────────────────────────────────────────\n\n/**\n * Synthetic structure class name for a non-native concept, mirroring the\n * runtime's `make_qualified_structure_class_name`: dots in hierarchical\n * domain codes are replaced with interpuncts (·) to keep the name a valid,\n * collision-free identifier (`a.b` → `a·b`, distinct from `a_b`).\n */\nexport function qualifiedStructureClassName(domain: string, code: string): string {\n return `${domain.replaceAll(\".\", \"·\")}__${code}`;\n}\n\nexport function nativeConceptInfo(code: NativeConceptCode): ConceptInfo {\n return {\n code,\n domain_code: NATIVE_DOMAIN,\n description: NATIVE_CONCEPT_DESCRIPTIONS[code],\n structure_class_name: `${code}Content`,\n refines: null,\n };\n}\n\n/**\n * Best-effort info for a concept that is referenced but not declared in the\n * material at hand — an implicit concept, a WIP ref, or a cross-bundle ref\n * that `mergeBundles` may still enrich later.\n */\nfunction stubConceptInfo(code: string, domain: string): ConceptInfo {\n return {\n code,\n domain_code: domain,\n description: \"\",\n structure_class_name: qualifiedStructureClassName(domain, code),\n refines: null,\n };\n}\n\n/**\n * Resolve parsed ref parts against the current bundle. `localConcepts` holds\n * the bundle's declared concepts keyed by bare code.\n */\nexport function resolveConceptInfo(\n parts: ConceptRefParts,\n currentDomain: string,\n localConcepts: Record<string, ConceptInfo>,\n): ConceptInfo {\n if (parts.domain === NATIVE_DOMAIN) {\n return isNativeConceptCode(parts.code)\n ? nativeConceptInfo(parts.code)\n : stubConceptInfo(parts.code, NATIVE_DOMAIN);\n }\n if (parts.domain !== null && parts.domain !== currentDomain) {\n return stubConceptInfo(parts.code, parts.domain);\n }\n // Local before native. The spec inverts this (\"Native concepts always take\n // priority\"), but it also makes a bundle that declares a native-named concept\n // invalid outright — so this branch is only reachable on a bundle pipelex\n // rejects. Tracked in `wip/native-concept-shadowing.md`.\n // `hasOwn`, not a truthiness test: `localConcepts` is a caller-supplied\n // record, and on a plain `{}` a code of `toString` or `constructor` reads a\n // built-in off `Object.prototype` and returns a function as the concept.\n if (Object.hasOwn(localConcepts, parts.code)) return localConcepts[parts.code];\n if (parts.domain === null && isNativeConceptCode(parts.code)) {\n return nativeConceptInfo(parts.code);\n }\n return stubConceptInfo(parts.code, currentDomain);\n}\n\n/** Build a `StuffSpecInfo` from already-parsed ref parts. */\nfunction stuffSpecFromParts(\n parts: ConceptRefParts,\n currentDomain: string,\n localConcepts: Record<string, ConceptInfo>,\n): StuffSpecInfo {\n return {\n concept: resolveConceptInfo(parts, currentDomain, localConcepts),\n multiplicity: parts.multiplicity,\n presence: parts.presence,\n };\n}\n\n/** Resolve a raw concept ref string straight to a `StuffSpecInfo`, or null when unparseable. */\nexport function resolveStuffSpec(\n raw: unknown,\n currentDomain: string,\n localConcepts: Record<string, ConceptInfo>,\n): StuffSpecInfo | null {\n const parts = parseConceptRef(raw);\n return parts === null ? null : stuffSpecFromParts(parts, currentDomain, localConcepts);\n}\n\nexport interface ResolvedInputSlot {\n /** The resolved slot, or null when its concept ref is not interpretable. */\n spec: StuffSpecInfo | null;\n /** True when an expanded slot table declares no `concept` at all — see {@link InputSlotParts}. */\n missingConcept: boolean;\n /** Keys of an expanded slot table this version of the standard does not define. */\n unknownKeys: string[];\n /** True when the table is the wreckage of an unquoted dotted input name — see {@link InputSlotParts}. */\n dottedName: boolean;\n}\n\n/**\n * Resolve one `inputs` value to a `StuffSpecInfo`, accepting either slot form.\n * The `StuffSpecInfo` is identical whichever form authored it, which is what\n * the standard means by calling `x = \"S\"` and `x = { concept = \"S\" }` the same\n * slot.\n */\nexport function resolveInputSlot(\n raw: unknown,\n currentDomain: string,\n localConcepts: Record<string, ConceptInfo>,\n): ResolvedInputSlot {\n const { ref, missingConcept, unknownKeys, dottedName } = parseInputSlot(raw);\n return {\n spec: ref === null ? null : stuffSpecFromParts(ref, currentDomain, localConcepts),\n missingConcept,\n unknownKeys,\n dottedName,\n };\n}\n","// ─── parseMthdsBundle: `.mthds` TOML text → ParsedBundle ─────────────────────\n// The single entry point for turning one raw `.mthds` string into a\n// blueprint-shaped bundle. Lenient in the `validateGraphSpec` house style but\n// inverted: instead of failing loudly on contract violations, it tolerates\n// missing or partial sections, skips what it cannot interpret, and records\n// non-fatal diagnostics — the whole point is rendering methods while they are\n// being written. It never throws on content; even unparseable TOML becomes an\n// `error` diagnostic with an empty bundle.\n\nimport { parse as parseToml } from \"smol-toml\";\n\nimport type { ConceptInfo, PipeBlueprintUnion } from \"@graph/types\";\n\nimport {\n isNativeConceptCode,\n NATIVE_DOMAIN,\n parseConceptRef,\n qualifiedStructureClassName,\n} from \"./conceptRefs\";\nimport { normalizePipe } from \"./normalizePipe\";\nimport type { Diagnostic, ParseMthdsBundleResult, ParsedBundle } from \"./types\";\nimport { authoredRecord, isPlainObject, strOrNull, UNKNOWN_DOMAIN } from \"./types\";\n\n// ─── Concept structure → JSON schema (display-only, best-effort) ─────────────\n\nconst FIELD_TYPE_TO_JSON: Record<string, Record<string, unknown>> = {\n text: { type: \"string\" },\n integer: { type: \"integer\" },\n number: { type: \"number\" },\n boolean: { type: \"boolean\" },\n date: { type: \"string\", format: \"date\" },\n datetime: { type: \"string\", format: \"date-time\" },\n time: { type: \"string\", format: \"time\" },\n list: { type: \"array\" },\n dict: { type: \"object\" },\n concept: { type: \"object\" },\n};\n\nfunction fieldSchema(spec: Record<string, unknown>): Record<string, unknown> {\n const typeName = strOrNull(spec.type) ?? \"text\";\n const schema: Record<string, unknown> = {\n ...(FIELD_TYPE_TO_JSON[typeName] ?? { type: \"string\" }),\n };\n const description = strOrNull(spec.description);\n if (description !== null) schema.description = description;\n if (typeName === \"list\") {\n const itemType = strOrNull(spec.item_type);\n schema.items = itemType !== null ? { ...(FIELD_TYPE_TO_JSON[itemType] ?? {}) } : {};\n }\n if (Array.isArray(spec.choices)) {\n schema.enum = spec.choices.filter((choice) => typeof choice === \"string\");\n }\n if (spec.default_value !== undefined && spec.default_value !== null) {\n schema.default = spec.default_value;\n }\n return schema;\n}\n\n/**\n * Derive a lightweight JSON schema from a `[concept.X.structure]` table so\n * concept detail panels have fields to show. Deliberately simpler than the\n * pydantic-generated schema the runtime emits (no anyOf-null wrapping, no\n * per-field titles) — this is presentation data, not a contract.\n */\nfunction deriveJsonSchema(\n structure: unknown,\n title: string,\n description: string,\n): Record<string, unknown> | undefined {\n if (!isPlainObject(structure)) return undefined;\n const properties = authoredRecord<unknown>();\n const required: string[] = [];\n for (const [name, spec] of Object.entries(structure)) {\n if (typeof spec === \"string\") {\n properties[name] = { type: \"string\", description: spec };\n continue;\n }\n if (!isPlainObject(spec)) continue;\n properties[name] = fieldSchema(spec);\n if (spec.required === true) required.push(name);\n }\n return {\n title,\n type: \"object\",\n description,\n properties,\n ...(required.length > 0 ? { required } : {}),\n };\n}\n\n// ─── Concept table parsing ───────────────────────────────────────────────────\n\n/** Qualify a `refines` ref the way the runtime registry does (`Text` → `native.Text`). */\nfunction qualifyRefines(\n raw: unknown,\n domain: string,\n declaredCodes: ReadonlySet<string>,\n conceptCode: string,\n diagnostics: Diagnostic[],\n): string | null {\n const parts = parseConceptRef(raw);\n if (parts === null) return null;\n // `refines` names a concept; multiplicity and presence are properties of an io\n // slot that holds values, so a `refines` carrying either is malformed. Dropping\n // the suffix silently would turn `refines = \"Text?\"` into a plain `native.Text`\n // that reads back as if the author had written it that way.\n if (parts.multiplicity !== null || parts.presence !== \"plain\") {\n diagnostics.push({\n severity: \"warning\",\n code: \"invalid-concept-ref\",\n message:\n `concept \"${conceptCode}\": \\`refines\\` names a concept, so it takes no multiplicity ` +\n `or presence suffix — ignored`,\n path: `concept.${conceptCode}.refines`,\n });\n return null;\n }\n if (parts.domain !== null) return `${parts.domain}.${parts.code}`;\n if (!declaredCodes.has(parts.code) && isNativeConceptCode(parts.code)) {\n return `${NATIVE_DOMAIN}.${parts.code}`;\n }\n return `${domain}.${parts.code}`;\n}\n\nfunction parseConcepts(\n raw: unknown,\n domain: string,\n diagnostics: Diagnostic[],\n): Record<string, ConceptInfo> {\n const concepts = authoredRecord<ConceptInfo>();\n if (raw === undefined) return concepts;\n if (!isPlainObject(raw)) {\n diagnostics.push({\n severity: \"warning\",\n code: \"invalid-bundle-shape\",\n message: \"concept section is not a table — ignored\",\n path: \"concept\",\n });\n return concepts;\n }\n const declaredCodes: ReadonlySet<string> = new Set(Object.keys(raw));\n for (const [code, entry] of Object.entries(raw)) {\n if (typeof entry === \"string\") {\n // Shorthand form: `Concept = \"description\"`.\n concepts[code] = {\n code,\n domain_code: domain,\n description: entry,\n structure_class_name: qualifiedStructureClassName(domain, code),\n refines: null,\n };\n continue;\n }\n if (!isPlainObject(entry)) {\n diagnostics.push({\n severity: \"warning\",\n code: \"invalid-concept-entry\",\n message: `concept \"${code}\" is neither a table nor a description string — skipped`,\n path: `concept.${code}`,\n });\n continue;\n }\n const description = strOrNull(entry.description) ?? \"\";\n // A `structure = \"ClassName\"` string names an existing structure class;\n // the table form gets the runtime's `<domain>__<Code>` synthetic name.\n const structureClassName =\n strOrNull(entry.structure) ?? qualifiedStructureClassName(domain, code);\n concepts[code] = {\n code,\n domain_code: domain,\n description,\n structure_class_name: structureClassName,\n refines: qualifyRefines(entry.refines, domain, declaredCodes, code, diagnostics),\n json_schema: deriveJsonSchema(entry.structure, structureClassName, description),\n };\n }\n return concepts;\n}\n\n// ─── Bundle parsing ──────────────────────────────────────────────────────────\n\nfunction emptyBundle(): ParsedBundle {\n return {\n domain: null,\n description: null,\n main_pipe: null,\n system_prompt: null,\n concepts: authoredRecord<ConceptInfo>(),\n pipes: authoredRecord<PipeBlueprintUnion>(),\n };\n}\n\n/**\n * Parse one `.mthds` TOML string. Returns whatever could be interpreted plus\n * the diagnostics collected along the way — never throws.\n */\nexport function parseMthdsBundle(tomlText: string): ParseMthdsBundleResult {\n const diagnostics: Diagnostic[] = [];\n let root: Record<string, unknown>;\n try {\n root = parseToml(tomlText);\n } catch (error) {\n diagnostics.push({\n severity: \"error\",\n code: \"toml-parse-error\",\n message: error instanceof Error ? error.message : String(error),\n });\n return { bundle: emptyBundle(), diagnostics };\n }\n\n const bundle = emptyBundle();\n bundle.domain = strOrNull(root.domain);\n bundle.description = strOrNull(root.description);\n bundle.main_pipe = strOrNull(root.main_pipe);\n bundle.system_prompt = strOrNull(root.system_prompt);\n if (bundle.domain === null) {\n diagnostics.push({\n severity: \"warning\",\n code: \"missing-domain\",\n message: `bundle declares no domain — using \"${UNKNOWN_DOMAIN}\"`,\n path: \"domain\",\n });\n }\n const domain = bundle.domain ?? UNKNOWN_DOMAIN;\n\n bundle.concepts = parseConcepts(root.concept, domain, diagnostics);\n\n const pipeTable = root.pipe;\n if (pipeTable !== undefined) {\n if (!isPlainObject(pipeTable)) {\n diagnostics.push({\n severity: \"warning\",\n code: \"invalid-bundle-shape\",\n message: \"pipe section is not a table — ignored\",\n path: \"pipe\",\n });\n } else {\n const ctx = { domain, concepts: bundle.concepts, diagnostics };\n for (const [code, entry] of Object.entries(pipeTable)) {\n if (!isPlainObject(entry)) {\n diagnostics.push({\n severity: \"error\",\n code: \"invalid-pipe-entry\",\n message: `pipe \"${code}\" is not a table — skipped`,\n path: `pipe.${code}`,\n });\n continue;\n }\n const pipe: PipeBlueprintUnion | null = normalizePipe(code, entry, ctx);\n if (pipe !== null) bundle.pipes[code] = pipe;\n }\n }\n }\n\n // Stamp every diagnostic with the file's namespace domain — the declaring-file\n // identity hosts need to qualify `pipe.<code>` locators into full pipe refs.\n // (The toml-parse-error path returns above, before any domain exists.)\n for (const diagnostic of diagnostics) {\n diagnostic.domain_code ??= domain;\n }\n\n return { bundle, diagnostics };\n}\n","// ─── Pipe normalization: authored TOML shape → registry blueprint shape ─────\n// The authoring surface (mthds_schema.json, checked in under data/schema/)\n// and the runtime-serialized registry shape (`PipeBlueprintUnion` in\n// `@graph/types`) name things differently: `steps` vs `sequential_sub_pipes`,\n// `model` vs `llm_choices`, `prompt` vs `prompt_blueprint`, … This module maps\n// the former to the latter, leniently: uninterpretable pieces are skipped with\n// a diagnostic, and a pipe is dropped entirely only when it names no usable\n// `type` and is not a signature (see `resolvePipeTypeTag`).\n\nimport type {\n ConceptInfo,\n PipeBlueprintUnion,\n PipeComposeConstructBlueprint,\n PipeComposeConstructField,\n PipeType,\n StuffSpecInfo,\n SubPipeSpec,\n TemplateBlueprint,\n} from \"@graph/types\";\nimport { KNOWN_PIPE_TYPES } from \"@graph/types\";\n\nimport {\n NATIVE_DOMAIN,\n nativeConceptInfo,\n resolveInputSlot,\n resolveStuffSpec,\n} from \"./conceptRefs\";\nimport type { Diagnostic } from \"./types\";\nimport { authoredRecord, boolOrNull, intOrNull, isPlainObject, strOrNull } from \"./types\";\n\nexport interface NormalizePipeContext {\n domain: string;\n /** The bundle's declared concepts, keyed by bare code. */\n concepts: Record<string, ConceptInfo>;\n diagnostics: Diagnostic[];\n}\n\n// ─── Small shared builders ───────────────────────────────────────────────────\n\nfunction makeTemplate(template: string, category: string): TemplateBlueprint {\n return { template, templating_style: null, category, extra_context: null };\n}\n\n/**\n * Extract a display string from a model choice, which the authoring surface\n * allows as a plain handle (`\"gpt-5\"`), an inline setting (`{ model = … }`),\n * or a model reference (`{ name = … }`).\n */\nfunction modelToString(value: unknown): string | null {\n if (typeof value === \"string\") return strOrNull(value);\n if (isPlainObject(value)) {\n return strOrNull(value.model) ?? strOrNull(value.raw) ?? strOrNull(value.name);\n }\n return null;\n}\n\nfunction stringArrayOrNull(value: unknown): string[] | null {\n if (!Array.isArray(value)) return null;\n return value.filter((item): item is string => typeof item === \"string\");\n}\n\n// ─── IO normalization ────────────────────────────────────────────────────────\n\nfunction normalizeInputs(\n raw: unknown,\n pipeCode: string,\n ctx: NormalizePipeContext,\n): Record<string, StuffSpecInfo> {\n const inputs = authoredRecord<StuffSpecInfo>();\n if (raw === undefined || raw === null) return inputs;\n if (!isPlainObject(raw)) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-pipe-entry\",\n message: `pipe \"${pipeCode}\": inputs is not a table — ignored`,\n path: `pipe.${pipeCode}.inputs`,\n });\n return inputs;\n }\n for (const [name, slot] of Object.entries(raw)) {\n const { spec, missingConcept, unknownKeys, dottedName } = resolveInputSlot(\n slot,\n ctx.domain,\n ctx.concepts,\n );\n if (dottedName) {\n // Not a slot table at all — an unquoted dotted input name, which TOML\n // nests and the expanded form would otherwise misread. Reported alone,\n // because the two generic diagnostics below are both true of it and\n // neither mentions the quoting rule that is the fix.\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-concept-ref\",\n message:\n `pipe \"${pipeCode}\": input \"${name}\" reads as a slot table but looks like an unquoted ` +\n `dotted input name — write it as one quoted key (\"${name}.${unknownKeys.join(\".\")}\" = …) — skipped`,\n path: `pipe.${pipeCode}.inputs.${name}`,\n });\n continue;\n }\n if (unknownKeys.length > 0) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"unknown-input-slot-key\",\n message:\n `pipe \"${pipeCode}\": input \"${name}\" declares ${unknownKeys.map((key) => `\"${key}\"`).join(\", \")}, ` +\n \"which the input slot form does not define — ignored here, and the runtime refuses the bundle\",\n path: `pipe.${pipeCode}.inputs.${name}`,\n });\n }\n if (spec === null) {\n // Two ways to reach here, and they are different author mistakes: an\n // expanded slot that never declared the required `concept` key, versus a\n // ref that was written and does not parse. Saying \"uninterpretable ref\"\n // for the first blames a ref the author never wrote, which reads as a\n // grammar problem when the fix is to add the key.\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-concept-ref\",\n message: missingConcept\n ? `pipe \"${pipeCode}\": input \"${name}\" is a slot table with no \"concept\" — the key is required — skipped`\n : `pipe \"${pipeCode}\": input \"${name}\" has an uninterpretable concept ref — skipped`,\n path: `pipe.${pipeCode}.inputs.${name}`,\n });\n continue;\n }\n inputs[name] = spec;\n }\n return inputs;\n}\n\nfunction normalizeOutput(raw: unknown, pipeCode: string, ctx: NormalizePipeContext): StuffSpecInfo {\n const spec = resolveStuffSpec(raw, ctx.domain, ctx.concepts);\n if (spec !== null) return spec;\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"missing-pipe-output\",\n message: `pipe \"${pipeCode}\": missing or uninterpretable output — assuming native.Anything`,\n path: `pipe.${pipeCode}.output`,\n });\n return { concept: nativeConceptInfo(\"Anything\"), multiplicity: null, presence: \"plain\" };\n}\n\n// ─── Sub-pipe normalization (sequence steps, parallel branches) ──────────────\n\nfunction normalizeSubPipe(\n raw: unknown,\n pipeCode: string,\n path: string,\n ctx: NormalizePipeContext,\n): SubPipeSpec | null {\n if (!isPlainObject(raw) || strOrNull(raw.pipe) === null) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-sub-pipe\",\n message: `pipe \"${pipeCode}\": sub-pipe entry without a \"pipe\" ref — skipped`,\n path,\n });\n return null;\n }\n const batchOver = strOrNull(raw.batch_over);\n const batchAs = strOrNull(raw.batch_as);\n let batchParams: SubPipeSpec[\"batch_params\"] = null;\n if (batchOver !== null && batchAs !== null) {\n batchParams = { input_list_stuff_name: batchOver, input_item_stuff_name: batchAs };\n } else if (batchOver !== null || batchAs !== null) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"incomplete-batch-spec\",\n message:\n `pipe \"${pipeCode}\": sub-pipe \"${raw.pipe as string}\" sets only one of ` +\n `batch_over/batch_as — batching ignored`,\n path,\n });\n }\n // Mirrors the runtime SubPipeFactory: explicit nb_output wins, then\n // multiple_output, and a batched step is implicitly multiple.\n let outputMultiplicity: SubPipeSpec[\"output_multiplicity\"] =\n intOrNull(raw.nb_output) ?? (raw.multiple_output === true ? true : null);\n if (batchParams !== null && outputMultiplicity === null) outputMultiplicity = true;\n return {\n pipe_code: raw.pipe as string,\n output_name: strOrNull(raw.result),\n output_multiplicity: outputMultiplicity,\n batch_params: batchParams,\n };\n}\n\nfunction normalizeSubPipeList(\n raw: unknown,\n pipeCode: string,\n key: string,\n ctx: NormalizePipeContext,\n): SubPipeSpec[] {\n if (!Array.isArray(raw)) {\n if (raw !== undefined) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-pipe-entry\",\n message: `pipe \"${pipeCode}\": ${key} is not an array — treated as empty`,\n path: `pipe.${pipeCode}.${key}`,\n });\n }\n return [];\n }\n return raw\n .map((entry, index) =>\n normalizeSubPipe(entry, pipeCode, `pipe.${pipeCode}.${key}[${index}]`, ctx),\n )\n .filter((entry): entry is SubPipeSpec => entry !== null);\n}\n\n// ─── Compose construct normalization ─────────────────────────────────────────\n\nfunction normalizeConstructField(value: unknown): PipeComposeConstructField | null {\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n Array.isArray(value)\n ) {\n return { method: \"fixed\", fixed_value: value };\n }\n if (isPlainObject(value)) {\n if (typeof value.from === \"string\") {\n return {\n method: \"from_var\",\n from_path: value.from,\n list_to_dict_keyed_by: strOrNull(value.list_to_dict_keyed_by),\n };\n }\n if (typeof value.template === \"string\") {\n return { method: \"template\", template: value.template };\n }\n const nested = normalizeConstruct(value);\n if (nested !== null) return { method: \"nested\", nested };\n }\n return null;\n}\n\nfunction normalizeConstruct(raw: unknown): PipeComposeConstructBlueprint | null {\n if (!isPlainObject(raw)) return null;\n const fields: Record<string, PipeComposeConstructField> = {};\n for (const [name, value] of Object.entries(raw)) {\n const field = normalizeConstructField(value);\n if (field !== null) fields[name] = field;\n }\n return Object.keys(fields).length > 0 ? { fields } : null;\n}\n\n// ─── The signature contract: `type` on two different surfaces ────────────────\n//\n// `KNOWN_PIPE_TYPES` serves two masters, and pipelex 0.41 made them diverge:\n//\n// - GraphSpec `pipe_type` / the `pipe_registry` dump — `PipeSignature` IS a\n// member. The runtime `PipeSignature.type` serializes normally, so a\n// registry entry does carry `type: \"PipeSignature\"`. `validateGraphSpec`\n// checks against that set and must keep accepting it.\n// - Authored `.mthds` — `PipeSignature` is NOT a member. `PipeSignatureBlueprint`\n// sets `exclude=True` on its tag: a signature has no `type` in `.mthds`,\n// because *omitting the type IS the signature*. It is the sole definition in\n// `data/schema/mthds_schema.json` with no `type` property, which is exactly\n// what discriminates it in the bundle-level `oneOf`.\n//\n// Only this module reads the authored surface, so the split lives here. Mirrors\n// `normalize_typeless_signature_section` in pipelex's `pipe_blueprint.py`.\n\n/**\n * The only keys a typeless section may declare — `PipeSignatureBlueprint.properties`\n * in `data/schema/mthds_schema.json`. Anything else means the author started an\n * implementation and simply has not named its `type` yet.\n */\nconst SIGNATURE_ONLY_KEYS: ReadonlySet<string> = new Set([\n \"description\",\n \"inputs\",\n \"output\",\n \"signature_for\",\n]);\n\n/**\n * Resolve the pipe class from the authored section, reconciling both spellings\n * of a signature. Returns null (with a diagnostic) when the section names no\n * usable class.\n */\nfunction resolvePipeTypeTag(\n code: string,\n raw: Record<string, unknown>,\n ctx: NormalizePipeContext,\n): PipeType | null {\n const typeValue = raw.type;\n\n if (typeValue === undefined) {\n // A typeless section is a signature — but only if it declares nothing\n // beyond the contract, and `output` is present (the schema requires it).\n // Everything else keeps the plain unknown-type error: the schema rejects it too.\n const isSignature =\n raw.output !== undefined && Object.keys(raw).every((key) => SIGNATURE_ONLY_KEYS.has(key));\n if (isSignature) return \"PipeSignature\";\n } else if (typeValue === \"PipeSignature\") {\n // Retired in 0.41. Tolerated with a warning rather than dropped: erroring\n // would delete the pipe from the bundle — and with it the whole calling\n // step — which is the exact hole the typeless branch above exists to close.\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"retired-signature-tag\",\n message:\n `pipe \"${code}\": \\`type = \"PipeSignature\"\\` is no longer a pipe type — delete the ` +\n \"`type` line. A pipe with no `type` and no implementation is a signature (contract only).\",\n path: `pipe.${code}.type`,\n });\n return \"PipeSignature\";\n }\n\n if (typeof typeValue === \"string\" && KNOWN_PIPE_TYPES.has(typeValue)) {\n return typeValue as PipeType;\n }\n\n ctx.diagnostics.push({\n severity: \"error\",\n code: \"unknown-pipe-type\",\n message: `pipe \"${code}\": unknown pipe type ${JSON.stringify(typeValue)} — pipe skipped`,\n path: `pipe.${code}.type`,\n });\n return null;\n}\n\n// ─── Per-type normalization ──────────────────────────────────────────────────\n\n/**\n * Normalize one `[pipe.<code>]` table to its registry blueprint shape.\n * Returns null (with a diagnostic) only when the section names no usable pipe\n * class and is not a signature — everything else degrades field-by-field.\n */\nexport function normalizePipe(\n code: string,\n raw: Record<string, unknown>,\n ctx: NormalizePipeContext,\n): PipeBlueprintUnion | null {\n const typeValue = resolvePipeTypeTag(code, raw, ctx);\n if (typeValue === null) return null;\n const type = typeValue;\n const base = {\n code,\n domain_code: ctx.domain,\n description: strOrNull(raw.description) ?? \"\",\n inputs: normalizeInputs(raw.inputs, code, ctx),\n output: normalizeOutput(raw.output, code, ctx),\n };\n\n switch (type) {\n case \"PipeSequence\":\n return {\n ...base,\n type,\n pipe_category: \"PipeController\",\n sequential_sub_pipes: normalizeSubPipeList(raw.steps, code, \"steps\", ctx),\n };\n case \"PipeParallel\":\n return {\n ...base,\n type,\n pipe_category: \"PipeController\",\n parallel_sub_pipes: normalizeSubPipeList(raw.branches, code, \"branches\", ctx),\n add_each_output: raw.add_each_output === true,\n combined_output: strOrNull(raw.combined_output),\n };\n case \"PipeCondition\": {\n const outcomeMap: Record<string, string> = {};\n if (isPlainObject(raw.outcomes)) {\n for (const [outcome, pipeRef] of Object.entries(raw.outcomes)) {\n if (typeof pipeRef === \"string\" && pipeRef.length > 0) {\n outcomeMap[outcome] = pipeRef;\n } else {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-pipe-entry\",\n message: `pipe \"${code}\": outcome \"${outcome}\" is not a pipe ref — skipped`,\n path: `pipe.${code}.outcomes.${outcome}`,\n });\n }\n }\n }\n return {\n ...base,\n type,\n pipe_category: \"PipeController\",\n expression: strOrNull(raw.expression) ?? strOrNull(raw.expression_template) ?? \"\",\n outcome_map: outcomeMap,\n default_outcome: strOrNull(raw.default_outcome) ?? \"\",\n add_alias_from_expression_to: strOrNull(raw.add_alias_from_expression_to),\n };\n }\n case \"PipeBatch\": {\n const branchPipeCode = strOrNull(raw.branch_pipe_code);\n if (branchPipeCode === null) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-pipe-entry\",\n message: `pipe \"${code}\": PipeBatch without branch_pipe_code`,\n path: `pipe.${code}.branch_pipe_code`,\n });\n }\n return {\n ...base,\n type,\n pipe_category: \"PipeController\",\n branch_pipe_code: branchPipeCode ?? \"\",\n batch_params: {\n input_list_stuff_name: strOrNull(raw.input_list_name) ?? \"\",\n input_item_stuff_name: strOrNull(raw.input_item_name) ?? \"\",\n },\n };\n }\n case \"PipeLLM\": {\n const systemPrompt = strOrNull(raw.system_prompt);\n const prompt = strOrNull(raw.prompt);\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n llm_prompt_spec: {\n system_prompt_blueprint:\n systemPrompt === null ? null : makeTemplate(systemPrompt, \"llm_prompt\"),\n prompt_blueprint: prompt === null ? null : makeTemplate(prompt, \"llm_prompt\"),\n user_image_references: null,\n user_document_references: null,\n system_image_references: null,\n system_document_references: null,\n },\n llm_choices: {\n for_text: modelToString(raw.model),\n for_object: modelToString(raw.model_to_structure),\n },\n structuring_method: strOrNull(raw.structuring_method),\n output_multiplicity: null,\n };\n }\n case \"PipeStructure\": {\n const inputNames = Object.keys(base.inputs);\n const llmChoice = isPlainObject(raw.model) ? raw.model : strOrNull(raw.model);\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n llm_choice: llmChoice,\n text_input_name: inputNames[0] ?? \"text\",\n output_multiplicity: null,\n };\n }\n case \"PipeExtract\": {\n // Mirrors the runtime PipeExtractFactory: the (single) input is either\n // image-like or document-like, and exactly one of the two stuff names is\n // set. Statically, \"compatible with native.Image\" approximates to the\n // concept being Image or refining it; anything else counts as a document.\n const isImageLike = (spec: StuffSpecInfo): boolean =>\n (spec.concept.domain_code === NATIVE_DOMAIN && spec.concept.code === \"Image\") ||\n spec.concept.refines === `${NATIVE_DOMAIN}.Image`;\n const inputEntries = Object.entries(base.inputs);\n const imageInput = inputEntries.find(([, spec]) => isImageLike(spec));\n const documentInput = imageInput === undefined ? inputEntries[0] : undefined;\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n extract_choice: modelToString(raw.model),\n should_caption_images: raw.page_image_captions === true,\n max_page_images: intOrNull(raw.max_page_images),\n should_include_page_views: raw.page_views === true,\n page_views_dpi: intOrNull(raw.page_views_dpi),\n render_js: boolOrNull(raw.render_js),\n include_raw_html: boolOrNull(raw.include_raw_html),\n image_stuff_name: imageInput?.[0] ?? null,\n document_stuff_name: documentInput?.[0] ?? null,\n };\n }\n case \"PipeSearch\":\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n search_choice: modelToString(raw.model),\n prompt_blueprint: makeTemplate(strOrNull(raw.prompt) ?? \"\", \"basic\"),\n include_images_override: boolOrNull(raw.include_images),\n max_results_override: intOrNull(raw.max_results),\n from_date: strOrNull(raw.from_date),\n to_date: strOrNull(raw.to_date),\n include_domains: stringArrayOrNull(raw.include_domains),\n exclude_domains: stringArrayOrNull(raw.exclude_domains),\n is_structured_output: false,\n };\n case \"PipeImgGen\": {\n const prompt = strOrNull(raw.prompt);\n const negativePrompt = strOrNull(raw.negative_prompt);\n const seed = intOrNull(raw.seed) ?? (raw.seed === \"auto\" ? \"auto\" : null);\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n img_gen_prompt_blueprint: {\n prompt_blueprint: prompt === null ? null : makeTemplate(prompt, \"img_gen_prompt\"),\n negative_prompt_blueprint:\n negativePrompt === null ? null : makeTemplate(negativePrompt, \"img_gen_prompt\"),\n image_references: null,\n },\n img_gen_choice: modelToString(raw.model),\n aspect_ratio: strOrNull(raw.aspect_ratio),\n is_raw: boolOrNull(raw.is_raw),\n seed,\n background: strOrNull(raw.background),\n output_format: strOrNull(raw.output_format),\n output_multiplicity:\n typeof base.output.multiplicity === \"number\" ? base.output.multiplicity : 1,\n };\n }\n case \"PipeCompose\": {\n const rawTemplate = raw.template;\n let template: string | null = null;\n let templatingStyle: string | null = null;\n let category = \"basic\";\n let extraContext: Record<string, unknown> | null = null;\n if (typeof rawTemplate === \"string\") {\n template = rawTemplate;\n } else if (isPlainObject(rawTemplate)) {\n template = strOrNull(rawTemplate.template);\n templatingStyle = strOrNull(rawTemplate.templating_style);\n category = strOrNull(rawTemplate.category) ?? category;\n extraContext = isPlainObject(rawTemplate.extra_context) ? rawTemplate.extra_context : null;\n }\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n template,\n templating_style: templatingStyle,\n category,\n extra_context: extraContext,\n construct_blueprint: normalizeConstruct(raw.construct),\n };\n }\n case \"PipeFunc\":\n return { ...base, type, pipe_category: \"PipeOperator\" };\n case \"PipeSignature\": {\n const signatureFor = strOrNull(raw.signature_for);\n // `PipeSignature` itself is excluded: it is no longer a member of pipelex's\n // `PipeType`, so `signature_for = \"PipeSignature\"` is rejected upstream.\n return {\n ...base,\n type,\n pipe_category: null,\n signature_for:\n signatureFor !== null &&\n signatureFor !== \"PipeSignature\" &&\n KNOWN_PIPE_TYPES.has(signatureFor)\n ? (signatureFor as PipeType)\n : null,\n };\n }\n default: {\n const _exhaustive: never = type;\n return _exhaustive;\n }\n }\n}\n","// ─── mergeBundles: ParsedBundle[] → MergedMethodSet ──────────────────────────\n// A method package may span several `.mthds` files; files sharing a domain\n// merge into one namespace. Duplicate codes keep the first declaration and\n// record a diagnostic — except when a pipe signature meets its concrete\n// definition, which is the multi-file idiom rather than a duplication: the\n// concrete wins whichever file it came from, and nothing is reported unless the\n// two halves disagree about the pipe type the signature promised. After\n// merging, io concept stubs are re-pointed at the declarations that other files\n// contributed (a pipe in file A can reference a concept declared in file B).\n\nimport type { ConceptInfo, PipeBlueprintUnion, StuffSpecInfo } from \"@graph/types\";\n\nimport type { Diagnostic, DomainNamespace, MergedMethodSet, ParsedBundle } from \"./types\";\nimport { authoredRecord, UNKNOWN_DOMAIN } from \"./types\";\n\nfunction enrichPipeConcepts(\n pipe: PipeBlueprintUnion,\n domains: Record<string, DomainNamespace>,\n): PipeBlueprintUnion {\n const enrichSpec = (spec: StuffSpecInfo): StuffSpecInfo => {\n const declared = domains[spec.concept.domain_code]?.concepts[spec.concept.code];\n return declared !== undefined && declared !== spec.concept\n ? { ...spec, concept: declared }\n : spec;\n };\n const inputs = authoredRecord<StuffSpecInfo>();\n for (const [name, spec] of Object.entries(pipe.inputs)) {\n inputs[name] = enrichSpec(spec);\n }\n return { ...pipe, inputs, output: enrichSpec(pipe.output) };\n}\n\n/**\n * Merge parsed bundles into one namespace per domain. Order matters: on\n * duplicate codes the first bundle wins. `mainDomain` and `mainPipe` are taken\n * together from the first bundle declaring `main_pipe`, so a bare entry ref\n * always resolves in its declaring bundle's namespace; when no bundle declares\n * one, `mainDomain` falls back to the first domained bundle. `description`\n * comes from the first bundle that declares it.\n */\nexport function mergeBundles(bundles: ParsedBundle[]): MergedMethodSet {\n const diagnostics: Diagnostic[] = [];\n const domains = authoredRecord<DomainNamespace>();\n let mainDomain: string | null = null;\n let mainPipe: string | null = null;\n let description: string | null = null;\n\n for (const bundle of bundles) {\n const domain = bundle.domain ?? UNKNOWN_DOMAIN;\n const namespace = (domains[domain] ??= {\n domain,\n concepts: authoredRecord<ConceptInfo>(),\n pipes: authoredRecord<PipeBlueprintUnion>(),\n });\n if (mainDomain === null && bundle.domain !== null) mainDomain = bundle.domain;\n if (mainPipe === null && bundle.main_pipe !== null) {\n mainPipe = bundle.main_pipe;\n // A bare main_pipe must resolve in the namespace of the bundle declaring\n // it, not whichever bundle happened to come first.\n mainDomain = domain;\n }\n if (description === null && bundle.description !== null) description = bundle.description;\n\n for (const [code, concept] of Object.entries(bundle.concepts)) {\n if (code in namespace.concepts) {\n diagnostics.push({\n severity: \"warning\",\n code: \"duplicate-concept\",\n message: `concept \"${domain}.${code}\" declared more than once — keeping the first declaration`,\n path: `concept.${code}`,\n domain_code: domain,\n });\n continue;\n }\n namespace.concepts[code] = concept;\n }\n for (const [code, pipe] of Object.entries(bundle.pipes)) {\n const existing = namespace.pipes[code];\n if (existing === undefined) {\n namespace.pipes[code] = pipe;\n continue;\n }\n // A signature is a forward declaration; the concrete pipe of the same code\n // is its definition, not a duplicate of it. Which file each landed in — and\n // therefore which one the merge sees first — is an authoring choice, so the\n // concrete always wins.\n const existingIsSignature = existing.type === \"PipeSignature\";\n const incomingIsSignature = pipe.type === \"PipeSignature\";\n if (existingIsSignature !== incomingIsSignature) {\n const signature = existing.type === \"PipeSignature\" ? existing : pipe;\n const concrete = existing.type === \"PipeSignature\" ? pipe : existing;\n if (existingIsSignature) namespace.pipes[code] = pipe;\n // Silent only when the two halves agree. `signature_for` is the type the\n // forward declaration promised, and it is an optional hint — an absent one\n // has nothing to disagree with. A present one naming a different type means\n // the package did not honour its own contract, and the merge is the only\n // place that ever sees both halves at once. The concrete still wins: it is\n // the implementation, and a renderer's job is to draw what was built.\n const promised =\n signature.type === \"PipeSignature\" ? (signature.signature_for ?? null) : null;\n if (promised !== null && promised !== concrete.type) {\n diagnostics.push({\n severity: \"warning\",\n code: \"signature-type-mismatch\",\n message:\n `pipe \"${domain}.${code}\": the signature promises \\`signature_for = \"${promised}\"\\` ` +\n `but the concrete definition is a ${concrete.type} — using the concrete definition`,\n path: `pipe.${code}`,\n domain_code: domain,\n });\n }\n continue;\n }\n diagnostics.push({\n severity: \"warning\",\n code: \"duplicate-pipe\",\n message: `pipe \"${domain}.${code}\" declared more than once — keeping the first declaration`,\n path: `pipe.${code}`,\n domain_code: domain,\n });\n }\n }\n\n for (const namespace of Object.values(domains)) {\n for (const [code, pipe] of Object.entries(namespace.pipes)) {\n namespace.pipes[code] = enrichPipeConcepts(pipe, domains);\n }\n }\n\n return { domains, mainDomain, mainPipe, description, diagnostics };\n}\n","// ─── Static graph builder: MergedMethodSet → GraphSpec ──────────────────────\n// The static walk from the design doc (wip/static-graph-design.md): walk pipe\n// *invocations* starting at the entry pipe, maintaining a scope (the static\n// mirror of working memory), and emit a GraphSpec with `meta.mode: \"static\"`\n// that the existing GraphViewer renders unchanged.\n//\n// Identity is deterministic: node ids are invocation paths\n// (`screening.process_cv/step_2/...`) and stuff digests are the raw strings\n// `<producer_node_id>:<name>` (external inputs: `input:<name>`). The UI treats\n// digests as opaque unique keys, so the raw string — collision-free by\n// construction and readable in snapshots — is preferred over a hash.\n//\n// Everything is best-effort: unresolvable refs skip the child, cycles render\n// as leaves, dependency-alias refs (`alias->pipe`) render as opaque leaf\n// cards. This module never throws on content.\n\nimport type {\n ConceptInfo,\n GraphSpec,\n GraphSpecEdge,\n GraphSpecEdgeKind,\n GraphSpecNode,\n GraphSpecNodeIoItem,\n PipeBatchBlueprint,\n PipeBlueprintUnion,\n PipeConditionBlueprint,\n PipeParallelBlueprint,\n PipeSequenceBlueprint,\n PipeType,\n StuffMultiplicity,\n StuffSpecInfo,\n SubPipeSpec,\n} from \"@graph/types\";\nimport { isPluralMultiplicity } from \"@graph/types\";\n\nimport { nativeConceptInfo } from \"./conceptRefs\";\nimport { mergeBundles } from \"./mergeBundles\";\nimport { parseMthdsBundle } from \"./parseMthdsBundle\";\nimport type { Diagnostic, DomainNamespace, MergedMethodSet } from \"./types\";\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\nexport interface StaticGraphOptions {\n /**\n * Pipe ref to walk from (`code` or `domain.code`). Defaults to the merged\n * set's `main_pipe`, falling back to a root heuristic (first pipe no other\n * pipe references) when none is declared.\n */\n entryPipe?: string;\n}\n\nexport interface StaticGraphResult {\n spec: GraphSpec;\n diagnostics: Diagnostic[];\n}\n\n/** Build a static GraphSpec from an already-parsed, merged method set. */\nexport function buildStaticGraphSpec(\n set: MergedMethodSet,\n options: StaticGraphOptions = {},\n): StaticGraphResult {\n const diagnostics: Diagnostic[] = [];\n const ctx: WalkCtx = {\n set,\n nodes: [],\n edges: [],\n pipeRegistry: {},\n conceptRegistry: {},\n stuffByDigest: new Map(),\n diagnostics,\n stack: [],\n edgeSeq: 0,\n };\n\n // Registries carry every parsed entry (the dry-run path often ships them\n // empty — populating them is what makes detail panels rich). Registered\n // before the walk so synthetic entries minted during it never clobber a\n // declared one.\n for (const namespace of Object.values(set.domains)) {\n for (const concept of Object.values(namespace.concepts)) registerConcept(ctx, concept);\n for (const pipe of Object.values(namespace.pipes)) {\n ctx.pipeRegistry[`${pipe.domain_code}.${pipe.code}`] = pipe;\n for (const spec of Object.values(pipe.inputs)) registerConcept(ctx, spec.concept);\n registerConcept(ctx, pipe.output.concept);\n }\n }\n\n const entry = pickEntryPipe(set, options.entryPipe ?? null, diagnostics);\n if (entry !== null) {\n walkPipe(ctx, entry.code, entry.domain, `${entry.domain}.${entry.code}`, null, new Map(), {\n resultName: null,\n outputMultiplicity: null,\n });\n }\n\n const spec: GraphSpec = {\n nodes: ctx.nodes,\n edges: ctx.edges,\n meta: { format: \"mthds\", mode: \"static\" },\n pipe_registry: ctx.pipeRegistry,\n concept_registry: ctx.conceptRegistry,\n };\n if (entry !== null) {\n spec.pipeline_ref = { domain: entry.domain, main_pipe: entry.code };\n }\n return { spec, diagnostics };\n}\n\n/**\n * Convenience wrapper: parse one or more `.mthds` TOML strings, merge them,\n * and build the static GraphSpec. Diagnostics from all three stages are\n * concatenated in order (parse, merge, build).\n */\nexport function buildStaticGraphSpecFromToml(\n tomlTexts: string | string[],\n options: StaticGraphOptions = {},\n): StaticGraphResult {\n const texts = Array.isArray(tomlTexts) ? tomlTexts : [tomlTexts];\n const parsed = texts.map((text) => parseMthdsBundle(text));\n const merged = mergeBundles(parsed.map((result) => result.bundle));\n const built = buildStaticGraphSpec(merged, options);\n return {\n spec: built.spec,\n diagnostics: [\n ...parsed.flatMap((result) => result.diagnostics),\n ...merged.diagnostics,\n ...built.diagnostics,\n ],\n };\n}\n\n// ─── Walk state ──────────────────────────────────────────────────────────────\n\n/** A scope entry — the static mirror of a working-memory stuff. */\ninterface StuffRecord {\n digest: string;\n name: string;\n concept: ConceptInfo;\n multiplicity: StuffMultiplicity;\n}\n\ntype Scope = Map<string, StuffRecord>;\n\ninterface WalkCtx {\n set: MergedMethodSet;\n nodes: GraphSpecNode[];\n edges: GraphSpecEdge[];\n pipeRegistry: Record<string, PipeBlueprintUnion>;\n conceptRegistry: Record<string, ConceptInfo>;\n stuffByDigest: Map<string, StuffRecord>;\n diagnostics: Diagnostic[];\n /** Qualified refs (`domain.code`) on the recursion stack — the cycle guard. */\n stack: string[];\n edgeSeq: number;\n}\n\n/** How a pipe is being invoked — the step/branch/outcome context. */\ninterface Invocation {\n /** The enclosing step's `result` name — names the operator's output stuff. */\n resultName: string | null;\n /** The enclosing step's `nb_output`/`multiple_output` override. */\n outputMultiplicity: SubPipeSpec[\"output_multiplicity\"];\n /** Set on condition children: the outcome value that routes here. */\n outcomeValue?: string;\n}\n\ninterface WalkResult {\n nodeId: string;\n /** Primary output stuff — what a sequence step's `result` binds to. */\n output: StuffRecord | null;\n /** Extra bindings a parallel with `add_each_output` exposes to the enclosing scope. */\n eachOutputs: [string, StuffRecord][];\n}\n\n// ─── Entry pipe selection ────────────────────────────────────────────────────\n\ntype PipeResolution =\n | { kind: \"resolved\"; blueprint: PipeBlueprintUnion; domain: string; code: string }\n | { kind: \"opaque\" }\n | { kind: \"unresolved\" };\n\n/**\n * Resolve a pipe ref against the merged set: bare refs in the current domain\n * (same-domain files are already merged into one namespace), `domain.code`\n * refs in the named domain. `alias->…` dependency refs are opaque in phase 1.\n */\nfunction resolvePipeRef(set: MergedMethodSet, ref: string, currentDomain: string): PipeResolution {\n if (ref.includes(\"->\")) return { kind: \"opaque\" };\n const dot = ref.lastIndexOf(\".\");\n const domain = dot === -1 ? currentDomain : ref.slice(0, dot);\n const code = dot === -1 ? ref : ref.slice(dot + 1);\n const blueprint = set.domains[domain]?.pipes[code];\n if (blueprint === undefined) return { kind: \"unresolved\" };\n return { kind: \"resolved\", blueprint, domain, code };\n}\n\n/** Sub-pipe refs appearing anywhere in a namespace — used by the root heuristic. */\nfunction referencedPipeCodes(namespace: DomainNamespace): Set<string> {\n const refs = new Set<string>();\n // Refs are authored strings: bare (`helper`) or qualified (`domain.helper`).\n // Reduce them to bare codes in this namespace, mirroring resolvePipeRef —\n // cross-domain and `alias->` refs can't name a pipe here, so they're dropped.\n const add = (ref: string): void => {\n if (ref === \"\" || ref.includes(\"->\")) return;\n const dot = ref.lastIndexOf(\".\");\n if (dot === -1) refs.add(ref);\n else if (ref.slice(0, dot) === namespace.domain) refs.add(ref.slice(dot + 1));\n };\n for (const pipe of Object.values(namespace.pipes)) {\n switch (pipe.type) {\n case \"PipeSequence\":\n for (const sub of pipe.sequential_sub_pipes) add(sub.pipe_code);\n break;\n case \"PipeParallel\":\n for (const sub of pipe.parallel_sub_pipes) add(sub.pipe_code);\n break;\n case \"PipeCondition\":\n for (const target of Object.values(pipe.outcome_map)) add(target);\n add(pipe.default_outcome);\n break;\n case \"PipeBatch\":\n add(pipe.branch_pipe_code);\n break;\n default:\n break;\n }\n }\n return refs;\n}\n\nfunction pickEntryPipe(\n set: MergedMethodSet,\n explicitRef: string | null,\n diagnostics: Diagnostic[],\n): { domain: string; code: string } | null {\n const domainsInOrder = Object.keys(set.domains);\n const fallbackDomain = set.mainDomain ?? domainsInOrder[0];\n if (fallbackDomain === undefined) {\n diagnostics.push({\n severity: \"error\",\n code: \"no-entry-pipe\",\n message: \"no bundles to build a graph from\",\n });\n return null;\n }\n\n const resolveEntry = (ref: string): { domain: string; code: string } | null => {\n const resolution = resolvePipeRef(set, ref, fallbackDomain);\n return resolution.kind === \"resolved\"\n ? { domain: resolution.domain, code: resolution.code }\n : null;\n };\n\n if (explicitRef !== null) {\n const entry = resolveEntry(explicitRef);\n if (entry === null) {\n diagnostics.push({\n severity: \"error\",\n code: \"unresolved-pipe-ref\",\n message: `entry pipe \"${explicitRef}\" not found in the method set`,\n });\n }\n return entry;\n }\n\n if (set.mainPipe !== null) {\n const entry = resolveEntry(set.mainPipe);\n if (entry !== null) return entry;\n diagnostics.push({\n severity: \"warning\",\n code: \"unresolved-pipe-ref\",\n message: `main_pipe \"${set.mainPipe}\" not found — falling back to a root heuristic`,\n // The owning bundle is known (the namespace that declares this main_pipe),\n // so stamp it — this is not an ownerless diagnostic.\n domain_code: fallbackDomain,\n });\n } else {\n diagnostics.push({\n severity: \"warning\",\n code: \"missing-main-pipe\",\n message: \"no main_pipe declared — falling back to a root heuristic\",\n domain_code: fallbackDomain,\n });\n }\n\n // Root heuristic: the first pipe (declaration order) that no other pipe in\n // its domain references; else the first pipe. Keeps half-written bundles\n // rendering something sensible.\n const domainWithPipes = [fallbackDomain, ...domainsInOrder].find(\n (domain) => Object.keys(set.domains[domain]?.pipes ?? {}).length > 0,\n );\n if (domainWithPipes === undefined) {\n diagnostics.push({\n severity: \"error\",\n code: \"no-entry-pipe\",\n message: \"no pipes found in any bundle\",\n });\n return null;\n }\n const namespace = set.domains[domainWithPipes];\n const referenced = referencedPipeCodes(namespace);\n const codes = Object.keys(namespace.pipes);\n const root = codes.find((code) => !referenced.has(code)) ?? codes[0];\n return { domain: domainWithPipes, code: root };\n}\n\n// ─── Small helpers ───────────────────────────────────────────────────────────\n\n/** `CamelCase` concept code → `snake_case` stuff name (the runtime's fallback naming). */\nfunction snakeCase(code: string): string {\n return code\n .replace(/([A-Z]+)([A-Z][a-z0-9])/g, \"$1_$2\")\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .toLowerCase();\n}\n\nfunction registerConcept(ctx: WalkCtx, concept: ConceptInfo): void {\n ctx.conceptRegistry[`${concept.domain_code}.${concept.code}`] ??= concept;\n}\n\n/**\n * Mint (or return the already-minted) stuff for a digest. First mint wins —\n * matching how the UI's stuff registry keeps the first occurrence per digest.\n */\nfunction mintStuff(\n ctx: WalkCtx,\n digest: string,\n name: string,\n concept: ConceptInfo,\n multiplicity: StuffSpecInfo[\"multiplicity\"],\n): StuffRecord {\n const existing = ctx.stuffByDigest.get(digest);\n if (existing !== undefined) return existing;\n const record: StuffRecord = { digest, name, concept, multiplicity: multiplicity ?? null };\n ctx.stuffByDigest.set(digest, record);\n registerConcept(ctx, concept);\n return record;\n}\n\n/**\n * An io item for `stuff`, optionally exposed under a *slot name* — the name\n * the invoking step binds it to (`result = \"x\"`). The runtime names a\n * controller's transparent output by its slot, while the producing operator\n * keeps the local name; the UI's stuff registry is first-occurrence-wins and\n * controllers are emitted before their children, so the slot name is what\n * renders (verified against the dry fixtures).\n */\nfunction ioItem(stuff: StuffRecord, slotName?: string | null): GraphSpecNodeIoItem {\n const item: GraphSpecNodeIoItem = {\n name: slotName ?? stuff.name,\n digest: stuff.digest,\n concept: stuff.concept.code,\n };\n // Carried only on a plural stuff, so a single-valued io item stays exactly as it was.\n if (isPluralMultiplicity(stuff.multiplicity)) item.multiplicity = stuff.multiplicity;\n return item;\n}\n\nfunction addEdge(\n ctx: WalkCtx,\n kind: GraphSpecEdgeKind,\n source: string,\n target: string,\n extras?: { label?: string; sourceStuff?: string; targetStuff?: string },\n): void {\n // Namespaced ids: the rendering pipeline synthesizes its own dataflow edges\n // named `edge_<n>` (graphBuilders.ts), so bare `edge_<n>` here would collide\n // in the ReactFlow key space.\n const edge: GraphSpecEdge = { id: `static:edge_${ctx.edgeSeq++}`, source, target, kind };\n if (extras?.label !== undefined) edge.label = extras.label;\n if (extras?.sourceStuff !== undefined) edge.source_stuff_digest = extras.sourceStuff;\n if (extras?.targetStuff !== undefined) edge.target_stuff_digest = extras.targetStuff;\n ctx.edges.push(edge);\n}\n\nfunction addNodeTag(node: GraphSpecNode, key: string, value: string): void {\n node.tags = { ...(node.tags ?? {}), [key]: value };\n}\n\nfunction formatBatchMultiplicity(multiplicity: number | boolean | null | undefined): string {\n if (typeof multiplicity === \"number\") return `x${multiplicity}`;\n if (multiplicity === true) return \"xmany\";\n return \"x?\";\n}\n\n/**\n * Working-memory name matching: exact name first, then dotted-prefix — an\n * input `a.b` is satisfied by a binding for `a`.\n */\nfunction lookupScope(scope: Scope, name: string): StuffRecord | undefined {\n let candidate = name;\n for (;;) {\n const found = scope.get(candidate);\n if (found !== undefined) return found;\n const dot = candidate.lastIndexOf(\".\");\n if (dot <= 0) return undefined;\n candidate = candidate.slice(0, dot);\n }\n}\n\nfunction conceptKey(concept: ConceptInfo): string {\n return `${concept.domain_code}.${concept.code}`;\n}\n\n/**\n * Bind the invoked pipe's declared inputs from the caller's scope. A name the\n * scope cannot satisfy is a *dangling* input: mint an input stuff\n * (`input:<name>`) with the declared concept — at the method root these are\n * exactly the method's external inputs, and the UI classifies producer-less\n * stuff as role `input`. The `input:` digest namespace is method-global on\n * purpose: an unbound name means the same missing working-memory entry\n * wherever it is read, so all its consumers share one stuff. When two\n * consumers declare *different* concepts for that shared name, the first\n * mint wins and a diagnostic surfaces the authoring inconsistency.\n *\n * Minted dangling inputs are written into `scope`: working memory is one flat\n * namespace shared down the walk (see the scope model note on `walkPipe`), so\n * later readers of the same name bind the same record.\n */\nfunction bindInputs(\n ctx: WalkCtx,\n blueprint: PipeBlueprintUnion,\n scope: Scope,\n): GraphSpecNodeIoItem[] {\n const ioInputs: GraphSpecNodeIoItem[] = [];\n for (const [name, spec] of Object.entries(blueprint.inputs)) {\n let bound = lookupScope(scope, name);\n if (bound === undefined) {\n bound = mintStuff(ctx, `input:${name}`, name, spec.concept, spec.multiplicity);\n scope.set(name, bound);\n if (conceptKey(bound.concept) !== conceptKey(spec.concept)) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"conflicting-input-concept\",\n message:\n `pipe \"${blueprint.code}\": dangling input \"${name}\" is declared as ` +\n `${conceptKey(spec.concept)} here but was first seen as ` +\n `${conceptKey(bound.concept)} — keeping the first`,\n path: `pipe.${blueprint.code}.inputs.${name}`,\n domain_code: blueprint.domain_code,\n });\n }\n }\n ioInputs.push(ioItem(bound));\n }\n return ioInputs;\n}\n\nfunction emitNode(\n ctx: WalkCtx,\n args: {\n id: string;\n kind: \"controller\" | \"operator\";\n pipeCode: string;\n pipeType: PipeType;\n description: string;\n domainCode: string;\n ioInputs: GraphSpecNodeIoItem[];\n parentId: string | null;\n inv: Invocation;\n },\n): GraphSpecNode {\n const node: GraphSpecNode = {\n id: args.id,\n kind: args.kind,\n pipe_code: args.pipeCode,\n pipe_type: args.pipeType,\n // validateGraphSpec requires a non-empty description; WIP pipes may lack one.\n description: args.description.length > 0 ? args.description : args.pipeCode,\n domain_code: args.domainCode,\n status: \"scheduled\",\n io: { inputs: args.ioInputs, outputs: [] },\n };\n if (args.inv.outcomeValue !== undefined) node.tags = { outcome: args.inv.outcomeValue };\n ctx.nodes.push(node);\n if (args.parentId !== null) {\n addEdge(\n ctx,\n \"contains\",\n args.parentId,\n args.id,\n args.inv.outcomeValue !== undefined ? { label: args.inv.outcomeValue } : undefined,\n );\n }\n return node;\n}\n\n// ─── The walk ────────────────────────────────────────────────────────────────\n\n/**\n * Walk one pipe *invocation*: resolve the ref, emit the node (and its\n * `contains` edge), bind inputs from the caller's scope, recurse per\n * controller type, and report the invocation's output stuff.\n *\n * Scope model — the static mirror of the runtime's working memory, which is\n * ONE flat namespace shared across the whole run (verified against the dry\n * fixtures: a result produced inside a nested sub-sequence is consumed by a\n * later step of an ancestor sequence). So: sequence steps see and mutate the\n * caller's scope *object*; parallel/batch branches and condition outcome\n * children each get a *copy* — branches because the runtime forks memory per\n * branch and merges back only the declared outputs, condition outcomes\n * because they are mutually exclusive alternatives (only one runs, so no\n * branch's writes may be visible to its siblings or, beyond the condition's\n * representative output, to the caller).\n */\nfunction walkPipe(\n ctx: WalkCtx,\n ref: string,\n currentDomain: string,\n nodeId: string,\n parentId: string | null,\n scope: Scope,\n inv: Invocation,\n): WalkResult | null {\n const resolution = resolvePipeRef(ctx.set, ref, currentDomain);\n if (resolution.kind === \"unresolved\") {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"unresolved-pipe-ref\",\n message: `pipe ref \"${ref}\" cannot be resolved — node skipped`,\n path: nodeId,\n // The uttering file's domain: a bare ref belongs to the namespace that\n // wrote it, mirroring the runtime's `_qualify_pipe_ref` inference.\n domain_code: currentDomain,\n });\n return null;\n }\n if (resolution.kind === \"opaque\") {\n return emitOpaqueLeaf(ctx, ref, currentDomain, nodeId, parentId, inv);\n }\n\n const { blueprint, domain, code } = resolution;\n const qualified = `${domain}.${code}`;\n const ioInputs = bindInputs(ctx, blueprint, scope);\n const node = emitNode(ctx, {\n id: nodeId,\n kind: blueprint.pipe_category === \"PipeController\" ? \"controller\" : \"operator\",\n pipeCode: code,\n pipeType: blueprint.type,\n description: blueprint.description,\n domainCode: blueprint.domain_code,\n ioInputs,\n parentId,\n inv,\n });\n\n if (ctx.stack.includes(qualified)) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"cyclic-pipe-ref\",\n message: `pipe \"${qualified}\" is invoked recursively — rendered as a leaf`,\n path: nodeId,\n domain_code: domain,\n });\n return finishLeaf(ctx, node, blueprint, nodeId, inv);\n }\n\n ctx.stack.push(qualified);\n try {\n switch (blueprint.type) {\n case \"PipeSequence\":\n return finishSequence(ctx, node, blueprint, nodeId, scope, inv);\n case \"PipeParallel\":\n return finishParallel(ctx, node, blueprint, nodeId, scope, inv);\n case \"PipeCondition\":\n return finishCondition(ctx, node, blueprint, nodeId, scope, inv);\n case \"PipeBatch\":\n return finishBatch(ctx, node, blueprint, nodeId, scope, inv);\n default:\n return finishLeaf(ctx, node, blueprint, nodeId, inv);\n }\n } finally {\n ctx.stack.pop();\n }\n}\n\n/**\n * A step (or branch) invocation: a step carrying inline `batch_over`/`batch_as`\n * becomes a synthetic PipeBatch node wrapping the invoked pipe — mirroring the\n * runtime, which materializes `<pipe>_batch` controllers for inline batching.\n */\nfunction walkSubPipe(\n ctx: WalkCtx,\n sub: SubPipeSpec,\n domain: string,\n nodeId: string,\n parentId: string,\n scope: Scope,\n inheritedMultiplicity: Invocation[\"outputMultiplicity\"] = null,\n): WalkResult | null {\n if (sub.batch_params != null) {\n return walkInlineBatch(ctx, sub, domain, nodeId, parentId, scope);\n }\n return walkPipe(ctx, sub.pipe_code, domain, nodeId, parentId, scope, {\n resultName: sub.output_name ?? null,\n // A step with no `nb_output`/`multiple_output` of its own runs under the one\n // its controller was invoked with, as the runtime copies the run params down.\n outputMultiplicity: sub.output_multiplicity ?? inheritedMultiplicity,\n });\n}\n\n// ─── Leaf (operators, signatures, cyclic refs) ───────────────────────────────\n\nfunction finishLeaf(\n ctx: WalkCtx,\n node: GraphSpecNode,\n blueprint: PipeBlueprintUnion,\n nodeId: string,\n inv: Invocation,\n): WalkResult {\n const name = inv.resultName ?? snakeCase(blueprint.output.concept.code);\n const multiplicity =\n typeof inv.outputMultiplicity === \"number\" || inv.outputMultiplicity === true\n ? inv.outputMultiplicity\n : blueprint.output.multiplicity;\n const output = mintStuff(ctx, `${nodeId}:${name}`, name, blueprint.output.concept, multiplicity);\n node.io.outputs = [ioItem(output)];\n return { nodeId, output, eachOutputs: [] };\n}\n\n/** Phase-1 policy for `alias->…` dependency refs: an opaque leaf card. */\nfunction emitOpaqueLeaf(\n ctx: WalkCtx,\n ref: string,\n currentDomain: string,\n nodeId: string,\n parentId: string | null,\n inv: Invocation,\n): WalkResult {\n const alias = ref.slice(0, ref.indexOf(\"->\"));\n const tail = ref.slice(ref.lastIndexOf(\"->\") + 2);\n const codeTail = tail.slice(tail.lastIndexOf(\".\") + 1);\n const node = emitNode(ctx, {\n id: nodeId,\n kind: \"operator\",\n pipeCode: codeTail.length > 0 ? codeTail : ref,\n pipeType: \"PipeSignature\",\n description: `External pipe from dependency \"${alias}\"`,\n domainCode: alias.length > 0 ? alias : currentDomain,\n ioInputs: [],\n parentId,\n inv,\n });\n const name = inv.resultName ?? \"output\";\n const output = mintStuff(ctx, `${nodeId}:${name}`, name, nativeConceptInfo(\"Anything\"), null);\n node.io.outputs = [ioItem(output)];\n return { nodeId, output, eachOutputs: [] };\n}\n\n// ─── Controllers ─────────────────────────────────────────────────────────────\n\nfunction finishSequence(\n ctx: WalkCtx,\n node: GraphSpecNode,\n blueprint: PipeSequenceBlueprint,\n nodeId: string,\n scope: Scope,\n inv: Invocation,\n): WalkResult {\n let lastOutput: StuffRecord | null = null;\n blueprint.sequential_sub_pipes.forEach((sub, index) => {\n const result = walkSubPipe(\n ctx,\n sub,\n blueprint.domain_code,\n `${nodeId}/step_${index + 1}`,\n nodeId,\n scope,\n inv.outputMultiplicity,\n );\n if (result === null) return;\n if (result.output !== null) {\n if (sub.output_name != null) scope.set(sub.output_name, result.output);\n lastOutput = result.output;\n }\n for (const [name, stuff] of result.eachOutputs) scope.set(name, stuff);\n });\n // Controller transparency: the sequence's output IS its last producing\n // step's stuff — same digest, so downstream consumers wire to the real\n // producer (the UI only takes producers from non-controller nodes).\n node.io.outputs = lastOutput === null ? [] : [ioItem(lastOutput, inv.resultName)];\n return { nodeId, output: lastOutput, eachOutputs: [] };\n}\n\nfunction finishParallel(\n ctx: WalkCtx,\n node: GraphSpecNode,\n blueprint: PipeParallelBlueprint,\n nodeId: string,\n scope: Scope,\n inv: Invocation,\n): WalkResult {\n const branchResults: { sub: SubPipeSpec; result: WalkResult }[] = [];\n blueprint.parallel_sub_pipes.forEach((sub, index) => {\n // Branches are independent: each gets its own copy of the inherited scope.\n const result = walkSubPipe(\n ctx,\n sub,\n blueprint.domain_code,\n `${nodeId}/branch_${index + 1}`,\n nodeId,\n new Map(scope),\n );\n if (result !== null) branchResults.push({ sub, result });\n });\n\n const eachOutputs: [string, StuffRecord][] = [];\n if (blueprint.add_each_output) {\n for (const { sub, result } of branchResults) {\n if (sub.output_name != null && result.output !== null) {\n eachOutputs.push([sub.output_name, result.output]);\n }\n }\n }\n\n const combinedName =\n blueprint.combined_output ?? inv.resultName ?? snakeCase(blueprint.output.concept.code);\n const combined = mintStuff(\n ctx,\n `${nodeId}:${combinedName}`,\n combinedName,\n blueprint.output.concept,\n blueprint.output.multiplicity,\n );\n for (const { result } of branchResults) {\n if (result.output !== null) {\n addEdge(ctx, \"parallel_combine\", result.nodeId, nodeId, {\n sourceStuff: result.output.digest,\n targetStuff: combined.digest,\n });\n }\n }\n node.io.outputs = [ioItem(combined, inv.resultName)];\n return { nodeId, output: combined, eachOutputs };\n}\n\nfunction finishCondition(\n ctx: WalkCtx,\n node: GraphSpecNode,\n blueprint: PipeConditionBlueprint,\n nodeId: string,\n scope: Scope,\n inv: Invocation,\n): WalkResult {\n const conditionScope: Scope = new Map(scope);\n if (blueprint.add_alias_from_expression_to != null) {\n const alias = blueprint.add_alias_from_expression_to;\n // The alias points at whatever the expression evaluates to at run time —\n // statically typed as native.Dynamic.\n conditionScope.set(\n alias,\n mintStuff(ctx, `${nodeId}:${alias}`, alias, nativeConceptInfo(\"Dynamic\"), null),\n );\n }\n\n // One child node per distinct *target pipe*, not per outcome value —\n // mirroring the runtime tracer. Outcomes routing to the same pipe (often\n // one value plus `default_outcome`) merge into a single child carrying all\n // its routing values. `fail` / `continue` are outcome actions, not refs.\n // The default route is tracked as a flag, never as a value string — an\n // *authored* outcome value literally named \"default\" must not collide with\n // the synthetic default sentinel (node ids and primary selection key on it).\n interface RouteEntry {\n values: string[];\n ref: string;\n viaDefault: boolean;\n }\n const targets: RouteEntry[] = [];\n const byRef = new Map<string, RouteEntry>();\n const addRoute = (value: string, ref: string, isDefault: boolean): void => {\n if (ref === \"\" || ref === \"fail\" || ref === \"continue\") return;\n const existing = byRef.get(ref);\n if (existing !== undefined) {\n existing.values.push(value);\n existing.viaDefault ||= isDefault;\n return;\n }\n const entry = { values: [value], ref, viaDefault: isDefault };\n byRef.set(ref, entry);\n targets.push(entry);\n };\n for (const [value, target] of Object.entries(blueprint.outcome_map)) {\n addRoute(value, target, false);\n }\n addRoute(\"default\", blueprint.default_outcome, true);\n\n const results: { entry: RouteEntry; result: WalkResult }[] = [];\n for (const entry of targets) {\n const idSegment =\n entry.viaDefault && entry.values.length === 1 ? \"default\" : `outcome_${entry.values[0]}`;\n const result = walkPipe(\n ctx,\n entry.ref,\n blueprint.domain_code,\n `${nodeId}/${idSegment}`,\n nodeId,\n new Map(conditionScope),\n {\n // The runtime stores whichever branch runs under the condition's own\n // slot name, so every branch's output carries it (dry-run parity).\n resultName: inv.resultName,\n // The chosen outcome runs under the condition's own run params, its\n // invocation's `nb_output`/`multiple_output` included.\n outputMultiplicity: inv.outputMultiplicity,\n outcomeValue: entry.values.join(\" | \"),\n },\n );\n if (result !== null) results.push({ entry, result });\n }\n\n // Statically all outcomes exist; pick one representative output for the\n // controller (the default route when present, else the first producing\n // outcome) so downstream consumers wire to a real producer.\n const primary =\n results.find(({ entry, result }) => entry.viaDefault && result.output !== null)?.result\n .output ??\n results.find(({ result }) => result.output !== null)?.result.output ??\n null;\n node.io.outputs = primary === null ? [] : [ioItem(primary, inv.resultName)];\n return { nodeId, output: primary, eachOutputs: [] };\n}\n\nfunction finishBatch(\n ctx: WalkCtx,\n node: GraphSpecNode,\n blueprint: PipeBatchBlueprint,\n nodeId: string,\n scope: Scope,\n inv: Invocation,\n): WalkResult {\n const params = blueprint.batch_params;\n\n let listStuff: StuffRecord | null = null;\n if (params.input_list_stuff_name !== \"\") {\n const bound = lookupScope(scope, params.input_list_stuff_name);\n if (bound !== undefined) {\n listStuff = bound;\n } else {\n // The list name is not among the declared inputs (sloppy but legal WIP\n // state): mint it as a dangling input and surface it on the node's io.\n listStuff = mintStuff(\n ctx,\n `input:${params.input_list_stuff_name}`,\n params.input_list_stuff_name,\n nativeConceptInfo(\"Anything\"),\n true,\n );\n node.io.inputs.push(ioItem(listStuff));\n }\n }\n\n let itemStuff: StuffRecord | null = null;\n const branchScope: Scope = new Map(scope);\n if (params.input_item_stuff_name !== \"\" && listStuff !== null) {\n // The item is one element of the list: same concept, single multiplicity.\n itemStuff = mintStuff(\n ctx,\n `${nodeId}:${params.input_item_stuff_name}`,\n params.input_item_stuff_name,\n listStuff.concept,\n null,\n );\n branchScope.set(params.input_item_stuff_name, itemStuff);\n }\n\n const batchMultiplicity = formatBatchMultiplicity(listStuff?.multiplicity);\n addNodeTag(node, \"batch_multiplicity\", batchMultiplicity);\n\n // One representative branch, not N — this is a method view, not a run trace.\n let branchResult: WalkResult | null = null;\n if (blueprint.branch_pipe_code !== \"\") {\n branchResult = walkPipe(\n ctx,\n blueprint.branch_pipe_code,\n blueprint.domain_code,\n `${nodeId}/batch_branch`,\n nodeId,\n branchScope,\n { resultName: null, outputMultiplicity: null },\n );\n const branchNode = ctx.nodes.find((candidate) => candidate.id === branchResult?.nodeId);\n if (branchNode !== undefined) {\n addNodeTag(branchNode, \"batch_multiplicity\", batchMultiplicity);\n }\n }\n\n const aggConcept = branchResult?.output?.concept ?? blueprint.output.concept;\n const aggName = inv.resultName ?? snakeCase(aggConcept.code);\n const aggregate = mintStuff(ctx, `${nodeId}:${aggName}`, aggName, aggConcept, true);\n\n if (branchResult !== null && listStuff !== null && itemStuff !== null) {\n addEdge(ctx, \"batch_item\", nodeId, branchResult.nodeId, {\n sourceStuff: listStuff.digest,\n targetStuff: itemStuff.digest,\n });\n }\n if (branchResult?.output != null) {\n addEdge(ctx, \"batch_aggregate\", branchResult.nodeId, nodeId, {\n sourceStuff: branchResult.output.digest,\n targetStuff: aggregate.digest,\n });\n }\n\n node.io.outputs = [ioItem(aggregate)];\n return { nodeId, output: aggregate, eachOutputs: [] };\n}\n\n/** Synthesize the PipeBatch node the runtime materializes for an inline `batch_over` step. */\nfunction walkInlineBatch(\n ctx: WalkCtx,\n sub: SubPipeSpec,\n domain: string,\n nodeId: string,\n parentId: string,\n scope: Scope,\n): WalkResult {\n const params = sub.batch_params as NonNullable<SubPipeSpec[\"batch_params\"]>;\n // Bare code of the branch ref: strip a dependency alias (`helpers->clean`)\n // and a domain qualifier (`lib.clean`) so the synthetic code reads cleanly.\n const aliasIdx = sub.pipe_code.lastIndexOf(\"->\");\n const refTail = aliasIdx === -1 ? sub.pipe_code : sub.pipe_code.slice(aliasIdx + 2);\n const branchTail = refTail.slice(refTail.lastIndexOf(\".\") + 1);\n const branchResolution = resolvePipeRef(ctx.set, sub.pipe_code, domain);\n const branchBlueprint = branchResolution.kind === \"resolved\" ? branchResolution.blueprint : null;\n\n const listBinding = lookupScope(scope, params.input_list_stuff_name);\n const listConcept =\n listBinding?.concept ??\n branchBlueprint?.inputs[params.input_item_stuff_name]?.concept ??\n nativeConceptInfo(\"Anything\");\n const outputSpec = branchBlueprint?.output ?? {\n concept: nativeConceptInfo(\"Anything\"),\n multiplicity: null,\n };\n\n // Registry key: the detail panel resolves blueprints by `domain.pipe_code`,\n // so every distinct inline batch needs its own entry. Reuse the code only\n // when it already points at this exact batch (same branch, same params);\n // otherwise disambiguate with a numeric suffix (`x_batch`, `x_batch_2`, …).\n const baseCode = `${branchTail}_batch`;\n let code = baseCode;\n for (let suffix = 2; ; suffix++) {\n const existing = ctx.pipeRegistry[`${domain}.${code}`];\n if (\n existing === undefined ||\n (existing.type === \"PipeBatch\" &&\n existing.branch_pipe_code === sub.pipe_code &&\n existing.batch_params.input_list_stuff_name === params.input_list_stuff_name &&\n existing.batch_params.input_item_stuff_name === params.input_item_stuff_name)\n ) {\n break;\n }\n code = `${baseCode}_${suffix}`;\n }\n const blueprint: PipeBatchBlueprint = {\n type: \"PipeBatch\",\n pipe_category: \"PipeController\",\n code,\n domain_code: domain,\n description: `Batch processing for ${branchTail}`,\n inputs: {\n [params.input_list_stuff_name]: {\n concept: listConcept,\n multiplicity: null,\n presence: \"plain\",\n },\n },\n output: { concept: outputSpec.concept, multiplicity: null, presence: \"plain\" },\n branch_pipe_code: sub.pipe_code,\n batch_params: params,\n };\n ctx.pipeRegistry[`${domain}.${code}`] ??= blueprint;\n\n const ioInputs = bindInputs(ctx, blueprint, scope);\n const inv: Invocation = {\n resultName: sub.output_name ?? null,\n outputMultiplicity: sub.output_multiplicity,\n };\n const node = emitNode(ctx, {\n id: nodeId,\n kind: \"controller\",\n pipeCode: code,\n pipeType: \"PipeBatch\",\n description: blueprint.description,\n domainCode: domain,\n ioInputs,\n parentId,\n inv,\n });\n return finishBatch(ctx, node, blueprint, nodeId, scope, inv);\n}\n","// Bridge from static-analysis diagnostics to the viewer's validation panel.\n\nimport type { ValidationIssue } from \"@graph/types\";\nimport { makePipeRef } from \"@graph/pipeRefs\";\nimport type { Diagnostic } from \"./types\";\n\n/**\n * Derive the viewer targeting fields from a diagnostic's TOML-style `path`\n * plus its declaring-namespace `domain_code`.\n *\n * - A walk-phase path is a GraphSpec node id and contains `/` (e.g.\n * `demo.main_flow/step_2`) → `nodeId`. Checked first: node ids embed the\n * domain, so a prefix test alone could misread them.\n * - A declaration path `pipe.<code>[...]` qualified by the diagnostic's\n * `domain_code` → `pipeRef` (`domain_code.pipe_code`). A diagnostic without\n * `domain_code` cannot be qualified and stays panel-only — decorating on a\n * bare code would ring every same-code node across domains.\n * - Everything else (concept paths, bare section paths like `pipe`, root\n * entry-pipe ids without `/`, missing paths) has no graph target — those\n * issues stay panel-only.\n */\nfunction targetFromPath(\n path: string | undefined,\n domainCode: string | undefined,\n): Pick<ValidationIssue, \"pipeRef\" | \"nodeId\"> {\n if (!path) return {};\n if (path.includes(\"/\")) return { nodeId: path };\n if (path.startsWith(\"pipe.\")) {\n const code = path.split(\".\")[1];\n if (code && domainCode) return { pipeRef: makePipeRef(domainCode, code) };\n }\n return {};\n}\n\n/**\n * Project static-graph {@link Diagnostic}s onto the viewer's presentation shape\n * so a host can feed them straight into `GraphViewer`'s `validationIssues`.\n * The TOML-style `path` becomes the locator chip; `origin: \"static\"` lets the\n * panel (and the host's issue policy) distinguish them from validator verdicts.\n * When the path identifies a pipe declaration or a precise invocation, the\n * targeting fields (`pipeRef` / `nodeId`) are filled so the viewer can\n * decorate the affected graph nodes.\n */\nexport function staticDiagnosticsToValidationIssues(diagnostics: Diagnostic[]): ValidationIssue[] {\n return diagnostics.map((diagnostic) => ({\n severity: diagnostic.severity,\n message: diagnostic.message,\n context: diagnostic.path,\n origin: \"static\",\n ...targetFromPath(diagnostic.path, diagnostic.domain_code),\n }));\n}\n","// ─── Which file of a method leads ────────────────────────────────────────────\n// A method spread over several `.mthds` files is merged in order, and the order\n// decides which bundle's `main_pipe`, `description` and fallback domain the\n// merged set adopts, and which declaration a genuine clash keeps (see\n// `mergeBundles`). Every host that holds a method as a list of files therefore\n// needs the same answer to \"which one leads\", and this module is that answer,\n// shared so no host keeps a private copy that drifts.\n\n/**\n * One `.mthds` file of a method: the name it goes by and its TOML text. The\n * same shape as an `mthds_sources[]` entry on the hosted API, so a host holding\n * one can pass it straight through.\n */\nexport interface MthdsSource {\n /**\n * File name, or a path ending in one. The whole string is the file's\n * identity: a `preferred` file is matched against it exactly, and an embed\n * lists each name once. Only the `bundle.mthds` tie-break reads the last\n * segment alone.\n */\n name: string;\n /** The file's `.mthds` TOML text. */\n content: string;\n}\n\n/** The file name that breaks a tie when several files declare `main_pipe`. */\nexport const DEFAULT_BUNDLE_FILE_NAME = \"bundle.mthds\";\n\nconst MAIN_PIPE_LINE = /^\\s*main_pipe\\s*=\\s*([\"'])[^\"']+\\1\\s*(?:#.*)?$/;\nconst TABLE_HEADER_LINE = /^\\s*\\[/;\n\n/**\n * Whether a file declares `main_pipe` at the top level, before its first table.\n *\n * A line scan rather than a TOML parse, on purpose: an editor asks this about\n * a file the author is in the middle of writing, and a syntax error further\n * down must not demote the file that plainly declares the entry point. The\n * scan stops at the first table header, because a `main_pipe` key inside a\n * table is not the bundle's.\n */\nexport function hasTopLevelMainPipe(content: string): boolean {\n for (const line of content.split(/\\r\\n|\\r|\\n/)) {\n if (TABLE_HEADER_LINE.test(line)) return false;\n if (MAIN_PIPE_LINE.test(line)) return true;\n }\n return false;\n}\n\nfunction isDefaultBundle(source: MthdsSource): boolean {\n const baseName = source.name.replace(/^.*[\\\\/]/, \"\");\n return baseName.toLowerCase() === DEFAULT_BUNDLE_FILE_NAME;\n}\n\n/**\n * The file a method's graph is anchored on.\n *\n * `preferred` is the file the host is looking at, such as the one open in an\n * editor; it leads whenever it declares `main_pipe` itself. Otherwise the file\n * declaring a top-level `main_pipe` leads, `bundle.mthds` when several do and\n * the first of them in the given order when none is named so. When no file\n * declares one, `preferred` leads, or else the first file. Returns `undefined`\n * only for an empty list.\n *\n * `preferred` is matched against `sources` by `name`, and the listed entry is\n * what is read and returned, so a host may pass its own object for the open\n * file rather than the list's: the result is always a member of `sources`,\n * because the merge reads the list and not `preferred`. That is also why\n * `preferred` is a plain `MthdsSource`: it cannot narrow the result's type and\n * strip the fields a host's own list entries carry. A `preferred` whose\n * name is not listed is ignored: it cannot lead a list it is not in, and the\n * answer is then the one given no `preferred` at all.\n */\nexport function selectPrimaryMthdsSource<T extends MthdsSource>(\n sources: readonly T[],\n preferred?: MthdsSource,\n): T | undefined {\n const listed =\n preferred === undefined ? undefined : sources.find((source) => source.name === preferred.name);\n if (listed !== undefined && hasTopLevelMainPipe(listed.content)) return listed;\n const withMainPipe = sources.filter((source) => hasTopLevelMainPipe(source.content));\n return withMainPipe.find(isDefaultBundle) ?? withMainPipe[0] ?? listed ?? sources[0];\n}\n\n/**\n * The files in the order the static builder should merge them: the primary\n * file (see {@link selectPrimaryMthdsSource}, which also says how `preferred`\n * is matched) first, then the rest in the order given. The rest keep their\n * order so a host that wants a deterministic merge only has to list its files\n * deterministically. Returns a new array.\n */\nexport function orderMthdsSources<T extends MthdsSource>(\n sources: readonly T[],\n preferred?: MthdsSource,\n): T[] {\n const primary = selectPrimaryMthdsSource(sources, preferred);\n const index = primary === undefined ? -1 : sources.indexOf(primary);\n if (index <= 0) return [...sources];\n return [sources[index], ...sources.slice(0, index), ...sources.slice(index + 1)];\n}\n","// ─── The `mthds-sources` embed ───────────────────────────────────────────────\n// A page carries a method's `.mthds` files as JSON in\n// `<script type=\"application/json\" id=\"mthds-sources\">`, and the standalone\n// viewer bundle draws the method from them. Both halves of that contract live\n// here, the check the bundle runs on what it reads and the serializer a host\n// writes the element with, so the writer and the reader cannot drift apart.\n// The contract itself is in `docs/static-graph.md`.\n\nimport type { MthdsSource } from \"./sourceOrder\";\n\n/** The id of the `<script type=\"application/json\">` element carrying the files. */\nexport const MTHDS_SOURCES_EMBED_ID = \"mthds-sources\";\n\nfunction describeEntry(index: number): string {\n return `<script id=\"${MTHDS_SOURCES_EMBED_ID}\"> entry ${index}`;\n}\n\n/**\n * Check a parsed `mthds-sources` value against the embed contract: a non-empty\n * array of `{ \"name\": string, \"content\": string }`, names non-empty and\n * distinct. Returns the entries with only those two keys. Throws with the\n * offending entry named, so a page written wrong says so on the error screen\n * instead of drawing a partial method.\n */\nexport function parseMthdsSourcesEmbed(raw: unknown): MthdsSource[] {\n if (!Array.isArray(raw)) {\n throw new Error(\n `<script id=\"${MTHDS_SOURCES_EMBED_ID}\"> must hold a JSON array of ` +\n `{ \"name\", \"content\" } objects, one per .mthds file.`,\n );\n }\n if (raw.length === 0) {\n throw new Error(`<script id=\"${MTHDS_SOURCES_EMBED_ID}\"> lists no .mthds file.`);\n }\n const seen = new Set<string>();\n return raw.map((entry: unknown, index) => {\n if (entry === null || typeof entry !== \"object\" || Array.isArray(entry)) {\n throw new Error(`${describeEntry(index)} is not a { \"name\", \"content\" } object.`);\n }\n const { name, content } = entry as Record<string, unknown>;\n if (typeof name !== \"string\" || name.trim() === \"\") {\n throw new Error(`${describeEntry(index)} has no \"name\" string.`);\n }\n if (typeof content !== \"string\") {\n throw new Error(`${describeEntry(index)} (\"${name}\") has no \"content\" string.`);\n }\n if (seen.has(name)) {\n throw new Error(`${describeEntry(index)} repeats the name \"${name}\".`);\n }\n seen.add(name);\n return { name, content };\n });\n}\n\n/**\n * The text a host places inside `<script type=\"application/json\"\n * id=\"mthds-sources\">`: the files as a JSON array of `{ name, content }`,\n * checked against the embed contract, with every `<` written as `\\u003c`.\n *\n * The escape is what makes the text safe inside the element. `JSON.parse`\n * reads it back as `<`, while the HTML parser never meets one, so no method\n * text can end the element early, whichever spelling of `</script` it uses, or\n * switch the element into the states a `<!--` opens. A prompt quoting a line of\n * HTML is enough to need it. Neither `JSON.stringify` nor any platform API has\n * an HTML-safe mode, which is why this function exists.\n *\n * Only `name` and `content` are written, whatever else a host's objects carry,\n * and the files keep the order given, because the bundle puts them in merge\n * order itself. Throws on a list the bundle would refuse, naming the entry at\n * fault.\n */\nexport function serializeMthdsSourcesEmbed(sources: readonly MthdsSource[]): string {\n return JSON.stringify(parseMthdsSourcesEmb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AAM,GAAG,cAAc,KAAK,CAAC,sBAAsB,IAAI,IAAI;AAAA,IACvE;AACA,SAAK,IAAI,IAAI;AACb,WAAO,EAAE,MAAM,QAAQ;AAAA,EACzB,CAAC;AACH;AAmBO,SAAS,2BAA2B,SAAyC;AAClF,SAAO,KAAK,UAAU,uBAAuB,OAAO,CAAC,EAAE,QAAQ,MAAM,SAAS;AAChF;","names":["spec","_a","_b"]}
|
|
1
|
+
{"version":3,"sources":["../../src/static-graph/types.ts","../../src/static-graph/conceptRefs.ts","../../src/static-graph/parseMthdsBundle.ts","../../src/static-graph/normalizePipe.ts","../../src/static-graph/mergeBundles.ts","../../src/static-graph/bindingWalk.ts","../../src/static-graph/buildStaticGraphSpec.ts","../../src/static-graph/validationIssues.ts","../../src/static-graph/sourceOrder.ts","../../src/static-graph/mthdsSourcesEmbed.ts"],"sourcesContent":["// ─── Static method-graph module: domain types ───────────────────────────────\n// Pure TypeScript, no React. This module parses raw `.mthds` TOML text into\n// blueprint-shaped bundles, reusing the `Pipe*Blueprint` registry types from\n// `@graph/types` so the parsed entries can feed a GraphSpec `pipe_registry`\n// directly. Parsing is lenient: half-written bundles produce partial results\n// plus non-fatal diagnostics, never exceptions.\n\nimport type { ConceptInfo, PipeBlueprintUnion } from \"@graph/types\";\n\n// ─── Diagnostics ─────────────────────────────────────────────────────────────\n\nexport type DiagnosticSeverity = \"error\" | \"warning\";\n\nexport type DiagnosticCode =\n | \"toml-parse-error\"\n | \"missing-domain\"\n | \"invalid-bundle-shape\"\n | \"invalid-concept-entry\"\n | \"invalid-pipe-entry\"\n | \"unknown-pipe-type\"\n | \"retired-signature-tag\"\n | \"invalid-concept-ref\"\n | \"unknown-input-slot-key\"\n | \"invalid-input-name\"\n | \"missing-pipe-output\"\n | \"invalid-sub-pipe\"\n | \"invalid-binding-step\"\n | \"binding-path-unresolved\"\n | \"incomplete-batch-spec\"\n | \"duplicate-concept\"\n | \"duplicate-pipe\"\n | \"signature-type-mismatch\"\n | \"unresolved-pipe-ref\"\n | \"cyclic-pipe-ref\"\n | \"missing-main-pipe\"\n | \"no-entry-pipe\"\n | \"conflicting-input-concept\";\n\n/**\n * A non-fatal note collected while parsing or merging. `error` means a whole\n * unit could not be interpreted (unparseable TOML, a skipped pipe); `warning`\n * means something was tolerated with a fallback (missing output, bad ref).\n */\nexport interface Diagnostic {\n severity: DiagnosticSeverity;\n code: DiagnosticCode;\n message: string;\n /** TOML-style locator for the offending entry, e.g. `pipe.analyze_candidate.output`. */\n path?: string;\n /**\n * Domain of the bundle namespace the diagnostic belongs to — the declaring-file\n * identity a host needs to qualify a `pipe.<code>` locator into a full pipe ref\n * (`domain_code.pipe_code`). Stamped wherever the owning namespace is known:\n * per-file diagnostics get their bundle's domain ({@link UNKNOWN_DOMAIN} when\n * the bundle declares none), merge/walk diagnostics the namespace being\n * processed, and entry selection stamps the diagnostics it can attribute (a\n * missing or unresolvable `main_pipe` names its declaring domain). Absent only\n * when no owning bundle can be resolved: unparseable TOML, or entry selection\n * with no resolvable owner (no bundles, no pipes anywhere, or a host-supplied\n * entry ref that matches nothing).\n */\n domain_code?: string;\n}\n\n// ─── Concept structures ──────────────────────────────────────────────────────\n\n/**\n * One field of a concept's declared structure, as the binding walk reads it:\n * the four keys that decide what a path through the field reaches. A field\n * written as a bare description string is a required text field, as pipelex\n * reads that shorthand.\n */\nexport interface StructureField {\n /** The declared `type`, or null when the field declares none (a field defined by its `choices`). */\n type: string | null;\n /** `concept_ref` of a `concept` field, as authored. */\n conceptRef: string | null;\n /** `item_type` of a `list` field. */\n itemType: string | null;\n /** `item_concept_ref` of a list of concepts, as authored. */\n itemConceptRef: string | null;\n}\n\n/**\n * What a concept declares for its structure, beside its `ConceptInfo`: its\n * fields in declaration order, or the name of the Python class a\n * `structure = \"ClassName\"` string points at, which a bundle does not show. A\n * concept declaring no structure has no entry. This is kept apart from\n * `ConceptInfo` on purpose: `ConceptInfo` is what a GraphSpec's\n * `concept_registry` carries, and a dry or live spec carries no such field.\n */\nexport type ConceptStructure = Record<string, StructureField> | string;\n\n// ─── Parsed bundle ───────────────────────────────────────────────────────────\n\n/**\n * One `.mthds` file, parsed and normalized. Pipes are narrowed to the same\n * `PipeBlueprintUnion` shapes the pipelex runtime serializes into GraphSpec\n * `pipe_registry`, and concepts to `ConceptInfo` — no parallel type universe.\n * Field names mirror the TOML bundle header keys.\n */\nexport interface ParsedBundle {\n domain: string | null;\n description: string | null;\n main_pipe: string | null;\n system_prompt: string | null;\n /** Concepts declared in this bundle, keyed by bare concept code. */\n concepts: Record<string, ConceptInfo>;\n /** The structures those concepts declare, keyed by bare concept code — what a binding step walks. */\n structures: Record<string, ConceptStructure>;\n /** Pipes declared in this bundle, keyed by bare pipe code. */\n pipes: Record<string, PipeBlueprintUnion>;\n}\n\nexport interface ParseMthdsBundleResult {\n bundle: ParsedBundle;\n diagnostics: Diagnostic[];\n}\n\n// ─── Merged method set ───────────────────────────────────────────────────────\n\n/** Namespace of one domain after merging bundles: concepts, their structures and pipes by bare code. */\nexport interface DomainNamespace {\n domain: string;\n concepts: Record<string, ConceptInfo>;\n structures: Record<string, ConceptStructure>;\n pipes: Record<string, PipeBlueprintUnion>;\n}\n\n/**\n * The merged namespace of a method package: every parsed bundle grouped by\n * domain, with duplicate codes resolved keep-first (plus a diagnostic).\n * `mainDomain` / `mainPipe` come as a pair from the first bundle declaring\n * `main_pipe` (falling back to the first domained bundle when none does) —\n * the walk entry point for the static graph builder. `description` comes from\n * the first bundle that declares it.\n */\nexport interface MergedMethodSet {\n domains: Record<string, DomainNamespace>;\n mainDomain: string | null;\n mainPipe: string | null;\n description: string | null;\n diagnostics: Diagnostic[];\n}\n\n/** Namespace used for bundles that declare no `domain` (a legal WIP state). */\nexport const UNKNOWN_DOMAIN = \"unknown\";\n\n// ─── Narrowing helpers (shared by the parsing modules) ───────────────────────\n\n/**\n * True for plain tables only — rejects arrays, class instances and dates\n * (smol-toml emits `TomlDate` objects for TOML datetime values).\n */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * An empty record for keys an author wrote.\n *\n * Every accumulator in this module is keyed by authored `.mthds` text — input\n * names, concept codes, pipe codes, domain names — and a plain `{}` hands those\n * keys `Object.prototype` to collide with. Three distinct failures follow, none\n * of which the author is told about: `record[name] = value` for a name of\n * `__proto__` invokes the prototype setter and creates no own key, so the entry\n * vanishes with no diagnostic; `record[code]` for a code of `toString` returns a\n * built-in function that reads as a declared entry; and `record[domain] ??= …`\n * for a domain of `__proto__` yields `Object.prototype` itself, whose missing\n * members then throw — breaking this module's contract that it never throws on\n * content. A null prototype has nothing to collide with, so all three stop\n * existing at once rather than needing a guard at every read and write.\n */\nexport function authoredRecord<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\nexport function strOrNull(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nexport function intOrNull(value: unknown): number | null {\n return typeof value === \"number\" && Number.isInteger(value) ? value : null;\n}\n\nexport function boolOrNull(value: unknown): boolean | null {\n return typeof value === \"boolean\" ? value : null;\n}\n","// ─── Concept reference parsing and resolution ────────────────────────────────\n// A concept ref in MTHDS TOML is `Code` or `domain.Code`, optionally suffixed\n// with a multiplicity marker — `Code[]` (many) or `Code[N]` (exactly N) — and\n// then a presence marker — `Code?` (optional) or `Code!` (force). The suffix\n// order is fixed, multiplicity before presence, mirroring the runtime's\n// `MULTIPLICITY_PATTERN` in `pipelex/core/pipes/variable_multiplicity.py`.\n// Resolution follows the spec's namespace rules: bare refs resolve in the\n// current bundle first, then the native domain; qualified refs name their\n// domain explicitly. Anything unresolved becomes a best-effort stub — this\n// module never throws on content.\n\nimport type { ConceptInfo, PresenceMarker, StuffSpecInfo } from \"@graph/types\";\n\nimport type { StructureField } from \"./types\";\nimport { isPlainObject } from \"./types\";\n\nexport const NATIVE_DOMAIN = \"native\";\n\n// ─── The native concept catalog ──────────────────────────────────────────────\n\nconst field = (type: string): StructureField => ({\n type,\n conceptRef: null,\n itemType: null,\n itemConceptRef: null,\n});\nconst conceptField = (conceptRef: string): StructureField => ({\n type: \"concept\",\n conceptRef,\n itemType: null,\n itemConceptRef: null,\n});\nconst conceptListField = (itemConceptRef: string): StructureField => ({\n type: \"list\",\n conceptRef: null,\n itemType: \"concept\",\n itemConceptRef,\n});\n\n/** What the catalog holds of one native. */\ninterface NativeConceptDefinition {\n description: string;\n /** The native it refines, as the runtime records it: `Markdown` refines `Text`. */\n refines?: string;\n /**\n * Its pinned fields, as the binding walk reads them (each field's type and the\n * concept it names), or null for a native structureless by definition.\n */\n fields: Readonly<Record<string, StructureField>> | null;\n}\n\n/**\n * The native concept catalog, the one source of what this module knows of a\n * native: its code, description and refinement, which resolve a ref, and its\n * pinned fields, which the binding walk reads. Copied from the MTHDS standard's\n * pinned set — `docs/spec/native-concepts.md` in the sibling `mthds/` repo —\n * which pipelex mirrors in `pipelex/core/concepts/native/concept_native.py`\n * (`NativeConceptCode`) and `native/pinned_blueprints.py`, together with\n * `Markdown`, which pipelex defines ahead of the standard. Structure class\n * names follow the runtime's `<Code>Content` rule. Keep this table in\n * `NativeConceptCode`'s order; a code missing here silently degrades to a stub.\n * See `docs/static-graph.md`.\n */\nconst NATIVE_CONCEPTS = {\n Dynamic: { description: \"A dynamic concept\", fields: null },\n Text: { description: \"A text\", fields: { text: field(\"text\") } },\n Markdown: {\n description: \"A text written in Markdown\",\n refines: \"native.Text\",\n fields: { text: field(\"text\") },\n },\n Image: {\n description: \"An image\",\n fields: {\n url: field(\"text\"),\n public_url: field(\"text\"),\n source_prompt: field(\"text\"),\n source_negative_prompt: field(\"text\"),\n caption: field(\"text\"),\n mime_type: field(\"text\"),\n width: field(\"integer\"),\n height: field(\"integer\"),\n filename: field(\"text\"),\n },\n },\n Document: {\n description: \"A document\",\n fields: {\n url: field(\"text\"),\n public_url: field(\"text\"),\n mime_type: field(\"text\"),\n filename: field(\"text\"),\n title: field(\"text\"),\n snippet: field(\"text\"),\n },\n },\n Html: {\n description: \"HTML content\",\n fields: { inner_html: field(\"text\"), css_class: field(\"text\") },\n },\n TextAndImages: {\n description: \"A text and an image\",\n fields: {\n text: conceptField(\"native.Text\"),\n images: conceptListField(\"native.Image\"),\n raw_html: field(\"text\"),\n },\n },\n Number: { description: \"A number\", fields: { number: field(\"number\") } },\n YesNo: {\n description: \"The answer to a yes/no question\",\n fields: { yes_no: field(\"boolean\"), probability: field(\"number\") },\n },\n Choice: {\n description: \"One option picked out of a declared set\",\n fields: { choice: field(\"text\"), confidence: field(\"number\"), probabilities: field(\"dict\") },\n },\n Rating: {\n description: \"A position on an ordered scale of described levels\",\n fields: {\n level: field(\"integer\"),\n confidence: field(\"number\"),\n probabilities: field(\"dict\"),\n position: field(\"number\"),\n },\n },\n Date: {\n description:\n \"A calendar date, optionally with a time of day — as precise as its source states.\",\n fields: { date: field(\"date\"), time: field(\"time\") },\n },\n Time: {\n description: \"A time of day, optionally with a UTC offset — as precise as its source states.\",\n fields: { time: field(\"time\") },\n },\n Page: {\n description:\n \"The content of a page of a document, comprising text and linked images and an optional page view image\",\n fields: {\n text_and_images: conceptField(\"native.TextAndImages\"),\n page_view: conceptField(\"native.Image\"),\n },\n },\n JSON: { description: \"A JSON object\", fields: { json_obj: field(\"dict\") } },\n SearchResult: {\n description: \"A search result with answer and sources\",\n fields: { answer: field(\"text\"), sources: conceptListField(\"native.Document\") },\n },\n Anything: { description: \"Anything\", fields: null },\n Composite: { description: \"A named composition of contents\", fields: null },\n} satisfies Record<string, NativeConceptDefinition>;\n\n/** A code the catalog knows. Derived from the catalog so the two cannot disagree. */\nexport type NativeConceptCode = keyof typeof NATIVE_CONCEPTS;\n\nexport const NATIVE_CONCEPT_CODES: ReadonlySet<string> = new Set(Object.keys(NATIVE_CONCEPTS));\n\n/** Narrow an arbitrary code to the catalog, so callers cannot mint a native the catalog lacks. */\nexport function isNativeConceptCode(code: string): code is NativeConceptCode {\n return Object.hasOwn(NATIVE_CONCEPTS, code);\n}\n\n/** A native's pinned fields, or null for a native structureless by definition. */\nexport function nativeConceptFields(\n code: NativeConceptCode,\n): Readonly<Record<string, StructureField>> | null {\n const definition: NativeConceptDefinition = NATIVE_CONCEPTS[code];\n return definition.fields;\n}\n\n// ─── Ref parsing ─────────────────────────────────────────────────────────────\n\nexport interface ConceptRefParts {\n /** Explicit domain qualifier (`recruitment` in `recruitment.Profile`), or null for bare refs. */\n domain: string | null;\n code: string;\n /** `[]` → true (many), `[N]` → N, no suffix → null (single). */\n multiplicity: number | boolean | null;\n /** `?` → \"optional\", `!` → \"force\", no suffix → \"plain\". */\n presence: PresenceMarker;\n}\n\nconst CONCEPT_REF_RE = /^(?:([A-Za-z0-9_][A-Za-z0-9_.]*)\\.)?([A-Za-z0-9_]+)(?:\\[(\\d*)\\])?([?!])?$/;\n\nfunction presenceFromSymbol(symbol: string | undefined): PresenceMarker {\n if (symbol === \"?\") return \"optional\";\n if (symbol === \"!\") return \"force\";\n return \"plain\";\n}\n\n/** Parse a concept ref string into its parts. Returns null when the ref is not interpretable. */\nexport function parseConceptRef(raw: unknown): ConceptRefParts | null {\n if (typeof raw !== \"string\") return null;\n const match = CONCEPT_REF_RE.exec(raw.trim());\n if (!match) return null;\n const [, domain, code, multiplicity, presence] = match;\n return {\n domain: domain ?? null,\n code,\n multiplicity:\n multiplicity === undefined\n ? null\n : multiplicity === \"\"\n ? true\n : Number.parseInt(multiplicity, 10),\n presence: presenceFromSymbol(presence),\n };\n}\n\n// ─── Input slot declarations ─────────────────────────────────────────────────\n// A value in a pipe's `inputs` table has two forms, and the standard states\n// them equivalent (`docs/spec/mthds-format.md`, \"Input slot declarations\"):\n// the string form `x = \"S\"`, and the expanded form `x = { concept = \"S\",\n// hints = { … } }`, whose `concept` carries exactly the same grammar. The\n// expanded form is inputs-only — an `output` is always a string — so this\n// layer sits beside `parseConceptRef` rather than inside it.\n\n/**\n * The keys the expanded slot table defines in this version of the standard.\n * The form is deliberately closed: the spec says an unknown key MUST be\n * rejected, which pipelex implements as `extra=\"forbid\"` on its\n * `InputSlotBlueprint`. This module renders rather than adjudicates, so it\n * reports the key and reads past it — see `parseInputSlot`.\n */\nconst INPUT_SLOT_KEYS: ReadonlySet<string> = new Set([\"concept\", \"hints\"]);\n\nexport interface InputSlotParts {\n /** The slot's concept ref parts, or null when the slot is not interpretable. */\n ref: ConceptRefParts | null;\n /**\n * True when an expanded slot table declares no `concept` at all. The key is\n * required, so there is no ref for a diagnostic to be about — the caller says\n * the key is missing rather than blaming a ref the author never wrote.\n */\n missingConcept: boolean;\n /** Keys of an expanded slot table this version of the standard does not define. */\n unknownKeys: string[];\n}\n\n/** A concept code as the standard pins it: `[A-Z][a-zA-Z0-9]*`. */\nconst CONCEPT_CODE_RE = /^[A-Z][A-Za-z0-9]*$/;\n\n/** Whether a value is a concept ref whose code has the shape the standard pins. */\nfunction isConceptCodeRef(raw: unknown): boolean {\n const parts = parseConceptRef(raw);\n return parts !== null && CONCEPT_CODE_RE.test(parts.code);\n}\n\n/**\n * The dotted names an `inputs` entry was written as, when TOML nested an\n * unquoted dotted key into it, or null when the entry is a slot of its own.\n *\n * `inputs = { page.page_view = \"Image\" }` arrives as an input named `page`\n * holding `{ page_view: \"Image\" }`, which the expanded slot form would read as\n * a slot table with an unknown key and no `concept`: two true sentences that\n * never say what is wrong, a dotted input name. A table with no `concept`\n * whose every key leads, through more such tables, to a concept ref (a string,\n * or a slot table's `concept`) can only be that, because a concept code MUST\n * be PascalCase: `{ widget = \"textarea\" }` is a slot with an unknown key, and\n * `{ page_view = \"Image\" }` can only be a field.\n */\nexport function unquotedDottedInputNames(name: string, raw: unknown): string[] | null {\n if (!isPlainObject(raw) || raw.concept !== undefined) return null;\n const keys = Object.keys(raw);\n if (keys.length === 0) return null;\n const dottedNames: string[] = [];\n for (const key of keys) {\n const value = raw[key];\n const dottedName = `${name}.${key}`;\n if (isConceptCodeRef(value) || (isPlainObject(value) && isConceptCodeRef(value.concept))) {\n dottedNames.push(dottedName);\n continue;\n }\n const nested = unquotedDottedInputNames(dottedName, value);\n if (nested === null) return null;\n dottedNames.push(...nested);\n }\n return dottedNames;\n}\n\n/**\n * Read one `inputs` value, whichever form authored it.\n *\n * `hints` is parsed as a known key and then dropped: intent hints are\n * presentational, and the standard routes them to renderers through the\n * input-form descriptor, not the GraphSpec (see `docs/static-graph.md`).\n * Their shape is not checked here for the same reason — a malformed `hints`\n * table is content this module never reads, so it is the validator's to\n * report, not the renderer's. An unknown key is different: it may well be\n * where a future standard puts something that changes the slot, so it is\n * named rather than passed over.\n */\nexport function parseInputSlot(raw: unknown): InputSlotParts {\n if (!isPlainObject(raw)) {\n return { ref: parseConceptRef(raw), missingConcept: false, unknownKeys: [] };\n }\n return {\n ref: parseConceptRef(raw.concept),\n missingConcept: raw.concept === undefined,\n unknownKeys: Object.keys(raw).filter((key) => !INPUT_SLOT_KEYS.has(key)),\n };\n}\n\n// ─── Resolution to ConceptInfo ───────────────────────────────────────────────\n\n/**\n * Synthetic structure class name for a non-native concept, mirroring the\n * runtime's `make_qualified_structure_class_name`: dots in hierarchical\n * domain codes are replaced with interpuncts (·) to keep the name a valid,\n * collision-free identifier (`a.b` → `a·b`, distinct from `a_b`).\n */\nexport function qualifiedStructureClassName(domain: string, code: string): string {\n return `${domain.replaceAll(\".\", \"·\")}__${code}`;\n}\n\nexport function nativeConceptInfo(code: NativeConceptCode): ConceptInfo {\n const definition: NativeConceptDefinition = NATIVE_CONCEPTS[code];\n return {\n code,\n domain_code: NATIVE_DOMAIN,\n description: definition.description,\n structure_class_name: `${code}Content`,\n refines: definition.refines ?? null,\n };\n}\n\n/**\n * Best-effort info for a concept that is referenced but not declared in the\n * material at hand — an implicit concept, a WIP ref, or a cross-bundle ref\n * that `mergeBundles` may still enrich later.\n */\nfunction stubConceptInfo(code: string, domain: string): ConceptInfo {\n return {\n code,\n domain_code: domain,\n description: \"\",\n structure_class_name: qualifiedStructureClassName(domain, code),\n refines: null,\n };\n}\n\n/**\n * Resolve parsed ref parts against the current bundle. `localConcepts` holds\n * the bundle's declared concepts keyed by bare code.\n */\nexport function resolveConceptInfo(\n parts: ConceptRefParts,\n currentDomain: string,\n localConcepts: Record<string, ConceptInfo>,\n): ConceptInfo {\n if (parts.domain === NATIVE_DOMAIN) {\n return isNativeConceptCode(parts.code)\n ? nativeConceptInfo(parts.code)\n : stubConceptInfo(parts.code, NATIVE_DOMAIN);\n }\n if (parts.domain !== null && parts.domain !== currentDomain) {\n return stubConceptInfo(parts.code, parts.domain);\n }\n // Local before native. The spec inverts this (\"Native concepts always take\n // priority\"), but it also makes a bundle that declares a native-named concept\n // invalid outright — so this branch is only reachable on a bundle pipelex\n // rejects. The diagnostic that would warn the author is L-260929-79b6e6.\n // `hasOwn`, not a truthiness test: `localConcepts` is a caller-supplied\n // record, and on a plain `{}` a code of `toString` or `constructor` reads a\n // built-in off `Object.prototype` and returns a function as the concept.\n if (Object.hasOwn(localConcepts, parts.code)) return localConcepts[parts.code];\n if (parts.domain === null && isNativeConceptCode(parts.code)) {\n return nativeConceptInfo(parts.code);\n }\n return stubConceptInfo(parts.code, currentDomain);\n}\n\n/** Build a `StuffSpecInfo` from already-parsed ref parts. */\nfunction stuffSpecFromParts(\n parts: ConceptRefParts,\n currentDomain: string,\n localConcepts: Record<string, ConceptInfo>,\n): StuffSpecInfo {\n return {\n concept: resolveConceptInfo(parts, currentDomain, localConcepts),\n multiplicity: parts.multiplicity,\n presence: parts.presence,\n };\n}\n\n/** Resolve a raw concept ref string straight to a `StuffSpecInfo`, or null when unparseable. */\nexport function resolveStuffSpec(\n raw: unknown,\n currentDomain: string,\n localConcepts: Record<string, ConceptInfo>,\n): StuffSpecInfo | null {\n const parts = parseConceptRef(raw);\n return parts === null ? null : stuffSpecFromParts(parts, currentDomain, localConcepts);\n}\n\nexport interface ResolvedInputSlot {\n /** The resolved slot, or null when its concept ref is not interpretable. */\n spec: StuffSpecInfo | null;\n /** True when an expanded slot table declares no `concept` at all — see {@link InputSlotParts}. */\n missingConcept: boolean;\n /** Keys of an expanded slot table this version of the standard does not define. */\n unknownKeys: string[];\n}\n\n/**\n * Resolve one `inputs` value to a `StuffSpecInfo`, accepting either slot form.\n * The `StuffSpecInfo` is identical whichever form authored it, which is what\n * the standard means by calling `x = \"S\"` and `x = { concept = \"S\" }` the same\n * slot.\n */\nexport function resolveInputSlot(\n raw: unknown,\n currentDomain: string,\n localConcepts: Record<string, ConceptInfo>,\n): ResolvedInputSlot {\n const { ref, missingConcept, unknownKeys } = parseInputSlot(raw);\n return {\n spec: ref === null ? null : stuffSpecFromParts(ref, currentDomain, localConcepts),\n missingConcept,\n unknownKeys,\n };\n}\n","// ─── parseMthdsBundle: `.mthds` TOML text → ParsedBundle ─────────────────────\n// The single entry point for turning one raw `.mthds` string into a\n// blueprint-shaped bundle. Lenient in the `validateGraphSpec` house style but\n// inverted: instead of failing loudly on contract violations, it tolerates\n// missing or partial sections, skips what it cannot interpret, and records\n// non-fatal diagnostics — the whole point is rendering methods while they are\n// being written. It never throws on content; even unparseable TOML becomes an\n// `error` diagnostic with an empty bundle.\n\nimport { parse as parseToml } from \"smol-toml\";\n\nimport type { ConceptInfo, PipeBlueprintUnion } from \"@graph/types\";\n\nimport {\n isNativeConceptCode,\n NATIVE_DOMAIN,\n parseConceptRef,\n qualifiedStructureClassName,\n} from \"./conceptRefs\";\nimport { normalizePipe } from \"./normalizePipe\";\nimport type {\n ConceptStructure,\n Diagnostic,\n ParseMthdsBundleResult,\n ParsedBundle,\n StructureField,\n} from \"./types\";\nimport { authoredRecord, isPlainObject, strOrNull, UNKNOWN_DOMAIN } from \"./types\";\n\n// ─── Concept structure → JSON schema (display-only, best-effort) ─────────────\n\nconst FIELD_TYPE_TO_JSON: Record<string, Record<string, unknown>> = {\n text: { type: \"string\" },\n integer: { type: \"integer\" },\n number: { type: \"number\" },\n boolean: { type: \"boolean\" },\n date: { type: \"string\", format: \"date\" },\n datetime: { type: \"string\", format: \"date-time\" },\n time: { type: \"string\", format: \"time\" },\n list: { type: \"array\" },\n dict: { type: \"object\" },\n concept: { type: \"object\" },\n};\n\nfunction fieldSchema(spec: Record<string, unknown>): Record<string, unknown> {\n const typeName = strOrNull(spec.type) ?? \"text\";\n const schema: Record<string, unknown> = {\n ...(FIELD_TYPE_TO_JSON[typeName] ?? { type: \"string\" }),\n };\n const description = strOrNull(spec.description);\n if (description !== null) schema.description = description;\n if (typeName === \"list\") {\n const itemType = strOrNull(spec.item_type);\n schema.items = itemType !== null ? { ...(FIELD_TYPE_TO_JSON[itemType] ?? {}) } : {};\n }\n if (Array.isArray(spec.choices)) {\n schema.enum = spec.choices.filter((choice) => typeof choice === \"string\");\n }\n if (spec.default_value !== undefined && spec.default_value !== null) {\n schema.default = spec.default_value;\n }\n return schema;\n}\n\n/**\n * Derive a lightweight JSON schema from a `[concept.X.structure]` table so\n * concept detail panels have fields to show. Deliberately simpler than the\n * pydantic-generated schema the runtime emits (no anyOf-null wrapping, no\n * per-field titles) — this is presentation data, not a contract.\n */\nfunction deriveJsonSchema(\n structure: unknown,\n title: string,\n description: string,\n): Record<string, unknown> | undefined {\n if (!isPlainObject(structure)) return undefined;\n const properties = authoredRecord<unknown>();\n const required: string[] = [];\n for (const [name, spec] of Object.entries(structure)) {\n if (typeof spec === \"string\") {\n // The shorthand is a required text field, as the runtime reads it.\n properties[name] = { type: \"string\", description: spec };\n required.push(name);\n continue;\n }\n if (!isPlainObject(spec)) continue;\n properties[name] = fieldSchema(spec);\n if (spec.required === true) required.push(name);\n }\n return {\n title,\n type: \"object\",\n description,\n properties,\n ...(required.length > 0 ? { required } : {}),\n };\n}\n\n// ─── Concept table parsing ───────────────────────────────────────────────────\n\n/** Qualify a `refines` ref the way the runtime registry does (`Text` → `native.Text`). */\nfunction qualifyRefines(\n raw: unknown,\n domain: string,\n declaredCodes: ReadonlySet<string>,\n conceptCode: string,\n diagnostics: Diagnostic[],\n): string | null {\n const parts = parseConceptRef(raw);\n if (parts === null) return null;\n // `refines` names a concept; multiplicity and presence are properties of an io\n // slot that holds values, so a `refines` carrying either is malformed. Dropping\n // the suffix silently would turn `refines = \"Text?\"` into a plain `native.Text`\n // that reads back as if the author had written it that way.\n if (parts.multiplicity !== null || parts.presence !== \"plain\") {\n diagnostics.push({\n severity: \"warning\",\n code: \"invalid-concept-ref\",\n message:\n `concept \"${conceptCode}\": \\`refines\\` names a concept, so it takes no multiplicity ` +\n `or presence suffix — ignored`,\n path: `concept.${conceptCode}.refines`,\n });\n return null;\n }\n if (parts.domain !== null) return `${parts.domain}.${parts.code}`;\n if (!declaredCodes.has(parts.code) && isNativeConceptCode(parts.code)) {\n return `${NATIVE_DOMAIN}.${parts.code}`;\n }\n return `${domain}.${parts.code}`;\n}\n\n/**\n * Read a `[concept.X.structure]` table into the fields a binding step walks.\n * A field written as a bare description string is a required text field, as\n * the runtime reads that shorthand; a field that is neither is skipped, since\n * it declares nothing a path could reach.\n */\nfunction parseStructureFields(structure: Record<string, unknown>): Record<string, StructureField> {\n const fields = authoredRecord<StructureField>();\n for (const [name, spec] of Object.entries(structure)) {\n if (typeof spec === \"string\") {\n fields[name] = { type: \"text\", conceptRef: null, itemType: null, itemConceptRef: null };\n continue;\n }\n if (!isPlainObject(spec)) continue;\n fields[name] = {\n type: strOrNull(spec.type),\n conceptRef: strOrNull(spec.concept_ref),\n itemType: strOrNull(spec.item_type),\n itemConceptRef: strOrNull(spec.item_concept_ref),\n };\n }\n return fields;\n}\n\ninterface ParsedConcepts {\n concepts: Record<string, ConceptInfo>;\n structures: Record<string, ConceptStructure>;\n}\n\nfunction parseConcepts(raw: unknown, domain: string, diagnostics: Diagnostic[]): ParsedConcepts {\n const concepts = authoredRecord<ConceptInfo>();\n const structures = authoredRecord<ConceptStructure>();\n if (raw === undefined) return { concepts, structures };\n if (!isPlainObject(raw)) {\n diagnostics.push({\n severity: \"warning\",\n code: \"invalid-bundle-shape\",\n message: \"concept section is not a table — ignored\",\n path: \"concept\",\n });\n return { concepts, structures };\n }\n const declaredCodes: ReadonlySet<string> = new Set(Object.keys(raw));\n for (const [code, entry] of Object.entries(raw)) {\n if (typeof entry === \"string\") {\n // Shorthand form: `Concept = \"description\"`.\n concepts[code] = {\n code,\n domain_code: domain,\n description: entry,\n structure_class_name: qualifiedStructureClassName(domain, code),\n refines: null,\n };\n continue;\n }\n if (!isPlainObject(entry)) {\n diagnostics.push({\n severity: \"warning\",\n code: \"invalid-concept-entry\",\n message: `concept \"${code}\" is neither a table nor a description string — skipped`,\n path: `concept.${code}`,\n });\n continue;\n }\n const description = strOrNull(entry.description) ?? \"\";\n // A `structure = \"ClassName\"` string names an existing structure class;\n // the table form gets the runtime's `<domain>__<Code>` synthetic name.\n const structureClassName =\n strOrNull(entry.structure) ?? qualifiedStructureClassName(domain, code);\n concepts[code] = {\n code,\n domain_code: domain,\n description,\n structure_class_name: structureClassName,\n refines: qualifyRefines(entry.refines, domain, declaredCodes, code, diagnostics),\n json_schema: deriveJsonSchema(entry.structure, structureClassName, description),\n };\n if (isPlainObject(entry.structure)) {\n structures[code] = parseStructureFields(entry.structure);\n } else if (typeof entry.structure === \"string\") {\n structures[code] = entry.structure;\n }\n }\n return { concepts, structures };\n}\n\n// ─── Bundle parsing ──────────────────────────────────────────────────────────\n\nfunction emptyBundle(): ParsedBundle {\n return {\n domain: null,\n description: null,\n main_pipe: null,\n system_prompt: null,\n concepts: authoredRecord<ConceptInfo>(),\n structures: authoredRecord<ConceptStructure>(),\n pipes: authoredRecord<PipeBlueprintUnion>(),\n };\n}\n\n/**\n * Parse one `.mthds` TOML string. Returns whatever could be interpreted plus\n * the diagnostics collected along the way — never throws.\n */\nexport function parseMthdsBundle(tomlText: string): ParseMthdsBundleResult {\n const diagnostics: Diagnostic[] = [];\n let root: Record<string, unknown>;\n try {\n root = parseToml(tomlText);\n } catch (error) {\n diagnostics.push({\n severity: \"error\",\n code: \"toml-parse-error\",\n message: error instanceof Error ? error.message : String(error),\n });\n return { bundle: emptyBundle(), diagnostics };\n }\n\n const bundle = emptyBundle();\n bundle.domain = strOrNull(root.domain);\n bundle.description = strOrNull(root.description);\n bundle.main_pipe = strOrNull(root.main_pipe);\n bundle.system_prompt = strOrNull(root.system_prompt);\n if (bundle.domain === null) {\n diagnostics.push({\n severity: \"warning\",\n code: \"missing-domain\",\n message: `bundle declares no domain — using \"${UNKNOWN_DOMAIN}\"`,\n path: \"domain\",\n });\n }\n const domain = bundle.domain ?? UNKNOWN_DOMAIN;\n\n const { concepts, structures } = parseConcepts(root.concept, domain, diagnostics);\n bundle.concepts = concepts;\n bundle.structures = structures;\n\n const pipeTable = root.pipe;\n if (pipeTable !== undefined) {\n if (!isPlainObject(pipeTable)) {\n diagnostics.push({\n severity: \"warning\",\n code: \"invalid-bundle-shape\",\n message: \"pipe section is not a table — ignored\",\n path: \"pipe\",\n });\n } else {\n const ctx = { domain, concepts: bundle.concepts, diagnostics };\n for (const [code, entry] of Object.entries(pipeTable)) {\n if (!isPlainObject(entry)) {\n diagnostics.push({\n severity: \"error\",\n code: \"invalid-pipe-entry\",\n message: `pipe \"${code}\" is not a table — skipped`,\n path: `pipe.${code}`,\n });\n continue;\n }\n const pipe: PipeBlueprintUnion | null = normalizePipe(code, entry, ctx);\n if (pipe !== null) bundle.pipes[code] = pipe;\n }\n }\n }\n\n // Stamp every diagnostic with the file's namespace domain — the declaring-file\n // identity hosts need to qualify `pipe.<code>` locators into full pipe refs.\n // (The toml-parse-error path returns above, before any domain exists.)\n for (const diagnostic of diagnostics) {\n diagnostic.domain_code ??= domain;\n }\n\n return { bundle, diagnostics };\n}\n","// ─── Pipe normalization: authored TOML shape → registry blueprint shape ─────\n// The authoring surface (mthds_schema.json, checked in under data/schema/)\n// and the runtime-serialized registry shape (`PipeBlueprintUnion` in\n// `@graph/types`) name things differently: `steps` vs `sequential_sub_pipes`,\n// `model` vs `llm_choices`, `prompt` vs `prompt_blueprint`, … This module maps\n// the former to the latter, leniently: uninterpretable pieces are skipped with\n// a diagnostic, and a pipe is dropped entirely only when it names no usable\n// `type` and is not a signature (see `resolvePipeTypeTag`).\n\nimport type {\n BindingStepSpec,\n ConceptInfo,\n JudgmentQuestionSpec,\n PipeBlueprintUnion,\n PipeComposeConstructBlueprint,\n PipeComposeConstructField,\n PipeType,\n SequenceStepSpec,\n StuffSpecInfo,\n SubPipeSpec,\n TemplateBlueprint,\n} from \"@graph/types\";\nimport { KNOWN_PIPE_TYPES } from \"@graph/types\";\n\nimport {\n NATIVE_DOMAIN,\n nativeConceptInfo,\n resolveInputSlot,\n resolveStuffSpec,\n unquotedDottedInputNames,\n} from \"./conceptRefs\";\nimport type { Diagnostic } from \"./types\";\nimport { authoredRecord, boolOrNull, intOrNull, isPlainObject, strOrNull } from \"./types\";\n\nexport interface NormalizePipeContext {\n domain: string;\n /** The bundle's declared concepts, keyed by bare code. */\n concepts: Record<string, ConceptInfo>;\n diagnostics: Diagnostic[];\n}\n\n// ─── Small shared builders ───────────────────────────────────────────────────\n\nfunction makeTemplate(template: string, category: string): TemplateBlueprint {\n return { template, templating_style: null, category, extra_context: null };\n}\n\n/**\n * Extract a display string from a model choice, which the authoring surface\n * allows as a plain handle (`\"gpt-5\"`), an inline setting (`{ model = … }`),\n * or a model reference (`{ name = … }`).\n */\nfunction modelToString(value: unknown): string | null {\n if (typeof value === \"string\") return strOrNull(value);\n if (isPlainObject(value)) {\n return strOrNull(value.model) ?? strOrNull(value.raw) ?? strOrNull(value.name);\n }\n return null;\n}\n\nfunction stringArrayOrNull(value: unknown): string[] | null {\n if (!Array.isArray(value)) return null;\n return value.filter((item): item is string => typeof item === \"string\");\n}\n\n// ─── IO normalization ────────────────────────────────────────────────────────\n\n/**\n * A plain name (`^[a-z][a-z0-9_]*$` in the schema): the grammar of an input\n * name, and of a binding step's `result`, since a later step reads the bound\n * value through its inputs. It has no dot, so a name never reaches into a\n * field, and no leading underscore, which keeps the reserved private prefix\n * out of an author's reach.\n */\nconst PLAIN_NAME_RE = /^[a-z][a-z0-9_]*$/;\n\n/** The binding step that hands the field a dotted path reaches to a pipe under a plain name. */\nfunction bindingStepFor(dottedPath: string): string {\n const plainName = dottedPath.slice(dottedPath.lastIndexOf(\".\") + 1);\n return `{ from = \"${dottedPath}\", result = \"${plainName}\" }`;\n}\n\n/** What to do about a dotted input name, as the runtime says it when it refuses one. */\nfunction dottedInputNameRemedy(dottedName: string): string {\n const root = dottedName.slice(0, dottedName.indexOf(\".\"));\n return (\n `an input names one whole value, so its name cannot reach into a field with a dot; declare \"${root}\" ` +\n `with its whole concept and read the field through it, or have the calling sequence bind the field ` +\n `to a plain name with a binding step (${bindingStepFor(dottedName)}) and declare that name`\n );\n}\n\n/** Why an input name breaking the plain-name grammar is refused. */\nfunction invalidInputNameReason(name: string): string {\n const segments = name.split(\".\");\n if (segments.length > 1 && segments.every((segment) => PLAIN_NAME_RE.test(segment))) {\n return `is not a plain input name: ${dottedInputNameRemedy(name)}`;\n }\n return \"is not a plain input name, which is a lowercase letter followed by lowercase letters, digits and underscores\";\n}\n\n/** A TOML-style locator segment for a key, quoted when a bare key cannot spell it. */\nfunction tomlKey(key: string): string {\n return /^[A-Za-z0-9_-]+$/.test(key) ? key : JSON.stringify(key);\n}\n\nfunction normalizeInputs(\n raw: unknown,\n pipeCode: string,\n ctx: NormalizePipeContext,\n): Record<string, StuffSpecInfo> {\n const inputs = authoredRecord<StuffSpecInfo>();\n if (raw === undefined || raw === null) return inputs;\n if (!isPlainObject(raw)) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-pipe-entry\",\n message: `pipe \"${pipeCode}\": inputs is not a table — ignored`,\n path: `pipe.${pipeCode}.inputs`,\n });\n return inputs;\n }\n for (const [name, slot] of Object.entries(raw)) {\n const path = `pipe.${pipeCode}.inputs.${tomlKey(name)}`;\n // The runtime refuses a name breaking the plain-name grammar, a quoted\n // dotted one among them, so it is skipped: nothing in scope holds it, and\n // drawing it would draw a dangling input for a bundle that never runs.\n if (!PLAIN_NAME_RE.test(name)) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-input-name\",\n message: `pipe \"${pipeCode}\": input \"${name}\" ${invalidInputNameReason(name)} — skipped`,\n path,\n });\n continue;\n }\n // The same name unquoted is a nesting in TOML, which reads as a slot table\n // with an unknown key and no `concept`. Reported alone and as what it is,\n // since the two generic diagnostics below never mention the dot.\n const dottedNames = unquotedDottedInputNames(name, slot);\n if (dottedNames !== null) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-input-name\",\n message:\n `pipe \"${pipeCode}\": input \"${name}\" is a table with no \"concept\", which is how TOML reads the ` +\n `unquoted dotted input ${dottedNames.length === 1 ? \"name\" : \"names\"} ` +\n `${dottedNames.map((dotted) => `\"${dotted}\"`).join(\", \")}; ` +\n `${dottedInputNameRemedy(dottedNames[0])} — skipped`,\n path,\n });\n continue;\n }\n const { spec, missingConcept, unknownKeys } = resolveInputSlot(slot, ctx.domain, ctx.concepts);\n if (unknownKeys.length > 0) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"unknown-input-slot-key\",\n message:\n `pipe \"${pipeCode}\": input \"${name}\" declares ${unknownKeys.map((key) => `\"${key}\"`).join(\", \")}, ` +\n \"which the input slot form does not define — ignored here, and the runtime refuses the bundle\",\n path,\n });\n }\n if (spec === null) {\n // Two ways to reach here, and they are different author mistakes: an\n // expanded slot that never declared the required `concept` key, versus a\n // ref that was written and does not parse. Saying \"uninterpretable ref\"\n // for the first blames a ref the author never wrote, which reads as a\n // grammar problem when the fix is to add the key.\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-concept-ref\",\n message: missingConcept\n ? `pipe \"${pipeCode}\": input \"${name}\" is a slot table with no \"concept\" — the key is required — skipped`\n : `pipe \"${pipeCode}\": input \"${name}\" has an uninterpretable concept ref — skipped`,\n path,\n });\n continue;\n }\n inputs[name] = spec;\n }\n return inputs;\n}\n\nfunction normalizeOutput(raw: unknown, pipeCode: string, ctx: NormalizePipeContext): StuffSpecInfo {\n const spec = resolveStuffSpec(raw, ctx.domain, ctx.concepts);\n if (spec !== null) return spec;\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"missing-pipe-output\",\n message: `pipe \"${pipeCode}\": missing or uninterpretable output — assuming native.Anything`,\n path: `pipe.${pipeCode}.output`,\n });\n return { concept: nativeConceptInfo(\"Anything\"), multiplicity: null, presence: \"plain\" };\n}\n\n// ─── Sub-pipe normalization (sequence steps, parallel branches) ──────────────\n\nfunction normalizeSubPipe(\n raw: Record<string, unknown>,\n pipeCode: string,\n path: string,\n ctx: NormalizePipeContext,\n): SubPipeSpec | null {\n if (strOrNull(raw.pipe) === null) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-sub-pipe\",\n message: `pipe \"${pipeCode}\": sub-pipe entry without a \"pipe\" ref — skipped`,\n path,\n });\n return null;\n }\n const batchOver = strOrNull(raw.batch_over);\n const batchAs = strOrNull(raw.batch_as);\n let batchParams: SubPipeSpec[\"batch_params\"] = null;\n if (batchOver !== null && batchAs !== null) {\n batchParams = { input_list_stuff_name: batchOver, input_item_stuff_name: batchAs };\n } else if (batchOver !== null || batchAs !== null) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"incomplete-batch-spec\",\n message:\n `pipe \"${pipeCode}\": sub-pipe \"${raw.pipe as string}\" sets only one of ` +\n `batch_over/batch_as — batching ignored`,\n path,\n });\n }\n // Mirrors the runtime SubPipeFactory: explicit nb_output wins, then\n // multiple_output, and a batched step is implicitly multiple.\n let outputMultiplicity: SubPipeSpec[\"output_multiplicity\"] =\n intOrNull(raw.nb_output) ?? (raw.multiple_output === true ? true : null);\n if (batchParams !== null && outputMultiplicity === null) outputMultiplicity = true;\n return {\n pipe_code: raw.pipe as string,\n output_name: strOrNull(raw.result),\n output_multiplicity: outputMultiplicity,\n batch_params: batchParams,\n };\n}\n\n/**\n * A binding step's `from` path, and a dotted `batch_over`: a name in working\n * memory followed by zero or more field names, each segment an identifier that\n * does not start with an underscore — the grammar of the standard and of the\n * schema's `BindingStepBlueprint.from`.\n */\nconst BINDING_PATH_RE = /^[A-Za-z][A-Za-z0-9_]*(?:\\.[A-Za-z][A-Za-z0-9_]*)*$/;\n\n/** The keys a binding step may carry: `from` and `result`, both required, nothing else. */\nconst BINDING_STEP_KEYS: ReadonlySet<string> = new Set([\"from\", \"result\"]);\n\n/**\n * The prefix of the private name a sequence binds a dotted `batch_over`'s list\n * under — the runtime's own, reserved so no name an author writes takes it.\n */\nexport const PRIVATE_BINDING_NAME_PREFIX = \"_bound_\";\n\n/**\n * Normalize one binding step, `{ from = \"invoice.total\", result = \"total_amount\" }`,\n * to the shape the runtime holds it in. The runtime refuses a step carrying\n * `pipe` beside `from`, one without `result`, and a `from` breaking the path\n * grammar, so those are skipped with a diagnostic: none of them names a value\n * a later step could read. A pipe step's key carried beside `from` is reported\n * and the binding still drawn, since nothing about what it binds is in doubt.\n */\nfunction normalizeBindingStep(\n raw: Record<string, unknown>,\n pipeCode: string,\n path: string,\n ctx: NormalizePipeContext,\n): BindingStepSpec | null {\n const skip = (why: string): null => {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-binding-step\",\n message: `pipe \"${pipeCode}\": binding step ${why} — skipped`,\n path,\n });\n return null;\n };\n if (raw.pipe !== undefined) return skip(`carries both \"from\" and \"pipe\"`);\n const fromPath = strOrNull(raw.from);\n if (fromPath === null || !BINDING_PATH_RE.test(fromPath)) {\n return skip(`has a \"from\" that is not a path of identifiers separated by dots`);\n }\n const result = strOrNull(raw.result);\n if (result === null) return skip(`binds \"${fromPath}\" under no \"result\"`);\n if (!PLAIN_NAME_RE.test(result)) {\n return skip(\n result.startsWith(PRIVATE_BINDING_NAME_PREFIX)\n ? `binds \"${fromPath}\" under \"${result}\", which takes the prefix \"${PRIVATE_BINDING_NAME_PREFIX}\" the runtime reserves for its own names`\n : `binds \"${fromPath}\" under \"${result}\", which is not a plain name (lowercase letters, digits and underscores, starting with a letter)`,\n );\n }\n const extraKeys = Object.keys(raw).filter((key) => !BINDING_STEP_KEYS.has(key));\n if (extraKeys.length > 0) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-binding-step\",\n message:\n `pipe \"${pipeCode}\": binding step of \"${fromPath}\" carries ` +\n `${extraKeys.map((key) => `\"${key}\"`).join(\", \")}, which a binding step does not take — ignored`,\n path,\n });\n }\n return { from_path: fromPath, output_name: result, is_dotted_batch_over: false };\n}\n\n/** Every name a sequence's inputs and steps write or read — the names a private binding name must not take. */\nfunction namesInSequence(inputNames: string[], rawSteps: unknown[]): Set<string> {\n const names = new Set(inputNames);\n for (const step of rawSteps) {\n if (!isPlainObject(step)) continue;\n if (step.from !== undefined) {\n const fromPath = strOrNull(step.from);\n if (fromPath !== null) names.add(fromPath.split(\".\")[0]);\n const result = strOrNull(step.result);\n if (result !== null) names.add(result);\n continue;\n }\n for (const name of [strOrNull(step.result), strOrNull(step.batch_as)]) {\n if (name !== null) names.add(name);\n }\n const batchOver = strOrNull(step.batch_over);\n if (batchOver !== null) names.add(batchOver.split(\".\")[0]);\n }\n return names;\n}\n\n/**\n * The private name a dotted `batch_over`'s list is bound under: the prefix and\n * the path with its dots turned into underscores (`_bound_catalog_pages`), with\n * `_2`, `_3`… appended when a name of the sequence already holds that spelling.\n * Mirrors the runtime's `make_private_binding_name`, so the static graph names\n * the bound list as a run graph does.\n */\nfunction makePrivateBindingName(path: string, takenNames: Set<string>): string {\n const baseName = `${PRIVATE_BINDING_NAME_PREFIX}${path.replaceAll(\".\", \"_\")}`;\n let name = baseName;\n for (let suffix = 2; takenNames.has(name); suffix++) name = `${baseName}_${suffix}`;\n return name;\n}\n\n/**\n * Normalize a sequence's `steps` to the runtime's `sequential_sub_pipes`: a\n * pipe step, or a binding step for a step carrying `from`. A pipe step whose\n * `batch_over` is a dotted path is held as the runtime holds it — a binding of\n * that path under a private name, followed by the same step batching over the\n * name — so the graph draws a binding followed by the batch.\n */\nfunction normalizeSequenceSteps(\n raw: unknown,\n pipeCode: string,\n inputNames: string[],\n ctx: NormalizePipeContext,\n): SequenceStepSpec[] {\n if (!Array.isArray(raw)) {\n if (raw !== undefined) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-pipe-entry\",\n message: `pipe \"${pipeCode}\": steps is not an array — treated as empty`,\n path: `pipe.${pipeCode}.steps`,\n });\n }\n return [];\n }\n const takenNames = namesInSequence(inputNames, raw);\n const steps: SequenceStepSpec[] = [];\n raw.forEach((entry, index) => {\n const path = `pipe.${pipeCode}.steps[${index}]`;\n if (isPlainObject(entry) && entry.from !== undefined) {\n const binding = normalizeBindingStep(entry, pipeCode, path, ctx);\n if (binding !== null) steps.push(binding);\n return;\n }\n if (!isPlainObject(entry)) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-sub-pipe\",\n message: `pipe \"${pipeCode}\": sub-pipe entry without a \"pipe\" ref — skipped`,\n path,\n });\n return;\n }\n const step = normalizeSubPipe(entry, pipeCode, path, ctx);\n if (step === null) return;\n const listName = step.batch_params?.input_list_stuff_name;\n if (step.batch_params != null && listName !== undefined && listName.includes(\".\")) {\n if (!BINDING_PATH_RE.test(listName)) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-binding-step\",\n message:\n `pipe \"${pipeCode}\": dotted batch_over \"${listName}\" is not a path of identifiers ` +\n `separated by dots — batching over it as a name`,\n path,\n });\n } else {\n const privateName = makePrivateBindingName(listName, takenNames);\n takenNames.add(privateName);\n steps.push({ from_path: listName, output_name: privateName, is_dotted_batch_over: true });\n step.batch_params = { ...step.batch_params, input_list_stuff_name: privateName };\n }\n }\n steps.push(step);\n });\n return steps;\n}\n\n/**\n * Normalize a parallel's `branches`. A branch is always a pipe step: the\n * runtime refuses a binding step there, and a dotted `batch_over`, since only\n * a sequence binds — a branch needing a field gets it bound by a sequence step\n * before the parallel. Both are skipped with a diagnostic.\n */\nfunction normalizeBranchList(\n raw: unknown,\n pipeCode: string,\n ctx: NormalizePipeContext,\n): SubPipeSpec[] {\n if (!Array.isArray(raw)) {\n if (raw !== undefined) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-pipe-entry\",\n message: `pipe \"${pipeCode}\": branches is not an array — treated as empty`,\n path: `pipe.${pipeCode}.branches`,\n });\n }\n return [];\n }\n const branches: SubPipeSpec[] = [];\n raw.forEach((entry, index) => {\n const path = `pipe.${pipeCode}.branches[${index}]`;\n if (!isPlainObject(entry)) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-sub-pipe\",\n message: `pipe \"${pipeCode}\": sub-pipe entry without a \"pipe\" ref — skipped`,\n path,\n });\n return;\n }\n if (entry.from !== undefined) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-binding-step\",\n message:\n `pipe \"${pipeCode}\": a parallel branch cannot be a binding step — ` +\n `bind in a sequence step before the parallel — skipped`,\n path,\n });\n return;\n }\n const branch = normalizeSubPipe(entry, pipeCode, path, ctx);\n if (branch === null) return;\n if (branch.batch_params?.input_list_stuff_name.includes(\".\")) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-binding-step\",\n message:\n `pipe \"${pipeCode}\": a parallel branch cannot batch over the dotted path ` +\n `\"${branch.batch_params.input_list_stuff_name}\" — bind it in a sequence step before ` +\n `the parallel — skipped`,\n path,\n });\n return;\n }\n branches.push(branch);\n });\n return branches;\n}\n\n// ─── Compose construct normalization ─────────────────────────────────────────\n\nfunction normalizeConstructField(value: unknown): PipeComposeConstructField | null {\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n Array.isArray(value)\n ) {\n return { method: \"fixed\", fixed_value: value };\n }\n if (isPlainObject(value)) {\n if (typeof value.from === \"string\") {\n return {\n method: \"from_var\",\n from_path: value.from,\n list_to_dict_keyed_by: strOrNull(value.list_to_dict_keyed_by),\n };\n }\n if (typeof value.template === \"string\") {\n return { method: \"template\", template: value.template };\n }\n const nested = normalizeConstruct(value);\n if (nested !== null) return { method: \"nested\", nested };\n }\n return null;\n}\n\nfunction normalizeConstruct(raw: unknown): PipeComposeConstructBlueprint | null {\n if (!isPlainObject(raw)) return null;\n const fields: Record<string, PipeComposeConstructField> = {};\n for (const [name, value] of Object.entries(raw)) {\n const field = normalizeConstructField(value);\n if (field !== null) fields[name] = field;\n }\n return Object.keys(fields).length > 0 ? { fields } : null;\n}\n\n// ─── PipeJudge question ──────────────────────────────────────────────────────\n\n/**\n * The question a PipeJudge asks, in the runtime's shape. The kind is decided\n * by which of `options` and `levels` the pipe declares, never by a field of its\n * own, and `prompt` is read in place of `question`, as the runtime reads it.\n */\nfunction normalizeJudgmentQuestion(raw: Record<string, unknown>): JudgmentQuestionSpec {\n const instructions = strOrNull(raw.question) ?? strOrNull(raw.prompt) ?? \"\";\n if (isPlainObject(raw.options)) {\n const options: Record<string, string | null> = {};\n for (const [key, description] of Object.entries(raw.options)) {\n options[key] = typeof description === \"string\" ? description : null;\n }\n return { kind: \"choice\", instructions, options };\n }\n if (Array.isArray(raw.levels)) {\n return {\n kind: \"rating\",\n instructions,\n levels: raw.levels.filter((level): level is string => typeof level === \"string\"),\n };\n }\n const criteria = isPlainObject(raw.criteria) ? raw.criteria : {};\n return {\n kind: \"yes_no\",\n instructions,\n yes_criterion: strOrNull(criteria.yes),\n no_criterion: strOrNull(criteria.no),\n };\n}\n\n// ─── The signature contract: `type` on two different surfaces ────────────────\n//\n// `KNOWN_PIPE_TYPES` serves two masters, and pipelex 0.41 made them diverge:\n//\n// - GraphSpec `pipe_type` / the `pipe_registry` dump — `PipeSignature` IS a\n// member. The runtime `PipeSignature.type` serializes normally, so a\n// registry entry does carry `type: \"PipeSignature\"`. `validateGraphSpec`\n// checks against that set and must keep accepting it.\n// - Authored `.mthds` — `PipeSignature` is NOT a member. `PipeSignatureBlueprint`\n// sets `exclude=True` on its tag: a signature has no `type` in `.mthds`,\n// because *omitting the type IS the signature*. It is the sole definition in\n// `data/schema/mthds_schema.json` with no `type` property, which is exactly\n// what discriminates it in the bundle-level `oneOf`.\n//\n// Only this module reads the authored surface, so the split lives here. Mirrors\n// `normalize_typeless_signature_section` in pipelex's `pipe_blueprint.py`.\n\n/**\n * The only keys a typeless section may declare — `PipeSignatureBlueprint.properties`\n * in `data/schema/mthds_schema.json`. Anything else means the author started an\n * implementation and simply has not named its `type` yet.\n */\nconst SIGNATURE_ONLY_KEYS: ReadonlySet<string> = new Set([\n \"description\",\n \"inputs\",\n \"output\",\n \"signature_for\",\n]);\n\n/**\n * Resolve the pipe class from the authored section, reconciling both spellings\n * of a signature. Returns null (with a diagnostic) when the section names no\n * usable class.\n */\nfunction resolvePipeTypeTag(\n code: string,\n raw: Record<string, unknown>,\n ctx: NormalizePipeContext,\n): PipeType | null {\n const typeValue = raw.type;\n\n if (typeValue === undefined) {\n // A typeless section is a signature — but only if it declares nothing\n // beyond the contract, and `output` is present (the schema requires it).\n // Everything else keeps the plain unknown-type error: the schema rejects it too.\n const isSignature =\n raw.output !== undefined && Object.keys(raw).every((key) => SIGNATURE_ONLY_KEYS.has(key));\n if (isSignature) return \"PipeSignature\";\n } else if (typeValue === \"PipeSignature\") {\n // Retired in 0.41. Tolerated with a warning rather than dropped: erroring\n // would delete the pipe from the bundle — and with it the whole calling\n // step — which is the exact hole the typeless branch above exists to close.\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"retired-signature-tag\",\n message:\n `pipe \"${code}\": \\`type = \"PipeSignature\"\\` is no longer a pipe type — delete the ` +\n \"`type` line. A pipe with no `type` and no implementation is a signature (contract only).\",\n path: `pipe.${code}.type`,\n });\n return \"PipeSignature\";\n }\n\n if (typeof typeValue === \"string\" && KNOWN_PIPE_TYPES.has(typeValue)) {\n return typeValue as PipeType;\n }\n\n ctx.diagnostics.push({\n severity: \"error\",\n code: \"unknown-pipe-type\",\n message: `pipe \"${code}\": unknown pipe type ${JSON.stringify(typeValue)} — pipe skipped`,\n path: `pipe.${code}.type`,\n });\n return null;\n}\n\n// ─── Per-type normalization ──────────────────────────────────────────────────\n\n/**\n * Normalize one `[pipe.<code>]` table to its registry blueprint shape.\n * Returns null (with a diagnostic) only when the section names no usable pipe\n * class and is not a signature — everything else degrades field-by-field.\n */\nexport function normalizePipe(\n code: string,\n raw: Record<string, unknown>,\n ctx: NormalizePipeContext,\n): PipeBlueprintUnion | null {\n const typeValue = resolvePipeTypeTag(code, raw, ctx);\n if (typeValue === null) return null;\n const type = typeValue;\n const base = {\n code,\n domain_code: ctx.domain,\n description: strOrNull(raw.description) ?? \"\",\n inputs: normalizeInputs(raw.inputs, code, ctx),\n output: normalizeOutput(raw.output, code, ctx),\n };\n\n switch (type) {\n case \"PipeSequence\":\n return {\n ...base,\n type,\n pipe_category: \"PipeController\",\n sequential_sub_pipes: normalizeSequenceSteps(\n raw.steps,\n code,\n Object.keys(base.inputs),\n ctx,\n ),\n };\n case \"PipeParallel\":\n return {\n ...base,\n type,\n pipe_category: \"PipeController\",\n parallel_sub_pipes: normalizeBranchList(raw.branches, code, ctx),\n add_each_output: raw.add_each_output === true,\n combined_output: strOrNull(raw.combined_output),\n };\n case \"PipeCondition\": {\n const outcomeMap: Record<string, string> = {};\n if (isPlainObject(raw.outcomes)) {\n for (const [outcome, pipeRef] of Object.entries(raw.outcomes)) {\n if (typeof pipeRef === \"string\" && pipeRef.length > 0) {\n outcomeMap[outcome] = pipeRef;\n } else {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-pipe-entry\",\n message: `pipe \"${code}\": outcome \"${outcome}\" is not a pipe ref — skipped`,\n path: `pipe.${code}.outcomes.${outcome}`,\n });\n }\n }\n }\n return {\n ...base,\n type,\n pipe_category: \"PipeController\",\n expression: strOrNull(raw.expression) ?? strOrNull(raw.expression_template) ?? \"\",\n outcome_map: outcomeMap,\n default_outcome: strOrNull(raw.default_outcome) ?? \"\",\n add_alias_from_expression_to: strOrNull(raw.add_alias_from_expression_to),\n };\n }\n case \"PipeBatch\": {\n const branchPipeCode = strOrNull(raw.branch_pipe_code);\n if (branchPipeCode === null) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"invalid-pipe-entry\",\n message: `pipe \"${code}\": PipeBatch without branch_pipe_code`,\n path: `pipe.${code}.branch_pipe_code`,\n });\n }\n return {\n ...base,\n type,\n pipe_category: \"PipeController\",\n branch_pipe_code: branchPipeCode ?? \"\",\n batch_params: {\n input_list_stuff_name: strOrNull(raw.input_list_name) ?? \"\",\n input_item_stuff_name: strOrNull(raw.input_item_name) ?? \"\",\n },\n };\n }\n case \"PipeLLM\": {\n const systemPrompt = strOrNull(raw.system_prompt);\n const prompt = strOrNull(raw.prompt);\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n llm_prompt_spec: {\n system_prompt_blueprint:\n systemPrompt === null ? null : makeTemplate(systemPrompt, \"llm_prompt\"),\n prompt_blueprint: prompt === null ? null : makeTemplate(prompt, \"llm_prompt\"),\n user_image_references: null,\n user_document_references: null,\n system_image_references: null,\n system_document_references: null,\n },\n llm_choices: {\n for_text: modelToString(raw.model),\n for_object: modelToString(raw.model_to_structure),\n },\n structuring_method: strOrNull(raw.structuring_method),\n output_multiplicity: null,\n };\n }\n case \"PipeStructure\": {\n const inputNames = Object.keys(base.inputs);\n const llmChoice = isPlainObject(raw.model) ? raw.model : strOrNull(raw.model);\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n llm_choice: llmChoice,\n text_input_name: inputNames[0] ?? \"text\",\n output_multiplicity: null,\n };\n }\n case \"PipeExtract\": {\n // Mirrors the runtime PipeExtractFactory: the (single) input is either\n // image-like or document-like, and exactly one of the two stuff names is\n // set. Statically, \"compatible with native.Image\" approximates to the\n // concept being Image or refining it; anything else counts as a document.\n const isImageLike = (spec: StuffSpecInfo): boolean =>\n (spec.concept.domain_code === NATIVE_DOMAIN && spec.concept.code === \"Image\") ||\n spec.concept.refines === `${NATIVE_DOMAIN}.Image`;\n const inputEntries = Object.entries(base.inputs);\n const imageInput = inputEntries.find(([, spec]) => isImageLike(spec));\n const documentInput = imageInput === undefined ? inputEntries[0] : undefined;\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n extract_choice: modelToString(raw.model),\n should_caption_images: raw.page_image_captions === true,\n max_page_images: intOrNull(raw.max_page_images),\n should_include_page_views: raw.page_views === true,\n page_views_dpi: intOrNull(raw.page_views_dpi),\n render_js: boolOrNull(raw.render_js),\n include_raw_html: boolOrNull(raw.include_raw_html),\n image_stuff_name: imageInput?.[0] ?? null,\n document_stuff_name: documentInput?.[0] ?? null,\n };\n }\n case \"PipeSearch\":\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n search_choice: modelToString(raw.model),\n prompt_blueprint: makeTemplate(strOrNull(raw.prompt) ?? \"\", \"basic\"),\n include_images_override: boolOrNull(raw.include_images),\n max_results_override: intOrNull(raw.max_results),\n from_date: strOrNull(raw.from_date),\n to_date: strOrNull(raw.to_date),\n include_domains: stringArrayOrNull(raw.include_domains),\n exclude_domains: stringArrayOrNull(raw.exclude_domains),\n is_structured_output: false,\n };\n case \"PipeImgGen\": {\n const prompt = strOrNull(raw.prompt);\n const negativePrompt = strOrNull(raw.negative_prompt);\n const seed = intOrNull(raw.seed) ?? (raw.seed === \"auto\" ? \"auto\" : null);\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n img_gen_prompt_blueprint: {\n prompt_blueprint: prompt === null ? null : makeTemplate(prompt, \"img_gen_prompt\"),\n negative_prompt_blueprint:\n negativePrompt === null ? null : makeTemplate(negativePrompt, \"img_gen_prompt\"),\n image_references: null,\n },\n img_gen_choice: modelToString(raw.model),\n aspect_ratio: strOrNull(raw.aspect_ratio),\n is_raw: boolOrNull(raw.is_raw),\n seed,\n background: strOrNull(raw.background),\n output_format: strOrNull(raw.output_format),\n output_multiplicity:\n typeof base.output.multiplicity === \"number\" ? base.output.multiplicity : 1,\n };\n }\n case \"PipeCompose\": {\n const rawTemplate = raw.template;\n let template: string | null = null;\n let templatingStyle: string | null = null;\n let category = \"basic\";\n let extraContext: Record<string, unknown> | null = null;\n if (typeof rawTemplate === \"string\") {\n template = rawTemplate;\n } else if (isPlainObject(rawTemplate)) {\n template = strOrNull(rawTemplate.template);\n templatingStyle = strOrNull(rawTemplate.templating_style);\n category = strOrNull(rawTemplate.category) ?? category;\n extraContext = isPlainObject(rawTemplate.extra_context) ? rawTemplate.extra_context : null;\n }\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n template,\n templating_style: templatingStyle,\n category,\n extra_context: extraContext,\n construct_blueprint: normalizeConstruct(raw.construct),\n };\n }\n case \"PipeFunc\":\n return { ...base, type, pipe_category: \"PipeOperator\" };\n case \"PipeJudge\":\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n judgment_choice: isPlainObject(raw.model) ? raw.model : strOrNull(raw.model),\n judgment_question: normalizeJudgmentQuestion(raw),\n threshold: typeof raw.threshold === \"number\" ? raw.threshold : null,\n };\n case \"PipeDocGen\":\n return {\n ...base,\n type,\n pipe_category: \"PipeOperator\",\n doc_gen_format: strOrNull(raw.format) ?? \"\",\n doc_gen_choice: isPlainObject(raw.model) ? raw.model : strOrNull(raw.model),\n template: strOrNull(raw.template),\n template_file: strOrNull(raw.template_file),\n filename: strOrNull(raw.filename),\n };\n case \"PipeSignature\": {\n const signatureFor = strOrNull(raw.signature_for);\n // `PipeSignature` itself is excluded: it is no longer a member of pipelex's\n // `PipeType`, so `signature_for = \"PipeSignature\"` is rejected upstream.\n return {\n ...base,\n type,\n pipe_category: null,\n signature_for:\n signatureFor !== null &&\n signatureFor !== \"PipeSignature\" &&\n KNOWN_PIPE_TYPES.has(signatureFor)\n ? (signatureFor as PipeType)\n : null,\n };\n }\n default: {\n const _exhaustive: never = type;\n return _exhaustive;\n }\n }\n}\n","// ─── mergeBundles: ParsedBundle[] → MergedMethodSet ──────────────────────────\n// A method package may span several `.mthds` files; files sharing a domain\n// merge into one namespace. Duplicate codes keep the first declaration and\n// record a diagnostic — except when a pipe signature meets its concrete\n// definition, which is the multi-file idiom rather than a duplication: the\n// concrete wins whichever file it came from, and nothing is reported unless the\n// two halves disagree about the pipe type the signature promised. After\n// merging, io concept stubs are re-pointed at the declarations that other files\n// contributed (a pipe in file A can reference a concept declared in file B).\n\nimport type { ConceptInfo, PipeBlueprintUnion, StuffSpecInfo } from \"@graph/types\";\n\nimport type {\n ConceptStructure,\n Diagnostic,\n DomainNamespace,\n MergedMethodSet,\n ParsedBundle,\n} from \"./types\";\nimport { authoredRecord, UNKNOWN_DOMAIN } from \"./types\";\n\nfunction enrichPipeConcepts(\n pipe: PipeBlueprintUnion,\n domains: Record<string, DomainNamespace>,\n): PipeBlueprintUnion {\n const enrichSpec = (spec: StuffSpecInfo): StuffSpecInfo => {\n const declared = domains[spec.concept.domain_code]?.concepts[spec.concept.code];\n return declared !== undefined && declared !== spec.concept\n ? { ...spec, concept: declared }\n : spec;\n };\n const inputs = authoredRecord<StuffSpecInfo>();\n for (const [name, spec] of Object.entries(pipe.inputs)) {\n inputs[name] = enrichSpec(spec);\n }\n return { ...pipe, inputs, output: enrichSpec(pipe.output) };\n}\n\n/**\n * Merge parsed bundles into one namespace per domain. Order matters: on\n * duplicate codes the first bundle wins. `mainDomain` and `mainPipe` are taken\n * together from the first bundle declaring `main_pipe`, so a bare entry ref\n * always resolves in its declaring bundle's namespace; when no bundle declares\n * one, `mainDomain` falls back to the first domained bundle. `description`\n * comes from the first bundle that declares it.\n */\nexport function mergeBundles(bundles: ParsedBundle[]): MergedMethodSet {\n const diagnostics: Diagnostic[] = [];\n const domains = authoredRecord<DomainNamespace>();\n let mainDomain: string | null = null;\n let mainPipe: string | null = null;\n let description: string | null = null;\n\n for (const bundle of bundles) {\n const domain = bundle.domain ?? UNKNOWN_DOMAIN;\n const namespace = (domains[domain] ??= {\n domain,\n concepts: authoredRecord<ConceptInfo>(),\n structures: authoredRecord<ConceptStructure>(),\n pipes: authoredRecord<PipeBlueprintUnion>(),\n });\n if (mainDomain === null && bundle.domain !== null) mainDomain = bundle.domain;\n if (mainPipe === null && bundle.main_pipe !== null) {\n mainPipe = bundle.main_pipe;\n // A bare main_pipe must resolve in the namespace of the bundle declaring\n // it, not whichever bundle happened to come first.\n mainDomain = domain;\n }\n if (description === null && bundle.description !== null) description = bundle.description;\n\n for (const [code, concept] of Object.entries(bundle.concepts)) {\n if (code in namespace.concepts) {\n diagnostics.push({\n severity: \"warning\",\n code: \"duplicate-concept\",\n message: `concept \"${domain}.${code}\" declared more than once — keeping the first declaration`,\n path: `concept.${code}`,\n domain_code: domain,\n });\n continue;\n }\n namespace.concepts[code] = concept;\n // The structure travels with the declaration it belongs to: keep-first, like the concept.\n if (Object.hasOwn(bundle.structures, code)) {\n namespace.structures[code] = bundle.structures[code];\n }\n }\n for (const [code, pipe] of Object.entries(bundle.pipes)) {\n const existing = namespace.pipes[code];\n if (existing === undefined) {\n namespace.pipes[code] = pipe;\n continue;\n }\n // A signature is a forward declaration; the concrete pipe of the same code\n // is its definition, not a duplicate of it. Which file each landed in — and\n // therefore which one the merge sees first — is an authoring choice, so the\n // concrete always wins.\n const existingIsSignature = existing.type === \"PipeSignature\";\n const incomingIsSignature = pipe.type === \"PipeSignature\";\n if (existingIsSignature !== incomingIsSignature) {\n const signature = existing.type === \"PipeSignature\" ? existing : pipe;\n const concrete = existing.type === \"PipeSignature\" ? pipe : existing;\n if (existingIsSignature) namespace.pipes[code] = pipe;\n // Silent only when the two halves agree. `signature_for` is the type the\n // forward declaration promised, and it is an optional hint — an absent one\n // has nothing to disagree with. A present one naming a different type means\n // the package did not honour its own contract, and the merge is the only\n // place that ever sees both halves at once. The concrete still wins: it is\n // the implementation, and a renderer's job is to draw what was built.\n const promised =\n signature.type === \"PipeSignature\" ? (signature.signature_for ?? null) : null;\n if (promised !== null && promised !== concrete.type) {\n diagnostics.push({\n severity: \"warning\",\n code: \"signature-type-mismatch\",\n message:\n `pipe \"${domain}.${code}\": the signature promises \\`signature_for = \"${promised}\"\\` ` +\n `but the concrete definition is a ${concrete.type} — using the concrete definition`,\n path: `pipe.${code}`,\n domain_code: domain,\n });\n }\n continue;\n }\n diagnostics.push({\n severity: \"warning\",\n code: \"duplicate-pipe\",\n message: `pipe \"${domain}.${code}\" declared more than once — keeping the first declaration`,\n path: `pipe.${code}`,\n domain_code: domain,\n });\n }\n }\n\n for (const namespace of Object.values(domains)) {\n for (const [code, pipe] of Object.entries(namespace.pipes)) {\n namespace.pipes[code] = enrichPipeConcepts(pipe, domains);\n }\n }\n\n return { domains, mainDomain, mainPipe, description, diagnostics };\n}\n","// ─── The binding walk: the concept a binding step's `from` path reaches ──────\n// A binding step `{ from = \"invoice.total\", result = \"total_amount\" }` stores\n// the value at a path under a new name, and the concept of that value is read\n// off declared structures alone, one segment at a time:\n//\n// | The segment names a field declared as | The walk continues into, or the result is |\n// | -------------------------------------------- | ----------------------------------------- |\n// | `concept`, `concept_ref = X` | `X`, whose structure the next segment walks |\n// | `list`, `item_type = \"concept\"`, `item_concept_ref = X` | `X`, crossing a list |\n// | `text`, or no `type` (a field of `choices`) | `native.Text`, a leaf |\n// | `number` or `integer` | `native.Number`, a leaf |\n// | `boolean` | `native.YesNo`, a leaf |\n// | `date` or `datetime` | `native.Date`, a leaf |\n// | `time` | `native.Time`, a leaf |\n// | `dict` | `native.JSON`, a leaf |\n// | `list` with a scalar `item_type` | that scalar's native, a leaf, crossing a list |\n//\n// Crossing any list, or starting from a plural root, makes the result a list;\n// a bare name keeps its root's concept and multiplicity. This mirrors the\n// runtime's derivation walk over a bundle's own blueprints, so the static graph\n// types a binding's result as a run graph does. It is pure and never throws:\n// a path it cannot walk comes back as a reason, which the builder reports.\n\nimport type { ConceptInfo, StuffMultiplicity } from \"@graph/types\";\nimport { isPluralMultiplicity } from \"@graph/types\";\n\nimport {\n isNativeConceptCode,\n NATIVE_DOMAIN,\n nativeConceptFields,\n resolveConceptInfo,\n} from \"./conceptRefs\";\nimport type { MergedMethodSet, StructureField } from \"./types\";\n\n/** The root's concept and multiplicity, as the sequence knows them at the binding step. */\nexport interface BindingRoot {\n concept: ConceptInfo;\n multiplicity: StuffMultiplicity;\n}\n\nexport type BindingDerivation =\n | { kind: \"derived\"; concept: ConceptInfo; multiplicity: StuffMultiplicity }\n | { kind: \"unresolved\"; reason: string };\n\n// ─── What the walk sees of a concept ─────────────────────────────────────────\n\ntype WalkableConcept =\n | { shape: \"structure\"; ref: string; fields: Readonly<Record<string, StructureField>> }\n /** A leaf: a single-field native, or a concept refining one, with why. */\n | { shape: \"value\"; ref: string; reason: string }\n /** Nothing to walk: a structureless native, a concept declaring no structure, or one nothing resolves, with why. */\n | { shape: \"no-structure\"; ref: string; reason: string };\n\nconst SINGLE_FIELD_NATIVE_REASON = \"holds its value in a single field\";\nconst DESCRIBED_ONLY_REASON = \"is declared with neither a structure nor refines\";\n\n/** Split a domain-qualified ref (`a.b.Code`) at its last dot. */\nfunction splitRef(ref: string): { domain: string; code: string } {\n const dot = ref.lastIndexOf(\".\");\n return { domain: ref.slice(0, dot), code: ref.slice(dot + 1) };\n}\n\n/**\n * A concept ref as a structure field writes it, made domain-qualified in the\n * declaring concept's domain, as the runtime qualifies it: a native's code\n * (bare or `native.`-prefixed) names the native, a dotted ref names its\n * domain, and a bare ref the declaring domain. A dependency ref\n * (`alias->domain.Code`) is left as written, and nothing resolves it here.\n */\nfunction qualifyFieldRef(ref: string, domain: string): string {\n if (ref.includes(\"->\")) return ref;\n if (ref.startsWith(`${NATIVE_DOMAIN}.`)) return ref;\n if (!ref.includes(\".\"))\n return isNativeConceptCode(ref) ? `${NATIVE_DOMAIN}.${ref}` : `${domain}.${ref}`;\n return ref;\n}\n\nfunction resolveWalkable(\n set: MergedMethodSet,\n ref: string,\n visited: ReadonlySet<string> = new Set(),\n): WalkableConcept {\n if (ref.includes(\"->\")) {\n return {\n shape: \"no-structure\",\n ref,\n reason: \"belongs to a dependency, which a method's own bundles do not show\",\n };\n }\n const { domain, code } = splitRef(ref);\n if (domain === NATIVE_DOMAIN) {\n // A native is walked through its pinned fields, which the catalog holds\n // beside its description, so what resolves as a native is what walks as one.\n if (!isNativeConceptCode(code)) {\n return { shape: \"no-structure\", ref, reason: \"is not a native concept\" };\n }\n const fields = nativeConceptFields(code);\n if (fields === null) {\n return { shape: \"no-structure\", ref, reason: \"is structureless by definition\" };\n }\n if (Object.keys(fields).length === 1) {\n return { shape: \"value\", ref, reason: SINGLE_FIELD_NATIVE_REASON };\n }\n return { shape: \"structure\", ref, fields };\n }\n if (visited.has(ref))\n return { shape: \"no-structure\", ref, reason: \"refines itself through a cycle\" };\n const namespace = set.domains[domain];\n const concept =\n namespace !== undefined && Object.hasOwn(namespace.concepts, code)\n ? namespace.concepts[code]\n : undefined;\n if (namespace === undefined || concept === undefined) {\n return { shape: \"no-structure\", ref, reason: \"is not declared in this method\" };\n }\n const structure = Object.hasOwn(namespace.structures, code)\n ? namespace.structures[code]\n : undefined;\n if (typeof structure === \"string\") {\n return {\n shape: \"no-structure\",\n ref,\n reason: \"has a Python class for a structure, which a bundle does not show\",\n };\n }\n if (structure !== undefined) {\n const fields: Record<string, StructureField> = Object.create(null) as Record<\n string,\n StructureField\n >;\n for (const [name, declared] of Object.entries(structure)) {\n fields[name] = {\n ...declared,\n conceptRef:\n declared.conceptRef === null ? null : qualifyFieldRef(declared.conceptRef, domain),\n itemConceptRef:\n declared.itemConceptRef === null\n ? null\n : qualifyFieldRef(declared.itemConceptRef, domain),\n };\n }\n return { shape: \"structure\", ref, fields };\n }\n if (concept.refines != null) {\n // A refinement inherits the structure it refines, or the leaf or void it refines.\n const refined = resolveWalkable(set, concept.refines, new Set([...visited, ref]));\n if (refined.shape === \"structure\") return { shape: \"structure\", ref, fields: refined.fields };\n const reason = `refines '${refined.ref}', which ${refined.reason}`;\n return refined.shape === \"value\"\n ? { shape: \"value\", ref, reason }\n : { shape: \"no-structure\", ref, reason };\n }\n return { shape: \"no-structure\", ref, reason: DESCRIBED_ONLY_REASON };\n}\n\n// ─── One field, as a step of the walk ────────────────────────────────────────\n\n/** The native a plain field type is stored as, or null for `concept`, `list` and a type the standard lacks. */\nconst SCALAR_NATIVE: Readonly<Record<string, string>> = {\n text: \"Text\",\n number: \"Number\",\n integer: \"Number\",\n boolean: \"YesNo\",\n date: \"Date\",\n datetime: \"Date\",\n time: \"Time\",\n dict: \"JSON\",\n};\n\ntype FieldStep =\n /** The field holds a concept's content: walk on into it, or end on it. */\n | { kind: \"concept\"; ref: string | null; crossesList: boolean }\n /** The field holds a plain value, stored as this native: a leaf. */\n | { kind: \"leaf\"; nativeCode: string; crossesList: boolean; description: string }\n /** No concept exists for what the field holds. */\n | { kind: \"underivable\"; crossesList: boolean; reason: string };\n\nfunction fieldStep(declared: StructureField): FieldStep {\n // A field declared by its `choices` alone holds one of them, a text.\n const type = declared.type ?? \"text\";\n if (type === \"concept\") return { kind: \"concept\", ref: declared.conceptRef, crossesList: false };\n if (type === \"list\") {\n const itemType = declared.itemType;\n if (itemType === null) {\n return { kind: \"underivable\", crossesList: true, reason: \"the list declares no item_type\" };\n }\n if (itemType === \"concept\") {\n return { kind: \"concept\", ref: declared.itemConceptRef, crossesList: true };\n }\n const nativeCode = Object.hasOwn(SCALAR_NATIVE, itemType) ? SCALAR_NATIVE[itemType] : null;\n if (nativeCode === null) {\n return {\n kind: \"underivable\",\n crossesList: true,\n reason: `the list's item_type '${itemType}' derives no concept`,\n };\n }\n return { kind: \"leaf\", nativeCode, crossesList: true, description: `a list of ${itemType}` };\n }\n const nativeCode = Object.hasOwn(SCALAR_NATIVE, type) ? SCALAR_NATIVE[type] : null;\n if (nativeCode === null) {\n return {\n kind: \"underivable\",\n crossesList: false,\n reason: `its type '${type}' derives no concept`,\n };\n }\n return { kind: \"leaf\", nativeCode, crossesList: false, description: `a ${type} field` };\n}\n\n/** The `ConceptInfo` a derived ref names: a declared concept, a native, or a best-effort stub. */\nfunction conceptInfoForRef(set: MergedMethodSet, ref: string): ConceptInfo {\n const { domain, code } = splitRef(ref);\n return resolveConceptInfo(\n { domain, code, multiplicity: null, presence: \"plain\" },\n domain,\n set.domains[domain]?.concepts ?? {},\n );\n}\n\nfunction conceptRefOf(concept: ConceptInfo): string {\n return `${concept.domain_code}.${concept.code}`;\n}\n\n// ─── The walk ────────────────────────────────────────────────────────────────\n\n/**\n * Walk a binding step's `from` path through the structures the method's\n * bundles declare, and derive the concept and multiplicity of what the step\n * binds. `path` already follows the path grammar; `root` is what the sequence\n * holds under the path's first segment at the step.\n */\nexport function deriveBinding(\n set: MergedMethodSet,\n path: string,\n root: BindingRoot,\n): BindingDerivation {\n const segments = path.split(\".\").slice(1);\n // A bare name binds a renamed copy of the whole value, concept and multiplicity unchanged.\n if (segments.length === 0) {\n return { kind: \"derived\", concept: root.concept, multiplicity: root.multiplicity };\n }\n\n let crossesAnyList = isPluralMultiplicity(root.multiplicity);\n let reachedPath = path.split(\".\")[0];\n let current: WalkableConcept | null = resolveWalkable(set, conceptRefOf(root.concept));\n let leafDescription: string | null = null;\n let derivedRef = conceptRefOf(root.concept);\n const fail = (reason: string): BindingDerivation => ({\n kind: \"unresolved\",\n reason: `cannot bind '${path}': ${reason}`,\n });\n\n for (const [index, segment] of segments.entries()) {\n if (leafDescription !== null) {\n return fail(\n `'${reachedPath}' is ${leafDescription}, a leaf holding a plain value, so the segment '${segment}' cannot follow it`,\n );\n }\n if (current === null) {\n return fail(\n `nothing is known of '${reachedPath}', so the segment '${segment}' cannot be walked`,\n );\n }\n if (current.shape === \"value\") {\n return fail(\n `'${reachedPath}' holds a '${current.ref}', which ${current.reason}, so it is a leaf and the segment '${segment}' cannot follow it`,\n );\n }\n if (current.shape === \"no-structure\") {\n return fail(\n `'${reachedPath}' holds a '${current.ref}', which ${current.reason}, so the segment '${segment}' has no structure to walk`,\n );\n }\n const declared = Object.hasOwn(current.fields, segment) ? current.fields[segment] : undefined;\n if (declared === undefined) {\n const names = Object.keys(current.fields);\n return fail(\n `'${reachedPath}' holds a '${current.ref}', which has no field '${segment}'` +\n (names.length > 0\n ? ` (its fields are ${names.map((name) => `'${name}'`).join(\", \")})`\n : \"\"),\n );\n }\n\n reachedPath = `${reachedPath}.${segment}`;\n const isLast = index === segments.length - 1;\n const step = fieldStep(declared);\n if (step.crossesList) crossesAnyList = true;\n switch (step.kind) {\n case \"underivable\":\n return fail(`'${reachedPath}' derives no concept, since ${step.reason}`);\n case \"concept\":\n if (step.ref === null) return fail(`the concept field '${reachedPath}' names no concept`);\n derivedRef = step.ref;\n current = isLast ? null : resolveWalkable(set, step.ref);\n break;\n case \"leaf\":\n derivedRef = `${NATIVE_DOMAIN}.${step.nativeCode}`;\n leafDescription = step.description;\n current = null;\n break;\n }\n }\n\n return {\n kind: \"derived\",\n concept: conceptInfoForRef(set, derivedRef),\n multiplicity: crossesAnyList ? true : null,\n };\n}\n","// ─── Static graph builder: MergedMethodSet → GraphSpec ──────────────────────\n// The static walk: walk pipe *invocations* starting at the entry pipe,\n// maintaining a scope (the static mirror of working memory), and emit a\n// GraphSpec with `meta.mode: \"static\"` that the existing GraphViewer renders\n// unchanged.\n//\n// Identity is deterministic: node ids are invocation paths\n// (`screening.process_cv/step_2/...`) and stuff digests are the raw strings\n// `<producer_node_id>:<name>` (external inputs: `input:<name>`). The UI treats\n// digests as opaque unique keys, so the raw string — collision-free by\n// construction and readable in snapshots — is preferred over a hash.\n//\n// A sequence's binding step (`{ from = \"invoice.total\", result = \"total\" }`)\n// is a node of its own, of kind `binding`, as in a run graph: it reads the\n// root's stuff and produces the bound one, whose concept the binding walk\n// derives from declared structures (`bindingWalk.ts`).\n//\n// Everything is best-effort: unresolvable refs skip the child, cycles render\n// as leaves, dependency-alias refs (`alias->pipe`) render as opaque leaf\n// cards, and a path the walk cannot follow binds `native.Anything` with a\n// diagnostic. This module never throws on content.\n\nimport type {\n BindingStepSpec,\n ConceptInfo,\n GraphSpec,\n GraphSpecEdge,\n GraphSpecEdgeKind,\n GraphSpecNode,\n GraphSpecNodeIoItem,\n NodePipeType,\n PipeBatchBlueprint,\n PipeBlueprintUnion,\n PipeConditionBlueprint,\n PipeParallelBlueprint,\n PipeSequenceBlueprint,\n StuffMultiplicity,\n StuffSpecInfo,\n SubPipeSpec,\n} from \"@graph/types\";\nimport { BINDING_STEP_TYPE, isBindingStepSpec, isPluralMultiplicity } from \"@graph/types\";\n\nimport { deriveBinding } from \"./bindingWalk\";\nimport { nativeConceptInfo } from \"./conceptRefs\";\nimport { mergeBundles } from \"./mergeBundles\";\nimport { parseMthdsBundle } from \"./parseMthdsBundle\";\nimport type { Diagnostic, DomainNamespace, MergedMethodSet } from \"./types\";\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\nexport interface StaticGraphOptions {\n /**\n * Pipe ref to walk from (`code` or `domain.code`). Defaults to the merged\n * set's `main_pipe`, falling back to a root heuristic (first pipe no other\n * pipe references) when none is declared.\n */\n entryPipe?: string;\n}\n\nexport interface StaticGraphResult {\n spec: GraphSpec;\n diagnostics: Diagnostic[];\n}\n\n/** Build a static GraphSpec from an already-parsed, merged method set. */\nexport function buildStaticGraphSpec(\n set: MergedMethodSet,\n options: StaticGraphOptions = {},\n): StaticGraphResult {\n const diagnostics: Diagnostic[] = [];\n const ctx: WalkCtx = {\n set,\n nodes: [],\n edges: [],\n pipeRegistry: {},\n conceptRegistry: {},\n stuffByDigest: new Map(),\n diagnostics,\n stack: [],\n edgeSeq: 0,\n };\n\n // Registries carry every parsed entry (the dry-run path often ships them\n // empty — populating them is what makes detail panels rich). Registered\n // before the walk so synthetic entries minted during it never clobber a\n // declared one.\n for (const namespace of Object.values(set.domains)) {\n for (const concept of Object.values(namespace.concepts)) registerConcept(ctx, concept);\n for (const pipe of Object.values(namespace.pipes)) {\n ctx.pipeRegistry[`${pipe.domain_code}.${pipe.code}`] = pipe;\n for (const spec of Object.values(pipe.inputs)) registerConcept(ctx, spec.concept);\n registerConcept(ctx, pipe.output.concept);\n }\n }\n\n const entry = pickEntryPipe(set, options.entryPipe ?? null, diagnostics);\n if (entry !== null) {\n walkPipe(ctx, entry.code, entry.domain, `${entry.domain}.${entry.code}`, null, new Map(), {\n resultName: null,\n outputMultiplicity: null,\n });\n }\n\n const spec: GraphSpec = {\n nodes: ctx.nodes,\n edges: ctx.edges,\n meta: { format: \"mthds\", mode: \"static\" },\n pipe_registry: ctx.pipeRegistry,\n concept_registry: ctx.conceptRegistry,\n };\n if (entry !== null) {\n spec.pipeline_ref = { domain: entry.domain, main_pipe: entry.code };\n }\n return { spec, diagnostics };\n}\n\n/**\n * Convenience wrapper: parse one or more `.mthds` TOML strings, merge them,\n * and build the static GraphSpec. Diagnostics from all three stages are\n * concatenated in order (parse, merge, build).\n */\nexport function buildStaticGraphSpecFromToml(\n tomlTexts: string | string[],\n options: StaticGraphOptions = {},\n): StaticGraphResult {\n const texts = Array.isArray(tomlTexts) ? tomlTexts : [tomlTexts];\n const parsed = texts.map((text) => parseMthdsBundle(text));\n const merged = mergeBundles(parsed.map((result) => result.bundle));\n const built = buildStaticGraphSpec(merged, options);\n return {\n spec: built.spec,\n diagnostics: [\n ...parsed.flatMap((result) => result.diagnostics),\n ...merged.diagnostics,\n ...built.diagnostics,\n ],\n };\n}\n\n// ─── Walk state ──────────────────────────────────────────────────────────────\n\n/** A scope entry — the static mirror of a working-memory stuff. */\ninterface StuffRecord {\n digest: string;\n name: string;\n concept: ConceptInfo;\n multiplicity: StuffMultiplicity;\n}\n\ntype Scope = Map<string, StuffRecord>;\n\ninterface WalkCtx {\n set: MergedMethodSet;\n nodes: GraphSpecNode[];\n edges: GraphSpecEdge[];\n pipeRegistry: Record<string, PipeBlueprintUnion>;\n conceptRegistry: Record<string, ConceptInfo>;\n stuffByDigest: Map<string, StuffRecord>;\n diagnostics: Diagnostic[];\n /** Qualified refs (`domain.code`) on the recursion stack — the cycle guard. */\n stack: string[];\n edgeSeq: number;\n}\n\n/** How a pipe is being invoked — the step/branch/outcome context. */\ninterface Invocation {\n /** The enclosing step's `result` name — names the operator's output stuff. */\n resultName: string | null;\n /** The enclosing step's `nb_output`/`multiple_output` override. */\n outputMultiplicity: SubPipeSpec[\"output_multiplicity\"];\n /** Set on condition children: the outcome value that routes here. */\n outcomeValue?: string;\n}\n\ninterface WalkResult {\n nodeId: string;\n /** Primary output stuff — what a sequence step's `result` binds to. */\n output: StuffRecord | null;\n /** Extra bindings a parallel with `add_each_output` exposes to the enclosing scope. */\n eachOutputs: [string, StuffRecord][];\n}\n\n// ─── Entry pipe selection ────────────────────────────────────────────────────\n\ntype PipeResolution =\n | { kind: \"resolved\"; blueprint: PipeBlueprintUnion; domain: string; code: string }\n | { kind: \"opaque\" }\n | { kind: \"unresolved\" };\n\n/**\n * Resolve a pipe ref against the merged set: bare refs in the current domain\n * (same-domain files are already merged into one namespace), `domain.code`\n * refs in the named domain. `alias->…` dependency refs are opaque in phase 1.\n */\nfunction resolvePipeRef(set: MergedMethodSet, ref: string, currentDomain: string): PipeResolution {\n if (ref.includes(\"->\")) return { kind: \"opaque\" };\n const dot = ref.lastIndexOf(\".\");\n const domain = dot === -1 ? currentDomain : ref.slice(0, dot);\n const code = dot === -1 ? ref : ref.slice(dot + 1);\n const blueprint = set.domains[domain]?.pipes[code];\n if (blueprint === undefined) return { kind: \"unresolved\" };\n return { kind: \"resolved\", blueprint, domain, code };\n}\n\n/** Sub-pipe refs appearing anywhere in a namespace — used by the root heuristic. */\nfunction referencedPipeCodes(namespace: DomainNamespace): Set<string> {\n const refs = new Set<string>();\n // Refs are authored strings: bare (`helper`) or qualified (`domain.helper`).\n // Reduce them to bare codes in this namespace, mirroring resolvePipeRef —\n // cross-domain and `alias->` refs can't name a pipe here, so they're dropped.\n const add = (ref: string): void => {\n if (ref === \"\" || ref.includes(\"->\")) return;\n const dot = ref.lastIndexOf(\".\");\n if (dot === -1) refs.add(ref);\n else if (ref.slice(0, dot) === namespace.domain) refs.add(ref.slice(dot + 1));\n };\n for (const pipe of Object.values(namespace.pipes)) {\n switch (pipe.type) {\n case \"PipeSequence\":\n for (const step of pipe.sequential_sub_pipes) {\n // A binding step runs no pipe, so it references none.\n if (!isBindingStepSpec(step)) add(step.pipe_code);\n }\n break;\n case \"PipeParallel\":\n for (const sub of pipe.parallel_sub_pipes) add(sub.pipe_code);\n break;\n case \"PipeCondition\":\n for (const target of Object.values(pipe.outcome_map)) add(target);\n add(pipe.default_outcome);\n break;\n case \"PipeBatch\":\n add(pipe.branch_pipe_code);\n break;\n default:\n break;\n }\n }\n return refs;\n}\n\nfunction pickEntryPipe(\n set: MergedMethodSet,\n explicitRef: string | null,\n diagnostics: Diagnostic[],\n): { domain: string; code: string } | null {\n const domainsInOrder = Object.keys(set.domains);\n const fallbackDomain = set.mainDomain ?? domainsInOrder[0];\n if (fallbackDomain === undefined) {\n diagnostics.push({\n severity: \"error\",\n code: \"no-entry-pipe\",\n message: \"no bundles to build a graph from\",\n });\n return null;\n }\n\n const resolveEntry = (ref: string): { domain: string; code: string } | null => {\n const resolution = resolvePipeRef(set, ref, fallbackDomain);\n return resolution.kind === \"resolved\"\n ? { domain: resolution.domain, code: resolution.code }\n : null;\n };\n\n if (explicitRef !== null) {\n const entry = resolveEntry(explicitRef);\n if (entry === null) {\n diagnostics.push({\n severity: \"error\",\n code: \"unresolved-pipe-ref\",\n message: `entry pipe \"${explicitRef}\" not found in the method set`,\n });\n }\n return entry;\n }\n\n if (set.mainPipe !== null) {\n const entry = resolveEntry(set.mainPipe);\n if (entry !== null) return entry;\n diagnostics.push({\n severity: \"warning\",\n code: \"unresolved-pipe-ref\",\n message: `main_pipe \"${set.mainPipe}\" not found — falling back to a root heuristic`,\n // The owning bundle is known (the namespace that declares this main_pipe),\n // so stamp it — this is not an ownerless diagnostic.\n domain_code: fallbackDomain,\n });\n } else {\n diagnostics.push({\n severity: \"warning\",\n code: \"missing-main-pipe\",\n message: \"no main_pipe declared — falling back to a root heuristic\",\n domain_code: fallbackDomain,\n });\n }\n\n // Root heuristic: the first pipe (declaration order) that no other pipe in\n // its domain references; else the first pipe. Keeps half-written bundles\n // rendering something sensible.\n const domainWithPipes = [fallbackDomain, ...domainsInOrder].find(\n (domain) => Object.keys(set.domains[domain]?.pipes ?? {}).length > 0,\n );\n if (domainWithPipes === undefined) {\n diagnostics.push({\n severity: \"error\",\n code: \"no-entry-pipe\",\n message: \"no pipes found in any bundle\",\n });\n return null;\n }\n const namespace = set.domains[domainWithPipes];\n const referenced = referencedPipeCodes(namespace);\n const codes = Object.keys(namespace.pipes);\n const root = codes.find((code) => !referenced.has(code)) ?? codes[0];\n return { domain: domainWithPipes, code: root };\n}\n\n// ─── Small helpers ───────────────────────────────────────────────────────────\n\n/** `CamelCase` concept code → `snake_case` stuff name (the runtime's fallback naming). */\nfunction snakeCase(code: string): string {\n return code\n .replace(/([A-Z]+)([A-Z][a-z0-9])/g, \"$1_$2\")\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .toLowerCase();\n}\n\nfunction registerConcept(ctx: WalkCtx, concept: ConceptInfo): void {\n ctx.conceptRegistry[`${concept.domain_code}.${concept.code}`] ??= concept;\n}\n\n/**\n * Mint (or return the already-minted) stuff for a digest. First mint wins —\n * matching how the UI's stuff registry keeps the first occurrence per digest.\n */\nfunction mintStuff(\n ctx: WalkCtx,\n digest: string,\n name: string,\n concept: ConceptInfo,\n multiplicity: StuffSpecInfo[\"multiplicity\"],\n): StuffRecord {\n const existing = ctx.stuffByDigest.get(digest);\n if (existing !== undefined) return existing;\n const record: StuffRecord = { digest, name, concept, multiplicity: multiplicity ?? null };\n ctx.stuffByDigest.set(digest, record);\n registerConcept(ctx, concept);\n return record;\n}\n\n/**\n * An io item for `stuff`, optionally exposed under a *slot name* — the name\n * the invoking step binds it to (`result = \"x\"`). The runtime names a\n * controller's transparent output by its slot, while the producing operator\n * keeps the local name; the UI's stuff registry is first-occurrence-wins and\n * controllers are emitted before their children, so the slot name is what\n * renders (verified against the dry fixtures).\n */\nfunction ioItem(stuff: StuffRecord, slotName?: string | null): GraphSpecNodeIoItem {\n const item: GraphSpecNodeIoItem = {\n name: slotName ?? stuff.name,\n digest: stuff.digest,\n concept: stuff.concept.code,\n };\n // Carried only on a plural stuff, so a single-valued io item stays exactly as it was.\n if (isPluralMultiplicity(stuff.multiplicity)) item.multiplicity = stuff.multiplicity;\n return item;\n}\n\nfunction addEdge(\n ctx: WalkCtx,\n kind: GraphSpecEdgeKind,\n source: string,\n target: string,\n extras?: { label?: string; sourceStuff?: string; targetStuff?: string },\n): void {\n // Namespaced ids: the rendering pipeline synthesizes its own dataflow edges\n // named `edge_<n>` (graphBuilders.ts), so bare `edge_<n>` here would collide\n // in the ReactFlow key space.\n const edge: GraphSpecEdge = { id: `static:edge_${ctx.edgeSeq++}`, source, target, kind };\n if (extras?.label !== undefined) edge.label = extras.label;\n if (extras?.sourceStuff !== undefined) edge.source_stuff_digest = extras.sourceStuff;\n if (extras?.targetStuff !== undefined) edge.target_stuff_digest = extras.targetStuff;\n ctx.edges.push(edge);\n}\n\nfunction addNodeTag(node: GraphSpecNode, key: string, value: string): void {\n node.tags = { ...(node.tags ?? {}), [key]: value };\n}\n\nfunction formatBatchMultiplicity(multiplicity: number | boolean | null | undefined): string {\n if (typeof multiplicity === \"number\") return `x${multiplicity}`;\n if (multiplicity === true) return \"xmany\";\n return \"x?\";\n}\n\nfunction conceptKey(concept: ConceptInfo): string {\n return `${concept.domain_code}.${concept.code}`;\n}\n\n/**\n * Bind the invoked pipe's declared inputs from the caller's scope. A name the\n * scope cannot satisfy is a *dangling* input: mint an input stuff\n * (`input:<name>`) with the declared concept — at the method root these are\n * exactly the method's external inputs, and the UI classifies producer-less\n * stuff as role `input`. The `input:` digest namespace is method-global on\n * purpose: an unbound name means the same missing working-memory entry\n * wherever it is read, so all its consumers share one stuff. When two\n * consumers declare *different* concepts for that shared name, the first\n * mint wins and a diagnostic surfaces the authoring inconsistency.\n *\n * Minted dangling inputs are written into `scope`: working memory is one flat\n * namespace shared down the walk (see the scope model note on `walkPipe`), so\n * later readers of the same name bind the same record.\n */\nfunction bindInputs(\n ctx: WalkCtx,\n blueprint: PipeBlueprintUnion,\n scope: Scope,\n): GraphSpecNodeIoItem[] {\n const ioInputs: GraphSpecNodeIoItem[] = [];\n for (const [name, spec] of Object.entries(blueprint.inputs)) {\n let bound = scope.get(name);\n if (bound === undefined) {\n bound = mintStuff(ctx, `input:${name}`, name, spec.concept, spec.multiplicity);\n scope.set(name, bound);\n if (conceptKey(bound.concept) !== conceptKey(spec.concept)) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"conflicting-input-concept\",\n message:\n `pipe \"${blueprint.code}\": dangling input \"${name}\" is declared as ` +\n `${conceptKey(spec.concept)} here but was first seen as ` +\n `${conceptKey(bound.concept)} — keeping the first`,\n path: `pipe.${blueprint.code}.inputs.${name}`,\n domain_code: blueprint.domain_code,\n });\n }\n }\n ioInputs.push(ioItem(bound));\n }\n return ioInputs;\n}\n\nfunction emitNode(\n ctx: WalkCtx,\n args: {\n id: string;\n kind: \"controller\" | \"operator\" | \"binding\";\n pipeCode: string;\n pipeType: NodePipeType;\n description: string;\n domainCode: string;\n ioInputs: GraphSpecNodeIoItem[];\n parentId: string | null;\n inv: Invocation;\n },\n): GraphSpecNode {\n const node: GraphSpecNode = {\n id: args.id,\n kind: args.kind,\n pipe_code: args.pipeCode,\n pipe_type: args.pipeType,\n // validateGraphSpec requires a non-empty description; WIP pipes may lack one.\n description: args.description.length > 0 ? args.description : args.pipeCode,\n domain_code: args.domainCode,\n status: \"scheduled\",\n io: { inputs: args.ioInputs, outputs: [] },\n };\n if (args.inv.outcomeValue !== undefined) node.tags = { outcome: args.inv.outcomeValue };\n ctx.nodes.push(node);\n if (args.parentId !== null) {\n addEdge(\n ctx,\n \"contains\",\n args.parentId,\n args.id,\n args.inv.outcomeValue !== undefined ? { label: args.inv.outcomeValue } : undefined,\n );\n }\n return node;\n}\n\n// ─── The walk ────────────────────────────────────────────────────────────────\n\n/**\n * Walk one pipe *invocation*: resolve the ref, emit the node (and its\n * `contains` edge), bind inputs from the caller's scope, recurse per\n * controller type, and report the invocation's output stuff.\n *\n * Scope model — the static mirror of the runtime's working memory, which is\n * ONE flat namespace shared across the whole run (verified against the dry\n * fixtures: a result produced inside a nested sub-sequence is consumed by a\n * later step of an ancestor sequence). So: sequence steps see and mutate the\n * caller's scope *object*; parallel/batch branches and condition outcome\n * children each get a *copy* — branches because the runtime forks memory per\n * branch and merges back only the declared outputs, condition outcomes\n * because they are mutually exclusive alternatives (only one runs, so no\n * branch's writes may be visible to its siblings or, beyond the condition's\n * one shared output, to the caller).\n */\nfunction walkPipe(\n ctx: WalkCtx,\n ref: string,\n currentDomain: string,\n nodeId: string,\n parentId: string | null,\n scope: Scope,\n inv: Invocation,\n): WalkResult | null {\n const resolution = resolvePipeRef(ctx.set, ref, currentDomain);\n if (resolution.kind === \"unresolved\") {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"unresolved-pipe-ref\",\n message: `pipe ref \"${ref}\" cannot be resolved — node skipped`,\n path: nodeId,\n // The uttering file's domain: a bare ref belongs to the namespace that\n // wrote it, mirroring the runtime's `_qualify_pipe_ref` inference.\n domain_code: currentDomain,\n });\n return null;\n }\n if (resolution.kind === \"opaque\") {\n return emitOpaqueLeaf(ctx, ref, currentDomain, nodeId, parentId, inv);\n }\n\n const { blueprint, domain, code } = resolution;\n const qualified = `${domain}.${code}`;\n const ioInputs = bindInputs(ctx, blueprint, scope);\n const node = emitNode(ctx, {\n id: nodeId,\n kind: blueprint.pipe_category === \"PipeController\" ? \"controller\" : \"operator\",\n pipeCode: code,\n pipeType: blueprint.type,\n description: blueprint.description,\n domainCode: blueprint.domain_code,\n ioInputs,\n parentId,\n inv,\n });\n\n if (ctx.stack.includes(qualified)) {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"cyclic-pipe-ref\",\n message: `pipe \"${qualified}\" is invoked recursively — rendered as a leaf`,\n path: nodeId,\n domain_code: domain,\n });\n return finishLeaf(ctx, node, blueprint, nodeId, inv);\n }\n\n ctx.stack.push(qualified);\n try {\n switch (blueprint.type) {\n case \"PipeSequence\":\n return finishSequence(ctx, node, blueprint, nodeId, scope, inv);\n case \"PipeParallel\":\n return finishParallel(ctx, node, blueprint, nodeId, scope, inv);\n case \"PipeCondition\":\n return finishCondition(ctx, node, blueprint, nodeId, scope, inv);\n case \"PipeBatch\":\n return finishBatch(ctx, node, blueprint, nodeId, scope, inv);\n default:\n return finishLeaf(ctx, node, blueprint, nodeId, inv);\n }\n } finally {\n ctx.stack.pop();\n }\n}\n\n/**\n * A step (or branch) invocation: a step carrying inline `batch_over`/`batch_as`\n * becomes a synthetic PipeBatch node wrapping the invoked pipe — mirroring the\n * runtime, which materializes `<pipe>_batch` controllers for inline batching.\n */\nfunction walkSubPipe(\n ctx: WalkCtx,\n sub: SubPipeSpec,\n domain: string,\n nodeId: string,\n parentId: string,\n scope: Scope,\n inheritedMultiplicity: Invocation[\"outputMultiplicity\"] = null,\n): WalkResult | null {\n if (sub.batch_params != null) {\n return walkInlineBatch(ctx, sub, domain, nodeId, parentId, scope);\n }\n return walkPipe(ctx, sub.pipe_code, domain, nodeId, parentId, scope, {\n resultName: sub.output_name ?? null,\n // A step with no `nb_output`/`multiple_output` of its own runs under the one\n // its controller was invoked with, as the runtime copies the run params down.\n outputMultiplicity: sub.output_multiplicity ?? inheritedMultiplicity,\n });\n}\n\n// ─── Leaf (operators, signatures, cyclic refs) ───────────────────────────────\n\nfunction finishLeaf(\n ctx: WalkCtx,\n node: GraphSpecNode,\n blueprint: PipeBlueprintUnion,\n nodeId: string,\n inv: Invocation,\n): WalkResult {\n const name = inv.resultName ?? snakeCase(blueprint.output.concept.code);\n const multiplicity =\n typeof inv.outputMultiplicity === \"number\" || inv.outputMultiplicity === true\n ? inv.outputMultiplicity\n : blueprint.output.multiplicity;\n const output = mintStuff(ctx, `${nodeId}:${name}`, name, blueprint.output.concept, multiplicity);\n node.io.outputs = [ioItem(output)];\n return { nodeId, output, eachOutputs: [] };\n}\n\n/** Phase-1 policy for `alias->…` dependency refs: an opaque leaf card. */\nfunction emitOpaqueLeaf(\n ctx: WalkCtx,\n ref: string,\n currentDomain: string,\n nodeId: string,\n parentId: string | null,\n inv: Invocation,\n): WalkResult {\n const alias = ref.slice(0, ref.indexOf(\"->\"));\n const tail = ref.slice(ref.lastIndexOf(\"->\") + 2);\n const codeTail = tail.slice(tail.lastIndexOf(\".\") + 1);\n const node = emitNode(ctx, {\n id: nodeId,\n kind: \"operator\",\n pipeCode: codeTail.length > 0 ? codeTail : ref,\n pipeType: \"PipeSignature\",\n description: `External pipe from dependency \"${alias}\"`,\n domainCode: alias.length > 0 ? alias : currentDomain,\n ioInputs: [],\n parentId,\n inv,\n });\n const name = inv.resultName ?? \"output\";\n const output = mintStuff(ctx, `${nodeId}:${name}`, name, nativeConceptInfo(\"Anything\"), null);\n node.io.outputs = [ioItem(output)];\n return { nodeId, output, eachOutputs: [] };\n}\n\n// ─── Controllers ─────────────────────────────────────────────────────────────\n\nfunction finishSequence(\n ctx: WalkCtx,\n node: GraphSpecNode,\n blueprint: PipeSequenceBlueprint,\n nodeId: string,\n scope: Scope,\n inv: Invocation,\n): WalkResult {\n let lastOutput: StuffRecord | null = null;\n // Steps are numbered as the runtime holds them, so a dotted `batch_over`,\n // held as a binding then the batch, takes two numbers.\n blueprint.sequential_sub_pipes.forEach((sub, index) => {\n const stepId = `${nodeId}/step_${index + 1}`;\n if (isBindingStepSpec(sub)) {\n // A binding stores its result as the main stuff, so a sequence ending\n // with one outputs what it binds.\n const bound = walkBindingStep(ctx, sub, blueprint, stepId, nodeId, scope);\n scope.set(sub.output_name, bound);\n lastOutput = bound;\n return;\n }\n const result = walkSubPipe(\n ctx,\n sub,\n blueprint.domain_code,\n stepId,\n nodeId,\n scope,\n inv.outputMultiplicity,\n );\n if (result === null) return;\n if (result.output !== null) {\n if (sub.output_name != null) scope.set(sub.output_name, result.output);\n lastOutput = result.output;\n }\n for (const [name, stuff] of result.eachOutputs) scope.set(name, stuff);\n });\n // Controller transparency: the sequence's output IS its last producing\n // step's stuff — same digest, so downstream consumers wire to the real\n // producer (the UI only takes producers from non-controller nodes).\n node.io.outputs = lastOutput === null ? [] : [ioItem(lastOutput, inv.resultName)];\n return { nodeId, output: lastOutput, eachOutputs: [] };\n}\n\n/**\n * Emit a binding step's node: it reads its root's stuff and produces the\n * bound one, named by the step's `result` and typed by the binding walk —\n * the shape a run graph gives a binding (`kind: \"binding\"`, `pipe_type:\n * \"BindingStep\"`, the `from` path as its `pipe_code`, `{ from, result }` as its\n * execution data). A root nothing in scope holds is a dangling input, as for\n * any unbound name; a path the walk cannot follow binds `native.Anything` and\n * is reported.\n */\nfunction walkBindingStep(\n ctx: WalkCtx,\n step: BindingStepSpec,\n sequence: PipeSequenceBlueprint,\n nodeId: string,\n parentId: string,\n scope: Scope,\n): StuffRecord {\n const rootName = step.from_path.split(\".\")[0];\n let root = scope.get(rootName);\n if (root === undefined) {\n root = mintStuff(ctx, `input:${rootName}`, rootName, nativeConceptInfo(\"Anything\"), null);\n scope.set(rootName, root);\n }\n const node = emitNode(ctx, {\n id: nodeId,\n kind: \"binding\",\n pipeCode: step.from_path,\n pipeType: BINDING_STEP_TYPE,\n description: `Binds '${step.from_path}' to '${step.output_name}'`,\n domainCode: sequence.domain_code,\n ioInputs: [ioItem(root, rootName)],\n parentId,\n inv: { resultName: step.output_name, outputMultiplicity: null },\n });\n node.execution_data = { from: step.from_path, result: step.output_name };\n\n const derivation = deriveBinding(ctx.set, step.from_path, {\n concept: root.concept,\n multiplicity: root.multiplicity,\n });\n let concept: ConceptInfo;\n let multiplicity: StuffMultiplicity;\n if (derivation.kind === \"derived\") {\n ({ concept, multiplicity } = derivation);\n } else {\n ctx.diagnostics.push({\n severity: \"warning\",\n code: \"binding-path-unresolved\",\n message: `pipe \"${sequence.code}\": ${derivation.reason} — bound as native.Anything`,\n path: nodeId,\n domain_code: sequence.domain_code,\n });\n concept = nativeConceptInfo(\"Anything\");\n multiplicity = isPluralMultiplicity(root.multiplicity) ? true : null;\n }\n const output = mintStuff(\n ctx,\n `${nodeId}:${step.output_name}`,\n step.output_name,\n concept,\n multiplicity,\n );\n node.io.outputs = [ioItem(output)];\n return output;\n}\n\nfunction finishParallel(\n ctx: WalkCtx,\n node: GraphSpecNode,\n blueprint: PipeParallelBlueprint,\n nodeId: string,\n scope: Scope,\n inv: Invocation,\n): WalkResult {\n const branchResults: { sub: SubPipeSpec; result: WalkResult }[] = [];\n blueprint.parallel_sub_pipes.forEach((sub, index) => {\n // Branches are independent: each gets its own copy of the inherited scope.\n const result = walkSubPipe(\n ctx,\n sub,\n blueprint.domain_code,\n `${nodeId}/branch_${index + 1}`,\n nodeId,\n new Map(scope),\n );\n if (result !== null) branchResults.push({ sub, result });\n });\n\n const eachOutputs: [string, StuffRecord][] = [];\n if (blueprint.add_each_output) {\n for (const { sub, result } of branchResults) {\n if (sub.output_name != null && result.output !== null) {\n eachOutputs.push([sub.output_name, result.output]);\n }\n }\n }\n\n const combinedName =\n blueprint.combined_output ?? inv.resultName ?? snakeCase(blueprint.output.concept.code);\n const combined = mintStuff(\n ctx,\n `${nodeId}:${combinedName}`,\n combinedName,\n blueprint.output.concept,\n blueprint.output.multiplicity,\n );\n for (const { result } of branchResults) {\n if (result.output !== null) {\n addEdge(ctx, \"parallel_combine\", result.nodeId, nodeId, {\n sourceStuff: result.output.digest,\n targetStuff: combined.digest,\n });\n }\n }\n node.io.outputs = [ioItem(combined, inv.resultName)];\n return { nodeId, output: combined, eachOutputs };\n}\n\nfunction finishCondition(\n ctx: WalkCtx,\n node: GraphSpecNode,\n blueprint: PipeConditionBlueprint,\n nodeId: string,\n scope: Scope,\n inv: Invocation,\n): WalkResult {\n const conditionScope: Scope = new Map(scope);\n if (blueprint.add_alias_from_expression_to != null) {\n const alias = blueprint.add_alias_from_expression_to;\n // The alias points at whatever the expression evaluates to at run time —\n // statically typed as native.Dynamic. Its digest has its own namespace: the\n // condition's shared output is `${nodeId}:<slot>`, and an alias named like\n // the slot must stay a separate stuff rather than become that output.\n conditionScope.set(\n alias,\n mintStuff(ctx, `${nodeId}:alias:${alias}`, alias, nativeConceptInfo(\"Dynamic\"), null),\n );\n }\n\n // One child node per distinct *target pipe*, not per outcome value —\n // mirroring the runtime tracer. Outcomes routing to the same pipe (often\n // one value plus `default_outcome`) merge into a single child carrying all\n // its routing values. `fail` / `continue` are outcome actions, not refs.\n // The default route is tracked as a flag, never as a value string — an\n // *authored* outcome value literally named \"default\" must not collide with\n // the synthetic default sentinel (node ids and primary selection key on it).\n interface RouteEntry {\n values: string[];\n ref: string;\n viaDefault: boolean;\n }\n const targets: RouteEntry[] = [];\n const byRef = new Map<string, RouteEntry>();\n const addRoute = (value: string, ref: string, isDefault: boolean): void => {\n if (ref === \"\" || ref === \"fail\" || ref === \"continue\") return;\n const existing = byRef.get(ref);\n if (existing !== undefined) {\n existing.values.push(value);\n existing.viaDefault ||= isDefault;\n return;\n }\n const entry = { values: [value], ref, viaDefault: isDefault };\n byRef.set(ref, entry);\n targets.push(entry);\n };\n for (const [value, target] of Object.entries(blueprint.outcome_map)) {\n addRoute(value, target, false);\n }\n addRoute(\"default\", blueprint.default_outcome, true);\n\n const results: { entry: RouteEntry; result: WalkResult }[] = [];\n for (const entry of targets) {\n const idSegment =\n entry.viaDefault && entry.values.length === 1 ? \"default\" : `outcome_${entry.values[0]}`;\n const result = walkPipe(\n ctx,\n entry.ref,\n blueprint.domain_code,\n `${nodeId}/${idSegment}`,\n nodeId,\n new Map(conditionScope),\n {\n // The runtime stores whichever branch runs under the condition's own\n // slot name, so every branch's output carries it (dry-run parity).\n resultName: inv.resultName,\n // The chosen outcome runs under the condition's own run params, its\n // invocation's `nb_output`/`multiple_output` included.\n outputMultiplicity: inv.outputMultiplicity,\n outcomeValue: entry.values.join(\" | \"),\n },\n );\n if (result !== null) results.push({ entry, result });\n }\n\n // Statically all outcomes exist, and each writes the condition's one slot: a\n // step after the condition reads that slot without knowing which outcome\n // filled it. So the condition's output is ONE stuff with a producer per\n // outcome — every outcome's output is renamed onto it, and whatever reads the\n // slot is wired to all of them.\n const outputs = results.flatMap(({ result }) => (result.output === null ? [] : [result.output]));\n // Named like the default route's output when there is one (the runtime names\n // the slot after whichever outcome wrote it), else the first producing one.\n const representative =\n results.find(({ entry, result }) => entry.viaDefault && result.output !== null)?.result\n .output ?? outputs[0];\n if (representative === undefined) {\n node.io.outputs = [];\n return { nodeId, output: null, eachOutputs: [] };\n }\n // Typed by the outcomes when they all agree, which is the most precise true\n // answer; by the condition's own declaration when they differ, since the slot\n // then holds either and only the declaration covers both.\n const outcomesAgree = outputs.every(\n (output) =>\n conceptKey(output.concept) === conceptKey(representative.concept) &&\n output.multiplicity === representative.multiplicity,\n );\n const declaredMultiplicity =\n typeof inv.outputMultiplicity === \"number\" || inv.outputMultiplicity === true\n ? inv.outputMultiplicity\n : blueprint.output.multiplicity;\n const shared = mintStuff(\n ctx,\n `${nodeId}:${representative.name}`,\n representative.name,\n outcomesAgree ? representative.concept : blueprint.output.concept,\n outcomesAgree ? representative.multiplicity : declaredMultiplicity,\n );\n for (const output of outputs) {\n // Only a stuff minted inside this condition is renamed: its digest names\n // its producer, so nothing outside the outcome's subtree can refer to it.\n if (output.digest.startsWith(`${nodeId}/`)) renameStuff(ctx, output.digest, shared);\n }\n node.io.outputs = [ioItem(shared, inv.resultName)];\n return { nodeId, output: shared, eachOutputs: [] };\n}\n\n/**\n * Re-point every io item and stuff-to-stuff edge already emitted from one stuff\n * to another. Only the digest moves: each io item keeps the concept its own\n * pipe declared, so an outcome's card still shows what that outcome produces.\n */\nfunction renameStuff(ctx: WalkCtx, from: string, to: StuffRecord): void {\n for (const node of ctx.nodes) {\n for (const item of [...node.io.inputs, ...node.io.outputs]) {\n if (item.digest === from) item.digest = to.digest;\n }\n }\n for (const edge of ctx.edges) {\n if (edge.source_stuff_digest === from) edge.source_stuff_digest = to.digest;\n if (edge.target_stuff_digest === from) edge.target_stuff_digest = to.digest;\n }\n ctx.stuffByDigest.delete(from);\n}\n\nfunction finishBatch(\n ctx: WalkCtx,\n node: GraphSpecNode,\n blueprint: PipeBatchBlueprint,\n nodeId: string,\n scope: Scope,\n inv: Invocation,\n): WalkResult {\n const params = blueprint.batch_params;\n\n let listStuff: StuffRecord | null = null;\n if (params.input_list_stuff_name !== \"\") {\n const bound = scope.get(params.input_list_stuff_name);\n if (bound !== undefined) {\n listStuff = bound;\n } else {\n // The list name is not among the declared inputs (sloppy but legal WIP\n // state): mint it as a dangling input and surface it on the node's io.\n listStuff = mintStuff(\n ctx,\n `input:${params.input_list_stuff_name}`,\n params.input_list_stuff_name,\n nativeConceptInfo(\"Anything\"),\n true,\n );\n node.io.inputs.push(ioItem(listStuff));\n }\n }\n\n let itemStuff: StuffRecord | null = null;\n const branchScope: Scope = new Map(scope);\n if (params.input_item_stuff_name !== \"\" && listStuff !== null) {\n // The item is one element of the list: same concept, single multiplicity.\n itemStuff = mintStuff(\n ctx,\n `${nodeId}:${params.input_item_stuff_name}`,\n params.input_item_stuff_name,\n listStuff.concept,\n null,\n );\n branchScope.set(params.input_item_stuff_name, itemStuff);\n }\n\n const batchMultiplicity = formatBatchMultiplicity(listStuff?.multiplicity);\n addNodeTag(node, \"batch_multiplicity\", batchMultiplicity);\n\n // One representative branch, not N — this is a method view, not a run trace.\n let branchResult: WalkResult | null = null;\n if (blueprint.branch_pipe_code !== \"\") {\n branchResult = walkPipe(\n ctx,\n blueprint.branch_pipe_code,\n blueprint.domain_code,\n `${nodeId}/batch_branch`,\n nodeId,\n branchScope,\n { resultName: null, outputMultiplicity: null },\n );\n const branchNode = ctx.nodes.find((candidate) => candidate.id === branchResult?.nodeId);\n if (branchNode !== undefined) {\n addNodeTag(branchNode, \"batch_multiplicity\", batchMultiplicity);\n }\n }\n\n const aggConcept = branchResult?.output?.concept ?? blueprint.output.concept;\n const aggName = inv.resultName ?? snakeCase(aggConcept.code);\n const aggregate = mintStuff(ctx, `${nodeId}:${aggName}`, aggName, aggConcept, true);\n\n if (branchResult !== null && listStuff !== null && itemStuff !== null) {\n addEdge(ctx, \"batch_item\", nodeId, branchResult.nodeId, {\n sourceStuff: listStuff.digest,\n targetStuff: itemStuff.digest,\n });\n }\n if (branchResult?.output != null) {\n addEdge(ctx, \"batch_aggregate\", branchResult.nodeId, nodeId, {\n sourceStuff: branchResult.output.digest,\n targetStuff: aggregate.digest,\n });\n }\n\n node.io.outputs = [ioItem(aggregate)];\n return { nodeId, output: aggregate, eachOutputs: [] };\n}\n\n/** Synthesize the PipeBatch node the runtime materializes for an inline `batch_over` step. */\nfunction walkInlineBatch(\n ctx: WalkCtx,\n sub: SubPipeSpec,\n domain: string,\n nodeId: string,\n parentId: string,\n scope: Scope,\n): WalkResult {\n const params = sub.batch_params as NonNullable<SubPipeSpec[\"batch_params\"]>;\n // Bare code of the branch ref: strip a dependency alias (`helpers->clean`)\n // and a domain qualifier (`lib.clean`) so the synthetic code reads cleanly.\n const aliasIdx = sub.pipe_code.lastIndexOf(\"->\");\n const refTail = aliasIdx === -1 ? sub.pipe_code : sub.pipe_code.slice(aliasIdx + 2);\n const branchTail = refTail.slice(refTail.lastIndexOf(\".\") + 1);\n const branchResolution = resolvePipeRef(ctx.set, sub.pipe_code, domain);\n const branchBlueprint = branchResolution.kind === \"resolved\" ? branchResolution.blueprint : null;\n\n const listBinding = scope.get(params.input_list_stuff_name);\n const listConcept =\n listBinding?.concept ??\n branchBlueprint?.inputs[params.input_item_stuff_name]?.concept ??\n nativeConceptInfo(\"Anything\");\n const outputSpec = branchBlueprint?.output ?? {\n concept: nativeConceptInfo(\"Anything\"),\n multiplicity: null,\n };\n\n // Registry key: the detail panel resolves blueprints by `domain.pipe_code`,\n // so every distinct inline batch needs its own entry. Reuse the code only\n // when it already points at this exact batch (same branch, same params);\n // otherwise disambiguate with a numeric suffix (`x_batch`, `x_batch_2`, …).\n const baseCode = `${branchTail}_batch`;\n let code = baseCode;\n for (let suffix = 2; ; suffix++) {\n const existing = ctx.pipeRegistry[`${domain}.${code}`];\n if (\n existing === undefined ||\n (existing.type === \"PipeBatch\" &&\n existing.branch_pipe_code === sub.pipe_code &&\n existing.batch_params.input_list_stuff_name === params.input_list_stuff_name &&\n existing.batch_params.input_item_stuff_name === params.input_item_stuff_name)\n ) {\n break;\n }\n code = `${baseCode}_${suffix}`;\n }\n const blueprint: PipeBatchBlueprint = {\n type: \"PipeBatch\",\n pipe_category: \"PipeController\",\n code,\n domain_code: domain,\n description: `Batch processing for ${branchTail}`,\n inputs: {\n [params.input_list_stuff_name]: {\n concept: listConcept,\n multiplicity: null,\n presence: \"plain\",\n },\n },\n output: { concept: outputSpec.concept, multiplicity: null, presence: \"plain\" },\n branch_pipe_code: sub.pipe_code,\n batch_params: params,\n };\n ctx.pipeRegistry[`${domain}.${code}`] ??= blueprint;\n\n const ioInputs = bindInputs(ctx, blueprint, scope);\n const inv: Invocation = {\n resultName: sub.output_name ?? null,\n outputMultiplicity: sub.output_multiplicity,\n };\n const node = emitNode(ctx, {\n id: nodeId,\n kind: \"controller\",\n pipeCode: code,\n pipeType: \"PipeBatch\",\n description: blueprint.description,\n domainCode: domain,\n ioInputs,\n parentId,\n inv,\n });\n return finishBatch(ctx, node, blueprint, nodeId, scope, inv);\n}\n","// Bridge from static-analysis diagnostics to the viewer's validation panel.\n\nimport type { ValidationIssue } from \"@graph/types\";\nimport { makePipeRef } from \"@graph/pipeRefs\";\nimport type { Diagnostic } from \"./types\";\n\n/**\n * Derive the viewer targeting fields from a diagnostic's TOML-style `path`\n * plus its declaring-namespace `domain_code`.\n *\n * - A walk-phase path is a GraphSpec node id and contains `/` (e.g.\n * `demo.main_flow/step_2`) → `nodeId`. Checked first: node ids embed the\n * domain, so a prefix test alone could misread them.\n * - A declaration path `pipe.<code>[...]` qualified by the diagnostic's\n * `domain_code` → `pipeRef` (`domain_code.pipe_code`). A diagnostic without\n * `domain_code` cannot be qualified and stays panel-only — decorating on a\n * bare code would ring every same-code node across domains.\n * - Everything else (concept paths, bare section paths like `pipe`, root\n * entry-pipe ids without `/`, missing paths) has no graph target — those\n * issues stay panel-only.\n */\nfunction targetFromPath(\n path: string | undefined,\n domainCode: string | undefined,\n): Pick<ValidationIssue, \"pipeRef\" | \"nodeId\"> {\n if (!path) return {};\n if (path.includes(\"/\")) return { nodeId: path };\n if (path.startsWith(\"pipe.\")) {\n const code = path.split(\".\")[1];\n if (code && domainCode) return { pipeRef: makePipeRef(domainCode, code) };\n }\n return {};\n}\n\n/**\n * Project static-graph {@link Diagnostic}s onto the viewer's presentation shape\n * so a host can feed them straight into `GraphViewer`'s `validationIssues`.\n * The TOML-style `path` becomes the locator chip; `origin: \"static\"` lets the\n * panel (and the host's issue policy) distinguish them from validator verdicts.\n * When the path identifies a pipe declaration or a precise invocation, the\n * targeting fields (`pipeRef` / `nodeId`) are filled so the viewer can\n * decorate the affected graph nodes.\n */\nexport function staticDiagnosticsToValidationIssues(diagnostics: Diagnostic[]): ValidationIssue[] {\n return diagnostics.map((diagnostic) => ({\n severity: diagnostic.severity,\n message: diagnostic.message,\n context: diagnostic.path,\n origin: \"static\",\n ...targetFromPath(diagnostic.path, diagnostic.domain_code),\n }));\n}\n","// ─── Which file of a method leads ────────────────────────────────────────────\n// A method spread over several `.mthds` files is merged in order, and the order\n// decides which bundle's `main_pipe`, `description` and fallback domain the\n// merged set adopts, and which declaration a genuine clash keeps (see\n// `mergeBundles`). Every host that holds a method as a list of files therefore\n// needs the same answer to \"which one leads\", and this module is that answer,\n// shared so no host keeps a private copy that drifts.\n\n/**\n * One `.mthds` file of a method: the name it goes by and its TOML text. The\n * same shape as an `mthds_sources[]` entry on the hosted API, so a host holding\n * one can pass it straight through.\n */\nexport interface MthdsSource {\n /**\n * File name, or a path ending in one. The whole string is the file's\n * identity: a `preferred` file is matched against it exactly, and an embed\n * lists each name once. Only the `bundle.mthds` tie-break reads the last\n * segment alone.\n */\n name: string;\n /** The file's `.mthds` TOML text. */\n content: string;\n}\n\n/** The file name that breaks a tie when several files declare `main_pipe`. */\nexport const DEFAULT_BUNDLE_FILE_NAME = \"bundle.mthds\";\n\nconst MAIN_PIPE_LINE = /^\\s*main_pipe\\s*=\\s*([\"'])[^\"']+\\1\\s*(?:#.*)?$/;\nconst TABLE_HEADER_LINE = /^\\s*\\[/;\n\n/**\n * Whether a file declares `main_pipe` at the top level, before its first table.\n *\n * A line scan rather than a TOML parse, on purpose: an editor asks this about\n * a file the author is in the middle of writing, and a syntax error further\n * down must not demote the file that plainly declares the entry point. The\n * scan stops at the first table header, because a `main_pipe` key inside a\n * table is not the bundle's.\n */\nexport function hasTopLevelMainPipe(content: string): boolean {\n for (const line of content.split(/\\r\\n|\\r|\\n/)) {\n if (TABLE_HEADER_LINE.test(line)) return false;\n if (MAIN_PIPE_LINE.test(line)) return true;\n }\n return false;\n}\n\nfunction isDefaultBundle(source: MthdsSource): boolean {\n const baseName = source.name.replace(/^.*[\\\\/]/, \"\");\n return baseName.toLowerCase() === DEFAULT_BUNDLE_FILE_NAME;\n}\n\n/**\n * The file a method's graph is anchored on.\n *\n * `preferred` is the file the host is looking at, such as the one open in an\n * editor; it leads whenever it declares `main_pipe` itself. Otherwise the file\n * declaring a top-level `main_pipe` leads, `bundle.mthds` when several do and\n * the first of them in the given order when none is named so. When no file\n * declares one, `preferred` leads, or else the first file. Returns `undefined`\n * only for an empty list.\n *\n * `preferred` is matched against `sources` by `name`, and the listed entry is\n * what is read and returned, so a host may pass its own object for the open\n * file rather than the list's: the result is always a member of `sources`,\n * because the merge reads the list and not `preferred`. That is also why\n * `preferred` is a plain `MthdsSource`: it cannot narrow the result's type and\n * strip the fields a host's own list entries carry. A `preferred` whose\n * name is not listed is ignored: it cannot lead a list it is not in, and the\n * answer is then the one given no `preferred` at all.\n */\nexport function selectPrimaryMthdsSource<T extends MthdsSource>(\n sources: readonly T[],\n preferred?: MthdsSource,\n): T | undefined {\n const listed =\n preferred === undefined ? undefined : sources.find((source) => source.name === preferred.name);\n if (listed !== undefined && hasTopLevelMainPipe(listed.content)) return listed;\n const withMainPipe = sources.filter((source) => hasTopLevelMainPipe(source.content));\n return withMainPipe.find(isDefaultBundle) ?? withMainPipe[0] ?? listed ?? sources[0];\n}\n\n/**\n * The files in the order the static builder should merge them: the primary\n * file (see {@link selectPrimaryMthdsSource}, which also says how `preferred`\n * is matched) first, then the rest in the order given. The rest keep their\n * order so a host that wants a deterministic merge only has to list its files\n * deterministically. Returns a new array.\n */\nexport function orderMthdsSources<T extends MthdsSource>(\n sources: readonly T[],\n preferred?: MthdsSource,\n): T[] {\n const primary = selectPrimaryMthdsSource(sources, preferred);\n const index = primary === undefined ? -1 : sources.indexOf(primary);\n if (index <= 0) return [...sources];\n return [sources[index], ...sources.slice(0, index), ...sources.slice(index + 1)];\n}\n","// ─── The `mthds-sources` embed ───────────────────────────────────────────────\n// A page carries a method's `.mthds` files as JSON in\n// `<script type=\"application/json\" id=\"mthds-sources\">`, and the standalone\n// viewer bundle draws the method from them. Both halves of that contract live\n// here, the check the bundle runs on what it reads and the serializer a host\n// writes the element with, so the writer and the reader cannot drift apart.\n// The contract itself is in `docs/static-graph.md`.\n\nimport type { MthdsSource } from \"./sourceOrder\";\n\n/** The id of the `<script type=\"application/json\">` element carrying the files. */\nexport const MTHDS_SOURCES_EMBED_ID = \"mthds-sources\";\n\nfunction describeEntry(index: number): string {\n return `<script id=\"${MTHDS_SOURCES_EMBED_ID}\"> entry ${index}`;\n}\n\n/**\n * Check a parsed `mthds-sources` value against the embed contract: a non-empty\n * array of `{ \"name\": string, \"content\": string }`, names non-empty and\n * distinct. Returns the entries with only those two keys. Throws with the\n * offending entry named, so a page written wrong says so on the error screen\n * instead of drawing a partial method.\n */\nexport function parseMthdsSourcesEmbed(raw: unknown): MthdsSource[] {\n if (!Array.isArray(raw)) {\n throw new Error(\n `<script id=\"${MTHDS_SOURCES_EMBED_ID}\"> must hold a JSON array of ` +\n `{ \"name\", \"content\" } objects, one per .mthds file.`,\n );\n }\n if (raw.length === 0) {\n throw new Error(`<script id=\"${MTHDS_SOURCES_EMBED_ID}\"> lists no .mthds file.`);\n }\n const seen = new Set<string>();\n return raw.map((entry: unknown, index) => {\n if (entry === null || typeof entry !== \"object\" || Array.isArray(entry)) {\n throw new Error(`${describeEntry(index)} is not a { \"name\", \"content\" } object.`);\n }\n const { name, content } = entry as Record<string, unknown>;\n if (typeof name !== \"string\" || name.trim() === \"\") {\n throw new Error(`${describeEntry(index)} has no \"name\" string.`);\n }\n if (typeof content !== \"string\") {\n throw new Error(`${describeEntry(index)} (\"${name}\") has no \"content\" string.`);\n }\n if (seen.has(name)) {\n throw new Error(`${describeEntry(index)} repeats the name \"${name}\".`);\n }\n seen.add(name);\n return { name, content };\n });\n}\n\n/**\n * The text a host places inside `<script type=\"application/json\"\n * id=\"mthds-sources\">`: the files as a JSON array of `{ name, content }`,\n * checked against the embed contract, with every `<` written as `\\u003c`.\n *\n * The escape is what makes the text safe inside the element. `JSON.parse`\n * reads it back as `<`, while the HTML parser never meets one, so no method\n * text can end the element early, whichever spelling of `</script` it uses, or\n * switch the element into the states a `<!--` opens. A prompt quoting a line of\n * HTML is enough to need it. Neither `JSON.stringify` nor any platform API has\n * an HTML-safe mode, which is why this function exists.\n *\n * Only `name` and `content` are written, whatever else a host's objects carry,\n * and the files keep the order given, because the bundle puts them in merge\n * order itself. Throws on a list the bundle would refuse, naming the entry at\n * fault.\n */\nexport function serializeMthdsSourcesEmbed(sources: readonly MthdsSource[]): string {\n return JSON.stringify(parseMthdsSourcesEmbed(sources)).replace(/</g, \"\\\\u003c\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkJO,IAAM,iBAAiB;AAQvB,SAAS,cAAc,OAAkD;AAC9E,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,QAAiB,OAAO,eAAe,KAAK;AAClD,SAAO,UAAU,OAAO,aAAa,UAAU;AACjD;AAiBO,SAAS,iBAAuC;AACrD,SAAO,uBAAO,OAAO,IAAI;AAC3B;AAEO,SAAS,UAAU,OAA+B;AACvD,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;AAEO,SAAS,UAAU,OAA+B;AACvD,SAAO,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK,IAAI,QAAQ;AACxE;AAEO,SAAS,WAAW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