{"version":3,"file":"unknown-abi.d.ts","sourceRoot":"","sources":["../../src/evolve/unknown-abi.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,kBAAkB,EAA4B,MAAM,sCAAsC,CAAC;AAOzG,OAAO,EAA+B,KAAK,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAI7F,OAAO,KAAK,EAAE,8BAA8B,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAExF,eAAO,MAAM,iCAAiC,IAAI,CAAC;AACnD,eAAO,MAAM,qBAAqB,IAAI,CAAC;AACvC,eAAO,MAAM,8BAA8B,QAAY,CAAC;AACxD,eAAO,MAAM,gCAAgC,QAAY,CAAC;AAC1D,eAAO,MAAM,4BAA4B,QAAa,CAAC;AACvD,eAAO,MAAM,6BAA6B,QAAa,CAAC;AACxD,eAAO,MAAM,gCAAgC,QAAa,CAAC;AAC3D,eAAO,MAAM,2BAA2B,KAAK,CAAC;AAQ9C,MAAM,WAAW,oBAAoB;IACpC,IAAI,EAAE,mBAAmB,CAAC;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CAClB;AAED;;;;GAIG;AACH,MAAM,WAAW,4BAA4B;IAC5C,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,MAAM,CAAC;IACZ,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,kBAAkB,EAAE,CAAC;CAC7B;AAED,MAAM,WAAW,qBAAqB;IACrC,IAAI,EAAE,WAAW,GAAG,UAAU,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,4BAA4B,CAAC;IACxC,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,iBAAiB,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,wBAAwB;IACxC,aAAa,EAAE,CAAC,CAAC;IACjB,MAAM,EAAE,oBAAoB,CAAC;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,kBAAkB,EAAE,8BAA8B,CAAC;IACnD,iBAAiB,EAAE,MAAM,EAAE,CAAC;IAC5B,KAAK,EAAE,qBAAqB,EAAE,CAAC;CAC/B;AA8HD,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,OAAO,GAAG,wBAAwB,CAkFtF;AA2ED,wBAAsB,uCAAuC,CAAC,OAAO,EAAE;IACtE,aAAa,EAAE,MAAM,CAAC;IACtB,iBAAiB,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,kBAAkB,EAAE,CAAC,CAAC,CAAC;IAC5E,QAAQ,CAAC,EAAE,cAAc,CAAC;CAC1B,GAAG,OAAO,CAAC,wBAAwB,EAAE,CAAC,CA2DtC;AA2CD;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,wBAAwB,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAqDpG","sourcesContent":["import { join } from \"node:path\";\nimport { isDigest } from \"../bundle/schema.ts\";\nimport { type EvoCapabilityGrant, parseEvoCapabilityGrants } from \"../components/capabilities/broker.ts\";\nimport {\n\tassertEvoAbiId,\n\tassertEvoCapability,\n\tassertEvoComponentId,\n\tparseEvoComponentManifest,\n} from \"../components/manifest.ts\";\nimport { createDefaultEvoAbiRegistry, type EvoAbiRegistry } from \"../components/registry.ts\";\nimport { type EvoPackComponent, type EvoPackWorkflow, loadEvoPack } from \"../pack/pack.ts\";\nimport { readRegularDirectoryNoFollow, readRegularFileNoFollow, resolveRegularDirectory } from \"../secure-file.ts\";\nimport { canonicalJson, sha256 } from \"../storage.ts\";\nimport type { EvoComponentActivationBoundary, EvoComponentManifest } from \"../types.ts\";\n\nexport const MAX_UNKNOWN_ABI_REQUESTS_PER_PACK = 4;\nexport const MAX_UNKNOWN_ABI_PARTS = 8;\nexport const MAX_UNKNOWN_ABI_MANIFEST_BYTES = 16 * 1024;\nexport const MAX_UNKNOWN_ABI_ENTRYPOINT_BYTES = 64 * 1024;\nexport const MAX_UNKNOWN_ABI_SOURCE_BYTES = 256 * 1024;\nexport const MAX_UNKNOWN_ABI_REQUEST_BYTES = 384 * 1024;\nexport const MAX_UNKNOWN_ABI_CODE_PATCH_BYTES = 256 * 1024;\nexport const MAX_UNKNOWN_ABI_PATCH_FILES = 12;\n\nconst PACK_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;\nconst PACK_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/;\nconst PACK_INTEGRITY_PATTERN = /^sha256:[0-9a-f]{64}$/;\nconst WORKFLOW_TRIGGER_PATTERN = /^\\/[a-z0-9][a-z0-9-]*$/;\nconst ACTIVATION_BOUNDARIES = new Set<EvoComponentActivationBoundary>([\"turn\", \"session\", \"process\", \"invocation\"]);\n\nexport interface UnknownAbiPackSource {\n\tkind: \"optimization-pack\";\n\tname: string;\n\tversion: string;\n\tintegrity: string;\n}\n\n/**\n * The exact selection that may be proposed only after this ABI lands and the\n * user retries import. Keeping grants here makes the future authority\n * reviewable without mutating policy or broker state during ABI generation.\n */\nexport interface UnknownAbiCandidateSelection {\n\tid: string;\n\tabi: string;\n\tartifactDigest: string;\n\tgrants: EvoCapabilityGrant[];\n}\n\nexport interface UnknownAbiBuilderPart {\n\tkind: \"component\" | \"workflow\";\n\tsurface: string;\n\ttrigger?: string;\n\tselection: UnknownAbiCandidateSelection;\n\tmanifest: EvoComponentManifest;\n\tentrypointContent: string;\n}\n\nexport interface UnknownAbiBuilderRequest {\n\tschemaVersion: 1;\n\tsource: UnknownAbiPackSource;\n\ttargetAbi: string;\n\tsurface: string;\n\tactivationBoundary: EvoComponentActivationBoundary;\n\tcapabilityCeiling: string[];\n\tparts: UnknownAbiBuilderPart[];\n}\n\nfunction asRecord(value: unknown, label: string): Record<string, unknown> {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new Error(`${label} must be an object`);\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nfunction exactKeys(record: Record<string, unknown>, allowed: readonly string[], label: string): void {\n\tconst allowedKeys = new Set(allowed);\n\tfor (const key of Object.keys(record)) {\n\t\tif (!allowedKeys.has(key)) throw new Error(`${label} has unknown key: ${key}`);\n\t}\n}\n\nfunction nonEmptyString(value: unknown, label: string, maxLength = 128): string {\n\tif (typeof value !== \"string\" || !value || value.length > maxLength) {\n\t\tthrow new Error(`${label} must be a non-empty string of at most ${maxLength} characters`);\n\t}\n\treturn value;\n}\n\nfunction sameStringSet(left: readonly string[], right: readonly string[]): boolean {\n\treturn [...left].sort().join(\"\\n\") === [...right].sort().join(\"\\n\");\n}\n\nfunction artifactIdentityDigest(manifest: EvoComponentManifest): string {\n\tconst { artifactDigest: _artifactDigest, ...identity } = manifest;\n\treturn sha256(canonicalJson({ componentArtifactSchemaVersion: 1, manifest: identity }));\n}\n\nfunction parsePackSource(value: unknown): UnknownAbiPackSource {\n\tconst source = asRecord(value, \"unknown ABI request.source\");\n\texactKeys(source, [\"kind\", \"name\", \"version\", \"integrity\"], \"unknown ABI request.source\");\n\tif (source.kind !== \"optimization-pack\") {\n\t\tthrow new Error(\"unknown ABI request.source.kind must be optimization-pack\");\n\t}\n\tconst name = nonEmptyString(source.name, \"unknown ABI request.source.name\");\n\tif (!PACK_NAME_PATTERN.test(name)) throw new Error(\"unknown ABI request.source.name is invalid\");\n\tconst version = nonEmptyString(source.version, \"unknown ABI request.source.version\");\n\tif (!PACK_VERSION_PATTERN.test(version)) throw new Error(\"unknown ABI request.source.version is invalid\");\n\tconst integrity = nonEmptyString(source.integrity, \"unknown ABI request.source.integrity\", 71);\n\tif (!PACK_INTEGRITY_PATTERN.test(integrity)) {\n\t\tthrow new Error(\"unknown ABI request.source.integrity must be a sha256 pack digest\");\n\t}\n\treturn { kind: \"optimization-pack\", name, version, integrity };\n}\n\nfunction parseSelection(value: unknown, label: string): UnknownAbiCandidateSelection {\n\tconst selection = asRecord(value, label);\n\texactKeys(selection, [\"id\", \"abi\", \"artifactDigest\", \"grants\"], label);\n\tconst id = nonEmptyString(selection.id, `${label}.id`);\n\tassertEvoComponentId(id, `${label}.id`);\n\tconst abi = nonEmptyString(selection.abi, `${label}.abi`);\n\tassertEvoAbiId(abi, `${label}.abi`);\n\tif (typeof selection.artifactDigest !== \"string\" || !isDigest(selection.artifactDigest)) {\n\t\tthrow new Error(`${label}.artifactDigest must be a digest`);\n\t}\n\treturn {\n\t\tid,\n\t\tabi,\n\t\tartifactDigest: selection.artifactDigest,\n\t\tgrants: parseEvoCapabilityGrants(selection.grants, `${label}.grants`),\n\t};\n}\n\nfunction parsePart(value: unknown, index: number): UnknownAbiBuilderPart {\n\tconst label = `unknown ABI request.parts[${index}]`;\n\tconst part = asRecord(value, label);\n\texactKeys(part, [\"kind\", \"surface\", \"trigger\", \"selection\", \"manifest\", \"entrypointContent\"], label);\n\tif (part.kind !== \"component\" && part.kind !== \"workflow\") {\n\t\tthrow new Error(`${label}.kind must be component or workflow`);\n\t}\n\tconst surface = nonEmptyString(part.surface, `${label}.surface`);\n\tassertEvoComponentId(surface, `${label}.surface`);\n\tlet trigger: string | undefined;\n\tif (part.kind === \"workflow\") {\n\t\ttrigger = nonEmptyString(part.trigger, `${label}.trigger`);\n\t\tif (!WORKFLOW_TRIGGER_PATTERN.test(trigger)) throw new Error(`${label}.trigger is invalid`);\n\t\tif (surface !== \"workflow\") throw new Error(`${label}.surface must be workflow`);\n\t} else {\n\t\tif (part.trigger !== undefined) throw new Error(`${label}.trigger is only valid for workflows`);\n\t\tif (surface === \"workflow\") throw new Error(`${label}.surface workflow requires kind workflow`);\n\t}\n\tconst selection = parseSelection(part.selection, `${label}.selection`);\n\tconst manifest = parseEvoComponentManifest(part.manifest);\n\tif (typeof part.entrypointContent !== \"string\") {\n\t\tthrow new Error(`${label}.entrypointContent must be a string`);\n\t}\n\tconst entrypointBytes = Buffer.from(part.entrypointContent);\n\tif (entrypointBytes.byteLength > MAX_UNKNOWN_ABI_ENTRYPOINT_BYTES) {\n\t\tthrow new Error(`${label}.entrypointContent exceeds ${MAX_UNKNOWN_ABI_ENTRYPOINT_BYTES} bytes`);\n\t}\n\tif (part.entrypointContent.includes(\"\\0\")) throw new Error(`${label}.entrypointContent contains a NUL byte`);\n\tif (sha256(entrypointBytes) !== manifest.entrypointSha256) {\n\t\tthrow new Error(`${label}.entrypointContent digest does not match its manifest`);\n\t}\n\tif (artifactIdentityDigest(manifest) !== manifest.artifactDigest) {\n\t\tthrow new Error(`${label}.manifest artifact identity is invalid`);\n\t}\n\tif (\n\t\tselection.id !== manifest.id ||\n\t\tselection.abi !== manifest.abi ||\n\t\tselection.artifactDigest !== manifest.artifactDigest\n\t) {\n\t\tthrow new Error(`${label}.selection does not match its artifact manifest`);\n\t}\n\tif (\n\t\t!sameStringSet(\n\t\t\tmanifest.capabilities,\n\t\t\tselection.grants.map((grant) => grant.capability),\n\t\t)\n\t) {\n\t\tthrow new Error(`${label}.selection must explicitly grant exactly the declared capability set`);\n\t}\n\treturn {\n\t\tkind: part.kind,\n\t\tsurface,\n\t\t...(trigger ? { trigger } : {}),\n\t\tselection,\n\t\tmanifest,\n\t\tentrypointContent: part.entrypointContent,\n\t};\n}\n\nexport function parseUnknownAbiBuilderRequest(value: unknown): UnknownAbiBuilderRequest {\n\tconst request = asRecord(value, \"unknown ABI request\");\n\texactKeys(\n\t\trequest,\n\t\t[\"schemaVersion\", \"source\", \"targetAbi\", \"surface\", \"activationBoundary\", \"capabilityCeiling\", \"parts\"],\n\t\t\"unknown ABI request\",\n\t);\n\tif (request.schemaVersion !== 1) throw new Error(\"unknown ABI request.schemaVersion must be 1\");\n\tconst source = parsePackSource(request.source);\n\tconst targetAbi = nonEmptyString(request.targetAbi, \"unknown ABI request.targetAbi\");\n\tassertEvoAbiId(targetAbi, \"unknown ABI request.targetAbi\");\n\tconst surface = nonEmptyString(request.surface, \"unknown ABI request.surface\");\n\tassertEvoComponentId(surface, \"unknown ABI request.surface\");\n\tif (\n\t\ttypeof request.activationBoundary !== \"string\" ||\n\t\t!ACTIVATION_BOUNDARIES.has(request.activationBoundary as EvoComponentActivationBoundary)\n\t) {\n\t\tthrow new Error(\"unknown ABI request.activationBoundary is invalid\");\n\t}\n\tif (\n\t\t!Array.isArray(request.capabilityCeiling) ||\n\t\trequest.capabilityCeiling.some((capability) => typeof capability !== \"string\")\n\t) {\n\t\tthrow new Error(\"unknown ABI request.capabilityCeiling must be a string array\");\n\t}\n\tconst capabilityCeiling = request.capabilityCeiling as string[];\n\tfor (const [index, capability] of capabilityCeiling.entries()) {\n\t\tassertEvoCapability(capability, `unknown ABI request.capabilityCeiling[${index}]`);\n\t}\n\tif (new Set(capabilityCeiling).size !== capabilityCeiling.length) {\n\t\tthrow new Error(\"unknown ABI request.capabilityCeiling must not contain duplicates\");\n\t}\n\tif (!Array.isArray(request.parts) || request.parts.length === 0) {\n\t\tthrow new Error(\"unknown ABI request.parts must be a non-empty array\");\n\t}\n\tif (request.parts.length > MAX_UNKNOWN_ABI_PARTS) {\n\t\tthrow new Error(`unknown ABI request.parts exceeds ${MAX_UNKNOWN_ABI_PARTS} parts`);\n\t}\n\tconst parts = request.parts.map((part, index) => parsePart(part, index));\n\tif (surface !== \"tool\" && surface !== \"workflow\" && parts.length !== 1) {\n\t\tthrow new Error(`unknown ABI singleton surface ${surface} must have exactly one candidate part`);\n\t}\n\tfor (const [index, part] of parts.entries()) {\n\t\tif (part.surface !== surface) throw new Error(`unknown ABI request.parts[${index}] has a different surface`);\n\t\tif (part.selection.abi !== targetAbi) {\n\t\t\tthrow new Error(`unknown ABI request.parts[${index}] targets a different ABI`);\n\t\t}\n\t\tif (part.manifest.activationBoundary !== request.activationBoundary) {\n\t\t\tthrow new Error(`unknown ABI request.parts[${index}] has a different activation boundary`);\n\t\t}\n\t}\n\tif (new Set(parts.map((part) => part.selection.id)).size !== parts.length) {\n\t\tthrow new Error(\"unknown ABI request.parts must not contain duplicate component ids\");\n\t}\n\tif (new Set(parts.map((part) => part.selection.artifactDigest)).size !== parts.length) {\n\t\tthrow new Error(\"unknown ABI request.parts must not contain duplicate artifacts\");\n\t}\n\tconst triggers = parts.flatMap((part) => (part.trigger ? [part.trigger] : []));\n\tif (new Set(triggers).size !== triggers.length) {\n\t\tthrow new Error(\"unknown ABI request.parts must not contain duplicate workflow triggers\");\n\t}\n\tconst declaredCeiling = [...new Set(parts.flatMap((part) => part.manifest.capabilities))].sort();\n\tif (!sameStringSet(capabilityCeiling, declaredCeiling)) {\n\t\tthrow new Error(\"unknown ABI request.capabilityCeiling must exactly match candidate declarations\");\n\t}\n\tconst sourceBytes = parts.reduce((total, part) => total + Buffer.byteLength(part.entrypointContent), 0);\n\tif (sourceBytes > MAX_UNKNOWN_ABI_SOURCE_BYTES) {\n\t\tthrow new Error(`unknown ABI request source exceeds ${MAX_UNKNOWN_ABI_SOURCE_BYTES} bytes`);\n\t}\n\tconst parsed: UnknownAbiBuilderRequest = {\n\t\tschemaVersion: 1,\n\t\tsource,\n\t\ttargetAbi,\n\t\tsurface,\n\t\tactivationBoundary: request.activationBoundary as EvoComponentActivationBoundary,\n\t\tcapabilityCeiling: [...capabilityCeiling].sort(),\n\t\tparts: parts.sort((left, right) => left.selection.id.localeCompare(right.selection.id)),\n\t};\n\tif (Buffer.byteLength(canonicalJson(parsed)) > MAX_UNKNOWN_ABI_REQUEST_BYTES) {\n\t\tthrow new Error(`unknown ABI request exceeds ${MAX_UNKNOWN_ABI_REQUEST_BYTES} bytes`);\n\t}\n\treturn parsed;\n}\n\ntype PackCodePart = { kind: \"component\"; part: EvoPackComponent } | { kind: \"workflow\"; part: EvoPackWorkflow };\n\nasync function inspectPackArtifact(\n\tpackDirectory: string,\n\tcodePart: PackCodePart,\n\tgrants: readonly EvoCapabilityGrant[],\n): Promise<UnknownAbiBuilderPart> {\n\tconst declaration = codePart.part;\n\tconst directory = join(packDirectory, declaration.artifact);\n\tconst entries = (await readRegularDirectoryNoFollow(directory, `Pack component artifact ${declaration.id}`)).sort(\n\t\t(left, right) => left.name.localeCompare(right.name),\n\t);\n\tif (entries.some((entry) => !entry.isFile() || entry.isSymbolicLink())) {\n\t\tthrow new Error(`Pack component artifact contains a non-regular file: ${declaration.id}`);\n\t}\n\tconst manifestEntry = entries.find((entry) => entry.name === \"manifest.json\");\n\tif (!manifestEntry) throw new Error(`Pack component artifact has no manifest: ${declaration.id}`);\n\tconst manifestPath = join(directory, \"manifest.json\");\n\tconst manifestBytes = await readRegularFileNoFollow(\n\t\tmanifestPath,\n\t\t`Pack component manifest ${declaration.id}`,\n\t\tMAX_UNKNOWN_ABI_MANIFEST_BYTES,\n\t);\n\tlet manifestText: string;\n\ttry {\n\t\tmanifestText = new TextDecoder(\"utf-8\", { fatal: true }).decode(manifestBytes);\n\t} catch (error) {\n\t\tthrow new Error(`Pack component manifest is not UTF-8: ${declaration.id}`, { cause: error });\n\t}\n\tconst manifest = parseEvoComponentManifest(JSON.parse(manifestText) as unknown);\n\tconst expectedFiles = [manifest.entrypoint, \"manifest.json\"].sort();\n\tif (entries.map((entry) => entry.name).join(\"\\n\") !== expectedFiles.join(\"\\n\")) {\n\t\tthrow new Error(`Pack component artifact file set is invalid: ${declaration.id}`);\n\t}\n\tconst entrypointPath = join(directory, manifest.entrypoint);\n\tconst entrypointBytes = await readRegularFileNoFollow(\n\t\tentrypointPath,\n\t\t`Pack component entrypoint ${declaration.id}`,\n\t\tMAX_UNKNOWN_ABI_ENTRYPOINT_BYTES,\n\t);\n\tlet entrypointContent: string;\n\ttry {\n\t\tentrypointContent = new TextDecoder(\"utf-8\", { fatal: true }).decode(entrypointBytes);\n\t} catch (error) {\n\t\tthrow new Error(`Pack component entrypoint is not UTF-8: ${declaration.id}`, { cause: error });\n\t}\n\tif (\n\t\tmanifest.id !== declaration.id ||\n\t\tmanifest.abi !== declaration.abi ||\n\t\t!sameStringSet(manifest.capabilities, declaration.capabilities)\n\t) {\n\t\tthrow new Error(`Pack component declaration does not match artifact: ${declaration.id}`);\n\t}\n\tconst parsedGrants = parseEvoCapabilityGrants(grants, `grantsByComponent.${declaration.id}`);\n\tconst surface = codePart.kind === \"workflow\" ? \"workflow\" : codePart.part.surface;\n\treturn parsePart(\n\t\t{\n\t\t\tkind: codePart.kind,\n\t\t\tsurface,\n\t\t\t...(codePart.kind === \"workflow\" ? { trigger: codePart.part.trigger } : {}),\n\t\t\tselection: {\n\t\t\t\tid: manifest.id,\n\t\t\t\tabi: manifest.abi,\n\t\t\t\tartifactDigest: manifest.artifactDigest,\n\t\t\t\tgrants: parsedGrants,\n\t\t\t},\n\t\t\tmanifest,\n\t\t\tentrypointContent,\n\t\t},\n\t\t0,\n\t);\n}\n\nexport async function createUnknownAbiBuilderRequestsFromPack(options: {\n\tpackDirectory: string;\n\tgrantsByComponent?: Readonly<Record<string, readonly EvoCapabilityGrant[]>>;\n\tregistry?: EvoAbiRegistry;\n}): Promise<UnknownAbiBuilderRequest[]> {\n\tconst packDirectory = await resolveRegularDirectory(options.packDirectory, \"pack directory\");\n\tconst loaded = await loadEvoPack(packDirectory);\n\tif (!loaded.integrity.ok) {\n\t\tthrow new Error(\n\t\t\t`pack integrity check failed: expected ${loaded.integrity.expected ?? \"(none declared)\"}, got ${loaded.integrity.actual}`,\n\t\t);\n\t}\n\tconst registry = options.registry ?? createDefaultEvoAbiRegistry();\n\tconst grouped = new Map<string, UnknownAbiBuilderPart[]>();\n\tconst codeParts: PackCodePart[] = [\n\t\t...loaded.manifest.contents.components.map((part): PackCodePart => ({ kind: \"component\", part })),\n\t\t...loaded.manifest.contents.workflows.map((part): PackCodePart => ({ kind: \"workflow\", part })),\n\t];\n\tfor (const codePart of codeParts) {\n\t\tif (registry.get(codePart.part.abi)) continue;\n\t\tconst part = await inspectPackArtifact(\n\t\t\tpackDirectory,\n\t\t\tcodePart,\n\t\t\toptions.grantsByComponent?.[codePart.part.id] ?? [],\n\t\t);\n\t\tconst group = grouped.get(codePart.part.abi) ?? [];\n\t\tgroup.push(part);\n\t\tgrouped.set(codePart.part.abi, group);\n\t}\n\tif (grouped.size > MAX_UNKNOWN_ABI_REQUESTS_PER_PACK) {\n\t\tthrow new Error(`Pack exceeds ${MAX_UNKNOWN_ABI_REQUESTS_PER_PACK} unregistered ABIs per import`);\n\t}\n\tconst requests = [...grouped.entries()]\n\t\t.sort(([left], [right]) => left.localeCompare(right))\n\t\t.map(([targetAbi, parts]) => {\n\t\t\tconst first = parts[0];\n\t\t\tif (!first) throw new Error(`Unknown ABI ${targetAbi} has no candidate parts`);\n\t\t\treturn parseUnknownAbiBuilderRequest({\n\t\t\t\tschemaVersion: 1,\n\t\t\t\tsource: {\n\t\t\t\t\tkind: \"optimization-pack\",\n\t\t\t\t\tname: loaded.manifest.name,\n\t\t\t\t\tversion: loaded.manifest.version,\n\t\t\t\t\tintegrity: loaded.integrity.actual,\n\t\t\t\t},\n\t\t\t\ttargetAbi,\n\t\t\t\tsurface: first.surface,\n\t\t\t\tactivationBoundary: first.manifest.activationBoundary,\n\t\t\t\tcapabilityCeiling: [...new Set(parts.flatMap((part) => part.manifest.capabilities))].sort(),\n\t\t\t\tparts,\n\t\t\t});\n\t\t});\n\tconst confirmed = await loadEvoPack(packDirectory);\n\tif (\n\t\t!confirmed.integrity.ok ||\n\t\tconfirmed.integrity.actual !== loaded.integrity.actual ||\n\t\tcanonicalJson(confirmed.manifest) !== canonicalJson(loaded.manifest)\n\t) {\n\t\tthrow new Error(\n\t\t\t`Pack changed while creating unknown ABI requests: expected ${loaded.integrity.actual}, got ${confirmed.integrity.actual}`,\n\t\t);\n\t}\n\treturn requests;\n}\n\nfunction allowedUnknownAbiPatchPath(path: string): boolean {\n\tif (path === \"packages/evo/src/components/registry.ts\") return true;\n\tif (path === \"packages/evo/src/bundle/runtime.ts\") return true;\n\tif (path === \"packages/evo/src/types.ts\" || path === \"packages/evo/src/extension.ts\") return true;\n\tif (\n\t\tpath.startsWith(\"packages/evo/src/components/\") &&\n\t\t!path.startsWith(\"packages/evo/src/components/capabilities/\") &&\n\t\tpath.endsWith(\".ts\")\n\t) {\n\t\treturn true;\n\t}\n\treturn /^packages\\/evo\\/test\\/[A-Za-z0-9._/-]+\\.test\\.ts$/.test(path);\n}\n\nfunction containsQuotedLiteral(text: string, value: string): boolean {\n\treturn text.includes(`\"${value}\"`) || text.includes(`'${value}'`);\n}\n\nfunction parseAddedCapabilityCeilings(patch: string): string[][] {\n\tconst added = patch\n\t\t.split(\"\\n\")\n\t\t.filter((line) => line.startsWith(\"+\") && !line.startsWith(\"+++\"))\n\t\t.map((line) => line.slice(1))\n\t\t.join(\"\\n\");\n\tconst ceilings: string[][] = [];\n\tfor (const match of added.matchAll(/capabilityCeiling\\s*:\\s*\\[([^\\]\\n]*)\\]/g)) {\n\t\tconst body = match[1] ?? \"\";\n\t\tconst capabilities: string[] = [];\n\t\tlet remainder = body;\n\t\tfor (const literal of body.matchAll(/([\"'])([a-z][a-z0-9]*(?:[._:-][a-z0-9]+)*)\\1/g)) {\n\t\t\tcapabilities.push(literal[2] as string);\n\t\t\tremainder = remainder.replace(literal[0], \"\");\n\t\t}\n\t\tif (remainder.replaceAll(\",\", \"\").trim()) {\n\t\t\tthrow new Error(\"Unknown ABI Builder capabilityCeiling must contain only string literals\");\n\t\t}\n\t\tceilings.push(capabilities);\n\t}\n\treturn ceilings;\n}\n\n/**\n * Enforce the narrow infrastructure-patch envelope before a worktree exists.\n * Git staging still performs the authoritative path, mode, binary, whitespace,\n * and L1 checks.\n */\nexport function assertUnknownAbiCodePatch(request: UnknownAbiBuilderRequest, patch: string): string[] {\n\tif (!patch.trim()) throw new Error(\"Unknown ABI Builder codePatch must not be empty\");\n\tif (Buffer.byteLength(patch) > MAX_UNKNOWN_ABI_CODE_PATCH_BYTES) {\n\t\tthrow new Error(`Unknown ABI Builder codePatch exceeds ${MAX_UNKNOWN_ABI_CODE_PATCH_BYTES} bytes`);\n\t}\n\tif (patch.includes(\"\\0\")) throw new Error(\"Unknown ABI Builder codePatch contains a NUL byte\");\n\tconst paths: string[] = [];\n\tfor (const line of patch.split(\"\\n\")) {\n\t\tif (!line.startsWith(\"diff --git \")) continue;\n\t\tconst match = /^diff --git a\\/([^\\t ]+) b\\/([^\\t ]+)\\r?$/.exec(line);\n\t\tif (!match || match[1] !== match[2]) {\n\t\t\tthrow new Error(\"Unknown ABI Builder codePatch has a malformed or renamed diff header\");\n\t\t}\n\t\tpaths.push(match[1]);\n\t}\n\tif (paths.length === 0) throw new Error(\"Unknown ABI Builder codePatch must use complete git diff headers\");\n\tif (paths.length > MAX_UNKNOWN_ABI_PATCH_FILES) {\n\t\tthrow new Error(`Unknown ABI Builder codePatch exceeds ${MAX_UNKNOWN_ABI_PATCH_FILES} files`);\n\t}\n\tif (new Set(paths).size !== paths.length) {\n\t\tthrow new Error(\"Unknown ABI Builder codePatch has duplicate file diffs\");\n\t}\n\tfor (const path of paths) {\n\t\tif (!allowedUnknownAbiPatchPath(path)) {\n\t\t\tthrow new Error(`Unknown ABI Builder codePatch changes a forbidden path: ${path}`);\n\t\t}\n\t}\n\tfor (const required of [\"packages/evo/src/components/registry.ts\", \"packages/evo/src/bundle/runtime.ts\"] as const) {\n\t\tif (!paths.includes(required)) {\n\t\t\tthrow new Error(`Unknown ABI Builder codePatch must change ${required}`);\n\t\t}\n\t}\n\tif (!paths.some((path) => path.startsWith(\"packages/evo/test/\"))) {\n\t\tthrow new Error(\"Unknown ABI Builder codePatch must add or update a focused Evo test\");\n\t}\n\tif (!patch.includes(\"EvoAbiDefinition\") || !containsQuotedLiteral(patch, request.targetAbi)) {\n\t\tthrow new Error(\"Unknown ABI Builder codePatch must define the exact requested EvoAbiDefinition\");\n\t}\n\tconst ceilings = parseAddedCapabilityCeilings(patch);\n\tif (ceilings.length === 0) {\n\t\tthrow new Error(\"Unknown ABI Builder codePatch must define an explicit capability ceiling\");\n\t}\n\tfor (const ceiling of ceilings) {\n\t\tif (!sameStringSet(ceiling, request.capabilityCeiling)) {\n\t\t\tthrow new Error(\"Unknown ABI Builder codePatch widens or narrows the declared capability ceiling\");\n\t\t}\n\t}\n\tfor (const part of request.parts) {\n\t\tif (patch.includes(part.selection.artifactDigest)) {\n\t\t\tthrow new Error(\"Unknown ABI Builder codePatch must not hard-code a future component selection\");\n\t\t}\n\t}\n\treturn [...paths].sort();\n}\n"]}