@runveric/cli 0.4.0 → 0.5.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../contracts/src/enums.ts","../../contracts/src/brand.ts","../../contracts/src/wire-identity.ts","../../contracts/src/problem.ts","../../contracts/src/permissions.ts","../../contracts/src/request-context.ts","../../contracts/src/role-permissions.ts","../../contracts/dist/me.js","../../contracts/dist/tenant-users.js","../../contracts/dist/invitations.js","../../contracts/dist/groups.js","../../contracts/src/catalog-policy.ts","../../contracts/src/catalog.ts","../../contracts/src/catalog-release.ts","../../contracts/src/action-repository.ts","../../contracts/src/catalog-release-spec.ts","../../contracts/src/catalog-lock.ts","../../contracts/src/catalog-manifest-placeholders.ts","../../contracts/src/change-control.ts","../../contracts/src/run-placement.ts","../../contracts/src/package-provenance.ts","../../contracts/src/package-tier.ts","../../contracts/src/packages.ts","../../contracts/src/validation.ts","../../contracts/src/execution.ts","../../contracts/src/decisions.ts","../../contracts/src/execution-site.ts","../../contracts/src/connections.ts","../../contracts/src/resources.ts","../../contracts/src/governance.ts","../../contracts/dist/audit.js","../../contracts/src/notifications.ts","../../contracts/dist/scheduling.js","../../contracts/src/operations.ts","../../contracts/src/runs.ts","../../contracts/src/evidence-pack.ts","../../contracts/src/package-egress.ts","../../contracts/src/package-execution.ts","../../contracts/src/runner-confinement.ts","../../contracts/src/runner-install.ts","../../contracts/src/authoring-cli.ts","../../contracts/src/runners.ts","../../contracts/src/scoped-credential.ts","../../contracts/src/action-protocol.ts","../../contracts/src/action-signing.ts","../../contracts/src/oci-media-types.ts","../../contracts/src/action-image.ts","../../contracts/src/runner-pool-presence.ts","../../contracts/src/runner-pool-routing.ts","../../contracts/src/target-identity.ts","../../contracts/src/which-entra.ts","../../contracts/src/onboarding.ts","../../contracts/src/workspace-domain.ts","../../contracts/src/workspace-features.ts","../../contracts/src/directory-sync.ts","../../contracts/src/workos-binding.ts","../../contracts/src/index.ts","../../action-manifest/src/package-runtime-declaration.ts","../../action-manifest/src/manifest.schema.ts","../../action-manifest/src/manifest-validator.ts","../../action-manifest/src/package-result-validator.ts","../../action-manifest/src/package-validation.ts","../../action-manifest/src/source-location.ts","../../action-manifest/src/findings.ts","../../action-manifest/src/interpreter-launch.ts","../../action-manifest/src/authoring-lint.ts","../../action-manifest/src/parameters-location.ts","../../action-manifest/src/check.ts","../../action-manifest/src/powershell-param-detection.ts","../../action-manifest/src/scaffold.ts","../../action-manifest/src/index.ts","../package.json","../src/report.ts","../src/catalog/publish-action.ts","../src/catalog/artifact.ts","../src/catalog/flags.ts","../src/catalog/image.ts","../src/catalog/publish-release.ts","../src/catalog/verify-image.ts","../src/catalog/index.ts","../src/check.ts","../src/package-dir.ts","../src/init.ts","../src/publish.ts","../src/renamed-variable.ts","../src/runner-image.ts","../src/test.ts","../src/azure-credential.ts","../src/main.ts"],"sourcesContent":["// Closed value sets shared across FE and BE. Mirror the DB enums (docs/05 §2).\n// Full enums ship now even where the feature is deferred (docs/12 §11.2).\n\n// EVERY closed vocabulary below is declared ONCE, as a `const … as const` array, with the\n// type derived from it (charter §4.2 R1). Never the other way round: TypeScript cannot\n// enumerate a union at run time, so a union written first forces every validator to\n// hand-copy its members — and a hand-copy that omits one is a 400 nobody notices until an\n// operator hits it.\n\n// The connection providers Opera can bind to. Azure ships first; aws/gcp/terraform\n// are declared now for the ProviderAdapter registry (docs/24 §7, §14).\n//\n// Shared as data by manifest validation and discovery-id parsing (docs/29 D1/D2).\nexport const PROVIDERS = [\"azure\", \"aws\", \"gcp\", \"terraform\"] as const;\nexport type Provider = (typeof PROVIDERS)[number];\n\n// How a connection's federated identity authenticates to its provider (docs/24 §5.1).\nexport const IDENTITY_MECHANISMS = [\n \"service_principal\",\n \"managed_identity\",\n \"iam_role\",\n \"hcp_dynamic\",\n \"api_token\",\n] as const;\nexport type IdentityMechanism = (typeof IDENTITY_MECHANISMS)[number];\n\n// Provider-neutral connection lifecycle (docs/24 §5.3).\nexport const CONNECTION_STATES = [\"draft\", \"active\", \"degraded\"] as const;\nexport type ConnectionState = (typeof CONNECTION_STATES)[number];\n\n// The kind of a discovered, governable scope under a connection (docs/24 §5.2).\nexport const CONNECTION_SCOPE_KINDS = [\n \"subscription\",\n \"account\",\n \"project\",\n \"workspace\",\n] as const;\nexport type ConnectionScopeKind = (typeof CONNECTION_SCOPE_KINDS)[number];\n\nexport const ACTION_CATEGORIES = [\n \"compute\",\n \"storage\",\n \"security\",\n \"databases\",\n \"containers\",\n] as const;\nexport type ActionCategory = (typeof ACTION_CATEGORIES)[number];\n\n/**\n * ASCENDING SEVERITY, and that order is now load-bearing — {@link maxRiskLevel} reads it as the\n * ranking rather than keeping a second table that could disagree with this one. Inserting a\n * level in the wrong place would silently change which of two risk levels governs a run.\n */\nexport const RISK_LEVELS = [\"low\", \"medium\", \"high\"] as const;\nexport type RiskLevel = (typeof RISK_LEVELS)[number];\n\n/**\n * The MORE severe of two risk levels — the one answer to \"which of these governs\".\n *\n * It exists because a trial run has two candidate risk levels: the draft's own declaration\n * (accurate — the draft's bytes are what runs) and the published definition's (authoritative —\n * it is what everyone else's runs of this package are governed at). Taking the draft's alone\n * would let an author lower the governance of a package by editing a draft, which is a\n * privilege-escalation path dressed as a text edit. Never under-govern.\n */\nexport function maxRiskLevel(left: RiskLevel, right: RiskLevel): RiskLevel {\n return RISK_LEVELS.indexOf(left) >= RISK_LEVELS.indexOf(right) ? left : right;\n}\n\nexport const VERSION_STATUSES = [\"draft\", \"published\", \"deprecated\"] as const;\nexport type VersionStatus = (typeof VERSION_STATUSES)[number];\n\nexport const ENVIRONMENTS = [\"production\", \"staging\", \"non_prod\"] as const;\nexport type Environment = (typeof ENVIRONMENTS)[number];\n\nexport const EXECUTION_STATUSES = [\n \"draft\",\n \"validating\",\n \"validated\",\n \"validation_failed\",\n \"pending_approval\",\n \"approved\",\n \"rejected\",\n \"queued\",\n \"pending_runner\",\n \"running\",\n \"succeeded\",\n \"rolling_back\",\n \"failed\",\n \"cancelled\",\n \"rolled_back\",\n \"rollback_failed\",\n] as const;\nexport type ExecutionStatus = (typeof EXECUTION_STATUSES)[number];\n\n/**\n * Is an execution SETTLED — will the worker never move this status again?\n *\n * Settled is NOT the same as \"has no legal onward transition\". `succeeded` and `failed`\n * both have onward transitions in the execution state machine (into the rollback path) and\n * are still settled, because that transition only ever happens when a HUMAN asks for it.\n * The question this Record answers is \"has the machine stopped?\", so that a poller can stop\n * polling and an interface can present an outcome. A new status belongs on the `false` side\n * if any automated step can still move it, and on the `true` side only if nothing but a new\n * operator-initiated action can.\n *\n * Keyed by the union so a new status is a COMPILE ERROR until someone answers the question\n * for it (charter §4.2 R2). This is the single answer for the API, the worker AND the web —\n * three hand-listed copies existed before, and the web's was missing two members.\n */\nexport const EXECUTION_STATUS_SETTLED: Record<ExecutionStatus, boolean> = {\n draft: false,\n validating: false,\n validated: false,\n validation_failed: true,\n pending_approval: false,\n approved: false,\n rejected: true,\n queued: false,\n // Handed to a pool and unclaimed. The machine has NOT stopped — a claim moves it forward\n // and the authorization's own expiry moves it to `failed`, both without anyone asking.\n pending_runner: false,\n running: false,\n succeeded: true,\n rolling_back: false,\n failed: true,\n cancelled: true,\n rolled_back: true,\n rollback_failed: true,\n};\n\n/**\n * ═══ HOW A CANCEL REACHES EACH STATUS ══════════════════════════════════════════════════\n *\n * ★ THREE ANSWERS, NOT A BOOLEAN, AND docs/61 IS WHY. This lived in the web app as\n * `CANCELLABLE: Record<ExecutionStatus, boolean>` with `running: false` and a comment\n * underneath explaining that a running execution IS cancellable, just not through that table —\n * one word carrying two facts, with the second one in prose. The API had the set spelled twice\n * more, as `status: \"running\"` in `recordCancelRequest` and as a four-string literal in\n * `cancel`. Adding `pending_runner`, which is cancellable by the same cooperative mechanism as\n * `running`, would have made that four places to keep in step and two entries that say `false`\n * while meaning `true`.\n *\n * · `no` — the state machine will not leave this status this way. 409.\n * · `direct` — nobody is holding the run; the API settles it to `cancelled` itself.\n * · `cooperative` — a WORKER is holding this run. The API records `cancel_requested_at`; the\n * worker observes it and settles at a safe checkpoint. The control is\n * therefore offered once and then reads as already-requested.\n *\n * It is a fact about the STATE MACHINE, not about a screen — which is why it is here, where\n * the API's two call sites and the browser's button can all read the one answer.\n *\n * Keyed by the union so a new status is a COMPILE ERROR until someone says how a cancel\n * reaches it (charter §4.2 R2).\n */\nexport type ExecutionCancelMechanism = \"no\" | \"direct\" | \"cooperative\";\n\nexport const EXECUTION_CANCEL_MECHANISM: Record<ExecutionStatus, ExecutionCancelMechanism> = {\n draft: \"direct\",\n validating: \"no\",\n validated: \"direct\",\n validation_failed: \"no\",\n pending_approval: \"direct\",\n approved: \"no\",\n rejected: \"no\",\n queued: \"direct\",\n /*\n * ★ CANCELLABLE, AND NOW DELIBERATELY SO (docs/61 §3.1). The founder's screenshot had a\n * Cancel button beside a run waiting on a dead pool only because `running` happened to allow\n * it. This is the state an operator is most likely to want out of — the alternative is\n * sitting out a timeout whose ending they can already predict — so the answer must not\n * depend on which word the run borrowed.\n *\n * ⚠ COOPERATIVE, NOT DIRECT, FOR A MECHANICAL REASON. A run waiting on a pool is parked\n * inside `RunnerDispatchService.awaitReport`, polling its authorization twice a second.\n * Settling it synchronously would leave that worker polling a run already terminal, and the\n * settle it performs a moment later would be an illegal transition out of `cancelled`.\n *\n * It costs nothing in honesty: nothing has started, so unlike `running` there is no\n * half-applied change to tear — which is why the confirm dialog keeps its plain wording.\n */\n pending_runner: \"cooperative\",\n running: \"cooperative\",\n succeeded: \"no\",\n rolling_back: \"no\",\n failed: \"no\",\n cancelled: \"no\",\n rolled_back: \"no\",\n rollback_failed: \"no\",\n};\n\n/** The statuses a worker is holding, derived — the API settles none of these itself. */\nexport const WORKER_HELD_EXECUTION_STATUSES: readonly ExecutionStatus[] =\n EXECUTION_STATUSES.filter((status) => EXECUTION_CANCEL_MECHANISM[status] === \"cooperative\");\n\n/** The statuses the API may settle to `cancelled` on the spot, derived. */\nexport const DIRECTLY_CANCELLABLE_EXECUTION_STATUSES: readonly ExecutionStatus[] =\n EXECUTION_STATUSES.filter((status) => EXECUTION_CANCEL_MECHANISM[status] === \"direct\");\n\n/** The settled statuses, derived — never hand-listed a second time. */\nexport const SETTLED_EXECUTION_STATUSES: readonly ExecutionStatus[] =\n EXECUTION_STATUSES.filter((status) => EXECUTION_STATUS_SETTLED[status]);\n\nexport function isSettledExecutionStatus(status: ExecutionStatus): boolean {\n return EXECUTION_STATUS_SETTLED[status] === true;\n}\n\nexport type ExecutionResult =\n | \"pending\"\n | \"running\"\n | \"success\"\n | \"failed\"\n | \"rolled_back\"\n | \"cancelled\";\n\n// Mirror Prisma ExecEventType/ExecEventLevel (docs/05 §3.4). The append-only\n// `execution_event` log surfaces verbatim to History via @runveric/contracts.\nexport type ExecutionEventType =\n | \"state_change\"\n | \"log\"\n | \"target_resolved\"\n | \"check\"\n | \"error\";\n\nexport type ExecutionEventLevel = \"info\" | \"warn\" | \"error\" | \"success\";\n\nexport type ApprovalStatus =\n | \"pending\"\n | \"approved\"\n | \"rejected\"\n | \"changes_requested\"\n // Terminal: the governed execution was cancelled while awaiting approval, so the\n // gate is withdrawn (not decided by an approver). Excluded from the Approval Center.\n | \"cancelled\";\n\nexport type ApprovalDecisionKind = \"approve\" | \"reject\" | \"request_changes\";\n\nexport const ROLE_KEYS = [\n \"viewer\",\n \"operator\",\n \"approver\",\n \"auditor\",\n \"admin\",\n] as const;\nexport type RoleKey = (typeof ROLE_KEYS)[number];\n\n/**\n * WHAT CAUSED A RUN TO EXIST. One vocabulary for every kind of run in the product.\n *\n * It lived on `operations` as `OPERATION_RUN_TRIGGER_KINDS` while only an Operation Run\n * could say how it was triggered. docs/45 §4.1 gave an `Execution` the same provenance, so\n * the name it was declared under would have made a standalone run carry an *Operation* Run's\n * trigger kind — one concept under two spellings, which is charter §4.2's defect written\n * into a type name. It moves here, to the leaf module every run type can reach.\n *\n * `agent` is unused today and deliberately kept: the audit trail can only say\n * `actorType: \"user\"` because nothing else has ever needed to be said, and a non-human\n * principal is the direction this column exists to make reachable.\n */\nexport const RUN_TRIGGER_KINDS = [\"manual\", \"schedule\", \"api\", \"agent\"] as const;\nexport type RunTriggerKind = (typeof RUN_TRIGGER_KINDS)[number];\n","// ═══ CLASS 1 — THE BRAND. THE ONE VALUE IN THIS REPOSITORY THAT IS GOING TO CHANGE ═════\n//\n// ★ THIS FILE IS THE MUTABLE HALF OF A DELIBERATE SPLIT, and the split is the whole point of\n// docs/95. Three kinds of string in this codebase spell \"Opera\", and they have OPPOSITE rules:\n//\n// · what a person READS on a screen or in a boot log — here, and it may change;\n// · what the HOSTED EXECUTION SITE is called — `run-placement.ts`, a LABEL for\n// a concept the brand does not own, and it may change SEPARATELY;\n// · what another system PARSES — `wire-identity.ts`, frozen.\n//\n// ⛔ NOTHING IN `wire-identity.ts` OR `run-placement.ts` MAY IMPORT THIS FILE, and nothing here\n// may be interpolated into a wire identifier. `` `${BRAND_DOMAIN}/package-result/v1` `` is the\n// single most likely way to ship the wrong thing: it welds a frozen protocol id to the one\n// value that is going to change, so a rebrand silently refuses every customer package that has\n// already been published. The independence is asserted — not merely intended — by\n// `brand-vocabulary-independence.spec.ts`, which reads these files' SOURCE and fails if either\n// of the frozen declarations so much as mentions this one.\n//\n// ⚠ A RENAME IS NOT A FIND-REPLACE OF \"Opera\". Editing `BRAND_NAME` below moves every site that\n// spells the FULL product name, and `pnpm brand:guards` (rule B1) keeps it that way by refusing a\n// second author of that string anywhere in the tree.\n//\n// ★ IT NOW MOVES THE SHORT FORM TOO (docs/96). `BRAND_SHORT_NAME` below is the bare \"Opera\" a\n// customer reads in \"Opera runs it in…\", and rule B1b refuses a second author of it. The census\n// that made this necessary: 372 non-comment sites across `apps` and `packages` — not the 162\n// this comment used to claim, which was scoped to `apps/*/src` and could not see the three\n// published packages where the largest concentrations actually were.\n//\n// ⇒ A rename is now ONE LINE OF PRODUCT CODE: edit `BRAND_NAME`. Everything else in this file\n// is DERIVED from it, and rules B1/B1b keep every call site reading the declaration. Measured,\n// not asserted: the whole suite — 359 + 281 + 118 + 48 + 2728 + 1405 — passes unchanged with\n// this value set to \"Runveric\".\n//\n// ⚠ AND THE HONEST FOOTNOTE, because \"one line\" is the kind of claim that gets repeated.\n// `tools/brand-vocabulary.mjs` (6) and `tools/verify-brand-vocabulary.mjs` (22) spell the\n// CURRENT name outside their comments, and they must be edited in the same commit. That is\n// deliberate, not debt: those literals are what pins the OLD name as forbidden, and litmus\n// case 9 only bites — a declaration gutted to `\"__gutted__\"` must be REFUSED — precisely\n// because the guard's pattern is independent of the value it is checking. Derive them from\n// this file and that case goes green against a tree with no vocabulary in it at all.\n//\n// ⚠⚠ AND A SECOND LINE OF PRODUCT CODE, WHICH THE FOOTNOTE ABOVE ORIGINALLY MISSED.\n// `HOSTED_EXECUTION_LABEL` in `run-placement.ts` is still the literal `\"Opera's cloud\"`. It has\n// its own declaration BECAUSE it names a concept the company does not own and may be renamed\n// separately (docs/95 §4.1) — but its VALUE is a brand possessive, so a rename does not leave it\n// alone: set `BRAND_NAME` to \"Runveric\" and four customer-visible components\n// (`where-runs-execute-panel`, `runners/[poolId]`, `runners/page`, `runs-on-callout`) go on\n// rendering the OLD brand. Separate declaration, not optional edit. Measured, not assumed: with\n// the brand renamed, `\"Opera's cloud\"` is the ONLY emitted literal left in the built contracts.\n//\n// ⇒ So, honestly: TWO lines of product code — `BRAND_NAME` here and `HOSTED_EXECUTION_LABEL`\n// there — plus 28 in the two guard files. `pnpm brand:guards` fails LOUDLY (\"no longer declares\n// the \\\"brand\\\" vocabulary\") until the guards move; the hosted label fails nothing, which is\n// exactly why it is written down here.\n\n/**\n * The product, as a person reads it. Six call sites today (docs/95 §2 Class 1): the browser\n * tab title, the sign-out `/callback` link, two mutually exclusive login-screen `<h1>`, and\n * the two boot log lines.\n *\n * ⚠ IT IS DELIBERATELY NOT `as const`. A literal type here would be a promise that this value\n * never changes, which is the opposite of what it is for — and it would make the rename a\n * cascade of type errors across every consumer instead of a one-line edit.\n */\n\n\nexport const BRAND_NAME = \"Runveric\";\n\n/**\n * ═══ THE SHORT FORM — DERIVED, NOT DECLARED, AND THAT IS THE WHOLE ARGUMENT ════════════\n *\n * The bare product name a person reads mid-sentence: \"Opera runs it in your cloud\", \"Opera\n * couldn't verify the connector\". **372** non-comment sites spell some form of it (docs/96\n * §1.1) and until docs/96 not one of them had an author — B1 matched \"Opera Cloud\" and a probe\n * file containing only the short form passed the guard, verified.\n *\n * ★ WHY THIS IS DERIVED AND NOT A SECOND CONSTANT. docs/95's test for \"is this its own class?\"\n * is whether it can change SEPARATELY. `HOSTED_EXECUTION_LABEL` earned its own declaration\n * because it names a concept the company does not own, so it may be renamed on its own. The\n * short form cannot: it is always a function of the product name. A second constant would be a\n * second thing to edit — and a rename that is two lines is exactly what this slice exists to\n * prevent. `BRAND_SLUG` below is derived for the same reason and was the precedent.\n *\n * ⚠ AND IT IS WHAT KEEPS THIS SLICE A NO-OP ON THE WIRE AND ON THE SCREEN. The alternative —\n * sweeping the 372 sites onto `BRAND_NAME` itself — silently rewrites 309 customer-visible\n * sentences from \"Opera\" to \"Opera Cloud\", which is prose change at scale disguised as a\n * refactor. Resolving to the FIRST WORD leaves every one of those sentences byte-identical\n * today, and moves all of them on the day `BRAND_NAME` changes.\n *\n * \"Opera Cloud\" → \"Opera\". \"Runveric\" → \"Runveric\" — a one-word brand is its own short form,\n * so nothing here needs revisiting when the name lands.\n */\nexport const BRAND_SHORT_NAME = BRAND_NAME.split(\" \")[0]!;\n\n/**\n * ═══ THE ARTICLE, BECAUSE A VARIABLE NOUN TAKES A VARIABLE ARTICLE ═════════════════════\n *\n * ★ A HAZARD THE SWEEP CREATES AND NOTHING ELSE WOULD HAVE CAUGHT. Seven sentences read\n * \"an Opera account\", \"author an Opera action\", \"This is an Opera defect\". They were correct\n * while the noun was fixed. Interpolating the brand into them makes the ARTICLE wrong the day\n * the name changes — \"an Runveric account\" — and no guard, type or test in this repository\n * has anything to say about English grammar. `pnpm brand:guards` would stay green.\n *\n * ⇒ So the article is derived too, and the rename stays one line. Same rule as `anArticle` in\n * `packages.ts`, which already solved this for runtime-kind nouns.\n *\n * ⚠ IT IS A LETTER TEST, NOT A SOUND TEST — \"an hour\", \"a university\" and \"an MSP\" all defeat\n * it. That is acceptable for a value this file owns and a human chooses: when the new name\n * lands, read these seven sentences once. It is not acceptable as a general-purpose helper,\n * which is why it is not exported as one.\n */\nexport const BRAND_ARTICLE = /^[aeiou]/i.test(BRAND_SHORT_NAME) ? \"an\" : \"a\";\n\n/** Sentence-initial form of {@link BRAND_ARTICLE}. */\nexport const BRAND_ARTICLE_CAPITALISED = BRAND_ARTICLE === \"an\" ? \"An\" : \"A\";\n\n/**\n * ═══ CLASS 4 — BRAND-DERIVED, OUTBOUND, AND NOT FROZEN ═════════════════════════════════\n *\n * Sent to third parties as a `User-Agent`. GitHub does not care what it says, so unlike a wire\n * identifier this one SHOULD follow the brand — which is exactly why it is DERIVED here rather\n * than spelled at the two registry call sites that send it.\n *\n * ★ THIS IS THE CLASS docs/95's FIRST DRAFT MISSED ENTIRELY, and the reason it was missed is\n * worth keeping: a reader holding only \"visible\" and \"wire\" has nowhere to file an outbound\n * header. It is invisible in the UI, so it is not Class 1; it is read by somebody else's\n * server, so it looks like Class 3. It is neither, and naming it is what makes it findable.\n *\n * The separator is a hyphen because RFC 9110 `User-Agent` products may not contain spaces.\n * Any brand at all survives this: \"Opera Cloud\" → `Opera-Cloud`, \"Tolmen\" → `Tolmen`.\n */\nexport const BRAND_SLUG = BRAND_NAME.replace(/[^A-Za-z0-9]+/g, \"-\").replace(/^-|-$/g, \"\");\n\n/** The `User-Agent` both GitHub registries send when importing an action package. */\nexport const PACKAGE_IMPORTER_USER_AGENT = `${BRAND_SLUG}-Action-Package-Importer`;\n","// ═══ CLASS 3 — THE WIRE. FROZEN, AND IN THE ONLY LAYER BOTH ENDS CAN REACH ═════════════\n//\n// ★ WHY THIS FILE EXISTS AT ALL, which is a LAYERING finding rather than a tidiness one.\n//\n// `runveric.dev/package-result/v1` had a single author — `PROTOCOL_VERSION` in\n// `apps/api/src/modules/packages/infrastructure/package-runtime-protocol.ts` — and that author\n// had exactly one occurrence in the repository: its own export line. Nothing imported it.\n// Meanwhile the ACCEPTOR of that protocol, `@runveric/action-manifest`'s\n// `validatePackageResult`, hardcoded the same string twice.\n//\n// That second author was STRUCTURAL, not sloppy. `@runveric/action-manifest` is a workspace\n// DEPENDENCY of `@runveric/api`, so it cannot import from `apps/api` — not by policy, by\n// packaging. The declaration sat in the APPLICATION layer and was consumed in the LIBRARY\n// layer, and the literal was the only way across. `@runveric/contracts` is the one package every\n// other package already depends on, so the fix is the layer, not the literal.\n//\n// ⛔ EVERY VALUE HERE IS FROZEN, and \"frozen\" is not a style. These strings live in systems we\n// do not control: published customer packages that hardcode the protocol version, installed\n// private runners speaking the channel protocol, and client code parsing RFC 9457 problem\n// types out of our responses. `apps/api/test/fixtures/` is the proof rather than the claim —\n// sixteen PowerShell and YAML fixtures simulating customer packages hardcode these exact\n// bytes, and `brand-wire-external-witness.spec.ts` reads them at RUN TIME and compares.\n//\n// ⛔ THIS FILE MAY NOT IMPORT `./brand`, and no value here may be assembled by interpolation.\n// A rebrand must not be able to reach a wire identifier. `brand-vocabulary-independence.spec.ts`\n// reads this file's SOURCE and fails if it mentions the brand module at all.\n//\n// ⚠ HOW MUCH THE TYPES BELOW ACTUALLY BUY, stated honestly (docs/93's mechanism, docs/95 §4.4).\n// Each identifier's LITERAL TYPE is derived from its one declaration and every consumer is\n// typed against it, so a ONE-SIDED edit — changing the constant without the shapes, or a call\n// site writing a different string — is a `tsc` error. A COORDINATED edit of both still\n// compiles. Nothing in the type system prevents that, and a `Frozen<T>` brand would not\n// either: the string stays editable. The only thing that catches a coordinated edit is the\n// external witness in `brand-wire-external-witness.spec.ts`, which compares these values to\n// artifacts this repository's application code did not author and may not touch.\n\n// ─── THE PACKAGE PROTOCOL (docs/22) ────────────────────────────────────────────────────\n\n/**\n * The structured result a package writes to `/runveric/output/result.json`.\n *\n * Read by `validatePackageResult` in `@runveric/action-manifest` — the ONE acceptor — and written\n * by every runtime that starts a package: the trusted subprocess, the Container Apps job\n * sandbox, and a private runner on a customer's own Docker host.\n */\nexport const PACKAGE_RESULT_PROTOCOL_VERSION = \"runveric.dev/package-result/v1\";\nexport type PackageResultProtocolVersion = typeof PACKAGE_RESULT_PROTOCOL_VERSION;\n\n/** The non-secret execution metadata written to `/runveric/input/context.json`. */\nexport const PACKAGE_EXECUTION_PROTOCOL_VERSION = \"runveric.dev/package-execution/v1\";\nexport type PackageExecutionProtocolVersion = typeof PACKAGE_EXECUTION_PROTOCOL_VERSION;\n\n/**\n * The `apiVersion` of an action manifest — the first line of every `action.yaml` a customer\n * writes, checked by `requiredConst` in the manifest validator and emitted by the scaffold the\n * published CLI runs on an author's laptop.\n */\nexport const ACTION_MANIFEST_API_VERSION = \"runveric.dev/action/v1\";\nexport type ActionManifestApiVersion = typeof ACTION_MANIFEST_API_VERSION;\n\n/** The envelope a work item carries to a runner that claimed it. */\nexport const PACKAGE_WORK_ITEM_VERSION = \"runveric.dev/package-work-item/v1\";\nexport type PackageWorkItemVersion = typeof PACKAGE_WORK_ITEM_VERSION;\n\n/**\n * ⚠ THE ONE VALUE HERE THAT IS TRANSMITTED TO SOFTWARE ALREADY INSTALLED ELSEWHERE.\n *\n * Sent to registered private runners on every claim, heartbeat and step dispatch\n * (`runner-channel.service.ts:139`, `:509`, `:569`). A runner that receives a version it does\n * not know refuses the work — which is the correct behaviour and also why this string cannot\n * be edited by anyone who has not shipped a new runner first.\n */\nexport const RUNNER_PROTOCOL_VERSION = \"runveric.dev/runner-channel/v2\";\nexport type RunnerProtocolVersion = typeof RUNNER_PROTOCOL_VERSION;\n\n/**\n * ═══ THE CONTRACT AN ENGINE ACTION SPEAKS (docs/128 §4) ════════════════════════════════\n *\n * The messages between the engine and an action runtime: the invocation the runtime fetches\n * once, and the events, checkpoint and report it posts back. An action's manifest declares the\n * contract it speaks (`execution.contract`) and the engine refuses one it does not list in\n * `ACTION_CONTRACTS` (`action-protocol.ts`).\n *\n * ⛔ IT WILL BE COMPILED INTO IMAGES BUILT IN OTHER REPOSITORIES. The runtime base image is ours,\n * but every action image pins a digest of it, so once one is published this string lives in\n * bytes nobody here can rebuild. A shape an older runtime would misread is a `v2` shipped\n * beside this one and supported for at least twelve months (docs/128 §4.3), never an edit here.\n */\nexport const ACTION_PROTOCOL_V1 = \"runveric.dev/action-protocol/v1\";\nexport type ActionProtocolV1 = typeof ACTION_PROTOCOL_V1;\n\n// ─── THE EVIDENCE PACK (docs/119) ──────────────────────────────────────────────────────\n\n/**\n * The `schemaVersion` of an Operation's evidence pack — the first field of a JSON file an\n * auditor is handed and may archive for seven years.\n *\n * ⚠ THE ONE VALUE HERE THAT OUTLIVES EVERY SYSTEM THAT READS IT. The others are parsed by\n * software we can at least ship a new version of; this one is read by a person, or by their\n * script, years after the export, from a file in somebody else's archive. It names the SHAPE\n * of that file, so it moves only when the shape does — a new field an old reader would\n * misread is a `v2`, never an edit here.\n */\nexport const EVIDENCE_PACK_SCHEMA_VERSION = \"runveric.dev/evidence-pack/v1\";\nexport type EvidencePackSchemaVersion = typeof EVIDENCE_PACK_SCHEMA_VERSION;\n\n// ─── THE CATALOG DELIVERY FORMATS (docs/121) ───────────────────────────────────────────\n\n/**\n * The `schemaVersion` of a CATALOG RELEASE — the immutable document that names each action\n * artifact by digest, and the one thing the product pins.\n *\n * ★ IT NAMES THE KIND AS WELL AS THE VERSION, and that is why it is a path rather than a number.\n * Pinning an ACTION artifact's digest by mistake must be refused by name (\"this is an action\n * artifact, not a release\"), and a bare `1` would read as a perfectly good release. ⛔ Published\n * to a public registry and read by a sync job whose image moves on a DIFFERENT clock from the\n * artifact: a shape an older job would misread is a `v2`, never an edit here.\n */\nexport const CATALOG_RELEASE_SCHEMA_V1 = \"runveric.dev/catalog-release/v1\";\nexport type CatalogReleaseSchemaV1 = typeof CATALOG_RELEASE_SCHEMA_V1;\n\n/** The `schemaVersion` of ONE action's artifact: its manifest's bytes and their provenance. */\nexport const CATALOG_ACTION_ARTIFACT_SCHEMA_V1 = \"runveric.dev/catalog-action/v1\";\nexport type CatalogActionArtifactSchemaV1 = typeof CATALOG_ACTION_ARTIFACT_SCHEMA_V1;\n\n/**\n * The `schemaVersion` of an ENGINE action's artifact (docs/128 §17.9): v1's manifest and provenance,\n * plus `image: { digest }` — the image the action runs, in the artifact's own repository. A v1\n * artifact whose manifest declares `execution` is refused, and so is a v2 whose manifest does not:\n * the version says which kind of action it carries, and the manifest must agree.\n */\nexport const CATALOG_ACTION_ARTIFACT_SCHEMA_V2 = \"runveric.dev/catalog-action/v2\";\nexport type CatalogActionArtifactSchemaV2 = typeof CATALOG_ACTION_ARTIFACT_SCHEMA_V2;\n\n/**\n * The OCI media type of both documents — the manifest's `artifactType` and its single layer.\n *\n * ONE type for both kinds, deliberately: the document's `schemaVersion` is the authority on what\n * it is. A second, per-kind media type would be a second author of the same fact, and the two\n * could disagree inside one artifact.\n */\nexport const CATALOG_ARTIFACT_MEDIA_TYPE = \"application/vnd.runveric.catalog-artifact+json\";\nexport type CatalogArtifactMediaType = typeof CATALOG_ARTIFACT_MEDIA_TYPE;\n\n// ─── THE PROBLEM-TYPE NAMESPACE (RFC 9457) ─────────────────────────────────────────────\n\n/**\n * ═══ ONE AUTHOR, WHERE THERE WERE THIRTEEN ═════════════════════════════════════════════\n *\n * Four modules declared their own `const ERROR_BASE` and nine more spelled the URI inline at\n * the point of throwing. docs/95 §3 counted the four named ones; the census found the other\n * nine, which is the more useful number because a guard that only knew about `ERROR_BASE`\n * would have left them standing.\n *\n * ⚠ IT IS A WIRE VALUE, NOT A BRAND ONE, despite reading like a marketing domain. RFC 9457\n * §3.1.1: the `type` member is an identifier, and clients are expected to match on it. Ours\n * appears in responses customers parse today, so it moves when the problem CLASS changes —\n * NOT when the company is renamed.\n *\n * ═══ ⛔ AND IT MOVED ONCE ANYWAY, FOR A REASON THAT IS NOT A REBRAND (docs/105) ══════════\n *\n * The sentence above was written beside the old value and it was right; the old value was\n * `opera.cloud`, and that host is registered through Opera Software's own brand-protection\n * registrar. It was never a domain this company could serve, so every RFC 9457 `type` we\n * emitted pointed a customer debugging a failed run at a browser vendor's website. The host\n * moved because we do not own it — not because the name on the door changed.\n *\n * ⇒ SO THE RULE SURVIVES AS WRITTEN. A future rebrand does not touch this value. If anyone\n * reaches for this line again, the question to answer first is whether the host is ours.\n *\n * ⚠ `runveric.dev` RESOLVES AND SERVES NOTHING — Porkbun A records, no HTTPS listener, so\n * `curl` returns 000. Dereferencing a type URI is a CONNECTION FAILURE WE OWN, not a 404 we\n * own, and RFC 9457 §3.1.1 only *encourages* the URI to dereference. Serving it is a separate\n * decision (docs/105 §6); nothing below depends on it.\n *\n * ⚠ The PATH SHAPE did not move. `…/errors/<type>` is unchanged; only the host is different,\n * so a client matching on the last segment is unaffected and one matching the whole URI is not.\n */\nexport const PROBLEM_TYPE_BASE = \"https://runveric.dev/errors\";\nexport type ProblemTypeBase = typeof PROBLEM_TYPE_BASE;\n\n/**\n * One problem type, by its slug — `problemType(\"forbidden\")`.\n *\n * ★ A FUNCTION RATHER THAN A BARE BASE, because a bare base leaves every call site to join the\n * path itself and one of them eventually forgets the separator. It also gives the guard a\n * shape to recognise: a `type:` field built any other way is a second author by construction.\n */\nexport function problemType(slug: string): string {\n return `${PROBLEM_TYPE_BASE}/${slug}`;\n}\n","/**\n * ═══ WHAT A REFUSAL LOOKS LIKE ON THE WIRE ═════════════════════════════════════════════\n *\n * The api speaks RFC 9457 Problem Details (docs/04 §1) and it has always spoken it correctly.\n * What was missing is this file: the shape was declared PRIVATELY inside the api\n * (`platform/http/parameter-validation.ts`) and never published, so the web re-spelled it from\n * memory — `errors?: Array<{ path?: string; message?: string }>` against a server sending\n * `{ field, message }`.\n *\n * Nothing in the build could notice. `error.path` is simply `undefined` on every entry, the\n * `?? \"request\"` fallback fires for all of them, and a customer opening the connector wizard\n * was told:\n *\n * request: Required.; request: Required.; request: Required. (PARAM_INVALID)\n *\n * Three empty fields, named three times as \"request\", plus a machine code. The comment above\n * that line said \"field-level validation errors name the field, which beats any sentence about\n * the form\" — the intent was right and the property was wrong, which is the only kind of defect\n * a shared type prevents and a careful reviewer does not.\n *\n * So the vocabulary is declared ONCE, here (charter §4.2), and both sides import it. Rename\n * `field` and the api stops compiling; the web is dragged along with it.\n *\n * ⚠ A DECLARED TYPE IS NOT A VERIFIED WIRE. This file pins what the two sides BELIEVE; it\n * cannot prove the bytes match. That is what `parseProblemDocument` is for, and why an api e2e\n * runs a REAL 422 through it (docs/42 §3.2) — two files in this repo agreeing while both\n * disagreed with reality is exactly how `@runveric/cli@0.1.1` 404'd on npm.\n */\nimport type { ManifestValidationError } from \"./packages\";\n\n/**\n * One field-level refusal: the field a reader must change, and what to change about it.\n *\n * `field` is the parameter's id as the schema declares it (`azureTenantId`), not its label —\n * a form maps it back to the label it rendered, and a client with no form shows the id, which\n * still beats \"request\".\n */\nexport interface FieldError {\n field: string;\n message: string;\n}\n\n/**\n * One entry of a problem document's `errors[]`, in EVERY shape this api really emits.\n *\n * ★ THREE, NOT ONE — and that is the finding behind docs/42 D2. Sweeping the concept rather\n * than the sighting turned up three vocabularies sharing one property name:\n *\n * `FieldError` `{ field, message }` — ParamInvalidException (422\n * PARAM_INVALID): connections,\n * executions. The customer's case.\n * `ManifestValidationError` `{ path, message, keyword? }` — manifestInvalid (422\n * PACKAGE_MANIFEST_INVALID): a\n * JSON-pointer INTO A DOCUMENT, not\n * a form field, so it keeps its own\n * name and is normalized on read.\n * `string` a blocking check's title — operations + scheduling\n * (BadRequestException).\n *\n * The old reader knew only the middle one, which is why `error.path ?? \"request\"` was not an\n * invention: it was the RIGHT property for the WRONG endpoint. Against the string form it was\n * worse still — a string has neither `path` nor `message`, so twelve blocked checks rendered as\n * \"request: invalid\" twelve times, a sentence naming nothing at all.\n *\n * A union is the honest declaration. `problemFieldErrors` is the one place that flattens it, so\n * a fourth shape has to be added HERE rather than guessed at a call site.\n */\nexport type ProblemErrorEntry = FieldError | ManifestValidationError | string;\n\n/**\n * An RFC 9457 problem document as this api emits it.\n *\n * The two human members are NOT interchangeable and the ordering matters (see the web's\n * `problemMessage`): `title` is the CLASS of problem and is identical for every occurrence\n * (\"You do not have permission to perform this action.\"); `detail` is THIS occurrence (\"This\n * needs the \\\"execution:create\\\" permission, which you do not have.\"). Reading `title` first\n * throws away everything specific the server took the trouble to say.\n *\n * Members beyond RFC 9457's five are extensions, which the RFC allows. Those a GENERIC reader\n * needs are declared here; ones only their own client reads (`check` on a trial-run refusal,\n * `stepIndex` on an operation refusal) extend this interface where they are read.\n */\nexport interface ProblemDocument {\n /** A URI naming the problem class — `https://runveric.dev/errors/validation`. */\n type?: string;\n /** The problem class, in a sentence. The same for every occurrence. */\n title?: string;\n status?: number;\n /** THIS occurrence, in a sentence. The most specific thing the server said. */\n detail?: string;\n /**\n * The machine code — `PARAM_INVALID`, `FORBIDDEN`.\n *\n * ⚠ FOR A LOG AND A SUPPORT CONVERSATION, NEVER FOR A READER (docs/42 §3.4). It stays in the\n * document, where a developer reading the network tab still has it, and it is not appended to\n * anybody's sentence.\n */\n code?: string;\n /** The permission a 403 was refused for — B7's whole subject. */\n permission?: string;\n /** Field-level refusals. See `ProblemErrorEntry` for why this is a union. */\n errors?: ProblemErrorEntry[];\n /**\n * Nest's own default shape, not ours: `BadRequestException(\"…\")` puts a string here and its\n * ValidationPipe puts an array of them. Declared because it is genuinely on the wire, so a\n * reader that handles it is reading rather than guessing.\n */\n message?: string | string[];\n}\n\n/** Is this a `{ field, message }` entry — the parameter-validation vocabulary? */\nfunction isFieldError(entry: unknown): entry is FieldError {\n if (typeof entry !== \"object\" || entry === null) return false;\n const record = entry as Record<string, unknown>;\n return typeof record.field === \"string\" && typeof record.message === \"string\";\n}\n\n/** Is this a `{ path, message }` entry — the manifest-validation vocabulary? */\nfunction isManifestError(entry: unknown): entry is ManifestValidationError {\n if (typeof entry !== \"object\" || entry === null) return false;\n const record = entry as Record<string, unknown>;\n return typeof record.path === \"string\" && typeof record.message === \"string\";\n}\n\n/** An optional member is absent, or it is the type it claims to be. Never \"close enough\". */\nfunction optional(value: unknown, type: \"string\" | \"number\"): boolean {\n return value === undefined || typeof value === type;\n}\n\n/**\n * Read a response body as a problem document — or refuse it.\n *\n * ⚠ THIS IS STRICT ON PURPOSE, AND THAT IS THE WHOLE POINT OF IT. A parser that accepted any\n * object would make the api's wire assertion (docs/42 §3.2) vacuous: \"the 422 parsed\" would be\n * true of `{}` and of a server that had renamed `field` to `fieldName` overnight. So every\n * member present must be the declared type, and every `errors[]` entry must be one of the three\n * shapes `ProblemErrorEntry` names. A body that satisfies this really is the document both\n * sides declared.\n *\n * Returns `null` rather than throwing: a non-JSON or non-problem error body is an ordinary\n * thing for a proxy or a gateway to send, and the caller has a labelled status to fall back on.\n */\nexport function parseProblemDocument(body: unknown): ProblemDocument | null {\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) return null;\n const record = body as Record<string, unknown>;\n\n if (!optional(record.type, \"string\")) return null;\n if (!optional(record.title, \"string\")) return null;\n if (!optional(record.status, \"number\")) return null;\n if (!optional(record.detail, \"string\")) return null;\n if (!optional(record.code, \"string\")) return null;\n if (!optional(record.permission, \"string\")) return null;\n\n if (record.message !== undefined) {\n const ok =\n typeof record.message === \"string\" ||\n (Array.isArray(record.message) && record.message.every((one) => typeof one === \"string\"));\n if (!ok) return null;\n }\n\n if (record.errors !== undefined) {\n if (!Array.isArray(record.errors)) return null;\n const ok = record.errors.every(\n (entry) => typeof entry === \"string\" || isFieldError(entry) || isManifestError(entry),\n );\n if (!ok) return null;\n }\n\n return record as ProblemDocument;\n}\n\n/**\n * Every field-level refusal in a problem document, flattened to ONE vocabulary.\n *\n * An entry that names no field — a bare blocking-check title — comes back with `field: \"\"`. It\n * is still a refusal a reader must be shown; it just cannot be attached to an input, so a form\n * lists it in the banner instead (docs/42 §3.3). Callers branch on the empty string rather than\n * on which of three shapes the server happened to use.\n */\nexport function problemFieldErrors(problem: ProblemDocument): FieldError[] {\n const entries = problem.errors ?? [];\n return entries.map((entry) => {\n if (typeof entry === \"string\") return { field: \"\", message: entry };\n if (isFieldError(entry)) return { field: entry.field, message: entry.message };\n return { field: entry.path, message: entry.message };\n });\n}\n","// Permission catalogue (docs/06 §3). Guards reference these atoms.\n//\n// `template:read`/`template:write` were removed when the templates module was deleted (docs/31\n// §5.7). They are not \"retired members kept for history\": a permission is only ever evaluated\n// against a live request, never stored — role assignments persist a `RoleKey`, and the set is\n// derived from `ROLE_PERMISSIONS` at request time — so a member with no guard behind it is a\n// grant that can authorize nothing. Audit rows that mention templates are untouched; they record\n// what happened, not what may happen.\n//\n// ═══ TWO KINDS OF PERMISSION, AND ONLY ONE OF THEM CAN BELONG TO A ROLE (docs/124 §3.3) ═══════\n//\n// A WORKSPACE permission is what a `RoleKey` carries, so any workspace admin can hand it out —\n// they hold `rbac:manage`. A PLATFORM permission acts on every workspace at once, so it is\n// granted by the deployment's configuration to a named issuer + subject and never by a role.\n// `ROLE_PERMISSIONS` is typed `WorkspacePermission[]`, which makes \"add a platform permission to\n// a role\" a `pnpm typecheck` failure naming the atom, not a convention somebody in a hurry skips.\n//\n// `Permission` stays the union, so every guard, decorator and `/me` reader keeps one type.\n\n/**\n * The permissions only configuration can grant — array-first, declared once (charter §4.2).\n *\n * ⛔ NEVER A ROLE'S. Roles are per-workspace and every workspace admin holds `rbac:manage`, so a\n * role carrying one of these is one any customer's admin could grant themselves — and then act\n * on every other customer. Adding a member here adds it to every configured operator at once:\n * the set is granted whole (`identity.service.ts`, `resolveContext`), never piecemeal.\n */\nexport const PLATFORM_PERMISSIONS = [\n // Which catalog release is live for every workspace (docs/121). Pinning one changes what EVERY\n // workspace can run, so it is neither `policy:manage` (one workspace's own governance) nor\n // `catalog:read` (the right to browse).\n \"catalog:release\",\n] as const;\nexport type PlatformPermission = (typeof PLATFORM_PERMISSIONS)[number];\n\n/** Everything a `RoleKey` may carry. */\nexport type WorkspacePermission =\n | \"catalog:read\"\n | \"subscription:read\"\n | \"operation:read\"\n | \"operation:write\"\n | \"execution:read\"\n | \"execution:create\"\n | \"execution:validate\"\n | \"execution:submit\"\n | \"execution:cancel\"\n | \"execution:rollback\"\n | \"execution:stream\"\n | \"evidence:read\"\n | \"approval:read\"\n | \"approval:decide\"\n | \"audit:read\"\n // ═══ READING WHERE RUNS EXECUTE, AND CHANGING IT, ARE TWO RIGHTS (docs/56 §3.1) ═════\n //\n // `connection:manage` was the ONLY connection atom, so every read of connector\n // configuration sat behind the right to CHANGE it. The runner-pool reads inherited that,\n // and a non-admin who could not read them was shown \"There are no runner pools yet\" — a\n // refusal rendered as an absence, on the one screen that says whether execution leaves\n // Opera's cloud.\n //\n // ★ THE SPLIT IS NOT A PERMISSION LOOSENING, IT IS A DIFFERENT QUESTION. An approver\n // deciding a run is entitled to know it will execute on machines the customer operates\n // rather than in ours (docs/56 §3.2) — the same fact the install panel already states out\n // loud to whoever installs a runner. Nothing this atom grants can change a binding, mint a\n // registration token, or reach a runner: those stay on `connection:manage`.\n | \"connection:read\"\n | \"connection:manage\"\n | \"package:manage\"\n | \"policy:manage\"\n | \"subscription:manage\"\n | \"rbac:manage\";\n\nexport type Permission = WorkspacePermission | PlatformPermission;\n\n/*\n * ★ THE SPLIT ONLY HOLDS IF THE TWO HALVES ARE DISJOINT. `ROLE_PERMISSIONS` refuses a platform\n * atom because it is not a `WorkspacePermission` — so the one edit that would defeat the guard\n * without touching it is spelling the atom into the workspace union as well. This line stops\n * compiling if that happens, and the error names the atom:\n * Type 'true' is not assignable to type '\"catalog:release\"'.\n */\ntype InBothHalves = Extract<WorkspacePermission, PlatformPermission>;\nconst _workspaceAndPlatformAreDisjoint: [InBothHalves] extends [never] ? true : InBothHalves = true;\nvoid _workspaceAndPlatformAreDisjoint;\n","import type { Permission } from \"./permissions\";\nimport type { RoleKey } from \"./enums\";\n\n/**\n * Who a verified OIDC token says this is: the issuer, and the subject that issuer asserts. Neither\n * half is editable in a profile form, and a subject means nothing without its issuer — this\n * deployment verifies more than one. It is the key a platform operator is named by (docs/124 §3.1).\n */\nexport interface VerifiedPrincipal {\n issuer: string;\n subject: string;\n}\n\n/**\n * The explicit context every facade and port receives (docs/11 §7, docs/12 §2.5).\n * Threaded from the first commit so an in-process call can become a remote call\n * unchanged. No module reads ambient auth state — it is always passed.\n */\nexport interface RequestContext {\n /** Opera Cloud tenant id (derived from the Entra `tid` claim). */\n tenantId: string;\n /**\n * Entra tenant id from the validated interactive token (`tid`). Present on HTTP\n * request contexts; worker contexts may omit it because they are reconstructed\n * from persisted Opera rows.\n */\n entraTenantId?: string;\n /** Opera Cloud user id (derived from the Entra `oid` claim). */\n userId: string;\n /** Effective roles for this user in this tenant. */\n roles: RoleKey[];\n /**\n * Effective permission set: what the roles grant, plus `PLATFORM_PERMISSIONS` when — and only\n * when — `platformAuthority` is set.\n */\n permissions: Permission[];\n /**\n * ═══ THIS REQUEST HOLDS PLATFORM PERMISSIONS, AND CONFIGURATION GRANTED THEM (docs/124 §3.5) ═\n *\n * Set by `resolveContext` in the same expression that adds the permissions, when the verified\n * `principal` is a pair the deployment's `PLATFORM_OPERATORS` names. No role can grant a\n * platform permission (it does not compile), so this is the only way one is ever held.\n *\n * `true` or absent — never `false`, so \"no platform authority\" has one spelling. Worker\n * contexts never carry it: they are rebuilt from rows, and a row is not a verified token.\n */\n platformAuthority?: true;\n /**\n * The verified issuer + subject this HTTP request authenticated as — the exact pair\n * `PLATFORM_OPERATORS` is matched against, carried so `GET /me` reports the SAME value the match\n * read rather than a stored copy of it. Absent on worker contexts, which have no token.\n */\n principal?: VerifiedPrincipal;\n /** Correlation id for tracing a request across API → queue → worker. */\n correlationId: string;\n}\n\nexport function hasPermission(ctx: RequestContext, p: Permission): boolean {\n return ctx.permissions.includes(p);\n}\n","// The Plane-A role → permission matrix (docs/06 §3). Single source of truth for\n// the permission set both the API guards (later steps) and the stub `/me`\n// permissions (Step 2) derive from. Keep in lockstep with the matrix table.\nimport type { Permission, WorkspacePermission } from \"./permissions\";\nimport type { RoleKey } from \"./enums\";\n\n// Read-only baseline shared by every role.\nconst VIEWER: WorkspacePermission[] = [\n \"catalog:read\",\n \"subscription:read\",\n // Every role can SEE the tenant's Operations — an approver reviewing a run and an\n // auditor reconstructing one both need the procedure, not just its executions.\n \"operation:read\",\n \"execution:read\",\n \"execution:stream\",\n \"evidence:read\",\n // ═══ WHERE A RUN EXECUTES IS PART OF READING A RUN (docs/56 §3.2) ═══════════════════\n //\n // In the baseline, so viewer, operator, APPROVER, auditor and admin all hold it — and the\n // two the doc names are covered by the two that matter: an approver decides whether a run\n // may leave Opera's cloud, and an auditor reconstructs one that already did. Granting it\n // to each of them separately would be five places to keep a single \"may read the connector's\n // configuration\" fact in step.\n //\n // ⚠ IT IS A READ AND ONLY A READ. Binding a scope to a pool, minting a registration token,\n // draining or revoking a runner all stay on `connection:manage`, which stays admin-only.\n \"connection:read\",\n];\n\n/**\n * ⛔ `WorkspacePermission[]`, NOT `Permission[]` (docs/124 §3.3). A role is grantable by any\n * workspace admin, so a platform permission here would be one a customer could hand themselves.\n * Writing one into any list below fails `pnpm typecheck` naming the atom; a platform operator is\n * named by the deployment's configuration instead (`PLATFORM_OPERATORS`).\n */\nexport const ROLE_PERMISSIONS: Record<RoleKey, WorkspacePermission[]> = {\n viewer: VIEWER,\n operator: [\n ...VIEWER,\n \"execution:create\",\n \"execution:validate\",\n \"execution:submit\",\n \"execution:cancel\",\n \"execution:rollback\",\n \"operation:write\",\n ],\n approver: [...VIEWER, \"approval:read\", \"approval:decide\"],\n auditor: [...VIEWER, \"approval:read\", \"audit:read\"],\n admin: [\n ...VIEWER,\n \"execution:create\",\n \"execution:validate\",\n \"execution:submit\",\n \"execution:cancel\",\n \"execution:rollback\",\n \"operation:write\",\n \"approval:read\",\n \"approval:decide\",\n \"audit:read\",\n \"connection:manage\",\n \"package:manage\",\n \"policy:manage\",\n \"subscription:manage\",\n \"rbac:manage\",\n ],\n};\n\n/**\n * Union of permissions granted by a set of roles. Roles are additive (docs/06 §2);\n * a user holding several roles gets the union. Order is stable + de-duplicated.\n */\nexport function permissionsForRoles(roles: RoleKey[]): Permission[] {\n const seen = new Set<Permission>();\n for (const role of roles) {\n for (const permission of ROLE_PERMISSIONS[role] ?? []) {\n seen.add(permission);\n }\n }\n return [...seen];\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n}); //# sourceMappingURL=me.js.map\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWUuanMiLCJzb3VyY2VzIjpbIi4uL3NyYy9tZS50cyJdLCJzb3VyY2VSb290IjoiIiwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n}); //# sourceMappingURL=tenant-users.js.map\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVuYW50LXVzZXJzLmpzIiwic291cmNlcyI6WyIuLi9zcmMvdGVuYW50LXVzZXJzLnRzIl0sInNvdXJjZVJvb3QiOiIiLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIn0=","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n}); //# sourceMappingURL=invitations.js.map\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW52aXRhdGlvbnMuanMiLCJzb3VyY2VzIjpbIi4uL3NyYy9pbnZpdGF0aW9ucy50cyJdLCJzb3VyY2VSb290IjoiIiwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n}); //# sourceMappingURL=groups.js.map\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ3JvdXBzLmpzIiwic291cmNlcyI6WyIuLi9zcmMvZ3JvdXBzLnRzIl0sInNvdXJjZVJvb3QiOiIiLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIn0=","// ═══ WHICH GLOBAL ACTIONS ONE WORKSPACE MAY USE (docs/112) — A LEAF ════════════════════\n//\n// ★ THIS FILE IMPORTS NOTHING, for the reason `package-provenance.ts` gives: three readers need\n// it — `catalog.ts` (the detail DTO carries the answer), the catalog module (the list's `where`\n// and the per-action read) and the execution oracle (the refusal) — and a vocabulary with no\n// imports cannot join a cycle between them.\n//\n// ─── WHAT IT GOVERNS, AND WHAT IT DOES NOT ─────────────────────────────────────────────\n//\n// `action_definition.tenant_id` is nullable, and that splits the catalog in two. A tenant-owned\n// action — a package this workspace adopted — already answers \"may this workspace use it\"\n// through `ActionAdoption`. A GLOBAL action (`tenant_id IS NULL`, the first-party catalog)\n// answered nothing: every workspace saw all of them and could run all of them. This is the gate\n// for that half and ONLY that half. Both the rules and the default mode apply to global actions;\n// a workspace on `deny_all` does not reach an adopted package, because the only instrument that\n// could re-allow one — a rule — is refused for it (docs/112 §2.1, §5.4).\n\n/**\n * What a workspace does with a global action it has written no rule about.\n *\n * ⚠ A MISSING POLICY ROW IS {@link CATALOG_DEFAULT_MODE_WHEN_UNSET}, not an error and not a\n * third mode. Migration 0090 writes no rows, so every workspace reads that value the moment it\n * is applied and nothing about any run changes.\n */\nexport type CatalogDefaultMode = \"allow_all\" | \"deny_all\";\n\n// ★ A `Record<…, true>` AND NOT A BARE `[…] as const` — the argument is written out beside\n// `ACTION_RUNNABILITY_CAUSE_KIND_SET` in `execution.ts`: an array literal pins nothing, and\n// `satisfies` is checked in both directions.\nconst CATALOG_DEFAULT_MODE_SET = {\n allow_all: true,\n deny_all: true,\n} as const satisfies Record<CatalogDefaultMode, true>;\n\n/** Derived, so the two spellings of this vocabulary cannot drift apart. */\nexport const CATALOG_DEFAULT_MODES = Object.keys(\n CATALOG_DEFAULT_MODE_SET,\n) as readonly CatalogDefaultMode[];\n\n/** The mode of a workspace that has never set one. Declared once; every reader asks here. */\nexport const CATALOG_DEFAULT_MODE_WHEN_UNSET: CatalogDefaultMode = \"allow_all\";\n\n/**\n * An explicit decision about ONE global action in ONE workspace.\n *\n * ⛔ THE EFFECT IS WRITTEN ON THE ROW, and a single id-set reinterpreted by the mode is the\n * design this rejects: it is smaller, and flipping the mode silently inverts every row — an\n * admin who built a denylist of five dangerous actions and then turned on whitelisting would\n * have allowed exactly those five and blocked everything else (docs/112 §4).\n *\n * ⛔ AND THERE IS NO `hidden`. `deny` means absent from browse AND refused with words\n * everywhere else; the admin has one intention and it gets one mechanism (docs/112 §6).\n */\nexport type CatalogRuleEffect = \"allow\" | \"deny\";\n\nconst CATALOG_RULE_EFFECT_SET = {\n allow: true,\n deny: true,\n} as const satisfies Record<CatalogRuleEffect, true>;\n\n/** Derived, so the two spellings of this vocabulary cannot drift apart. */\nexport const CATALOG_RULE_EFFECTS = Object.keys(\n CATALOG_RULE_EFFECT_SET,\n) as readonly CatalogRuleEffect[];\n\n/** The answer, for one global action in one workspace. */\nexport type CatalogAccess = \"allowed\" | \"blocked\";\n\n// Keyed on the two vocabularies rather than written as ternaries, so a third mode or effect is a\n// compile error here instead of silently falling into whichever branch a ternary's `else` is.\nconst RULE_ACCESS = {\n allow: \"allowed\",\n deny: \"blocked\",\n} as const satisfies Record<CatalogRuleEffect, CatalogAccess>;\n\nconst UNRULED_ACCESS = {\n allow_all: \"allowed\",\n deny_all: \"blocked\",\n} as const satisfies Record<CatalogDefaultMode, CatalogAccess>;\n\n/**\n * ═══ THE TRUTH TABLE, IN ONE PLACE (docs/112 §4) ═══════════════════════════════════════\n *\n * workspace default rule for this action effective\n * allow_all (none) allowed\n * allow_all allow allowed\n * allow_all deny blocked\n * deny_all (none) blocked\n * deny_all allow allowed\n * deny_all deny blocked\n *\n * An explicit rule always beats the default.\n *\n * ★ ROWS 2 AND 6 ARE PINS, NOT REDUNDANCY. An `allow` recorded while the workspace is\n * `allow_all` changes nothing today and survives a later switch to `deny_all` — which is what\n * an admin turning on whitelisting wants: the actions they already trusted keep working instead\n * of everything going dark at once.\n *\n * ★ BOTH ENFORCEMENT PATHS ASK THIS, AND NEITHER RESTATES IT. The per-action read (the run\n * oracle's refusal and the detail page's `catalogAccess`) passes the one rule it read; the\n * browse list passes each rule row to partition them into the ids its SQL `where` excludes or\n * admits. The database supplies inputs to this function and never re-implements it.\n *\n * ⛔ AND THE BROWSER NEVER HOLDS A COPY (docs/113 §5). The admin view asks this on the server —\n * once per row for its `access`, once per mode for `availableUnder` — and sends the ANSWERS.\n * A screen that derived either from `(defaultMode, rule)` would be a second implementation of\n * the workspace's policy, able to disagree with the run path.\n */\nexport function effectiveCatalogAccess(\n defaultMode: CatalogDefaultMode,\n rule: CatalogRuleEffect | null,\n): CatalogAccess {\n return rule !== null ? RULE_ACCESS[rule] : UNRULED_ACCESS[defaultMode];\n}\n\n/** One rule as the admin view reads it (`GET /actions/policy`). */\nexport interface CatalogRuleDto {\n actionDefinitionId: string;\n effect: CatalogRuleEffect;\n /** Why, for the next administrator. `null` when none was given. */\n note: string | null;\n /** The `app_user` id of whoever last set it. */\n setBy: string;\n /** ISO-8601. */\n setAt: string;\n}\n\n/**\n * ═══ THE WHOLE-WORKSPACE HALF OF THE ADMIN VIEW (docs/113 §2) ══════════════════════════\n *\n * `PUT /actions/policy`'s answer, and carried beside every page of `GET /actions/policy` and\n * every row write — so the screen's sentence and its switch confirmation are never older than\n * the last change. A row write moves these numbers too: pinning one action changes what\n * `deny_all` would leave available, and a confirmation read from before the pin would state a\n * count that is no longer true at the one moment it is read.\n *\n * `defaultMode` is {@link CATALOG_DEFAULT_MODE_WHEN_UNSET} for a workspace that never set one.\n * The field is `defaultMode` and never `default`: `const { default } = dto` does not parse.\n */\nexport interface CatalogPolicySummaryDto {\n defaultMode: CatalogDefaultMode;\n /**\n * How many global actions this policy governs — the global catalog as browse would list it\n * with nothing blocked. The WHOLE workspace, never a page.\n */\n governedCount: number;\n /**\n * How many of those {@link governedCount} would be available under each mode, with the rules\n * as they stand. Computed by the server from {@link effectiveCatalogAccess}; never a number\n * the browser could reach by counting what it holds.\n *\n * A `Record` over the closed set, so a third mode cannot be added without answering for it.\n */\n availableUnder: Record<CatalogDefaultMode, number>;\n}\n\n/** Body of `PUT /actions/policy`. */\nexport interface SetCatalogDefaultModeInput {\n defaultMode: CatalogDefaultMode;\n}\n\n/** Body of `PUT /actions/:id/policy`. */\nexport interface SetCatalogRuleInput {\n effect: CatalogRuleEffect;\n note?: string | null;\n}\n","// Catalog DTOs — the action contract shared verbatim between the API (catalog\n// module) and apps/web (docs/04 §2.1, docs/11 §6). Single source of truth: no\n// drift between FE rendering and BE serialization (docs/12 §9.1). No NestJS or\n// Prisma imports here — only closed value sets from ./enums.\nimport type {\n ActionCategory,\n Provider,\n RiskLevel,\n VersionStatus,\n} from \"./enums\";\nimport type {\n CatalogAccess,\n CatalogPolicySummaryDto,\n CatalogRuleDto,\n} from \"./catalog-policy\";\nimport type { PackageTier } from \"./package-tier\";\n\n/**\n * ═══ THE LIFECYCLE OF AN ACTION DEFINITION, AND WHAT EACH STATE ENTITLES IT TO ═════════\n *\n * Array-first (charter §4.2), because the catalog's query partitions are DERIVED from this\n * list below. It was a bare union until docs/92 — no runtime members, no compile pin, nothing\n * able to iterate it — which is the one shape a closed vocabulary here is not allowed to have.\n */\nexport const ACTION_LIFECYCLES = [\n /** Authored, never offered. Runnable only through a recorded trial run (docs/32). */\n \"draft\",\n /**\n * Offered and runnable, and SAYS it is still settling. A first-party state: Opera ships it to\n * every workspace on purpose (docs/92 §14.1.3), so the badge is the disclosure.\n */\n \"beta\",\n /** Offered, runnable, and Opera stands behind it. What a seeded row is unless it says otherwise. */\n \"published\",\n /**\n * Offered and STILL RUNNABLE. Deprecation is a statement about the future, not a refusal\n * (docs/92 §3.10), and it must name a successor or say plainly that there is none.\n */\n \"deprecated\",\n /**\n * Withdrawn: cannot be started or adopted. Existing runs and their history are untouched —\n * nothing that has run is ever deleted (docs/92 §3.13).\n */\n \"retired\",\n] as const;\nexport type ActionLifecycle = (typeof ACTION_LIFECYCLES)[number];\n\n/**\n * ═══ ★★ THE PARTITION, DECLARED ONCE — AND THE DEFECT THAT PUT IT HERE ═════════════════\n *\n * `listed` and `runnable` were written THREE TIMES as hand-kept literal lists in\n * `catalog.repository.ts`: `in [\"published\",\"deprecated\"]` twice, and `in [\"draft\",\"retired\"]`\n * once. Those are COMPLEMENTS over a four-member vocabulary — correct only while the vocabulary\n * has exactly four members, and nothing anywhere said so.\n *\n * ⚠ MEASURED BEFORE THIS EXISTED (docs/92 §1.3): a fifth member fell into NEITHER list, so a\n * `beta` global builtin was invisible in the catalog list AND returned 404 from\n * `resolveRunnableVersionById` — `findRunnableVersionById`, `findInactiveRunnableVersionById`\n * and `findUnofferedVersionById` each returned null, the last because it requires a\n * tenant-owned `git` definition and a first-party row is neither. A silent 404 on an official\n * action, earned by adding one word to a union.\n *\n * ★ KEYED ON THE TYPE, NOT ON A LIST OF NAMES. The remedy is not \"remember to update the three\n * lists\" — remembering is what failed. It is that a new member DOES NOT COMPILE until both\n * questions have been answered here. That is the docs/90 guard shape applied one level down,\n * and it is why `beta` was safe to add at all.\n */\nexport const ACTION_LIFECYCLE_STANDING = {\n draft: { listed: false, runnable: false },\n beta: { listed: true, runnable: true },\n published: { listed: true, runnable: true },\n deprecated: { listed: true, runnable: true },\n retired: { listed: false, runnable: false },\n} as const satisfies Record<ActionLifecycle, { listed: boolean; runnable: boolean }>;\n\n/**\n * A lifecycle a pinned version may still be STARTED from. Derived from the standing above by\n * the same mapped type the runtime lists are filtered by, so the type and the array cannot\n * disagree — `RunnableVersionResolution` narrows on the complement of this.\n */\nexport type RunnableActionLifecycle = {\n [L in ActionLifecycle]: (typeof ACTION_LIFECYCLE_STANDING)[L][\"runnable\"] extends true\n ? L\n : never;\n}[ActionLifecycle];\n\n/** Resolvable but refused: the complement, so \"runnable\" and \"inactive\" can never drift apart. */\nexport type InactiveActionLifecycle = Exclude<ActionLifecycle, RunnableActionLifecycle>;\n\n/** What the catalog offers when no explicit lifecycle filter was asked for. */\nexport const LISTED_ACTION_LIFECYCLES: readonly ActionLifecycle[] = ACTION_LIFECYCLES.filter(\n (lifecycle) => ACTION_LIFECYCLE_STANDING[lifecycle].listed,\n);\n\n/**\n * The two runtime lists the repository filters on. The predicates restate the standing rather\n * than asserting a separate fact: each narrows to the type derived from the very entry it reads,\n * so a member that changes its mind in the `Record` moves in both places at once.\n */\nexport const RUNNABLE_ACTION_LIFECYCLES: readonly RunnableActionLifecycle[] =\n ACTION_LIFECYCLES.filter(\n (lifecycle): lifecycle is RunnableActionLifecycle =>\n ACTION_LIFECYCLE_STANDING[lifecycle].runnable,\n );\n\nexport const INACTIVE_ACTION_LIFECYCLES: readonly InactiveActionLifecycle[] =\n ACTION_LIFECYCLES.filter(\n (lifecycle): lifecycle is InactiveActionLifecycle =>\n !ACTION_LIFECYCLE_STANDING[lifecycle].runnable,\n );\n\n/** Badge copy. A `Record`, so a new member must be given words before anything renders it. */\nexport const ACTION_LIFECYCLE_LABELS = {\n draft: \"Draft\",\n beta: \"Beta\",\n published: \"Published\",\n deprecated: \"Deprecated\",\n retired: \"Retired\",\n} as const satisfies Record<ActionLifecycle, string>;\n\n/**\n * Action capabilities (persisted as `action_definition.capabilities` jsonb,\n * docs/05 §3.2). Drives the capability chips on the catalog card and details\n * (verified / rollback / approval / dry-run).\n */\nexport interface ActionCapabilities {\n verified: boolean;\n rollback: boolean;\n /** Whether this action defaults to requiring approval (policy can still override). */\n approvalDefault: boolean;\n dryRun: boolean;\n /**\n * An ENGINE action that deletes or overwrites says so (docs/128 §4.2), and the engine then\n * refuses its success unless a restore point was acknowledged first. Required of an engine\n * action's manifest; absent on every built-in, whose connector keeps its own write-ahead record.\n * No screen reads it.\n */\n destructive?: boolean;\n}\n\n/**\n * One required permission row (persisted in `action_version.required_permissions`\n * jsonb, docs/05 §3.2). Lifted from the prototype's `detail.permissions`.\n */\nexport interface RequiredPermission {\n /** Azure role or fine-grained action, e.g. \"Key Vault Secrets Officer\". */\n role: string;\n /** Where the permission applies, e.g. \"Target Key Vault\". */\n scope: string;\n /** Classification, e.g. \"Built-in role\" | \"Action\". */\n kind: string;\n}\n\n/** One ordered \"how it works\" / workflow step (persisted in `action_version.workflow`). */\nexport interface WorkflowStep {\n /** Display ordinal, e.g. \"01\". */\n n: string;\n title: string;\n body: string;\n}\n\n/**\n * The control the wizard renders for a parameter (UI annotation on the schema).\n * `info` is a non-editable callout — it carries no value; the wizard renders its\n * `title`/`description` as explanatory text and omits it from the submitted parameters.\n *\n * Array-first (charter §4.2), and for the same reason `ACTION_LIFECYCLES` is: docs/97 needs\n * to VALIDATE this vocabulary at the edge of the process, where a catalog manifest read off\n * disk becomes a typed declaration. A bare union has no runtime members, so the ingest would\n * have had to spell the four names a second time — a complete hand-written copy in the one\n * file that decides whether an untrusted file is admitted.\n */\nexport const PARAMETER_CONTROLS = [\"select\", \"text\", \"switch\", \"info\"] as const;\n\nexport type ParameterControl = (typeof PARAMETER_CONTROLS)[number];\n\n/**\n * A single parameter, expressed as a JSON-Schema property plus UI annotations.\n * `type`/`enum`/`default`/`title`/`description` are standard JSON Schema; `control`\n * is a custom annotation (ignored by validators) telling the wizard how to render.\n * Server-side validation in Step 4 keys off the same schema (docs/04 §5, docs/09 §2).\n */\nexport interface ParameterProperty {\n type: \"string\" | \"boolean\";\n title: string;\n description?: string;\n enum?: string[];\n default?: string | boolean;\n control: ParameterControl;\n /**\n * Optional discovery annotation (docs/20 §4.3, docs/29 D1). A provider-namespaced\n * discovery id (`\"azure/virtualMachine\"`); a bare value (`\"resourceGroup\"`) is a\n * legacy pinned id and is read as `azure/<type>`. When present, the wizard offers a\n * combobox populated by live discovery of this type in the chosen scope, while\n * still allowing a typed value. This is purely a UI hint: it is NOT a JSON-Schema\n * `enum` (the list is live, not a closed set), an unimplemented type simply renders\n * as free text, and server-side validation is unchanged — the connector resolves\n * the real resource at execution.\n */\n discover?: string;\n /**\n * Optional cascade parents (docs/20 §4.3, docs/29 D4). Discovery of this param is\n * scoped to the values of the named sibling params. Array form: each item is a\n * sibling param name that ALSO serves as its scope key — e.g. a secret picker\n * (`discover: \"azure/keyVaultSecret\"`, `dependsOn: [\"vault\"]`) lists the secrets of\n * the chosen vault. Object form maps scope key → sibling param name for when the\n * two differ — e.g. `{ resourceGroup: \"rgName\" }`. The wizard stays free-text until\n * every parent has a value and re-fetches when any of them change. Like `discover`,\n * it is a pure UI hint; the scope keys are what the discovery adapter reads.\n */\n dependsOn?: string[] | Record<string, string>;\n}\n\n/**\n * ═══ ★★ THE AUTHOR'S FIELD-ORDER KEY — DECLARED ONCE, HERE ═══════════════════════════════\n *\n * ⚠ IT WAS A BARE LITERAL IN 42 PLACES UNTIL docs/107, WHICH IS WHY IT NEEDED A MIGRATION AND\n * A CENSUS TO FIND. The census row for this family had an EMPTY `declaredBy`: nobody owned the\n * string, so every reader of it was its own author and the rename had no single place to start.\n *\n * ★ ONE SPELLING AGAIN, SINCE docs/108. docs/107 renamed `x-opera-order` to this by ADDING it\n * beside the old key (migration 0088) and writing both for one release, because the api image\n * and the web bundle roll on separate clocks. Migration 0089 removed the retired key from every\n * row, once no image and no bundle read it — and it REFUSES to run if any row would lose its only\n * order key in the process. {@link orderedParameterEntries} and {@link withParameterOrder} are\n * the only places that read and write it, and no surface may do either itself.\n */\nexport const PARAMETER_ORDER_KEY = \"x-runveric-order\";\n\n/**\n * The pinned parameter schema (persisted as `action_version.parameter_schema`\n * jsonb, docs/05 §3.2). A JSON Schema object — both FE generic rendering and BE\n * validation key off it (docs/09 §2).\n */\nexport interface ParameterSchema {\n $schema: string;\n type: \"object\";\n properties: Record<string, ParameterProperty>;\n required: string[];\n additionalProperties: false;\n /**\n * The order the AUTHOR declared these parameters in — as an ARRAY, because that is the\n * only shape that survives the trip to storage.\n *\n * `parameter_schema` is a `jsonb` column, and jsonb does not preserve object KEY order: it\n * normalizes keys by length, then bytewise. So a package declaring `resourceGroup`,\n * `vmName`, `confirmOsDiskWipe` (13, 6 and 17 characters) came back as `vmName`,\n * `resourceGroup`, `confirmOsDiskWipe` and the wizard asked for a virtual machine before\n * the resource group that scopes the list of virtual machines. Every author's form was\n * silently rearranged by how long they happened to name their fields.\n *\n * jsonb DOES preserve array order, so the fix is this field and no migration. It is written\n * once, at import, where `JSON.parse` still holds the authored order (and by the first-party\n * catalog seed, from its own `params` array) — see {@link withParameterOrder}.\n *\n * OPTIONAL, permanently. A package version pinned before this existed has no order, and it\n * must keep rendering rather than break: {@link orderedParameterEntries} falls back to\n * `Object.entries` for exactly that reason. Production holds two such rows.\n */\n [PARAMETER_ORDER_KEY]?: string[];\n}\n\n/**\n * THE order every surface that DISPLAYS parameters reads — the run wizard's form, the plan\n * preview, the approver's snapshot, the catalog's parameter table.\n *\n * One helper rather than one `Object.entries` per surface, because \"which order does the\n * reader see\" is a single question and four answers to it is how three of them end up wrong.\n *\n * Deliberately total: a property NOT named in the order array still renders (appended, in\n * `Object.entries` order), and a name in the order with no property is skipped. The declared\n * order is a display hint, and a hint must never be able to hide a field.\n */\nexport function orderedParameterEntries(\n schema: Pick<ParameterSchema, \"properties\" | typeof PARAMETER_ORDER_KEY>,\n): [string, ParameterProperty][] {\n const properties = schema.properties ?? {};\n /*\n * ONE KEY, NO FALLBACK TO THE RETIRED SPELLING (docs/108). Dropping it is safe because every\n * writer that could leave a row carrying only `x-opera-order` is gone: `v171` wrote only that\n * key, and nothing has run `v171` since docs/107; `v172` wrote BOTH, so a row it touches during\n * this release's roll still carries this one. Migration 0089 refused to run over any row that\n * held the retired key alone.\n */\n const declared = schema[PARAMETER_ORDER_KEY] ?? [];\n const seen = new Set<string>();\n const ordered: [string, ParameterProperty][] = [];\n for (const id of declared) {\n const property = properties[id];\n if (!property || seen.has(id)) continue;\n seen.add(id);\n ordered.push([id, property]);\n }\n for (const [id, property] of Object.entries(properties)) {\n if (seen.has(id)) continue;\n ordered.push([id, property]);\n }\n return ordered;\n}\n\n/**\n * Stamp a schema with the order its properties are currently in — called at the ONE moment\n * that order is still the author's: right after `JSON.parse` at import, and from the\n * first-party seed's `params` array. Anything later reads the schema back out of jsonb, where\n * the authored key order no longer exists to be recorded.\n */\nexport function withParameterOrder<T extends ParameterSchema>(schema: T): T {\n return { ...schema, [PARAMETER_ORDER_KEY]: Object.keys(schema.properties ?? {}) };\n}\n\n/**\n * Catalog list/card item (maps to `ActionCard`). Mirrors docs/04 §2.1 response.\n * Presentation-only fields (initials, provider display, \"updated X ago\",\n * formatted durations) are derived on the client, not persisted.\n */\nexport interface ActionSummaryDto {\n id: string;\n key: string;\n name: string;\n summary: string;\n provider: Provider;\n category: ActionCategory;\n /** Runtime connector key declared by the catalog row; availability is resolved elsewhere. */\n connectorKey: string;\n riskLevel: RiskLevel;\n capabilities: ActionCapabilities;\n maintainer: string;\n lifecycle: ActionLifecycle;\n /** Who vouches for this action (docs/92 §4.1). Rendered as a badge carrying its claim. */\n tier: PackageTier;\n /**\n * When the definition's latest version was published, ISO-8601, null until it is. The ONLY\n * input to {@link isNewAction} — see the note there for why this is a date and not a flag.\n */\n publishedAt: string | null;\n ownerId: string | null;\n deprecationNote: string | null;\n successorDefinitionId: string | null;\n /**\n * ═══ WHETHER THE PERSON ASKING HAS MARKED THIS ACTION AS A FAVOURITE (docs/120) ═════════\n *\n * A user PREFERENCE, not an org POLICY: it grants nothing, and it is answered per reader —\n * two people listing the same catalog get different bodies, which is why `GET /actions`\n * must never sit behind a shared cache. It never changes which rows come back; the\n * `favourite` QUERY does that, in the query's `where` ({@link ListActionsQuery.favourite}).\n *\n * Two rules in this file look as if they forbid this field. Neither does, and the reasons\n * are written here so nobody has to re-derive them:\n *\n * · {@link ActionDetailDto.catalogAccess} is kept OFF the summary because a blocked action\n * is absent from `GET /actions`, so on a list row it could only ever say `allowed` — a\n * constant. This varies row by row and reader by reader, and the list is exactly the\n * surface that needs it.\n * · \"THERE IS NO `isNew` FLAG\" ({@link isNewAction}) states the rule NEVER STORE A FACT YOU\n * CAN COMPUTE: `isNew` is derivable from `publishedAt`, and a stored copy is a second\n * source of truth nobody unsets. This is derivable from nothing — the `action_favourite`\n * row IS the fact, and this field is a fresh per-caller projection of it, read with the\n * page, not a cached verdict. The rule was never \"no booleans\".\n */\n favourite: boolean;\n}\n\n/**\n * ═══ ★ \"NEW\" IS A QUESTION ABOUT A DATE, NOT A COLUMN (docs/92 §7.1) ═══════════════════\n *\n * ⛔ THERE IS NO `isNew` FLAG, AND THERE MUST NEVER BE ONE. A stored boolean is written by\n * whoever publishes and unset by nobody, so \"New\" stays lit for two years and the badge stops\n * meaning anything. The only durable fact is WHEN the version was published; \"is that recent\"\n * is a question asked at render time, against a window declared exactly once — here.\n *\n * ⚠ AND THE CONSEQUENCE IS ACCEPTED, NOT ENGINEERED AROUND: none of the six first-party\n * actions is New today, because none of them IS. They all declare `2026-01-01`. Dating one of\n * them to \"now\" so a screenshot could show the badge is precisely the lie this rule exists to\n * prevent, so the badge is proven with a fixture instead and the six are asserted to show\n * nothing (docs/92 §14.3.11).\n */\nexport const NEW_ACTION_WINDOW_DAYS = 30;\n\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\n/**\n * Whether a catalog row should carry the \"New\" badge.\n *\n * `now` is a parameter rather than a call to `Date.now()` inside, because a function that reads\n * the clock itself can only be tested by moving the clock. Callers pass the render time.\n *\n * Unpublished (`null`) is NOT new — it has never been released to anybody. A publish date in\n * the future is not new either: it has not happened, and treating \"ahead of the clock\" as\n * \"fresh\" would let a bad timestamp light the badge permanently.\n */\nexport function isNewAction(publishedAt: string | null, now: Date): boolean {\n if (publishedAt === null) return false;\n const published = new Date(publishedAt).getTime();\n if (Number.isNaN(published)) return false;\n const age = now.getTime() - published;\n return age >= 0 && age < NEW_ACTION_WINDOW_DAYS * MS_PER_DAY;\n}\n\n/** A specific published version's contract (docs/04 §2.1 `/versions/{version}`). */\nexport interface ActionVersionDto {\n /**\n * action_version.id (uuid) — the pinned-version row id the wizard passes to\n * `POST /executions` as `actionVersionId` (docs/04 §2.3). Exposed so the FE can\n * resolve the version uuid straight from the action detail response.\n */\n id: string;\n version: string;\n status: VersionStatus;\n parameterSchema: ParameterSchema;\n requiredPermissions: RequiredPermission[];\n workflow: WorkflowStep[];\n /** ISO-8601 timestamp; null until published. */\n publishedAt: string | null;\n}\n\n/**\n * Action details (docs/04 §2.1 `/actions/{id}`). Embeds the full latest published\n * version so the Details screen renders params/permissions/workflow in one fetch.\n */\nexport interface ActionDetailDto extends ActionSummaryDto {\n description: string;\n latestVersion: ActionVersionDto | null;\n /**\n * Whether THIS WORKSPACE permits this action (docs/112). Always `allowed` for a tenant-owned\n * action, which `ActionAdoption` governs instead.\n *\n * ★ ON THE DETAIL AND NOT ON {@link ActionSummaryDto}, AND THAT IS NOT AN OMISSION. A blocked\n * action is ABSENT from `GET /actions`, so no list row can carry `blocked` and a list field\n * would only ever say `allowed`. The detail is what a bookmark, a shared link or a schedule\n * that stopped firing reaches — the one page that has to be able to say why.\n */\n catalogAccess: CatalogAccess;\n}\n\n/** Query for `GET /actions` (docs/04 §2.1). */\nexport interface ListActionsQuery {\n q?: string;\n category?: ActionCategory;\n provider?: Provider;\n risk?: RiskLevel;\n lifecycle?: ActionLifecycle;\n /**\n * Only the caller's own favourites (docs/120 §3). ⚠ A FILTER, NOT THE FLAG: it changes which\n * rows come back, so the server applies it inside the keyset query's `where` — removing rows\n * after `take: limit + 1` would hand back short pages. It never reorders: the cursor is\n * `(name, id)`, and a favourites-first sort would stop it being a total order.\n */\n favourite?: boolean;\n cursor?: string;\n limit?: number;\n}\n\n/**\n * ═══ ONE GLOBAL ACTION AS THIS WORKSPACE'S POLICY GOVERNS IT (docs/113 §2) ═════════════\n *\n * A row of Settings → Catalog. Unlike {@link ActionSummaryDto} it exists for BLOCKED actions\n * too: `GET /actions` leaves those out (docs/112 §6), and an admin who cannot see what they\n * blocked cannot unblock it.\n *\n * ⛔ `access` IS THE ANSWER, AND THE BROWSER RENDERS IT RATHER THAN DERIVING IT. The truth\n * table lives in `effectiveCatalogAccess` and nowhere else (docs/113 §5); `rule` is here so the\n * row can say WHY, never so the screen can work out WHAT.\n */\nexport interface CatalogGovernedActionDto {\n id: string;\n key: string;\n name: string;\n summary: string;\n riskLevel: RiskLevel;\n lifecycle: ActionLifecycle;\n access: CatalogAccess;\n /** The explicit rule, or `null` when this action follows the workspace default. */\n rule: CatalogRuleDto | null;\n}\n\n/**\n * `GET /actions/policy` — one keyset page of the governed surface, and the whole-workspace\n * summary beside it. The page is `data` + `nextCursor` like every other keyset list here\n * (`Page<T>`, `RunFeedPageDto`); the summary's counts are the workspace's, never this page's.\n */\nexport interface CatalogPolicyPageDto extends CatalogPolicySummaryDto {\n data: CatalogGovernedActionDto[];\n nextCursor: string | null;\n}\n\n/**\n * The answer to `PUT` and `DELETE /actions/:id/policy`: the row as it now stands, and the\n * workspace summary it moved. The row refreshes in place without a page refetch, and without\n * the browser computing its new `access` or new counts.\n */\nexport interface CatalogRuleChangeDto {\n action: CatalogGovernedActionDto;\n policy: CatalogPolicySummaryDto;\n}\n\n/** Query for `GET /actions/policy` — searched and keyset-paged by the same rule as the list. */\nexport interface ListCatalogPolicyQuery {\n q?: string;\n cursor?: string;\n limit?: number;\n}\n","// ═══ A CATALOG RELEASE — WHAT THE PRODUCT PINS INSTEAD OF SHIPPING AN IMAGE (docs/121) ══════\n//\n// Each first-party action publishes its own immutable, digest-addressed ARTIFACT. A CATALOG\n// RELEASE is one more artifact that names each of them by digest. The product pins exactly one\n// release; with no pin, the manifests inside the api image declare the catalog exactly as they\n// did before docs/121.\n//\n// ★ THE TWO FORMATS MOVE ON A DIFFERENT CLOCK FROM THE JOB THAT READS THEM. The catalog sync job\n// once ran a v170 image against a v173 api and its reconcile upserted declared over live,\n// stripping a migrated key in silence. An artifact published after a job's image was built can\n// carry a shape that image has never seen, so the shapes a build can read are DECLARED here,\n// array-first, and the resolver refuses any other one by name rather than guessing.\n\nimport {\n CATALOG_ACTION_ARTIFACT_SCHEMA_V1,\n CATALOG_ACTION_ARTIFACT_SCHEMA_V2,\n CATALOG_RELEASE_SCHEMA_V1,\n} from \"./wire-identity\";\n\n/** Every catalog-release schema this build can read. A release declaring another is refused. */\nexport const CATALOG_RELEASE_SCHEMA_VERSIONS = [CATALOG_RELEASE_SCHEMA_V1] as const;\nexport type CatalogReleaseSchemaVersion = (typeof CATALOG_RELEASE_SCHEMA_VERSIONS)[number];\n\n/**\n * Every action-artifact schema this build can read. An artifact declaring another is refused.\n * v1 carries a built-in's manifest; v2 an engine action's manifest and its image (docs/128 §17.9).\n */\nexport const CATALOG_ACTION_ARTIFACT_SCHEMA_VERSIONS = [\n CATALOG_ACTION_ARTIFACT_SCHEMA_V1,\n CATALOG_ACTION_ARTIFACT_SCHEMA_V2,\n] as const;\nexport type CatalogActionArtifactSchemaVersion =\n (typeof CATALOG_ACTION_ARTIFACT_SCHEMA_VERSIONS)[number];\n\n/**\n * ═══ HOW AN ARTIFACT IS ADDRESSED — A REPOSITORY AND A DIGEST, AND NOTHING THAT MOVES ═══\n *\n * A registry repository: a lowercase host, an optional port, one or more path segments. The only\n * `:` it admits is a port straight after the host, so no tag can be smuggled into it. Declared\n * here because two programs check it — the api's resolver (`artifact-reference.ts`, bound to\n * migration 0093's CHECK by `catalog-release.migration.spec.ts`) and the CLI that publishes, which\n * refuses before a push what the server would refuse after one.\n */\nexport const ARTIFACT_REPOSITORY_PATTERN = /^[a-z0-9][a-z0-9.-]*(:[0-9]+)?(\\/[a-z0-9][a-z0-9._-]*)+$/;\n\n/** The only resolution input: `sha256:` and 64 lowercase hex characters. */\nexport const ARTIFACT_DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/** Where a published artifact came from. Required on both formats; never inferred by a reader. */\nexport interface CatalogArtifactProvenance {\n /** The repository the content was authored and reviewed in. */\n repository: string;\n /** The commit it was published from. */\n commit: string;\n /** When it was published, ISO 8601. */\n publishedAt: string;\n}\n\n/**\n * A release, addressed the only way the product ever resolves one.\n *\n * ⛔ `artifactRef` is a registry REPOSITORY — no tag, no digest — and `digest` is the ONLY input\n * to a fetch. There is no field a tag could be written into, so \"pin `:latest`\" is not a request\n * this API can receive, and `catalog_release.digest` refuses anything but a sha256 in the schema.\n */\nexport interface CatalogReleaseRef {\n artifactRef: string;\n /** `sha256:` followed by 64 lowercase hex characters. */\n digest: string;\n}\n\n/** The body of `PUT /catalog/release` and `POST /catalog/release/plan`. */\nexport type PinCatalogReleaseInput = CatalogReleaseRef;\n\n/** The live pin: what is declared, who chose it, and when. */\nexport interface PinnedCatalogReleaseDto extends CatalogReleaseRef {\n /**\n * The release's own label, recorded for humans FROM THE RELEASE DOCUMENT at pin time — never\n * typed by the person pinning, and never an input to a fetch.\n */\n version: string;\n /**\n * Where the release was assembled, recorded FROM THE RELEASE DOCUMENT at pin time (docs/127\n * §14.2 B4: the Delivery screen links to it). `null` for a pin made before migration 0098, which\n * recorded none — never re-fetched to fill it in, because a read must not reach a registry.\n */\n provenance: Pick<CatalogArtifactProvenance, \"repository\" | \"commit\"> | null;\n /** The user who pinned it. */\n pinnedBy: string;\n /**\n * Their name as this workspace can see it. `null` when the pin was made from another workspace,\n * whose people this one cannot read — never blank, and never the id in its place.\n */\n pinnedByName: string | null;\n pinnedAt: string;\n}\n\n/**\n * ═══ WHAT ONE RUN OF THE CATALOG SYNC JOB DID (docs/127 §14.2 B1) ══════════════════════════\n *\n * The job writes one row per run, after its outcome is known; the api only reads them. Declared\n * array-first because migration 0098's CHECK is bound to this array by a spec, and the Delivery\n * screen's sentences are keyed on it.\n *\n * applied the declaration was written — the release, or the in-image directory\n * refused nothing was written: the release could not be resolved, verified or validated, or\n * the write failed and rolled back. Production reads what it read before the run.\n * superseded nothing was written: the pin changed between the job reading it and the job\n * holding the catalog seed lock, so the next run applies the new one.\n */\nexport const CATALOG_SYNC_RUN_OUTCOMES = [\"applied\", \"refused\", \"superseded\"] as const;\nexport type CatalogSyncRunOutcome = (typeof CATALOG_SYNC_RUN_OUTCOMES)[number];\n\n/** What declared the catalog for one run: the in-image directory, or a pinned release. */\nexport const CATALOG_SYNC_SOURCES = [\"directory\", \"release\"] as const;\nexport type CatalogSyncSource = (typeof CATALOG_SYNC_SOURCES)[number];\n\n/**\n * How often the catalog sync job runs. ★ THE SCHEDULE IS TERRAFORM'S (`schedule_trigger_config`\n * on `azurerm_container_app_job.catalog_sync`), and a spec reads that file and holds its cron to\n * this number — so the screen's \"every 15 minutes\" cannot outlive a change to the schedule.\n */\nexport const CATALOG_SYNC_INTERVAL_MINUTES = 15;\n\n/** Two schedules missed: past this with no recorded run, the screen says so rather than guessing. */\nexport const CATALOG_SYNC_STALE_AFTER_MINUTES = CATALOG_SYNC_INTERVAL_MINUTES * 2;\n\n/** One recorded run. `release` is the one resolved, and `null` exactly when the directory declared. */\nexport interface CatalogSyncRunDto {\n startedAt: string;\n finishedAt: string;\n /** `API_IMAGE_TAG` of the image that ran; `null` when it ran outside a built image. */\n imageTag: string | null;\n source: CatalogSyncSource;\n release: (CatalogReleaseRef & {\n /** `null` when the run was refused before it could read the release document's own label. */\n version: string | null;\n }) | null;\n outcome: CatalogSyncRunOutcome;\n /** The sentence that ended the run, verbatim — a refusal, a drift report, or the summary. */\n detail: string;\n}\n\n/**\n * `GET /catalog/release` — and the answer to `PUT` and `DELETE`, which return the state they left.\n *\n * ★ `release: null` IS A STATE, NOT A MISSING RESOURCE: no pin means the manifests inside the api\n * image declare the catalog, exactly as before docs/121.\n *\n * ★ `liveSince` IS A FACT THE JOB RECORDED, NOT AN INFERENCE (docs/127 §14.2 B4): the `finishedAt`\n * of the first `applied` run of exactly this pin — its repository and digest — that finished after\n * it was pinned. `null` while the pin has not yet been applied, and always `null` with no pin.\n */\nexport interface CatalogReleaseStateDto {\n release: PinnedCatalogReleaseDto | null;\n /** `API_IMAGE_TAG` of the api answering — the product version the directory belongs to. */\n imageTag: string | null;\n /** The most recently finished sync run, or `null` when none has ever been recorded. */\n lastSync: CatalogSyncRunDto | null;\n liveSince: string | null;\n}\n\n/** A `CatalogReleaseStateDto` that cannot be read. Its message names the field that was wrong. */\nexport class CatalogReleaseStateError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CatalogReleaseStateError\";\n }\n}\n\ntype StateFields = Record<string, unknown>;\n\nfunction stateObject(path: string, value: unknown): StateFields {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new CatalogReleaseStateError(`${path} is not an object.`);\n }\n return value as StateFields;\n}\n\nfunction stateString(path: string, value: unknown, pattern?: RegExp, expected = \"a non-empty string\"): string {\n if (typeof value !== \"string\" || value === \"\" || (pattern !== undefined && !pattern.test(value))) {\n throw new CatalogReleaseStateError(`${path} is ${JSON.stringify(value)}, not ${expected}.`);\n }\n return value;\n}\n\nfunction stateInstant(path: string, value: unknown): string {\n const text = stateString(path, value);\n if (Number.isNaN(Date.parse(text))) {\n throw new CatalogReleaseStateError(`${path} is \"${text}\", which is not a timestamp.`);\n }\n return text;\n}\n\nconst orNull = <T>(value: unknown, read: (value: unknown) => T): T | null =>\n value === null ? null : read(value);\n\nfunction stateMember<T extends string>(path: string, value: unknown, members: readonly T[]): T {\n if (typeof value === \"string\" && (members as readonly string[]).includes(value)) return value as T;\n throw new CatalogReleaseStateError(\n `${path} is ${JSON.stringify(value)}; this build reads ${members.join(\", \")}.`,\n );\n}\n\nfunction parseSyncRun(value: unknown): CatalogSyncRunDto {\n const run = stateObject(\"lastSync\", value);\n const source = stateMember(\"lastSync.source\", run.source, CATALOG_SYNC_SOURCES);\n const release = orNull(run.release, (raw) => {\n const fields = stateObject(\"lastSync.release\", raw);\n return {\n artifactRef: stateString(\"lastSync.release.artifactRef\", fields.artifactRef, ARTIFACT_REPOSITORY_PATTERN, \"a registry repository\"),\n digest: stateString(\"lastSync.release.digest\", fields.digest, ARTIFACT_DIGEST_PATTERN, \"a sha256 digest\"),\n version: orNull(fields.version, (label) => stateString(\"lastSync.release.version\", label)),\n };\n });\n if ((source === \"release\") !== (release !== null)) {\n throw new CatalogReleaseStateError(\n `lastSync.source is \"${source}\" and lastSync.release is ${release === null ? \"null\" : \"set\"}; ` +\n `a run names a release exactly when a release declared it.`,\n );\n }\n return {\n startedAt: stateInstant(\"lastSync.startedAt\", run.startedAt),\n finishedAt: stateInstant(\"lastSync.finishedAt\", run.finishedAt),\n imageTag: orNull(run.imageTag, (tag) => stateString(\"lastSync.imageTag\", tag)),\n source,\n release,\n outcome: stateMember(\"lastSync.outcome\", run.outcome, CATALOG_SYNC_RUN_OUTCOMES),\n detail: stateString(\"lastSync.detail\", run.detail),\n };\n}\n\nfunction parsePinned(value: unknown): PinnedCatalogReleaseDto {\n const pin = stateObject(\"release\", value);\n return {\n artifactRef: stateString(\"release.artifactRef\", pin.artifactRef, ARTIFACT_REPOSITORY_PATTERN, \"a registry repository\"),\n digest: stateString(\"release.digest\", pin.digest, ARTIFACT_DIGEST_PATTERN, \"a sha256 digest\"),\n version: stateString(\"release.version\", pin.version),\n provenance: orNull(pin.provenance, (raw) => {\n const fields = stateObject(\"release.provenance\", raw);\n return {\n repository: stateString(\"release.provenance.repository\", fields.repository),\n commit: stateString(\"release.provenance.commit\", fields.commit),\n };\n }),\n pinnedBy: stateString(\"release.pinnedBy\", pin.pinnedBy),\n pinnedByName: orNull(pin.pinnedByName, (name) => stateString(\"release.pinnedByName\", name)),\n pinnedAt: stateInstant(\"release.pinnedAt\", pin.pinnedAt),\n };\n}\n\n/**\n * ═══ READ THE STATE — PARSED, NEVER CAST ═══════════════════════════════════════════════════\n *\n * Takes the JSON body of `GET`, `PUT` or `DELETE /catalog/release` and returns exactly the fields\n * this build declares, or throws a {@link CatalogReleaseStateError} naming the first one wrong. A\n * field this build does not know is ignored rather than refused: the web and the api roll on\n * separate clocks, and an api one release ahead must not blank an operator's screen.\n *\n * ⚠ AN ABSENT FIELD IS NOT A NULL ONE. `liveSince: null` says \"not applied yet\"; a body with no\n * `liveSince` at all came from an api that cannot say, and reading it as `null` would put \"goes\n * live at the next catalog sync\" on a screen whose pin went live hours ago.\n */\nexport function parseCatalogReleaseState(value: unknown): CatalogReleaseStateDto {\n const state = stateObject(\"the catalog release state\", value);\n for (const field of [\"release\", \"imageTag\", \"lastSync\", \"liveSince\"]) {\n if (!(field in state)) throw new CatalogReleaseStateError(`${field} is missing.`);\n }\n const release = orNull(state.release, parsePinned);\n const liveSince = orNull(state.liveSince, (instant) => stateInstant(\"liveSince\", instant));\n if (release === null && liveSince !== null) {\n throw new CatalogReleaseStateError(\"liveSince is set with nothing pinned; only a pin goes live.\");\n }\n return {\n release,\n imageTag: orNull(state.imageTag, (tag) => stateString(\"imageTag\", tag)),\n lastSync: orNull(state.lastSync, parseSyncRun),\n liveSince,\n };\n}\n\n/** One action artifact a release names, as resolved and verified. */\nexport interface CatalogReleaseActionDto {\n key: string;\n artifactRef: string;\n digest: string;\n provenance: CatalogArtifactProvenance;\n /**\n * An ENGINE action's image (docs/128 §17.8): its digest in the artifact's own repository, and\n * the hint of the trusted key whose signature over it verified — the plan is where an operator\n * sees what will run and who signed it. `null` for a built-in, whose code ships in the api image.\n * No screen reads it before Slice C.\n */\n image: { digest: string; keyHint: string } | null;\n}\n\n/**\n * What the sync would do to one declared action. The drift check's own three outcomes, and the\n * api maps them across with a compile-time equality check, so this cannot gain a fourth that the\n * job does not have.\n */\nexport type CatalogReleasePlanOutcome = \"created\" | \"corrected\" | \"unchanged\";\n\nexport interface CatalogReleasePlanActionDto {\n key: string;\n outcome: CatalogReleasePlanOutcome;\n /** The fields a `corrected` row would have overwritten. Empty otherwise. */\n fields: string[];\n}\n\n/**\n * A global row in the database that the candidate release does NOT declare. The sync is\n * upsert-only and never deletes, so these survive the pin — and an `offered` one fails the job.\n */\nexport interface CatalogReleasePlanUndeclaredDto {\n key: string;\n /** As stored. Not narrowed: an unrecognised value counts as offered, never as harmless. */\n lifecycle: string;\n offered: boolean;\n}\n\n/** A parameter whose discovery type this platform cannot discover. Admitted; free text. */\nexport interface CatalogReleasePlanUndiscoverableDto {\n /** The manifest it is in, e.g. `azure.vm.stop.yaml`. */\n file: string;\n /** The manifest path, e.g. `params[1].source.discover`. */\n path: string;\n message: string;\n}\n\n/**\n * `POST /catalog/release/plan` — what pinning a release WOULD change, computed by the same drift\n * check the sync job runs. ⛔ Producing it writes nothing.\n */\nexport interface CatalogReleasePlanDto {\n candidate: CatalogReleaseRef & {\n version: string;\n provenance: CatalogArtifactProvenance;\n actions: CatalogReleaseActionDto[];\n };\n /** The pin it would replace; `null` when the in-image manifests declare the catalog now. */\n current: PinnedCatalogReleaseDto | null;\n /** Per declared action, in the release's key order. */\n actions: CatalogReleasePlanActionDto[];\n undeclared: CatalogReleasePlanUndeclaredDto[];\n undiscoverable: CatalogReleasePlanUndiscoverableDto[];\n /** The consequences in sentences — including the ones nothing above can show. */\n notices: string[];\n}\n","// ═══ ONE ACTION, ONE NAME — THE KEY AND THE PACKAGE IT IS PUBLISHED FROM (docs/126 §9, docs/127 §5) ═══\n//\n// A first-party catalog action is authored in its own repository and published as its own OCI\n// package, and both carry ONE name derived from the action's key:\n//\n// azure.keyvault.rotateSecret ⇄ action-azure-keyvault-rotate-secret\n//\n// ★ REVERSIBLE BY CONSTRUCTION. Strip the prefix; the first token is the provider, the second the\n// resource, everything after is the verb (kebab → camelCase). That only works because the key has\n// a GRAMMAR — provider and resource are one lowercase word, the verb is camelCase with no two\n// capitals in a row (`rotateSSLCert` kebab-cases to `rotate-s-s-l-cert` and comes back as\n// something else). The grammar is declared HERE and nowhere else: the manifest validator refuses\n// a key outside it, the resolver refuses a package that does not carry its key's name, and the\n// CLI checks the same thing before a push as a convenience the server never relies on.\n//\n// ⚠ THIS ENCODES THE PACKAGE NAME, NOT THE GITHUB TOPOLOGY (docs/127 §5). One repository could\n// still publish several packages; what is fixed is that the package a key is FETCHED from carries\n// that key's name, so an artifact cannot claim an identity its package does not carry.\n\n/** Every action repository and package name starts with this. */\nexport const ACTION_REPOSITORY_PREFIX = \"action-\";\n\n/** A provider or resource segment: one lowercase word. */\nconst WORD = /^[a-z][a-z0-9]*$/;\n/** A verb: camelCase, and every capital is followed by at least one lowercase letter or digit. */\nconst VERB = /^[a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)*$/;\n\n/**\n * Why `key` is not an action key, in a sentence that names it — or `null` when it is one.\n *\n * The one place the grammar is judged. Every refusal of a key, wherever it happens, is this\n * sentence, so a manifest refused at ingest and a release refused at pin say the same thing.\n */\nexport function actionKeyRefusal(key: string): string | null {\n const shape =\n \"an action key is <provider>.<resource>.<verb>: provider and resource are one lowercase word \" +\n \"(a-z, then a-z or 0-9), the verb is camelCase with no two capitals in a row — so the key \" +\n \"maps to exactly one repository name and back.\";\n const segments = key.split(\".\");\n if (segments.length !== 3) {\n return `\"${key}\" is not an action key: it has ${segments.length} dot-separated segment(s), not 3; ${shape}`;\n }\n const [provider, resource, verb] = segments as [string, string, string];\n const not = (what: string) => `\"${key}\" is not an action key: ${what}; ${shape}`;\n if (!WORD.test(provider)) return not(`its provider \"${provider}\" is not one lowercase word`);\n if (!WORD.test(resource)) return not(`its resource \"${resource}\" is not one lowercase word`);\n if (!VERB.test(verb)) return not(`its verb \"${verb}\" is not camelCase without two capitals in a row`);\n return null;\n}\n\nexport function isActionKey(key: string): boolean {\n return actionKeyRefusal(key) === null;\n}\n\n/** `rotateSecret` → `rotate-secret`. */\nconst kebab = (verb: string): string => verb.replace(/[A-Z]/g, (capital) => `-${capital.toLowerCase()}`);\n\n/**\n * The repository and package name of an action: `action-<provider>-<resource>-<verb in kebab>`.\n *\n * ⛔ THROWS for a key outside the grammar rather than inventing a name for it — a name that does\n * not map back is a name two keys could share.\n */\nexport function actionRepositoryName(key: string): string {\n const refusal = actionKeyRefusal(key);\n if (refusal !== null) throw new Error(refusal);\n const [provider, resource, verb] = key.split(\".\") as [string, string, string];\n return `${ACTION_REPOSITORY_PREFIX}${provider}-${resource}-${kebab(verb)}`;\n}\n\n/**\n * ═══ WHERE EVERY ACTION IS AUTHORED — ONE GITHUB ORGANISATION (docs/128 §17.4a) ═════════════\n *\n * An engine action's image says where it was built (`org.opencontainers.image.source`), and its\n * artifact's `provenance.repository` says where it was authored; both must be this prefix followed\n * by the action's own repository name. A signature binds a DIGEST and never a name, so without\n * this one action's signed image could be offered under another action's manifest.\n */\nexport const ACTION_SOURCE_REPOSITORY_PREFIX = \"https://github.com/runveric/\";\n\n/** `https://github.com/runveric/action-<…>` — the repository action `key` is built in. Throws as {@link actionRepositoryName} does. */\nexport function actionSourceRepository(key: string): string {\n return `${ACTION_SOURCE_REPOSITORY_PREFIX}${actionRepositoryName(key)}`;\n}\n\n/**\n * The action key a repository or package name spells, or `null` for a name that is not an action\n * name — no `action-` prefix, too few segments, or a spelling no key maps to.\n *\n * ★ NOT A SECOND GRAMMAR. A candidate is read off the name and accepted only when it is a key AND\n * maps back to exactly this name, so the two directions cannot disagree about any input.\n */\nexport function actionKeyOf(name: string): string | null {\n if (!name.startsWith(ACTION_REPOSITORY_PREFIX)) return null;\n const [provider, resource, first, ...rest] = name.slice(ACTION_REPOSITORY_PREFIX.length).split(\"-\");\n if (provider === undefined || resource === undefined || first === undefined) return null;\n const verb = first + rest.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(\"\");\n const key = `${provider}.${resource}.${verb}`;\n return isActionKey(key) && actionRepositoryName(key) === name ? key : null;\n}\n\n/**\n * Why the package at `artifactRef` (a registry repository, `host/…/name`) cannot carry action\n * `key` — or `null` when its last path segment is exactly the key's name.\n *\n * ★ THE SENTENCE NAMES BOTH: the key, and the package it must come from. The resolver refuses with\n * it before any fetch (at plan, pin, sync and vendor — one resolver), and the CLI refuses with it\n * before a push.\n */\nexport function actionPackageRefusal(key: string, artifactRef: string): string | null {\n const keyRefusal = actionKeyRefusal(key);\n if (keyRefusal !== null) return `${keyRefusal} No package can carry it.`;\n const cut = artifactRef.lastIndexOf(\"/\");\n const named = artifactRef.slice(cut + 1);\n const expected = actionRepositoryName(key);\n if (named === expected) return null;\n return (\n `action \"${key}\" is published only from a package named \"${expected}\" ` +\n `(${artifactRef.slice(0, cut + 1)}${expected}), not \"${named}\". An action's package carries ` +\n `its key's name, so an artifact cannot claim an identity its package does not carry.`\n );\n}\n","// ═══ release.yaml — WHAT A PERSON PROPOSES AS THE NEXT CATALOG RELEASE (docs/127 §4.1) ═══\n//\n// The catalog repository holds one file a pull request edits: a version label for humans and, per\n// action, the artifact a release should name — by digest:\n//\n// version: \"2026.10.1\"\n// actions:\n// azure.vm.stop: <registry>/<org>/action-azure-vm-stop@sha256:…\n//\n// Merging publishes it (`runveric catalog publish-release --from release.yaml`), which makes the\n// release AVAILABLE; only a pin makes it live (docs/121 §3.6).\n//\n// ★ THIS DECLARES THE SHAPE, NOT THE RULES ABOUT A RELEASE. Which namespace an action may live in,\n// that a digest is a digest and that a package carries its key's name are refused by the CLI per\n// entry — the same checks whether the entries came from this file or from `--action` flags — and\n// by the server again at plan, pin and sync. The caller parses the YAML; this reads the value.\n\n/** One action a release names: the key, the package, and the digest that is the only input. */\nexport interface CatalogReleaseSpecAction {\n key: string;\n artifactRef: string;\n digest: string;\n}\n\nexport interface CatalogReleaseSpec {\n /** A label recorded with the pin, for humans. Nothing ever resolves by it. */\n version: string;\n /** In the order the file lists them. */\n actions: CatalogReleaseSpecAction[];\n}\n\n/** A release.yaml that cannot be read. Its message names what was wrong. */\nexport class CatalogReleaseSpecError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CatalogReleaseSpecError\";\n }\n}\n\n/**\n * `<repository>@<digest>` split at the `@` — or `null` when there is no `@`, or nothing on either\n * side of it. Whether the halves are a repository and a digest is the caller's refusal to make.\n */\nexport function splitArtifactReference(reference: string): { artifactRef: string; digest: string } | null {\n const at = reference.indexOf(\"@\");\n if (at <= 0 || at === reference.length - 1) return null;\n return { artifactRef: reference.slice(0, at), digest: reference.slice(at + 1) };\n}\n\nconst isMapping = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Read a parsed release.yaml — parsed, never cast. Refuses an unknown top-level field, a version\n * that is not a string (YAML reads `2026.10` as a NUMBER, `2026.1`, so the label must be quoted),\n * and an empty release.\n */\nexport function parseCatalogReleaseSpec(value: unknown): CatalogReleaseSpec {\n if (!isMapping(value)) {\n throw new CatalogReleaseSpecError(\"release.yaml is not a mapping of `version` and `actions`.\");\n }\n const unknown = Object.keys(value).filter((key) => key !== \"version\" && key !== \"actions\");\n if (unknown.length > 0) {\n throw new CatalogReleaseSpecError(\n `release.yaml carries ${unknown.map((key) => `\"${key}\"`).join(\", \")}; it has exactly two ` +\n \"fields, `version` and `actions`.\",\n );\n }\n const { version, actions } = value;\n if (typeof version !== \"string\" || version.trim().length === 0) {\n throw new CatalogReleaseSpecError(\n `release.yaml's version is ${JSON.stringify(version ?? null)}, not a label. Write it as a ` +\n 'quoted string — version: \"2026.10.1\" — because YAML reads an unquoted 2026.10 as a number.',\n );\n }\n if (actions === null || actions === undefined || (isMapping(actions) && Object.keys(actions).length === 0)) {\n throw new CatalogReleaseSpecError(\n \"release.yaml declares no action. An empty release is refused: pinned, it would declare a \" +\n \"catalog with nothing in it.\",\n );\n }\n if (!isMapping(actions)) {\n throw new CatalogReleaseSpecError(\n \"release.yaml's actions is not a mapping of action key to <repository>@<digest>.\",\n );\n }\n return {\n version,\n actions: Object.entries(actions).map(([key, reference]) => {\n const split = typeof reference === \"string\" ? splitArtifactReference(reference) : null;\n if (split === null) {\n throw new CatalogReleaseSpecError(\n `release.yaml's ${key} is ${JSON.stringify(reference)}, not <repository>@<digest>.`,\n );\n }\n return { key, ...split };\n }),\n };\n}\n","// ═══ THE LOCK — WHICH RELEASE THE IN-IMAGE DIRECTORY IS A COPY OF (docs/127 §3) ══════════\n//\n// Once actions are authored in their own repositories, `apps/api/prisma/catalog/` stops being an\n// author and becomes a VENDORED COPY of one published catalog release. This file declares the lock\n// that says which: the release, and per action the artifact, its digest, the sha256 of the\n// manifest bytes written into the directory, and where it was authored.\n//\n// ★ THE LOCK'S EXISTENCE IS THE SWITCH. No lock: the directory is the author, exactly as before.\n// A lock: every manifest in the directory must be the bytes it names, and an edit made here is\n// refused with a sentence naming the repository the action is authored in. There is no state in\n// which some actions are locked and others are not — the lock names the whole release or nothing.\n//\n// ⛔ WRITTEN BY `catalog:vendor`, NEVER BY HAND. The parser below is strict for that reason: an\n// unknown field, an unsorted list or a malformed digest means the file was edited, and an edited\n// lock is a claim about a release nobody published.\n//\n// ⚠ NOT A PUBLISHED FORMAT. The lock never leaves this repository, which is why its schema id is\n// not under the `runveric.dev/` namespace the published formats in `wire-identity.ts` use.\n\nimport { actionPackageRefusal, actionRepositoryName } from \"./action-repository\";\nimport { ARTIFACT_DIGEST_PATTERN, ARTIFACT_REPOSITORY_PATTERN } from \"./catalog-release\";\n\n/** The one lock schema this build reads and writes. */\nexport const CATALOG_LOCK_SCHEMA_V1 = \"runveric.catalog-lock/v1\";\n\n/** Where the lock lives, beside the manifests it locks. Not a `.yaml`, so ingest never reads it. */\nexport const CATALOG_LOCK_FILE = \"release.lock.json\";\n\nexport interface CatalogLockAction {\n key: string;\n /** The action's package, e.g. `ghcr.io/<org>/action-azure-vm-stop`. */\n artifactRef: string;\n digest: string;\n /** The sha256 of the manifest bytes vendored as `<key>.yaml`, 64 lowercase hex characters. */\n manifestSha256: string;\n /** Where the action is authored, as its artifact recorded it. */\n provenance: { repository: string; commit: string };\n /**\n * ★ AN ENGINE ACTION IS RECORDED AND NOT VENDORED (docs/128 §17.8). It reaches a deployment only\n * through a pinned release, so the directory holds NO file for it: the lock names it, its\n * manifest's sha256 and its image digest, and the offline check refuses a `<key>.yaml` beside it.\n * Both fields present, or both absent (a built-in).\n */\n executes?: typeof CATALOG_LOCK_ENGINE_EXECUTION;\n /** The engine action's image, by digest, in its artifact's own repository. */\n imageDigest?: string;\n}\n\n/** The one value `executes` takes: the action runs as an image, through the engine. */\nexport const CATALOG_LOCK_ENGINE_EXECUTION = \"engine\";\n\nexport interface CatalogLock {\n schemaVersion: typeof CATALOG_LOCK_SCHEMA_V1;\n /** The release the directory is a copy of — the pin an operator would make. */\n release: { artifactRef: string; digest: string; version: string };\n /** Sorted by key, each key once. */\n actions: CatalogLockAction[];\n}\n\n/** A lock that cannot be read. Its message names the path that was wrong. */\nexport class CatalogLockError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CatalogLockError\";\n }\n}\n\n/**\n * A manifest's sha256: 64 lowercase hex characters. The lock records it per action, and since\n * docs/128 §17.7 `action_version.engine_manifest_sha256` holds the same value for an engine version —\n * its CHECK is bound to this pattern by `an-engine-version-is-signed.migration.spec.ts`.\n */\nexport const MANIFEST_SHA256_PATTERN = /^[0-9a-f]{64}$/;\n\ntype Fields = Record<string, unknown>;\n\nfunction objectAt(path: string, value: unknown, keys: readonly string[]): Fields {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new CatalogLockError(`${path} is not an object.`);\n }\n const unknown = Object.keys(value).filter((key) => !keys.includes(key));\n if (unknown.length > 0) {\n throw new CatalogLockError(\n `${path} carries ${unknown.map((key) => `\"${key}\"`).join(\", \")}, which a lock does not have. ` +\n `A lock is written by catalog:vendor and never edited; re-vendor instead.`,\n );\n }\n return value as Fields;\n}\n\nfunction stringAt(path: string, value: unknown, pattern?: RegExp, expected?: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new CatalogLockError(`${path} is not a non-empty string.`);\n }\n if (pattern !== undefined && !pattern.test(value)) {\n throw new CatalogLockError(`${path} is \"${value}\", which is not ${expected}.`);\n }\n return value;\n}\n\n/**\n * ═══ READ A LOCK — PARSED, NEVER CAST ═════════════════════════════════════════════════════\n *\n * Takes the JSON value (the caller reads the file and `JSON.parse`s it) and returns a lock or\n * throws a {@link CatalogLockError} naming the first thing wrong. Every action's package must\n * carry its key's name — the rule the resolver enforced when the release was vendored — so a lock\n * edited to point a key at another package is refused here too.\n */\nexport function parseCatalogLock(value: unknown): CatalogLock {\n const root = objectAt(\"the lock\", value, [\"schemaVersion\", \"release\", \"actions\"]);\n if (root.schemaVersion !== CATALOG_LOCK_SCHEMA_V1) {\n throw new CatalogLockError(\n `the lock declares schemaVersion ${JSON.stringify(root.schemaVersion)}; this build reads ` +\n `${CATALOG_LOCK_SCHEMA_V1} only.`,\n );\n }\n\n const release = objectAt(\"release\", root.release, [\"artifactRef\", \"digest\", \"version\"]);\n const lock: CatalogLock = {\n schemaVersion: CATALOG_LOCK_SCHEMA_V1,\n release: {\n artifactRef: stringAt(\"release.artifactRef\", release.artifactRef, ARTIFACT_REPOSITORY_PATTERN, \"a registry repository\"),\n digest: stringAt(\"release.digest\", release.digest, ARTIFACT_DIGEST_PATTERN, \"a sha256 digest\"),\n version: stringAt(\"release.version\", release.version),\n },\n actions: [],\n };\n\n if (!Array.isArray(root.actions) || root.actions.length === 0) {\n throw new CatalogLockError(\"actions is not a non-empty array. A release names at least one action.\");\n }\n root.actions.forEach((entry: unknown, index) => {\n const path = `actions[${index}]`;\n const action = objectAt(path, entry, [\n \"key\",\n \"artifactRef\",\n \"digest\",\n \"manifestSha256\",\n \"provenance\",\n \"executes\",\n \"imageDigest\",\n ]);\n const key = stringAt(`${path}.key`, action.key);\n const artifactRef = stringAt(`${path}.artifactRef`, action.artifactRef, ARTIFACT_REPOSITORY_PATTERN, \"a registry repository\");\n const misnamed = actionPackageRefusal(key, artifactRef);\n if (misnamed !== null) throw new CatalogLockError(`${path}: ${misnamed}`);\n const previous = lock.actions[lock.actions.length - 1];\n if (previous !== undefined && !(previous.key < key)) {\n throw new CatalogLockError(\n `${path}.key \"${key}\" follows \"${previous.key}\": a lock names each action once, sorted by key.`,\n );\n }\n const provenance = objectAt(`${path}.provenance`, action.provenance, [\"repository\", \"commit\"]);\n if ((action.executes === undefined) !== (action.imageDigest === undefined)) {\n throw new CatalogLockError(\n `${path} carries ${action.executes === undefined ? \"imageDigest without executes\" : \"executes without imageDigest\"}; ` +\n `an engine action records both, a built-in neither.`,\n );\n }\n if (action.executes !== undefined && action.executes !== CATALOG_LOCK_ENGINE_EXECUTION) {\n throw new CatalogLockError(\n `${path}.executes is ${JSON.stringify(action.executes)}; the one value it takes is \"${CATALOG_LOCK_ENGINE_EXECUTION}\".`,\n );\n }\n lock.actions.push({\n key,\n artifactRef,\n digest: stringAt(`${path}.digest`, action.digest, ARTIFACT_DIGEST_PATTERN, \"a sha256 digest\"),\n manifestSha256: stringAt(`${path}.manifestSha256`, action.manifestSha256, MANIFEST_SHA256_PATTERN, \"64 lowercase hex characters\"),\n provenance: {\n repository: stringAt(`${path}.provenance.repository`, provenance.repository),\n commit: stringAt(`${path}.provenance.commit`, provenance.commit),\n },\n ...(action.executes === undefined\n ? {}\n : {\n executes: CATALOG_LOCK_ENGINE_EXECUTION,\n imageDigest: stringAt(`${path}.imageDigest`, action.imageDigest, ARTIFACT_DIGEST_PATTERN, \"a sha256 digest\"),\n }),\n });\n });\n return lock;\n}\n\n/**\n * The lock as `catalog:vendor` writes it: actions sorted by key, two-space JSON, one trailing\n * newline. Field order is fixed by construction here, so two vendors of one release write the\n * same bytes.\n */\nexport function catalogLockText(lock: CatalogLock): string {\n const ordered: CatalogLock = {\n schemaVersion: lock.schemaVersion,\n release: { artifactRef: lock.release.artifactRef, digest: lock.release.digest, version: lock.release.version },\n actions: [...lock.actions]\n .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))\n .map((action) => ({\n key: action.key,\n artifactRef: action.artifactRef,\n digest: action.digest,\n manifestSha256: action.manifestSha256,\n provenance: { repository: action.provenance.repository, commit: action.provenance.commit },\n ...(action.executes === undefined || action.imageDigest === undefined\n ? {}\n : { executes: action.executes, imageDigest: action.imageDigest }),\n })),\n };\n return `${JSON.stringify(ordered, null, 2)}\\n`;\n}\n\n/**\n * ★ THE SENTENCE A VENDORED MANIFEST IS REFUSED WITH (docs/127 §3): where the action is authored,\n * and the four steps that change it. The organisation is the release's own namespace — the lock\n * names it, so no second spelling of it exists here.\n */\nexport function authoredElsewhere(lock: CatalogLock, key: string): string {\n const namespace = lock.release.artifactRef.slice(0, lock.release.artifactRef.lastIndexOf(\"/\"));\n const organisation = namespace.slice(namespace.lastIndexOf(\"/\") + 1);\n return `${key} is authored in ${organisation}/${actionRepositoryName(key)} — change it there, publish, assemble, vendor`;\n}\n","// ═══ THE PLACEHOLDERS A CATALOG MANIFEST MAY USE FOR THE BRAND (docs/97 §4.3) ══════════════\n//\n// A YAML file cannot read a constant, so a first-party catalog manifest writes\n// `{{BRAND_SHORT_NAME}}` and whoever reads the manifest substitutes the declaration in\n// `./brand`. The api's validator does it at ingest (and refuses a literal brand or an unknown\n// placeholder — `catalog-manifest.ts` §2 says why); the repository-creation script does it to fill\n// an action repository's README from the same fields (docs/127 §4.2).\n//\n// ★ DECLARED HERE SINCE docs/127 so those two readers share one map and one pattern rather than\n// each keeping a copy that could disagree about which placeholders exist.\n\nimport { BRAND_NAME, BRAND_SHORT_NAME } from \"./brand\";\n\n/** Every placeholder a manifest may write, and the declaration it stands for. */\nexport const MANIFEST_PLACEHOLDERS: Readonly<Record<string, string>> = {\n BRAND_SHORT_NAME,\n BRAND_NAME,\n};\n\n/** `{{ NAME }}`, spaces allowed inside the braces. Global: use it with `String.replace`. */\nexport const MANIFEST_PLACEHOLDER_PATTERN = /\\{\\{\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*\\}\\}/g;\n","/**\n * ═══ A RUN THAT NAMES ITS CHANGE (docs/83) ═════════════════════════════════════════════\n *\n * A customer's runs must name a record in their system of record — a change request, an\n * incident — and Opera must refuse the run unless that record ACTUALLY AUTHORIZES it.\n *\n * This file is the whole vocabulary, and it is a leaf: it imports nothing from this package\n * and nothing imports it back. Everything that decides an outcome is declared once, here,\n * and every surface reads it — the policy the admin writes, the gate at submit, the gate at\n * dispatch, the sentence a refused run shows.\n *\n * ─── WHY A SECOND POLICY KIND AND NOT A SECOND FLAG ON THE APPROVAL RULE ─────────────────\n *\n * `resolvePolicy` is `.find` — the first matching rule in precedence order decides and the\n * rest are not consulted. Correct, and harmless while a rule carries exactly ONE\n * requirement. The moment a rule carries two, precedence starts REMOVING requirements:\n *\n * An admin has \"production requires a change record\" at priority 2. They later add\n * \"rotate-secret requires approval\" at priority 1, for an unrelated reason. Rotating a\n * secret in production now matches the narrower rule, and the change-record requirement\n * is silently gone. Nobody decided it, nothing says it, and the run succeeds.\n *\n * So `Policy` gains a KIND. One table, one match vocabulary, one CRUD shape, one admin\n * section — and PRECEDENCE PER KIND, so a run may need approval, a change record, both or\n * neither, and neither stack can delete the other's requirement. `policy-bypass.spec.ts`\n * demonstrates both halves of that rather than arguing them.\n */\n\n/**\n * ═══ WHAT A POLICY DECIDES ═════════════════════════════════════════════════════════════\n *\n * Array-first, so the set is one value the code can walk — and so a caller asking for \"each\n * kind\" gets the kinds that exist rather than the ones somebody remembered.\n *\n * `approval` is every row that existed before migration 0082, backfilled. Its semantics are\n * untouched by this slice: same match, same effect, same precedence, same sentence.\n */\n\nimport { BRAND_SHORT_NAME } from \"./brand\";\n\nexport const POLICY_KINDS = [\"approval\", \"change_control\"] as const;\nexport type PolicyKind = (typeof POLICY_KINDS)[number];\n\n/** The kind a rule written before migration 0082 has, and the one a CRUD call defaults to. */\nexport const DEFAULT_POLICY_KIND: PolicyKind = \"approval\";\n\n/** How each kind reads. One vocabulary, one wording, in every list and every sentence. */\nexport const POLICY_KIND_LABEL: Record<PolicyKind, string> = {\n approval: \"Approval\",\n change_control: \"Change control\",\n};\n\n/**\n * ═══ THE RECORD TYPES A RULE MAY REQUIRE ═══════════════════════════════════════════════\n *\n * Array-first and compile-pinned. Two in v1; a third is a deliberate decision, not a\n * string somebody adds — see {@link CHANGE_RECORD_AUTHORIZATION}, which will not compile\n * until the new type says what authorizes a run.\n */\nexport const CHANGE_RECORD_TYPES = [\"change_request\", \"incident\"] as const;\nexport type ChangeRecordType = (typeof CHANGE_RECORD_TYPES)[number];\n\n/** How each type reads to an operator. Never the raw key — `change_request` is not English. */\nexport const CHANGE_RECORD_TYPE_LABEL: Record<ChangeRecordType, string> = {\n change_request: \"Change request\",\n incident: \"Incident\",\n};\n\n/**\n * ═══ ★ THE PRODUCT OWNS WHAT \"AUTHORIZES\" MEANS, AND THE ADMIN DOES NOT ════════════════\n *\n * The admin picks WHICH KINDS OF RECORD count. They do not configure which states are\n * acceptable, and that is the decision this whole file is shaped around.\n *\n * EXISTENCE IS NOT AUTHORIZATION. A closed change exists. A rejected change exists. If an\n * admin could tick \"just check it exists\", every deployment of this feature would eventually\n * be configured that way, and the audit trail would look like control while being none —\n * docs/78's defect (\"a domain nobody verified\": WorkOS reported a domain as *claimed* and\n * nothing ever checked it was *verified*) wearing a ticket number.\n *\n * ★ AND IT IS A `Record` KEYED BY TYPE, WHICH IS THE COMPILE-TIME HALF. A new\n * `ChangeRecordType` is a missing-property error here until somebody writes down what\n * authorizes it. A free-standing lookup would let a new type default to the empty list —\n * which is \"anything authorizes\", the one answer nobody would choose on purpose. Same shape\n * and same reason as `AZURE_SUPPORTS: Record<IdentityMechanism, boolean>`.\n */\nexport const CHANGE_RECORD_AUTHORIZATION = {\n /**\n * Approved, in a state that permits work, and NOW inside its planned window.\n *\n * All three, because each alone is routinely true of a record that authorizes nothing: a\n * change approved last week for a window that closed; a change approved and still in\n * \"Assess\"; a change in its window that nobody signed off.\n */\n change_request: [\"approved\", \"permits_work\", \"within_window\"],\n /**\n * Open — not resolved, not closed. An incident has no approval and no planned window: the\n * work IS the response, and requiring a window would refuse every emergency this type\n * exists to admit.\n */\n incident: [\"open\"],\n} as const satisfies Record<ChangeRecordType, readonly ChangeRecordRequirement[]>;\n\n/**\n * ═══ ★ HOW A RUN'S REFERENCE WAS ESTABLISHED (docs/84 §3) ══════════════════════════════\n *\n * Two levels, and the distance between them is the whole of this slice. The gate at submit\n * WRITES one onto the run; the run record, the approval context and the audit event carry it\n * wherever the reference goes; and nothing anywhere DERIVES it at read time.\n *\n * ★ WHY IT IS STORED AND NOT COMPUTED. `verified` is a claim about a round trip that happened\n * at a named moment. Recomputing it later would answer a different question — \"could we check\n * this record NOW?\" — with the word for \"we checked it THEN\". The day an adapter is connected,\n * every run recorded before it would silently start reading as verified, and an auditor could\n * no longer tell which runs were checked. That history is the one thing a later slice cannot\n * repair, which is why the column ships in the same migration as the feature.\n *\n * ⚠ AND IT IS NOT A `ChangeRecordVerdict`. A verdict is \"did this record authorize the run\",\n * which is true at a moment and stale by the next one — the reason the window is re-checked at\n * dispatch. This is \"what did Opera DO about it\", which never stops being true.\n */\nexport const CHANGE_RECORD_ASSURANCE = [\"recorded\", \"verified\"] as const;\nexport type ChangeRecordAssurance = (typeof CHANGE_RECORD_ASSURANCE)[number];\n\n/**\n * ★ WHAT A RULE WITH NO STORED `assurance` REQUIRES — `verified`, the STRONGER level.\n *\n * Every change-control rule written before docs/84 was written under a product that promised\n * \"Opera checks that the record actually authorizes the work\", so `verified` is what its\n * author asked for. Defaulting an absent value to `recorded` would silently downgrade a\n * control nobody chose to downgrade — the reassuring member of a vocabulary taken as the safe\n * default, which is the shape `ChangeRecordProviderRegistry.resolve` already refuses for\n * `not_found` and `unavailable`.\n *\n * Production holds zero change-control rules, so no stored row is affected. The default is\n * stated for the READER and for the type, not for a migration.\n */\nexport const DEFAULT_CHANGE_RECORD_ASSURANCE: ChangeRecordAssurance = \"verified\";\n\n/** The word for a level, for a chip or a tile heading. Never the raw key in prose. */\nexport const CHANGE_RECORD_ASSURANCE_LABEL: Record<ChangeRecordAssurance, string> = {\n recorded: \"Recorded\",\n verified: \"Verified\",\n};\n\n/**\n * WHAT A RULE AT THIS LEVEL REQUIRES — future tense, for the admin at the point of choice and\n * for the plan an operator reads before they submit.\n *\n * ★ THE `recorded` SENTENCE SAYS WHAT IS NOT DONE, IN THE SAME BREATH AS WHAT IS. Recording\n * the reference IS a control — the immutable link between this run, this person, this time\n * and that reference is the artifact an auditor samples — and it is not a check. A sentence\n * that claimed only the first half would be docs/81's defect; one that led with the second\n * would read as an apology for a control that earns its place.\n */\nexport const CHANGE_RECORD_ASSURANCE_REQUIRES: Record<ChangeRecordAssurance, string> = {\n recorded:\n `The run must name a record of an accepted type. ${BRAND_SHORT_NAME} records it on the run permanently ` +\n \"and does not check it — nothing is looked up in your system of record.\",\n verified:\n `${BRAND_SHORT_NAME} looks the record up in your system of record and refuses the run unless it ` +\n \"authorizes the work — re-checked the moment the run starts.\",\n};\n\n/**\n * WHAT WAS ACTUALLY DONE TO THIS RUN'S REFERENCE — past tense, for the run record, the\n * approval context and the audit trail.\n *\n * A SECOND MAP AND NOT A REUSE OF THE ONE ABOVE (docs/44 §3.1, on orthogonal facts): \"what\n * this rule will require\" and \"what happened to this reference\" are two questions, and the\n * one surface that most needs them separate is the run record of a run that was refused —\n * where the rule's requirement is what was asked for and the run's assurance is what was got.\n */\nexport const CHANGE_RECORD_ASSURANCE_ESTABLISHED: Record<ChangeRecordAssurance, string> = {\n recorded: `Recorded on this run. ${BRAND_SHORT_NAME} did not check it.`,\n verified: \"Checked with your system of record, which authorized this run.\",\n};\n\n/**\n * ═══ ★ WHO NAMED THE RECORD THIS RUN CARRIES (docs/88 §4.2) ════════════════════════════\n *\n * Two members, because a run's reference arrives by exactly two routes and they mean\n * different things to the person reading the row:\n *\n * · `run` — somebody named it FOR THIS RUN, at submit, with this run in front of them.\n * · `schedule` — somebody named it ONCE, on the schedule, pre-authorising every occurrence.\n *\n * ★ IT CARRIES THE SCHEDULE'S NAME, NOT ITS ID. Denormalized at fire time like\n * `execution.scheduleName` itself and for the same reason: a schedule is genuinely deleted,\n * and the row has to stay readable years later. `null` is the honest answer for a run whose\n * row predates that column.\n */\nexport type ChangeRecordDeclarer =\n | { kind: \"run\" }\n | { kind: \"schedule\"; scheduleName: string | null };\n\n/**\n * ═══ ★ WHAT WAS DONE TO THIS REFERENCE, AND BY WHOM — AS ONE SENTENCE ══════════════════\n *\n * ★ A FUNCTION AND NO LONGER FOUR READS OF {@link CHANGE_RECORD_ASSURANCE_ESTABLISHED}.\n * That map's `recorded` sentence opens \"Recorded on this run\", which four surfaces rendered\n * verbatim under the reference — and on a scheduled run it is FALSE. Nobody recorded anything\n * on last night's backup; they recorded it on the schedule, months ago, and every occurrence\n * since has carried the copy. A reader who takes \"on this run\" at face value concludes a human\n * authorised last night's work, which is the one conclusion docs/88 §4.2 exists to prevent.\n *\n * ★ THE ASSURANCE AND THE DECLARER ARE ORTHOGONAL AND BOTH ARE SAID. \"Did anyone check it\"\n * and \"who named it\" are two facts (docs/44 §3.1); collapsing them into one map keyed on\n * assurance is what produced a sentence that answered the first and got the second wrong.\n *\n * ★ AND IT IS THE SAME FUNCTION ON EVERY SURFACE — the run record, the approval card, the\n * audit entry, the feed row. `execution-facts.tsx` already carried the note that one run must\n * not be described three ways; this is that note made mechanical.\n *\n * ★★ IT TAKES THE CITATION AND NOT TWO ARGUMENTS, which is what makes \"a surface that renders\n * the reference and forgets who declared it\" unwritable rather than merely discouraged. The\n * declarer rides on the citation from the row it was read off, so the four callers each pass\n * the one value they already hold and none of them has to know this distinction exists.\n */\nexport function changeRecordEstablishedSentence(citation: ChangeRecordCitation): string {\n const declarer = citation.declaredBy ?? { kind: \"run\" };\n const assurance = citation.assurance;\n if (declarer.kind === \"run\") return CHANGE_RECORD_ASSURANCE_ESTABLISHED[assurance];\n // The schedule's own words. \"Not named for this run\" is stated rather than implied: the\n // reference is sitting in the reader's line and the default reading of a reference on a run\n // is that somebody put it there for that run.\n const named = declarer.scheduleName\n ? `the schedule “${declarer.scheduleName}”`\n : \"the schedule that fired this run\";\n return assurance === \"recorded\"\n ? `Declared on ${named}, not named for this run. ${BRAND_SHORT_NAME} did not check it.`\n : `Declared on ${named}, and checked with your system of record when this run started.`;\n}\n\n/**\n * The requirements a record type may impose. Declared as its own closed set rather than\n * inferred from the table above, because each one owns a SENTENCE (see\n * {@link CHANGE_RECORD_REQUIREMENT_UNMET}) and a sentence needs somewhere to live.\n */\nexport const CHANGE_RECORD_REQUIREMENTS = [\n \"approved\",\n \"permits_work\",\n \"within_window\",\n \"open\",\n] as const;\nexport type ChangeRecordRequirement = (typeof CHANGE_RECORD_REQUIREMENTS)[number];\n\n/**\n * WHY A RECORD DID NOT AUTHORIZE, per unmet requirement — the reader's half of the table\n * above. Written as a clause so the refusal can name the record and then say what is wrong\n * with it, rather than repeating the reference in every branch.\n *\n * ★ `within_window` DOES NOT SAY WHICH WINDOW. The window is the record's own fact and is\n * carried on the refusal so it can be rendered exactly as the system of record has it — a\n * sentence that guessed at a timezone would be worse than one that quoted nothing.\n */\nexport const CHANGE_RECORD_REQUIREMENT_UNMET: Record<ChangeRecordRequirement, string> = {\n approved: \"it has not been approved\",\n permits_work: \"its state does not permit work yet\",\n within_window: \"now is outside its planned window\",\n open: \"it is no longer open\",\n};\n\n/** A planned implementation window, as the system of record states it. */\nexport interface ChangeRecordWindow {\n /** ISO-8601 instant. */\n startsAt: string;\n /** ISO-8601 instant. */\n endsAt: string;\n}\n\n/**\n * WHICH RECORD a run names. The operator supplies both halves: the type says which system\n * of record and which rules apply, the reference is the identifier a human would quote.\n *\n * ★ THE TYPE IS SUPPLIED, NEVER SNIFFED FROM THE REFERENCE. `CHG0031425` and `INC0012938`\n * are distinguishable by prefix in ServiceNow and in nothing else; a parser that guessed\n * would be a parser that eventually decides a rule requiring a change request is satisfied\n * by an incident, which is the one mistake this field must not permit.\n */\nexport interface ChangeRecordRef {\n type: ChangeRecordType;\n /** The identifier as the operator supplied it — never normalized, never re-cased. */\n reference: string;\n}\n\n/**\n * ═══ ★ THE REFERENCE, AND HOW IT WAS ESTABLISHED — TRAVELLING TOGETHER (docs/84 §3.3) ═══\n *\n * What a run KEPT, as against {@link ChangeRecordRef}, which is what an operator SUPPLIED.\n *\n * ★ A SEPARATE TYPE AND NOT A THIRD FIELD ON `ChangeRecordRef`, and that is the compile-time\n * half of §2. The ref is submit input: adding `assurance` to it would let a caller POST their\n * own `\"verified\"` and have the run record say Opera checked a record it never asked about.\n * Here the assurance is only ever WRITTEN by the gate, so the wrong thing does not type-check\n * rather than being refused by a parser somebody has to remember to update.\n *\n * ★ AND IT IS WHY THE TWO NEVER TRAVEL APART. A reader who sees `CHG0031425` on a screen\n * assumes it was checked unless told otherwise, so every surface that renders a reference\n * renders this — the run record, the approval context, the audit event. `execution`'s triple\n * CHECK constraint (migration 0083) is the same rule stated where it cannot be forgotten.\n */\nexport interface ChangeRecordCitation extends ChangeRecordRef {\n assurance: ChangeRecordAssurance;\n /**\n * ★ …AND WHO NAMED IT (docs/88 §4.2). Travels with the other two for the same reason they\n * travel with each other: a reader who sees `CHG0031425` on last night's backup assumes a\n * person put it there for last night's backup, and on a scheduled run that is false.\n *\n * ⚠ OPTIONAL, AND ABSENT MEANS `{kind: \"run\"}`. Every row written before docs/88 was named\n * by somebody at a keyboard — a schedule had no way to name one at all — so the absence is\n * not an unknown, it is the answer. `changeRecordEstablishedSentence` reads it that way, and\n * it is omitted rather than written for a run's own record so no row grows a field that only\n * ever restates the default.\n */\n declaredBy?: ChangeRecordDeclarer;\n}\n\n/**\n * ═══ WHAT A PROVIDER REPORTS — FACTS, NEVER A VERDICT ══════════════════════════════════\n *\n * ★ A PROVIDER ANSWERS WHAT ITS SYSTEM SAYS; {@link changeRecordAuthorization} DECIDES WHAT\n * THAT MEANS. An adapter that returned `authorized: boolean` would be an adapter that owns\n * the policy — and there would then be one copy of \"existence is not authorization\" per\n * vendor, drifting, with the vendor's own words for a state deciding an Opera outcome. The\n * split is what lets ServiceNow, Jira Service Management and a fake in a test all be\n * measured against the same rule.\n */\nexport interface ChangeRecordFacts {\n type: ChangeRecordType;\n /** The reference the provider resolved, in the system of record's canonical spelling. */\n reference: string;\n /** A link into the system of record, when the provider can build one. Null otherwise. */\n url: string | null;\n /**\n * The record's state IN THE PROVIDER'S OWN WORDS — \"Scheduled\", \"Implement\", \"Resolved\".\n * RENDERED, never interpreted: the booleans below are what decides, and this is what a\n * reader recognises when they go and look the record up.\n */\n stateLabel: string;\n /** Somebody signed this record off. False for a type with no approval concept. */\n approved: boolean;\n /** The record's state is one in which the work may actually happen. */\n permitsWork: boolean;\n /** Not resolved, not closed, not cancelled. */\n open: boolean;\n /** The planned implementation window, or null when the record declares none. */\n window: ChangeRecordWindow | null;\n}\n\n/**\n * ═══ ASKING, AND THE THREE ANSWERS ═════════════════════════════════════════════════════\n *\n * ★ `unavailable` IS NOT `not_found`, AND CONFLATING THEM IS THE DEFECT THIS UNION EXISTS\n * TO PREVENT. \"We could not reach your system of record\" and \"there is no such record\" are\n * different facts with different owners: one is Opera's or the network's to fix, the other\n * is the operator's. Both fail closed — the run does not go — but only one of them is the\n * customer's to act on, and a refusal that cannot tell them which wastes the outage.\n */\nexport type ChangeRecordLookup =\n | { outcome: \"resolved\"; facts: ChangeRecordFacts }\n | { outcome: \"not_found\" }\n /** WE COULD NOT ASK. `detail` is the provider's own words, for the operator to quote. */\n | { outcome: \"unavailable\"; detail: string };\n\n/** A record authorizes, or it does not and every unmet requirement is named. */\nexport type ChangeRecordVerdict =\n | { authorized: true }\n | { authorized: false; unmet: readonly ChangeRecordRequirement[] };\n\n/**\n * ═══ DOES THIS RECORD AUTHORIZE A RUN, RIGHT NOW? ══════════════════════════════════════\n *\n * Pure, total over {@link CHANGE_RECORD_REQUIREMENTS}, and the ONE author of the answer —\n * submit asks it, dispatch asks it again, and the checker asks it about a hypothetical.\n * Three callers, one rule, so a run cannot be refused for a reason the plan said nothing\n * about.\n *\n * ⚠ `now` IS AN ARGUMENT, NOT `Date.now()`. The window is the reason this is re-asked at\n * dispatch, so the moment has to be the caller's to state — and a test that cannot choose\n * the moment cannot test a window at all.\n *\n * ★ EVERY UNMET REQUIREMENT IS RETURNED, NOT THE FIRST. A change that is neither approved\n * nor in its window has two things wrong with it, and telling the operator about one, then\n * about the other after they fix it, is two trips for one refusal.\n */\nexport function changeRecordAuthorization(\n facts: ChangeRecordFacts,\n now: Date,\n): ChangeRecordVerdict {\n const unmet = CHANGE_RECORD_AUTHORIZATION[facts.type].filter(\n (requirement) => !requirementMet(requirement, facts, now),\n );\n return unmet.length === 0 ? { authorized: true } : { authorized: false, unmet };\n}\n\n/**\n * One requirement against one record. A total switch, so a new\n * {@link ChangeRecordRequirement} is a compile error here — which is the moment somebody is\n * actually in a position to say how it is measured.\n */\nfunction requirementMet(\n requirement: ChangeRecordRequirement,\n facts: ChangeRecordFacts,\n now: Date,\n): boolean {\n switch (requirement) {\n case \"approved\":\n return facts.approved;\n case \"permits_work\":\n return facts.permitsWork;\n case \"open\":\n return facts.open;\n case \"within_window\":\n return withinWindow(facts.window, now);\n }\n}\n\n/**\n * ★ A RECORD WITH NO WINDOW IS OUTSIDE ITS WINDOW, AND THAT IS DELIBERATE.\n *\n * `null` here means the system of record states no planned window for a type whose rule is\n * \"now is inside its planned window\". Reading that as \"no window, so no constraint\" would\n * make the requirement vanish for exactly the records that declare the least — the most\n * permissive reading of the least information, which is how a control ends up weaker than it\n * appears. A window that cannot be parsed is treated the same way and for the same reason.\n *\n * Half-open on the end: a window ending at 04:00 does not authorize a run AT 04:00. An\n * operator reading \"02:00–04:00\" is entitled to have the work finished by then, and\n * inclusive ends are how \"it started at 03:59:59\" becomes an argument.\n */\nfunction withinWindow(window: ChangeRecordWindow | null, now: Date): boolean {\n if (!window) return false;\n const start = Date.parse(window.startsAt);\n const end = Date.parse(window.endsAt);\n if (Number.isNaN(start) || Number.isNaN(end)) return false;\n const at = now.getTime();\n return at >= start && at < end;\n}\n\n/**\n * ═══ WHY A RUN WAS REFUSED — THE CLOSED SET ════════════════════════════════════════════\n *\n * Every member names the RULE that refused, because a decision that cannot name its cause is\n * not an explanation (docs/46 §3.1) — and on this gate the rule is the only thing that can\n * tell an operator whether they are looking at policy they can get changed or a ticket they\n * need to go and fix.\n *\n * The five members are five different next moves, and collapsing any two would be the\n * wrong-cause lie `ActionRunnabilityCause` was split to remove:\n *\n * · `no_reference` — name a record. Nothing is wrong anywhere.\n * · `wrong_type` — you named one, of a kind this rule does not accept.\n * · `not_found` — your system of record does not have it. Check the reference.\n * · `unavailable` — WE COULD NOT ASK. Nothing for the operator to fix on the record.\n * · `not_authorizing`— WE ASKED AND THE ANSWER WAS NO. The record is the thing to fix.\n */\nexport type ChangeControlRefusal =\n | {\n kind: \"no_reference\";\n rule: ChangeControlRule;\n recordTypes: readonly ChangeRecordType[];\n }\n | {\n kind: \"wrong_type\";\n rule: ChangeControlRule;\n supplied: ChangeRecordRef;\n recordTypes: readonly ChangeRecordType[];\n }\n | { kind: \"not_found\"; rule: ChangeControlRule; supplied: ChangeRecordRef }\n | {\n kind: \"unavailable\";\n rule: ChangeControlRule;\n supplied: ChangeRecordRef;\n /** The provider's own words for what went wrong, quoted rather than paraphrased. */\n detail: string;\n }\n | {\n kind: \"not_authorizing\";\n rule: ChangeControlRule;\n facts: ChangeRecordFacts;\n unmet: readonly ChangeRecordRequirement[];\n }\n /*\n * ═══ ★ A STANDING DECLARATION MET A RULE THAT CHECKS PER RUN (docs/88 §4.5) ══════════\n *\n * The reference came from the SCHEDULE — named once, for every future occurrence — and the\n * rule that matched this occurrence is `verified`, which means \"Opera looks the record up\n * and refuses the run unless it authorizes the work, re-checked the moment the run starts\".\n *\n * ★ REFUSED BEFORE THE LOOKUP, NOT AFTER IT, AND THAT IS THE WHOLE POINT. Asking the\n * provider would sometimes answer yes — a change request approved for tonight's window\n * authorizes tonight's occurrence perfectly well. It authorizes NO OTHER occurrence: a CHG\n * carries one planned window and a schedule fires forever, so the next firing fails\n * `within_window` and every one after it. Letting the first through would ship a schedule\n * that works tonight and dies tomorrow for a reason nothing on the screen predicts, and\n * would write `assurance: \"verified\"` onto occurrences whose authorisation nobody renewed —\n * exactly the history docs/84 §2 says a later slice cannot repair.\n *\n * ★ A SIXTH KIND AND NOT A `not_authorizing` WITH A DIFFERENT CLAUSE. The other five are\n * about the RECORD; this one is about WHERE THE REFERENCE CAME FROM, and the next move is\n * neither \"fix the record\" nor \"name a different one\" — it is \"this work cannot be run\n * unattended under this rule\". Collapsing it into `not_authorizing` would send a reader to\n * their change manager about a record that is perfectly fine.\n */\n | {\n kind: \"standing_declaration\";\n rule: ChangeControlRule;\n supplied: ChangeRecordRef;\n /** The schedule that declared it, by name — see {@link ChangeRecordDeclarer}. */\n scheduleName: string | null;\n };\n\n/**\n * ═══ THE SAME CLOSED SET, DECLARED (charter §4.2) ══════════════════════════════════════\n *\n * A `Record<…, true>` and not a bare `[…] as const`, for the reason\n * `ACTION_RUNNABILITY_CAUSE_KIND_SET` gives in as many words: an array literal pins nothing\n * and can go stale beside the union it claims to enumerate, while this is checked in BOTH\n * directions. A member added to the union without a key here is a missing-property error; a\n * key here that no member declares is an excess-property error.\n */\nconst CHANGE_CONTROL_REFUSAL_KIND_SET = {\n no_reference: true,\n wrong_type: true,\n not_found: true,\n unavailable: true,\n not_authorizing: true,\n standing_declaration: true,\n} as const satisfies Record<ChangeControlRefusal[\"kind\"], true>;\n\n/** Read straight off the union, so the NAME of a kind can never be a second spelling of it. */\nexport type ChangeControlRefusalKind = ChangeControlRefusal[\"kind\"];\n\nexport const CHANGE_CONTROL_REFUSAL_KINDS = Object.keys(\n CHANGE_CONTROL_REFUSAL_KIND_SET,\n) as readonly ChangeControlRefusalKind[];\n\n/**\n * WHOSE PROBLEM IT IS — total over the union, which is the compile-time half of the \"we\n * could not ask\" / \"the answer was no\" distinction acceptance §8.7 asks for.\n *\n * `opera` means nothing the customer does to their record changes the outcome. Every screen\n * that renders a refusal reads this rather than matching on a kind, so adding a sixth member\n * is one decision in one place instead of a sweep nobody finishes.\n */\nexport const CHANGE_CONTROL_REFUSAL_OWNER = {\n no_reference: \"operator\",\n wrong_type: \"operator\",\n not_found: \"operator\",\n unavailable: \"opera\",\n not_authorizing: \"record\",\n // THE OPERATOR'S, and specifically the schedule owner's — the record is fine and Opera is\n // working. What has to change is the arrangement: run this attended and name a record each\n // time, or have the rule that matched it set to Recorded.\n standing_declaration: \"operator\",\n} as const satisfies Record<ChangeControlRefusalKind, \"operator\" | \"record\" | \"opera\">;\n\n/**\n * A change-control rule in its own terms, for the sentences that cite it.\n *\n * Deliberately NOT `MatchedPolicyDto` plus a field: this file is a leaf and importing the\n * governance DTOs would make it one half of a cycle. The two carry the same `id`/`name`\n * because they describe the same row, and `governance.ts` composes them where both are in\n * scope ({@link ExecutionPlanChangeControl}).\n */\nexport interface ChangeControlRule {\n id: string;\n name: string;\n /** What the rule requires. At least one — a rule requiring nothing is refused at save. */\n recordTypes: readonly ChangeRecordType[];\n /**\n * ★ HOW FAR OPERA GOES (docs/84 §3.1). `recorded` is satisfiable today and requires nothing\n * external; `verified` is refused at save until a provider adapter exists.\n *\n * NOT OPTIONAL ON THIS TYPE, deliberately. The storage is jsonb and may predate the field —\n * `assuranceOf` is the one place that reads it defensively, and it answers\n * {@link DEFAULT_CHANGE_RECORD_ASSURANCE}. Everything downstream of that read holds a value,\n * so no refusal sentence and no screen has to decide what an absent level means.\n */\n assurance: ChangeRecordAssurance;\n}\n\n/**\n * ═══ THE REFUSAL, AS ONE SENTENCE ══════════════════════════════════════════════════════\n *\n * Written ONCE, here, because five surfaces say it: the 4xx from submit, the message settled\n * onto a run refused at dispatch, the run record, the plan preview and the governance\n * checker. Five phrasings of one fact is how four of them go stale — and on this gate a\n * stale phrasing is an auditor reading a reason the platform no longer acts on.\n *\n * ★ EVERY BRANCH NAMES THE RULE. That is docs/46's rule applied to the one decision where a\n * reader most needs to know whether to go and argue with their change manager or with their\n * Opera admin.\n */\nexport function changeControlRefusalSentence(\n refusal: ChangeControlRefusal,\n subject: ChangeControlSubject = { kind: \"run\" },\n): string {\n const rule = `your governance rule “${refusal.rule.name}”`;\n switch (refusal.kind) {\n case \"no_reference\":\n // NO \"a\" BEFORE `typeWord`: the word carries its own article. It read \"This run needs a\n // a change request\" in the running app — see `changeRecordTypeNoun` for the audit that\n // found this and its twin two branches down.\n //\n // ★ AND THE SCHEDULE BRANCH DOES NOT SAY \"SUBMIT AGAIN\". Nobody submitted anything —\n // an occurrence came round and there was nobody to ask (docs/88 §1). The remedy is to\n // name the record on the schedule, and the sentence says so and says when it takes\n // effect, because the reader is looking at a job that stopped.\n return subject.kind === \"schedule\"\n ? `Schedule “${subject.name}” did not fire: it needs ` +\n `${orList(refusal.recordTypes.map(typeWord))}, because ${rule} matches the runs ` +\n \"it starts. Name the record this schedule implements and it fires again at its \" +\n \"next occurrence.\"\n : `This run needs ${orList(refusal.recordTypes.map(typeWord))} before it can go ` +\n `ahead: ${rule} requires one. Name the record this run implements and submit again.`;\n case \"wrong_type\":\n return (\n `This run names ${typeWord(refusal.supplied.type)} ${refusal.supplied.reference}, ` +\n `and ${rule} requires ${orList(refusal.recordTypes.map(typeWord))}.`\n );\n case \"not_found\":\n // \"no change request CHG…\", not \"no a change request CHG…\" — `no` IS the determiner\n // here, so this is the branch that needs the bare noun.\n return (\n `Your system of record has no ${typeNoun(refusal.supplied.type)} ` +\n `${refusal.supplied.reference}. ${capitalize(rule)} requires one that exists, so ` +\n `nothing was started — check the reference.`\n );\n // ★ \"WE COULD NOT ASK\", AND IT SAYS SO. The run is refused exactly as firmly as the\n // branch below, and the operator is told plainly that the record is not the problem —\n // otherwise the next twenty minutes are spent looking at a change that was fine.\n case \"unavailable\":\n return (\n `${BRAND_SHORT_NAME} could not reach your system of record to check ` +\n `${typeWord(refusal.supplied.type)} ${refusal.supplied.reference}, so this run was ` +\n `refused rather than started unchecked (${rule} requires it). There is nothing to ` +\n `fix on the record itself — the connection reported: ${refusal.detail}`\n );\n // ★ …AND \"THE ANSWER WAS NO\", which is the operator's to fix and says which part.\n case \"not_authorizing\":\n return (\n `${capitalize(typeWord(refusal.facts.type))} ${refusal.facts.reference} does not ` +\n `authorize this run: ${orList(\n refusal.unmet.map((requirement) => CHANGE_RECORD_REQUIREMENT_UNMET[requirement]),\n \"and\",\n )}. It is ${refusal.facts.stateLabel}${windowClause(refusal)}. ` +\n `${capitalize(rule)} requires a record that authorizes the work.`\n );\n // ★ IT NAMES THE SCHEDULE FROM THE REFUSAL AND NOT FROM `subject`, because this is the\n // one kind that can be read on a surface the schedule is not the subject of — a child\n // execution's own run record, settled at dispatch, where the only thing that still knows\n // a schedule was involved is the row.\n case \"standing_declaration\":\n return (\n `${capitalize(scheduleNameClause(refusal.scheduleName))} names ` +\n `${typeWord(refusal.supplied.type)} ${refusal.supplied.reference} for every ` +\n `occurrence, and ${rule} now requires a record ${BRAND_SHORT_NAME} checks when each run starts. ` +\n \"A reference named once cannot be that — a change request authorizes one planned \" +\n \"window and this job recurs — so nothing was started. Either set that rule to \" +\n \"Recorded, or run this work attended and name a record each time.\"\n );\n }\n}\n\n/**\n * ═══ WHAT WAS REFUSED — A RUN, OR A SCHEDULE THAT REACHED ITS OCCURRENCE ═══════════════\n *\n * ★ A PARAMETER AND NOT A SIXTH COPY OF THE SENTENCE. The branches differ only in their last\n * clause — the REMEDY — and the remedy is the one thing that genuinely differs between the\n * two: \"submit again\" is an instruction the reader of a stopped schedule cannot follow, and an\n * instruction nobody can follow is how a refusal stops being read at all. Everything before it\n * — which rule, which types, which record, what the provider said — is the same fact and stays\n * written once (docs/88 §4.5).\n *\n * ⚠ ONLY `no_reference` VARIES TODAY, AND THAT IS NOT AN OVERSIGHT. It is the only kind a\n * schedule can be refused for before it fires: every other kind needs a reference, and the\n * only reference a schedule can supply is its own — which reaches the gate on the child run\n * and is refused there, on that run's own record, where `standing_declaration` names it.\n */\nexport type ChangeControlSubject =\n | { kind: \"run\" }\n | { kind: \"schedule\"; name: string };\n\n/** The schedule that declared a reference, from a DENORMALIZED name that may be absent. */\nfunction scheduleNameClause(scheduleName: string | null): string {\n return scheduleName\n ? `the schedule “${scheduleName}”`\n : \"the schedule that fired this run\";\n}\n\n/**\n * THE RECORD'S OWN WINDOW, IN THE REFUSAL (acceptance §8.6). Rendered only when the window\n * is the thing that failed: quoting a window on a refusal about an unapproved change would\n * put the one fact that IS fine in front of a reader looking for the one that is not.\n *\n * ISO-8601 verbatim, deliberately. The instants come from the customer's system of record\n * and Opera does not know which timezone their change manager reads in; a localized string\n * built server-side would be a guess rendered as a fact. The surfaces that know the reader's\n * locale may format it from `refusal.facts.window`.\n */\nfunction windowClause(\n refusal: Extract<ChangeControlRefusal, { kind: \"not_authorizing\" }>,\n): string {\n if (!refusal.unmet.includes(\"within_window\")) return \"\";\n const window = refusal.facts.window;\n return window\n ? `, and its planned window is ${window.startsAt} to ${window.endsAt}`\n : \", and it names no planned window at all\";\n}\n\n/**\n * ═══ WHAT THE PLAN SAYS BEFORE SUBMIT ══════════════════════════════════════════════════\n *\n * A requirement the plan can SEE COMING, stated while the operator can still act on it.\n *\n * ★ IT IS A STATEMENT AND NEVER A REFUSAL, which is the same call `packageProvenance` made\n * on this DTO and for the same reason: the plan is computed before the operator has named a\n * record, so \"no record named\" is not a defect at plan time — it is the next thing to do.\n * Routing it through `unrunnable` would make an action read as structurally unrunnable in a\n * wizard whose whole purpose is to let the operator satisfy it.\n *\n * ⚠ AND IT IS NOT AN `ActionRunnabilityCause` FOR THE SECOND REASON TOO (docs/83 §4): those\n * six causes are capability facts — local, cheap, cacheable and previewed in the catalog. A\n * ServiceNow round-trip behind every catalog preview is an outage waiting for the customer's\n * first slow morning.\n */\nexport interface ExecutionPlanChangeControl {\n /** The rule that will require it, by name and in its own terms. */\n rule: ChangeControlRule;\n /** What the operator must name. Never empty. */\n recordTypes: readonly ChangeRecordType[];\n /**\n * HOW FAR OPERA WILL GO with what they name — {@link CHANGE_RECORD_ASSURANCE_REQUIRES} is\n * the sentence. Read off `rule.assurance` and repeated here for the same reason\n * `recordTypes` is: the plan's fields are what the wizard renders, and a form that had to\n * reach inside `rule` for one of two facts about the same requirement is a form that will\n * eventually render one of them and not the other.\n */\n assurance: ChangeRecordAssurance;\n /**\n * TRUE when a provider is connected and can be asked.\n *\n * ⚠ FALSE IS ONLY A PROBLEM WHEN `assurance` IS `verified` — and since docs/84 it is the\n * ORDINARY state of a `recorded` rule rather than a fault. A `recorded` rule asks no\n * provider anything, so it is satisfiable with the registry empty, which is every workspace\n * in this release. Reading this field alone and warning on it would put \"this run will be\n * refused\" under a rule that is about to let the run through — see `ChangeRecordField`,\n * where the two are read together.\n *\n * When `assurance` IS `verified`, false still means the run WILL be refused, and saying so\n * on the plan is the difference between an operator who knows and one who finds out after\n * typing a ticket number. Such a rule cannot be ENABLED in that state (docs/83 §5), so it\n * is reachable only by a provider that was connected and went away.\n */\n providerConnected: boolean;\n}\n\n/**\n * \"a change request\", \"an incident\" — a record type AS IT READS INSIDE A SENTENCE.\n *\n * ★ EXPORTED, because the browser needs it too. Three surfaces built this phrase from\n * `CHANGE_RECORD_TYPE_LABEL[type].toLowerCase()` and every one of them dropped the article:\n * the policy editor's live preview read *\"every run will be refused unless the run names\n * change request that authorizes it\"* — measured in a real browser, not inferred. The label\n * map is for LABELS (a chip, a tile heading); this is for prose, and the difference is exactly\n * the article, which is a property of the word and not of the sentence.\n */\nexport function changeRecordTypeWord(type: ChangeRecordType): string {\n return type === \"incident\" ? \"an incident\" : \"a change request\";\n}\n\n/** The same phrase for a list of types: \"a change request or an incident\". */\nexport function changeRecordTypesPhrase(types: readonly ChangeRecordType[]): string {\n return orList(types.map(changeRecordTypeWord));\n}\n\n/**\n * ═══ THE BARE NOUN — \"change request\", with no article ═════════════════════════════════\n *\n * ★ A SECOND FORM, BECAUSE ENGLISH NEEDS ONE, AND EVERY BRANCH WAS AUDITED TO FIND WHICH.\n * `changeRecordTypeWord` carries its own article, which is right after a verb (\"names a change\n * request\") and wrong after a determiner (\"has no A change request\") or a second article\n * (\"needs A a change request\"). Both of those shipped into the running app, and one of them\n * was frozen into a test that asserted the broken string back — the assertion had been written\n * from the code rather than from what a reader should see.\n *\n * So the five branches of {@link changeControlRefusalSentence} were each read out loud:\n *\n * · `no_reference` \"needs …\" → bare-with-article, no leading \"a\" (fixed)\n * · `wrong_type` \"names …\" / \"requires …\" → with article (was ok)\n * · `not_found` \"has no …\" → BARE NOUN (fixed)\n * · `unavailable` \"to check …\" → with article (was ok)\n * · `not_authorizing` \"«Type» X does not …\" → capitalized, with article (was ok)\n */\nexport function changeRecordTypeNoun(type: ChangeRecordType): string {\n return type === \"incident\" ? \"incident\" : \"change request\";\n}\n\n/** Internal aliases, so the refusal sentences above read as prose rather than as calls. */\nconst typeWord = changeRecordTypeWord;\nconst typeNoun = changeRecordTypeNoun;\n\nfunction orList(values: readonly string[], conjunction: \"or\" | \"and\" = \"or\"): string {\n if (values.length <= 1) return values[0] ?? \"\";\n return `${values.slice(0, -1).join(\", \")} ${conjunction} ${values[values.length - 1]!}`;\n}\n\nfunction capitalize(value: string): string {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\n","// ═══ WHERE A RUN EXECUTES — THE VOCABULARY, AS A LEAF ══════════════════════════════════\n//\n// ★ IT IS ITS OWN FILE BECAUSE IT IS ASKED BY BOTH ENDS OF A CYCLE. `execution-site.ts` holds\n// the DTOs that RECORD where a run went and needs `PackagePhase`; `package-execution.ts` holds\n// the package protocol and, since docs/60, needs to be told where a run is PLACED. Declaring\n// the vocabulary in either one makes the two import each other, which `.dependency-cruiser.cjs`\n// refuses by name — and correctly: a cycle is how two files come to be edited as one.\n//\n// The same cut this repository has made before (`validation.ts`, closing the `pnpm boundaries`\n// failure that had been red since docs/57): when a shared vocabulary sits in a file that also\n// holds shapes, the vocabulary moves to a leaf and the shapes import it.\n\n/**\n * The closed vocabulary. Declared once (charter §4.2) and stored as TEXT with a CHECK\n * constraint that repeats it — a second Postgres enum would be a second place to add a member.\n */\nexport const EXECUTION_SITES = [\"hosted\", \"runner\", \"unknown\"] as const;\nexport type ExecutionSite = (typeof EXECUTION_SITES)[number];\n\n/** True for a stored value this vocabulary understands. */\nexport function isExecutionSite(value: string): value is ExecutionSite {\n return (EXECUTION_SITES as readonly string[]).includes(value);\n}\n\n/**\n * ═══ THE TWO DESTINATIONS, NOT THE THREE RECORD STATES ═════════════════════════════════\n *\n * Derived from {@link EXECUTION_SITES} rather than spelled again, minus the one member that is\n * not a destination: `unknown` is what a row says when nothing wrote to it, and no run is ever\n * SENT there. `satisfies readonly ExecutionSite[]` is what makes a rename above a compile error\n * here rather than two vocabularies drifting.\n *\n * docs/60 §3.3 needs it as an INPUT: which isolation confines a package depends on which of\n * these two places its run was placed with, and the engine already computes exactly this value\n * for {@link import(\"./execution-site\").RunExecutionSiteDto}.\n */\nexport const RUN_PLACEMENTS = [\"hosted\", \"runner\"] as const satisfies readonly ExecutionSite[];\nexport type RunPlacement = (typeof RUN_PLACEMENTS)[number];\n\n/**\n * ═══ WHERE A RUN IS PLACED, AND — WHEN THAT IS A POOL — WHICH ONE ══════════════════════\n *\n * ★ ONE VALUE, NOT A SITE PLUS A NULLABLE POOL, for the reason {@link\n * import(\"./execution-site\").RunExecutionSiteDto} gives one level down: two loose fields make\n * \"runner, pool unknown\" and \"hosted, but here is a pool\" both expressible, and one of them\n * would eventually be built. A discriminated union means the caller that says `runner` is\n * exactly the caller that has a pool in hand.\n *\n * ⚠ IT CARRIES THE POOL AND NOT A RUNNER, deliberately. Which MACHINE takes the work is decided\n * when a runner claims, minutes later and by the runner itself; a placement is what the plan\n * gate decided, and the plan gate decides a pool.\n */\nexport type RunPlacementRef =\n | { site: \"hosted\" }\n | { site: \"runner\"; pool: RunPlacementPool };\n\n/** A pool, named — enough for a message that tells somebody where their run went. */\nexport interface RunPlacementPool {\n id: string;\n name: string;\n}\n\n/**\n * ═══ CLASS 2 — WHAT THE HOSTED SITE IS CALLED, AND WHY IT LIVES HERE ════════════════════\n *\n * ★ THE CONCEPT WAS ALREADY DECLARED; ONLY ITS LABEL WAS NOT. `\"Opera's cloud\"` was the most\n * common brand-shaped phrase in the tree — 99 occurrences — and it is NOT the brand. It is the\n * human-readable name of {@link EXECUTION_SITES}'s `hosted` member: the execution site we run,\n * as opposed to a customer's private runner. Six functions in `@runveric/contracts` alone spelled\n * it as a literal (`execution-site.ts` four times, `execution.ts`, `runner-pool-routing.ts`),\n * which is charter §4.2's defect exactly — a closed vocabulary with several authors.\n *\n * ⛔ AND IT IS NOT `` `${BRAND_NAME}'s cloud` ``. That is the trap docs/95 §4.1 names, and it\n * is worse than the literal it replaces: a possessive built on a brand asserts that the company\n * owns the concept, so the day the company is renamed every sentence about WHERE A RUN\n * EXECUTES changes with it — including the ones an approver reads immediately before saying\n * yes. The two values are independent on purpose. This file imports nothing, `./brand` least\n * of all, and `brand-vocabulary-independence.spec.ts` asserts that from the source.\n *\n * ⚠ ONE RENDERED CHARACTER, AND IT IS THE STRAIGHT APOSTROPHE `'` (U+0027). Two spellings\n * stood in the tree: 93 with `'`, and 6 in JSX written as the HTML entity `Opera&rsquo;s`,\n * which renders as `’` (U+2019). One constant cannot be both, and the entity cannot survive\n * the move AT ALL: `&rsquo;` is markup that only JSX TEXT resolves, so the same bytes inside a\n * string constant interpolated as `{HOSTED_EXECUTION_LABEL}` would render the literal text\n * \"&rsquo;\" on the page. The straight apostrophe is therefore the only spelling expressible as\n * one declaration — and it is also the majority, what `execution-site.ts` already returned, and\n * what the specs already asserted. The six entity sites' rendered glyph changes from `’` to `'`.\n *\n * ⚠ DO NOT SHORTEN THIS NAME TO `HOSTED`. `where-runs-execute-panel.tsx` already has a\n * `const HOSTED = \"__hosted__\"` — an unrelated `<Select>` sentinel — and an import of that\n * name would shadow it silently in the one file that renders this label.\n */\nexport const HOSTED_EXECUTION_LABEL = \"our hosted cloud\";\n","// ═══ WHERE A PACKAGE'S BYTES CAME FROM — A LEAF, AND THE LEAF IS THE POINT ══════════════\n//\n// ★ THIS MODULE IMPORTS NOTHING, AND THAT IS WHY IT EXISTS SEPARATELY FROM `packages.ts`.\n// docs/59 gave three more modules a reason to read the provenance vocabulary: `governance.ts`\n// (the approver's snapshot), `runners.ts` (what a pool has vouched for) and\n// `runner-pool-routing.ts` (the pool a run resolves to). `packages.ts` already imports\n// `ExecutionPlanGovernance` from `governance.ts`, so the first of those closed a cycle:\n//\n// governance.ts → packages.ts → governance.ts\n//\n// MEASURED, not predicted: `pnpm boundaries` reported it by name — while `pnpm\n// boundaries:verify` stayed GREEN through it, because that script is the LITMUS (it proves the\n// checker can reject a cross-module-internal import) and not the check. A cycle of exactly this\n// shape shipped to production once, red from `e97948b` until `b4074bc`, because a whole\n// programme was reviewed with the litmus mistaken for the check.\n//\n// The fix is the one that closed that cycle too: cut the shared vocabulary to a module that\n// depends on nothing, so every reader can reach it without reaching each other. `packages.ts`\n// re-exports all of it, so no existing call site moved.\n\n/**\n * ─── HOW A PACKAGE VERSION GOT HERE (charter §4.2, array-first) ─────────────────────────\n *\n * PROVENANCE is not the same question as WHICH GIT SOURCE. `sourceId` answers \"through which\n * connection did Opera fetch these bytes\", and it is null for two completely different reasons:\n * an anonymous public-Git import, and a package an admin authored inside Opera. Reading trust\n * off `sourceId != null` therefore collapsed those two into one, and the second one — the safer\n * of the two by every measure below — inherited the first one's answer.\n *\n * So provenance is recorded as its own closed vocabulary, declared ONCE, here.\n *\n * git_source fetched through a tenant-owned GitHub App / GHES connection. Trust comes from\n * a repository the tenant demonstrably controls, and it is REVOCABLE — the\n * connection can be disconnected or removed, and the package stops running.\n * public_git fetched anonymously from a public repository. Nobody vouched for it. This is\n * the untrusted tier and it stays untrusted.\n * authored written or pasted into Opera by an authenticated principal of this tenant\n * holding `package:manage`.\n *\n * ─── WHY `authored` IS ORGANIZATION TIER, AND `public_git` IS NOT ───────────────────────\n *\n * The question the organization tier answers is: *did an authorized principal of this tenant\n * put this code here, and can we prove it later?*\n *\n * A Git App source answers it by proving a repository the tenant controls — an org owner\n * selected the repositories, a tenant admin connected the source, and Opera fetched through\n * that installation. The evidence is a chain of two configurations.\n *\n * An authenticated admin pasting into their own tenant answers the SAME question with a\n * STRONGER trail. Opera knows the user id, the exact time, the request that carried it, and\n * the exact bytes — hashed into `contentDigest` and immutable from the moment they land. The\n * Git path knows a commit sha in a repository whose history somebody else can rewrite.\n *\n * `public_git` answers it with nothing at all. Anyone can publish a public repository, so a\n * public import proves only that the URL resolved. That is why widening the community tier\n * would have been the wrong route to the same feature: it would have admitted every anonymous\n * import along with the authored one, to make the authored one work.\n *\n * WHAT `authored` DOES NOT CHANGE: the sandbox, the brokered credential, the egress rules, the\n * immutability of a published version, and the adoption/approval gates are all identical. It is\n * a statement about where bytes came from, and nothing else.\n *\n * It also carries NO reconnect/disconnect lifecycle, because there is no external account to\n * lose — see {@link PACKAGE_PROVENANCE_IS_REVOCABLE}.\n */\n\nimport { BRAND_SHORT_NAME } from \"./brand\";\n\nexport const PACKAGE_PROVENANCE_KINDS = [\"git_source\", \"public_git\", \"authored\"] as const;\nexport type PackageProvenanceKind = (typeof PACKAGE_PROVENANCE_KINDS)[number];\n\n/**\n * Whether a provenance can STOP vouching for a package after the fact.\n *\n * Keyed by the union (charter §4.2 R2), so a new provenance is a compile error until somebody\n * decides this. It is the fact behind the `source_disconnected` / `source_removed` refusals: a\n * package whose provenance is not revocable can never reach either of them, because there is no\n * external account whose loss would trigger one. Asserted, not assumed — see\n * `authored-provenance.spec.ts`.\n */\nexport const PACKAGE_PROVENANCE_IS_REVOCABLE: Record<PackageProvenanceKind, boolean> = {\n // A GitHub App installation can be disconnected in Opera or uninstalled on GitHub.\n git_source: true,\n // Nothing to revoke — nothing vouched for it in the first place.\n public_git: false,\n // The authoring user can be deactivated and the tenant can remove an authored RELEASE, but\n // neither is an external account that Opera reads a live status from. There is no connection\n // to lose, so there is no state in which the bytes are still here and their provenance is not.\n authored: false,\n};\n\n/** How each provenance reads in a sentence — one wording, used by every surface. */\nexport const PACKAGE_PROVENANCE_LABELS: Record<PackageProvenanceKind, string> = {\n git_source: \"Imported from Git\",\n public_git: \"Imported from a public repository\",\n authored: `Authored in ${BRAND_SHORT_NAME}`,\n};\n\n/**\n * ═══ THE LABEL AS IT READS INSIDE A SENTENCE ═══════════════════════════════════════════\n *\n * ★★ A DECLARED FORM, NOT `LABELS[kind].toLowerCase()`, AND THE BROWSER IS WHAT SETTLED IT.\n * The refusal was built by lower-casing the label so it could sit mid-clause, and it rendered\n * as *\"This action's package is authored in opera\"* — a mechanical transform flattening a\n * PROPER NOUN. No test could see it: every assertion matched case-insensitively or on a\n * substring that did not span the word.\n *\n * This is the same defect `plannedExecutionSiteSentence` already carries a warning about one\n * module over — *\"'Opera's cloud' keeps its capital because it is a proper noun, not because it\n * is the start of a sentence\"* — and it is why casing is a VOCABULARY here rather than a\n * function of one. `Record` keyed by the union, so a fourth provenance has to state both forms.\n */\nexport const PACKAGE_PROVENANCE_CLAUSES: Record<PackageProvenanceKind, string> = {\n git_source: \"imported from Git\",\n public_git: \"imported from a public repository\",\n // ⚠ \"Opera\" KEEPS ITS CAPITAL. This is the entry the whole record exists for.\n authored: `authored in ${BRAND_SHORT_NAME}`,\n};\n\n/**\n * ═══ WHO WROTE THIS CODE, IN A SENTENCE A NON-ENGINEER CAN ACT ON (docs/59 §3.3) ════════\n *\n * `PACKAGE_PROVENANCE_LABELS` is a LABEL — three words for a badge. This is the DISCLOSURE:\n * what the label means for the person being asked to accept it, or being told what is about to\n * run on their machines.\n *\n * ★ TWO LENGTHS, NOT TWO VOCABULARIES, for the reason `actionRunnabilityHeadline` gives one\n * module over: the plan's callout and the pool's consent screen are the same fact said to two\n * readers, and two hand-written copies of a sentence about who wrote some code drift. It\n * switches over the union in the file that declares it, so a fourth provenance cannot be worded\n * here in a way that contradicts its label.\n *\n * ⚠ IT STATES THE FACT AND NOT A VERDICT. None of these three sentences says \"safe\",\n * \"trusted\" or \"verified\": Opera does not know whether a customer should run a given package on\n * a given machine, and a sentence that implied it did would be Opera vouching — which is\n * precisely what docs/59 refuses to do.\n */\nexport const PACKAGE_PROVENANCE_DISCLOSURES: Record<PackageProvenanceKind, string> = {\n // The two-level GitHub App binding. It says an authorized principal of this tenant connected\n // the repository — NOT that anybody read what is in it.\n git_source:\n \"imported from a Git repository your organisation connected. Connecting a repository \" +\n \"says who it belongs to; it does not say anybody reviewed what is in it.\",\n // ★ THE ONE THE WHOLE SLICE TURNS ON. It must not be softened, and it must not be moralised\n // either — the sentence states who did not write it and stops.\n public_git:\n `imported from a public repository. Neither ${BRAND_SHORT_NAME} nor your organisation wrote it, and ` +\n \"nobody vouched for it when it was imported.\",\n // Stronger than a Git App binding, and the sentence says why rather than asserting it.\n authored:\n `written in ${BRAND_SHORT_NAME} by a named member of your organisation, and pinned to the exact bytes ` +\n \"they published.\",\n};\n\n/**\n * ═══ WHO OPENED THIS POOL TO THIS CODE, AND WHEN — ANSWERABLE BY FILTERING ══════════════\n *\n * The audit action names for accepting and revoking one provenance on one pool (docs/59\n * judgement 4). Following `runner.rule.created` / `runner.rule.deleted`: an action per\n * DIRECTION, because accepting sends a class of code somewhere new and revoking takes it away,\n * and an auditor filtering for the first must not be handed the second.\n *\n * ★★ AND AN ACTION PER PROVENANCE, WHICH GOES ONE LEVEL FURTHER THAN THE RULE EVENTS DO.\n * MEASURED first: `AuditRepository.list` filters on `action` prefixes, `at`, `actorId`, and a\n * `q` that searches `action`, `subjectType`, `subjectId` and the curated `metadata.reference`\n * / `metadata.label`. It does NOT reach arbitrary payload fields. So a single\n * `runner.pool.provenance_accepted` carrying `{provenance: \"public_git\"}` would put the whole\n * question — *who opened this pool to PUBLIC code* — in a field no filter can see, and an\n * auditor would answer it by reading rows instead of selecting them.\n *\n * Naming it in the action makes `q=accepted_public_git` the query, and `q=<poolId>` the other\n * axis (the pool is the audit SUBJECT, which `q` does search). That is the same argument\n * `RUNNER_LIFECYCLE_EVENTS` makes for splitting drain/resume/revoke rather than putting the\n * state in metadata — applied to the axis that actually carries the risk here, because docs/59\n * §3.2's whole reason for a SET rather than a boolean is that these three are different risks.\n * An audit trail that re-collapsed them would give back exactly what the model paid to keep.\n *\n * ⚠ KEYED BY THE UNION, so a fourth provenance is a compile error until somebody names its two\n * actions — and `audit.service.ts` DERIVES its subscription list from this, so there is no\n * second list to forget.\n *\n * The `runner.` prefix keeps these in the `connections` audit category, where the pool's other\n * history already lives: \"what changed about how we reach that estate\" is one question.\n */\nexport const POOL_PROVENANCE_AUDIT_ACTIONS = {\n git_source: {\n accepted: \"runner.pool.accepted_git_source\",\n revoked: \"runner.pool.revoked_git_source\",\n },\n public_git: {\n accepted: \"runner.pool.accepted_public_git\",\n revoked: \"runner.pool.revoked_public_git\",\n },\n authored: {\n accepted: \"runner.pool.accepted_authored\",\n revoked: \"runner.pool.revoked_authored\",\n },\n} as const satisfies Record<PackageProvenanceKind, { accepted: string; revoked: string }>;\n\n/** Every action name above, derived — so a subscriber cannot list a stale subset. */\nexport const POOL_PROVENANCE_AUDIT_ACTION_NAMES: readonly string[] = Object.values(\n POOL_PROVENANCE_AUDIT_ACTIONS,\n).flatMap((pair) => [pair.accepted, pair.revoked]);\n\n/** The action one change writes. One provenance, one direction, one row. */\nexport function poolProvenanceAuditAction(\n provenance: PackageProvenanceKind,\n accepted: boolean,\n): string {\n const pair = POOL_PROVENANCE_AUDIT_ACTIONS[provenance];\n return accepted ? pair.accepted : pair.revoked;\n}\n","// ═══ WHO VOUCHES FOR A PACKAGE — A LEAF, FOR THE REASON `package-provenance.ts` IS ══════\n//\n// ★ THIS MODULE IMPORTS NOTHING. `PackageTier` lived in `packages.ts`, which imports\n// `ActionCapabilities` and friends from `catalog.ts`; docs/92 §7.1 puts a TIER BADGE on the\n// catalog row, so `catalog.ts` now needs the vocabulary and would have closed:\n//\n// catalog.ts → packages.ts → catalog.ts\n//\n// The fix is the one `package-provenance.ts` already documents — cut the shared vocabulary to a\n// module that depends on nothing, so every reader can reach it without reaching each other.\n// `packages.ts` re-exports all of it, so no existing call site moved.\n\n/**\n * ─── WHAT EACH RUNG CLAIMS (docs/92 §4.1) ───────────────────────────────────────────────\n *\n * A tier is a claim about ACCOUNTABILITY, not about quality. It answers one question — *who is\n * answerable when this code does something nobody wanted?* — and for two of the five rungs the\n * honest answer is \"nobody\", which is precisely why the words below have to be rendered.\n */\n\nimport { BRAND_SHORT_NAME } from \"./brand\";\n\nexport type PackageTier = \"official\" | \"partner\" | \"verified\" | \"community\" | \"organization\";\n\n/**\n * ★★ THE BADGE CARRIES ITS OWN LIMIT, AND `verified` IS WHY THIS EXISTS.\n *\n * \"Verified\" reads as \"vetted\" and means \"a linter passed\". docs/84's rule is that a reader who\n * sees a badge assumes it was checked unless told otherwise, so the claim is not a tooltip and\n * not a docs page — it is rendered next to the word, from here.\n *\n * ⚠ A `Record` KEYED ON THE UNION, DELIBERATELY NOT AN ARRAY (docs/92 §14.1.5). An exhaustive\n * `Record` already fails the build when a sixth tier is added, which is the whole property\n * charter §4.2 protects — a member cannot arrive without someone writing what it claims. An\n * array buys ITERATION, and nothing iterates tiers: the catalog row renders the one tier its\n * definition carries. Slice 3's tier-ladder page is the first thing that will walk all five,\n * and that is when `PACKAGE_TIERS` should be born.\n *\n * ⛔ So do not \"complete\" this with an unused `PACKAGE_TIERS` array. An exported const that\n * nothing reads is the third vacuous guard this codebase has had to delete.\n */\nexport const PACKAGE_TIER_CLAIMS = {\n official: `${BRAND_SHORT_NAME} wrote and maintains this action.`,\n partner: \"Published by a named partner under agreement, with a security contact.\",\n verified: \"Automated checks passed. Nobody reviewed the code.\",\n community: \"Published by anyone. Nobody vouches for it.\",\n organization: \"Authored inside this workspace by one of its own admins.\",\n} as const satisfies Record<PackageTier, string>;\n\n/** The badge word itself. Same `Record` reasoning as the claims above. */\nexport const PACKAGE_TIER_LABELS = {\n official: \"Official\",\n partner: \"Partner\",\n verified: \"Verified\",\n community: \"Community\",\n organization: \"Workspace\",\n} as const satisfies Record<PackageTier, string>;\n","import type {\n ActionCapabilities,\n ParameterControl,\n ParameterSchema,\n RequiredPermission,\n} from \"./catalog\";\nimport type { ActionCategory, Environment, Provider, RiskLevel } from \"./enums\";\nimport type { ExecutionPlanGovernance } from \"./governance\";\nimport type { EgressDisclosureDto } from \"./package-egress\";\n/*\n * ★ RE-EXPORTED, NOT REDECLARED. The provenance vocabulary moved to a leaf module so\n * `governance.ts` could read it without closing a cycle back through this file — see\n * `package-provenance.ts` for the measurement. Every existing importer of\n * `PACKAGE_PROVENANCE_*` and `PackageProvenanceKind` from `@runveric/contracts` is unaffected,\n * which is what makes this a boundary fix rather than a rename with a blast radius.\n */\nexport * from \"./package-provenance\";\n/* `PackageTier` moved to a leaf for the same cycle reason — see `package-tier.ts`. */\nexport * from \"./package-tier\";\nimport type { ActionManifestApiVersion } from \"./wire-identity\";\nimport type { PackageTier } from \"./package-tier\";\nimport type { PackageProvenanceKind } from \"./package-provenance\";\nimport { BRAND_SHORT_NAME } from \"./brand\";\n\n/**\n * ═══ ⛔ THE PACKAGE-RUNNER CONNECTOR KEY — A COLUMN VALUE, AND AN AUTHORED ONE ═══════════\n *\n * `action_definition.connector_key` holds this string, and `ConnectorRegistry.get()` THROWS\n * `UnknownConnectorError` on a key it does not know — so a row whose value the running image\n * does not recognise is not a degraded run, it is every run of that action failing.\n *\n * docs/107 taught every reader both spellings and kept writing the old one; docs/108 writes\n * this one, and migration 0089 rewrote the one production row that held the old.\n */\nexport const PACKAGE_RUNNER_CONNECTOR_KEY = \"runveric.package-runner\";\n\n/**\n * ⛔ THE RETIRED SPELLING — AND IT IS STILL READ, ON PURPOSE, BECAUSE IT IS NOT ONLY IN A ROW.\n *\n * It is the `connectorKey:` line of an AUTHOR'S `action.yaml`. The scaffold behind\n * `runveric init` and the in-app \"start from scratch\" wrote it into every package from\n * 2026-08-05 until docs/108, and a manifest that names it is runner-backed whatever its\n * source's trust (`packages.service.ts` projects `manifest.connectorKey` when the package is\n * not runner-eligible). Those files are in authors' repositories and drafts, where no migration\n * reaches, and they import today — the `apiVersion` they declare did not change. So this is\n * accepted until the manifest schema moves, exactly like any other published vocabulary.\n *\n * ⚠ READING ONE VALUE HERE WOULD NOT FAIL A BUILD. It would make such a manifest look like a\n * built-in: the runner's capability gates skipped at import, a definition bound to a key no\n * connector answers, \"No runtime\" in the catalog and `UnknownConnectorError` at run time. It is\n * never WRITTEN: {@link canonicalConnectorKey} maps it to {@link PACKAGE_RUNNER_CONNECTOR_KEY}\n * before anything reaches a row.\n */\nexport const LEGACY_PACKAGE_RUNNER_CONNECTOR_KEY = \"opera.package-runner\";\n\n/**\n * ★★ THE ONLY WAY TO ASK \"IS THIS THE PACKAGE RUNNER?\" — and the reason it is a function and\n * not a comparison is that there are two right answers and nine call sites.\n *\n * Eight of them were `connectorKey === PACKAGE_RUNNER_CONNECTOR_KEY`, spread across the\n * execution service, the run handler and the packages service. A rename that widened seven and\n * missed one would not fail a build or a test: the missed site would simply take the wrong\n * branch — a package treated as a built-in, or a built-in asked for a package timeout — on the\n * one row in production that matters.\n */\nexport function isPackageRunnerConnectorKey(connectorKey: string): boolean {\n return (\n connectorKey === PACKAGE_RUNNER_CONNECTOR_KEY ||\n connectorKey === LEGACY_PACKAGE_RUNNER_CONNECTOR_KEY\n );\n}\n\n/**\n * The spelling a connector key is STORED under: the package runner's current one, whichever\n * spelling an author's manifest used; every other key unchanged. What makes the retired\n * spelling read-only rather than merely unwritten by us.\n */\nexport function canonicalConnectorKey(connectorKey: string): string {\n return isPackageRunnerConnectorKey(connectorKey) ? PACKAGE_RUNNER_CONNECTOR_KEY : connectorKey;\n}\n\n/**\n * How a package declares the environment its logic needs (docs/21 §11.4, docs/31 §10.2).\n *\n * The discriminant names the SHAPE of the declaration, not the specific tool: `interpreter`\n * is \"an interpreter plus a pinned version\", so a second interpreter later is a new `name`,\n * never a new kind. `oci` is \"these exact image bytes\", identified by digest.\n */\nexport const PACKAGE_RUNTIME_KINDS = [\"interpreter\", \"oci\"] as const;\nexport type PackageRuntimeKind = (typeof PACKAGE_RUNTIME_KINDS)[number];\n\n/**\n * The interpreters a package may declare — the closed vocabulary behind docs/31 story C3\n * (\"bring an existing script, in any language, into the catalog without rewriting it\").\n *\n * Array-first (charter §4.2): declared ONCE, here, with the union derived from it. It used to\n * be no vocabulary at all — `name` was a free-form `string` and the protocol compared it to the\n * literal `\"powershell\"` — so \"any language\" meant PowerShell 7.4, enforced by a hard-coded\n * comparison that neither an author nor an operator could see.\n *\n * A member of this list is a PROMISE that some adapter on some deployment executes it, which is\n * why the vocabulary and the runner image that ships the interpreters land together: a name here\n * that no image provides would move the failure from import (where it is a sentence) to mid-run\n * (where it is a stack trace).\n */\nexport const PACKAGE_INTERPRETERS = [\"powershell\", \"bash\", \"python\"] as const;\nexport type PackageInterpreter = (typeof PACKAGE_INTERPRETERS)[number];\n\n/** An interpreter runtime, pinned to a version — e.g. `powershell` 7.4. */\nexport interface PackageInterpreterRuntime {\n kind: \"interpreter\";\n /**\n * Closed, not free-form: an interpreter Opera does not know is refused at IMPORT, naming\n * what IS supported, rather than travelling all the way to an adapter to fail there.\n */\n name: PackageInterpreter;\n version: string;\n}\n\n/**\n * An OCI image runtime. `image` is ALWAYS a digest-pinned reference\n * (`<registry>/<repository>@sha256:<64 hex>`) — a tag is rejected at import, because a tag\n * is a mutable pointer and a digest is the content.\n */\nexport interface PackageOciRuntime {\n kind: \"oci\";\n image: string;\n}\n\n/** The execution environment a package version is pinned to. */\nexport type PackageRuntime = PackageInterpreterRuntime | PackageOciRuntime;\n\n/** The package-native capability declaration retained with the immutable version. */\nexport interface PackageCapabilities {\n dryRun: boolean;\n idempotent: boolean;\n rollback: boolean;\n}\n\n/** Provider-native permissions from action.yaml, before catalog projection. */\nexport interface PackageRequiredPermission {\n provider: Provider;\n actions: string[];\n scope: string;\n}\n\n/** Frozen Phase-1 action.yaml contract. */\nexport interface ActionPackageManifest {\n apiVersion: ActionManifestApiVersion;\n id: string;\n name: string;\n author: string;\n version: string;\n summary: string;\n category: ActionCategory;\n providers: Provider[];\n connectorKey: string;\n runtime: PackageRuntime;\n executionTimeout: string;\n parametersRef: string;\n entrypoint: string;\n rollback: boolean;\n rollbackEntrypoint?: string;\n validateEntrypoint?: string;\n riskLevel: RiskLevel;\n requiredPermissions: PackageRequiredPermission[];\n capabilities: PackageCapabilities;\n requiresNetwork: boolean;\n /** Additional outbound destinations requested by the package. Empty when network is disabled. */\n egressAllowlist?: string[];\n secrets: string[];\n /**\n * AAD scopes (`https://<resource>/.default`) the sandbox credential broker mints a\n * short-lived, least-privilege token for (docs/21 §12.5). Optional; absent → the broker\n * defaults to the provider's management scope. Brokered only on the first-party sandbox path.\n */\n credentialScopes?: string[];\n license: string;\n minRunvericVersion: string;\n}\n\nexport interface ImportPackageInput {\n source: string;\n ref: string;\n /** Tenant-owned Git source connection. Omitted preserves anonymous public Git import. */\n sourceId?: string;\n}\n\nexport type PackageProjectionSourceKind = \"builtin\" | \"git\";\nexport type PackageSourceKind = \"github_app\" | \"github_enterprise\" | \"public_git\";\nexport type PackageSourceStatus = \"connected\" | \"disconnected\" | \"error\";\n\nexport const ADOPTION_STATUSES = [\"draft\", \"published\", \"decommissioned\"] as const;\nexport type AdoptionStatus = (typeof ADOPTION_STATUSES)[number];\n\nexport interface AdoptionDto {\n id: string;\n tenantId: string;\n packageVersionId: string;\n actionDefinitionId: string;\n status: AdoptionStatus;\n requiresApproval: boolean | null;\n adoptedBy: string;\n publishedAt: string | null;\n decommissionedAt: string | null;\n createdAt: string;\n}\n\n/**\n * A first adoption carries NO review digest, and that is a decision rather than an omission\n * (docs/31 §10.4). Package versions are immutable, so the disclosure for version X cannot go\n * stale between reading it and accepting it — there is nothing for a token to protect\n * against. Adding one would be ceremony without a threat model, and ceremony teaches people\n * to click through ceremony. The drift guard belongs on `UpdateAdoptionInput`, where the\n * `from` side really can move underneath the reader.\n */\nexport interface CreateAdoptionInput {\n packageVersionId: string;\n}\n\n/**\n * Move an adoption onto another version of the same package (docs/31 §10.4, charter §4.9).\n *\n * The two acknowledgement fields are REQUIRED, and deliberately so: an upgrade that can be\n * applied without them is the vulnerability this input exists to close. `CreateAdoptionInput`\n * carries no such fields on purpose — see its own note.\n */\nexport interface UpdateAdoptionInput {\n packageVersionId: string;\n /**\n * The version the caller believed the adoption was on. A mismatch means somebody else\n * re-pointed it since the review was read, so the acknowledgement is not about this move.\n */\n fromPackageVersionId: string;\n /**\n * The `reviewDigest` of the review the caller actually read. The server recomputes the\n * review and compares — it never trusts this value as evidence of anything but intent.\n */\n reviewedReviewDigest: string;\n}\n\nexport interface SetAdoptionApprovalInput {\n requiresApproval: boolean | null;\n}\n\n/**\n * ─── WHAT THE APPROVAL SETTING ACTUALLY DOES ──────────────────────────────────────────\n *\n * An adoption override may ADD approval to an action policy would let through. It can never\n * REMOVE approval that policy mandates — otherwise adopting a package would be a way around\n * governance, which is the opposite of what an adoption is for.\n *\n * That behaviour is correct and is not changing. What was wrong was the INTERFACE: a\n * decisive-looking three-way control that could only ever escalate, and that said nothing at\n * all when an admin's \"Not required\" was overruled by policy. They found out from a run.\n *\n * So this is served beside the control: the stored preference, and — per environment, from the\n * SAME `evaluatePolicy` call a run makes and the SAME sentence the plan preview renders — what\n * a run will actually get. Not a second implementation of the rule, and not a guess.\n */\nexport interface AdoptionApprovalOutcomeDto {\n adoptionId: string;\n /** The stored preference: true (always require), false (do not), null (inherit policy). */\n requiresApproval: boolean | null;\n /**\n * One entry per environment, because a policy may match on environment — so \"does this need\n * approval\" has no single answer, and collapsing it into one would be the same kind of\n * confident half-truth the control already told.\n */\n environments: AdoptionApprovalEnvironmentOutcome[];\n}\n\nexport interface AdoptionApprovalEnvironmentOutcome {\n environment: Environment;\n /** What a run in this environment gets, with the stored preference applied. */\n effective: ExecutionPlanGovernance;\n /**\n * True when POLICY ALONE requires approval here — evaluated with the adoption override\n * removed. This is the fact the interface was missing: it is what makes a stored\n * \"Not required\" inert, and it is why the preference is still worth storing (policy can\n * relax later, and the preference has to survive that).\n */\n policyMandatesApproval: boolean;\n}\n\n/**\n * ─── THE SUPPLY-CHAIN REVIEW (docs/31 §10.4, charter §4.9) ────────────────────────────\n *\n * Adopting or upgrading third-party code is the moment a workspace inherits someone else's\n * risk. These vocabularies are how that risk is named.\n */\n\n/**\n * How dangerous a single change is. Declared MOST severe first, because this array IS the\n * display order everywhere the changes are grouped — one ordering, not one per surface.\n */\nexport const ADOPTION_CHANGE_SEVERITIES = [\n /** The action can now do something it could not before. */\n \"privilege_increase\",\n /** No new power, but a guarantee that existed is gone. */\n \"safety_reduction\",\n /** Expected on any real upgrade, and still shown. */\n \"code_changed\",\n /** Good news — stated so a careful upgrade reads as careful. */\n \"privilege_decrease\",\n /** Everything else that differs. */\n \"metadata\",\n] as const;\nexport type AdoptionChangeSeverity = (typeof ADOPTION_CHANGE_SEVERITIES)[number];\n\n/** Every difference this review can name. Grouped by the severity each one carries. */\nexport const ADOPTION_CHANGE_KINDS = [\n // ── privilege_increase ───────────────────────────────────────────────────────────────\n \"permission_added\",\n \"permission_scope_widened\",\n \"egress_host_added\",\n \"network_enabled\",\n \"secret_added\",\n \"credential_scope_added\",\n \"version_contract_violation\",\n // ── safety_reduction ─────────────────────────────────────────────────────────────────\n \"rollback_removed\",\n \"dry_run_removed\",\n \"idempotency_removed\",\n \"validate_entrypoint_removed\",\n \"timeout_increased\",\n // ── code_changed ─────────────────────────────────────────────────────────────────────\n \"content_digest_changed\",\n \"runtime_kind_changed\",\n \"runtime_image_changed\",\n \"runtime_interpreter_changed\",\n \"entrypoint_changed\",\n \"rollback_entrypoint_changed\",\n \"validate_entrypoint_changed\",\n // ── privilege_decrease ───────────────────────────────────────────────────────────────\n \"permission_removed\",\n \"permission_scope_narrowed\",\n \"egress_host_removed\",\n \"network_disabled\",\n \"secret_removed\",\n \"credential_scope_removed\",\n \"timeout_decreased\",\n // ── metadata ─────────────────────────────────────────────────────────────────────────\n \"capability_added\",\n \"source_repo_changed\",\n \"git_commit_changed\",\n \"tier_changed\",\n] as const;\nexport type AdoptionChangeKind = (typeof ADOPTION_CHANGE_KINDS)[number];\n\n/**\n * How dangerous each kind is — THE product decision this whole feature exists to encode.\n *\n * Keyed by the kind union (charter §4.2 R2), so adding a kind is a COMPILE ERROR until\n * somebody decides how dangerous it is. A severity that could be passed in by a caller, or\n * defaulted, is a severity nobody chose.\n */\nexport const ADOPTION_CHANGE_SEVERITY: Record<\n AdoptionChangeKind,\n AdoptionChangeSeverity\n> = {\n permission_added: \"privilege_increase\",\n permission_scope_widened: \"privilege_increase\",\n egress_host_added: \"privilege_increase\",\n network_enabled: \"privilege_increase\",\n secret_added: \"privilege_increase\",\n credential_scope_added: \"privilege_increase\",\n version_contract_violation: \"privilege_increase\",\n\n rollback_removed: \"safety_reduction\",\n dry_run_removed: \"safety_reduction\",\n idempotency_removed: \"safety_reduction\",\n validate_entrypoint_removed: \"safety_reduction\",\n timeout_increased: \"safety_reduction\",\n\n content_digest_changed: \"code_changed\",\n runtime_kind_changed: \"code_changed\",\n runtime_image_changed: \"code_changed\",\n runtime_interpreter_changed: \"code_changed\",\n entrypoint_changed: \"code_changed\",\n rollback_entrypoint_changed: \"code_changed\",\n validate_entrypoint_changed: \"code_changed\",\n\n permission_removed: \"privilege_decrease\",\n permission_scope_narrowed: \"privilege_decrease\",\n egress_host_removed: \"privilege_decrease\",\n network_disabled: \"privilege_decrease\",\n secret_removed: \"privilege_decrease\",\n credential_scope_removed: \"privilege_decrease\",\n timeout_decreased: \"privilege_decrease\",\n\n capability_added: \"metadata\",\n // NOT metadata, deliberately. A package that keeps its id while its ORIGIN repository\n // changes is the supply-chain SUBSTITUTION shape: the name stayed, the source moved. A\n // benign repo move (an org rename, a transfer) looks identical to a hostile one from here,\n // so it belongs in a group the reader actually reads rather than in \"everything else\".\n // NOT privilege_increase either: no new power is granted, and firing the strongest signal\n // on a routine org rename is how a reader learns to ignore the strongest signal.\n source_repo_changed: \"code_changed\",\n git_commit_changed: \"metadata\",\n tier_changed: \"metadata\",\n};\n\n/**\n * Which way the adoption is moving. A downgrade is legitimate — undoing a bad upgrade is\n * the right move — but it can silently reintroduce something the newer version fixed, so it\n * is NAMED rather than presented as a neutral switch.\n */\nexport const ADOPTION_REVIEW_DIRECTIONS = [\"upgrade\", \"downgrade\", \"same\"] as const;\nexport type AdoptionReviewDirection = (typeof ADOPTION_REVIEW_DIRECTIONS)[number];\n\n/** The provider-native permission a permission change is about. */\nexport interface AdoptionPermissionChangeDto {\n provider: Provider;\n actions: string[];\n scope: string;\n /** Present only on a widening or narrowing: the scope the same action held before. */\n previousScope?: string;\n}\n\n/**\n * One difference, as DATA. The server owns WHAT changed; the UI owns how it is worded —\n * a pre-formatted sentence here would put product copy in the API and make it unrenderable\n * in any other surface.\n */\nexport interface AdoptionChangeDto {\n kind: AdoptionChangeKind;\n /** Always read from {@link ADOPTION_CHANGE_SEVERITY}; never supplied by a caller. */\n severity: AdoptionChangeSeverity;\n /** The single thing the change is about, when it has one: a host, a secret name, a capability. */\n subject?: string;\n /** The value before. Absent on a pure addition. */\n from?: string;\n /** The value after. Absent on a pure removal. */\n to?: string;\n /** Permission changes only. */\n permission?: AdoptionPermissionChangeDto;\n /** Timeout changes only — both durations already parsed, so no reader re-parses \"90s\". */\n durationMs?: { from: number; to: number };\n}\n\n/** The identity of one side of the review. */\nexport interface AdoptionReviewVersionDto {\n packageVersionId: string;\n packageId: string;\n semanticVersion: string;\n sourceRepo: string;\n gitCommitSha: string;\n contentDigest: string;\n tier: PackageTier;\n}\n\n/**\n * What a FIRST adoption is being asked to trust: the full declared surface, not a diff.\n * The first adopt is the moment risk is inherited, so it gets a review too (docs/31 C4).\n */\nexport interface AdoptionDisclosureDto {\n permissions: PackageRequiredPermission[];\n egressAllowlist: string[];\n secretNames: string[];\n credentialScopes: string[];\n requiresNetwork: boolean;\n capabilities: PackageCapabilities;\n runtime: PackageRuntime;\n executionTimeout: string;\n /**\n * What this deployment would actually DO with the allowlist above (slice 6b-II). Declaring\n * the hosts and not the mode is what let an allowlist read as a boundary on a substrate that\n * only configures it; the two are disclosed together or the disclosure is not honest.\n *\n * Null when the deployment cannot answer — an unreadable runtime declaration, or a package\n * no configured adapter would run. A missing answer is shown as missing, never as `denied`.\n */\n egress: EgressDisclosureDto | null;\n}\n\nexport interface AdoptionReviewDto {\n /**\n * Meaningful only when {@link from} is set. A FIRST adoption has no previous version to\n * move from, so this reads `upgrade` and the surface discriminates on `from === null`\n * instead — never on this field.\n */\n direction: AdoptionReviewDirection;\n /** null for a first adoption — there is nothing to diff against. */\n from: AdoptionReviewVersionDto | null;\n to: AdoptionReviewVersionDto;\n /** Empty for a first adoption, which discloses instead of diffing. */\n changes: AdoptionChangeDto[];\n /** Present ONLY for a first adoption. */\n disclosure?: AdoptionDisclosureDto;\n counts: Record<AdoptionChangeSeverity, number>;\n /**\n * Human-readable names of the fields compared and found identical. Absence of change is\n * information, and hiding it makes a careful reader wonder what was not checked.\n */\n unchanged: string[];\n /**\n * True when anything here is a `privilege_increase`. ONE boolean, so \"is this dangerous\"\n * is answered in one place and the UI, the button label and the audit row cannot disagree.\n */\n requiresElevatedTrust: boolean;\n /**\n * sha256 of the canonicalized review, excluding this field. What the caller echoes back on\n * accept, and what the server recomputes rather than trusts.\n */\n reviewDigest: string;\n}\n\n/** Tenant-owned Git source metadata. Installation credentials are never persisted. */\nexport interface PackageSourceDto {\n id: string;\n kind: PackageSourceKind;\n account: string;\n baseUrl: string | null;\n appSlug: string | null;\n installationId: string | null;\n selectedRepos: string[];\n status: PackageSourceStatus;\n createdBy: string;\n createdAt: string;\n}\n\n/** Starts either the github.com or GHES App installation flow. */\nexport interface CreateGitSourceInput {\n kind: \"github_app\" | \"github_enterprise\";\n baseUrl?: string;\n appSlug?: string;\n /** Present only when the existing installation flow is reconnecting a known source. */\n sourceId?: string;\n}\n\n/**\n * One authoritative explanation for the ONE refusal source removal still has.\n *\n * Imported versions no longer block removal, and that is a correction rather than a relaxation:\n * a version's provenance lives in its own NOT NULL `sourceRepo` / `gitCommitSha` /\n * `contentDigest` / `manifestHash` columns, which survive the connection. `sourceId` records\n * only WHICH connection Opera fetched through, and nulling it fails CLOSED — organization-tier\n * sandbox credentials require a non-null id AND a live source, so removal can never escalate.\n */\nexport function packageSourceConnectedRemovalMessage(): string {\n return (\n \"This source is still connected, so removing it would silently drop a live GitHub App \" +\n \"installation. Disconnect it first, then remove it.\"\n );\n}\n\nexport interface GitInstallUrlDto {\n url: string;\n state: string;\n}\n\n/**\n * What a reconnect actually DID (docs/27 §4). Two outcomes, because the common one needs no\n * GitHub round-trip at all: Opera's Disconnect only marks the row, so the installation is\n * normally still live and re-minting a token for the stored `installationId` proves it. The\n * install URL is offered ONLY when GitHub definitively says the installation is gone — a\n * transient failure is an error, never a trip to reinstall something that was never broken.\n */\nexport const PACKAGE_SOURCE_RECONNECT_OUTCOMES = [\"reconnected\", \"reinstall_required\"] as const;\nexport type PackageSourceReconnectOutcome =\n (typeof PACKAGE_SOURCE_RECONNECT_OUTCOMES)[number];\n\nexport type PackageSourceReconnectDto =\n /** The stored installation is alive: repositories re-read, selection intersected, no redirect. */\n | { outcome: \"reconnected\"; source: PackageSourceDto }\n /** The installation is genuinely gone. The admin must install the App again. */\n | { outcome: \"reinstall_required\"; url: string; state: string };\n\nexport interface GitInstallCallbackInput {\n installationId: string;\n state: string;\n setupAction?: string;\n}\n\nexport interface GitSourceRepoDto {\n fullName: string;\n name: string;\n owner: string;\n private: boolean;\n selected: boolean;\n}\n\nexport interface SelectGitSourceReposInput {\n repositories: string[];\n}\n\n/** One stable, client-renderable manifest/package validation problem. */\nexport interface ManifestValidationError {\n path: string;\n message: string;\n keyword?: string;\n}\n\n/**\n * One non-fatal import advisory (docs/29 D3) — same shape as\n * `ManifestValidationError`, but the import still succeeds. Never persisted;\n * recomputed on every (re-)import (docs/29 D4).\n */\nexport interface ManifestValidationWarning {\n path: string;\n message: string;\n keyword?: string;\n}\n\n/** Compact row used by Settings -> Packages. */\nexport interface PackageDto {\n id: string;\n packageId: string;\n semanticVersion: string;\n sourceRepo: string;\n gitCommitSha: string;\n actionVersionId: string;\n sourceId: string | null;\n tier: PackageTier;\n /** How these bytes got here. See {@link PACKAGE_PROVENANCE_KINDS}. */\n provenance: PackageProvenanceKind;\n /** The Opera user who wrote it. Non-null exactly for `authored` provenance. */\n authoredBy: string | null;\n /**\n * How many times the action version this package projected has run. NOT a guard — run\n * history no longer refuses removal — but the number an admin needs to be told before\n * removing a version that has been used, together with what happens to those runs.\n */\n executionCount: number;\n importedAt: string;\n}\n\n/**\n * ─── REMOVING AN IMPORTED PACKAGE VERSION (docs/27 §5) ────────────────────────────────\n *\n * A release has ONE refusal, and it is one the admin can act on: a live adoption means the\n * Catalog is serving this version, so decommission it first. A trial never reaches release\n * removal: its immutable row is retained as execution evidence.\n *\n * Run history does NOT refuse a release. A release that has executed is removable, because the run\n * record is self-contained: the evidence manifest carries the action key, the semantic\n * version, the content digest and the commit — and packages are immutable after publication\n * (charter §4.8), so that tuple identifies the code that ran without the row. Keeping a table\n * immortal was never the guarantee; writing the field is.\n *\n * Built here so the API refusal and the disabled web action say the same words.\n */\nexport function packageVersionAdoptedRemovalMessage(adoption: {\n id: string;\n status: AdoptionStatus;\n}): string {\n return (\n `This version cannot be removed while an action still adopts it: adoption ${adoption.id} ` +\n `is ${adoption.status}. Decommission that adoption first — then this version can be removed.`\n );\n}\n\n/**\n * The package identity an evidence manifest records for a package-backed run: WHICH bytes\n * ran, not merely which action. Absent for a built-in connector, which has no package.\n */\nexport interface PackageIdentityDto {\n packageId: string;\n semanticVersion: string;\n contentDigest: string;\n gitCommitSha: string;\n}\n\n/** Full immutable package-version metadata returned by import/detail. */\nexport interface PackageVersionDto extends PackageDto {\n contentDigest: string;\n manifestHash: string;\n runtime: PackageRuntime;\n executionTimeout: string;\n entrypoint: string;\n rollbackEntrypoint: string | null;\n validateEntrypoint: string | null;\n manifestCapabilities: PackageCapabilities;\n manifestRequiredPermissions: PackageRequiredPermission[];\n requiresNetwork: boolean;\n egressAllowlist: string[];\n secretNames: string[];\n credentialScopes: string[];\n importedBy: string;\n}\n\n/**\n * Import response (docs/29 D4): the immutable version plus this import's advisories.\n * Warnings are not stored — an idempotent re-import recomputes and returns them again.\n */\nexport interface PackageImportResultDto extends PackageVersionDto {\n warnings: ManifestValidationWarning[];\n}\n\n/**\n * WHY an adopted action cannot run on this deployment — the closed vocabulary shared by the\n * catalog and the run path (docs/31 §10.2, extended).\n *\n * Runnability has TWO axes and the catalog originally asked about only one. `runtime_kind` and\n * `runtime_unavailable` are the runtime axis: the first means no adapter executes this KIND of\n * declaration, the second that the adapter which would execute it has no substrate to execute\n * it ON. They are separate members because they are fixed by different people: the first by\n * whoever publishes the package, the second by whoever operates the deployment. The other three\n * are the trust axis, which refuses on facts about where the code came from.\n *\n * `source_disconnected` and `source_removed` are deliberately separate members rather than one\n * \"source problem\": the first is undone by the Reconnect button in Settings → Packages, the\n * second needs a fresh import through a live connection. Collapsing them would hide the\n * difference between \"press this\" and \"start over\", which is the only thing the reader needs.\n *\n * `interpreter_unavailable` is the runtime axis one level finer than `runtime_kind`: the\n * declaration IS an interpreter, which some adapter here executes, but the specific interpreter\n * it names is one no adapter on this deployment ships. It carries the interpreters that ARE\n * available, because the reader's next question is always \"then what can I use\".\n *\n * `egress_unconfigurable` is the runtime axis again, one level finer (slice 6b-II): the\n * substrate is there and the package is trusted, but the package declares outbound network and\n * this deployment has nothing to broker it with. It is a separate member from\n * `runtime_unavailable` because the fix is different — a proxy image and port, not a runner —\n * and because it refuses only the packages that ask for network, while `runtime_unavailable`\n * refuses every package routed to that isolation.\n *\n * Severity is NOT a member of this vocabulary and never becomes one: every reason here means\n * the same thing to the engine — this action cannot run.\n */\nexport const ACTION_UNRUNNABLE_REASONS = [\n \"runtime_kind\",\n \"interpreter_unavailable\",\n \"runtime_unavailable\",\n \"egress_unconfigurable\",\n \"source_disconnected\",\n \"source_removed\",\n \"not_trusted\",\n] as const;\nexport type ActionUnrunnableReason = (typeof ACTION_UNRUNNABLE_REASONS)[number];\n\n/**\n * One reason plus exactly the detail that makes it actionable: the runtime kind for\n * `runtime_kind`, the Git account for the two source reasons. Anything more would be detail\n * the reader cannot act on, and anything less puts a reason on screen nobody can chase.\n */\nexport type ActionUnrunnableDetailDto =\n | { reason: \"runtime_kind\"; runtimeKind: PackageRuntimeKind }\n /**\n * `interpreter` is a plain string, not {@link PackageInterpreter}: the name is refused at\n * import now, but a version pinned BEFORE the vocabulary existed can carry anything, and\n * this reason is exactly how such a row explains itself instead of crashing an adapter.\n *\n * `available` is the interpreters this deployment does ship — the one fact that turns \"no\"\n * into a next step.\n */\n | { reason: \"interpreter_unavailable\"; interpreter: string; available: string[] }\n /**\n * `isolation` is the API's own deployment vocabulary (`SandboxIsolation`), not one of\n * this package's — contracts is a leaf and must not learn the runtime's internals — so it\n * crosses as a plain string. It is carried because this reason is fundamentally an\n * OPERATOR's to fix, and which substrate is missing is the only fact that shortens that fix.\n */\n | { reason: \"runtime_unavailable\"; isolation: string }\n /**\n * `isolation` for the same reason as above — it is the operator's fix, and which substrate\n * cannot broker egress is the fact that shortens it.\n */\n | { reason: \"egress_unconfigurable\"; isolation: string }\n | { reason: \"source_disconnected\"; sourceAccount: string }\n | { reason: \"source_removed\"; sourceAccount: string }\n | { reason: \"not_trusted\" };\n\n/** How each runtime kind reads in a sentence a user has to act on. */\nconst RUNTIME_KIND_NAMES: Record<PackageRuntimeKind, string> = {\n interpreter: \"interpreter\",\n oci: \"OCI image\",\n};\n\n/** \"an OCI image\" / \"an interpreter\" — the article the copy needs, without a template lie. */\nfunction anArticle(noun: string): string {\n return `${/^[aeiou]/i.test(noun) ? \"an\" : \"a\"} ${noun}`;\n}\n\n/**\n * \"This deployment runs powershell, bash and python. A package has to be published for one of\n * those, or …\" — written once, because the EMPTY case is a real one (a deployment with no\n * working runner at all) and \"This deployment runs . A package has to be published for one of\n * those\" is the kind of sentence that ships when three surfaces each build it themselves.\n */\nfunction supportedInterpreterRemedy(available: readonly string[]): string {\n const deploy =\n \"an administrator has to deploy a runner that provides the one this package needs.\";\n if (available.length === 0) {\n return `This deployment runs no package interpreter at all, so ${deploy}`;\n }\n const list =\n available.length === 1\n ? available[0]!\n : `${available.slice(0, -1).join(\", \")} and ${available[available.length - 1]!}`;\n return (\n `This deployment runs ${list}. A package has to be published for one of those, or ${deploy}`\n );\n}\n\n/**\n * THE sentence for each reason, written once. `cause` is a PREDICATE — its subject is supplied\n * by the surface (\"This action's package …\" in the catalog, \"Package x from y …\" in the run\n * refusal) — so the identical clause names the cause in both places and they cannot drift into\n * describing different problems. That drift is precisely the defect this vocabulary closes: the\n * catalog said \"Available\" while the run path said \"not allowlisted\", and neither named the\n * disconnected Git source that was actually at fault.\n */\nfunction unrunnableClauses(detail: ActionUnrunnableDetailDto): { cause: string; remedy: string } {\n switch (detail.reason) {\n case \"runtime_kind\":\n return {\n cause: `runs as ${anArticle(RUNTIME_KIND_NAMES[detail.runtimeKind])}, which ${BRAND_SHORT_NAME} cannot execute yet.`,\n remedy:\n \"Nothing is wrong with your setup — the package has to be published for a runtime \" +\n \"this deployment supports.\",\n };\n case \"interpreter_unavailable\":\n return {\n cause: `is written for ${detail.interpreter}, which no runner on this deployment executes.`,\n remedy: supportedInterpreterRemedy(detail.available),\n };\n case \"runtime_unavailable\":\n return {\n cause:\n `has to run under the \"${detail.isolation}\" isolation, and this deployment provides ` +\n \"no runner for it.\",\n remedy:\n \"Nothing about the package or its Git source needs to change — an administrator has \" +\n \"to configure that runner before any package routed to it can run.\",\n };\n case \"egress_unconfigurable\":\n return {\n cause:\n \"declares outbound network access, and this deployment has no way to broker it \" +\n `under the \"${detail.isolation}\" isolation.`,\n remedy:\n \"A package that declares network is never run without its allowlist in force, so an \" +\n \"administrator has to configure the egress proxy for that runner first.\",\n };\n case \"source_disconnected\":\n return {\n cause:\n `came from the Git source ${detail.sourceAccount}, which is disconnected, so ${BRAND_SHORT_NAME} ` +\n \"can no longer vouch for where its code came from.\",\n remedy: \"Reconnecting that source is all it takes — nothing has to be re-imported.\",\n };\n case \"source_removed\":\n return {\n cause:\n `came from the Git source ${detail.sourceAccount}, and that connection has been ` +\n `removed, so ${BRAND_SHORT_NAME} can no longer vouch for where its code came from.`,\n remedy: \"Re-import the package through a live Git source to run it again.\",\n };\n case \"not_trusted\":\n return {\n cause:\n \"is not allowlisted for trusted execution, and this deployment does not run \" +\n \"untrusted packages.\",\n remedy: \"Ask an administrator to allowlist this package for trusted execution.\",\n };\n }\n}\n\n/** The catalog's copy for one unrunnable action. */\nexport function actionUnrunnableCopy(detail: ActionUnrunnableDetailDto): string {\n const { cause, remedy } = unrunnableClauses(detail);\n return `This action's package ${cause} ${remedy}`;\n}\n\n/**\n * The cause as a HEADLINE — one clause carrying the fact that makes it actionable, for a\n * surface that gets a title and nothing else.\n *\n * It exists because the Operation verification check's TITLE is what becomes the\n * `verification_failed` notification, and a notification reading \"this deployment cannot run\n * its action's package\" tells the owner of a broken Operation nothing they can act on. The\n * detail line is not read by whoever gets the email.\n *\n * A third length, not a third vocabulary: same closed union, same exhaustive switch, same\n * file, so a reason cannot be worded here in a way that contradicts {@link actionUnrunnableCopy}\n * without both being in front of the same reader.\n */\nexport function actionUnrunnableHeadline(detail: ActionUnrunnableDetailDto): string {\n switch (detail.reason) {\n case \"runtime_kind\":\n return `its package runs as ${anArticle(RUNTIME_KIND_NAMES[detail.runtimeKind])}, which ${BRAND_SHORT_NAME} cannot execute`;\n case \"interpreter_unavailable\":\n return `its package is written for ${detail.interpreter}, which no runner here executes`;\n case \"runtime_unavailable\":\n return `this deployment provides no \"${detail.isolation}\" runner for its package`;\n case \"egress_unconfigurable\":\n return `its package needs outbound network and the \"${detail.isolation}\" runner here has no egress proxy`;\n case \"source_disconnected\":\n return `its package's Git source ${detail.sourceAccount} is disconnected`;\n case \"source_removed\":\n return `its package's Git source ${detail.sourceAccount} has been removed`;\n case \"not_trusted\":\n return \"its package is not allowlisted for trusted execution\";\n }\n}\n\n/**\n * The run path's refusal for the same reason — same cause clause, plus the package identity an\n * API caller or a mid-run Operation needs to find it, and the \"nothing was started\" guarantee.\n */\nexport function actionUnrunnableRefusal(\n detail: ActionUnrunnableDetailDto,\n pkg: { packageId: string; sourceRepo: string },\n): string {\n const { cause, remedy } = unrunnableClauses(detail);\n return `Package ${pkg.packageId} from ${pkg.sourceRepo} ${cause} ${remedy} Nothing was started.`;\n}\n\n/**\n * One adopted action this deployment cannot run, and why (docs/31 §10.2). Read by the catalog\n * so an action nobody can run says so before someone configures a run, rather than failing at\n * the adapter — and now says which of the two axes refused it.\n */\nexport interface UnsupportedActionRuntimeDto {\n actionDefinitionId: string;\n reason: ActionUnrunnableDetailDto;\n}\n\n/**\n * The same refusal for ONE action version, plus the package identity {@link actionUnrunnableRefusal}\n * needs to name it. This is what Packages hands to Execution so the enqueue gate can refuse with\n * the cause instead of a generic \"not yet available\" — the run path is the surface where the\n * reader is furthest from a screen that could explain itself.\n */\nexport interface ActionPackageUnrunnableDto {\n detail: ActionUnrunnableDetailDto;\n packageId: string;\n sourceRepo: string;\n}\n\nexport interface PackageRuntimeSupportDto {\n unsupported: UnsupportedActionRuntimeDto[];\n}\n\n/**\n * ═══ WHAT A VERSION IS BEING MINTED FOR ════════════════════════════════════════════════\n *\n * A `release` is the thing an author commits to: it takes the manifest's own version, its\n * definition is offered in the catalog, and it is what an adoption can pin.\n *\n * A `trial` is the same immutable version, minted so the author can RUN their draft before\n * committing to it. It is identified by its CONTENT DIGEST rather than by a semantic version\n * (see {@link trialSemanticVersion}), its definition is born `draft` lifecycle — which every\n * catalog listing already excludes — and nothing can adopt it.\n *\n * The mode controls EXACTLY FIVE things and nothing else: the version string, the lifecycle a\n * NEWLY CREATED definition gets, `action_version.status`, whether `latest_version_id` is\n * recomputed, and whether an EXISTING definition's columns are updated. Validation, the trust\n * decision, the capability gates, the artifact cache, the fidelity assertion, the egress rules\n * and the audit event are identical in both modes — deliberately, and it is the whole point of\n * the trial run: a trial that got a different decision anywhere in there would be testing\n * something other than what publishing will produce.\n */\nexport const PACKAGE_VERSION_MODES = [\"trial\", \"release\"] as const;\nexport type PackageVersionMode = (typeof PACKAGE_VERSION_MODES)[number];\n\n/** How much of the digest a trial version carries. Long enough to never collide in practice. */\nconst TRIAL_DIGEST_LENGTH = 12;\n\n/**\n * THE VERSION STRING OF A TRIAL — semver build metadata over the manifest's own version.\n *\n * This is what lets an author iterate without touching a version number. Editing the draft\n * changes the bytes, which changes the digest, which makes a DIFFERENT immutable version — so\n * \"a published version is immutable\" (charter §4.8) is never bent. Re-running UNCHANGED bytes\n * produces the same string, resolves to the version that already exists, and costs nothing.\n *\n * Build metadata is also why a trial can never collide with a release: publishing mints\n * `manifest.version` bare, and this always appends. Note that build metadata is NOT orderable —\n * `compareSemanticVersions` rightly refuses it — which is exactly why only `published` versions\n * are candidates for a definition's latest pin. See catalog.repository.ts.\n */\nexport function trialSemanticVersion(manifestVersion: string, contentDigest: string): string {\n return `${manifestVersion}+trial.${contentDigest.slice(0, TRIAL_DIGEST_LENGTH)}`;\n}\n\n/** Catalog-owned projection input passed across the public facade boundary. */\nexport interface ProjectPackageInput {\n key: string;\n name: string;\n summary: string;\n description: string;\n provider: Provider;\n category: ActionCategory;\n connectorKey: string;\n riskLevel: RiskLevel;\n capabilities: ActionCapabilities;\n maintainer: string;\n version: string;\n parameterSchema: ParameterSchema;\n requiredPermissions: RequiredPermission[];\n tier: PackageTier;\n sourceKind: PackageProjectionSourceKind;\n /** What this version is for. See {@link PACKAGE_VERSION_MODES} for what it controls. */\n mode: PackageVersionMode;\n}\n\nexport interface ProjectPackageResult {\n actionDefinitionId: string;\n actionVersionId: string;\n}\n\n/**\n * ═══ AUTHORING IN OPERA — THE DRAFT AND ITS LIFECYCLE ═══════════════════════════════════\n *\n * The CLI serves teams that already have Git. This serves the person evaluating Opera who is\n * not going to install a GitHub App to find out whether it works.\n *\n * THE STATES, AND EVERY TRANSITION INCLUDING THE ENDINGS:\n *\n * draft created by paste or from a template. EDITABLE. Not runnable, not\n * adoptable, not in the catalog. Visible only to `package:manage`.\n * → published publish (creates an immutable version)\n * → discarded discard (HARD delete; it never entered the audit story)\n * published an immutable package version, indistinguishable downstream from a\n * Git-imported one. Editing it is impossible by construction — publishing\n * again from the same draft creates a NEW version and leaves this one\n * byte-identical.\n * → adopted the existing adoption flow, with no special case\n * → superseded a newer version of the same package id exists\n * → removed the existing package-version removal path\n * adopted / decommissioned / removed\n * entirely unchanged. An authored version travels the same paths as any\n * other, which is the point of giving it a provenance rather than a\n * separate lifecycle.\n *\n * A state a user can enter and not leave is the defect this project has shipped twice before,\n * so every transition above is reachable from the UI and every one writes an audit event\n * naming the actor.\n */\nexport const PACKAGE_DRAFT_STATES = [\"draft\", \"published\", \"superseded\"] as const;\nexport type PackageDraftState = (typeof PACKAGE_DRAFT_STATES)[number];\n\n/** One file of a draft or an authored publish: a package-relative path and its UTF-8 text. */\nexport interface AuthoredPackageFileDto {\n path: string;\n contents: string;\n}\n\nexport interface PackageDraftDto {\n id: string;\n packageId: string;\n name: string;\n interpreter: PackageInterpreter;\n /**\n * DERIVED, never stored: `draft` until it has published anything, `published` once it has,\n * and `superseded` when a NEWER version of the same package id exists than the one this\n * draft produced. Storing it would create a second answer to a question the version rows\n * already answer, and the two would drift the first time a version was removed.\n */\n state: PackageDraftState;\n /**\n * WHETHER THE DRAFT HAS MOVED SINCE IT PUBLISHED — a fact ORTHOGONAL to `state`, which is\n * why it is a separate field rather than a fourth member of that enum.\n *\n * A draft can be superseded AND edited since at the same time. Collapsing the two into one\n * enum forces a choice between two true statements, and the row goes back to saying one of\n * them and meaning the other — which is the defect this field exists to end: a list that\n * read \"Published 0.1.0 — an immutable version exists\" about bytes that were no longer in\n * the draft, leaving the author unable to tell whether their edit had been kept.\n *\n * `false` when nothing has been published: there is no version to diverge FROM, and calling\n * an unpublished draft \"changed\" would be measuring it against nothing.\n *\n * Decided by CONTENT DIGEST, never by a timestamp — `updatedAt` moves for a no-op save — and\n * never by diffing file lists. See `canonicalContentDigest`: publishing hashes the draft's\n * bytes with it, so comparing the two digests is one function's answer to one question, and\n * editing a draft back to the bytes it published reports `false` again.\n */\n hasUnpublishedChanges: boolean;\n /** The version this draft published, when it has published one. */\n publishedVersionId: string | null;\n publishedSemanticVersion: string | null;\n /**\n * The adoption state of the published version — `null` when nothing has adopted it.\n *\n * PUBLISHING IS NOT ADOPTING, and that separation is deliberate: an immutable version exists,\n * and somebody still has to choose to put it in the catalog. But an author looking at\n * \"Published\" had no way to tell whether that choice had been made, and no route to making\n * it — the banner said \"adopt it in Settings → Packages\" as plain text. This is what turns\n * the state into a next step instead of a dead end.\n */\n publishedAdoptionStatus: AdoptionStatus | null;\n /** Present only when `state` is `superseded` — what supersedes it, so the UI can link. */\n supersededByVersionId: string | null;\n supersededBySemanticVersion: string | null;\n createdBy: string;\n updatedBy: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * ═══ WHERE THIS PACKAGE'S PARAMETERS LIVE ══════════════════════════════════════════════\n *\n * `action.yaml`'s `parametersRef` is the ONE answer to \"which file holds the parameters\", and\n * the server resolves it with the same validator that publishes. It travels on the DTO so the\n * browser can render the Parameters tab without learning to parse a manifest — `apps/web` does\n * not depend on `@runveric/action-manifest` and must not start.\n *\n * THE EDITOR USED TO HARDCODE `parameters.json`. That agreed with the manifest for exactly as\n * long as every package was scaffolded, and an imported package declaring\n * `parametersRef: parameters.schema.json` met an editor that showed \"No parameters yet\" and then\n * silently DISCARDED every parameter added to it — its write replaced only the file whose path\n * matched, and nothing matched.\n */\n\n/**\n * Why a package's parameters file could not be located. Array-first (charter §4.2).\n *\n * ALL FOUR ARE REACHABLE MID-EDIT, which is why each is named rather than collapsed into one\n * \"cannot read the manifest\". The Parameters tab says which is true and what to fix, and a\n * silent fallback to `parameters.json` is forbidden — that fallback is how one file became two\n * answers in the first place.\n */\nexport const PACKAGE_PARAMETERS_UNRESOLVED_REASONS = [\n \"manifest_missing\",\n \"manifest_unparseable\",\n \"parameters_ref_missing\",\n \"parameters_ref_unsafe\",\n] as const;\nexport type PackageParametersUnresolvedReason =\n (typeof PACKAGE_PARAMETERS_UNRESOLVED_REASONS)[number];\n\n/** What the author is told, and what to do about it. Declared once so no surface rewords it. */\nexport const PACKAGE_PARAMETERS_UNRESOLVED_COPY: Record<\n PackageParametersUnresolvedReason,\n { headline: string; fix: string }\n> = {\n manifest_missing: {\n headline: \"This package has no action.yaml.\",\n fix: \"Every package needs one — it is the file that declares which file holds the parameters. Add it in the Files tab.\",\n },\n manifest_unparseable: {\n headline: \"action.yaml cannot be read.\",\n fix: \"It is not valid YAML, so nothing can tell which file holds the parameters. Fix it in the Files tab and this returns.\",\n },\n parameters_ref_missing: {\n headline: \"action.yaml does not declare parametersRef.\",\n fix: \"Add `parametersRef: parameters.json` — the path, relative to the package root, of the file that holds the parameters.\",\n },\n parameters_ref_unsafe: {\n headline: \"action.yaml's parametersRef is not a safe package path.\",\n fix: \"It must be relative to the package root, use forward slashes, and contain no `.` or `..` segments.\",\n },\n};\n\n/**\n * A DISCRIMINATED location, so a resolved one carries its path and an unresolved one carries its\n * reason. The alternative — `path: string | null` beside `reason: Reason | null` — is two\n * nullable fields with an invariant nobody enforces, and it cannot express §6's requirement that\n * the tab name WHICH state is true.\n */\nexport type ParametersFileLocationDto =\n | { resolved: true; path: string }\n | { resolved: false; reason: PackageParametersUnresolvedReason };\n\n/** A draft with its files. The list view deliberately does not carry these. */\nexport interface PackageDraftDetailDto extends PackageDraftDto {\n files: AuthoredPackageFileDto[];\n /**\n * The file this draft's own `action.yaml` names in `parametersRef`, resolved by the server.\n *\n * The editor reads AND writes through this and has no filename of its own. It is re-resolved\n * on every response — including the autosave's — because an author may edit `parametersRef` in\n * the Files tab, and a path cached for the life of the page would point at the old file.\n */\n parametersFile: ParametersFileLocationDto;\n /**\n * THE FILE THIS PACKAGE ACTUALLY RUNS — `run/body.ps1` for a scaffolded or pasted draft, the\n * author's own path for an imported one.\n *\n * DERIVED, not stored: `run/main.*` — Opera's wrapper — is the one place that says which file\n * it starts, and it is read back through the same module that writes it. A column would be a\n * second answer that goes stale the moment somebody edits the wrapper, and the wrapper is the\n * thing the runner obeys.\n *\n * NULL when the wrapper's declaration cannot be read, which is what an edited wrapper looks\n * like. Re-detection REFUSES rather than guessing then: reading a `param()` block from a file\n * the runner will not bind is the same silent-discard shape this slice exists to remove.\n */\n entrypoint: string | null;\n}\n\n/**\n * ═══ READING THE PARAMETERS A SCRIPT ALREADY DECLARES (docs/32 S5–S9) ══════════════════\n *\n * A PowerShell `param()` block IS a formal parameter declaration. Opera reads it with\n * PowerShell's own parser and PROPOSES a run form; the author accepts, edits or rejects it\n * (D5). Nothing here is persisted — a proposal is recomputed on demand, never stored.\n *\n * ─── WHY THE VOCABULARY HAS TWO MEMBERS AND NOT THREE ───────────────────────────────────\n *\n * docs/32 §5 sketched `python_argparse` alongside these. It is deliberately ABSENT: the API\n * image ships PowerShell 7.4 and `python3` is deliberately absent from the runtime stage\n * (docs/32 §9 is still open), so nothing in this deployment can produce that value. A member no\n * code can emit is a contract that lies about what the product does; Slice D adds it when it\n * adds the parser that answers for it.\n */\nexport const PARAMETER_DETECTION_SOURCES = [\"powershell_param\", \"none\"] as const;\nexport type ParameterDetectionSource = (typeof PARAMETER_DETECTION_SOURCES)[number];\n\n/**\n * ─── WHY AN INTERPRETER YIELDS NOTHING, IN THE AUTHOR'S WORDS (S6, D6) ──────────────────\n *\n * `null` means detection WORKS for this interpreter. Any other value is the sentence shown\n * beside a control that is VISIBLE AND DISABLED — never silently absent, because a control that\n * vanishes teaches an author the product is inconsistent while one that explains itself teaches\n * them something true about their own script.\n *\n * Declared here rather than composed on either side, because BOTH need it and they must not\n * word it differently: the browser disables the toggle before any request is made, and the\n * server returns the same sentence as `unavailableReason` when asked anyway.\n *\n * Keyed by {@link PackageInterpreter}, so adding an interpreter is a COMPILE ERROR here until\n * somebody says whether its declarations can be read.\n */\nexport const PARAMETER_DETECTION_UNAVAILABLE: Record<PackageInterpreter, string | null> = {\n powershell: null,\n // NOT \"not supported yet\". Bash genuinely has no parameter declaration — `$1` and `getopts`\n // are code, not a contract — so there is nothing to read and there never will be (docs/32 §11).\n bash: \"Bash has no parameter declaration to read, so you will define these yourself.\",\n // A different sentence, because it is a different fact: Python DOES declare parameters, in\n // `argparse`, and Opera cannot read them yet. Promising nothing is honest; implying Python is\n // as unreadable as Bash would not be.\n python:\n `${BRAND_SHORT_NAME} cannot read Python parameters yet — argparse detection is not built. Define these yourself for now.`,\n};\n\n/**\n * What CHOOSING this language means, in one sentence, for the author who has not written the\n * script yet. Its sibling above is the consequence of HAVING CHOSEN — shown on the Parameters\n * tab, where the difference between \"never will\" and \"not yet\" is the fact that matters.\n *\n * ★ DERIVED FROM THE RECORD ABOVE, NEVER BRANCHED PER LANGUAGE (docs/39 §4.5). The picker must\n * not encode that PowerShell is special — no \"Recommended\" badge, no privileged case — because\n * that fact EXPIRES: the day Python's entry above becomes `null` it is two of three, and a\n * design that hard-coded today's winner has to be rebuilt. Written as one expression over the\n * whole closed vocabulary, the cards re-word themselves on that day and nobody has to remember\n * this file exists.\n *\n * Both sentences are the AUTHOR'S consequence, phrased symmetrically, and neither mentions our\n * backlog: \"You define parameters yourself\", not \"argparse detection is not built\".\n */\nexport function parameterDetectionConsequence(interpreter: PackageInterpreter): string {\n return PARAMETER_DETECTION_UNAVAILABLE[interpreter] === null\n ? `${BRAND_SHORT_NAME} reads your parameters from your script.`\n : \"You define your parameters yourself.\";\n}\n\n/**\n * The interpreter's name as its own community spells it. A display label is not the wire value:\n * `powershell` is the vocabulary member and \"PowerShell\" is what an author recognises, and a\n * `toUpperCase()` on the first letter would render \"Powershell\".\n */\nexport const PACKAGE_INTERPRETER_LABEL: Record<PackageInterpreter, string> = {\n powershell: \"PowerShell\",\n bash: \"Bash\",\n python: \"Python\",\n};\n\n/**\n * One parameter Opera PROPOSES, already mapped onto Opera's own model.\n *\n * The mapping happens on the SERVER and the browser renders it. Opera's parameter model is\n * narrower than PowerShell's type system, and a browser that re-derived \"what would this render\n * as\" would eventually disagree with the schema the author actually accepted.\n */\nexport interface DetectedParameterDto {\n /** The variable's name, exactly as declared. This is what the script reads. */\n name: string;\n /**\n * What the operator reads on the run form — the parameter editor requires one, and a proposal\n * that arrived without it would show as a problem the author has to fix before accepting.\n *\n * THE DECLARED NAME, VERBATIM. Not a prettified rendering of it: `VMName` does not become\n * \"V M Name\" and `SubscriptionId` does not become anything the author did not write. Turning\n * an identifier into English is a guess, and this row is the one place the product must be\n * showing the author their own file back. They rename it afterwards if they want to.\n */\n title: string;\n /** What the author wrote — `[string]`, `[int]`, `[ValidateSet(...)] [string]`. */\n declaredType: string;\n type: \"string\" | \"boolean\";\n control: ParameterControl;\n required: boolean;\n /** `[ValidateSet(...)]`, when there is one. Empty otherwise. */\n enumValues: string[];\n /** The declared default, as Opera would store it. Null when the author declared none. */\n defaultValue: string | boolean | null;\n /** `[Parameter(HelpMessage=…)]`, else the `.PARAMETER` comment help, else empty. */\n description: string;\n /**\n * A fact about the mapping that the author must read before accepting — today, only that a\n * numeric or date type is proposed as TEXT because Opera parameters are text or true/false.\n * Null when the declaration maps exactly.\n *\n * A composed SENTENCE rather than a code, because there is nothing for the UI to branch on:\n * a row with a note is de-emphasised and shows it. A vocabulary would be a second name for\n * the same one thing.\n */\n note: string | null;\n /** 1-based line in {@link DetectedParametersDto.fromFile} where the declaration starts. */\n sourceLine: number;\n /** The declaration itself, whitespace-collapsed — so the claim is checkable against the file. */\n sourceText: string;\n}\n\n/**\n * A declaration Opera READ and will NOT propose.\n *\n * A SEPARATE ARRAY, not a flag on {@link DetectedParameterDto}, and that is structural rather\n * than stylistic: anything iterating `parameters` is iterating what may be written to the draft,\n * so an array parameter cannot be proposed by a caller who forgot to check a boolean. A text box\n * that pretends to be a `[string[]]` produces a run that fails on a type the operator was never\n * warned about.\n *\n * It carries `sourceLine` for the same reason the proposed rows do: the review list is shown in\n * the author's DECLARATION ORDER, with these interleaved and de-emphasised — visible, never\n * hidden behind a disclosure, because being seen is their entire purpose.\n */\nexport interface UnrepresentableParameterDto {\n name: string;\n declaredType: string;\n /** Why it cannot be carried, and what the author can do about it. Composed once, here. */\n reason: string;\n sourceLine: number;\n sourceText: string;\n}\n\n/**\n * ─── WHAT WAS READ, AS ONE OBJECT ───────────────────────────────────────────────────────\n *\n * Produced by `POST /packages/drafts/detect-parameters`, which is STATELESS AND READ-ONLY: it\n * writes nothing, so a proposal can be recomputed, re-reviewed or discarded freely (D5).\n *\n * `source: \"none\"` with a non-null `unavailableReason` is the honest answer for bash and python.\n * `source: \"powershell_param\"` with an EMPTY `parameters` array is a different and equally valid\n * answer: a PowerShell script that declares no parameters. The two are not the same state and\n * the UI says so — one is \"there is nothing here to read\", the other is \"there was nothing\".\n */\nexport interface DetectedParametersDto {\n source: ParameterDetectionSource;\n /** Why this interpreter yields nothing (S6). Null when detection ran. */\n unavailableReason: string | null;\n /** Which file was parsed. Null when nothing was. */\n fromFile: string | null;\n /** In the author's DECLARATION ORDER — never alphabetised (charter §4.2, the order key). */\n parameters: DetectedParameterDto[];\n unrepresentable: UnrepresentableParameterDto[];\n /**\n * The parse itself failed — a timeout, or a child that could not be started.\n *\n * SEPARATE FROM `unavailableReason`, because they are different facts and the author acts on\n * them differently: one says this interpreter has nothing to read, the other says Opera could\n * not read it THIS TIME. Neither ever blocks the import — the draft is created either way and\n * parameters can be declared by hand.\n */\n failure: string | null;\n}\n\n/** What `POST /packages/drafts/detect-parameters` takes. Same edge rules as `inspect-upload`. */\nexport interface DetectParametersInput {\n files: AuthoredPackageFileDto[];\n /**\n * The file to read — the one the wrapper will BIND against at run time. Required, and never\n * inferred here: a detector that picked its own file could read a `param()` block the runner\n * never binds, which is the whole class of defect this slice exists to remove.\n */\n entrypoint: string;\n}\n\n/**\n * ═══ FILTERING THE AUTHOR'S LIST ═══════════════════════════════════════════════════════\n *\n * DELIBERATELY NOT `PackageDraftState`. That enum answers \"which version did this draft\n * produce\"; this vocabulary is what an author actually looks for, and `unpublished_changes`\n * is not a state at all — it is `hasUnpublishedChanges`, which composes with any of them.\n *\n * A draft matching `unpublished_changes` may also be `published` or `superseded`, so these\n * are NOT a partition and nothing may treat them as one. Filtering by one is asking a\n * question, not naming a bucket.\n *\n * Every member is answered in SQL. A filter evaluated after the page is fetched returns short\n * pages and reports \"no matches\" for drafts it simply had not read yet.\n */\nexport const PACKAGE_DRAFT_FILTERS = [\n \"never_published\",\n \"published\",\n \"unpublished_changes\",\n \"superseded\",\n] as const;\nexport type PackageDraftFilter = (typeof PACKAGE_DRAFT_FILTERS)[number];\n\n/** How each filter reads. Declared once so the API and the UI cannot word it differently. */\nexport const PACKAGE_DRAFT_FILTER_LABELS: Record<PackageDraftFilter, string> = {\n never_published: \"Never published\",\n published: \"Published\",\n unpublished_changes: \"Unpublished changes\",\n superseded: \"Superseded\",\n};\n\n/** Query for `GET /packages/drafts`. Keyset-paginated; `cursor` is opaque to the client. */\nexport interface ListPackageDraftsQuery {\n /** Matched against the package id AND the display name, server-side, case-insensitively. */\n q?: string;\n filter?: PackageDraftFilter;\n interpreter?: PackageInterpreter;\n cursor?: string;\n limit?: number;\n}\n\n/**\n * ─── THE TWO WAYS A DRAFT STARTS ────────────────────────────────────────────────────────\n *\n * SCAFFOLD — no `files`. `interpreter` is REQUIRED, because there is no file to derive it from,\n * and `script` is the author's paste.\n *\n * IMPORT — `files` and an `entrypoint`. `interpreter` is REFUSED rather than optional: the\n * entrypoint's extension decides it (docs/32 D4), so sending one too is asking the same question\n * twice, and silently preferring either answer is how the plan an author read stops describing\n * the draft they got.\n *\n * Written as one interface with the constraint in prose rather than as a union, because it is\n * the WIRE shape and a JSON body has no discriminant. The server parses it into\n * `CreateDraftCommand`, which IS a union, and refuses every combination this comment forbids.\n */\nexport interface CreatePackageDraftInput {\n packageId: string;\n name: string;\n /** Required WITHOUT `files`; refused WITH them. See the note above. */\n interpreter?: PackageInterpreter;\n /**\n * The author's pasted script. Opera scaffolds a working action and puts this in the run\n * phase's BODY file (`run/body.sh`, `body.ps1`, `body.py`) — never over the entrypoint, which\n * is the wrapper carrying the result contract.\n *\n * Composed on the SERVER, deliberately: a client that assembled the file set itself is a\n * second implementation of \"which file does a paste go in\", and the first one put the script\n * over `run/main.*` and shipped actions that failed at run.\n */\n script?: string;\n /**\n * Optional. Absent → Opera scaffolds a working action, exactly as `runveric init` does.\n * Present → the author's own files, stored VERBATIM at the paths they arrived with, with the\n * manifest, the parameter schema and the wrapper generated around them; `script` is then\n * meaningless and refused.\n */\n files?: AuthoredPackageFileDto[];\n /**\n * WHICH OF `files` RUNS — package-relative, and required whenever `files` is present unless\n * those files already carry an `action.yaml`.\n *\n * It is not `run/body.*` and it is not moved there. An imported script lives at `deploy.ps1`\n * or `scripts/restart.sh`, and the generated wrapper is pointed AT IT rather than the file\n * being pointed at the wrapper — because their own `. ./lib/helpers.ps1` names a path\n * relative to where the file was, and moving the file is how that path stops existing.\n *\n * Its EXTENSION decides the interpreter (docs/32 D4): the runtime provides exactly one per\n * package, so the file that runs is the only thing that could decide which. An `interpreter`\n * that disagrees with it is refused rather than silently overridden.\n */\n entrypoint?: string;\n}\n\nexport interface UpdatePackageDraftInput {\n packageId?: string;\n name?: string;\n interpreter?: PackageInterpreter;\n files?: AuthoredPackageFileDto[];\n}\n\n/**\n * ═══ BRINGING AN EXISTING SCRIPT IN ════════════════════════════════════════════════════\n *\n * An author with a script on their laptop has two ways in: `runveric` for a directory they\n * already have in Git, and this — dropping files into a page. Neither replaces the other.\n *\n * THE FILES ARE NEVER TRANSFORMED. They are stored at the paths they arrived with, byte for\n * byte: no concatenation, no rewriting, no reordering, no renaming (docs/32 D3). Their author's\n * own `source ./lib/util.sh` and `. ./lib/helpers.ps1` name paths relative to where the file\n * was, and the only way those keep working is for the file to still be there. What Opera adds\n * is a manifest, a parameter schema and a wrapper — beside their work, never over it.\n */\n\n/**\n * THE BOUNDS ON A DRAFT'S FILES, DECLARED ONCE.\n *\n * A draft's files live in a jsonb column, read whole on every autosave and hashed on every\n * digest, so \"how big can this get\" is a question with a real answer rather than a shrug. These\n * are the numbers, and they are enforced on the SERVER — a browser-side check is a courtesy to\n * somebody who dropped the wrong folder, and courtesies are not rules.\n *\n * ONE PAIR OF NUMBERS FOR ONE COLUMN. The import path, the draft autosave and the CLI's publish\n * route all write the same column and all read these constants; a second set of limits on one\n * of those routes would be a second answer to one question.\n *\n * BYTES, NOT CHARACTERS. A UTF-8 astral character is four bytes and one `String.length` of two,\n * so a character count is not a bound on what reaches storage.\n */\nexport const PACKAGE_IMPORT_LIMITS = {\n /** Per file. A source file larger than this is a mistake worth naming, not a package. */\n maxFileBytes: 1024 * 1024,\n /** Per draft, summed across every imported file. */\n maxTotalBytes: 5 * 1024 * 1024,\n /** How many files one package may contain. */\n maxFiles: 200,\n /**\n * ─── AND THE CEILING ON A DROP, WHICH IS A DIFFERENT QUESTION ─────────────────────────\n *\n * The three limits above bound a PACKAGE. These bound what may be handed to `inspect-upload`\n * in one request, and they are deliberately far looser, because the whole point of the\n * pre-flight is to look at a folder that contains things which will NOT be in the package and\n * say so. A drop of 38 files where 26 are skipped has to be inspectable, or the author learns\n * nothing about the 26.\n *\n * They exist because a folder can also be a Node project. Dragging one brings `node_modules`,\n * and \"the server decides every skip\" cannot mean \"the browser first uploads 400 MB to be\n * told\". Over these, the drop itself is refused with the counts named and the suggestion to\n * pick the script's own folder — a sentence about the drop, not a plan.\n *\n * The browser checks them so the refusal is instant, and the server checks them because the\n * browser's check is a courtesy.\n */\n maxInspectFiles: 2000,\n maxInspectBytes: 20 * 1024 * 1024,\n} as const;\n\n/**\n * ─── WHY A FILE WAS NOT IMPORTED ────────────────────────────────────────────────────────\n *\n * Array-first (charter §4.2), because every one of these must be RENDERABLE. Dragging a project\n * folder brings `.git/`, `node_modules/`, a `.DS_Store` and whatever the last build left behind.\n * Skipping them is right; skipping them QUIETLY is not — an author whose `lib/` vanished because\n * it sat under a filtered directory has no way to find out except from a failed run.\n *\n * So a skip is a REASON, and the reason is shown next to the path. Nothing is dropped silently\n * and nothing is dropped without a name.\n */\nexport const PACKAGE_IMPORT_SKIP_REASONS = [\n \"version_control\",\n \"dependencies\",\n \"build_output\",\n \"editor_metadata\",\n \"os_metadata\",\n \"lockfile\",\n \"runveric_scratch\",\n \"not_text\",\n] as const;\nexport type PackageImportSkipReason = (typeof PACKAGE_IMPORT_SKIP_REASONS)[number];\n\n/** How each skip reads to the author. Declared once so the API and the UI cannot differ. */\nexport const PACKAGE_IMPORT_SKIP_REASON_LABELS: Record<PackageImportSkipReason, string> = {\n version_control: \"version-control metadata\",\n dependencies: \"dependencies are not part of a package\",\n build_output: \"build output\",\n editor_metadata: \"editor settings\",\n os_metadata: \"operating-system metadata\",\n lockfile: \"a dependency lockfile\",\n runveric_scratch: \"scratch written by `runveric test`\",\n not_text: \"not UTF-8 text\",\n};\n\n/**\n * A file that WILL be imported and will not run. One member today, and a vocabulary anyway:\n * the alternative is a free-form string that the UI has to pattern-match to choose a tone.\n *\n * `mixed_interpreter` is a WARNING and never a refusal (docs/32 D4). A package provides exactly\n * one interpreter, so a `.py` beside a `.ps1` entrypoint ships into the sandbox and fails there\n * with an unhelpful message — worth naming the file for. A `.json`, `.csv` or `.md` beside it is\n * DATA and warns about nothing: a PowerShell package with a `config.json` is entirely\n * legitimate, and a blunter rule would block it.\n */\nexport const PACKAGE_IMPORT_WARNING_REASONS = [\"mixed_interpreter\"] as const;\nexport type PackageImportWarningReason = (typeof PACKAGE_IMPORT_WARNING_REASONS)[number];\n\n/** One file that arrived, and what will happen to it. */\nexport interface ImportPlanFileDto {\n path: string;\n /** Decoded UTF-8 length in bytes — what counts against {@link PACKAGE_IMPORT_LIMITS}. */\n bytes: number;\n}\n\nexport interface ImportPlanSkippedDto extends ImportPlanFileDto {\n reason: PackageImportSkipReason;\n /** The sentence to render, already composed — the UI never assembles its own. */\n message: string;\n}\n\nexport interface ImportPlanWarningDto extends ImportPlanFileDto {\n reason: PackageImportWarningReason;\n message: string;\n}\n\n/**\n * WHICH FILE RUNS, and how confident Opera is about it (docs/32 S3).\n *\n * `chosen` is null ONLY when nothing recognisable was found; `ambiguous` says the author must\n * confirm rather than that Opera failed. The two are different facts and a single nullable\n * field cannot carry both — an ambiguous plan HAS a pre-selected proposal, it just may not\n * act on it unasked.\n */\nexport interface ImportPlanEntrypointDto {\n /** The entrypoint, pre-selected. Null when no file in the upload could be one. */\n chosen: string | null;\n /** Every candidate script, in the order they should be offered. */\n proposals: string[];\n /**\n * True when more than one candidate exists and none is conventionally named, so Opera has no\n * grounds to pick. The UI blocks creation and says why; choosing one clears it.\n */\n ambiguous: boolean;\n /**\n * Why `chosen` is what it is — \"the only script in the upload\", \"named `main.ps1` by\n * convention\". Shown so that \"selected silently\" never means \"selected invisibly\".\n */\n reason: string;\n}\n\n/**\n * The interpreter, and the sentence that explains it (docs/32 D4).\n *\n * READ-ONLY IN THE UI, WITH ITS REASON. The runtime provides exactly one interpreter per\n * package and the entrypoint's extension decides which, so offering a picker would offer a\n * choice that does not exist. A disabled dropdown with no explanation teaches an author the\n * product is arbitrary; a sentence teaches them something true about their own upload.\n */\nexport interface ImportPlanInterpreterDto {\n /** Null exactly when {@link ImportPlanEntrypointDto.chosen} is null. */\n value: PackageInterpreter | null;\n reason: string;\n}\n\n/**\n * ─── WHAT WILL HAPPEN, AS ONE OBJECT ────────────────────────────────────────────────────\n *\n * The single description of an import. The screen RENDERS this; it does not compute a second\n * opinion in the browser and hope the two agree — a pre-flight that disagrees with the thing it\n * previews is worse than no pre-flight, because it is trusted.\n *\n * Produced by `POST /packages/drafts/inspect-upload`, which is STATELESS and READ-ONLY: it\n * writes nothing, so an author can re-drop files, change the entrypoint and re-inspect as often\n * as they like without leaving a trail of abandoned drafts.\n */\nexport interface ImportPlanDto {\n entrypoint: ImportPlanEntrypointDto;\n interpreter: ImportPlanInterpreterDto;\n /** Files that will become the draft, at exactly these paths. */\n included: ImportPlanFileDto[];\n skipped: ImportPlanSkippedDto[];\n warnings: ImportPlanWarningDto[];\n /**\n * Paths Opera would GENERATE that the upload already occupies. A collision is a REFUSAL, not\n * an overwrite: silently clobbering a file somebody just handed us is the worst outcome\n * available. Empty when the upload carries its own `action.yaml`, because then Opera generates\n * nothing at all and there is nothing to collide with.\n */\n collisions: string[];\n /**\n * True when the upload already contains `action.yaml` — an Opera package being re-imported\n * (exported, cloned from a colleague, or produced by the CLI). Opera GENERATES NOTHING for\n * one: overwriting an author's manifest would destroy the riskLevel, requiredPermissions and\n * egress declarations that took them the longest to get right.\n */\n alreadyAnActionPackage: boolean;\n /** What Opera will add. Empty when {@link alreadyAnActionPackage}. */\n generated: string[];\n totals: { files: number; bytes: number };\n /**\n * The validator's verdict on an upload that BROUGHT ITS OWN `action.yaml`, and null otherwise.\n *\n * Opera generates nothing for such an upload, so the only useful thing it can say is whether\n * what arrived is valid — run through `checkActionPackage`, the same call behind\n * `runveric check`, the Check panel and publishing. Without this the author would import a\n * package with a broken manifest and find out one screen later.\n */\n check: PackageCheckResultDto | null;\n}\n\n/** What `POST /packages/drafts/inspect-upload` takes. */\nexport interface InspectUploadInput {\n files: AuthoredPackageFileDto[];\n /**\n * The author's choice, when they have made one. Absent on the first inspect, so Opera\n * proposes; present on re-inspect, so the plan reflects what they picked — including the\n * interpreter, which their choice decides.\n */\n entrypoint?: string;\n}\n\n/** What the CLI's `publish` and the app's Publish button both send. */\nexport interface PublishAuthoredPackageInput {\n files: AuthoredPackageFileDto[];\n}\n\n/**\n * ─── ONE CHECK RESULT, FOR THE CLI AND THE APP ──────────────────────────────────────────\n *\n * The same `AuthoringFinding` shape @runveric/action-manifest produces. It crosses the wire so\n * the in-app Check button renders exactly what `runveric check` prints — same rules, same\n * lines, same fixes — rather than the app growing its own idea of what is wrong.\n *\n * Declared here rather than imported from @runveric/action-manifest because contracts is a LEAF:\n * the web app must be able to render one without pulling in a Node-only validator.\n */\nexport interface AuthoringFindingDto {\n severity: \"error\" | \"warning\";\n rule: string;\n file: string;\n line?: number;\n column?: number;\n message: string;\n fix: string;\n /**\n * An ERROR by volume that gates nothing — the shape a heuristic rule takes. See\n * `AuthoringFinding.advisory` in @runveric/action-manifest for why the two facts are separate.\n */\n advisory?: boolean;\n}\n\nexport interface PackageCheckResultDto {\n /** Whether Opera would ACCEPT this package at publish. */\n ok: boolean;\n /**\n * True when Opera would accept it AND the lint found something that misbehaves at run time\n * — the `$Name?` shape. Separate from `ok` because they are different facts and the second\n * one is the more dangerous, precisely because publishing says nothing about it.\n *\n * Advisory findings are excluded: they are reported, they do not gate.\n */\n lintBlocked: boolean;\n findings: AuthoringFindingDto[];\n errorCount: number;\n warningCount: number;\n /** How many of `errorCount` are advisory — reported at full volume, gating nothing. */\n advisoryCount: number;\n}\n\n/**\n * ═══ THE VERSION A TRIAL RUN WILL EXECUTE ══════════════════════════════════════════════\n *\n * What `PackagesFacade.mintTrialVersion` hands back: a real, immutable package version that is\n * invisible to the catalog, plus the two facts the caller cannot derive for itself.\n *\n * It carries NO knowledge that a run exists. Packages mints versions; Execution runs them. That\n * separation is what let this feature be built without pointing `packages` at `execution` —\n * which `execution` already depends on, and which dependency-cruiser rejects as a cycle (§2.4).\n */\nexport interface TrialVersionDto {\n draftId: string;\n /** The pinned version a run is created against. */\n actionVersionId: string;\n actionDefinitionId: string;\n packageId: string;\n /** The draft's display name, captured for the run's history. */\n name: string;\n contentDigest: string;\n /** `${manifest.version}+trial.<digest>` — see {@link trialSemanticVersion}. */\n semanticVersion: string;\n /**\n * THE RISK LEVEL THIS RUN IS GOVERNED AT: the more severe of the draft's declaration and any\n * existing definition's. See {@link maxRiskLevel} for why it is never just the draft's.\n */\n riskLevel: RiskLevel;\n /** What the draft's own manifest declares. Differs from `riskLevel` only when out-governed. */\n declaredRiskLevel: RiskLevel;\n /**\n * The PINNED schema, read back off the version that will run — not the draft's file. It is\n * what the server validates a run's parameters against, and it carries the order key, so a\n * form rendered from it asks for fields in the order the author arranged them.\n */\n parameterSchema: ParameterSchema;\n /**\n * Whether the DRAFT's manifest declares `capabilities.dryRun`.\n *\n * From the manifest rather than from the projected definition, deliberately: capabilities are\n * definition-owned and a trial never rewrites the definition, so for a package that has\n * already published, the definition's copy answers for the RELEASED version. The bytes about\n * to run are the draft's, and this is a claim about them.\n */\n dryRunSupported: boolean;\n /** The check that admitted it — warnings and advisories included, since none of them gate. */\n check: PackageCheckResultDto;\n}\n\n/**\n * How an author installs the CLI, served BY the deployment rather than written in a doc.\n *\n * An author who cannot install the tool has no loop, and the two facts they need — the install\n * line and which runner image their Opera actually runs — are facts about THIS deployment. A\n * hard-coded npm line in the UI would be wrong for anyone running a private registry, and a\n * missing runner image reference is what makes a local `test` an approximation.\n */\nexport interface AuthoringToolingDto {\n /**\n * e.g. `npx @runveric/cli@0.1.2` — copy-pasteable, exactly as it should be typed.\n *\n * IT PINS A VERSION. `@latest` would hand an author whatever was published most recently,\n * which may be newer than the deployment they are pointed at — the same reason nothing else\n * in this codebase names an artifact loosely.\n */\n installCommand: string;\n /**\n * The registry page for the CLI, or NULL when this deployment installs from somewhere else.\n *\n * A customer evaluating a tool wants to see that it exists, who published it and when — but\n * only the deployment knows whether {@link installCommand} still refers to the public\n * package. When it has been overridden for a private registry, this is `null` and the UI\n * shows no link, rather than sending someone to inspect a package they do not install.\n */\n packageUrl: string | null;\n /** The runner image reference to set as OPERA_RUNNER_IMAGE, or null if not configured. */\n runnerImage: string | null;\n /** The API origin the CLI publishes to. */\n apiBaseUrl: string;\n}\n","// ═══ WHAT A PRE-FLIGHT VALIDATE PRODUCED — WHOEVER PRODUCED IT ═════════════════════════\n//\n// A leaf. It imports nothing, and that is the point: these are the vocabulary of a validate\n// RESULT, and validate has two producers that must not know about each other — the in-process\n// connector, whose result lands on `ExecutionDto`/`ExecutionPlanDto` (`execution.ts`), and a\n// private runner, whose result arrives as a `RunnerStepReport` (`runners.ts`).\n//\n// ─── ★ WHY THEY MOVED HERE ─────────────────────────────────────────────────────────────\n//\n// They were declared in `execution.ts`, so `runners.ts` had to import the whole execution\n// module to describe a report. `runner-pool-presence.ts` derives from `runners.ts`, and\n// `ExecutionPlanDto.runnerWait` reads back from `runner-pool-presence.ts` — which closed a\n// cycle the moment docs/57 added that field:\n//\n// execution → runner-pool-presence → runners → execution\n//\n// Type-only in every edge, so nothing was broken at runtime and it shipped to production;\n// `pnpm boundaries` is the only thing that ever said so. The cut is here rather than at\n// either of the other two edges because this is the only edge pointing the WRONG WAY: a\n// plan depending on pool facts is the real direction of that dependency, and a pool\n// summary depending on runners is too. A runner report depending on the entire execution\n// module, for two shapes that are not about executions, was not.\n//\n// `execution.ts` re-exports all of them, so every existing importer — inside this package and\n// out — is untouched.\n\n// ═══════════════════════════════════════════════════════════════════════════════════════\n// ★ A COUNT THAT WAS NOT TAKEN MUST BE ABLE TO SAY SO (docs/66 §3.1)\n// ═══════════════════════════════════════════════════════════════════════════════════════\n//\n// This file used to declare ONE shape — three bare `number`s — and that is the whole reason a\n// plan lied about its targets for as long as it did. An author who must return three integers\n// when the scope call has not happened has three integers available and nothing else, so\n// `execution.service.ts` returned `{ eligible: 1, excluded: 0, blocked: 0 }`: a literal, shown\n// to the operator as `✓ Validated — 1 eligible target(s)`, persisted onto the execution row,\n// and rendered by the run record for the rest of that run's life.\n//\n// ★ THE LITERAL WAS THE SYMPTOM. THE TYPE WAS THE CAUSE. Scope resolution is a live call into a\n// customer's cloud: it is throttled, it is refused, credentials expire, and some actions have no\n// cloud scope at all. Silence was unexpressible, so fabrication was the only move left. Give the\n// absence a name and nobody has to invent a number — which is docs/56's `EXECUTION_SITE_UNKNOWN`\n// argument on a different fact: an absence is reserved for THE ABSENCE OF A WRITE, never for a\n// value we chose.\n//\n// ─── ★ WHY NOT `0 / 0 / 0` ON FAILURE ──────────────────────────────────────────────────\n//\n// Because it is a WORSE lie than the `1`, not a smaller one. `0 eligible` is a sentence this\n// system can legitimately produce — a tag selector that matched nothing — and an operator who\n// reads it stops, because a run with no targets is a run that will do nothing. Handing them that\n// when the truth is \"the subscription was throttled and we never asked\" makes them act on a\n// finding that does not exist. Counted-and-empty and never-counted are different facts and this\n// vocabulary keeps them apart.\n//\n// ─── ★ WHY THE COUNTS AND THE ABSENCE ARE ONE UNION AND NOT FOUR FIELDS ─────────────────\n//\n// `{ eligible, excluded, blocked, uncounted }` as four loose fields makes \"we did not count, and\n// here are the counts\" expressible, and something would eventually build it. As a union there is\n// nowhere to put that. Measured: `{ eligible: 1, excluded: 0, blocked: 0, uncounted: \"no_scope\" }`\n// is a compile error — `Object literal may only specify known properties`.\n\n/**\n * ═══ THE THREE COUNTS, FROM A SCOPE THAT WAS ACTUALLY RESOLVED ═════════════════════════\n *\n * Unchanged from before docs/66, deliberately: a count that WAS taken reads exactly as it always\n * did, on the wire and in the column. What changed is that it is now one member of a union\n * rather than the only thing a caller can say.\n *\n * ★ THIS — NOT {@link TargetSummary} — IS WHAT A CONNECTOR RETURNS, and the asymmetry is the\n * design. A connector counts, or it throws; it is a live call and a failed one is an exception,\n * not a value. WHY the count is absent is a conclusion drawn by the caller that made the call\n * and knows what happened to it, so the absence lives one level up where that knowledge is.\n * Keeping `resolveScope` on the narrower type is also what leaves `run-execution.handler.ts`\n * untouched (docs/66 §3.4) and the runner protocol's `RunnerStepReport.targets` unchanged on\n * the wire — an older runner's report parses exactly as it did.\n */\n\nimport { BRAND_SHORT_NAME } from \"./brand\";\n\nexport interface TargetCounts {\n eligible: number;\n excluded: number;\n blocked: number;\n /**\n * ⚠ NEVER PRESENT ON A REAL COUNT. It exists only so TypeScript discriminates this member\n * from {@link UncountedTargets} on one property, which is what makes `if (summary.uncounted)`\n * narrow in both directions and what makes the mixed shape above unbuildable. It is optional\n * and always `undefined`, so it serializes to nothing and no stored or transmitted value\n * changes shape because of it.\n */\n uncounted?: undefined;\n}\n\n/**\n * ═══ WHY A COUNT IS ABSENT — THREE ANSWERS, NOT ONE ════════════════════════════════════\n *\n * They are three because the remedies are three, and a reader handed the wrong one goes and\n * changes the wrong thing:\n *\n * | member | what happened | what a person would do |\n * |-----------------|--------------------------------------------|---------------------------|\n * | `no_scope` | this action has no cloud scope to enumerate | nothing — it is normal |\n * | `unavailable` | we asked and could not get an answer | retry, fix the credential |\n * | `not_attempted` | nobody has asked yet | validate the run |\n *\n * `no_scope` is PERMANENT and a property of the action; `unavailable` is TRANSIENT and a property\n * of this attempt; `not_attempted` is the absence of a write. Collapsing them into one \"unknown\"\n * would tell the owner of a package action that their cloud is unreachable, every single time.\n */\nexport const TARGET_COUNT_ABSENCES = [\"no_scope\", \"unavailable\", \"not_attempted\"] as const;\nexport type TargetCountAbsence = (typeof TARGET_COUNT_ABSENCES)[number];\n\n/** True for a stored value this vocabulary understands. */\nexport function isTargetCountAbsence(value: unknown): value is TargetCountAbsence {\n return (\n typeof value === \"string\" && (TARGET_COUNT_ABSENCES as readonly string[]).includes(value)\n );\n}\n\n/** A scope that has no counts, and says which of the three reasons is why. */\nexport interface UncountedTargets {\n uncounted: TargetCountAbsence;\n /**\n * What actually went wrong, in the words of whatever refused — carried so the check a person\n * reads names the reason rather than saying \"something failed\" (docs/66 §3.2). Only meaningful\n * for `unavailable`: the other two absences have nothing situational to add.\n */\n detail?: string;\n}\n\n/**\n * What a PLAN promises and what a RECORD holds about a run's targets.\n *\n * ⚠ ONE TYPE FOR BOTH, WHERE `execution-site.ts` DELIBERATELY HAS TWO. A plan's site and a\n * record's site are different vocabularies because a plan cannot name a runner and a record can.\n * Targets are the opposite case: docs/66 §6 requires that the approver reading later sees THE\n * SAME VALUE the operator saw — not a recount that quietly disagrees because the cloud changed\n * in between. One type is what makes \"the number you approved is the number on the record\"\n * a property of the shape rather than of everyone remembering.\n */\nexport type TargetSummary = TargetCounts | UncountedTargets;\n\n/**\n * ═══ THE COUNT FOR AN ACTION THAT NAMES EXACTLY ONE RESOURCE ═══════════════════════════\n *\n * Six built-in connectors resolve a scope of exactly one — a named VM, a named disk, a named\n * database, a named secret — because breadth is an Operation's fan-out and never a connector's\n * (docs/31 §8). They each spelled `{ eligible: 1, excluded: 0, blocked: 0 }` out, which is six\n * copies of one sentence and exactly the class docs/62 exists to end.\n *\n * ⚠ IT IS NOT A DEFAULT AND MUST NEVER BECOME ONE. A connector calls this AFTER parsing the\n * parameters that name its one resource — the count is derived from \"this action names one\n * thing\", which is a fact about the action, not a fallback for not having asked. The value for\n * not having asked is {@link TARGETS_NOT_COUNTED} and it is a different shape on purpose.\n */\nexport function singleTarget(): TargetCounts {\n return { eligible: 1, excluded: 0, blocked: 0 };\n}\n\n/**\n * ═══ WHAT A PHASE THAT FAILED REPORTS (the runner protocol) ════════════════════════════\n *\n * ⚠ THIS IS NOT THE docs/66 DEFECT, AND THE DIFFERENCE IS WHO READS IT. The defect was a PLAN\n * promising a count to an operator who then approved it. This is a RUNNER reporting that its\n * `validate` phase THREW: the protocol refuses an outcome on a validate report, so a failure\n * reports an error-level check, and the report's `targets` is what a phase that never got as\n * far as counting has to put there.\n *\n * ★ IT IS A NAMED CONSTRUCTOR RATHER THAN A LITERAL FOR THE REASON THE GUARD EXISTS: the two\n * places that report a failed validate — the dispatcher's protocol refusal and the step\n * container's own crash handler — had a copy each, and two copies of a count is how they come\n * to disagree about what a failure looks like on the wire.\n *\n * ⚠ RECORDED, NOT FIXED: the honest value here is ABSENCE, and `RunnerStepReport.targets` is\n * already optional. Omitting it would make `RunnerDelegatingConnector.resolveScope` throw its\n * own \"carried no target summary\" error and BURY the runner's real message — a change to what a\n * run does, which docs/66 §3.4 puts out of this slice.\n */\nexport function noTargetsResolved(): TargetCounts {\n return { eligible: 0, excluded: 0, blocked: 0 };\n}\n\n/**\n * Nobody has counted. The value a freshly created run carries, and the value a row written\n * before docs/66 reads back as (migration 0071 stamps them; see `targetSummaryOf`).\n *\n * Exported so no caller has to spell the member — a `{ uncounted: \"not_attempted\" }` written out\n * at a call site is a call site somebody can later change to `{ eligible: 0, … }` thinking they\n * mean the same thing.\n */\nexport const TARGETS_NOT_COUNTED: TargetSummary = { uncounted: \"not_attempted\" };\n\n/** This action has no scope for Opera to enumerate before it runs. A normal answer. */\nexport const TARGETS_NO_SCOPE: TargetSummary = { uncounted: \"no_scope\" };\n\n/** We asked and could not get an answer. `detail` is what the refusal actually said. */\nexport function targetsUnavailable(detail: string): TargetSummary {\n return { uncounted: \"unavailable\", detail };\n}\n\n/**\n * ═══ ONE SENTENCE, ONE PLACE (docs/46 §3.2's rule, applied again) ══════════════════════\n *\n * The operator's toast, the run record's `Targets` tile, the wizard's affected-count line and\n * the validate check list all state this fact. Four copies is how one number comes to be\n * explained four ways — and it is worse than usual here, because three of those surfaces read\n * the value AFTER an approver has said yes to it.\n */\nexport function targetSummarySentence(summary: TargetSummary): string {\n if (!summary.uncounted) {\n return `${summary.eligible} eligible ${summary.eligible === 1 ? \"target\" : \"targets\"}`;\n }\n switch (summary.uncounted) {\n case \"no_scope\":\n return `No scope for ${BRAND_SHORT_NAME} to count`;\n case \"unavailable\":\n return summary.detail\n ? `Targets could not be counted — ${summary.detail}`\n : \"Targets could not be counted\";\n case \"not_attempted\":\n return \"Targets not counted\";\n }\n}\n\n/** The shorter form, for a tile that has one line and a label above it already saying \"Targets\". */\nexport function targetSummaryLabel(summary: TargetSummary): string {\n if (!summary.uncounted) return `${summary.eligible} eligible`;\n switch (summary.uncounted) {\n case \"no_scope\":\n return \"None to count\";\n case \"unavailable\":\n return \"Could not count\";\n case \"not_attempted\":\n return \"Not counted\";\n }\n}\n\n/**\n * The eligible count, or `null` when no count was taken.\n *\n * ⚠ FOR A CALLER THAT GENUINELY NEEDS THE NUMBER — a sentence that inflects on it, a progress\n * denominator. `null` is not a zero and a caller that coalesces it to one has re-created the\n * defect this file exists to close, one surface at a time.\n */\nexport function eligibleTargetCount(summary: TargetSummary): number | null {\n return summary.uncounted ? null : summary.eligible;\n}\n\n/**\n * ═══ THE CHECK DERIVES FROM THE SUMMARY — IT DOES NOT RESTATE IT (docs/66 §3.3) ════════\n *\n * `stubValidationChecks()` used to return the literal sentence \"Scope resolved (stub) — 1\n * eligible target.\" beside a `targets` field holding a literal `1`. Two authors for one fact,\n * free to drift the moment either moved — the docs/62 class, already fixed twice here.\n *\n * ⚠ `warn`, NEVER `error`, WHEN THE COUNT IS ABSENT. docs/57 §3.3 settled this for `runnerWait`\n * and docs/66 §3.2 repeats it: a plan may carry a warning without becoming un-runnable. An\n * operator may knowingly proceed against an uncounted scope; what they may not do is proceed\n * against a fabricated one. Every surface blocks on `level === \"error\"` and only that, so the\n * level here is the whole mechanism by which an uncounted plan stays submittable.\n */\nexport function targetsValidationCheck(summary: TargetSummary): ValidationCheck {\n if (!summary.uncounted) {\n return { level: \"info\", title: `Scope resolved — ${targetSummarySentence(summary)}.` };\n }\n if (summary.uncounted === \"no_scope\") {\n // Not a warning: a package declares its own targets and Opera counting none is correct,\n // not degraded. Warning tone here would put a yellow row on every package run forever.\n return {\n level: \"info\",\n title: `This action has no scope for ${BRAND_SHORT_NAME} to count — it acts on what it declares.`,\n };\n }\n return { level: \"warn\", title: `${targetSummarySentence(summary)}. The run can still be submitted.` };\n}\n\n/**\n * ═══ READING BACK WHAT WAS STORED, INCLUDING WHAT WAS STORED BEFORE docs/66 ════════════\n *\n * `execution.target_summary` is jsonb and was previously written with a blind cast in both\n * directions. Every value it has EVER held was written by one of two authors — the literal\n * `{ eligible: 1, excluded: 0, blocked: 0 }` at validate, or `{ eligible: 0, … }` at create —\n * so no genuine count exists anywhere in the table today. Migration 0071 stamps those rows as\n * `not_attempted` because that is what they are.\n *\n * ★ THIS PARSER IS THE BELT TO THAT MIGRATION'S BRACES, and it is not redundant: during a\n * rolling deploy an older image can write the old shape after the migration has run. A bare\n * three-number object still parses as a count, which is the pre-docs/66 behaviour and the only\n * safe reading of a value this function cannot distinguish. Anything it does not recognise —\n * `null`, `{}`, a string — is an absence, because a row nothing legible was written to has not\n * been counted.\n */\nexport function targetSummaryOf(stored: unknown): TargetSummary {\n if (typeof stored !== \"object\" || stored === null) return TARGETS_NOT_COUNTED;\n const value = stored as Record<string, unknown>;\n if (value.uncounted !== undefined) {\n return isTargetCountAbsence(value.uncounted)\n ? {\n uncounted: value.uncounted,\n ...(typeof value.detail === \"string\" ? { detail: value.detail } : {}),\n }\n : TARGETS_NOT_COUNTED;\n }\n const { eligible, excluded, blocked } = value;\n if (\n typeof eligible === \"number\" &&\n typeof excluded === \"number\" &&\n typeof blocked === \"number\"\n ) {\n return { eligible, excluded, blocked };\n }\n return TARGETS_NOT_COUNTED;\n}\n\n/**\n * ═══ HOW LOUD A CHECK IS — SEVERITY, AND ONLY SEVERITY (docs/126 §3) ═══════════════════\n *\n * Array-first (charter §4.2): it was a bare union, so \"which levels exist\" had no value a guard\n * or a test could iterate. `error` is the one that BLOCKS — `run-execution.handler.ts` stops a\n * run on it and every plan surface refuses on it — and that is the only meaning a level has.\n *\n * ⛔ \"THIS NEEDS A PERSON'S DECISION\" IS NOT A FOURTH LEVEL. Severity and decision are two facts\n * (docs/126 §3): a DECIDE check is a `warn` when it is asked and an `error` when it reaches a run\n * nobody answered it for, so a level that meant \"decide\" would have to mean both. The decision\n * is its own field on {@link ValidationCheck}, below.\n */\nexport const CHECK_LEVELS = [\"info\", \"warn\", \"error\"] as const;\nexport type CheckLevel = (typeof CHECK_LEVELS)[number];\n\n/** True for a level this vocabulary declares — for a parser reading a check off the wire. */\nexport function isCheckLevel(value: unknown): value is CheckLevel {\n return typeof value === \"string\" && (CHECK_LEVELS as readonly string[]).includes(value);\n}\n\n/**\n * ═══ THE CHECKS NOBODY MAY OVERRIDE — REFUSE (docs/126 §3, §6.2) ═══════════════════════\n *\n * A fact that makes the action unsafe or a promise dishonest. A REFUSE check is ALWAYS level\n * `error` — the shape below will not let it be anything else — so it stops a run through the\n * one rule that already stops runs, and it is RETURNED, never thrown: a throw stops the run but\n * the reason never reaches the approver or the evidence (§3.3).\n *\n * ★ A STABLE CODE, so a test, a record and a later fan-out summary name WHICH refusal fired\n * rather than matching a sentence somebody will reword.\n */\nexport const REFUSAL_CODES = [\n \"disk.notUnattached\",\n \"disk.locked\",\n \"disk.shared\",\n \"disk.inRecoveryPlan\",\n \"disk.keyUnusable\",\n \"disk.unverifiable\",\n] as const;\nexport type RefusalCode = (typeof REFUSAL_CODES)[number];\n\n/** True for a value this vocabulary declares. */\nexport function isRefusalCode(value: unknown): value is RefusalCode {\n return typeof value === \"string\" && (REFUSAL_CODES as readonly string[]).includes(value);\n}\n\n/**\n * ═══ THE CHECKS THE REQUESTER DECIDES — DECIDE (docs/126 §3, §6.2) ════════════════════\n *\n * A risk the operator owns. The platform informs; the person decides (§0.1). The code is what a\n * decision NAMES: the submit carries the codes the requester acknowledged, and the server\n * re-runs the checks and refuses unless the two sets are equal — the browser is never the\n * authority on what was decided.\n *\n * ⚠ A CODE IS FOREVER. It is stored on the run (`execution.decisions`) and in the approval\n * snapshot, so renaming one strands every record that cites it. Add a member; never respell one.\n */\nexport const DECISION_CODES = [\n \"disk.recentlyDetached\",\n \"disk.customerKey\",\n \"disk.customerKeyUnverified\",\n \"disk.guestEncrypted\",\n \"disk.noSnapshot\",\n // A confidential VM's disk: its snapshot keeps the VM's guest state, region-bound, and restoring\n // one is unverified (docs/126 §6.6.1) — the operator's call, never a refusal.\n \"disk.confidential\",\n] as const;\nexport type DecisionCode = (typeof DECISION_CODES)[number];\n\n/** True for a value this vocabulary declares — the parser's test for a stored or posted code. */\nexport function isDecisionCode(value: unknown): value is DecisionCode {\n return typeof value === \"string\" && (DECISION_CODES as readonly string[]).includes(value);\n}\n\n/**\n * ═══ ONE PRE-FLIGHT CHECK (docs/04 §2.3) — INFORM, REFUSE OR DECIDE (docs/126 §3) ═══════\n *\n * Three shapes in one union, and the union is what keeps the two facts apart:\n *\n * | shape | `level` | `refusal` | `decision` |\n * |-----------|-------------------|-----------|------------|\n * | ordinary | any | — | — |\n * | REFUSE | `error`, always | a code | — |\n * | DECIDE | `warn` or `error` | — | a code |\n *\n * ★ A DECIDE CHECK MAY BE AN `error`, AND THAT IS docs/126 §3.3, NOT A CONTRADICTION. When it is\n * ASKED — on a plan — it is a `warn` the requester acknowledges. When it reaches a RUN nobody\n * answered it for, the platform raises it to `error`, because only `error` blocks and a `warn`\n * would delete exactly the disk nobody decided about. The marker survives the raise, so the\n * record still says it was a decision nobody made rather than a refusal.\n *\n * ★ AN `info` CHECK CANNOT ASK FOR A DECISION and a REFUSE cannot be anything but `error` —\n * both are compile errors, not conventions. A check that is both a refusal and a decision is\n * unbuildable too: the absent member of each pair is typed `undefined`.\n */\nexport type ValidationCheck = OrdinaryCheck | RefusalCheck | DecisionCheck;\n\n/** INFORM, or any check that is not one of the two coded kinds. */\nexport interface OrdinaryCheck {\n level: CheckLevel;\n title: string;\n refusal?: undefined;\n decision?: undefined;\n}\n\n/** REFUSE — not overridable, never thrown. */\nexport interface RefusalCheck {\n level: \"error\";\n title: string;\n refusal: RefusalCode;\n decision?: undefined;\n}\n\n/** DECIDE — the requester's call; the title is the sentence they read before choosing. */\nexport interface DecisionCheck {\n level: Exclude<CheckLevel, \"info\">;\n title: string;\n decision: DecisionCode;\n refusal?: undefined;\n}\n\n/**\n * ═══ ONE CHECK, READ OFF A WIRE — THE ONE PARSER FOR IT (docs/126 §3.3, docs/128 §4.1) ════\n *\n * Two channels carry checks the control plane did not produce: a private runner's step report\n * (runner-channel v2) and an engine action's validate report (action-protocol v1). Both read\n * each check through THIS function, so the rules a check is held to — a level from the\n * vocabulary, a title, a decision only above `info`, a refusal only at `error`, and no code\n * outside {@link DECISION_CODES} / {@link REFUSAL_CODES} — are written once. Each caller wraps\n * the refusal sentence in its own protocol error.\n *\n * ★ A CHECK CARRYING BOTH CODES IS REFUSED. The union above cannot build one, so only a sender\n * that is not our code can send one — and reading it as either kind would let a REFUSE be\n * re-labelled a DECIDE a person can acknowledge away.\n *\n * Parsed, never cast: the check returned is rebuilt from the fields read, so nothing else the\n * sender put on the object reaches the record.\n */\nexport function validationCheckOf(\n value: unknown,\n): { check: ValidationCheck } | { refusal: string } {\n const raw = (typeof value === \"object\" && value !== null ? value : {}) as Record<string, unknown>;\n const level = raw.level;\n if (!isCheckLevel(level)) {\n return { refusal: `A check level of \"${String(level)}\" is not in the vocabulary.` };\n }\n if (typeof raw.title !== \"string\" || raw.title.length === 0) {\n return { refusal: \"Every check must carry a title.\" };\n }\n if (raw.decision !== undefined && raw.refusal !== undefined) {\n return {\n refusal:\n `A check carrying both a decision (\"${String(raw.decision)}\") and a refusal ` +\n `(\"${String(raw.refusal)}\") is not a check any producer of ours can build.`,\n };\n }\n if (raw.decision !== undefined) {\n if (!isDecisionCode(raw.decision) || level === \"info\") {\n return {\n refusal: `A check's decision of \"${String(raw.decision)}\" at level \"${level}\" is not one this channel accepts.`,\n };\n }\n return { check: { level, title: raw.title, decision: raw.decision } };\n }\n if (raw.refusal !== undefined) {\n if (!isRefusalCode(raw.refusal) || level !== \"error\") {\n return {\n refusal: `A check's refusal of \"${String(raw.refusal)}\" at level \"${level}\" is not one this channel accepts.`,\n };\n }\n return { check: { level, title: raw.title, refusal: raw.refusal } };\n }\n return { check: { level, title: raw.title } };\n}\n\n/**\n * ═══ WHY A SCOPE CALL FAILED, IN THE WORDS OF WHATEVER REFUSED ═════════════════════════\n *\n * The normaliser that turns a thrown thing into an {@link UncountedTargets.detail}. It lived\n * in `execution.service.ts` as a file-private function, which was correct while the PLAN was\n * the only caller. docs/68 gives the RUN the same problem — a `resolveScope` that throws has\n * to record an absence with a reason — and a second copy of this is how one failure comes to\n * be described two ways on the two screens that show it.\n *\n * ⚠ TRAILING PUNCTUATION COMES OFF, and the browser is what showed why. Connector messages are\n * written as whole sentences (\"… requires \\\"resourceGroup\\\" and \\\"vm\\\" parameters.\"), and every\n * caller embeds this inside one of its own — so the rendered row read \"… parameters.. The run\n * can still be submitted.\" Nothing in the API response looked wrong; only the sentence did.\n */\nexport function scopeFailureDetail(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error);\n const oneLine = raw.replace(/\\s+/g, \" \").trim().replace(/[.!]+$/, \"\");\n if (oneLine.length === 0) return \"the connector refused without saying why\";\n return oneLine.length > 180 ? `${oneLine.slice(0, 179)}…` : oneLine;\n}\n\n/**\n * The absence a caller that CAUGHT something records. One call instead of two, so no site can\n * reach {@link targetsUnavailable} with a raw `err.message` the normaliser never saw.\n */\nexport function targetsUnavailableFrom(error: unknown): TargetSummary {\n return targetsUnavailable(scopeFailureDetail(error));\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════════════\n// ★ WHAT WAS PROMISED, AND WHAT WAS TOUCHED (docs/68)\n// ═══════════════════════════════════════════════════════════════════════════════════════\n//\n// Since docs/66 a scope is resolved TWICE, by two parties, at two different times: the PLAN\n// counts it when the operator validates and the approver approves, and the RUN counts it again\n// when it actually executes. For an approval-gated run those moments can be days apart, and a\n// customer's cloud changes in between.\n//\n// Both numbers were already recorded — the promise on `execution.target_summary`, the outcome\n// in the evidence bundle — and NOTHING SHOWED THEM TOGETHER. So the one question a governance\n// product exists to answer, *did the run act on what was approved?*, could not be asked on any\n// screen; it was reachable only by downloading a JSON manifest and comparing by eye.\n//\n// ─── ★ THIS IS A DERIVATION, NOT A COLUMN ──────────────────────────────────────────────\n//\n// The two summaries are stored; this sentence is not, and never will be — `poolNotice` is the\n// same decision on `runnerWait` (docs/61 §3.2). A stored sentence is a sentence that keeps\n// saying what it said when it was written, after the vocabulary underneath it has moved.\n//\n// ─── ★ AND IT IS A 2×2, NOT AN ORDERED CHAIN OF `if`s ──────────────────────────────────\n//\n// docs/57 §3 is the reason that is worth saying out loud: three independent axes were modelled\n// as one ordered `if (X === total)` chain there, and EIGHT pairs were decided by line order\n// rather than by anything anybody chose. The two axes here are *did the plan count* and *did\n// the run count*, they are genuinely independent, and all four cells are named below.\n\n/**\n * ═══ THE FOUR CELLS ════════════════════════════════════════════════════════════════════\n *\n * | | run counted | run did not count |\n * |------------------|---------------|-------------------|\n * | plan counted | matched/drifted | `unconfirmed` |\n * | plan did not | `unpromised` | `unpromised` |\n *\n * ★ THE TWO ABSENCES DO NOT COLLAPSE, and that is the whole point of having four names. A run\n * REFUSED before it ever reached `resolveScope` is `unconfirmed` — the plan promised a number\n * and the record cannot confirm it — which must never read as agreement (docs/68 §3.3). A run\n * whose plan never had a number is `unpromised`: nothing was approved, so nothing can have\n * departed from it, whatever the run went on to find.\n *\n * ★ WHY `unpromised` WINS THE BOTTOM ROW BY ARGUMENT AND NOT BY LINE ORDER. If nothing numeric\n * was approved, there is no promise for an outcome to be a departure from — so the outcome's\n * own presence or absence cannot change the answer. That is a property of the question, not of\n * which `if` happens to be written first.\n */\nexport const TARGET_COMPARISON_KINDS = [\n \"matched\",\n \"drifted\",\n \"unconfirmed\",\n \"unpromised\",\n] as const;\nexport type TargetComparisonKind = (typeof TARGET_COMPARISON_KINDS)[number];\n\n/**\n * What the plan promised set beside what the run touched.\n *\n * ★ IT CARRIES BOTH OPERANDS, NOT JUST A VERDICT. A bare enum would force every surface that\n * wants to say \"400 approved, 402 touched\" to go back to the two summaries and compose the\n * sentence itself — which is four surfaces composing four sentences, the exact defect docs/62\n * found three times in one evening. With the operands here, {@link targetComparisonSentence}\n * is the only thing that ever needs to read them.\n */\nexport type TargetComparison =\n | { kind: \"matched\"; promised: TargetCounts; touched: TargetCounts }\n | { kind: \"drifted\"; promised: TargetCounts; touched: TargetCounts }\n | { kind: \"unconfirmed\"; promised: TargetCounts; touched: UncountedTargets }\n | { kind: \"unpromised\"; promised: UncountedTargets; touched: TargetSummary };\n\n/**\n * ═══ THE ONE PLACE THE TWO NUMBERS ARE PUT SIDE BY SIDE ════════════════════════════════\n *\n * ⚠ DECIDED ON `eligible`, DELIBERATELY, AND THE OTHER TWO COUNTS ARE CARRIED BUT NOT COMPARED.\n * The question is *did the run act on what was approved*, and \"acted on\" is `eligible` — it is\n * the only one of the three any surface has ever rendered, and the only one an approver saw.\n * A plan of `{400, 40, 12}` and a run of `{400, 0, 0}` acted on exactly the 400 that were\n * approved; calling that \"drifted\" and then printing two identical numbers beside the word\n * would be a worse record than saying nothing. Both counts are on the value, so a later slice\n * can widen this without every caller changing.\n *\n * ⚠ NOTHING HERE REFUSES, ERRORS, OR BLOCKS (docs/68 §3.2). A cloud changes between approval\n * and execution; a run that touched 397 where 400 were approved is the single most useful thing\n * an auditor can learn from the record. {@link targetComparisonLevel} is typed so it cannot\n * even say `error`.\n */\nexport function compareTargets(\n promised: TargetSummary,\n touched: TargetSummary,\n): TargetComparison {\n if (promised.uncounted) return { kind: \"unpromised\", promised, touched };\n if (touched.uncounted) return { kind: \"unconfirmed\", promised, touched };\n return {\n kind: promised.eligible === touched.eligible ? \"matched\" : \"drifted\",\n promised,\n touched,\n };\n}\n\n/**\n * ═══ ONE SENTENCE, ONE AUTHOR (docs/68 §9.4) ═══════════════════════════════════════════\n *\n * The run record's notice and the feed row's marker both read this. Change the wording here and\n * both move; there is nowhere else the pair of summaries is turned into words, which\n * `targets-render-through-one-module.spec.ts` pins by grepping the call sites.\n *\n * ─── ★ WHY IT CAN RETURN `null`, AND WHEN ──────────────────────────────────────────────\n *\n * Two cases have nothing to say, and printing a sentence over either of them would be worse\n * than silence:\n *\n * · **The plan declared no scope.** `no_scope` is the Package Runner's answer, and it is\n * correct and permanent rather than degraded (docs/66 — which is why its check is `info`\n * and not a warning). Its run then resolves ONE invocation, and rendering that as \"the run\n * acted on 1 eligible target\" would put a customer-resource count on every package run\n * forever — the fabrication docs/66 §7 exists to end, reintroduced one layer up.\n * · **Neither side has a number.** Every row written before this slice is here, and so is\n * every run refused before either party counted. There is no comparison to report, and the\n * `Targets` tile already states the promise's own absence in its own words.\n */\nexport function targetComparisonSentence(comparison: TargetComparison): string | null {\n switch (comparison.kind) {\n case \"matched\":\n return `The run acted on what was approved — ${targetSummarySentence(comparison.promised)}.`;\n case \"drifted\":\n return (\n `Approved for ${targetSummarySentence(comparison.promised)}; ` +\n `the run acted on ${comparison.touched.eligible}.`\n );\n case \"unconfirmed\": {\n // The reason, in the words of whatever refused — the same raw `detail` that\n // `targetSummarySentence` embeds in ITS sentence. A different sentence about a different\n // subject (this one is about the RUN, not about a count in the abstract), quoting the\n // same datum: not a second author for either.\n const because = comparison.touched.detail ? ` — ${comparison.touched.detail}` : \"\";\n return (\n `Approved for ${targetSummarySentence(comparison.promised)}. ` +\n `The run did not record what it acted on${because}.`\n );\n }\n case \"unpromised\":\n if (comparison.promised.uncounted === \"no_scope\") return null;\n if (comparison.touched.uncounted) return null;\n return (\n \"No target count was approved for this run; \" +\n `it acted on ${targetSummarySentence(comparison.touched)}.`\n );\n }\n}\n\n/**\n * ═══ THE SHORT FORM, FOR A LIST ROW THAT HAS ONE LINE ══════════════════════════════════\n *\n * {@link targetSummaryLabel} is the same relationship to {@link targetSummarySentence}, in this\n * same file, for the same reason: a run record has room for a sentence and a feed row scanning\n * twenty-five runs has room for two words. Both come from here, so the list and the drawer\n * cannot word one run two ways — which they would, the first time somebody typed \"Drifted\" into\n * a `.tsx` because the sentence was too long for the row.\n *\n * ★ `null` FOR THE THREE QUIET KINDS, AND THAT IS A DECISION THIS FUNCTION OWNS RATHER THAN THE\n * LIST. `matched` is the expected case and marking every row buries the ones that matter — the\n * rule the actor chip already established on that row. `unconfirmed` is a run that ended before\n * it recorded anything, which the STATUS column beside it already says louder than a marker\n * could. `unpromised` is every package run and every row written before migration 0073, where\n * there is nothing to have drifted from. Only `drifted` is a fact the row cannot otherwise show.\n */\nexport function targetComparisonLabel(comparison: TargetComparison): string | null {\n return comparison.kind === \"drifted\" ? \"Targets drifted\" : null;\n}\n\n/**\n * How loudly a reader should be told, and it is NOT part of the sentence's job to decide —\n * `poolNotice` settled that shape for `runnerWait` (docs/61 §3.3): the tone belongs to the\n * function that knows what happened, not to the call site that renders it.\n *\n * ★ THE RETURN TYPE CANNOT SPELL `error`, AND THAT IS THE MECHANISM RATHER THAN A CONVENTION.\n * Every surface in this product blocks on `level === \"error\"` and only that. Narrowing\n * {@link CheckLevel} here is what makes docs/68 §3.2 — *drift never refuses* — a property of\n * the type instead of a rule four call sites have to remember.\n */\nexport function targetComparisonLevel(\n comparison: TargetComparison,\n): Exclude<CheckLevel, \"error\"> {\n return comparison.kind === \"drifted\" ? \"warn\" : \"info\";\n}\n","// Execution + Connections DTOs — shared verbatim between the API (execution /\n// connections modules) and apps/web (docs/04 §2.2, §2.3, docs/12 §9.1). Single\n// source of truth: no drift between the wizard and the server. No NestJS or Prisma\n// imports here — only closed value sets from ./enums and the catalog schema type.\nimport type {\n ActionCapabilities,\n ParameterSchema,\n RequiredPermission,\n WorkflowStep,\n} from \"./catalog\";\nimport { HOSTED_EXECUTION_LABEL } from \"./run-placement\";\nimport type { ConnectionRef } from \"./connections\";\nimport type {\n AmbiguousRoutingPlace,\n PlannedExecutionSiteDto,\n RunExecutionSiteDto,\n} from \"./execution-site\";\nimport type { PoolWaitWarningDto, RunnerWaitRecordDto } from \"./runner-pool-presence\";\nimport type { TargetSummary, ValidationCheck } from \"./validation\";\nimport type { TargetIdentities } from \"./target-identity\";\nimport type {\n Environment,\n ExecutionEventLevel,\n ExecutionEventType,\n ExecutionResult,\n ExecutionStatus,\n Provider,\n RiskLevel,\n RunTriggerKind,\n} from \"./enums\";\nimport type { ExecutionPlanGovernance } from \"./governance\";\nimport type {\n ChangeRecordCitation,\n ChangeRecordRef,\n ExecutionPlanChangeControl,\n} from \"./change-control\";\nimport type {\n ActionPackageUnrunnableDto,\n PackageProvenanceKind,\n TrialVersionDto,\n} from \"./packages\";\nimport {\n PACKAGE_PROVENANCE_CLAUSES,\n PACKAGE_PROVENANCE_LABELS,\n} from \"./packages\";\nimport {\n actionUnrunnableCopy,\n actionUnrunnableHeadline,\n actionUnrunnableRefusal,\n} from \"./packages\";\nimport { BRAND_SHORT_NAME } from \"./brand\";\nimport type { EngineVersionFacts } from \"./action-signing\";\n\n/**\n * The execution-oriented view of a pinned `action_version`, resolved by id through\n * `CatalogFacade.getVersionById` (docs/03 invariant: Execution reads the pinned\n * version through the facade, never the catalog tables directly). Carries the\n * `parameterSchema` Execution validates against, the parent definition's\n * `riskLevel` + `connectorKey`, and enough identity/display fields to persist and\n * render an execution.\n */\nexport interface ActionVersionContract {\n /** action_version.id (uuid) — the pinned version row. */\n id: string;\n /** action_definition.id (uuid). */\n actionDefinitionId: string;\n /** action_definition.key, e.g. \"azure.keyvault.rotateSecret\". */\n actionKey: string;\n /** action_definition.name, e.g. \"Rotate Key Vault Secret\". */\n actionName: string;\n /** Semver of this version, e.g. \"v2.1.0\". */\n version: string;\n /** External-system provider this action runs against, e.g. \"azure\". */\n provider: Provider;\n /** Which connector the engine will run (docs/02 §5.3). */\n connectorKey: string;\n /**\n * Rollback/dry-run/governance capabilities. A BUILT-IN's are inherited from the parent\n * definition; an ENGINE version's are its own, as it was published (docs/128 §17.2 D4a) — the\n * definition row describes the newest manifest, and an older pinned image keeps its rules.\n */\n capabilities: ActionCapabilities;\n /**\n * What an ENGINE version runs and who signed it (docs/128 §17.7) — `null` for a built-in. The\n * engine re-verifies `signature` before every validate, run and rollback.\n * ⚠ Server-side only: no HTTP response carries an `ActionVersionContract`.\n */\n engine: EngineVersionFacts | null;\n /** Inherited from the parent definition — drives policy + display. */\n riskLevel: RiskLevel;\n /** The pinned JSON Schema both FE rendering and BE validation key off. */\n parameterSchema: ParameterSchema;\n /** Declared Azure RBAC ceiling for pre-flight permission checks. */\n requiredPermissions: RequiredPermission[];\n /** Ordered \"what will happen\" steps — the declared plan-of-record for the approver. */\n workflow: WorkflowStep[];\n /** Published tenant-adoption override. Only populated by the submit-time gate. */\n adoptionRequiresApproval?: boolean | null;\n}\n\n/**\n * ═══ THE REFUSAL A STALE CALLER GETS, DECLARED ONCE ════════════════════════════════════\n *\n * Three routes took a scope id under the name `subscriptionId` and now take\n * `connectionScopeId`. A body carrying the old name is REFUSED rather than ignored, and the\n * sentence says which id is meant and where to get it.\n *\n * ★ REFUSED, NOT ACCEPTED-AS-AN-ALIAS. An alias would keep the trap armed: the whole defect was\n * a caller sending an `azure_subscription.id` under a name that reads like one, so a route that\n * went on accepting that name would go on accepting the wrong value. It would also silently\n * un-fix Rerun for any client that had not been rebuilt.\n *\n * ⚠ AND NOT LEFT AS \"connectionScopeId is required\" EITHER. That is what an unknown field\n * produces on its own, and it sends the reader to look for a field they are already sending.\n * Naming the rename is the difference between a five-minute fix and an afternoon.\n */\nexport const SUBSCRIPTION_ID_FIELD_RENAMED =\n \"`subscriptionId` is not accepted on this route. It named an `azure_subscription.id` while \" +\n \"this route has always resolved a `connection_scope.id`. The two were the same value while \" +\n \"one shim gave a scope the registry row's id; a scope discovered since has an id of its \" +\n \"own, and the registry id is either nobody's scope or another connector's. Send \" +\n \"`connectionScopeId` \" +\n \"— the value `ExecutionDto.connectionScopeId` reports for a run.\";\n\n/**\n * Body of `POST /executions` (docs/04 §2.3).\n *\n * ═══ IT IS A `connection_scope.id`, AND THE FIELD SAYS SO NOW ═══════════════════════════\n *\n * ⚠ IT WAS CALLED `subscriptionId` AND DOCUMENTED AS \"the azure_subscription.id\", AND BOTH\n * WERE WRONG. The server has resolved this value through `resolveExecutionScope` — a\n * `connection_scope` lookup — since docs/24 Slice 2. `azure_subscription` is the tenant-level REGISTRY — one row per subscription GUID per tenant,\n * and the table `execution.azure_subscription_id` points at. `connection_scope` is the\n * PER-CONNECTION binding — one row per (connection, subscription) — and its id is an\n * INDEPENDENT `gen_random_uuid()`, because `upsertDiscoveredSubscriptions` creates it by its own\n * natural key rather than by the shared registry PK. That change is the fix for cross-connector\n * scope stealing, and it is what made the two ids different things.\n *\n * ★ THEY WERE THE SAME VALUE FOR A LONG TIME, WHICH IS WHY THIS WAS INVISIBLE. The one-release\n * Azure shim gave a scope the registry row's id; MEASURED on the dev database, 263 of 267\n * `connection_scope` rows still have an id equal to some `azure_subscription` id. Every scope\n * created since is unrelated to any registry id.\n *\n * ★ THE RENAME IS THE FIX, NOT A TIDY-UP. `ExecutionDto` used to export the OTHER table's id\n * under this same name, so Rerun read `execution.subscriptionId` and posted it back here — and\n * on a subscription reachable by two connectors it resolved to whichever connector discovered\n * it FIRST. A successful run, on a connector nobody chose. Correcting only that caller would\n * have left a field named for one table carrying the other's id, and the next caller repeats\n * it; a rename makes passing the wrong id a compile error at every site.\n */\nexport interface CreateExecutionInput {\n /** The pinned action_version.id to run. */\n actionVersionId: string;\n /**\n * The `connection_scope.id` to run against — WHICH CONNECTOR'S view of a cloud scope, not\n * which cloud scope. One Azure subscription reachable by two connectors is one\n * `azure_subscription` row and two `connection_scope` rows, and this picks between them.\n */\n connectionScopeId: string;\n /** Validated server-side against the pinned `parameterSchema`. */\n parameters: Record<string, unknown>;\n /** Dry-run simulates without mutating (docs/02 §5.1). */\n dryRun: boolean;\n /**\n * An ALREADY-DECIDED approval this execution runs under, so it neither re-evaluates\n * policy nor opens a gate of its own. Set by an Operation run after ONE approval was\n * granted for the whole step; `execution.approval_request_id` and the `linkedExecution`\n * relation already model one approval to many executions.\n *\n * SERVER-TRUSTED, and refused over HTTP with a 400 that names the field (exactly as\n * `autoApprove` is on the start-run route). Accepting it from a client would let anyone\n * submit an execution claiming someone else's approval.\n */\n approvalRequestId?: string;\n /**\n * The risk level to GOVERN this run at, when the definition's own is not the accurate one.\n *\n * Set only by the trial-run path, where the code that runs is a draft's and the definition's\n * risk level belongs to the published version. Absent means \"use the definition's\", which is\n * every other run in the product.\n *\n * SERVER-TRUSTED for the same reason `approvalRequestId` is, and refused over HTTP by the\n * same parser: a caller who could name their own risk level could govern themselves down to\n * no approval at all. The one caller that sets it computes it with {@link maxRiskLevel}, so\n * it can only ever raise the bar.\n */\n riskLevel?: RiskLevel;\n /**\n * WHAT CAUSED THIS RUN (docs/45 §4.1). Absent means `manual`, which is what a person in\n * the run wizard is.\n *\n * Two in-process callers set it: the scheduler, which fires an action under its\n * schedule's standing authority, and the Operation run advance handler, which fires\n * children under the run's own provenance. Both already hold the facts — the columns\n * exist so an execution can KEEP them, rather than the reader inferring the cause from\n * an actor id that looks identical either way.\n *\n * SERVER-TRUSTED for the same reason `approvalRequestId` and `riskLevel` are, and refused\n * over HTTP by the same parsers: a caller who could stamp `triggerKind: \"schedule\"` and a\n * schedule name onto their own run could make a manual change to production read, in the\n * feed and in every screen that renders provenance, as routine automation.\n */\n trigger?: RunTrigger;\n /**\n * ═══ THE RECORD THIS RUN IMPLEMENTS (docs/83) ═══════════════════════════════════════\n *\n * ★ THE ONE OPTIONAL FIELD ON THIS INPUT THAT IS THE CALLER'S TO SUPPLY, and the contrast\n * with the three above it is the whole reason it is safe. `approvalRequestId`, `riskLevel`\n * and `trigger` are refused over HTTP because each of them LOWERS a bar: a caller naming\n * their own risk level chooses their own approval gate. This one can only ever raise one —\n * a run that names no record is refused by any rule that requires one, and a run that names\n * a record is refused unless the customer's own system of record says that record\n * authorizes it. There is no value an attacker can put here that admits a run Opera would\n * otherwise have refused.\n *\n * Absent means the operator named nothing, which is every run in a workspace with no\n * change-control rule, and a refusal in one that has a matching one.\n */\n changeRecord?: ChangeRecordRef;\n}\n\n/**\n * The trigger provenance an in-process caller carries into a run it starts.\n *\n * One object rather than three loose fields, so `scheduleName` without `scheduleId`, or\n * either without `kind: \"schedule\"`, is not a shape a caller can accidentally build.\n */\nexport interface RunTrigger {\n kind: RunTriggerKind;\n scheduleId?: string | null;\n scheduleName?: string | null;\n}\n\n/**\n * A validate RESULT is not an execution concept — `runners.ts` reports the same two shapes\n * for a run it executed itself, and importing this module to say so closed an import cycle\n * (see `validation.ts`). Declared there, re-exported here, so no importer moved.\n */\nexport type {\n CheckLevel,\n DecisionCheck,\n DecisionCode,\n OrdinaryCheck,\n RefusalCheck,\n RefusalCode,\n TargetComparison,\n TargetComparisonKind,\n TargetCountAbsence,\n TargetCounts,\n TargetSummary,\n UncountedTargets,\n ValidationCheck,\n} from \"./validation\";\n// The runtime half of the same vocabulary — the constructors, the two sentences and the parser.\n// Re-exported alongside the types for the same reason they are: no importer moved (docs/66 §3.1).\nexport {\n CHECK_LEVELS,\n DECISION_CODES,\n isCheckLevel,\n isDecisionCode,\n isRefusalCode,\n REFUSAL_CODES,\n compareTargets,\n eligibleTargetCount,\n isTargetCountAbsence,\n noTargetsResolved,\n scopeFailureDetail,\n singleTarget,\n TARGET_COMPARISON_KINDS,\n TARGET_COUNT_ABSENCES,\n TARGETS_NO_SCOPE,\n TARGETS_NOT_COUNTED,\n targetComparisonLabel,\n targetComparisonLevel,\n targetComparisonSentence,\n targetsUnavailable,\n targetsUnavailableFrom,\n targetSummaryLabel,\n targetSummaryOf,\n targetSummarySentence,\n targetsValidationCheck,\n validationCheckOf,\n} from \"./validation\";\n\n/**\n * An execution as returned by `POST /executions` and `GET /executions/{id}`\n * (docs/04 §2.3). The full row Execution owns — History (Step 6) reads more of it.\n */\nexport interface ExecutionDto {\n id: string;\n /** Human reference, e.g. \"OPS-4821\". */\n reference: string;\n status: ExecutionStatus;\n /** The run outcome — `pending` until the worker runs it (docs/05 §3.4). */\n result: ExecutionResult;\n riskLevel: RiskLevel;\n environment: Environment;\n dryRun: boolean;\n actionVersionId: string;\n /** Display fields resolved from the pinned action_version via CatalogFacade. */\n actionName: string;\n actionKey: string;\n /** Capability flags from the pinned action definition, used for generic UI affordances. */\n actionCapabilities: ActionCapabilities;\n /**\n * The `connection_scope.id` this run resolved — the id a RERUN must send back.\n *\n * ⚠ THIS FIELD USED TO BE `subscriptionId` AND CARRIED `execution.azure_subscription_id`,\n * which is a different table's key. It was replaced rather than renamed, because nothing\n * wanted the registry id: the only consumer in the product was Rerun, and Rerun wanted this.\n * A DTO that offered both would be a DTO that can still hand a caller the wrong one.\n *\n * `null` for a row written before docs/24 Slice 2, which recorded no scope. Rerun has nothing\n * to send for those and says so rather than guessing — see `execution-run-expansion.tsx`.\n */\n connectionScopeId: string | null;\n /**\n * THE RECORD THIS RUN NAMED (docs/83), or null when it named none — which is every run\n * submitted before this shipped, and every run in a workspace with no change-control rule.\n *\n * ★ IT IS THE REFERENCE, NOT A VERDICT. A verdict taken at submit would be stale by\n * dispatch, which is the whole reason the window is re-checked; what the row keeps is what\n * the operator named, so the record a run cited is recoverable for an auditor forever —\n * including for a run that was later refused because that record stopped authorizing it.\n *\n * ★ AND SINCE docs/84 IT CARRIES HOW THAT REFERENCE WAS ESTABLISHED, which is the one fact\n * about it that a later slice could not have added. `assurance` is written when the\n * reference is captured and raised only by a gate that really asked a system of record —\n * never derived at read time from whether a provider happens to be connected now. A\n * `ChangeRecordCitation` and not a `ChangeRecordRef` precisely so a screen cannot render the\n * reference and leave the reader to assume the check.\n */\n changeRecord: ChangeRecordCitation | null;\n /**\n * The connector this run leased its credential from, NAMED (docs/46 §3.3), or null\n * when it never resolved a scope.\n *\n * An execution has AT MOST one — `connection_scope_id` is a column, so the cardinality\n * is a fact of the schema, not a rendering choice. That is the same concept an Operation\n * run reports as a SET (`RunExpansionDto.connections`); both are read through the one\n * truth table in `run-connections.ts`, which is what stops \"1 connector\" and \"n\n * connectors\" being two renderings that can disagree.\n */\n connection: ConnectionRef | null;\n parameters: Record<string, unknown>;\n /**\n * ═══ WHAT WAS PROMISED (docs/66) ═════════════════════════════════════════════════════\n *\n * The count the PLAN took, at validate, and the value an approver said yes to. It does not\n * move afterwards — docs/66 §6 requires that the approver reading later sees the same value\n * the operator saw, not a recount that quietly disagrees because the cloud changed in\n * between. What the RUN found is {@link ExecutionDto.executedTargets}, beside it.\n */\n targetSummary: TargetSummary;\n /**\n * ═══ AND WHAT WAS TOUCHED (docs/68 §3.1) ═════════════════════════════════════════════\n *\n * The count the RUN resolved, recorded on the row the moment `resolveScope` answered. The\n * SAME type as the promise, including its three absences: a run whose scope call failed must\n * be able to say so, for exactly the reason a plan must (docs/66 §5 — `0/0/0` is a worse lie\n * than the `1` it replaced).\n *\n * ⚠ THE COMPARISON IS NOT HERE, AND NEVER WILL BE. `compareTargets` derives it at read time,\n * which is what stops the run record and the feed row wording one run two ways — the same\n * decision `runnerWait` records counts for and lets `poolNotice` word (docs/61 §3.2).\n *\n * ⚠ `{ uncounted: \"not_attempted\" }` FOR A RUN THAT NEVER GOT THAT FAR, and for every row\n * written before migration 0073. That is the absence of a write and says so; it must never\n * read as agreement with the promise (docs/68 §3.3).\n *\n * ⚠ NOT THE PROOF. `evidence_bundle` is append-only by charter §4.1 and carries the same\n * fact; this row is mutable and is the READABLE copy, not the authoritative one (docs/56 §6).\n */\n executedTargets: TargetSummary;\n /**\n * ═══ AND WHICH RESOURCES BOTH OF THOSE NUMBERS ARE ABOUT (docs/69 §3.1) ══════════════\n *\n * The two counts above say HOW MANY; these say WHICH. Two fields for two phases, never one\n * overwritten by the other, for the reason stated on `executedTargets` — what was promised and\n * what was touched are two facts (docs/68 §1).\n *\n * ⚠ `{ unnamed: \"not_attempted\" }` ON BOTH SIDES FOR EVERY ROW WRITTEN BEFORE docs/69, and for\n * every phase that has not resolved yet. That is the absence of a write and says so; it must\n * never read as \"this run acts on no resources\", and it must never read as \"the resource is\n * unknown to us\" — the run's own parameters are on the same screen (docs/69 §3.2).\n *\n * ⚠ THE DIFFERENCE IS NOT HERE, AND NEVER WILL BE. `compareTargetIdentities` derives it\n * wherever the pair is read, which is what stops two surfaces wording one run two ways — the\n * same decision `compareTargets` records for the counts.\n */\n targetIdentities: TargetIdentities;\n /**\n * ═══ WHERE THIS RUN EXECUTED (docs/56 §3.3) ══════════════════════════════════════════\n *\n * Recorded by the engine at the moment it chose, read from the ONE place it is stored, and\n * rendered by the run drawer, the History page and the trial drawer through the one\n * sentence in `execution-site.ts`. `{ site: \"unknown\" }` for every run that predates\n * migration 0064 — which is most of them, and which says so rather than defaulting to\n * \"Opera's cloud\".\n */\n executedOn: RunExecutionSiteDto;\n /**\n * ═══ WHY THIS RUN IS WAITING FOR A RUNNER (docs/61 §3.2) ═════════════════════════════\n *\n * The pool's COUNTS at a named instant, so a reader arriving at a stalled run learns why\n * without scrolling its log. The SENTENCE is not here and never will be: `poolNotice` —\n * the function the pool screen renders — derives it from `presence`, which is what makes\n * the run and that screen physically unable to word one pool two ways.\n *\n * ⚠ NULL ON EVERY HOSTED RUN, and that is a fact rather than an absence: a run that never\n * left Opera's worker was never offered to anybody. Also null for runs that predate\n * migration 0069.\n *\n * ⚠ IT OUTLIVES THE WAIT. The record is not cleared when a runner claims, because for a run\n * that was ABANDONED it is the most useful fact on the row and nothing can re-derive it\n * afterwards. Whether to SHOW it is the status's question, not this field's.\n */\n runnerWait: RunnerWaitRecordDto | null;\n /** ISO-8601 timestamp. */\n createdAt: string;\n /**\n * ISO-8601 timestamp set when a cancel was REQUESTED against a `running` execution,\n * else null. Cancellation is cooperative/async (the worker observes the request at\n * a safe checkpoint), so the status stays `running` until the worker settles; the UI\n * uses this flag to show a \"Cancellation requested…\" pending state.\n */\n cancelRequestedAt: string | null;\n /** ISO-8601 timestamp, or null until the run starts. */\n startedAt: string | null;\n /** ISO-8601 timestamp, or null until the run finishes. */\n finishedAt: string | null;\n /** DB-derived wall-clock duration, or null until finished. */\n durationMs: number | null;\n /** The linked `evidence_bundle.id`, or null until the worker writes evidence. */\n evidenceBundleId: string | null;\n /** The linked rollback evidence bundle id, or null until rollback reaches terminal state. */\n rollbackEvidenceBundleId: string | null;\n}\n\n/**\n * The write-once `evidence_bundle` a terminal run produces (docs/05 §3.4, docs/08\n * §2.3), as returned by `GET /executions/{id}/evidence`. The worker writes exactly\n * one per execution before/with the terminal state; History downloads it as JSON.\n * `contents` is the JSON manifest (resolved targets, outcome, event summary — no\n * secrets); `uri`/`sha256` are the store's pointer + integrity hash.\n */\nexport interface EvidenceBundleDto {\n executionId: string;\n /** The evidence store pointer, e.g. `pg://evidence/{tenant}/{execution}`. */\n uri: string;\n sha256: string;\n contents: Record<string, unknown>;\n /** ISO-8601 timestamp. */\n createdAt: string;\n}\n\n/**\n * One append-only `execution_event` (docs/05 §3.4) as History renders it. `seq` is\n * the per-execution ordering key, serialized as a JSON number (small in this MVP).\n */\nexport interface ExecutionEventDto {\n seq: number;\n type: ExecutionEventType;\n level: ExecutionEventLevel;\n message: string;\n data: Record<string, unknown>;\n /** ISO-8601 timestamp. */\n at: string;\n}\n\n/** Frames emitted by `GET /executions/{id}/events/stream` (REST + SSE, docs/04). */\nexport type ExecutionEventStreamFrame =\n | { kind: \"event\"; event: ExecutionEventDto }\n | { kind: \"heartbeat\" }\n | { kind: \"done\"; status: ExecutionStatus };\n\n/**\n * ═══ WHAT A RUN IS DOING WHILE ITS LOG STREAMS (docs/77 §3.1) ══════════════════════════\n *\n * ★ THE SENTENCE A DROPPED LOG SHOWS IS A FACT ABOUT THE RUN, AND ON 2026-09-08 IT WAS A\n * HARD-CODED GUESS. `OPS-4358` sat at `queued` for two hours while its log said *\"the run\n * itself is unaffected — it is running on the server\"*. It was not running: nothing was\n * consuming the queue. The component rendering that string HELD the status and never read it.\n *\n * That is this codebase's most-repeated defect — docs/57's pool notice asserted connectivity\n * it never checked, docs/65's panel asserted freshness it never re-read, docs/72's remedy\n * named a substrate it never asked about. The fix each time is the same: the words become a\n * function of the fact, and the fact becomes something the type will not let you skip.\n *\n * ─── WHY THE COPY LIVES HERE AND NOT IN THE COMPONENT ───────────────────────────────────\n *\n * Not because a second surface renders it — `one-log-renderer.spec.ts` proves exactly one\n * does. Because `no-sentence-copies.spec.ts` walks THIS package's exports and refuses a\n * re-typed copy anywhere in `apps/web/src`, `apps/api/src` or `packages/ui/src`. A sentence\n * authored inside the component is a sentence no guard can see being copied out of it.\n *\n * ⚠ THE PROSE IS IN THE RECORDS, DELIBERATELY, AND NOT INSIDE THE FUNCTION. That guard's own\n * stated limit is that prose living inside a function body is not in its corpus. Keeping\n * `executionLogStreamSentence` a pure JOIN of two published constants is what puts every word\n * below under the guard; moving one word into the template literal would quietly remove it.\n */\nexport const EXECUTION_LOG_ACTIVITIES = [\n \"executing\",\n \"queued\",\n \"awaiting_runner\",\n \"awaiting_approval\",\n] as const;\n/** What a run whose log is streaming is actually doing — never assumed to be \"executing\". */\nexport type ExecutionLogActivity = (typeof EXECUTION_LOG_ACTIVITIES)[number];\n\n/**\n * The two things a log can honestly say about a connection it has lost.\n *\n * ★ THEY ARE DIFFERENT PROMISES, WHICH IS WHY THERE ARE TWO. `reconnecting` says the reader\n * needs to do nothing; `stopped` says the client has exhausted its bounded retries and is\n * handing the decision back. Only the second may carry a button — a button offered beside\n * \"reconnecting on its own\" invites a person to fix something that is already being fixed.\n */\nexport const EXECUTION_LOG_STREAM_PHASES = [\"reconnecting\", \"stopped\"] as const;\nexport type ExecutionLogStreamPhase = (typeof EXECUTION_LOG_STREAM_PHASES)[number];\n\n/** What happened to the connection. Pinned to the phase union. */\nexport const EXECUTION_LOG_CONNECTION_PHRASE: Record<ExecutionLogStreamPhase, string> = {\n reconnecting: \"The live connection dropped, so this log has paused. It is reconnecting on its own.\",\n stopped:\n \"The live connection dropped and could not be restored, so this log has stopped updating.\",\n};\n\n/**\n * What the RUN is doing meanwhile. Pinned to the activity union, so a new activity is a\n * compile error here before it can reach a reader as silence.\n *\n * ⚠ EVERY PHRASE IS SEVEN WORDS OR LONGER ON PURPOSE. `no-sentence-copies.spec.ts` matches\n * seven-word windows; a shorter phrase would be invisible to it and could be re-typed into a\n * component without anything going red. If one of these is ever shortened, that guard stops\n * covering it and only a rendering assertion does.\n */\nexport const EXECUTION_LOG_ACTIVITY_PHRASE: Record<ExecutionLogActivity, string> = {\n executing: \"The run itself is unaffected — it is still executing on the server.\",\n // ★ THE ONE THAT WAS WRONG. A queued run has not started, and saying otherwise is what sent\n // the founder looking at a healthy-looking log for two hours instead of at a dead worker.\n queued: \"The run has not started yet — it is waiting in the queue to be picked up.\",\n awaiting_runner:\n \"The run has not started yet — it is waiting for one of your runners to pick it up.\",\n awaiting_approval:\n \"The run has not started yet — it is waiting for a person to approve it.\",\n};\n\n/**\n * The whole notice: what happened to the connection, then what the run is doing.\n *\n * Two axes, never collapsed — the connection can be reconnecting or given up independently of\n * whether the run is executing or waiting, and all eight cells are reachable and answerable.\n */\nexport function executionLogStreamSentence(\n phase: ExecutionLogStreamPhase,\n activity: ExecutionLogActivity,\n): string {\n return `${EXECUTION_LOG_CONNECTION_PHRASE[phase]} ${EXECUTION_LOG_ACTIVITY_PHRASE[activity]}`;\n}\n\n/** Result of `POST /executions/{id}/validate` (docs/04 §2.3). */\nexport interface ValidationResultDto {\n status: ExecutionStatus;\n targets: TargetSummary;\n checks: ValidationCheck[];\n}\n\n/** Result of `POST /executions/{id}/submit` — returns 202 (docs/04 §2.3). */\nexport interface SubmitExecutionResultDto {\n reference: string;\n status: ExecutionStatus;\n}\n\n/**\n * A no-side-effect \"what will happen\" preview of a run, returned by\n * `POST /executions/preview`. It resolves the pinned version, the chosen scope, and\n * the governance decision through the same facades `create`/`submit` use, but persists\n * nothing and enqueues nothing — a read-only Terraform-`plan`-style summary the wizard\n * shows on its Review step so the operator confirms the real, governed outcome (named\n * targets, approval gate, dry-run vs apply) before committing (docs/04 §2.3).\n *\n * Presentation (effect headline, named resources, workflow steps) is composed on the\n * client from the action detail it already holds; this DTO carries only the\n * server-authoritative facts the client cannot derive: the governance decision, the\n * resolved environment, connector runnability, and the resolved target counts.\n */\nexport interface ExecutionPlanDto {\n actionVersionId: string;\n /** Parent action_definition.id resolved with the pinned version. */\n actionDefinitionId: string;\n /** Server-authoritative — an `env` parameter can override the scope's environment. */\n environment: Environment;\n dryRun: boolean;\n /** Whether this action can run here — the same answer submit's authoritative gate uses. */\n runnable: boolean;\n /**\n * WHY it cannot, when it cannot; null when it can.\n *\n * A bare boolean was the whole problem: the Plan step could say \"not runnable\" and nothing\n * else, so an operator who reached it from a tab opened before an admin disconnected a Git\n * source had no way to learn what changed. The reason travels with the verdict.\n */\n unrunnable: ActionRunnabilityCause | null;\n /**\n * ═══ WHERE THIS RUN WILL EXECUTE (docs/56 §3.4) ══════════════════════════════════════\n *\n * The plan already carried the VERDICT (`runnable`) and, since docs/54, the REASON\n * (`unrunnable`). It did not carry the place — so an operator on the Review step, and an\n * approver about to say yes, could not tell whether execution was about to leave Opera's\n * cloud and run on machines the customer operates.\n *\n * ★ THIS IS THE HONEST ANSWER TO \"SHOULD AN OPERATOR PICK A POOL AT RUN TIME\" (docs/56\n * §3.5), and it is deliberately a statement rather than a control. Reachability is a\n * property of the TARGET, not of the person clicking: someone who can choose the pool can\n * choose the wrong one at 2am, and the failure looks like a permissions problem rather\n * than a routing mistake. A human should SEE where a run will execute and be able to\n * refuse it — not choose it.\n *\n * Read from the same `poolForConnectionScope` the engine will read (docs/49 §4.3), so the\n * plan and the run cannot disagree about anything except an admin rebinding the connection\n * in between — which the RECORD then reports, because that is what a record is for.\n */\n executesOn: PlannedExecutionSiteDto;\n /**\n * ═══ …AND WHETHER ANYTHING THERE CAN TAKE IT RIGHT NOW (docs/57 §3.3) ════════════════\n *\n * ★ A SECOND FIELD, BECAUSE A POOL'S REACH AND ITS LIVENESS ARE TWO FACTS. `executesOn`\n * says WHERE the run goes and is stable — it changes only when an admin rebinds. This says\n * whether anything there is awake, and it is true for as long as a container takes to\n * restart. Folding the second into the first would make \"runs on pool asia-vnet\" a value\n * that flickers, and a reader could not tell which half had changed.\n *\n * ★★ AND IT IS NOT AN `ActionRunnabilityCause`. The run is runnable; it will be accepted\n * and it will wait. `runnable` stays `true` and `unrunnable` stays `null` when this is set\n * — asserted, so a restarting runner can never make an action read as structurally\n * unrunnable in the catalog.\n *\n * `null` for a hosted run, and for a pool with a runner able to take work.\n */\n runnerWait: PoolWaitWarningDto | null;\n /**\n * ═══ …AND WHAT WILL EXECUTE (docs/59 §3.3) ═══════════════════════════════════════════\n *\n * The provenance of the action's package, or `null` when this run executes no package at all\n * — an ordinary built-in action, which is most runs.\n *\n * ★★ ITS OWN FIELD, NOT A MEMBER OF `executesOn`, AND THE SEPARATION IS THE DECISION\n * (docs/59 judgement 2). `PlannedExecutionSiteDto` is a union over DESTINATIONS —\n * hosted / runner / ambiguous — and provenance is orthogonal to every one of them: a hosted\n * run has a provenance too, and an ambiguous one has a provenance it never gets to use.\n * Folding it into the `runner` member would make the fact expressible in exactly one of three\n * places it is true, which is charter §4.2's orthogonal-facts rule and the same argument\n * `runnerWait` won one field above: a pool's REACH and its LIVENESS are two facts, and so are\n * WHERE a run goes and WHAT it runs.\n *\n * ★ AND IT IS A STATEMENT, NEVER A REFUSAL. A run refused for provenance says so through\n * `unrunnable`, in the vocabulary every surface already fails closed on. This field is set on\n * runs that are going ahead — which is the case docs/59 §3.3 asks for, because a plan that\n * mentions provenance only when it refuses would leave an approver reading a green plan with\n * no idea whose code is about to run on their machines.\n *\n * ⚠ `null` MEANS \"NO PACKAGE\", AND ONLY THAT. It is not \"we did not look\": every caller that\n * builds a plan resolves this through the same `plannedProvenance` the runnability gate used,\n * so the plan and the verdict beneath it read one value. A package-backed action whose\n * package row could not be read is refused rather than planned, so it never reaches here.\n */\n packageProvenance: PackageProvenanceKind | null;\n /**\n * ═══ WHAT THIS RUN WILL ACT ON — COUNTED, OR HONESTLY ABSENT (docs/66 §3.1) ═══════════\n *\n * ★ IT IS THE VALUE `validate` PERSISTS, not a second opinion. The operator reads it before\n * approving and the run record renders the same value forever, which is what makes the count\n * an approver sees the count that was taken. It was a literal `1` until docs/66 — \"stub\n * resolution today; real pre-flight enriches later\" is what this comment said while it was.\n *\n * ⚠ AN ABSENCE HERE NEVER MAKES A PLAN UN-RUNNABLE. `runnable` above is untouched by it:\n * docs/57 §3.3's precedent, restated by docs/66 §3.2 — an operator may knowingly proceed\n * against an uncounted scope; what they may not do is proceed against a fabricated one.\n */\n targets: TargetSummary;\n governance: ExecutionPlanGovernance;\n /**\n * ═══ …AND WHETHER THIS RUN MUST NAME A CHANGE RECORD (docs/83 §4) ════════════════════\n *\n * The requirement the plan can SEE COMING, stated while the operator can still act on it.\n * Null when no `change_control` rule matches, which is every run in a workspace that has\n * written none.\n *\n * ★ A STATEMENT, NEVER A REFUSAL, and NOT an `ActionRunnabilityCause`. `runnable` stays\n * `true` and `unrunnable` stays `null` when this is set — see\n * {@link ExecutionPlanChangeControl} for both halves of why, and §4 for the catalog-badge\n * defect (docs/54) that answering a run-gate question in a cacheable capability fact\n * produced last time.\n *\n * ⚠ AND IT IS NOT THE DECISION. The plan states the requirement; the gate at submit\n * resolves the named record, and the gate at DISPATCH resolves it again, because a change\n * approved for 02:00–04:00 must not run at 05:00 because submit happened at 03:59.\n */\n changeControl: ExecutionPlanChangeControl | null;\n /**\n * Pre-flight checks: parameter validation, runnability, the scope count — and, for a connector\n * that declares `plannedChecks: \"validate\"`, the connector's own (docs/126 §3).\n *\n * ★ THE CONNECTOR'S CHECKS ARE WHERE THE DECISIONS ARE. A DECIDE check carries a `decision`\n * code; the requester acknowledges each one, and the submit carries those codes back for the\n * server to compare against the checks it runs again. An `error` here — a REFUSE among them —\n * blocks the run on every surface, exactly as before.\n */\n checks: ValidationCheck[];\n /**\n * ═══ WHAT THE CONNECTOR CHECKED ABOUT THE RESOURCE, FOR THE PERSON DECIDING (docs/126 §3) ═══\n *\n * The connector's own checks — its facts, warnings, DECIDE questions and REFUSE refusals —\n * exactly as it returned them, or `null` for a connector that plans none (every action before\n * docs/126). The SAME values are in `checks`, which is what every gate reads; this is that list\n * kept apart from the platform's own lines (\"Parameters valid…\", \"Scope resolved…\") so the Plan\n * step can show the requester what was checked about THIS resource — the list the approver\n * will later read back as facts, warnings and decisions. Asked once, read twice.\n */\n preflight: ValidationCheck[] | null;\n}\n\n/**\n * Runtime connector availability exposed by Execution. Catalog owns connectorKey\n * declarations; Execution owns the registry of keys that can actually run.\n *\n * A pure projection of the in-process registry, so it costs nothing and every caller may\n * read it per request. It is NOT the whole answer to \"can this action run\": every\n * package-backed action projects onto the one package-runner key, so this set says\n * yes to all of them regardless of trust or runtime kind. Ask\n * `ExecutionFacade.actionRunnability` for one action; this remains the cheap fleet-wide\n * projection the catalog composes with connector keys it already holds.\n */\nexport interface RunnableConnectorKeysDto {\n connectorKeys: string[];\n}\n\n/**\n * WHY execution refuses to run one action version. TWO FACTS, deliberately not collapsed:\n *\n * - `connector_unregistered` — this deployment has no connector for the action's\n * `connectorKey` at all. Nothing about the action is wrong; the engine cannot dispatch it.\n * - `package` — the connector is registered (it is the package runner), but this\n * deployment cannot run the action's PACKAGE, for one of the `ActionUnrunnableDetailDto`\n * reasons. The fix is a Git source or an allowlist, never a connector.\n * - `runner_pool` — nothing is wrong with the action OR the deployment. This RUN's connection\n * executes on a private runner, and an action package may not execute there (docs/54). It is\n * the only member that depends on the connection rather than the action, which is why it\n * carries the pool name and no package identity: the same action is perfectly runnable\n * through a connection that is not pool-bound.\n *\n * Collapsing them would put \"this action is not yet available to run\" in front of someone\n * whose Git source was disconnected an hour ago — which is the wrong-cause lie the reason\n * vocabulary exists to remove.\n *\n * - `catalog_blocked` — nothing is wrong with the action, the deployment or the connection.\n * THIS WORKSPACE's administrators have not permitted this global action (docs/112). It is\n * the one PERMISSION among capabilities, which is why the oracle asks it first.\n */\nexport type ActionRunnabilityCause =\n | {\n /**\n * ═══ THIS WORKSPACE DOES NOT PERMIT THIS ACTION (docs/112) ═══════════════════════\n *\n * ★ ASKED FIRST, BEFORE EVERY CAPABILITY. Told \"the connector is not registered\" an\n * operator files a bug against us; told \"this workspace does not permit this action\"\n * they talk to their administrator, which is the true and actionable sentence — and\n * answering a capability question first would describe the deployment to somebody who\n * has been told they may not use the thing at all.\n *\n * No payload: the sentence is constant and the action's name is already on the screen\n * that renders it.\n */\n kind: \"catalog_blocked\";\n }\n | { kind: \"connector_unregistered\"; connectorKey: string }\n | ({ kind: \"package\" } & ActionPackageUnrunnableDto)\n | {\n kind: \"runner_pool\";\n poolName: string;\n /**\n * WHICH provenance was refused. `null` is a package whose provenance could not be\n * resolved at all — a `package_version` row that has gone missing under a live action\n * version — and it REFUSES like any other, because a pool cannot have consented to a\n * provenance nobody could name (docs/59 §3.4).\n */\n provenance: PackageProvenanceKind | null;\n /** What this pool DOES accept, so the remedy is a choice rather than a dead end. */\n accepts: readonly PackageProvenanceKind[];\n }\n | {\n /**\n * ═══ THE RUNNER IMAGE DOES NOT CARRY THE CODE THIS RUN NEEDS (docs/59 follow-up) ══\n *\n * ★ A CAPABILITY, WHERE `runner_pool` IS A PERMISSION, AND THEY ARE NOT ONE AXIS.\n * `runner_pool` says the pool's owner has not vouched — an admin can change it, and\n * docs/59 exists so they can. This one says nothing on the runner can execute this\n * action's code at all, which no amount of vouching alters. Collapsing them would put\n * \"an administrator can accept this provenance\" in front of somebody for whom accepting\n * it changes nothing — the wrong-cause lie this vocabulary exists to remove, in the one\n * direction where the wrong remedy is also an instruction to grant a permission.\n *\n * ⚠ IT IS ASKED AFTER CONSENT, NOT BEFORE. A pool that has vouched for nothing is the\n * state of every pool in the product, and \"you have not vouched\" is the true and\n * actionable sentence for it. This member is what the reader gets once they HAVE\n * vouched — the person who needs to know, at the moment the answer is theirs to act on.\n *\n * MEASURED, not inferred: the step image's registry is {@link builtInConnectors} and\n * resolving the package-runner key against it raises `UnknownConnectorError`. The step\n * container also holds no control-plane address, so it could not fetch a package's bytes\n * even if it could name a connector for them.\n */\n kind: \"runner_image\";\n poolName: string;\n /**\n * WHICH connector the image does not carry. Deliberately never printed — a connector\n * key is an internal identifier, and rendering one is the class-name trap this codebase\n * has already paid for. It is carried because it decides WHICH sentence: \"your code,\n * which a runner cannot fetch\" and \"our code, which this image was not built with\" are\n * two different absences with two different owners.\n */\n connectorKey: string;\n }\n | {\n /**\n * ═══ THE POOL CANNOT CONFINE THIS PACKAGE'S EGRESS (docs/70 §3.3) ═════════════════\n *\n * ★ A SECOND CAPABILITY, AND THE ARGUMENT IS THE ONE ABOVE IT, RUN AGAIN. `runner_image`\n * says the runner cannot EXECUTE this code. This one says a runner can execute it\n * perfectly well and the substrate cannot CONTAIN it: the package declares an egress\n * allowlist, and the pool's runners measured that undeclared outbound traffic is not\n * stopped where they run — a Kubernetes cluster whose CNI does not enforce NetworkPolicy,\n * most often, which is off by default on EKS with the VPC CNI.\n *\n * ⚠ IT IS A CAPABILITY AND NOT `runner_pool`, WHICH IS THE DECISION THIS MEMBER EXISTS TO\n * RECORD. The test is the one stated above: `runner_pool` is a PERMISSION — *\"the pool's\n * owner has not vouched — an admin can change it, and docs/59 exists so they can.\"* No\n * amount of vouching installs a CNI. An administrator who accepted this package's\n * provenance on this pool would change nothing at all about whether the traffic is\n * stopped, which is precisely the damage the comment above names: *\"Collapsing them would\n * put 'an administrator can accept this provenance' in front of somebody for whom\n * accepting it changes nothing — the wrong-cause lie this vocabulary exists to remove, in\n * the one direction where the wrong remedy is also an instruction to grant a\n * permission.\"* Refusing here on `runner_pool` would be exactly that sentence, in exactly\n * that direction. `runner-egress-refusal.spec.ts` asserts the remedy names no permission.\n *\n * ★★ AND IT IS A NEW MEMBER RATHER THAN `runner_image`, THOUGH BOTH ARE CAPABILITIES.\n * They differ in what a reader must do and in who owns it: `runner_image` is OUR artifact\n * and its remedy is to install a runner build that carries the connector. This one is the\n * customer's own cluster, and its remedy is a CNI that enforces policy — or routing the\n * package somewhere else. One sentence cannot carry both without naming a limit whose\n * owner the reader has to guess.\n *\n * ⚠ WHY REFUSE RATHER THAN DOWNGRADE TO `cooperative`. Container Apps runs these packages\n * today and honestly discloses `cooperative`, so the precedent for degrading exists. It\n * does not transfer: `ISOLATION_EGRESS_MODE.runner` is `enforced`, keyed by ISOLATION, and\n * making it vary per installation would make `enforced` mean \"enforced, unless\" — which\n * `EGRESS_MODES`' own comment forbids in as many words, *\"a control that is weaker than it\n * appears is worse than no control, because someone will rely on it.\"* So the word keeps\n * one meaning and the run that could not have it does not happen.\n */\n kind: \"runner_egress\";\n poolName: string;\n /** How many of the pool's runners can confine, out of how many could take this work. */\n confinedRunners: number;\n totalRunners: number;\n }\n | { kind: \"runner_pool_ambiguous\"; places: readonly AmbiguousRoutingPlace[] };\n\n\n/**\n * ═══ THE SAME CLOSED SET, DECLARED (charter §4.2) ══════════════════════════════════════\n *\n * This union was a BARE one for two quarters, and that is precisely how `runner_pool` was\n * added by docs/54 without a single consumer noticing: a reader that matched one literal\n * (`unrunnable?.kind === \"package\"`) kept compiling, kept returning `null` for the new member,\n * and the run wizard read that `null` as \"runnable\". An operator reached the final step and\n * was offered Run on an action the server had already decided it would refuse.\n *\n * ★ IT IS A `Record<…, true>` AND NOT A BARE `[…] as const`, WHICH IS WHAT IT BEATS. An array\n * literal pins nothing: `[\"package\"] as const` compiles perfectly beside a three-member union,\n * so the declaration itself could go stale and the next reader would trust it. `satisfies\n * Record<ActionRunnabilityCause[\"kind\"], true>` is checked in BOTH directions — a member added\n * to the union without a key here is a missing-property error, and a key here that no member\n * declares is an excess-property error. The array is then DERIVED, so the two spellings of this\n * vocabulary cannot drift apart at all rather than merely being expected not to.\n *\n * What it buys, concretely: a test can enumerate every member (rather than the three somebody\n * remembered), and a `Record<ActionRunnabilityCauseKind, …>` in any consumer goes red the day a\n * fourth member lands — which is the moment somebody is actually in a position to answer what\n * the new cause should do.\n */\nconst ACTION_RUNNABILITY_CAUSE_KIND_SET = {\n catalog_blocked: true,\n connector_unregistered: true,\n package: true,\n runner_pool: true,\n runner_image: true,\n runner_egress: true,\n runner_pool_ambiguous: true,\n} as const satisfies Record<ActionRunnabilityCause[\"kind\"], true>;\n\n/** Read straight off the union, so the NAME of a kind can never be a second spelling of it. */\nexport type ActionRunnabilityCauseKind = ActionRunnabilityCause[\"kind\"];\n\nexport const ACTION_RUNNABILITY_CAUSE_KINDS = Object.keys(\n ACTION_RUNNABILITY_CAUSE_KIND_SET,\n) as readonly ActionRunnabilityCauseKind[];\n\n/**\n * The ONE answer to \"can this action version run here\", produced by Execution — the module\n * that owns the enqueue gate — and consumed by every surface that has to agree with it:\n * `POST /executions/preview`, `validate`, `submit`, and the Operation verification sweep.\n *\n * Execution combines two things it already reaches and re-implements neither: its own\n * connector registry, and — only for a package-backed action — the packages classifier the\n * catalog reports from. A second implementation of this question is exactly how the catalog\n * came to say **Available** for an action the run path refused.\n */\nexport type ActionRunnabilityDto =\n | { runnable: true }\n | { runnable: false; cause: ActionRunnabilityCause };\n\n/**\n * What a registered-but-unavailable connector says. Unchanged wording: it is a genuine\n * \"we have not built this yet\", and it is still the right sentence for that fact alone.\n */\nexport const CONNECTOR_UNAVAILABLE_MESSAGE = \"This action is not yet available to run.\";\n\n/**\n * ═══ WHY THIS WORKSPACE WILL NOT START AN ACTION, WRITTEN ONCE (docs/112 §5.3) ══════════\n *\n * A cause clause and a remedy clause, for the reason {@link runnerPoolClauses} gives: the plan,\n * the catalog detail, the verification check and the submit refusal must name the same fact.\n *\n * ★ THE CAUSE IS SCOPED TO THIS WORKSPACE, and it has to be. \"This action is unavailable\" would\n * read as broken, or as withdrawn for everybody — and the same action runs in every workspace\n * that has not blocked it. ★ THE REMEDY NAMES A PERSON, because no screen, retry or connection\n * changes this answer: an administrator of this workspace does.\n */\nconst CATALOG_BLOCKED_CAUSE = \"This workspace does not permit this action.\";\nconst CATALOG_BLOCKED_REMEDY =\n \"An administrator of this workspace decides which catalog actions may run here, and can allow it.\";\n\n/**\n * The reader-facing sentence for a refusal, for surfaces that describe the ACTION — the\n * catalog badge and the run wizard's Plan step. The package branch is the catalog's own\n * copy, verbatim, so the badge and the plan cannot name different causes for the same fact.\n */\nexport function actionRunnabilityCopy(cause: ActionRunnabilityCause): string {\n switch (cause.kind) {\n case \"catalog_blocked\":\n return `${CATALOG_BLOCKED_CAUSE} ${CATALOG_BLOCKED_REMEDY}`;\n case \"package\":\n return actionUnrunnableCopy(cause.detail);\n case \"runner_pool\": {\n const { cause: why, remedy } = runnerPoolClauses(cause);\n return `This action's package ${why} ${remedy}`;\n }\n case \"runner_image\": {\n const { cause: why, remedy } = runnerImageClauses(cause);\n return `${why} ${remedy}`;\n }\n case \"runner_egress\": {\n const { cause: why, remedy } = runnerEgressClauses(cause);\n return `${why} ${remedy}`;\n }\n case \"runner_pool_ambiguous\":\n return `This run's resources do not all execute in the same place: ${describeRoutingPlaces(cause.places)}. ${AMBIGUOUS_ROUTING_REMEDY}`;\n case \"connector_unregistered\":\n return CONNECTOR_UNAVAILABLE_MESSAGE;\n }\n}\n\n/**\n * ═══ WHY A RUN THAT SPANS TWO POOLS IS REFUSED RATHER THAN SPLIT (docs/58 §3.3) ═════════\n *\n * Written once, beside the cause, for the reason {@link runnerPoolClauses} is: the plan's\n * sentence and the run path's refusal must name the same fact, and two hand-written copies of\n * a routing refusal drift.\n *\n * ★ IT NAMES BOTH DESTINATIONS AND A WITNESS RESOURCE FOR EACH, so an operator can check the\n * claim against their own estate rather than take it on trust — the same posture\n * `describeSelector` takes when a fan-out refuses.\n *\n * ★ AND THE REMEDY IS REAL. \"Narrow the targets and run each group separately\" is something\n * the reader can do today. Three reasons the run is not simply split, in order of weight:\n * `execution.executed_pool_id` is ONE column, so a split run writes a lie in the record; an\n * approver is shown ONE sentence about where a run executes, and docs/56 exists so it is not\n * \"partly in Frankfurt and partly in Singapore\"; and running twice is recoverable where a\n * silently split run is not.\n */\nconst AMBIGUOUS_ROUTING_REMEDY =\n \"Nothing was started — a run is recorded as having executed in ONE place, and splitting it \" +\n \"would make that record untrue. Narrow the targets so they route together, and run each \" +\n \"group separately.\";\n\nfunction describeRoutingPlaces(places: readonly AmbiguousRoutingPlace[]): string {\n return places\n .map((place) => {\n const where = place.poolName ? `runner pool “${place.poolName}”` : HOSTED_EXECUTION_LABEL;\n // WHY it went there, because the destination alone does not tell an admin which row to\n // edit — and a rule name is rendered nowhere in this product without its criteria or,\n // as here, without the resource that proves it matched.\n const why = place.ruleName\n ? `the rule “${place.ruleName}”`\n : \"this connection's default\";\n return `${place.targetCount} via ${why} → ${where} (for example ${place.exampleResourceId})`;\n })\n .join(\"; \");\n}\n\n/**\n * ═══ WHY AN ACTION PACKAGE DOES NOT RUN ON A PRIVATE RUNNER (docs/54) ═══════════════════\n *\n * Written ONCE, as a cause clause and a remedy clause, for the same reason\n * `unrunnableClauses` is: the catalog-shaped sentence and the run-path refusal must name the\n * same fact, and two hand-written copies of a security sentence drift.\n *\n * ★ THE CAUSE IS A MEASUREMENT, NOT A ROADMAP. It used to read \"cannot execute on a private\n * runner YET\", which names no cause, offers no remedy, and reads as a feature nobody has got\n * to. What was actually measured (docs/54 §2, re-measured 2026-08-21) is that a runner's step\n * container is an ordinary container: `/proc/self/uid_map` inside it is the identity map\n * `0 0 4294967295`, so its root IS the host's root, and with no `--network` flag it answered\n * HTTP 200 from both the public internet and the host's own LAN gateway. That is a substrate\n * that confines nothing, sitting inside the customer's trusted network — which is exactly the\n * combination an action package must not be handed.\n *\n * ★ AND IT IS NOT A DEAD END. The remedy says what DOES run in that pool, because the reader\n * is an operator whose run just refused and whose next question is \"then how do I do this\".\n */\nfunction runnerPoolClauses(\n cause: Extract<ActionRunnabilityCause, { kind: \"runner_pool\" }>,\n): { cause: string; remedy: string } {\n const provenance = cause.provenance\n ? `is ${PACKAGE_PROVENANCE_CLAUSES[cause.provenance]}`\n : // The row that would say is gone. Named as an absence rather than guessed at, because\n // every other value this sentence could take is a claim about where bytes came from.\n \"has no recorded provenance\";\n return {\n /*\n * ⚠ THE SECOND HALF OF THIS SENTENCE CHANGED IN docs/60, AND THE FIRST HALF DID NOT. It\n * used to end \"a runner executes a step in an ordinary container that shares its host's\n * kernel and reaches everything that host can reach\" — which described a STEP, correctly,\n * and was borrowed to describe a PACKAGE. A package no longer runs in a step container: it\n * gets one of its own, on a Docker network with no gateway, whose only occupant besides it\n * is a broker holding its declared allowlist.\n *\n * ★ WHAT SURVIVES IS WHAT MAKES CONSENT A REAL DECISION. Confinement narrowed what the code\n * can reach; it did not change whose machine it runs on, whose kernel it shares, or whose\n * credential it acts with. A refusal that dropped those would be telling an admin the\n * decision no longer matters.\n */\n cause:\n `${provenance}, and would run on the private runner pool \"${cause.poolName}\", because ` +\n \"that is where runs using this connection execute — on a machine you own, in a container \" +\n \"that shares its host's kernel and acts with this connection's credential.\",\n remedy: `${acceptedClause(cause.accepts)} ${POOL_CONSENT_REMEDY}`,\n };\n}\n\n/**\n * ═══ WHAT THIS POOL HAS ACTUALLY VOUCHED FOR — INCLUDING WHEN THE ANSWER IS NOTHING ═════\n *\n * ★ THE EMPTY CASE IS THE COMMON ONE AND IT GETS ITS OWN SENTENCE. Every pool alive on the\n * day docs/59 ships accepts nothing, so \"This pool accepts: \" followed by a blank would be the\n * sentence most readers see. An empty list rendered as an absence is the `(none)` rule one\n * level up: a reader must never be shown a gap where a value goes and left to infer.\n */\nfunction acceptedClause(accepts: readonly PackageProvenanceKind[]): string {\n if (accepts.length === 0) {\n return \"This pool does not accept action packages of any provenance.\";\n }\n const labels = accepts.map((kind) => `“${PACKAGE_PROVENANCE_LABELS[kind]}”`);\n return `This pool accepts ${joinWithAnd(labels)}, but not this package's provenance.`;\n}\n\nfunction joinWithAnd(parts: readonly string[]): string {\n if (parts.length <= 1) return parts[0] ?? \"\";\n return `${parts.slice(0, -1).join(\", \")} and ${parts[parts.length - 1]}`;\n}\n\n/**\n * ═══ THE REMEDY, AND WHY IT NAMES A PERSON RATHER THAN A WORKAROUND (docs/59 §3.4) ══════\n *\n * ★ IT REPLACED \"an action package has to run through a connection that is not bound to one\",\n * which was TRUE and useless. docs/58 had already made it incomplete — routing is now decided\n * per resource, so \"not bound to one\" is not a property of a connection an operator can go and\n * check. Worse, it described the BYPASS: fork the package into your own Git source, or run it\n * from cron, and the identical bytes execute on the identical host with no approval gate and no\n * run record. A refusal whose remedy is \"route around me\" is friction, not a control.\n *\n * ★ AND IT DOES NOT SAY \"ASK OPERA\". The decision is not Opera's to make and the sentence must\n * not imply that it is: the host, the network and the credential belong to the customer, so the\n * person who can change this is their own admin. Naming the screen is what makes that\n * actionable — the reader who was refused is usually not that person, and \"an admin can\" tells\n * them who to go to.\n */\n/**\n * ═══ WHY A POOL'S CONSENT MAY STILL CHANGE NOTHING — DECLARED ONCE, FOR TWO READERS ═════\n *\n * ⚠ IT REPLACES `RUNNER_STEP_IMAGE_RUNS_NO_PACKAGE`, WHICH BECAME FALSE (docs/60). That\n * sentence said \"no action package executes on a runner\", full stop, and it was true for\n * exactly as long as a runner had nowhere to execute one. A package now runs in a container of\n * its own that the dispatcher starts, on a network with no gateway, so the old sentence\n * described a product that no longer exists. It was DELETED rather than reworded, because a\n * permanent-limit sentence and a deployment-configuration sentence are different facts with\n * different remedies, and rewording one into the other is how a refusal comes to name a cause\n * nobody can act on.\n *\n * ★ WHAT IS LEFT IS CONDITIONAL AND SAYS WHAT TO DO. A deployment pins the package runtime\n * image its runners install with; until it does, a runner in this pool runs built-in actions\n * and nothing else, and accepting a provenance is a real decision whose effect is still ahead\n * of it. The panel renders this ONLY when the served install facts carry no package image —\n * `reachable-and-false rather than always-true`, which is the whole shape docs/60 §3.6 asks\n * for.\n *\n * ★★ IT IS A COMPLETE, SELF-TERMINATING SENTENCE, AND THAT IS DELIBERATE. This panel has\n * already shipped the splice defect once: a clause written to complete \"Code …\" was pasted\n * mid-sentence elsewhere and rendered as \"…nobody vouched for it when it was imported. will\n * run on every runner in this pool\" — two broken sentences, invisible to every substring\n * assertion in the suite and visible only in a browser. A shared string that ends in a full\n * stop can be PLACED by a reader rather than spliced into one.\n *\n * ⚠ PRESENT TENSE, WITH NO \"YET\" AND NO \"TODAY\", for the reason docs/54 established: a\n * sentence that describes itself as temporary invites the reader to treat it as a queue\n * position rather than as the state of the thing. What is true is stated; the remedy is named\n * because there is one.\n */\nexport const RUNNER_PACKAGE_RUNTIME_NOT_PINNED =\n \"This deployment has not pinned a package runtime image, so its runners are installed \" +\n \"without one and no action package can execute on a runner here.\";\n\n/**\n * ★ WHAT ACCEPTING A PROVENANCE DECIDES, AND WHAT IT DOES NOT. The second half of the same\n * fact, split out because the two readers need it in opposite orders: the refusal leads with\n * the capability and closes with this, while the consent screen leads with the decision the\n * admin is making. One string, placed twice, rather than two strings that agree today.\n */\nexport const ACCEPTING_A_PROVENANCE_IS_NOT_A_CAPABILITY =\n \"Accepting a provenance decides WHOSE code may run on your machines; it does not decide \" +\n \"whether a runner is able to run it.\";\n\n/**\n * ═══ WHAT A RUNNER'S STEP IMAGE ACTUALLY CARRIES, AS A SENTENCE (docs/59 follow-up) ═════\n *\n * ★ THE CAUSE IS A MEASUREMENT AND NOT AN OPINION, exactly as {@link runnerPoolClauses}'s is.\n * The step image's connector registry is `builtInConnectors()`; resolving\n * the package-runner key against it raises `UnknownConnectorError`, and the container it runs\n * in holds no control-plane address with which to fetch a package's bytes. Both are properties\n * of an artefact, checkable by reading it, and neither is a claim about risk.\n *\n * ★ AND THE REMEDY IS \"NOTHING YOU CAN DO ON THIS POOL\", SAID OUT LOUD. The reader has almost\n * always just granted a provenance under Settings → Runners and is entitled to know that it\n * did not do what the screen implied. A remedy that offered a knob here would be inventing\n * one; the honest sentence names the limit, says accepting a provenance does not move it, and\n * points at what DOES run there — the same shape {@link POOL_CONSENT_REMEDY} takes.\n *\n * ⚠ IT DOES NOT SAY \"YET\". The same rule `package-on-runner-refused.spec.ts` pins for the\n * consent refusal applies: a sentence that describes itself as temporary is a roadmap, and a\n * reader cannot act on one. If a later slice puts a package runtime in the image, THIS\n * sentence is what stops being true — and it will be deleted rather than reworded.\n */\nfunction runnerImageClauses(\n cause: Extract<ActionRunnabilityCause, { kind: \"runner_image\" }>,\n): { cause: string; remedy: string } {\n const where =\n `would run on the private runner pool “${cause.poolName}”, because that is where runs ` +\n \"using this connection execute\";\n /*\n * ⚠ THE PACKAGE BRANCH THAT USED TO SIT HERE IS GONE, AND ITS ABSENCE IS THE POINT (docs/60).\n *\n * This cause answers \"the runner's STEP IMAGE does not carry this connector\", and a package\n * never needed to be in the step image: it executes in a container of its own. So the\n * capability question for a package moved to where it can actually be answered — the package\n * oracle, asked with the run's placement, which names the real limit\n * (`runtime_unavailable` for the `runner` isolation) and tells an administrator what to pin.\n * `execution.service.ts` excludes the Package Runner from the clause that raises this cause,\n * so the branch below is now the only one, for a BUILT-IN Opera would have had to ship.\n */\n return {\n cause:\n `This action's connector ${where} — and it is not one of the connectors built into ` +\n \"the runner's step image.\",\n remedy:\n \"Every runner in the pool would have to be running an image that carries it. Runs \" +\n `whose resources execute in ${HOSTED_EXECUTION_LABEL} are unaffected.`,\n };\n}\n\n/**\n * ═══ WHAT A POOL CANNOT CONTAIN, AS A SENTENCE (docs/70 §3.3) ══════════════════════════\n *\n * ★ THE REMEDY NAMES NO PERMISSION, AND THAT IS THE WHOLE TEST OF THIS MEMBER. `runner_pool`'s\n * remedy is \"accept this provenance\", because an administrator can. Here nobody can: no grant\n * anywhere in Opera makes a CNI enforce NetworkPolicy. So the remedy points at the two things\n * that WOULD change the answer — the cluster, and where the run goes — and at neither of them\n * is there a switch inside this product. `runner-egress-refusal.spec.ts` asserts these strings\n * contain no permission verb, which is the mechanical form of \"not the wrong-cause lie\".\n *\n * ★ AND THE CAUSE IS A MEASUREMENT, NOT AN OPINION — the same posture the two clause builders\n * above take. The runner ran a probe against an address this deployment had already reached,\n * once with the confinement applied and once without, and reported what happened. The counts\n * travel on the cause so the sentence can say how much of the pool it is talking about rather\n * than generalising from one runner.\n */\nfunction runnerEgressClauses(\n cause: Extract<ActionRunnabilityCause, { kind: \"runner_egress\" }>,\n): { cause: string; remedy: string } {\n const scope =\n cause.confinedRunners === 0\n ? `No runner in the private runner pool “${cause.poolName}” blocks`\n : `Only ${cause.confinedRunners} of ${cause.totalRunners} runners in the private runner ` +\n `pool “${cause.poolName}” block`;\n return {\n cause:\n `This action's package declares the hosts it may reach, and ${BRAND_SHORT_NAME} would have to enforce ` +\n `that where the package runs. ${scope} outbound traffic a package was never configured ` +\n \"to send — each one measured that on its own substrate — so the list could be stated \" +\n \"but not enforced.\",\n remedy:\n \"A run cannot choose which runner claims it, so this is a property of the pool. It \" +\n \"changes when the hosts running these runners can confine outbound traffic — on \" +\n \"Kubernetes that means a CNI that enforces NetworkPolicy, which several do not by \" +\n `default. Runs whose resources execute in ${HOSTED_EXECUTION_LABEL}, or on a pool that confines, ` +\n \"are unaffected.\",\n };\n}\n\nconst POOL_CONSENT_REMEDY =\n `${BRAND_SHORT_NAME} does not vouch for what runs on your machines — the owner of this pool does. An ` +\n \"administrator can accept this provenance under Settings → Runners, and until they do, \" +\n \"nothing of this provenance will be sent there. Built-in actions still run in that pool.\";\n\n/**\n * The cause as a HEADLINE — one clause, for a surface that gets a title and nothing else.\n *\n * A THIRD LENGTH, NOT A THIRD VOCABULARY, for the reason {@link actionUnrunnableHeadline}\n * already gives one level down: the Operation verification check's TITLE becomes the\n * `verification_failed` notification, and that is the one sentence that reaches an owner who is\n * not looking at Opera. It switches over the same union in the same file, so a member cannot be\n * worded here in a way that contradicts {@link actionRunnabilityCopy}.\n *\n * ⚠ `runner_pool` CANNOT ARRIVE FROM THE SWEEP TODAY and is written anyway. The sweep verifies\n * an ACTION, so it asks the runnability oracle without a connection scope and never gets this\n * member back. Writing the branch is not defensive padding: it is what makes threading a scope\n * into the sweep later a one-line change rather than a change that has to invent copy under\n * time pressure — and an exhaustive switch with a member missing is a compile error nobody can\n * resolve correctly at 3am.\n */\nexport function actionRunnabilityHeadline(cause: ActionRunnabilityCause): string {\n switch (cause.kind) {\n case \"catalog_blocked\":\n // The fact AND whose move it is, because this line is the whole `verification_failed`\n // notification: an owner reading it in their inbox has no other sentence to go on.\n return \"this workspace does not permit its action — an administrator of this workspace can allow it\";\n case \"package\":\n return actionUnrunnableHeadline(cause.detail);\n case \"runner_pool\":\n // Names the PROVENANCE, because that is what changed: this is no longer \"a package\n // cannot run on a runner\" but \"this pool has not accepted packages of this kind\".\n return cause.provenance\n ? `the pool \"${cause.poolName}\" does not accept packages ${PACKAGE_PROVENANCE_CLAUSES[cause.provenance]}`\n : `its package has no recorded provenance, so the pool \"${cause.poolName}\" cannot accept it`;\n case \"runner_image\":\n // Names the ARTEFACT, because that is the thing that would have to change — not the\n // pool, and not what the pool accepts. One sentence since docs/60: a package's own\n // capability limit is a different cause with a different remedy (see `runnerImageClauses`).\n return `the runners in \"${cause.poolName}\" run an image that does not carry this action's connector`;\n case \"runner_egress\":\n // Names the CONFINEMENT, because that is the fact — not the image, and not what\n // the pool accepts. A package that declares where it may reach needs that\n // enforced, and this pool measured that it cannot enforce it.\n return cause.confinedRunners === 0\n ? `no runner in \"${cause.poolName}\" can confine this package's outbound traffic`\n : `only ${cause.confinedRunners} of ${cause.totalRunners} runners in \"${cause.poolName}\" can confine this package's outbound traffic`;\n case \"runner_pool_ambiguous\":\n return `its resources would execute in ${cause.places.length} different places`;\n case \"connector_unregistered\":\n return `this deployment has no connector for \"${cause.connectorKey}\"`;\n }\n}\n\n/**\n * The RUN PATH's refusal — what `submit` throws and `validate` mirrors. It carries the\n * package identity and the \"nothing was started\" guarantee, because this is the message that\n * reaches an API caller or the owner of a firing schedule: somebody who is not at a screen\n * that could explain itself, and who otherwise learns only that their automation stopped.\n */\nexport function actionRunnabilityRefusal(cause: ActionRunnabilityCause): string {\n switch (cause.kind) {\n case \"catalog_blocked\":\n return `${CATALOG_BLOCKED_CAUSE} ${CATALOG_BLOCKED_REMEDY} Nothing was started.`;\n case \"package\":\n return actionUnrunnableRefusal(cause.detail, cause);\n case \"runner_pool\": {\n const { cause: why, remedy } = runnerPoolClauses(cause);\n // \"Nothing was started\" for the same reason every other run-path refusal carries it:\n // the reader is an API caller or the owner of a schedule that just stopped firing, and\n // \"did half of it happen\" is their first question.\n return `This action's package ${why} ${remedy} Nothing was started.`;\n }\n case \"runner_image\": {\n const { cause: why, remedy } = runnerImageClauses(cause);\n return `${why} ${remedy} Nothing was started.`;\n }\n case \"runner_egress\": {\n const { cause: why, remedy } = runnerEgressClauses(cause);\n return `${why} ${remedy} Nothing was started.`;\n }\n case \"runner_pool_ambiguous\":\n // The SAME sentence the plan shows. This one already carries \"Nothing was started\",\n // which is the first question an API caller or a schedule owner has.\n return `This run's resources do not all execute in the same place: ${describeRoutingPlaces(cause.places)}. ${AMBIGUOUS_ROUTING_REMEDY}`;\n case \"connector_unregistered\":\n return CONNECTOR_UNAVAILABLE_MESSAGE;\n }\n}\n\n/**\n * Tenant-scoped real execution aggregates for one action definition. `successRate`\n * is a 0..1 fraction and `avgDurationMs` comes from the DB-generated duration_ms.\n */\nexport interface ActionRunStatsDto {\n actionDefinitionId: string;\n runs: number;\n successRate: number;\n avgDurationMs: number;\n}\n\n/** Tenant-wide real execution summary for the catalog KPI strip. */\nexport interface TenantRunSummaryDto {\n totalRuns: number;\n successRate: number;\n}\n\n/** Query for `GET /executions` (docs/04 §2.3). Filters grow in Step 6. */\nexport interface ListExecutionsQuery {\n cursor?: string;\n limit?: number;\n}\n\n/**\n * ═══ ONE ROW OF THE TENANT-LEVEL SUBSCRIPTION REGISTRY ═════════════════════════════════\n *\n * Maps to one `azure_subscription` row: `id` is that row's Opera uuid, and `subscriptionId` is\n * the external Azure GUID. Both names are correct here and neither moves.\n *\n * ⚠ IT USED TO SAY `id` WAS \"what `create` references\", AND THAT BECAME FALSE. `POST /executions`\n * takes a `connection_scope.id` — a per-connection binding — and pointing a reader at an\n * `azure_subscription.id` for that purpose is precisely the confusion that made a rerun change\n * the connector it ran on. The clause is removed rather than reworded: what an id IS cannot rot,\n * and what consumes it is a fact about another module that this one should not be asserting.\n *\n * ★ WHERE A RUN'S SCOPE ACTUALLY COMES FROM, as a pointer and not a claim: the run wizard picks\n * a {@link import(\"./connections\").ConnectionScopeDto} and sends its `id`.\n *\n * ⚠ AND THIS DTO IS SERVED BUT UNREACHED. `GET /subscriptions` and `POST /subscriptions/sync`\n * still answer, and their two web clients (`fetchSubscriptions`, `syncSubscriptions`) have NO\n * callers anywhere in `apps/web` — measured 2026-08-25. It is live over the HTTP API and absent\n * from every product surface. Recorded rather than deleted: removing a served route is its own\n * decision, with its own blast radius, and it is not this one.\n */\nexport interface SubscriptionSummaryDto {\n id: string;\n subscriptionId: string;\n displayName: string;\n environment: Environment;\n}\n\n/**\n * ═══ TRIAL RUNS — RUNNING A DRAFT BEFORE COMMITTING TO IT ══════════════════════════════\n *\n * A trial run is a REAL run: real bytes, real substrate, real connection, real governance gate,\n * real audit. What makes it safe is that its version is not in the catalog and nothing can adopt\n * it — containment, not pretending. A simulated path would prove nothing about what publishing\n * produces, which is the entire reason this exists.\n *\n * It is modelled here, in Execution, because the thing being created is an EXECUTION. Packages\n * mints the version through {@link TrialVersionDto} and knows nothing about runs; Execution\n * orchestrates. The reverse arrangement would need `packages` → `execution`, and `execution`\n * already depends on `packages` — a cycle dependency-cruiser rejects (§2.4).\n */\nexport interface CreateTrialRunInput {\n draftId: string;\n /**\n * The `connection_scope.id` to run against — a real one; there is no sandbox connection.\n *\n * Renamed with {@link CreateExecutionInput.connectionScopeId}, which it is forwarded to. Its\n * doc comment already said \"connection scope\" while its NAME said subscription; one of the\n * two had to move, and the name is what a caller reads.\n */\n connectionScopeId: string;\n parameters: Record<string, unknown>;\n dryRun: boolean;\n /*\n * ═══ ★ A TRIAL RUN IS ATTENDED, SO IT NAMES A RECORD LIKE ANY OTHER (docs/88 §4.3) ═══\n *\n * ⚠ THIS FIELD'S ABSENCE WAS A HOLE, not an exemption. The gate sits at `execution.submit`\n * and a trial goes straight through it (`trial-runs.service.ts:103`) — so a matching rule\n * already refused every trial run with `no_reference`, and `executionInputFor` had nothing\n * to forward. The author was standing right there; there was simply no field.\n *\n * Forwarded verbatim to {@link CreateExecutionInput.changeRecord} and parsed by the same\n * `parseChangeRecordRef` every other route uses. Nothing about a trial is special here, and\n * that is the point: an exemption would have made \"run it as a trial\" the way past the gate.\n */\n changeRecord?: ChangeRecordRef;\n}\n\n/**\n * What the author is shown BEFORE the run exists: the version that will run, and the ordinary\n * plan preview over it — same governance decision, same resolved environment, same runnability\n * oracle every other run gets, because it is literally the same call.\n *\n * Producing this MINTS the trial version, which is why it is not on the read altitude the plain\n * preview sits at. The mint is content-addressed and idempotent, so previewing twice costs one\n * version, and previewing then running costs the same one — and it is the only way the plan can\n * describe the thing that will actually run rather than an approximation of it.\n */\nexport interface TrialRunPlanDto {\n trial: TrialVersionDto;\n plan: ExecutionPlanDto;\n}\n\n/** What `POST /executions/trial-runs` hands back: the version that ran and the run itself. */\nexport interface TrialRunStartedDto {\n trial: TrialVersionDto;\n execution: ExecutionDto;\n}\n\n/**\n * One trial run on a draft's Runs tab.\n *\n * `packageId` and `name` are DENORMALIZED, and `draftId` goes null when the draft is discarded.\n * A run that really changed a customer's infrastructure cannot become unreadable because\n * somebody tidied up a draft (charter §4.1), and a history that renders as a bare uuid after a\n * discard is unreadable in every sense that matters.\n */\nexport interface TrialRunDto {\n id: string;\n executionId: string;\n /** The run's human reference, e.g. `OPS-1042`. */\n reference: string;\n draftId: string | null;\n packageId: string;\n name: string;\n contentDigest: string;\n status: ExecutionStatus;\n result: ExecutionResult;\n dryRun: boolean;\n /** Resolved to a display name by the caller, exactly as the Activity timeline does. */\n createdBy: string;\n createdAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n durationMs: number | null;\n}\n\n/**\n * Which draft, if any, a run was a trial of — the batch lookup the run history joins so a trial\n * run can say so on the ordinary run detail rather than looking like a catalog run that nobody\n * can find. Mirrors `OperationRunLinkDto`: one request per page, never one per row.\n *\n * A separate lookup rather than a field on {@link ExecutionDto} even though Execution owns the\n * table, because the vast majority of runs are not trials and every `get`/`list` in the product\n * would otherwise pay for a join that answers \"no\".\n */\nexport interface TrialRunLinkDto {\n executionId: string;\n draftId: string | null;\n packageId: string;\n name: string;\n contentDigest: string;\n}\n","// ═══ WHAT A PERSON DECIDED ABOUT A PLAN'S DECIDE CHECKS (docs/126 §3, §4) ═══════════════\n//\n// `validation.ts` declares what a check IS — its level, and the codes a REFUSE or a DECIDE\n// carries. This file declares what happens to a DECIDE check once a person has read it: the\n// submit that carries their acknowledgements, the comparison the server makes against the checks\n// it re-ran, and the record that travels to the run and to the approver.\n//\n// ★ IT READS `validation.ts` AND NOTHING ELSE, and nothing in `validation.ts` reads it. The check\n// vocabulary is the leaf both producers of a validate result share (see that file's header); a\n// decision is a later fact about one of those results, so the dependency points this way only.\n\nimport {\n isDecisionCode,\n type DecisionCode,\n type ValidationCheck,\n} from \"./validation\";\n\n/**\n * ═══ ONE DECISION, AS IT IS KEPT (`execution.decisions`, migration 0096) ════════════════\n *\n * The code the requester acknowledged, WHO acknowledged it and WHEN. Written by the server at\n * submit, in the same statement that moves the run out of `validated`, after it re-ran the checks\n * and found the acknowledgements matched them exactly. Never written from a client's say-so.\n *\n * ★ PER DECISION, NOT PER RUN, although today every decision on a run is made by its submitter\n * at the moment of submit. docs/126 Slice B asks the requester of a fan-out to decide per TARGET\n * at plan time, and a record that kept one \"who/when\" for the run would have nowhere to say so.\n */\nexport interface RecordedDecision {\n code: DecisionCode;\n /** The `app_user.id` of the person who acknowledged it. */\n acknowledgedBy: string;\n /** ISO-8601, the server's clock at the moment it was recorded. */\n acknowledgedAt: string;\n}\n\n/**\n * ═══ READING BACK WHAT WAS STORED — NEVER CAST ═════════════════════════════════════════\n *\n * `execution.decisions` is jsonb and so is the approval snapshot that copies it. Anything this\n * cannot read — a malformed entry, an unknown code, a non-array — is DROPPED, and the direction\n * of that is the safety property: a decision that cannot be read is a decision that was not made,\n * so the DECIDE check it would have answered stays unanswered and the run refuses (docs/126 §3.2).\n * Reading an unknown entry as \"acknowledged\" would be the one wrong answer.\n */\nexport function recordedDecisionsOf(stored: unknown): RecordedDecision[] {\n if (!Array.isArray(stored)) return [];\n const read: RecordedDecision[] = [];\n for (const entry of stored) {\n if (typeof entry !== \"object\" || entry === null) continue;\n const { code, acknowledgedBy, acknowledgedAt } = entry as Record<string, unknown>;\n if (!isDecisionCode(code)) continue;\n if (typeof acknowledgedBy !== \"string\" || acknowledgedBy.length === 0) continue;\n if (typeof acknowledgedAt !== \"string\" || Number.isNaN(Date.parse(acknowledgedAt))) continue;\n if (read.some((decision) => decision.code === code)) continue;\n read.push({ code, acknowledgedBy, acknowledgedAt });\n }\n return read;\n}\n\n/**\n * ═══ WHAT A CHECK'S PRODUCER IS TOLD ABOUT DECISIONS — AND WHEN IT IS BEING ASKED (docs/126 §3) ══\n *\n * Two phases, and they are the whole reason this is a union rather than a list:\n *\n * | phase | who is reading the checks | a DECIDE check is… |\n * |--------|------------------------------------|-----------------------------------------|\n * | `plan` | the requester, about to choose | a QUESTION — `warn`, acknowledged or not |\n * | `run` | nobody; the answers are on record | answered, or an `error` that blocks |\n *\n * ★ AN EMPTY LIST IS NOT THE SAME AS NOT BEING ASKED YET. `{ phase: \"run\", recorded: [] }` is a\n * run nobody decided anything for — every fan-out child before docs/126 Slice B, every schedule —\n * and a DECIDE check there refuses. A bare `RecordedDecision[]` could not tell that apart from a\n * plan, which is precisely the conflation that would let a plan's `warn` reach a run.\n *\n * ⛔ IT IS NOT `parameters`. Decisions are not inputs to the action; they are a person's answers\n * about its risks, and a vocabulary that means two things is the defect charter §4.2 exists for.\n *\n * ★ DECLARED HERE SINCE docs/128, beside the record it carries, because it crosses a wire: an\n * engine action's invocation carries exactly this value (`action-protocol.ts`), and the action\n * SDK hands it to the author's handler. The engine and the SDK read one type.\n */\nexport type DecisionsInHand =\n | { readonly phase: \"plan\" }\n | { readonly phase: \"run\"; readonly recorded: readonly RecordedDecision[] };\n\n/**\n * What a DECIDE check nobody answered says once it reaches a run. Appended to the check's own\n * sentence, so the run's events and its evidence say what the risk was AND why nothing happened.\n */\nexport const UNDECIDED_AT_RUN =\n \"Nobody acknowledged this before the run, so it was not acted on.\";\n\n/**\n * ═══ ★ AT A RUN, AN UNANSWERED DECIDE CHECK IS AN `error` (docs/126 §3.3) ═══════════════\n *\n * Only `error` blocks (`run-execution.handler.ts`: \"AN ERROR-LEVEL CHECK BLOCKS THE RUN\"); a\n * `warn` PROCEEDS. So a DECIDE check whose code is not on the record must be raised to `error`\n * here, or the run deletes exactly the disk nobody decided about. With the code on the record it\n * stays `warn` and the run goes ahead — the decision itself is now what the record shows.\n *\n * ★ ONE FUNCTION, THREE CALLERS, ONE RULE. The worker applies it to whatever `validate` returned —\n * for EVERY connector, including one whose checks come back from a runner, because what a check\n * means is the control plane's question (docs/49 §7). The engine connector applies it to every\n * report an engine action sends, never trusting a level the action chose (docs/128 §4.2). And a\n * connector or an engine action that acts destructively applies it again to its own re-check\n * before it acts — the action SDK re-exports THIS function for that — so the delete is\n * unreachable through any path that skipped the worker. Breaking this function breaks all of\n * them, which is the point: there is no second copy of the rule to keep the first one honest by\n * accident. It moved here from the execution module in docs/128 so the engine and the SDK could\n * share it rather than each hold one.\n *\n * ★ IDEMPOTENT. A check already at `error` is left alone, so settling twice cannot append the\n * sentence twice — and a DECIDE check a connector chose to emit at `error` stays blocking whatever\n * was decided, because nothing here ever LOWERS a level.\n */\nexport function settleDecisionChecks(\n checks: readonly ValidationCheck[],\n inHand: DecisionsInHand,\n): ValidationCheck[] {\n if (inHand.phase === \"plan\") return [...checks];\n return checks.map((check) => {\n if (!check.decision || check.level === \"error\") return check;\n if (inHand.recorded.some((decision) => decision.code === check.decision)) return check;\n return { ...check, level: \"error\", title: `${check.title} ${UNDECIDED_AT_RUN}` };\n });\n}\n\n/**\n * The DECIDE codes a set of checks raises, once each, in the order the checks raised them.\n *\n * ★ THE ONE PLACE \"WHICH DECISIONS DOES THIS PLAN ASK FOR\" IS ANSWERED. The wizard reads it to\n * know which acknowledgements to collect; the server reads it to know which it must receive. Two\n * derivations would be two answers to the question the server exists to settle.\n */\nexport function raisedDecisionCodes(checks: readonly ValidationCheck[]): DecisionCode[] {\n const raised: DecisionCode[] = [];\n for (const check of checks) {\n if (check.decision && !raised.includes(check.decision)) raised.push(check.decision);\n }\n return raised;\n}\n\n/**\n * ═══ WHERE THE SUBMIT'S ACKNOWLEDGEMENTS AND THE SERVER'S CHECKS DISAGREE ═══════════════\n *\n * Both directions, because both are refusals (docs/126 §3):\n *\n * · `unacknowledged` — the server raised it and the requester did not acknowledge it. Running\n * would act on a risk nobody accepted.\n * · `notRaised` — the requester acknowledged a code the server did not raise. Accepting it\n * would put a decision on the record about a risk that is not there, and a client that can\n * add decisions can make the record say anything.\n *\n * `null` when the two sets are equal, which is the only case a submit proceeds on.\n */\nexport interface DecisionMismatch {\n unacknowledged: DecisionCode[];\n notRaised: DecisionCode[];\n}\n\nexport function decisionMismatch(\n raised: readonly DecisionCode[],\n acknowledged: readonly DecisionCode[],\n): DecisionMismatch | null {\n const unacknowledged = raised.filter((code) => !acknowledged.includes(code));\n const notRaised = acknowledged.filter((code) => !raised.includes(code));\n return unacknowledged.length === 0 && notRaised.length === 0\n ? null\n : { unacknowledged, notRaised };\n}\n\n/**\n * ═══ THE REFUSAL A MISMATCH IS ANSWERED WITH — THE RISK IN WORDS, NEVER A CODE ═════════════\n *\n * One sentence, for the 409 and for any surface that shows it. A risk the plan now raises is named\n * by the check's OWN sentence — the one the requester would have read on the plan — and one that was\n * acknowledged but is no longer raised by the label they ticked (`DECISION_ACKNOWLEDGEMENT`). The\n * codes travel beside it in the problem body's `unacknowledged` and `notRaised` fields, for a client\n * that acts on them; a person is never handed `\"disk.noSnapshot\"` to decode (docs/126 §6.6.6).\n *\n * `checks` are the checks the server ran AGAIN at submit — the source of each raised risk's sentence.\n */\nexport function decisionMismatchSentence(\n mismatch: DecisionMismatch,\n checks: readonly ValidationCheck[] = [],\n): string {\n return (\n \"This run was not submitted: the checks were run again at submit, and they no longer match what was acknowledged. \" +\n `${mismatchParts(mismatch, checks).join(\" \")} Review the plan and submit again.`\n );\n}\n\n/**\n * ═══ THE SAME REFUSAL, PER TARGET OF A FAN-OUT (docs/126 §14 B-3) ═══════════════════════\n *\n * An Operation run is started once for many targets, and the server compares each target's\n * acknowledgements with that target's re-run checks exactly as a single run's submit does — so the\n * 409 names every target whose answers no longer match, each by its label and in the words above.\n * `unknown` is a target the requester answered about that the server no longer resolves: the plan\n * they read is not the plan the run would act on.\n */\nexport interface TargetDecisionMismatch extends DecisionMismatch {\n ref: string;\n label: string;\n /** True when the server no longer resolves this target at all. */\n unknown: boolean;\n /** The target's checks as the server ran them again — the source of each raised risk's sentence. */\n checks: readonly ValidationCheck[];\n}\n\nexport function targetDecisionsMismatchSentence(\n mismatches: readonly TargetDecisionMismatch[],\n): string {\n const parts = mismatches.map((target) =>\n target.unknown\n ? `${target.label}: no longer one of this step's targets.`\n : `${target.label}: ${mismatchParts(target, target.checks).join(\" \")}`,\n );\n const count = mismatches.length;\n return (\n `This run was not started: the checks were run again, and for ${count} ${count === 1 ? \"target\" : \"targets\"} ` +\n `they no longer match what was decided. ${parts.join(\" \")} Review the plan and start the run again.`\n );\n}\n\nfunction mismatchParts(mismatch: DecisionMismatch, checks: readonly ValidationCheck[]): string[] {\n const parts: string[] = [];\n for (const code of mismatch.unacknowledged) {\n const sentence = checks.find((check) => check.decision === code)?.title ?? DECISION_ACKNOWLEDGEMENT[code];\n parts.push(`Not acknowledged: ${withStop(sentence)}`);\n }\n for (const code of mismatch.notRaised) {\n parts.push(`Acknowledged, but no longer raised: “${DECISION_ACKNOWLEDGEMENT[code]}”.`);\n }\n return parts;\n}\n\n/**\n * ═══ THE DECISIONS A VERIFIED ANSWER RECORDS (docs/126 §3) ═════════════════════════════\n *\n * One per code the plan raised — which, once the server has compared, is exactly the set the\n * requester acknowledged. Who and when are the SERVER's: the submitting user and this moment.\n *\n * ★ ONE AUTHOR FOR BOTH PLACES A PERSON ANSWERS: a single run's submit, and an Operation run's\n * start, which answers per target (docs/126 §14 B-3). Two copies would be two ideas of \"who\".\n */\nexport function decisionsMadeAtSubmit(\n codes: readonly DecisionCode[],\n by: string,\n at: Date,\n): RecordedDecision[] {\n return codes.map((code) => ({ code, acknowledgedBy: by, acknowledgedAt: at.toISOString() }));\n}\n\n/**\n * ═══ WHAT BECOMES OF ONE TARGET OF A FAN-OUT, DECIDED BEFORE ITS GATE (docs/126 §14 B-3) ═══\n *\n * | disposition | who said so | acted on |\n * |-------------|--------------------------------------|----------|\n * | `ready` | the checks, and the requester's answers | yes |\n * | `left_out` | the requester | no |\n * | `refused` | the platform — a REFUSE, or a check that could not complete | no |\n *\n * ★ ARRAY-FIRST, DECLARED ONCE. The run's target plan, the approval card and the preview all read\n * this list; a fourth disposition is a compile error in every `Record` keyed by it.\n *\n * ⛔ `left_out` IS THE RUN'S FACT, NEVER THE OPERATION'S. Writing it into a step's\n * `excludeResourceIds` would publish a new Operation version per run (docs/126 §14 F4).\n */\nexport const TARGET_DISPOSITIONS = [\"ready\", \"left_out\", \"refused\"] as const;\nexport type TargetDisposition = (typeof TARGET_DISPOSITIONS)[number];\n\nexport function isTargetDisposition(value: unknown): value is TargetDisposition {\n return typeof value === \"string\" && (TARGET_DISPOSITIONS as readonly string[]).includes(value);\n}\n\nfunction withStop(sentence: string): string {\n const trimmed = sentence.trim();\n return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;\n}\n\n/**\n * ═══ WHAT THE ACKNOWLEDGE CONTROL SAYS, PER CODE ════════════════════════════════════════\n *\n * The check's own title is the sentence that explains the risk; this is the label on the control\n * that accepts it — so a requester ticks a box that says what they are agreeing to rather than a\n * generic \"I understand\". Pinned to the union: a sixth code is a compile error here before it can\n * reach a wizard as a blank control.\n */\nexport const DECISION_ACKNOWLEDGEMENT: Record<DecisionCode, string> = {\n \"disk.recentlyDetached\": \"Delete it even though it was detached recently\",\n \"disk.customerKey\": \"Delete it — restoring later depends on this key staying enabled\",\n \"disk.customerKeyUnverified\": \"Delete it without confirmation that the key is enabled\",\n \"disk.guestEncrypted\": \"Delete it — restoring later depends on the guest's encryption secrets\",\n \"disk.noSnapshot\": \"Delete it with no snapshot — this cannot be undone\",\n \"disk.confidential\": \"Delete it, accepting that restoring a confidential VM disk is not verified\",\n};\n\n/**\n * ═══ THE BODY OF `POST /executions/{id}/submit` (docs/126 §3) ═══════════════════════════\n *\n * The DECIDE codes the requester acknowledged on the plan. CODES, not checks, and not\n * sentences: what a person decided is named by the stable code, and the server — which re-runs\n * the checks — is the only party that says what those codes mean today.\n *\n * Absent or empty means nothing was acknowledged, which is every submit before docs/126 and\n * every in-process submit (a schedule, an Operation's child): no human was asked, so a plan that\n * raises a DECIDE check is refused rather than run.\n */\nexport interface SubmitExecutionInput {\n acknowledgedDecisions?: DecisionCode[];\n}\n","// ═══ WHERE A RUN EXECUTED — RECORDED, NOT INFERRED (docs/56 §3.3) ═══════════════════════\n//\n// A run that executed on a customer's machine in Asia and a run that executed in Opera's cloud\n// were INDISTINGUISHABLE in the audit trail. `runner_authorization` carried both the execution\n// id and the runner id, and `discardAuthorization` deletes that row when the step ends — by\n// design, because that is what makes the authorization single-use. Measured on the dev database\n// after every proof run this programme has done: `authorizations=0 with_runner=0`, across 541\n// executions. A security property ate an audit property; both were correct alone.\n//\n// The fix is not to keep the authorization. It is to write the fact somewhere that OUTLIVES the\n// step, which is the execution row itself.\n//\n// ─── ★ WHY THREE VALUES AND NOT A NULLABLE POOL ID ─────────────────────────────────────\n//\n// Because `null` would have to mean two different things at once:\n//\n// | the run | a nullable pool id says | the truth |\n// |------------------------------------------|-------------------------|-----------------|\n// | executed in Opera's cloud | null | `hosted` |\n// | executed on a private runner | the pool id | `runner` |\n// | predates this slice — nobody wrote it down| null | `unknown` |\n//\n// Rows one and three collide, and the collision is not cosmetic: every execution in the\n// database predates this slice, so reading their absent value as \"ran in Opera's cloud\" would\n// write a guess into the audit trail thousands of rows deep. It is PROBABLY true. It is not\n// KNOWN, and this codebase already separates those — `EGRESS_MODES` keeps\n// `substrateBlocksUndeclared` apart from the mode for exactly this reason.\n//\n// So `hosted` is a value the engine WRITES, `unknown` is what a row says when nothing wrote\n// one, and migration 0064 backfills nothing.\nimport { HOSTED_EXECUTION_LABEL } from \"./run-placement\";\nimport type { PackagePhase } from \"./package-execution\";\n\n// ⚠ THE VOCABULARY ITSELF IS NO LONGER DECLARED HERE. `EXECUTION_SITES` and `isExecutionSite`\n// moved to the leaf `run-placement.ts` when `package-execution.ts` came to need them too and\n// this file imports from there — a cycle `.dependency-cruiser.cjs` refuses by name. They reach\n// consumers through the package barrel, which exports both files; re-exporting them here as\n// well would be a second path to one declaration.\n\n/**\n * ═══ WHERE ONE EXECUTION RAN, AS THE RECORD HOLDS IT ═══════════════════════════════════\n *\n * A discriminated union, so the wrong thing cannot be built. `hosted` has no pool to carry;\n * `unknown` has nothing at all; and `runner` cannot exist without naming the pool it went to.\n * The alternative — five loose fields on the DTO — is a shape where \"runner, pool unknown\" and\n * \"hosted, but here is a pool\" are both expressible, and one of them would eventually be built.\n *\n * ─── THE IDENTITIES ARE DENORMALIZED, FOLLOWING `scheduleName` ─────────────────────────\n *\n * A pool and a runner are genuinely DELETED (`ON DELETE CASCADE` from `runner_pool`, and a\n * revoked runner is expected to be torn down), so a join would find nothing and the record\n * would go blank precisely when an auditor needs it. `execution.schedule_name` solved this\n * once, for the same reason, and this follows it: the id AND the name as they were at the time.\n * Neither is a foreign key — a run is a historical record, and deleting the pool that ran it\n * must neither delete nor rewrite the evidence that it happened.\n */\nexport type RunExecutionSiteDto =\n | { site: \"hosted\" }\n | {\n site: \"runner\";\n /** The pool this run was placed with, as it was named at the time. */\n pool: ExecutionSiteRef;\n /**\n * ★ THE RUNNER THAT EXECUTED THE WORK, or `null` — AND `null` IS A FACT, NOT A GAP.\n *\n * It means NO RUNNER EVER CLAIMED this run's work: the authorization expired unclaimed,\n * or the control plane refused the step before it was offered. Nothing executed, which\n * the run's own status and message already say — and which is a different statement from\n * `site: \"unknown\"`, where something may well have executed and we did not record where.\n *\n * Filled in the moment a runner claims, so a step that runs for eleven minutes names its\n * runner while it is still running rather than only at the end.\n */\n runner: ExecutionSiteRef | null;\n /**\n * ⚠ WHICH PHASE THIS NAMES, STATED RATHER THAN IMPLIED. A runner-executed step is TWO\n * authorizations — `validate` then `run` — and they may be claimed by different runners\n * in the same pool. `runner` names the one that claimed the phase that ACTS: `run` on an\n * apply, `rollback` on a rollback. The pre-flight's runner is deliberately not recorded:\n * a field labelled \"where this run executed\" naming the machine that only ran the\n * pre-flight would be wrong for the case that matters most — a run whose checks passed\n * on one runner and whose apply never started at all.\n *\n * The POOL bounds both either way (docs/49 §4.2: one step, one pool), so the blast\n * radius docs/49 §4.5 asks for stays legible.\n */\n phase: PackagePhase;\n }\n | { site: \"unknown\" };\n\n/** A pool or a runner, as the record froze it. The name is what a human reads. */\nexport interface ExecutionSiteRef {\n id: string;\n name: string;\n}\n\n/**\n * ═══ ONE SENTENCE, ONE PLACE (docs/46 §3.2's rule, applied again) ══════════════════════\n *\n * The run feed, the run drawer, the evidence bundle and the plan preview all state this, and a\n * second copy is how one fact comes to be explained two ways. It is a function returning a\n * string for the same reason `runProvenanceSentence` is: the site and the two names rendered\n * side by side are three fields a later edit can separate, and the separated version says\n * \"runner\" with no runner in it.\n *\n * ★ `unknown` READS AS AN ABSENCE OF RECORD, NEVER AS \"OPERA'S CLOUD\". Every run in the\n * database before this slice is `unknown`, so at first this is most of the feed (docs/56 §4)\n * — which is exactly why the sentence has to be the honest one rather than the tidy one.\n */\nexport function runExecutionSiteSentence(where: RunExecutionSiteDto): string {\n switch (where.site) {\n case \"hosted\":\n return HOSTED_EXECUTION_LABEL;\n case \"runner\":\n return where.runner\n ? `Your runner “${where.runner.name}” in pool “${where.pool.name}”`\n : // Placed with the pool, and nothing there took it. The run's own status says the\n // rest; this says where it was sent.\n `Pool “${where.pool.name}” — no runner claimed it`;\n case \"unknown\":\n return \"Not recorded\";\n }\n}\n\n/** The shorter form, for a feed row that has one line and already says a great deal. */\nexport function runExecutionSiteLabel(where: RunExecutionSiteDto): string {\n switch (where.site) {\n case \"hosted\":\n return HOSTED_EXECUTION_LABEL;\n case \"runner\":\n return where.runner ? where.runner.name : where.pool.name;\n case \"unknown\":\n return \"Not recorded\";\n }\n}\n\n/**\n * The one value a row that nobody wrote to reads as. Exported so no caller has to spell the\n * literal — a `{ site: \"unknown\" }` written out at a call site is a call site that can be\n * changed to `{ site: \"hosted\" }` by somebody who thinks they mean the same thing.\n */\nexport const EXECUTION_SITE_UNKNOWN: RunExecutionSiteDto = { site: \"unknown\" };\n\n// ═══ AND WHERE IT WILL EXECUTE, BEFORE ANYBODY DECIDES (docs/56 §3.4) ═══════════════════\n//\n// ★ A SEPARATE TYPE FROM {@link RunExecutionSiteDto}, AND THE SEPARATION IS THE DESIGN.\n// A plan is a PREDICTION and a record is a FACT, and the two vocabularies differ in both\n// directions:\n//\n// · `unknown` is not reachable at plan time. The preview resolves the connection scope and\n// asks which pool it is bound to; if that read fails, the whole preview fails. A plan that\n// could say \"we do not know where this will run\" would be a plan that had not been made.\n// · A RUNNER cannot be named at plan time. Nothing has been offered to anyone yet — a runner\n// is chosen by whichever one claims, at the instant it claims (docs/49 §4.3). A shape that\n// could carry one would eventually be filled in with the pool's first runner, which is a\n// guess about which machine will take the work.\n//\n// Sharing one type would make both of those expressible, and \"make the wrong thing\n// unexpressible\" is worth more here than one fewer type: this is the value an approver reads\n// immediately before saying yes.\n\n/**\n * ═══ ONE PLACE A RUN'S RESOURCES WOULD HAVE GONE (docs/58 §3.3) ═════════════════════════\n *\n * ★ A SEPARATE MEMBER FROM `runner_pool`, NOT A FLAG ON IT, because they are opposite facts.\n * `runner_pool` says the destination is KNOWN and the action may not go there; this says the\n * destination is NOT KNOWN, because the run's resources resolve to two. The remedies differ\n * too — one is \"use a different connection\", the other is \"narrow the targets and run twice\" —\n * and a reader handed the wrong one goes and changes the wrong thing.\n *\n * ⚠ THE FIELDS ARE FLAT ON PURPOSE, and it is not laziness. Reusing `PoolRoutingMatch` would\n * make `execution.ts` import `runner-pool-routing.ts`, which imports `operations.ts`, which\n * imports `execution.ts` — a dependency cycle. That exact cycle shipped to production once\n * (`execution → runner-pool-presence → runners → execution`, red from `e97948b` until\n * `b4074bc`) because the gate was composed with `boundaries:verify`, the LITMUS, in place of\n * `boundaries`, the check. Four names copied here beat re-earning that.\n */\nexport interface AmbiguousRoutingPlace {\n /** The pool, or `null` for Opera's cloud — which is a destination like any other here. */\n poolName: string | null;\n /** The rule that sent them, or `null` when the connection's default did. */\n ruleName: string | null;\n targetCount: number;\n /** A resource that would have gone there, so an operator can check the claim. */\n exampleResourceId: string;\n}\n\n/**\n * Where a run WILL execute, as the plan states it.\n *\n * THREE values since docs/58, and the third is not a hedge — it is a genuinely different\n * answer. Routing is decided by the run's TARGET RESOURCES, and a fan-out over 80 VMs can\n * resolve resources that match different rules. That run does not have \"a place\".\n *\n * ★ IT IS A MEMBER RATHER THAN A NULL, AND THAT MATTERS HERE SPECIFICALLY. `null` is already\n * spoken for on every surface that renders this: it means \"this request predates the record\",\n * and `RunsOnCallout` says so in as many words. Reusing it would tell an operator whose\n * brand-new run was just refused for splitting across two pools that their request is too old\n * to have been recorded — the wrong-cause lie, in the one place they are looking.\n *\n * ★ AND IT MAKES THE SPLIT RUN UNRENDERABLE AS ONE PLACE. With two values, the only way to\n * return anything at all for an ambiguous run is to pick one of its pools, which is precisely\n * the silent discard docs/58 §3.3 refuses. There is now nowhere to put that guess.\n */\nexport type PlannedExecutionSiteDto =\n | { site: \"hosted\" }\n | { site: \"runner\"; pool: ExecutionSiteRef }\n | { site: \"ambiguous\"; places: readonly AmbiguousRoutingPlace[] };\n\n/**\n * What the plan preview and the approval card say. Present tense about a future run, and\n * deliberately not the past-tense sentence the record uses.\n *\n * ⚠ IT IS A PREDICTION AND IT SAYS SO NOWHERE, BECAUSE THE CALLER SAYS IT. An admin can\n * rebind the connection between this plan and the run; what makes that honest is the RECORD\n * (`RunExecutionSiteDto`), which says where it actually went. Two facts, two sentences, and\n * neither is the other's default.\n */\nexport function plannedExecutionSiteSentence(where: PlannedExecutionSiteDto): string {\n // ⚠ LOWERCASE, AND IT IS NOT A STYLE PREFERENCE. Every caller renders this INSIDE a clause\n // — \"Runs on …\" — so a sentence-cased value produced \"Runs on Your own network\", which is\n // what the browser showed and no test could. \"Opera's cloud\" keeps its capital because it\n // is a proper noun, not because it is the start of a sentence.\n switch (where.site) {\n case \"hosted\":\n return HOSTED_EXECUTION_LABEL;\n case \"runner\":\n return `your own network — runner pool “${where.pool.name}”`;\n // ⚠ THE CALLER MUST NOT RENDER THIS INSIDE \"Runs on …\", and the wording is what says so:\n // \"Runs on more than one place\" is not a sentence anybody wrote on purpose. `RunsOnCallout`\n // branches before it reaches here, because an ambiguous plan is a REFUSAL and gets the\n // refusal's own layout rather than a destination line with bad grammar.\n case \"ambiguous\":\n return `${where.places.length} different places`;\n }\n}\n\n/** Every distinct destination an ambiguous plan named, for a surface that lists them. */\nexport function ambiguousPlaceLabel(place: AmbiguousRoutingPlace): string {\n return place.poolName ? `runner pool “${place.poolName}”` : HOSTED_EXECUTION_LABEL;\n}\n","import type { ParameterSchema, RequiredPermission } from \"./catalog\";\nimport type {\n ConnectionScopeKind,\n ConnectionState,\n Environment,\n IdentityMechanism,\n Provider,\n} from \"./enums\";\n\nexport type AzureConnectionStatus = \"connected\" | \"consent_pending\" | \"error\";\n\nexport type ConnectionHealth =\n | \"connected\"\n | \"consent-needed\"\n | \"missing-permissions\"\n | \"unreachable\";\n\nexport type PermissionCheckStatus = \"ok\" | \"missing\" | \"unknown\" | \"unreachable\";\n\n/**\n * How Opera authenticates to the tenant's Azure. `federated` = real customer\n * onboarding (admin consent + a consented service principal). `dev` = local\n * development credential (DefaultAzureCredential) — there is NO consented SP, so the\n * consent identity and per-SP permission checks do not apply.\n */\nexport type ConnectionMode = \"dev\" | \"federated\";\n\n/**\n * Legacy Azure-only connection shape, embedded in {@link ConnectionStatusDto} and\n * returned by the `/connections/azure` status shim. The provider-neutral aggregate is\n * {@link ConnectionDto} (docs/24 §5.1). Kept for one release (docs/24 §12).\n */\nexport interface AzureConnectionDto {\n id: string;\n azureTenantId: string;\n spObjectId: string;\n status: AzureConnectionStatus;\n createdAt: string;\n}\n\nexport interface AdminConsentUrlDto {\n url: string;\n}\n\nexport interface ConnectionStatusDto {\n mode: ConnectionMode;\n health: ConnectionHealth;\n connection: AzureConnectionDto | null;\n adminConsent: AdminConsentUrlDto | null;\n permissionStatus: PermissionStatusDto | null;\n message: string;\n}\n\n/**\n * A connection NAMED, for a reader — the id it is keyed by and the name it is known as.\n *\n * The narrowest thing a screen can be given that lets it say WHICH connector without\n * being handed a connection aggregate it would then have to be trusted not to read the\n * rest of. Used wherever a run has to report the connector it went out under (docs/46\n * §3.3) — a set of these, never one, because a fan-out can span several.\n */\nexport interface ConnectionRef {\n id: string;\n name: string;\n}\n\n/**\n * Provider-neutral connection aggregate (docs/24 §5.1). One row = one governed,\n * verifiable binding to one external account. `identityRef`/`federationConfig`\n * carry references only, never a secret (charter §6). `scopeCount` is the number of\n * discovered scopes (subscriptions/accounts/…) under the connection.\n */\nexport interface ConnectionDto {\n id: string;\n provider: Provider;\n name: string;\n identityMechanism: IdentityMechanism;\n /** `true` when the mechanism is keyless workload-identity federation (docs/24 §6). */\n keyless: boolean;\n identityRef: Record<string, string>;\n status: ConnectionState;\n statusDetail: string | null;\n scopeCount: number;\n lastVerifiedAt: string | null;\n decommissionedAt: string | null;\n createdBy: string | null;\n createdAt: string;\n /**\n * The federated trust the customer must create in their own cloud portal (docs/24\n * §6.2, §10.2 step 4). Populated ONLY on the single-connection detail read (never in\n * the list) so the add-connector wizard can render the copyable issuer/subject/\n * audience + portal steps. Contains references only — never a secret.\n */\n trust?: TrustInstructionsDto | null;\n}\n\n/**\n * The keyless federated trust binding Opera issues per connection (docs/24 §6.2). The\n * customer configures their cloud to trust exactly `{ issuer, subject, audience }`, so\n * only that connection's subject may assume the identity. No secret is ever exchanged.\n */\nexport interface TrustInstructionsDto {\n issuer: string;\n subject: string;\n audience: string;\n /** Copyable, ordered steps for the customer's cloud portal. */\n steps: string[];\n}\n\n/**\n * Body of `POST /connections` (docs/24 §13, §10.2). Creates a DRAFT connection.\n * `values` is validated server-side against the provider adapter's\n * `onboardingSchema(mechanism)` (it carries the connection `name` + the provider's\n * `identity_ref` fields — references only, never a secret).\n */\nexport interface CreateConnectionInput {\n provider: Provider;\n mechanism: IdentityMechanism;\n values: Record<string, string>;\n}\n\n/** A discovered, governable scope under a connection (docs/24 §5.2). */\nexport interface ConnectionScopeDto {\n id: string;\n connectionId: string;\n providerScopeId: string;\n displayName: string;\n kind: ConnectionScopeKind;\n regionHint: string | null;\n active: boolean;\n discoveredAt: string;\n}\n\n/** Visual identity for a provider badge in the Connectors UI (docs/24 §7, §10.1). */\nexport interface ProviderBadgeDto {\n /** Short label rendered in the badge, e.g. \"Azure\". */\n label: string;\n /** Foreground/accent colour token or hex, consumed by the badge component. */\n color: string;\n}\n\n/**\n * ═══ A SECOND, PROVIDER-OWNED PALETTE — DECLARED HERE BECAUSE IT IS NOT OURS ═══════════\n *\n * docs/38 §3, verdict DECLARE-SEPARATE. A provider badge is painted in the PROVIDER's brand\n * colour: `#0078d4` is Microsoft's blue, not an Opera token, and it can never be mapped onto\n * `brand` or `info` without the badge ceasing to identify anything. So it is not laundered\n * into the design vocabulary — and it is not exempted either, because an exemption is where\n * the next one hides.\n *\n * It lives HERE, beside {@link ProviderBadgeDto}, because that makes it ONE declaration: the\n * provider adapter that serves it and the web fixture that mirrors it both read this map,\n * where before each held its own literal and the two had already drifted in case. A colour\n * that is data still has a declaration point; it is just not the Tailwind preset.\n *\n * What is governed about it: the badge renders white text on this fill, so every entry owes\n * the 4.5:1 AA floor against white — asserted in `__tests__/provider-badge-contrast.spec.ts`,\n * which reads THIS object, so a provider added next year cannot ship an unreadable badge.\n *\n * There is no fallback member. A provider that supplies no colour is not a provider colour\n * problem — it is Opera's neutral, so it stays in Opera's token layer (`ink-muted`) where\n * the rest of the neutral scale is.\n */\nexport const PROVIDER_BADGE_COLOR: Readonly<Record<string, string>> = {\n azure: \"#0078d4\",\n};\n\n/**\n * A registered provider, enumerated from the ProviderRegistry so the UI renders the\n * provider picker + badges from data, not hard-coded screens (docs/24 §7).\n */\nexport interface ProviderDto {\n key: Provider;\n label: string;\n badge: ProviderBadgeDto;\n mechanisms: IdentityMechanism[];\n /**\n * The onboarding field schema per identity mechanism (docs/24 §7, §10.2 step 3),\n * keyed by {@link IdentityMechanism}. The add-connector wizard renders these with the\n * existing parameter-form engine so \"which fields to collect\" stays data, not a\n * hard-coded screen. Each schema collects the connection `name` + the provider's\n * `identity_ref` references (never a secret).\n */\n onboarding: Record<string, ParameterSchema>;\n}\n\n/** Filters accepted by the connections list endpoint (docs/24 §13). */\nexport interface ConnectionListFilter {\n provider?: Provider;\n status?: ConnectionState;\n q?: string;\n includeDecommissioned?: boolean;\n}\n\n/**\n * Server-side resolution of the `connection_scope.id` a caller passes as `connectionScopeId`.\n *\n * ⚠ THIS COMMENT DESCRIBED A DUAL-WRITE PERIOD THAT ENDED, AND THE DESCRIPTION OUTLIVED IT.\n * It said the wizard passes the scope id \"as `subscriptionId`\", which was true while the two\n * ids were equal — the one-release Azure shim — and stopped being true when `connection_scope`\n * gained `connectionId` in its unique key. Nothing updated it, `ExecutionDto` went on exporting\n * `azure_subscription.id` under the same name, and Rerun posted one back as the other.\n *\n * ★ THIS TYPE ALREADY HAD THE RIGHT SHAPE THROUGHOUT, and is the reason the fix was small: it\n * carries `id` (the scope) and `legacyAzureSubscriptionId` (the registry row) as two fields\n * named for what they are. The inputs now do the same.\n */\nexport interface ResolvedConnectionScopeDto {\n id: string;\n connectionId: string;\n provider: Provider;\n connectionStatus: ConnectionState;\n connectionDecommissionedAt: string | null;\n providerScopeId: string;\n displayName: string;\n kind: ConnectionScopeKind;\n active: boolean;\n legacyAzureSubscriptionId: string | null;\n environment: Environment | null;\n}\n\nexport interface AdminConsentCallbackInput {\n adminConsent?: boolean | string;\n error?: string;\n errorDescription?: string;\n spObjectId?: string;\n}\n\n/**\n * The identity whose EFFECTIVE cloud permissions the check evaluated — i.e. the identity\n * the connector actually runs under (docs/30). Grant any missing role to THIS principal\n * in the provider portal. Present once a real check has run; the fields are populated\n * best-effort from the access token (a managed identity carries no display name, so\n * `clientId`/`objectId` are the fallbacks).\n */\nexport interface CheckedIdentity {\n /** Directory object id of the evaluated principal (token `oid`). */\n objectId: string | null;\n /** App/client id when the principal is an app or managed identity (token `appid`). */\n clientId: string | null;\n /** Human label when the token carries one (app display name, or a user's name/UPN). */\n displayName: string | null;\n}\n\nexport interface PermissionStatusDto {\n status: PermissionCheckStatus;\n subscriptionId: string;\n actionVersionId: string | null;\n checkedAt: string;\n requiredPermissions: RequiredPermission[];\n grantedRoles: string[];\n missingPermissions: RequiredPermission[];\n message: string;\n /** The identity the check evaluated; null when no real check ran (docs/30). */\n checkedIdentity?: CheckedIdentity | null;\n}\n","// Resource-discovery DTOs + the provider-namespaced discovery vocabulary (docs/20\n// §4.2, docs/29 D1/D2). Shared verbatim between the connections module (live ARM\n// discovery), the packages module (import validation), and apps/web (the\n// discovery-backed combobox). No NestJS/Prisma imports — pure shapes and helpers\n// only. Discovery is a UX convenience, not a security control: the server still\n// validates the real resource at execution time (docs/20 §2), so these types never\n// gate acceptance of a parameter value.\n\nimport { PROVIDERS, type Provider } from \"./enums\";\n\n/** Metadata for one discoverable resource type (docs/29 D2). */\nexport interface DiscoveryTypeSpec {\n /** Cascade scope keys this type's discovery needs before it can list anything. */\n requires: readonly string[];\n /**\n * ═══ IS A RESOURCE OF THIS TYPE SOMETHING A RUN MUST REACH? (docs/58) ═══════════════\n *\n * A runner pool binding rule is about REACHABILITY, so it needs to know which of an\n * action's parameters name a thing that sits on a network and which merely name a value\n * picked from a list. `azure.vm.resize` takes THREE discovery-backed parameters —\n * `resourceGroup`, `vm`, `vmSize` — and exactly one of them is a machine somebody has to\n * be able to talk to.\n *\n * ★ IT IS DECLARED ON THE TYPE, NOT DERIVED FROM THE ACTION, because every derivation\n * available is wrong. \"The leaf of the `dependsOn` chain\" answers `vmSize` for\n * `azure.vm.resize`; \"the last required parameter\" is authoring order. And it is\n * REQUIRED rather than optional so a new discovery type is a compile error here until\n * somebody answers it — the `AZURE_SUPPORTS: Record<IdentityMechanism, boolean>` rule.\n * A defaulted `false` would silently make a new resource type unroutable, which is the\n * one answer nobody chose.\n *\n * FALSE for a CATALOGUE VALUE (`vmSize`, `location`) and for a CONTAINER whose identity a\n * rule already matches on directly (`resourceGroup` — `TargetSelectorQuery.resourceGroups`\n * tests it as a field of the real target, so counting it as a target of its own would make\n * every VM run route on two resources and read as ambiguous).\n */\n routable: boolean;\n /**\n * ═══ HOW A RESOURCE OF THIS TYPE IS IDENTIFIED, WITHOUT ASKING THE PROVIDER (docs/69) ═══\n *\n * A template for the resource's own provider id, with `{placeholder}` segments filled from\n * three sources and nowhere else:\n *\n * | placeholder | filled from |\n * |------------------|------------------------------------------------------------------|\n * | `{subscription}` | the connection scope's `providerScopeId` |\n * | `{name}` | the value of the parameter that carries this type |\n * | anything else | the cascade scope key of that name (`identifiedBy ?? requires`) |\n *\n * ★ A TEMPLATE RATHER THAN A LOOKUP, BECAUSE docs/69 §8 FORBIDS THE LOOKUP. The id of a\n * resource a run NAMES is already determined by the run's own parameters plus the\n * subscription it runs against — it is a composition, not a discovery. Asking the provider\n * for it would put a `list` call on every plan, which docs/66 §8 refused when the cost was\n * only a credential mint. What the provider knows and this does not is the resource's TAGS\n * and whether it exists; neither is an identity, and `resolveScope` does not claim either.\n *\n * ★ NULL IS A REAL ANSWER AND MUST STAY REACHABLE. A catalogue value reaches nothing, so\n * there is no id to compose (`location`, `vmSize`). And `keyVault` has an ARM id this\n * vocabulary genuinely cannot compose: an ARM vault id is scoped to a RESOURCE GROUP, and\n * `keyVault.requires` is empty because vaults list subscription-wide — so nothing in a run\n * that names a vault carries the group its id needs. Composing one from a guessed group\n * would be a fabricated identity, which is the entire defect docs/69 exists to end. An\n * action whose only resource is a vault is therefore COUNTED AND HONESTLY UNNAMED, which\n * {@link TARGET_COUNT_ABSENCES} already has a word for.\n *\n * ★ REQUIRED, LIKE `routable` ABOVE, so a discovery type added next quarter is a compile\n * error here until somebody answers it. A defaulted `null` would make a new resource type\n * silently unnamable — the one answer nobody chose — and a defaulted template would be worse\n * still, because it would be wrong and would look right.\n */\n identity: string | null;\n /**\n * Cascade scope keys a resource of this type BELONGS to — what a fan-out binds per\n * child. Defaults to `requires`; the two differ only when a type can be LISTED more\n * broadly than it can be IDENTIFIED. `virtualMachine` lists subscription-wide but\n * still lives in one resource group, and a child that is not told which one acts on\n * the wrong machine.\n */\n identifiedBy?: readonly string[];\n /**\n * ═══ IS A RESOURCE OF THIS TYPE A POINTER TO A SECRET VALUE? (docs/122 §3.5) ══════════\n *\n * A parameter over a type that answers TRUE holds a REFERENCE — it names a secret, it never\n * is one. That is already how the platform behaves (charter §6: nothing stores, logs, caches\n * or evidences a secret value), but until this field existed nothing DECLARED it, so no\n * surface could treat such a value differently from a literal, and a later slice that\n * resolves references (docs/123) would have had nothing to key resolution off.\n *\n * ⚠ WHAT THE PARAMETER CARRIES IS THE SECRET'S NAME, NOT ITS URI. The picker yields\n * `ResourceSummaryDto.name`, and `azure.keyvault.rotateSecret` takes `secret` as a name inside\n * its `vault`. The URI is {@link identity}, composed from the two — which is exactly the value\n * discovery returns as `id`, so a named secret and a discovered one still compare equal.\n *\n * ★ REQUIRED, LIKE `routable`, so a discovery type added next quarter is a compile error here\n * until somebody has decided whether it points at a secret. A defaulted `false` would let the\n * first secret-bearing type of a new provider render, audit and evidence as a plain literal —\n * the one answer nobody chose, on the one field where it matters most.\n */\n secretRef: boolean;\n}\n\n// The Azure discovery vocabulary — EXACTLY the types the Azure adapter implements. Adding a\n// type here without its handler in `AzureResourceDiscovery` is a `pnpm typecheck` failure that\n// names the type (docs/122 §3.2): the handler table is typed off these keys. The\n// vocabulary-honesty spec (docs/29 §4.3) asserts the same at run time as a backstop.\nconst AZURE_DISCOVERY_TYPES = {\n // A CONTAINER, not a target of its own: `TargetSelectorQuery.resourceGroups` already\n // matches it as a FIELD of the real resource, so counting it separately would make every\n // ordinary VM run name two resources and read as ambiguous.\n resourceGroup: { requires: [], routable: false, identity: null, secretRef: false },\n // ROUTABLE BUT NOT NAMABLE, and the two are different questions. A rule matches a vault by\n // its NAME and its tags, which discovery supplies; an ARM vault id needs the resource group\n // this vocabulary never asks for (`requires` is empty so vaults list subscription-wide). See\n // `identity` on the spec above — null is the honest answer, not an omission.\n // NOT a secret reference: a vault CONTAINS secrets, and naming one reveals nothing a run\n // could read. The secret inside it is the reference (`keyVaultSecret` below).\n keyVault: { requires: [], routable: true, identity: null, secretRef: false },\n // ★ A DATA-PLANE URI, NOT AN ARM PATH, AND IT IS WHAT DISCOVERY ALREADY RETURNS. The Key\n // Vault SDK reports `SecretProperties.id` as `https://<vault>.vault.azure.net/secrets/<name>`\n // and `AzureResourceDiscovery.keyVaultSecret` passes it through untouched, so a secret named\n // from parameters and a secret found by discovery carry the SAME id — which is the only thing\n // that makes the two comparable at all.\n keyVaultSecret: {\n requires: [\"vault\"],\n routable: true,\n identity: \"https://{vault}.vault.azure.net/secrets/{name}\",\n // ★ THE ONE TYPE TODAY WHOSE VALUE POINTS AT A SECRET (docs/122 §3.5). The parameter holds\n // the secret's NAME within its vault; nothing in the platform ever reads the value behind it.\n secretRef: true,\n },\n // A catalogue value. Nothing is reached by naming a region.\n location: { requires: [], routable: false, identity: null, secretRef: false },\n managedDisk: {\n requires: [\"resourceGroup\"],\n routable: true,\n identity:\n \"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/disks/{name}\",\n secretRef: false,\n },\n sqlServer: {\n requires: [\"resourceGroup\"],\n routable: true,\n identity:\n \"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{name}\",\n secretRef: false,\n },\n sqlDatabase: {\n requires: [\"resourceGroup\", \"server\"],\n routable: true,\n identity:\n \"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{server}/databases/{name}\",\n secretRef: false,\n },\n // The one type where LISTING and IDENTIFYING are different questions. It lists\n // SUBSCRIPTION-WIDE when no resource group is given (`virtualMachines.listAll()`,\n // deriving each VM's own group from its ARM id) and narrows to\n // `virtualMachines.list(rg)` when one is — so `requires` is empty, which is what lets\n // \"every VM tagged env=dev\" fan out without an operator enumerating the estate by hand.\n // But every VM still LIVES in exactly one resource group, so a fanned-out child must be\n // told which: hence `identifiedBy`. Leaving that implied by `requires` is precisely how\n // a subscription-wide fan-out ends up deallocating the wrong same-named machine.\n // ★ `identifiedBy`, NOT `requires`, IS WHAT THE ID READS — and this type is the reason that\n // distinction exists. A VM LISTS subscription-wide (`requires: []`) but LIVES in exactly one\n // resource group, and its ARM id names that group. Composing the id from `requires` would\n // produce `/resourceGroups//providers/...` for every VM in the catalog.\n virtualMachine: {\n requires: [],\n identifiedBy: [\"resourceGroup\"],\n routable: true,\n identity:\n \"/subscriptions/{subscription}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}\",\n secretRef: false,\n },\n // The sizes ONE machine can actually be resized to right now — not the region's SKU\n // catalogue. `requires` is genuinely both fields' answer here: the safe set cannot be\n // computed without knowing WHICH machine, so listing and identifying ask the same\n // question and `identifiedBy` would only restate it.\n // NOT routable: a size is a value a run picks, not a machine it has to reach — which is\n // exactly why `routable` cannot be derived from the `dependsOn` chain, whose leaf this is.\n vmSize: { requires: [\"resourceGroup\", \"vm\"], routable: false, identity: null, secretRef: false },\n} as const satisfies Record<string, DiscoveryTypeSpec>;\n\n/**\n * ═══ ★ THE DECLARED VOCABULARY, PER PROVIDER, WITH ITS KEYS KEPT (docs/122 §3.1) ═══════\n *\n * `satisfies` rather than an annotation, for the reason `ACTION_LIFECYCLE_STANDING` uses it:\n * the annotation would widen every provider's map to `Record<string, …>` and throw away the\n * one fact the compiler needs — WHICH types each provider declares. Keeping the literal keys\n * is what lets {@link DiscoveryTypeOf} exist, and that is what makes a declared type with no\n * implementation a `pnpm typecheck` failure instead of a picker that silently lists nothing.\n *\n * ★ A NEW PROVIDER IS A COMPILE ERROR HERE until it has a slot, because the `satisfies` is\n * keyed on the {@link Provider} union.\n */\nconst DECLARED_DISCOVERY = {\n azure: AZURE_DISCOVERY_TYPES,\n aws: {},\n gcp: {},\n terraform: {},\n} as const satisfies Record<Provider, Readonly<Record<string, DiscoveryTypeSpec>>>;\n\n/**\n * The bare type names provider `P` declares. Distributive, so `DiscoveryTypeOf<Provider>` is\n * every provider's names together rather than only the ones they all share (which, with three\n * empty providers, would be none).\n */\nexport type DiscoveryTypeOf<P extends Provider> = P extends Provider\n ? Extract<keyof (typeof DECLARED_DISCOVERY)[P], string>\n : never;\n\n/**\n * ═══ ★★ WHAT CAN BE DISCOVERED AT ALL — THE UNION, QUALIFIED (docs/122 §2, §3.1) ═══════\n *\n * This was `keyof typeof AZURE_DISCOVERY_TYPES`: the universe of discoverable things defined\n * as \"whatever Azure's map happens to have\", so a manifest naming `aws/…` was refused at\n * ingest while `DISCOVERY_VOCABULARY` had a slot waiting for it. It is now DERIVED from every\n * provider's declared vocabulary, and nothing is ever added to it by hand.\n *\n * ★ QUALIFIED, BECAUSE TWO PROVIDERS MAY DECLARE THE SAME WORD. Azure has `location`; the next\n * provider will too, and the two are not the same thing. A union of BARE names would merge\n * them into one member and let either be dispatched to the other's adapter. `provider/type`\n * is the canonical id everywhere — wire, manifest, storage, logs. A bare id still RESOLVES\n * (to Azure — see {@link resolveDiscoveryType}) because pinned manifests and stored rows carry\n * them; it is never written as new.\n */\nexport type ResourceType = { [P in Provider]: `${P}/${DiscoveryTypeOf<P>}` }[Provider];\n\n/**\n * One vocabulary for every provider (docs/29 D2): {@link DECLARED_DISCOVERY}, widened for the\n * callers that look a type up by an arbitrary string (an authored manifest, a stored schema).\n * The SAME object — not a copy — so the literal-keyed view and this one cannot disagree.\n *\n * ⚠ DECLARED IS NOT DISCOVERABLE. This says what each provider's adapter WOULD implement; which\n * adapters are actually registered is a fact about the running build, and the types a platform\n * can serve are {@link liveDiscoveryTypes} of that registration — derived, never listed.\n */\nexport const DISCOVERY_VOCABULARY: Readonly<\n Record<Provider, Readonly<Record<string, DiscoveryTypeSpec>>>\n> = DECLARED_DISCOVERY;\n\n/**\n * A BARE discovery id is a legacy one, and every legacy id is Azure's (docs/29 D1): the\n * first-party catalog and every package pinned before `provider/type` existed wrote them.\n * Declared once so the rule has one author. Never used to WRITE an id — only to read one.\n */\nexport const LEGACY_DISCOVERY_PROVIDER = \"azure\" as const satisfies Provider;\n\n/** The canonical ids of one provider's declared types. Read at call time, never cached. */\nexport function discoveryTypesOf(provider: Provider): ResourceType[] {\n return Object.keys(DISCOVERY_VOCABULARY[provider]).map(\n (type) => formatDiscoveryType(provider, type) as ResourceType,\n );\n}\n\n/** Every type ANY provider declares, qualified — the universe, not what this build serves. */\nexport function declaredDiscoveryTypes(): ResourceType[] {\n return PROVIDERS.flatMap(discoveryTypesOf);\n}\n\n/**\n * ═══ ★ THE LIVE SET — DERIVED FROM REGISTRATION, NEVER DECLARED TWICE (docs/122 §3.2) ══\n *\n * The same relationship `LISTED_ACTION_LIFECYCLES` has to `ACTION_LIFECYCLE_STANDING`: one\n * declaration (the vocabulary), one fact about the build (which providers have a registered\n * adapter), and the answer computed from the two. A hand-kept \"discoverable types\" list would\n * be correct only until somebody registered or declared something.\n *\n * ★ SOUND BECAUSE A REGISTERED ADAPTER CANNOT SERVE LESS THAN ITS PROVIDER DECLARES — that is a\n * compile error in the adapter (`DiscoveryHandlers` in the api's connections module), not a\n * boot check. So \"every declared type of every registered provider\" IS what the platform can\n * discover, and not merely what it hopes to.\n */\nexport function liveDiscoveryTypes(registered: Iterable<Provider>): ResourceType[] {\n const providers = new Set(registered);\n return PROVIDERS.filter((provider) => providers.has(provider)).flatMap(discoveryTypesOf);\n}\n\n/**\n * The canonical `provider/type` form of an authored id, WHETHER OR NOT any provider declares\n * the type — a bare id reads as {@link LEGACY_DISCOVERY_PROVIDER}'s. `null` only for a\n * malformed id or an unknown provider namespace, which are authoring errors rather than gaps.\n * What every writer stores, so no bare id is ever written as new (docs/122 §3.1).\n */\nexport function canonicalDiscoveryId(value: string): string | null {\n const parsed = parseDiscoveryType(value.trim(), LEGACY_DISCOVERY_PROVIDER);\n return parsed ? formatDiscoveryType(parsed.provider, parsed.type) : null;\n}\n\n/** A discovery id resolved to a DECLARED type: canonical id, its parts, and its spec. */\nexport interface ResolvedDiscoveryType {\n /** The canonical, qualified id — what is written, compared and logged. */\n id: ResourceType;\n provider: Provider;\n /** The bare name inside the provider's vocabulary — what the provider's adapter is handed. */\n type: string;\n spec: DiscoveryTypeSpec;\n}\n\n/**\n * ★ THE ONE RESOLUTION OF AN AUTHORED DISCOVERY ID (docs/122 §3.1).\n *\n * `azure/virtualMachine` and the legacy bare `virtualMachine` resolve to the SAME type. A bare\n * id resolves to {@link LEGACY_DISCOVERY_PROVIDER} and nowhere else — so a bare id naming\n * another provider's type does not resolve at all, rather than resolving to whichever provider\n * happens to declare that word. Returns `null` for a malformed id, an unknown provider, or a\n * type its provider does not declare.\n */\nexport function resolveDiscoveryType(value: string): ResolvedDiscoveryType | null {\n const parsed = parseDiscoveryType(value.trim(), LEGACY_DISCOVERY_PROVIDER);\n if (!parsed) return null;\n const spec = discoveryTypeSpec(parsed.provider, parsed.type);\n if (!spec) return null;\n return {\n id: formatDiscoveryType(parsed.provider, parsed.type) as ResourceType,\n provider: parsed.provider,\n type: parsed.type,\n spec,\n };\n}\n\n/**\n * Whether a parameter holds a REFERENCE to a secret rather than a literal — read off its\n * discovery type's `secretRef`, never guessed from a label (docs/122 §3.5). One answer for every\n * surface that marks it: a form, a review, and later the resolver docs/123 keys off it.\n */\nexport function isSecretReference(discover: string | undefined): boolean {\n return discover ? resolveDiscoveryType(discover)?.spec.secretRef === true : false;\n}\n\n/**\n * Canonical discovery-id format (docs/29 D1): optional `<provider>/` prefix plus a\n * camelCase type. Group 1 = provider prefix (absent for a bare legacy id), group 2 =\n * the resource type.\n */\nexport const DISCOVERY_TYPE_PATTERN = /^(?:([a-z][a-z0-9]*)\\/)?([a-z][a-zA-Z0-9]{0,63})$/;\n\nexport interface ParsedDiscoveryType {\n provider: Provider;\n type: string;\n}\n\n/**\n * Parse a discovery id (docs/29 D1). Returns `null` for a malformed value or an\n * unknown provider prefix. A bare value resolves against `fallbackProvider` (legacy\n * pinned ids are always Azure), or `null` when no fallback is given.\n */\nexport function parseDiscoveryType(\n value: string,\n fallbackProvider?: Provider,\n): ParsedDiscoveryType | null {\n const match = DISCOVERY_TYPE_PATTERN.exec(value);\n if (!match) return null;\n const [, prefix, type] = match;\n if (prefix !== undefined) {\n const provider = PROVIDERS.find((p) => p === prefix);\n return provider ? { provider, type: type! } : null;\n }\n return fallbackProvider ? { provider: fallbackProvider, type: type! } : null;\n}\n\n/** Format the canonical `<provider>/<type>` discovery id (docs/29 D1). */\nexport function formatDiscoveryType(provider: Provider, type: string): string {\n return `${provider}/${type}`;\n}\n\n/**\n * Look up a type's vocabulary entry; `undefined` for unknown provider or type.\n *\n * ⚠ OWN PROPERTIES ONLY. The vocabulary is a plain object and `DISCOVERY_TYPE_PATTERN` admits\n * `constructor`, `toString` and `valueOf`, so a bare index answered `azure/constructor` with\n * `Object` itself — a \"declared type\" nobody declared, and truthy everywhere a spec is tested.\n */\nexport function discoveryTypeSpec(\n provider: string,\n type: string,\n): DiscoveryTypeSpec | undefined {\n if (!Object.prototype.hasOwnProperty.call(DISCOVERY_VOCABULARY, provider)) return undefined;\n const vocabulary = DISCOVERY_VOCABULARY[provider as Provider];\n return Object.prototype.hasOwnProperty.call(vocabulary, type) ? vocabulary[type] : undefined;\n}\n\n/**\n * Map each cascade scope key to the action parameter that carries its value.\n *\n * Lives here, beside the vocabulary it interprets, because BOTH sides of the platform read\n * it and they must not diverge: the server builds discovery scopes and binds each fanned-out\n * child through it, and the builder decides which inputs to show through it. It moved out of\n * the API for exactly that reason — a second copy is how the form and the engine end up\n * disagreeing about what the author is being asked for.\n *\n * `dependsOn` comes in two shapes: an array, where each entry is a sibling parameter that\n * doubles as its own scope key, and an object mapping scope key → parameter name for when\n * the two differ. A key with no entry defaults to a parameter of the same name.\n */\nexport function dependsOnLookup(\n keys: readonly string[],\n dependsOn: string[] | Record<string, string> | undefined,\n): Record<string, string> {\n const lookup: Record<string, string> = {};\n for (const key of keys) lookup[key] = key;\n if (Array.isArray(dependsOn)) {\n for (const name of dependsOn) if (keys.includes(name)) lookup[name] = name;\n } else if (dependsOn) {\n for (const [key, name] of Object.entries(dependsOn)) {\n if (typeof name === \"string\" && name.trim()) lookup[key] = name.trim();\n }\n }\n return lookup;\n}\n\n/**\n * The cascade scope one discovery call needs, read out of a step's own parameters.\n *\n * ★ ONE DERIVATION, TWO MESSAGES. Both the fan-out's `buildDiscoveryScopes` and the run\n * path's single-target routing lookup (docs/58) have to turn \"this type requires\n * `resourceGroup` and `server`\" into \"…so read those two parameters\". Writing it twice is\n * charter §4.2's shape, and the two copies would diverge the first time `dependsOn` grew a\n * form. So the DERIVATION lives here and returns a discriminated result carrying only the\n * FACT — which key had no value — while each caller renders the refusal its own reader needs.\n *\n * A missing key is never a silent `{}`: discovery would answer `[]` for an absent cascade\n * value, and an empty result is indistinguishable from \"nothing matched\".\n */\nexport type DiscoveryScopeValues =\n | { resolved: true; scope: Record<string, string> }\n | { resolved: false; missingKey: string; parameter: string };\n\nexport function discoveryScopeValues(\n requires: readonly string[],\n dependsOn: string[] | Record<string, string> | undefined,\n parameters: Record<string, unknown>,\n /** Keys the caller supplies itself — the fan-out varies `resourceGroup` per named group. */\n skipKeys: readonly string[] = [],\n): DiscoveryScopeValues {\n const parameterFor = dependsOnLookup(requires, dependsOn);\n const scope: Record<string, string> = {};\n for (const key of requires) {\n if (skipKeys.includes(key)) continue;\n const parameter = parameterFor[key] ?? key;\n const value = parameters[parameter];\n if (typeof value !== \"string\" || value.trim().length === 0) {\n return { resolved: false, missingKey: key, parameter };\n }\n scope[key] = value.trim();\n }\n return { resolved: true, scope };\n}\n\n/**\n * ═══ THE PROVIDER ID OF A RESOURCE A RUN NAMES (docs/69 §3.1) ══════════════════════════\n *\n * Fills {@link DiscoveryTypeSpec.identity}'s template from the run's own values. Lives here,\n * beside the vocabulary it interprets, for the reason {@link discoveryScopeValues} does: the\n * template is data in this file, and a reader of it that lived somewhere else would be a\n * second place that decides what `{resourceGroup}` means.\n *\n * ★ IT REFUSES RATHER THAN LEAVING A HOLE, and that is the whole point of returning a union.\n * A template with an unfilled placeholder composes to\n * `/subscriptions/…/resourceGroups//providers/…` — a string that is not any resource's id, on\n * a field whose entire job is to say WHICH one. That is a fabricated identity wearing a\n * plausible shape, which is the defect docs/69 exists to end; `stub-target-1` at least looked\n * like a stub. So a missing value is named, and the caller records an absence.\n *\n * ⚠ EVERY VALUE IS TRIMMED AND NONE IS ESCAPED. These are provider resource names, which the\n * provider itself constrains to alphanumerics, dashes, underscores and periods — there is no\n * separator here for a name to smuggle. A name that DID contain a slash would compose an id\n * that simply matches nothing, which is a wrong answer and not an unsafe one: nothing executes\n * against this value. The connector re-reads the parameters it acts on (docs/20 §2).\n */\nexport type ComposedTargetIdentity =\n | { composed: true; resourceId: string }\n | { composed: false; missing: string };\n\nexport function composeTargetIdentity(\n template: string,\n values: Readonly<Record<string, string>>,\n): ComposedTargetIdentity {\n let missing = \"\";\n const resourceId = template.replace(/\\{([a-zA-Z][a-zA-Z0-9]*)\\}/g, (_whole, key: string) => {\n const value = values[key]?.trim();\n if (!value) {\n // The FIRST unfilled placeholder is the one reported: a reader fixing a template needs\n // one name to act on, and the rest are usually consequences of the same missing input.\n if (!missing) missing = key;\n return \"\";\n }\n return value;\n });\n return missing ? { composed: false, missing } : { composed: true, resourceId };\n}\n\n/**\n * The parameter NAMES a fan-out sets per target — and which the author must therefore not\n * be asked for.\n *\n * ONE derivation, read by the step form and by the server's authoring-time exemption, so a\n * field the form hides cannot be a field the server then reports as missing. Computing this\n * in two places is precisely what shipped a required \"Resource group\" input above the\n * sentence explaining that the fan-out fills the parameters in.\n *\n * A parameter is supplied when the fan-out SETS it and discovery does not CONSUME it:\n *\n * • the SELECTOR's own parameter, always — it is the resource being fanned out over;\n * • every key in `identifiedBy ?? requires` that discovery does not need as a literal.\n * A key absent from `requires` is never read by discovery at all (`virtualMachine`\n * lists subscription-wide and is identified by its resource group afterwards), and a\n * key the selector's own query VARIES is supplied by the varying rather than by the\n * step — `buildDiscoveryScopes` issues one call per named resource group, so the\n * step's single literal is already dead.\n *\n * A key that IS required and is NOT varied stays the author's to fill: for `managedDisk`\n * the resource group is the listing scope, and removing that input would break resolution.\n */\nexport function fanOutSuppliedParameters(input: {\n spec: DiscoveryTypeSpec;\n /** The `dependsOn` of the selector's parameter, in either supported form. */\n dependsOn: string[] | Record<string, string> | undefined;\n selectorParameter: string;\n /**\n * Cascade keys the selector's own query varies, e.g. `[\"resourceGroup\"]` when\n * `query.resourceGroups` is non-empty.\n */\n variedByQuery?: readonly string[];\n}): string[] {\n const { spec, dependsOn, selectorParameter, variedByQuery = [] } = input;\n const identity = spec.identifiedBy ?? spec.requires;\n const lookup = dependsOnLookup(identity, dependsOn);\n const varied = new Set(variedByQuery);\n\n const supplied: string[] = [];\n const push = (name: string): void => {\n const trimmed = name.trim();\n if (trimmed && !supplied.includes(trimmed)) supplied.push(trimmed);\n };\n\n push(selectorParameter);\n for (const key of identity) {\n if (spec.requires.includes(key) && !varied.has(key)) continue;\n push(lookup[key] ?? key);\n }\n return supplied;\n}\n\n/**\n * One discovered Azure resource, narrowed to what the picker needs (docs/20 §4.1).\n * `name` is what the connector consumes as the parameter value; `id` is the full ARM\n * resource id; `resourceGroup`/`location` are optional context for disambiguation.\n */\nexport interface ResourceSummaryDto {\n id: string;\n name: string;\n resourceGroup?: string;\n location?: string;\n /**\n * Provider tags, when the listing carries them (docs/31 §8.2). Tags are how ops teams\n * actually name a fleet (`env=dev`), so target selection by tag needs them at\n * discovery time — without this field `TargetSelector.query.tags` could not be\n * honoured and must not be offered. Absent (rather than `{}`) for a resource kind\n * that has no tags at all, so \"untagged\" and \"tags unknown\" stay distinguishable.\n */\n tags?: Record<string, string>;\n}\n\n/**\n * ═══ A PICKER'S ANSWER — BOUNDED, AND SAYING SO (docs/122 §3.7) ═══════════════════════════\n *\n * What `GET …/resources` returns. It was a bare array with no bound at all: a subscription\n * with five thousand machines put five thousand rows into a wizard picker. A bound alone would\n * be worse than none — a picker showing a thousand rows of five thousand, without saying so,\n * teaches an operator that the list is the world. So the bound and the fact that it bit travel\n * together, and a surface that renders the list is handed both or neither.\n *\n * ⚠ THE PICKER PATH ONLY. Target resolution is strict and unbounded here on purpose: it has its\n * own `TargetSelector.limit`, which REFUSES a run rather than shortening it (docs/31 §8.3).\n */\nexport interface ResourceDiscoveryPageDto {\n /** At most `limit` resources, sorted by name. */\n resources: ResourceSummaryDto[];\n /**\n * TRUE when the provider had MORE than `limit` to offer and the rest were not listed. How\n * many more is not known — finding out would mean listing all of them, which is the cost the\n * bound exists to avoid — so a surface says \"more than\", never a total.\n */\n truncated: boolean;\n /** The bound this answer was cut at. */\n limit: number;\n}\n\n/**\n * ═══ WHAT THIS PLATFORM CAN DISCOVER — AND WHAT THIS WORKSPACE CAN (docs/122 §3.3) ═══════\n *\n * Two different questions, and a screen that answers one while asking the other lies:\n *\n * `registered` — THE PLATFORM CAN: this build registers an adapter for the provider.\n * `activeConnections` — YOU CAN, HERE: this workspace has an active connection to use it.\n *\n * A provider can be registered with no connection here (discoverable in principle, not yet by\n * you), and a provider can have declared types with no adapter at all (a manifest may name\n * them; they render as free text). Every provider is listed, so the second case is visible too.\n */\nexport interface DiscoveryCapabilitiesDto {\n providers: ProviderDiscoveryCapabilityDto[];\n}\n\nexport interface ProviderDiscoveryCapabilityDto {\n provider: Provider;\n /** An adapter for this provider is registered in this build. */\n registered: boolean;\n /** This workspace's connections to the provider that are active and not decommissioned. */\n activeConnections: number;\n /** Every type the provider DECLARES — discoverable only when `registered` is true. */\n types: DiscoveryTypeCapabilityDto[];\n}\n\nexport interface DiscoveryTypeCapabilityDto {\n /** The canonical, qualified id. */\n id: ResourceType;\n requires: string[];\n routable: boolean;\n secretRef: boolean;\n}\n","// Governance DTOs — shared verbatim between the API (governance module) and\n// apps/web (Approval Center). Single source of truth, mirroring execution.ts. No\n// NestJS/Prisma/Azure imports — only closed value sets from ./enums.\nimport type { RequiredPermission, WorkflowStep } from \"./catalog\";\nimport type { PackageProvenanceKind } from \"./package-provenance\";\nimport type { PlannedExecutionSiteDto } from \"./execution-site\";\nimport type { EgressDisclosureDto } from \"./package-egress\";\nimport { recordedDecisionsOf } from \"./decisions\";\nimport type { RecordedDecision, TargetDisposition } from \"./decisions\";\nimport type { ValidationCheck } from \"./validation\";\nimport type {\n ApprovalDecisionKind,\n ApprovalStatus,\n Environment,\n RiskLevel,\n} from \"./enums\";\nimport type {\n ChangeControlRule,\n ChangeRecordAssurance,\n ChangeRecordCitation,\n ChangeRecordType,\n ExecutionPlanChangeControl,\n PolicyKind,\n} from \"./change-control\";\n\n/**\n * WHAT an approval governs. Exactly one of the two, mirroring the database CHECK.\n *\n * The run-step subject exists because policy is evaluated per ACTION and a fan-out step\n * runs one action over many targets: gating each target's execution separately produced N\n * cards and N justifications for one human decision, which is how a real audit trail\n * degrades into \"das\"/\"dasd\". One step, one gate, one justification.\n */\nexport type ApprovalSubject =\n | { kind: \"execution\"; executionId: string }\n | { kind: \"operation_run_step\"; operationRunStepId: string };\n\nexport type ApprovalSubjectKind = ApprovalSubject[\"kind\"];\n\n/**\n * ═══ THE GROUP WHOSE MEMBERS DECIDE (docs/47) ══════════════════════════════════════════\n *\n * `approverGroup` was a free-text string naming a concept the governance engine never read:\n * `permissionForApproverGroup` returned `approval:decide` for every input, and the approver\n * fan-out asked everyone holding it. The field READ as \"only this team may approve\" and did\n * nothing — so every UI treatment of it was a differently-shaped lie, and a picker over the\n * tenant's real groups would have been the most convincing one.\n *\n * It is a REFERENCE now. A named group scopes BOTH halves (§3.2): a user may decide only if\n * they hold `approval:decide` AND belong to it, and the fan-out asks that group's members\n * rather than everyone. NULL means \"any approver\" — which is not a new behaviour but the\n * current one finally stated truthfully.\n *\n * ─── WHY THE PAIR TRAVELS TOGETHER ──────────────────────────────────────────────────────\n *\n * The id is what DECIDES; the name is what an auditor READS. On the rule they are separate\n * fields, because the rule authors an id and the name is resolved on read (exactly like\n * `connectionId`/`connectionName`). From the decision onward they move as one value, because\n * the approval record must store both at request time (§3.7): membership changes, and\n * reconstructing \"who was eligible then\" from an id whose group has since been renamed or\n * deleted is not reconstruction.\n */\nexport interface ApproverGroupRef {\n id: string;\n /** The group's name AT THE MOMENT it was recorded — never re-resolved for an audit read. */\n name: string;\n}\n\n/**\n * Which Operation, which step, and HOW MANY TARGETS a run-step approval covers.\n * Denormalized onto the `approval_request` context so the card says what it authorises —\n * a card that looks like a single-execution card while authorising forty machines is\n * worse than forty honest cards.\n */\nexport interface ApprovalOperationContext {\n runId: string;\n /** The run's own reference, e.g. \"OPR-4821\". */\n runReference: string;\n operationName: string;\n /** The step's stable author-facing key. */\n stepKey: string;\n /** 1-based position of this step, and how many steps the run has. */\n position: number;\n totalSteps: number;\n /** How many targets this approval covers — always the TRUE count. */\n targetCount: number;\n}\n\n/**\n * One pending (or resolved) approval as the Approval Center renders it. Built\n * entirely from `approval_request` — including the denormalized `context` display\n * fields — so a card is self-contained with no governance→execution read (which\n * would close a forbidden module cycle, docs/12 §2.4).\n */\nexport interface ApprovalListItemDto {\n id: string;\n /** What this approval governs. `executionId` below is the legacy read of the same fact. */\n subject: ApprovalSubject;\n /**\n * Null for a run-step subject: the executions do not exist yet when the gate opens, and\n * that is the point — nothing may mutate the cloud before a human decides.\n */\n executionId: string | null;\n /** Present only for a run-step subject; null for an execution. */\n operationRun: ApprovalOperationContext | null;\n /** The execution's human reference, e.g. \"OPS-4821\" (denormalized). */\n reference: string;\n /** Display name of the action being governed (denormalized). */\n actionName: string;\n /** Action key, e.g. \"azure.keyvault.rotateSecret\" (denormalized). */\n actionKey: string;\n environment: Environment;\n riskLevel: RiskLevel;\n status: ApprovalStatus;\n /**\n * The group whose members may decide this request, captured when it was opened (§3.7).\n * Null means any approver — the request is open to everyone holding `approval:decide`.\n */\n approverGroup: ApproverGroupRef | null;\n /** ISO-8601 timestamp the request was opened. */\n requestedAt: string;\n /** The submitter's user id — the decider must differ (separation of duties). */\n requestedBy: string;\n /**\n * True when the CURRENT VIEWER may self-approve THIS request under break-glass:\n * the tenant's matching policy enables it AND the viewer is an admin. The\n * requester may then decide their own request, but only with a written\n * justification.\n */\n breakGlassEligible: boolean;\n}\n\n/** The chosen scope a governed run targets, denormalized for the approver. */\nexport interface ApprovalPlanScope {\n displayName: string;\n /** External provider scope id, e.g. the Azure subscription GUID. */\n providerScopeId: string;\n}\n\n/** One parameter, pre-formatted for display (booleans → Yes/No, empty → —). */\nexport interface ApprovalPlanParameter {\n label: string;\n value: string;\n}\n\n/** One resolved target inside an approved fan-out plan. */\nexport interface ApprovalPlanTarget {\n /** The provider resource id — the identity the drift guard compares on. */\n ref: string;\n /** What an operator reads, e.g. \"app-01 (rg-payments)\". */\n label: string;\n /**\n * ═══ WHETHER THIS APPROVAL COVERS ACTING ON IT (docs/126 §14 B-4) ════════════════════\n *\n * `ready` targets are the approved set — the only ones the drift guard compares and the only\n * ones the run acts on. `left_out` (the requester's choice) and `refused` (the platform's) are\n * listed so the approver sees every target the step resolved, and why some are not in the plan.\n * A snapshot written before docs/126 Slice B carries none and is read as `ready`: every target\n * on it was in the approved set.\n */\n disposition: TargetDisposition;\n /**\n * Why a `refused` target is not acted on, in the checks' own words. `null` for a `ready` target\n * and for a `left_out` one — the requester left it out, and the card names the requester.\n */\n reason: string | null;\n /**\n * ═══ WHAT THE REQUESTER SAW ABOUT THIS TARGET, AND WHAT THEY DECIDED (docs/126 §4) ═══\n *\n * The facts, the warnings, and each DECIDE check with the requester's acknowledgement — the\n * run as the requester saw it, plus what they chose. The approver approves the DECISIONS, not\n * just the target: one who disagrees with \"include the disk detached yesterday\" rejects the\n * run. There is no partial approval, because a partial approval is a plan nobody reviewed.\n *\n * ⚠ `null` MEANS NOBODY CHECKED THIS TARGET BEFORE THE GATE, AND IT IS NOT \"NOTHING TO SAY\".\n * Since docs/126 Slice B an Operation fan-out is checked per target when the run is started, so\n * `null` is: a step whose action plans no checks, a step whose parameters come from an earlier\n * step's outputs, a scheduled run (nobody to ask), a target that is not `ready`, and every\n * snapshot written before docs/126. An empty assessment would tell an approver of forty disks\n * that none is locked or recent, which nobody has looked at; `null` is the honest absence.\n */\n assessment: ApprovalPlanTargetAssessment | null;\n}\n\n/**\n * One target's pre-flight, as the requester read it and as the server verified it at submit.\n *\n * ★ THREE LISTS AND NOT A CHECK ARRAY, because they are three different things to the person\n * deciding: context, risks nobody has to decide about, and risks somebody did decide about. There\n * is no fourth list for refusals — a plan with a REFUSE check is refused at submit and never\n * reaches an approver.\n */\nexport interface ApprovalPlanTargetAssessment {\n /** INFORM — what the target is: SKU, size, region, age, encryption, tags, … */\n facts: string[];\n /** `warn` checks that ask for no decision. */\n warnings: string[];\n /** Every DECIDE check the plan raised, with who acknowledged it and when. */\n decisions: ApprovalPlanDecision[];\n}\n\n/** A DECIDE check as the approver reads it: the sentence the requester read, and their answer. */\nexport interface ApprovalPlanDecision extends RecordedDecision {\n /** The check's sentence, exactly as the requester was shown it. */\n title: string;\n}\n\n/**\n * The targets a run-step approval covers — THE APPROVED SET, in full.\n *\n * Not a sample: after the decision the step re-resolves and compares against this exact\n * set, failing rather than running if anything was added, removed or changed. An approver\n * who signed off on three machines must never have authorised six. The UI caps what it\n * RENDERS and always shows `total` beside it.\n *\n * ★ `total` COUNTS THE `ready` TARGETS — the set approving covers (docs/126 §14 B-4). The list\n * holds them first, then the targets left out, then the targets refused, so the approver sees\n * every target the step resolved; only the first group is authorised.\n */\nexport interface ApprovalPlanTargets {\n total: number;\n targets: ApprovalPlanTarget[];\n}\n\n/**\n * ═══ THE TARGET AS THE REQUESTER SAW IT, FOR THE APPROVER (docs/126 §4) ═════════════════\n *\n * The connector's checks sorted into what they are to a person deciding: facts, warnings nobody\n * had to decide about, and each decision with who made it. A check with an `error` level cannot be\n * here — a target with one is refused, never put in front of an approver as one to act on.\n *\n * ★ ONE AUTHOR, TWO WRITERS: a single run's submit (execution) and an Operation run's start,\n * per target (operations, docs/126 §14 B-3). The approver reads the same three lists from both.\n */\nexport function approvalAssessmentOf(\n checks: readonly ValidationCheck[],\n decided: readonly RecordedDecision[],\n): ApprovalPlanTargetAssessment {\n const assessment: ApprovalPlanTargetAssessment = { facts: [], warnings: [], decisions: [] };\n for (const check of checks) {\n if (check.decision) {\n const answer = decided.find((decision) => decision.code === check.decision);\n if (answer) assessment.decisions.push({ ...answer, title: check.title });\n } else if (check.level === \"warn\") {\n assessment.warnings.push(check.title);\n } else if (check.level === \"info\") {\n assessment.facts.push(check.title);\n }\n }\n return assessment;\n}\n\n/**\n * ═══ READING AN ASSESSMENT BACK FROM JSONB — NEVER CAST (docs/126 §4) ════════════════════\n *\n * Kept on the approval snapshot and on an Operation run's target plan. `null` for anything\n * malformed.\n *\n * ★ ONE UNREADABLE DECISION MAKES THE WHOLE ASSESSMENT ABSENT, NOT SHORTER. The approver approves\n * the decisions; a list that silently lost one would be a different plan from the one decided,\n * shown as if it were the whole. Absent is the honest failure.\n */\nexport function planAssessmentOf(value: unknown): ApprovalPlanTargetAssessment | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n const a = value as Record<string, unknown>;\n if (!Array.isArray(a.facts) || !Array.isArray(a.warnings) || !Array.isArray(a.decisions)) {\n return null;\n }\n const decisions: ApprovalPlanDecision[] = [];\n for (const entry of a.decisions) {\n const [decision] = recordedDecisionsOf([entry]);\n const title =\n typeof entry === \"object\" && entry !== null ? (entry as Record<string, unknown>).title : null;\n if (!decision || typeof title !== \"string\") return null;\n decisions.push({ ...decision, title });\n }\n const strings = (list: unknown[]): string[] =>\n list.filter((item): item is string => typeof item === \"string\");\n return { facts: strings(a.facts), warnings: strings(a.warnings), decisions };\n}\n\n/**\n * A denormalized, reviewable snapshot of the governed run — captured on the\n * `approval_request` at submit time so an approver can inspect exactly what they are\n * approving (operation, target scope, parameters, dry-run vs live, the RBAC it needs,\n * and the declared workflow) WITHOUT governance ever reading the execution table (which\n * would close a forbidden module cycle, docs/12 §2.4). The mirror of the run wizard's\n * Plan step, for the person on the other side of separation of duties.\n */\nexport interface ApprovalPlanDto {\n actionName: string;\n actionKey: string;\n /** The pinned action version, e.g. \"v2.1.0\". */\n version: string;\n riskLevel: RiskLevel;\n environment: Environment;\n /** True when the run only simulates — no resources change. */\n dryRun: boolean;\n scope: ApprovalPlanScope | null;\n parameters: ApprovalPlanParameter[];\n /** The declared Azure RBAC the run needs (from the pinned action version). */\n requiredPermissions: RequiredPermission[];\n /** The ordered \"what will happen\" steps declared by the action version. */\n workflow: WorkflowStep[];\n /**\n * The resolved fan-out this approval covers. Null for an execution subject and for a\n * run step that resolved no selector — both of which act on exactly one thing.\n */\n targets: ApprovalPlanTargets | null;\n /**\n * The outbound network this run will get, and HOW MUCH that is worth on the substrate that\n * will run it (slice 6b-II). Null for a built-in connector, which has no package and no\n * declared allowlist, and for approvals opened before this shipped.\n *\n * The approver is the reason this field exists. They are the reader furthest from the\n * deployment and the one whose \"yes\" carries the most, so the difference between an\n * allowlist that cannot be exceeded and one that merely was not exceeded has to be in front\n * of them at the moment they decide — not discoverable afterwards in a bundle.\n */\n egress: EgressDisclosureDto | null;\n /**\n * ═══ WHERE THIS RUN WILL EXECUTE, IN FRONT OF THE PERSON APPROVING IT (docs/56 §3.4) ══\n *\n * The approver is the reason this field exists, for the same reason `egress` above is: they\n * are the reader furthest from the deployment and the one whose \"yes\" carries the most.\n * An approver deciding a run is entitled to know it will execute on machines the CUSTOMER\n * operates rather than in Opera's cloud (docs/56 §3.2) — the install panel already says as\n * much to whoever installs a runner, and if it is worth telling them it is worth telling\n * the person who approves the work.\n *\n * ★ `null` MEANS THE SNAPSHOT PREDATES THIS FIELD, AND MUST NOT RENDER AS \"OPERA'S CLOUD\".\n * Same rule the record follows (`RunExecutionSiteDto`'s `unknown`) and the same rule\n * `toPlanEgress` follows: degrading to the reassuring member of a vocabulary is precisely\n * how a security field starts lying.\n */\n executesOn: PlannedExecutionSiteDto | null;\n /**\n * ═══ …AND WHOSE CODE IT IS (docs/59 §3.3) ════════════════════════════════════════════\n *\n * ★ THE APPROVER IS THE READER THIS FIELD EXISTS FOR, AND MORE SO THAN THE FIELD ABOVE.\n * Since docs/59 an action package CAN execute on a customer's own machine, if that\n * customer's administrator accepted its provenance on that pool. The approver is a\n * different person from that administrator, deciding a different question — this run, now —\n * and \"an admin accepted this class of code six weeks ago\" is not something they can see\n * from anywhere else on the card.\n *\n * ⚠ `null` IS \"THIS RUN EXECUTES NO PACKAGE\", and — on a snapshot written before this field\n * existed — \"not recorded\". Unlike `executesOn`, the two do not need separating: the field\n * is only ever RENDERED beside `executesOn.site === \"runner\"`, and before docs/59 no package\n * could reach a runner at all, so no pre-existing snapshot can be hiding one.\n */\n packageProvenance: PackageProvenanceKind | null;\n /**\n * ═══ ★ THE RECORD THIS RUN NAMED, AND WHETHER OPERA CHECKED IT (docs/84 §3.3) ════════\n *\n * Null when the run named none — every run in a workspace with no change-control rule, and\n * every snapshot written before this field existed.\n *\n * ★ THE APPROVER IS THE READER THIS FIELD EXISTS FOR, for the same reason `egress` and\n * `executesOn` name them: they are furthest from the deployment and their \"yes\" carries the\n * most. And they are the reader for whom a bare `CHG0031425` is most dangerous — a change\n * reference on an approval card reads as a change that was checked, so the card says which\n * it was. An approver signing off a `recorded` reference is approving the operator's word,\n * and is entitled to know that is what they are doing.\n */\n changeRecord: ChangeRecordCitation | null;\n}\n\n/**\n * Full approval detail for `GET /approvals/{id}` — the list fields plus the reviewable\n * plan snapshot. `plan` is null for requests opened before the snapshot feature (their\n * denormalized context predates it); the card still renders from the list fields.\n */\nexport interface ApprovalDetailDto extends ApprovalListItemDto {\n plan: ApprovalPlanDto | null;\n}\n\n/** Body of `POST /approvals/{id}/decision`. */\nexport interface ApprovalDecisionInput {\n decision: ApprovalDecisionKind;\n comment?: string;\n /**\n * Mandatory written justification when a requester self-approves under break-glass\n * (decision = approve, decider = requester, policy break-glass enabled). Ignored for\n * ordinary decisions. Recorded on a distinct, heightened audit event.\n */\n justification?: string;\n}\n\n/**\n * ═══ A GOVERNANCE RULE IS A MANAGEABLE OBJECT ══════════════════════════════════════════\n *\n * It was not. `policy` was seeded once per tenant and then read-only forever: the API was\n * `GET /` and `PATCH /:id/break-glass`, so the rule deciding whether every run in the platform\n * needs approval could not be created, edited, reordered, disabled or deleted. A founder who\n * set an adoption to \"Not required\", saw the run gated anyway, and followed the honest\n * explanation to Settings → Governance arrived at a page that could only toggle break-glass.\n *\n * The model was always right — `match` keys the request, `effect` carries the decision, the\n * highest-priority ENABLED match wins — so this is the lifecycle the model always implied,\n * finally exposed. Nothing about evaluation changes.\n */\n/**\n * A connector a rule names, carrying the name it has TODAY — resolved on read, never stored\n * on the rule. A connector renamed must read differently everywhere it is cited, with nobody\n * remembering to update a second copy.\n *\n * ★ `name` IS NULL WHEN THE CONNECTOR NO LONGER EXISTS, and the pair is still present. That\n * is the distinction worth the extra object: a rule pointing at a deleted connector matches\n * nothing, printing its uuid would suggest otherwise, and DROPPING it would make the rule\n * read narrower than it is. So the entry survives and says what is true about it.\n */\nexport interface PolicyConnectionRef {\n id: string;\n /** The connector's name today, or null when it no longer exists. Never the uuid. */\n name: string | null;\n}\n\n/**\n * ═══ THE MATCH GRAMMAR — EVERY KEY A RULE'S SCOPE MAY CONSTRAIN ════════════════════════\n *\n * ★ THE POINT OF THIS TYPE EXISTING IS THAT IT DID NOT (docs/90 §1.2). The grammar was\n * `Record<string, unknown>` in the matcher and four loose fields on each of three DTOs, so\n * \"which keys are scope keys, and what shape is each\" was a question only a reader could\n * answer — and the answer drifted. docs/85 made two of them lists and stopped; the founder\n * had to point at the third. A memory did not stop it. A declaration does.\n *\n * ─── THE DISTINCTION THAT WAS BEING CONFUSED (docs/90 §1.1) ─────────────────────────────\n *\n * A FACT ON A RUN IS SINGULAR. One environment, one risk level, one action, one connector —\n * {@link PolicyEvaluationQuery} asks about exactly one of each, because it asks what a *run*\n * gets. That is unchanged and must stay unchanged.\n *\n * A RULE'S SCOPE IS A SET. It names which values it COVERS. \"Staging and non-prod but not\n * production\" is an ordinary thing to want, and it used to cost two rows in a precedence\n * stack. `riskLevels` always encoded this correctly, and a run has exactly one risk level —\n * which is why `policy-editor.tsx`'s \"environment names exactly one thing\" refuted itself\n * three lines from where it was written.\n *\n * `approverGroupId` is the case that comment was half-remembering, and it is NOT here: it is\n * an EFFECT — who approves — not a scope key. Effects name one thing; scope keys name sets.\n *\n * ★ EMPTY MEANS ANY, on every axis, which is what an absent key has always meant. Present\n * means \"one of these\". Both only ever NARROW, which is what keeps a rule readable as one\n * sentence and precedence untouched.\n *\n * ⚠ `subscriptionId` IS DELETED AND IS NOT COMING BACK (docs/90 §1). It was a fifth scope\n * key the matcher read as a SCALAR, in no contract, no DTO and no editor — `matchOf` never\n * wrote it, and it was declared \"reserved by the model\" in the commit that added it. A key\n * nothing can set is a branch nothing can test, and here it was a branch in the code that\n * decides whether a run is governed. Migration 0086 proves no stored row carries one.\n */\nexport interface PolicyMatch {\n /**\n * ★ THE KEY THIS TYPE EXISTS FOR. It was `environment: Environment | null` until docs/90 —\n * the last scalar, kept that way by a comment that argued cardinality while `riskLevels`\n * sat three lines above it being a list about a fact that is equally singular on a run.\n *\n * ⚠ STORAGE STILL CARRIES A SINGULAR MIRROR FOR ONE RELEASE. `match.environment` is\n * written beside this whenever exactly one environment is selected, so an api rolled back\n * to `v158` reads the rule as scoped rather than as ANY. That mirror is storage\n * compatibility and deliberately not part of the grammar — see `StoredPolicyMatch` in the\n * api's `policy-evaluation.ts`, which is the one place allowed to know about it.\n */\n environments: Environment[];\n riskLevels: RiskLevel[];\n actionKeys: string[];\n connectionIds: string[];\n}\n\n/**\n * ═══ ★★ THE GUARD — EVERY SCOPE KEY IS A LIST, READ OFF THE TYPE ═══════════════════════\n *\n * This is docs/90's actual deliverable, and it is a TYPE rather than a test because a type\n * is the only thing that can read a type. It names no keys. That matters more than it looks:\n * a hand-written list of key names would be the FIFTH author of this fact, and it would be\n * stale the first time a key was added — which is precisely how the third scalar survived\n * two slices that were about exactly this.\n *\n * HOW IT FIRES. Declare any key of {@link PolicyMatch} as something other than a list and\n * `ScalarScopeKeys` stops being `never`; the assertion below then demands that the literal\n * `true` be assignable to a union of the offending key NAMES, and `tsc` prints them:\n *\n * src/governance.ts(383,7): error TS2322: Type 'true' is not assignable to type '\"environment\"'.\n *\n * So the failure names the key that broke it. `pnpm typecheck` is stage 3 of the gate, and\n * `every-scope-key-is-a-list.spec.ts` fires the same property at runtime off a real value —\n * two stages, because a guard nobody has watched fail has not been tested (docs/90 §1.2).\n *\n * `NonNullable` is deliberate: `RiskLevel[] | null` is still a list-shaped axis and the\n * defect being guarded is a SCALAR, not an optional. `-?` is deliberate for the same reason —\n * an optional list is a list.\n */\ntype ScalarScopeKeys<T> = {\n [K in keyof T]-?: NonNullable<T[K]> extends readonly unknown[] ? never : K;\n}[keyof T];\n\n/** `true` when no key of `T` is a scalar; otherwise the offending key names, so `tsc` says them. */\ntype EveryKeyIsAList<T> = [ScalarScopeKeys<T>] extends [never] ? true : ScalarScopeKeys<T>;\n\nconst _everyScopeKeyIsAList: EveryKeyIsAList<PolicyMatch> = true;\nvoid _everyScopeKeyIsAList;\n\n/**\n * ═══ ★ THE SAME PROPERTY, AT RUNTIME, OFF A VALUE THE PRODUCT ACTUALLY USES ════════════\n *\n * A rule that constrains nothing — which is what a new draft starts as, and what \"empty\n * means ANY\" means spelled out. The editor opens on exactly this.\n *\n * ★ IT IS ALSO THE OTHER HALF OF THE GUARD, and the reason it is a `const` and not a list of\n * strings. `PolicyMatch` forces this object to carry EVERY key and nothing else, so\n * `Object.values` is the grammar's key set read off the type — with no name written down\n * anywhere. Add a scalar key and this stops compiling until it is given a value; give it a\n * scalar value and `every-scope-key-is-a-list.spec.ts` goes red naming the key. So the guard\n * fires in the typecheck stage AND in the suite, from one declaration.\n */\nexport const ANY_POLICY_MATCH: PolicyMatch = {\n environments: [],\n riskLevels: [],\n actionKeys: [],\n connectionIds: [],\n};\n\n/**\n * And the same property on every surface that RESTATES the grammar. `Extract` limits this to\n * the keys a DTO shares with {@link PolicyMatch}, so `id` and `name` are not swept in — and\n * again no key is named here. A DTO that re-declares `riskLevels` as `RiskLevel | null` fails\n * on the line that mentions only the DTO.\n */\ntype ScalarSharedScopeKeys<T> = ScalarScopeKeys<Pick<T, Extract<keyof T, keyof PolicyMatch>>>;\ntype SharedScopeKeysAreLists<T> = [ScalarSharedScopeKeys<T>] extends [never]\n ? true\n : ScalarSharedScopeKeys<T>;\n\nexport interface PolicyDto {\n id: string;\n /**\n * ═══ WHAT THIS RULE DECIDES (docs/83 §2) ═════════════════════════════════════════════\n *\n * `approval` is every rule that existed before migration 0082, backfilled, and its\n * behaviour is untouched. `change_control` is the new one: it requires the run to name a\n * record in the customer's system of record.\n *\n * ★ ONE TABLE AND ONE MATCH VOCABULARY, BUT PRECEDENCE PER KIND. `resolvePolicy` is\n * `.find` — the first matching rule wins and the rest are not consulted — so a rule\n * carrying TWO requirements would let an unrelated, higher-priority rule silently delete\n * one of them. Two kinds resolved independently is what makes \"a run may need approval, a\n * change record, both, or neither\" a fact rather than a hope.\n */\n kind: PolicyKind;\n name: string;\n /**\n * ═══ THE ENVIRONMENTS THIS RULE COVERS — EMPTY MEANS EVERY ENVIRONMENT (docs/90 §1) ══\n *\n * A LIST, for the reason `actionKeys` is one directly below: \"staging and non-prod but not\n * production\" is one rule an admin thinks of as one, and it used to cost two rows in a\n * precedence stack. See {@link PolicyMatch} for why the singular survived two slices that\n * were about exactly this.\n */\n environments: Environment[];\n riskLevels: RiskLevel[];\n /**\n * ═══ THE ACTIONS THIS RULE COVERS — EMPTY MEANS EVERY ACTION (docs/85 §1) ════════════\n *\n * A LIST, because \"five of our ten actions\" is one rule an admin thinks of as one, and it\n * used to cost five rows in a precedence stack. `riskLevels` was already a list and\n * `actionKey` was not, for no reason anybody chose — this finishes that pattern rather\n * than starting one.\n *\n * ★ EMPTY MEANS ANY, EXACTLY AS AN ABSENT SCALAR DID. The match grammar is unchanged:\n * absent is any, present is \"one of these\", and both only ever narrow. Precedence is\n * unchanged too — one rule still matches or it does not, and a rule naming five actions\n * is ONE row in ONE stack, which is easier to reason about than five, not harder.\n */\n actionKeys: string[];\n /**\n * ═══ THE CONNECTORS THIS RULE COVERS, EACH WITH ITS NAME TODAY (docs/45 §3, docs/85) ══\n *\n * Empty means every connector — the same \"absent key means ANY\" grammar every other\n * constraint here uses, so a connector rule is one more attribute on an axis that already\n * exists rather than a new kind of thing.\n *\n * ★ THE NAME IS ATTACHED PER CONNECTOR, NOT CARRIED IN A PARALLEL ARRAY, and that is the\n * whole reason this is a `{id, name}` pair rather than two lists. `name` is null when the\n * connector NO LONGER EXISTS, and a rule pointing at a deleted connector matches nothing —\n * so that connector has to stay VISIBLE, in place, as itself. Two index-coupled arrays\n * would make \"drop the ones we could not name\" a one-character mistake, and a rule would\n * then read NARROWER than it is on the one screen an admin checks its reach against.\n *\n * ★ WHY THIS IS THE RIGHT PLACE, AND WHY A FLAG ON THE CONNECTOR IS NOT (D2). A connector\n * is what HOLDS THE CREDENTIAL, so approval on a connector is approval to USE that\n * credential — GitHub Environments exactly: an environment holds secrets, a protection\n * rule names required reviewers, and a job cannot reach those secrets until a reviewer\n * approves. Opera's equivalent moment is the credential lease at execution time, which is\n * already where P5 puts the approval. A `requiresApproval` boolean on the connector row\n * would be a second policy engine with one condition — no precedence, no approver group,\n * no break-glass, and no answer at all when it disagrees with a rule.\n */\n connections: PolicyConnectionRef[];\n requireApproval: boolean;\n /**\n * ═══ WHO MAY APPROVE, AND WHO IS ASKED (docs/47 D2) ══════════════════════════════════\n *\n * `group.id`, or null for \"any approver\". A REFERENCE, not a label: a dangling string is\n * what let this field drift from meaning anything for as long as it did, and a referential\n * fact cannot. Deleting a group a rule names is refused (§3.5) rather than cascading or\n * silently widening the rule to everyone.\n */\n approverGroupId: string | null;\n /**\n * That group's name TODAY, resolved on read — never stored on the rule, for the same\n * reason {@link PolicyDto.connectionName} is not. Null when the rule names no group.\n *\n * It cannot be null-because-missing the way a connector's can: the FK is `Restrict`, so a\n * rule can never point at a group that stopped existing.\n */\n approverGroupName: string | null;\n /** Whether break-glass self-approval is permitted for requests this policy gates. */\n allowBreakGlass: boolean;\n /**\n * ═══ WHAT A CHANGE-CONTROL RULE REQUIRES (docs/83 §3) ════════════════════════════════\n *\n * The record types that satisfy this rule. Non-empty on a `change_control` rule and\n * EMPTY on an `approval` one — not because an approval rule has \"none\", but because the\n * field is not a question that kind of rule answers.\n *\n * ★ THE ADMIN PICKS WHICH KINDS OF RECORD COUNT, AND NOTHING ELSE. Which STATES\n * authorize is the product's, declared once in `CHANGE_RECORD_AUTHORIZATION` — see there\n * for why a \"just check it exists\" option is the one thing this feature must not offer.\n */\n recordTypes: ChangeRecordType[];\n /**\n * ═══ ★ HOW FAR OPERA GOES WITH WHAT A RUN NAMES (docs/84 §3.1) ═══════════════════════\n *\n * `recorded` — capture the reference on the run and do not check it. Satisfiable today.\n * `verified` — resolve it against the system of record and refuse the run unless it\n * authorizes the work. Refused at save until a provider adapter exists.\n *\n * Meaningless on an `approval` rule, which stores {@link DEFAULT_CHANGE_RECORD_ASSURANCE}\n * and never reads it — the same posture `recordTypes` takes one field up, so the two kinds\n * cannot half-express each other's effect.\n *\n * ⚠ NEVER ABSENT ON THE WIRE. `assuranceOf` resolves the stored jsonb — which may predate\n * the field — to `verified`, so a reader here always has a value and no screen has to\n * decide what a missing level means.\n */\n assurance: ChangeRecordAssurance;\n enabled: boolean;\n /**\n * Precedence. Higher decides first — but the UI never shows this as a number and never asks\n * for one: the list is ORDERED and the order writes the priority. See `ReorderPoliciesInput`.\n */\n priority: number;\n createdAt: string;\n /** Last modification (migration 0054). */\n updatedAt: string;\n}\n\n/**\n * ═══ WHAT GOVERNS RUNS THROUGH ONE CONNECTOR (docs/45 D4) ══════════════════════════════\n *\n * An operator looking at a connector must be able to see that it requires approval without\n * going to Governance to find out. This is that read — and it is a READ OF THE ONE SOURCE\n * OF TRUTH, not a second one: the rules come from the same table, through the same mapper,\n * as the Governance page's own list. There is no `requiresApproval` column on the connector\n * and no second place where the question is decided (D2).\n *\n * ─── WHY THIS DOES NOT SAY \"THIS CONNECTOR REQUIRES APPROVAL\" ───────────────────────────\n *\n * Because that would be a claim the policy engine might not honour. A rule naming this\n * connector also constrains environment and risk, and a HIGHER-priority rule may decide\n * first and require nothing — precedence is \"highest-priority enabled match wins\", and no\n * summary of one rule can anticipate it. So this lists the rules and lets each state its own\n * reach in its own terms; a reader who needs the answer for a specific run has\n * `POST /policies/evaluate`, which performs the real resolution.\n *\n * ─── WHY A VIEWER MAY READ IT ───────────────────────────────────────────────────────────\n *\n * Every field here is already reachable at the same altitude through the run wizard's plan\n * preview, which returns the matched rule and its approver group to any authenticated\n * caller. `allowBreakGlass` and `enabled` are deliberately NOT here: they are not, and this\n * read must not become the widening its own docblock denies.\n */\nexport interface ConnectorGovernanceDto {\n connectionId: string;\n /**\n * The ENABLED rules naming this connector, in precedence order — the order that decides,\n * so the list a reader sees is the order the engine walks.\n */\n rules: ConnectorGovernanceRuleDto[];\n}\n\nexport interface ConnectorGovernanceRuleDto {\n /** The rule, in its own terms — feed it to {@link policyScopeSentence}. */\n rule: MatchedPolicyDto;\n /** WHICH stack this rule sits in, so a reader is never shown two orders as one. */\n kind: PolicyKind;\n /** Non-empty only on a `change_control` rule — what it requires a run to name. */\n recordTypes: ChangeRecordType[];\n /**\n * How far Opera goes with what is named (docs/84). Beside `recordTypes` rather than folded\n * into it, because \"which records count\" and \"what we do about one\" are the two halves an\n * admin reading a connector's governance has to be able to tell apart.\n */\n assurance: ChangeRecordAssurance;\n requireApproval: boolean;\n /** The group this rule scopes approval to, or null for any approver (docs/47 §3.2). */\n approverGroup: ApproverGroupRef | null;\n}\n\n/**\n * ═══ ★ WHAT CHANGE CONTROL CAN ASK OF A RUN IN THIS WORKSPACE, TODAY (docs/84 §5) ══════\n *\n * `GET /policies/change-control`. One read, two readers with two different questions:\n *\n * · the Operation run dialog asks `rules` — \"does anything here need a record named?\" —\n * so an operator is asked exactly once, before the run, with the rules named.\n * · the rule editor asks `verifiedAvailable` — so `Verified` reads as a capability that is\n * not yet available and says what it WILL do, rather than as an option whose Save button\n * is refused (docs/80: a capability naming why it is unavailable is a sales signal).\n *\n * One endpoint and not two, because the two answers come from the same two facts and a second\n * read would be a second chance for them to disagree.\n */\nexport interface ChangeControlCapabilityDto {\n /**\n * The workspace's ENABLED change-control rules, in precedence order. Empty is the honest\n * and overwhelmingly common answer: a workspace that has written none requires nothing.\n *\n * ⚠ IT IS THE WORKSPACE QUESTION AND NOT \"WHICH RULES APPLY TO THIS OPERATION\". A fan-out\n * can discover a target in a connection scope nothing previewed, whose child then matches a\n * rule a per-Operation answer would have omitted — and that false negative is a child\n * refused with nowhere to have named a record.\n */\n rules: ChangeControlRule[];\n /**\n * FALSE when Opera has no system-of-record adapter connected AT ALL, which is every\n * workspace in this release — so a rule cannot be saved enabled at `verified`.\n *\n * ★ IT IS A FACT ABOUT WHAT IS CONNECTED, NEVER A HARD-CODED \"not in this version\". The day\n * an adapter registers, this answers true with no browser change — and a build that shipped\n * the constant instead would go on saying \"coming soon\" beside a working integration.\n *\n * ⚠ TRUE DOES NOT MEAN THIS RULE CAN BE SAVED. A provider may answer for change requests and\n * not for incidents; that is the WORKSPACE refusal at save, which names the types nothing\n * can answer for. This field only separates \"the product cannot do this yet\" from \"your\n * workspace has not connected it\".\n */\n verifiedAvailable: boolean;\n}\n\n/** Body of `PATCH /policies/{id}/break-glass`. */\nexport interface SetBreakGlassInput {\n allowBreakGlass: boolean;\n}\n\n/**\n * What a rule matches and what it does. Shared by create and update, because a half-editable\n * rule is the shape that produced the original defect — every field here decides an outcome,\n * so every field is changeable.\n *\n * A null/absent constraint means ANY. `{environment: null, riskLevels: []}` is a rule that\n * covers every run, which is legitimate and, being at some position in an ordered list, still\n * predictable.\n */\nexport interface PolicyRuleInput extends PolicyMatch {\n /**\n * WHAT THIS RULE DECIDES. See {@link PolicyDto.kind}. Absent on the wire means\n * `approval` — which is what every rule written before docs/83 is, and what a client\n * that has not been rebuilt is still sending.\n *\n * ★ IMMUTABLE AFTER CREATE, and refused rather than ignored. A rule's kind decides which\n * precedence stack it sits in; changing it in place would move a rule between two ordered\n * lists, leaving both at a precedence nobody chose — the exact harm the reorder endpoint\n * refuses a partial list to prevent.\n */\n kind: PolicyKind;\n name: string;\n requireApproval: boolean;\n /**\n * `group.id`, or null for \"any approver\" (docs/47). The write side names only the id —\n * the name is the identity module's to give, and a rule that stored its own copy would go\n * stale the first time somebody renamed the group.\n *\n * A rule requiring approval from a group with nobody able to approve is REFUSED at save\n * (§3.4). Null is always allowed: it means everyone holding `approval:decide`.\n */\n approverGroupId: string | null;\n allowBreakGlass: boolean;\n /**\n * The record types a `change_control` rule accepts — at least one, refused at save\n * otherwise: a rule requiring nothing would match runs and demand a record of no kind,\n * which no operator could ever satisfy.\n *\n * Ignored on an `approval` rule and stored empty, so the two kinds cannot half-express\n * each other's effect.\n */\n recordTypes: ChangeRecordType[];\n /**\n * How far Opera goes with what a run names — see {@link PolicyDto.assurance}.\n *\n * ★ ABSENT ON THE WIRE MEANS `verified`, NOT `recorded`. A client that has not been rebuilt\n * is one written under a product that promised the record would be checked, and reading its\n * silence as the weaker level would downgrade a control nobody chose to downgrade. The\n * parser applies {@link DEFAULT_CHANGE_RECORD_ASSURANCE}, so an old client's `change_control`\n * rule is refused at save exactly as it is today rather than quietly becoming satisfiable.\n *\n * Ignored on an `approval` rule and stored as the default, like `recordTypes` above.\n */\n assurance: ChangeRecordAssurance;\n enabled: boolean;\n}\n\nexport type CreatePolicyInput = PolicyRuleInput;\n/** Every field is optional; each supplied one replaces its stored value. */\nexport type UpdatePolicyInput = Partial<PolicyRuleInput>;\n\n/**\n * THE ORDER IS THE PRIORITY. The client sends the ids it wants, top (highest precedence)\n * first, and the server assigns the numbers — so nobody has to know whether to type 100 or 250,\n * and two rules can never silently share a priority and resolve by a tie-break the user cannot\n * see. Same lesson as parameter order: the thing that decides behaviour is arranged visibly.\n */\nexport interface ReorderPoliciesInput {\n /**\n * WHICH PRECEDENCE STACK is being rewritten. Precedence is per kind (docs/83 §2), so an\n * order is too: one list containing both kinds would be an ordering whose meaning changes\n * halfway down it.\n *\n * Absent means `approval` — the only kind a client written before docs/83 can have, and\n * the only kind that can exist in a workspace such a client is talking to.\n */\n kind: PolicyKind;\n /** Every policy id OF THAT KIND in the tenant, in the intended precedence order. */\n policyIds: string[];\n}\n\n/**\n * ═══ \"WHICH RULE APPLIES?\" ═════════════════════════════════════════════════════════════\n *\n * The question the founder could not ask. Answered by the SAME resolution the run performs —\n * not a re-implementation, which would be worse than nothing because it would be believed.\n */\nexport interface PolicyEvaluationQuery {\n environment: Environment;\n riskLevel: RiskLevel;\n /** Optional: some rules constrain a single action. Absent asks about actions generally. */\n actionKey?: string;\n /**\n * Optional: some rules constrain a single connector. Absent asks about connectors\n * generally, and therefore CANNOT match a connector rule — the same way an absent\n * `actionKey` cannot match a rule scoped to one action.\n *\n * This endpoint is the only place an operator can ask \"which rule applies?\" without\n * performing the act (§3.3), so it has to be askable about a connector too. A checker\n * that could not see connector rules would answer confidently and wrongly for every run\n * one of them gates.\n */\n connectionId?: string;\n}\n\nexport interface PolicyEvaluationDto {\n environment: Environment;\n riskLevel: RiskLevel;\n actionKey: string | null;\n connectionId: string | null;\n /** The rule that decides, or null when nothing matches — which means no approval. */\n matched: MatchedPolicyDto | null;\n /** What a run with these attributes actually gets, in the plan's own words. */\n outcome: ExecutionPlanGovernance;\n /**\n * ═══ …AND THE OTHER STACK, ANSWERED BY THE SAME RESOLUTION (docs/83 §2) ══════════════\n *\n * The `change_control` rule that would decide, or null when none matches. A SECOND FIELD\n * rather than a second endpoint, because the admin's question is \"what would this run\n * get?\" and a checker that answered half of it would send them away believing the half it\n * did not mention was \"nothing\".\n *\n * ★ IT IS THE SAME DTO THE PLAN CARRIES. The checker says what a run would be told,\n * verbatim, so an admin comparing the two never has to decide whether a wording difference\n * is a behaviour difference — the same discipline `outcome` already follows.\n */\n changeControl: ExecutionPlanChangeControl | null;\n}\n\n/**\n * The rule that decided, carried WITH the decision.\n *\n * This is the other half of the founder's problem. The run told them \"your organization's\n * governance policy\" and named nothing — so there was no rule to go and look at, and the page\n * they were sent to could not have changed it anyway. A decision that cannot name its cause is\n * not an explanation.\n *\n * Its own terms, derived from the policy: the name the admin gave it, and the environment and\n * risk levels IT constrains. Never a hardcoded sentence — a rule renamed or re-scoped must read\n * differently everywhere it is cited, with nobody remembering to update a second copy.\n */\nexport interface MatchedPolicyDto {\n id: string;\n name: string;\n /** The environments this rule constrains; EMPTY means any. See {@link PolicyMatch}. */\n environments: Environment[];\n riskLevels: RiskLevel[];\n /** The actions this rule constrains; EMPTY means any. See {@link PolicyDto.actionKeys}. */\n actionKeys: string[];\n /**\n * The connectors this rule constrains, each with its name today; EMPTY means any.\n *\n * The names are carried HERE rather than passed to {@link policyScopeSentence} as an\n * argument so the sentence stays a pure function of the rule's own terms. A caller that\n * had to supply them separately is a caller that can forget to — and the failure is\n * silent: the rule's reach would read wider than it is.\n */\n connections: PolicyConnectionRef[];\n}\n\n/**\n * What deleting or disabling a rule would actually change, COMPUTED by re-resolving the\n * remaining rules — never a guessed sentence.\n *\n * Removing the last rule that requires approval is legitimate: a tenant may genuinely want\n * none. It is also the highest-consequence action on the page, so the confirm names what stops\n * being gated instead of asking \"are you sure?\" about a rule whose reach the admin would\n * otherwise have to work out by hand.\n */\nexport interface PolicyRemovalImpactDto {\n policyId: string;\n /**\n * The {environment, riskLevel} combinations that require approval today and would not\n * afterwards. Empty means nothing stops being gated — another rule already covers them, or\n * this one never gated anything.\n */\n losesApproval: PolicyImpactCombination[];\n /**\n * ═══ AND THE SAME QUESTION FOR THE OTHER STACK (docs/83 §2) ══════════════════════════\n *\n * The combinations that require a change record today and would not afterwards.\n *\n * ★ ITS OWN FIELD, AND OMITTING IT WOULD HAVE BEEN A LIE ON A CONFIRM DIALOG. Deleting a\n * change-control rule loses nothing on the approval axis, so a confirm reading only\n * `losesApproval` would have said \"nothing stops being gated\" about a rule whose deletion\n * stops every run it covered from having to name a change record at all.\n */\n losesChangeControl: PolicyImpactCombination[];\n /** True when NO rule of EITHER kind would gate anything anywhere afterwards. */\n leavesNothingGated: boolean;\n}\n\nexport interface PolicyImpactCombination {\n environment: Environment;\n riskLevel: RiskLevel;\n}\n\n/** KPI strip for the Approval Center (`GET /approvals/summary`). */\nexport interface ApprovalSummaryDto {\n /** Requests currently awaiting a decision. */\n pending: number;\n /** Requests approved since the start of today (tenant-local server time). */\n approvedToday: number;\n /** Pending requests whose governed execution is high-risk. */\n highRiskWaiting: number;\n}\n\n/**\n * The governance half of a plan preview: whether the run will be held for approval\n * BEFORE it executes, resolved from the tenant's live policy set exactly as submit\n * resolves it (docs/08 §3.2). Server-authoritative — the wizard cannot compute this\n * client-side because policies live server-side. `reason` is an honest, plain-English\n * explanation the review surface renders verbatim.\n */\nexport interface ExecutionPlanGovernance {\n requiresApproval: boolean;\n /**\n * The group whose members must sign off, when approval is required. NULL means ANY\n * APPROVER — and after docs/47 that is a real distinction rather than a missing value, so\n * the two cases have to read differently everywhere this is rendered (D4).\n */\n approverGroup: ApproverGroupRef | null;\n reason: string;\n /**\n * The RULE that decided, when a policy did. Null when nothing matched, and null when an\n * adoption override forced approval on its own — in that case the adoption is the cause and\n * `reason` says so.\n *\n * Carried so a forced approval can name its rule and link to it. \"Approval required by your\n * organization's governance policy\" with no rule named is where the founder got stuck.\n */\n matchedPolicy?: MatchedPolicyDto | null;\n}\n\n/**\n * ─── THE APPROVAL SENTENCE, WRITTEN ONCE (charter §4.2) ─────────────────────────────────\n *\n * Turn a policy decision into the plan's governance summary. Pure — it invents nothing and\n * asserts only what the decision actually tells us: an adoption override is named specifically\n * (we know it forced approval); otherwise the reason stays at the truthful \"your governance\n * policy requires it\" altitude rather than guessing which policy matched.\n *\n * IT LIVES HERE BECAUSE TWO SURFACES ASK THE SAME QUESTION. The run wizard's plan preview shows\n * what a run will get; the adoption's approval control has to show the same thing, or an admin\n * sets \"Not required\", sees nothing contradict them, and finds out from a run that policy\n * overruled it. Both call `evaluatePolicy` and both render through this function, so \"the\n * control agrees with the plan\" is one implementation rather than two that must be kept in\n * step.\n */\nexport function approvalOutcome(\n decision: {\n requireApproval: boolean;\n approverGroup: ApproverGroupRef | null;\n matchedPolicy?: MatchedPolicyDto | null;\n },\n adoptionRequiresApproval: boolean,\n): ExecutionPlanGovernance {\n if (!decision.requireApproval) {\n return {\n requiresApproval: false,\n approverGroup: null,\n reason: \"No approval required — this run is submitted straight to execution.\",\n matchedPolicy: null,\n };\n }\n // ★ D4 — THE TWO CASES READ DIFFERENTLY, because they now ARE different. This used to be\n // \"a member of the X group must approve it first\" for a value that scoped nothing, and an\n // empty string when there was no value — so the sentence overclaimed in one branch and\n // said nothing in the other. Null is not a missing group: it is every approver, which is\n // a fact worth stating to the person waiting on the gate.\n const who = decision.approverGroup\n ? ` A member of ${decision.approverGroup.name} must approve it first.`\n : \" Anyone who can approve may sign it off.\";\n // THE RULE, BY NAME AND IN ITS OWN TERMS. Derived from the policy that matched, so renaming\n // or re-scoping a rule changes every sentence that cites it with nobody remembering to.\n const rule = decision.matchedPolicy;\n const why = adoptionRequiresApproval\n ? \"Approval required — this action's adoption is configured to require sign-off.\"\n : rule\n ? `Approval required by your governance rule “${rule.name}” (${policyScopeSentence(rule)}).`\n : \"Approval required by your organization's governance policy.\";\n return {\n requiresApproval: true,\n approverGroup: decision.approverGroup,\n reason: `${why}${who}`,\n matchedPolicy: adoptionRequiresApproval ? null : (rule ?? null),\n };\n}\n\n/**\n * What a rule covers, as a phrase — \"high or medium risk in production\", \"any action in\n * staging\", \"every run\". Built from the rule's OWN match so it cannot describe a rule that has\n * since been re-scoped.\n *\n * Exported because the governance list, the checker and the forced-approval explanation all\n * describe a rule's reach, and three phrasings of one fact is how two of them go stale.\n */\nexport function policyScopeSentence(rule: MatchedPolicyDto): string {\n const parts: string[] = [];\n if (rule.riskLevels.length > 0) {\n parts.push(`${joinWithOr(rule.riskLevels)}-risk`);\n }\n // ★ EVERY ACTION IS NAMED, AND \"runs of 5 actions\" WOULD BE VAGUER THAN WHAT THIS SAID\n // BEFORE. This sentence exists so an admin can compare a rule's reach against what they\n // meant; a bare count hides exactly the thing they are checking. `joinWithOr` of one value\n // is that value, so a rule naming ONE action reads character-for-character as it did when\n // this key was a scalar — asserted, because five surfaces cite this sentence.\n parts.push(rule.actionKeys.length > 0 ? `runs of ${joinWithOr(rule.actionKeys)}` : \"runs\");\n // ★ JOINED, EXACTLY AS `riskLevels` IS ONE LINE ABOVE. `joinWithOr` of one value IS that\n // value, so a rule naming ONE environment reads character-for-character as it did when this\n // key was a scalar — the same property docs/85 asserted for `actionKeys`, and for the same\n // reason: five surfaces cite this sentence and none of them may change wording today.\n if (rule.environments.length > 0) {\n parts.push(`in ${joinWithOr(rule.environments.map((e) => ENVIRONMENT_PHRASE[e]))}`);\n }\n // A rule scoped to connectors that did not SAY so would describe itself as \"every run\" —\n // a false statement about its reach, in the checker, the governance list and the sentence\n // a gated run is given.\n //\n // ★ A CONNECTOR THAT NO LONGER EXISTS KEEPS ITS PLACE IN THE LIST. Dropping it would make\n // the rule read narrower than it is; printing its uuid would suggest it still matches\n // something, which it does not. The phrase is the last resort rather than the first, and\n // it is per connector — a rule naming three, one of them gone, says so about that one.\n if (rule.connections.length > 0) {\n const named = rule.connections.map((c) => c.name ?? \"a connector that no longer exists\");\n parts.push(`using ${joinWithOr(named)}`);\n }\n const sentence = parts.join(\" \");\n return sentence === \"runs\" ? \"every run\" : sentence;\n}\n\n/** How each environment reads inside a sentence. One vocabulary, one wording. */\nconst ENVIRONMENT_PHRASE: Record<Environment, string> = {\n production: \"production\",\n staging: \"staging\",\n non_prod: \"non-prod\",\n};\n\nfunction joinWithOr(values: readonly string[]): string {\n if (values.length <= 1) return values[0] ?? \"\";\n return `${values.slice(0, -1).join(\", \")} or ${values[values.length - 1]!}`;\n}\n\n/**\n * ═══ ★ THE GUARD, APPLIED TO EVERY SURFACE THAT RESTATES THE GRAMMAR ═══════════════════\n *\n * Declared at the foot of the file because the DTOs have to exist first. `PolicyRuleInput`\n * is absent on purpose: it `extends PolicyMatch`, so it cannot disagree — which is the\n * stronger form of this check and the reason the write path was made to inherit rather than\n * restate. `PolicyDto` and `MatchedPolicyDto` are PROJECTIONS (they resolve `connectionIds`\n * to `{id, name}` pairs), so they cannot inherit, and these two lines are what stops a\n * projection from quietly reverting an axis to a scalar.\n *\n * Again: no key is named here. Break one and `tsc` names it for you.\n */\nconst _policyDtoScopeKeysAreLists: SharedScopeKeysAreLists<PolicyDto> = true;\nconst _matchedPolicyDtoScopeKeysAreLists: SharedScopeKeysAreLists<MatchedPolicyDto> = true;\nvoid _policyDtoScopeKeysAreLists;\nvoid _matchedPolicyDtoScopeKeysAreLists;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n}); //# sourceMappingURL=audit.js.map\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXVkaXQuanMiLCJzb3VyY2VzIjpbIi4uL3NyYy9hdWRpdC50cyJdLCJzb3VyY2VSb290IjoiIiwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9","export const NOTIFICATION_TYPES = [\n \"run_completed\",\n \"approval_requested\",\n \"approval_resolved\",\n \"schedule_failed\",\n // Continuous verification found an Operation that would no longer run (docs/31 §11.3).\n // Fires on the TRANSITION into `broken` only: an Operation broken for a week must not\n // produce seven notifications, or the signal becomes the noise it exists to replace.\n \"verification_failed\",\n] as const;\nexport type NotificationType = (typeof NOTIFICATION_TYPES)[number];\n\nexport const NOTIFICATION_LEVELS = [\"success\", \"error\", \"warning\", \"info\"] as const;\nexport type NotificationLevel = (typeof NOTIFICATION_LEVELS)[number];\n\nexport interface NotificationDto {\n id: string;\n type: NotificationType;\n level: NotificationLevel;\n title: string;\n body: string;\n link: string | null;\n readAt: string | null;\n createdAt: string;\n}\n\nexport interface NotificationSummaryDto {\n unreadCount: number;\n}\n\nexport interface NotificationPreferenceDto {\n type: NotificationType;\n muted: boolean;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n}); //# sourceMappingURL=scheduling.js.map\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NoZWR1bGluZy5qcyIsInNvdXJjZXMiOlsiLi4vc3JjL3NjaGVkdWxpbmcudHMiXSwic291cmNlUm9vdCI6IiIsIm5hbWVzIjpbXSwibWFwcGluZ3MiOiIifQ==","// Operations DTOs (docs/31 §4, §5). An Operation is a named, versioned, tenant-owned\n// SEQUENCE of steps. An Operation Run orchestrates child Executions and never performs\n// a side effect itself — every mutation happens inside an Execution.\n//\n// The vocabulary here is CLOSED and deliberately weaker than a language: three step\n// kinds (one of them reserved), an enum failure policy, and name-only data binding.\n// See operations/domain/operation-schema.ts for the tripwire that keeps it that way.\n\nimport type { RequiredPermission } from \"./catalog\";\nimport type { CheckedIdentity } from \"./connections\";\nimport type { RunTriggerKind } from \"./enums\";\nimport type { CheckLevel } from \"./execution\";\nimport { planAssessmentOf } from \"./governance\";\nimport type { ApprovalPlanTargetAssessment, ExecutionPlanGovernance } from \"./governance\";\nimport type { ChangeRecordRef, ExecutionPlanChangeControl } from \"./change-control\";\nimport { isTargetDisposition, recordedDecisionsOf } from \"./decisions\";\nimport type { RecordedDecision, TargetDisposition } from \"./decisions\";\nimport type { DecisionCode } from \"./validation\";\n\n/** Lifecycle of an Operation, mirroring the action lifecycle (docs/31 §5.1). */\nexport const OPERATION_LIFECYCLES = [\n \"draft\",\n \"published\",\n \"deprecated\",\n \"retired\",\n] as const;\nexport type OperationLifecycle = (typeof OPERATION_LIFECYCLES)[number];\n\n/**\n * Continuous-verification health (docs/31 §11.3). `unverified` is the honest state for\n * an Operation the sweep has not reached yet — never a green tick we have not earned.\n */\nexport const OPERATION_HEALTH_STATES = [\n \"unverified\",\n \"healthy\",\n \"degraded\",\n \"broken\",\n] as const;\nexport type OperationHealth = (typeof OPERATION_HEALTH_STATES)[number];\n\n/**\n * The outcome of ONE verification attempt (docs/31 §11.3). Narrower than\n * {@link OperationHealth} on purpose: a verification that FINISHED always produces a\n * verdict, so it can never be `unverified`.\n *\n * ⚠ THIS ENUM ANSWERS ONE QUESTION: \"what did it find\". How far along the attempt is —\n * queued, running, finished, abandoned — is a DIFFERENT FACT and lives in\n * {@link OperationVerificationLifecycle}. Adding `running` or `pending` here would put two\n * orthogonal facts in one enum, which is the defect class charter §4.2 exists to prevent:\n * every reader of `result` would then have to ask \"is this a verdict or a progress\n * report?\", `aggregateResult` would have a value it cannot aggregate, and an Operation\n * whose probe is merely still running would project a health nobody earned.\n */\nexport type OperationVerificationResult = \"healthy\" | \"degraded\" | \"broken\";\n\n/**\n * How far along ONE verification attempt is — the fact `result` deliberately does not carry.\n *\n * A verification used to be a RECORD OF SOMETHING ALREADY OVER: the row was created when\n * the work finished, so the only readable state was \"done\". That is why the dry-run route\n * could return no id (there was nothing to name), why the client had to remember which\n * verification was newest and poll for a DIFFERENT one to appear, and why the reader\n * learned nothing at all until the verdict landed.\n *\n * The row now exists from the moment the work is accepted, and this says where it is.\n *\n * · `queued` — admitted and enqueued; no worker has claimed it yet.\n * · `running` — a worker is producing checks; they land one by one as they resolve.\n * · `finished` — it has a `result`. The ONLY state that feeds `OperationHealth`.\n * · `abandoned` — it passed its own deadline without finishing. A real, nameable ending:\n * a verification stuck in `running` for ever is worse than one that\n * failed, because the screen lies indefinitely.\n */\nexport const OPERATION_VERIFICATION_LIFECYCLES = [\n \"queued\",\n \"running\",\n \"finished\",\n \"abandoned\",\n] as const;\nexport type OperationVerificationLifecycle =\n (typeof OPERATION_VERIFICATION_LIFECYCLES)[number];\n\n/** What asked for this verification: the worker cron, or a human pressing \"Verify now\". */\nexport type OperationVerificationTrigger = \"schedule\" | \"manual\";\n\n/**\n * ═══ ★ HOW A REPRESENTATIVE DRY RUN ENDED — ARRAY-FIRST, AND WHY IT STOPPED BEING A UNION ══\n *\n * Declared as an ARRAY and derived into a type (charter §4.2), not as a bare union. It was a\n * bare union until docs/94 — one of the 28 docs/92 §1 recorded — and this is the slice that\n * added a member to it, which is exactly the moment a partition goes stale unnoticed: nothing\n * downstream is forced to notice a member it has never heard of, so the new one ships\n * invisible (docs/92's `beta`) or a copy keeps four of five (docs/93 measured three).\n *\n * ★ TWO OF THESE ARE NOT FINDINGS ABOUT THE OPERATION AT ALL, and that is the whole reason\n * the vocabulary is wider than passed/failed:\n *\n * · `passed` / `failed` — a verdict. The probe ran and the Operation earned the answer.\n * · `unsupported` — the action cannot be simulated; nothing was attempted.\n * · `quota_exhausted` — the TENANT'S BUDGET is spent (docs/31 §11.2).\n * · `change_record_required` — the WORKSPACE'S GOVERNANCE requires a change record for this\n * action, and a probe Opera creates on the customer's behalf\n * names none (docs/94). It belongs to an Operation VERSION, not\n * to an `operation_run`, so there is nothing for it to inherit.\n *\n * ⚠ THE LAST TWO MUST NEVER FOLD INTO `failed`. Both would mark a working Operation broken for\n * a fact about the workspace rather than about the Operation — see `checkDryRunRepresentative`,\n * which is where the level is decided and the argument is written out in full.\n *\n * ★ NAMED FOR THE CAUSE, NOT THE SYMPTOM. `change_record_required` says WHY no probe ran, the\n * way `quota_exhausted` does. `refused`/`blocked` would name what happened to the probe, which\n * is the thing the reader can already see.\n */\nexport const DRY_RUN_OUTCOMES = [\n \"passed\",\n \"failed\",\n \"unsupported\",\n \"quota_exhausted\",\n \"change_record_required\",\n] as const;\nexport type DryRunOutcome = (typeof DRY_RUN_OUTCOMES)[number];\n\n/**\n * One verification check (docs/31 §5.4). `code` is the stable machine name, `title` the\n * one-line claim naming the step it belongs to, and `detail` the sentence that says what\n * to do about it. Slice 4a emits only the four zero-cost codes — everything that would\n * cost a provider call belongs to 4b/4c (docs/31 §11.5). The optional structured\n * fields are evidence for checks that need more than prose: the exact missing roles,\n * running identity, representative target and probe Execution.\n */\nexport interface OperationVerificationCheckDto {\n code: string;\n /**\n * MACHINE IDENTITY, not display: what makes two checks the same check.\n *\n * A verification job is re-run when its worker dies, so appending has to recognise a check\n * it already recorded — the code alone cannot, because `action_available` is emitted per\n * step and `permissions_held` per (step, scope). Optional only because attempts recorded\n * before this existed have none; every check written now carries one.\n */\n key?: string;\n level: CheckLevel;\n title: string;\n detail: string;\n /**\n * Connection scope evaluated by `permissions_held`, when applicable. `scopeId` is\n * OPERA'S INTERNAL `connection_scope` row id — kept here as support evidence and\n * never rendered in `title`/`detail`, where only `providerScopeId` (the Azure\n * subscription GUID, the value an operator pastes into `az`) may appear.\n */\n scopeId?: string;\n scopeLabel?: string;\n /** The provider's own id for that scope, e.g. the Azure subscription GUID. */\n providerScopeId?: string;\n /** Roles/actions absent from the connector's effective cloud permissions. */\n missingPermissions?: RequiredPermission[];\n /** The connector identity whose effective permissions were evaluated. */\n checkedIdentity?: CheckedIdentity | null;\n /** The single representative target chosen for an opt-in dry run. */\n targetRef?: string;\n targetLabel?: string;\n /** Real probe Execution, linked from verification into Execution History. */\n executionId?: string;\n executionReference?: string;\n /** Outcome of an opt-in representative dry run; absent on zero-cost checks. */\n dryRunOutcome?: DryRunOutcome;\n}\n\n/**\n * ONE probe Execution this verification created, recorded THE MOMENT IT IS CREATED.\n *\n * This is the single most useful thing the verification screen can show, and it is\n * deliberately not folded into {@link OperationVerificationCheckDto}: a check is a\n * VERDICT, and a probe that has been submitted and not yet settled has no verdict. Giving\n * the check a \"still running\" level would put progress into the severity enum — the same\n * orthogonality mistake {@link OperationVerificationLifecycle} exists to avoid, one level\n * down.\n *\n * APPEND-ONLY and never rewritten. When the probe settles, a `dry_run_representative`\n * check lands carrying the SAME `executionId` plus the verdict; that check supersedes this\n * entry in the UI. So there is no window in which two writers disagree about one probe,\n * because there is only ever one writer per fact.\n */\nexport interface OperationVerificationProbeDto {\n /** Which action step this probe stands for, named as the checks name it. */\n stepKey: string;\n position: number;\n executionId: string;\n executionReference: string;\n /** The one representative target chosen; never implied fan-out. */\n targetRef: string;\n targetLabel: string;\n startedAt: string;\n}\n\n/** What every verification attempt carries, whatever state it is in. */\ninterface OperationVerificationBaseDto {\n id: string;\n operationId: string;\n /** The version that was verified — always the latest PUBLISHED one. */\n operationVersionId: string;\n /**\n * Checks that have RESOLVED, in the order they resolved. Grows while the attempt runs.\n * Order is the array's — jsonb preserves array order (it destroys object KEY order, which\n * is why nothing here depends on the order of a check's own fields).\n */\n checks: OperationVerificationCheckDto[];\n /** Probe Executions created so far, each openable while it is still running. */\n probes: OperationVerificationProbeDto[];\n triggeredBy: OperationVerificationTrigger;\n /**\n * Whether this attempt runs representative dry-run probes. Declared at CREATION, not\n * derived from the presence of a `dry_run_representative` check — at `queued` time there\n * are no checks yet, and the reader has to be told what they are watching before the\n * first one lands.\n */\n dryRun: boolean;\n /**\n * When this attempt stops being believable. Server-owned, DERIVED from the queue's own\n * worst case — every retry the job may get, plus the delays between them — so it is\n * impossible for the reaper to give up on a job that is still going to run. Null on an\n * attempt that was recorded already finished.\n */\n expiresAt: string | null;\n /**\n * Which dispatch of this verification is in flight, and how many it may have.\n *\n * A reader watching a queued attempt cannot otherwise tell \"a worker picked this up a\n * second ago\" from \"its worker died ten minutes back\" — the screen looked identical, which\n * is what made a stalled verification read as a bug. `attempt` says which try this is;\n * `maxAttempts` says what happens when they run out.\n */\n dispatchAttempt: number;\n maxDispatchAttempts: number;\n startedAt: string;\n}\n\n/**\n * One verification attempt (docs/31 §5.4), retained for trend — as a DISCRIMINATED UNION\n * over its lifecycle rather than a bag of nullable fields.\n *\n * `{ lifecycle: string; result: OperationVerificationResult | null }` would admit\n * \"finished with no result\" and \"running with a verdict\", two states with no meaning that\n * every consumer would have to hand-narrow and one of which renders a health nobody\n * earned. The union makes both unrepresentable, and it means the surfaces that read a\n * FINISHED attempt keep a non-null `result` with no narrowing at all.\n */\nexport type OperationVerificationDto =\n | OperationVerificationInFlightDto\n | OperationVerificationFinishedDto\n | OperationVerificationAbandonedDto;\n\n/** Admitted and not yet settled. No verdict exists, so none is offered. */\nexport interface OperationVerificationInFlightDto extends OperationVerificationBaseDto {\n lifecycle: \"queued\" | \"running\";\n result: null;\n /** A thing that has not finished has no finish time. */\n finishedAt: null;\n}\n\n/** Settled with a verdict. The only shape that feeds `OperationHealth`. */\nexport interface OperationVerificationFinishedDto extends OperationVerificationBaseDto {\n lifecycle: \"finished\";\n result: OperationVerificationResult;\n finishedAt: string;\n}\n\n/**\n * Passed its deadline without finishing — the worker died, or the job never ran. An\n * ENDING, with the time we stopped believing it, and deliberately no `result`: nothing was\n * concluded about the Operation, so nothing is claimed about it.\n */\nexport interface OperationVerificationAbandonedDto extends OperationVerificationBaseDto {\n lifecycle: \"abandoned\";\n result: null;\n finishedAt: string;\n}\n\n/**\n * The closed step vocabulary (docs/31 §4.3). `approval` is RESERVED for a later slice\n * and is rejected at validation with a 422 — the union carries it so the contract does\n * not reshape when the standalone approval step lands.\n */\nexport const OPERATION_STEP_KINDS = [\"action\", \"wait\", \"approval\"] as const;\nexport type OperationStepKind = (typeof OPERATION_STEP_KINDS)[number];\n\n/**\n * What the platform does when a step fails. Three values, evaluated by the platform,\n * never authored (docs/31 §4.3). This is data, not logic.\n */\nexport const STEP_FAILURE_POLICIES = [\"stop\", \"continue\", \"rollback_completed\"] as const;\nexport type StepFailurePolicy = (typeof STEP_FAILURE_POLICIES)[number];\n\n/**\n * Run lifecycle (docs/31 §7.1). `cancelling` is the transient settle-to-cancelled state.\n *\n * `rolled_back` is earned, not assumed: it means EVERY succeeded target was reversed, no\n * step was `not_reversible` and no child rollback failed. Anything less is\n * `partially_rolled_back` — the run list is where someone scans to find out what happened\n * overnight, and a row reading \"Rolled back\" for a run that left half the estate mutated\n * is the failure this product cannot afford. `partially_succeeded` is deliberately NOT\n * reused for it: that status means a half-failed forward run, and the two are different\n * facts an operator responds to differently.\n */\nexport const OPERATION_RUN_STATUSES = [\n \"pending\",\n \"running\",\n \"pending_approval\",\n \"cancelling\",\n \"succeeded\",\n \"partially_succeeded\",\n \"failed\",\n \"rolled_back\",\n \"partially_rolled_back\",\n \"cancelled\",\n] as const;\nexport type OperationRunStatus = (typeof OPERATION_RUN_STATUSES)[number];\n\n/**\n * Per-step status. `not_reversible` is recorded when a rollback was required but the\n * step's action declares none — reported honestly rather than silently skipped.\n */\nexport const OPERATION_RUN_STEP_STATUSES = [\n \"pending\",\n \"running\",\n \"awaiting_approval\",\n \"succeeded\",\n \"failed\",\n \"skipped\",\n \"not_reversible\",\n] as const;\nexport type OperationRunStepStatus = (typeof OPERATION_RUN_STEP_STATUSES)[number];\n\n/**\n * Per-target status, projected from the child execution's terminal state.\n *\n * `rollback_failed` is its OWN status rather than being folded into `failed`: a target\n * whose forward work succeeded and whose reversal then failed is still applied to the\n * cloud, which is the opposite of what `failed` tells a reader. Collapsing the two would\n * report a run as reverted while the estate is still mutated.\n */\nexport const OPERATION_RUN_TARGET_STATUSES = [\n \"pending\",\n \"running\",\n \"awaiting_approval\",\n \"succeeded\",\n \"failed\",\n \"cancelled\",\n \"rolled_back\",\n \"rollback_failed\",\n] as const;\nexport type OperationRunTargetStatus = (typeof OPERATION_RUN_TARGET_STATUSES)[number];\n\n// Who or what started a run is NOT an Operation-Run-only fact any more (docs/45 §4.1):\n// `RUN_TRIGGER_KINDS` in ./enums is the one declaration, and an Execution carries it too.\n\n/**\n * The ONLY data-flow primitive between steps: bind a parameter to an EARLIER step's\n * declared output, by name. `from` is exactly `\"<stepKey>.outputs.<name>\"`. No\n * expressions, no concatenation, no arithmetic, no conditionals — if a value needs\n * computing, that computation belongs inside an action (docs/31 §4.3).\n */\nexport interface OperationOutputBinding {\n from: string;\n}\n\n/**\n * Criteria for a `query`-mode selector. Every field is an EQUALITY or a PREFIX match and\n * they are ANDed together (docs/31 §8.1). There are deliberately no operators, no\n * expressions and no negation beyond `excludeResourceIds`, because an operator must\n * always be able to answer \"why did this match?\" without reading a grammar.\n */\nexport interface TargetSelectorQuery {\n /** Resource groups to search. Equality, ORed within the field, ANDed with the rest. */\n resourceGroups?: string[];\n /** Every pair must be present on the resource — AND across keys, never OR. */\n tags?: Record<string, string>;\n /** Case-insensitive prefix on the resource NAME. */\n namePrefix?: string;\n /** Provider resource ids to drop after everything else matched. */\n excludeResourceIds?: string[];\n}\n\n/** An explicitly listed target set. Still resolved server-side — the list is advisory. */\nexport interface TargetSelectorExplicit {\n /** Provider resource ids. */\n resourceIds: string[];\n}\n\n/**\n * Fan out one action step over many resources (docs/31 §8.1).\n *\n * A step already targets a connection SCOPE; the resource it acts on is an ordinary\n * PARAMETER carrying a `discover` annotation (`azure.disk.clone` takes a `disk`,\n * `azure.sql.backup` a `database`). Fanning out therefore means \"run this step once per\n * resource bound to parameter X\", which is why the selector names that parameter rather\n * than a resource type. **The type is derived server-side from the pinned action\n * version's `discover` annotation and is never taken from the client** — the same rule\n * `actionDefinitionId` earned.\n */\nexport interface TargetSelector {\n /**\n * The action parameter to fan out over. Must exist on the pinned action version's\n * parameter schema AND carry a `discover` annotation.\n */\n parameter: string;\n /** One or more `connection_scope.id`s — this is the multi-connector case. */\n connectionScopeIds: string[];\n mode: \"explicit\" | \"query\";\n /** Populated iff `mode` is `explicit`. */\n explicit?: TargetSelectorExplicit;\n /** Populated iff `mode` is `query`. */\n query?: TargetSelectorQuery;\n /**\n * Refuse the run if more than this many targets resolve. Never a truncation: a silently\n * shortened fan-out is a correctness bug in someone's change window (docs/31 §8.3).\n * Must be ≤ `QUOTA_MAX_TARGETS_PER_RUN`.\n */\n limit?: number;\n}\n\n/** Config of an `action` step. Stored as validated JSONB on `operation_step`. */\nexport interface ActionStepConfig {\n actionVersionId: string;\n /**\n * The parent `action_definition.id` of the pinned version, DERIVED SERVER-SIDE when the\n * step is written and never taken from the client.\n *\n * Pinning means `actionVersionId` stops being the action's latest the moment a newer\n * version is published, so it cannot be used to look the action up. This field is what\n * lets a reader resolve the action in one request instead of scanning the catalog for a\n * version that will never match again.\n *\n * Optional because a step written before migration 0043 may not carry it, and because\n * the backfill deliberately leaves it absent when the pinned version no longer exists —\n * an absent field is honest, a guessed one is not.\n */\n actionDefinitionId?: string;\n /** Provider-neutral `connection_scope.id` — the scope the child execution runs in. */\n connectionScopeId: string;\n /** Literal values, or `{ from: \"<stepKey>.outputs.<name>\" }` bindings. */\n parameters: Record<string, unknown>;\n dryRun: boolean;\n onFailure: StepFailurePolicy;\n /**\n * Fan this step out over many resources (docs/31 §8.1). OPTIONAL, and its absence is\n * the whole backward-compatibility story: a step WITHOUT a selector keeps slice 2a's\n * behaviour exactly — one `connectionScopeId`, one child execution, `targetRef` = the\n * scope id — so no stored step changes shape and no data migration is needed.\n */\n targetSelector?: TargetSelector;\n}\n\n/** Config of a `wait` step. Bounded to 1..86400 seconds so a run cannot become immortal. */\nexport interface WaitStepConfig {\n durationSeconds: number;\n}\n\nexport type OperationStepConfig = ActionStepConfig | WaitStepConfig;\n\n/**\n * One stored step. `stepKey` is stable across versions and is what output bindings\n * reference; `position` is dense and 1-based.\n */\nexport type OperationStepDto =\n | {\n id: string;\n stepKey: string;\n position: number;\n kind: \"action\";\n config: ActionStepConfig;\n }\n | {\n id: string;\n stepKey: string;\n position: number;\n kind: \"wait\";\n config: WaitStepConfig;\n };\n\n/** An Operation version. Immutable once `publishedAt` is set (docs/31 §4.4). */\nexport interface OperationVersionDto {\n id: string;\n version: number;\n publishedAt: string | null;\n createdBy: string;\n createdAt: string;\n steps: OperationStepDto[];\n}\n\n/** Compact, read-only entry used to navigate an Operation's immutable history. */\nexport interface OperationVersionSummaryDto {\n id: string;\n version: number;\n publishedAt: string | null;\n createdBy: string;\n createdAt: string;\n stepCount: number;\n}\n\n/** List/summary view of an Operation. */\nexport interface OperationDto {\n id: string;\n key: string;\n name: string;\n description: string | null;\n ownerId: string;\n lifecycle: OperationLifecycle;\n health: OperationHealth;\n healthReason: string | null;\n healthCheckedAt: string | null;\n latestVersionId: string | null;\n latestVersionNumber: number | null;\n /** Newest version with `publishedAt` set — the version a run pins. Null = not runnable. */\n latestPublishedVersionId: string | null;\n stepCount: number;\n /** Run history is evidence: this count determines whether hard deletion is available. */\n runCount: number;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Detail view: the Operation plus its latest version's full step list. */\nexport interface OperationDetailDto extends OperationDto {\n latestVersion: OperationVersionDto | null;\n /** Newest first. Full steps are loaded only for the version the reader selects. */\n versions: OperationVersionSummaryDto[];\n /**\n * The most recent FINISHED verification attempt, or null when the sweep has not reached\n * this Operation yet. The badge reads `health` on the row above; this is the evidence\n * behind it — every check, with its level and what to do about it.\n *\n * ⚠ FINISHED, and that is load-bearing. An attempt still in flight has no verdict, so\n * letting it become \"the last verification\" would make a healthy Operation read as\n * broken for as long as a probe is merely still running. In-flight attempts are reported\n * separately, below.\n */\n lastVerification: OperationVerificationFinishedDto | null;\n /**\n * The attempt currently in flight, when there is one — the handle that makes a dry-run\n * verification something a reader can WATCH.\n *\n * At most one exists per Operation: the database refuses a second in-flight row (a\n * partial unique index), because two concurrent verifications writing checks into\n * different rows while the Operation shows one health is a state with no honest reading.\n * It is here on the detail DTO so a reader who reloads mid-verification is reattached\n * rather than told nothing is happening.\n */\n activeVerification: OperationVerificationInFlightDto | null;\n}\n\n/** One child execution of one action step. Slice 2a records exactly one per step. */\nexport interface OperationRunTargetDto {\n id: string;\n executionId: string;\n /** The connection scope id in slice 2a; a provider resource id once fan-out lands. */\n targetRef: string;\n targetLabel: string;\n status: OperationRunTargetStatus;\n}\n\nexport interface OperationRunStepDto {\n id: string;\n stepId: string;\n stepKey: string;\n position: number;\n kind: OperationStepKind;\n status: OperationRunStepStatus;\n /** Declared outputs available for name binding by later steps. */\n outputs: Record<string, unknown>;\n startedAt: string | null;\n finishedAt: string | null;\n error: string | null;\n targets: OperationRunTargetDto[];\n /**\n * ═══ WHAT WAS DECIDED ABOUT EACH TARGET BEFORE ANY CHILD EXISTED (docs/126 §14 B-3) ════\n *\n * `targets` above are child executions, and a target that never got one — left out by the\n * requester, refused by its checks — has no row there. This is where the run says what happened\n * to it. `null` when the step was not checked before the run and no child was refused at submit.\n */\n targetPlan: TargetPlanEntry[] | null;\n}\n\n/**\n * ═══ ONE TARGET OF A STEP, AS THE RUN DECIDED IT BEFORE ITS GATE (docs/126 §14 B-3) ═══════\n *\n * Kept on `operation_run_step.target_plan` (migration 0099), one entry per target the step\n * resolved when the run was started, written in the same transaction as the run's steps.\n *\n * ref the provider resource id — the identity re-resolution and the drift guard compare\n * label what a person reads, from `targetLabel`\n * disposition ready | left_out | refused (`TARGET_DISPOSITIONS`)\n * decisions for a `ready` target, every DECIDE code its checks raised, with WHO answered it —\n * the user who started the run — and WHEN, by the server's clock; `[]` otherwise\n * assessment for a `ready` target, its facts, warnings and decisions as the approver reads them;\n * `null` otherwise\n * refusal for a `refused` target, the checks' own sentence; `null` otherwise\n *\n * ★ A REFUSAL CAN ARRIVE LATER. A `ready` target whose checks changed after approval is refused\n * ALONE when its child is submitted, and this entry becomes `refused` with that sentence — so the\n * run says why a target it approved never got an execution.\n */\nexport interface TargetPlanEntry {\n ref: string;\n label: string;\n disposition: TargetDisposition;\n decisions: RecordedDecision[];\n assessment: ApprovalPlanTargetAssessment | null;\n refusal: string | null;\n}\n\n/**\n * ═══ READING A TARGET PLAN BACK — PARSED, NEVER CAST ════════════════════════════════════\n *\n * `null` for a NULL column, and for anything that is not an array. An entry this cannot read is\n * DROPPED, and the direction of that is the safety property: a dropped `left_out` or `refused`\n * entry is no longer subtracted from the re-resolved set, so the drift guard fails the step closed;\n * a dropped `ready` entry carries no decisions, so that target's child is refused at submit. An\n * unreadable decision is dropped by `recordedDecisionsOf` for the same reason — a decision that\n * cannot be read was not made.\n */\nexport function targetPlanOf(stored: unknown): TargetPlanEntry[] | null {\n if (!Array.isArray(stored)) return null;\n const plan: TargetPlanEntry[] = [];\n for (const entry of stored) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) continue;\n const { ref, label, disposition, decisions, assessment, refusal } = entry as Record<string, unknown>;\n if (typeof ref !== \"string\" || ref.length === 0) continue;\n if (typeof label !== \"string\" || !isTargetDisposition(disposition)) continue;\n if (refusal !== null && typeof refusal !== \"string\") continue;\n plan.push({\n ref,\n label,\n disposition,\n decisions: recordedDecisionsOf(decisions),\n assessment: planAssessmentOf(assessment),\n refusal: refusal ?? null,\n });\n }\n return plan;\n}\n\n/** One run of one Operation version. */\nexport interface OperationRunDto {\n id: string;\n /** Human reference, `OPR-####` — distinct from an execution's `OPS-####`. */\n reference: string;\n operationId: string;\n operationKey: string;\n operationName: string;\n operationVersionId: string;\n version: number;\n status: OperationRunStatus;\n triggeredBy: string;\n triggerKind: RunTriggerKind;\n scheduleId: string | null;\n /**\n * The schedule's name as it stood when the run fired. Denormalized so run detail can\n * say WHICH schedule produced a 3am run without operations reading scheduling's table.\n */\n scheduleName: string | null;\n /** The schedule owner's standing pre-authorization, carried on the run itself. */\n autoApprove: boolean;\n dryRun: boolean;\n /**\n * ═══ ★ THE RECORD THIS OPERATION'S RUNS IMPLEMENT (docs/84 §5) ═══════════════════════\n *\n * Named ONCE, here, and carried onto every child execution this run creates. Null when the\n * operator named none — every run before this shipped, and every run in a workspace with no\n * change-control rule.\n *\n * ★ IT IS A `ChangeRecordRef` AND NOT A `ChangeRecordCitation`, AND THE DIFFERENCE IS THE\n * POINT. An Operation run is not gated: `assertChangeRecord` runs on each CHILD execution,\n * so this level is a DECLARATION and never an establishment. Giving it an `assurance` would\n * put the vocabulary in a place where nothing could ever raise it past `recorded`, and the\n * one honest thing to say about this reference is which runs to read it on. Each child\n * carries its own, established by its own gate — see `ExecutionDto.changeRecord`.\n */\n changeRecord: ChangeRecordRef | null;\n startedAt: string | null;\n finishedAt: string | null;\n createdAt: string;\n}\n\n/**\n * One step a rollback would NOT reverse, because its action declares none. Named rather\n * than counted: \"2 steps cannot be rolled back\" tells an operator nothing they can act on.\n */\nexport interface OperationRunIrreversibleStepDto {\n stepKey: string;\n position: number;\n actionName: string;\n /** Targets of that step whose changes would remain applied. */\n targets: number;\n}\n\n/**\n * Whether this run can be rolled back, and what a rollback would actually do — computed\n * server-side so the confirm dialog states the truth before the operator commits, and so a\n * refusal always arrives with its reason rather than as a disabled control.\n */\nexport interface OperationRunRollbackPlanDto {\n available: boolean;\n /** Why not, in the operator's terms. Null when available. */\n reason: string | null;\n /** How many targets would be reversed. */\n reversibleTargets: number;\n irreversibleSteps: OperationRunIrreversibleStepDto[];\n}\n\nexport interface OperationRunDetailDto extends OperationRunDto {\n steps: OperationRunStepDto[];\n rollback: OperationRunRollbackPlanDto;\n}\n\n/**\n * Which Operation run, if any, a child execution belongs to.\n *\n * This exists as its own lookup rather than as fields on `ExecutionDto` because the link\n * lives on `operation_run_target`, a table the `operations` module owns. For `execution`\n * to read it would break the one-owning-module rule (docs/12 §3.1), and for `execution`\n * to ask the operations facade would close a cycle — `operations` already depends on\n * `execution` — which the dependency-cruiser `no-cycles` rule rejects outright. So the\n * owning module answers the question, and the caller joins.\n */\nexport interface OperationRunLinkDto {\n executionId: string;\n runId: string;\n /** The run's human reference, e.g. `OPR-1042`. */\n reference: string;\n operationName: string;\n}\n\n/** One authored step on the way in. `config` is validated server-side, never trusted. */\nexport interface CreateOperationStepInput {\n stepKey: string;\n kind: OperationStepKind;\n /** Optional; when present it must equal the step's dense, 1-based position. */\n position?: number;\n config: Record<string, unknown>;\n}\n\nexport interface CreateOperationInput {\n key: string;\n name: string;\n description?: string;\n steps: CreateOperationStepInput[];\n}\n\nexport interface UpdateOperationInput {\n name?: string;\n description?: string | null;\n /** `published` restores a deprecated or retired Operation without rewriting a version. */\n lifecycle?: Extract<OperationLifecycle, \"published\" | \"deprecated\" | \"retired\">;\n /** Replacing the step list of a PUBLISHED version creates a new draft version. */\n steps?: CreateOperationStepInput[];\n}\n\nexport interface StartOperationRunInput {\n dryRun?: boolean;\n triggerKind?: RunTriggerKind;\n scheduleId?: string;\n /**\n * Denormalized at fire time so the run records the standing authorization exactly\n * as it was granted — surviving a later rename or deletion of the schedule — and\n * so run detail can name the schedule without a cross-module read.\n */\n scheduleName?: string;\n /**\n * The schedule owner's standing pre-authorization. Only accepted with\n * `triggerKind === \"schedule\"` and a `scheduleId`, and only from a caller holding\n * `approval:decide`. Never accepted over HTTP.\n */\n autoApprove?: boolean;\n /** Caller-supplied run key; defaults to a generated one. Unique per tenant. */\n idempotencyKey?: string;\n /**\n * ═══ ★ ONE REFERENCE, NAMED ONCE, CARRIED TO EVERY CHILD (docs/84 §5) ════════════════\n *\n * The change-record gate sits ABOVE `submitPreApproved`, deliberately — below it, wrapping\n * an action in an Operation would be a way past change control. The cost docs/83 recorded\n * and deferred is that an Operation run had nowhere to NAME a record, so a matching rule\n * refused every child with `no_reference`. Harmless while no rule could be enabled; a broken\n * feature the moment a `recorded` one can be. This field is the other half.\n *\n * ★ ACCEPTED OVER HTTP, unlike `autoApprove` and `triggerKind` beside it, and for the reason\n * `SubmitExecutionInput.changeRecord` gives: those two LOWER a bar, and this one can only\n * ever raise one. There is no value a caller can put here that admits a run Opera would\n * otherwise have refused.\n *\n * ⚠ NOT VALIDATED HERE. Each child's own gate resolves the rule that applies to ITS action,\n * environment and connector and refuses it if the record does not satisfy it — which is the\n * only place that question has a single correct answer, since a fan-out may straddle\n * environments and connectors that match different rules.\n */\n changeRecord?: ChangeRecordRef;\n /**\n * ═══ ★ WHAT THE REQUESTER DECIDED, PER STEP AND PER TARGET (docs/126 §14 B-3) ══════════\n *\n * For each step the preview CHECKED: the DECIDE codes acknowledged for each target, and the\n * targets left out. ANSWERS, never the authority — the server re-runs every target's checks at\n * start and refuses with a 409 naming every target whose raised codes differ from these, in both\n * directions, exactly as a single run's submit does. Nothing here is trusted, cached or stored as\n * sent: what is kept is the server's own target plan, built from its own checks.\n *\n * Absent means nothing was decided and nothing left out — which every client before Slice B\n * sends, and which a step raising a DECIDE check refuses.\n */\n stepDecisions?: StartOperationRunStepDecisions[];\n}\n\n/** One checked step's answers, keyed by the version's step id (`OperationPreviewStepDto.stepId`). */\nexport interface StartOperationRunStepDecisions {\n stepId: string;\n /** Per target ref, the DECIDE codes acknowledged. A target with nothing to decide is omitted. */\n acknowledged: { ref: string; codes: DecisionCode[] }[];\n /** The refs the requester left out. Excluded BY THE RUN, never written into the Operation. */\n leftOut: string[];\n}\n\n/** Body of `POST /operations/:id/preview`. */\nexport interface PreviewOperationRunInput {\n /** Preview as a dry run, exactly as `StartOperationRunInput.dryRun` would run it. */\n dryRun?: boolean;\n}\n\n/** One resolved target on a preview — what a child execution would be created for. */\nexport interface OperationPreviewTargetDto {\n /** Provider resource id. Becomes `operation_run_target.targetRef`. */\n id: string;\n /** Resource name — the value that would be bound to the selector's parameter. */\n name: string;\n resourceGroup?: string;\n /** The connection scope this resource was discovered in. */\n connectionScopeId: string;\n}\n\n/**\n * A step's resolved target set. `total` is ALWAYS the full count even when `sample` is\n * capped for display — a preview that shows ten of four hundred targets without saying\n * \"four hundred\" is the exact failure mode this endpoint exists to prevent.\n */\nexport interface OperationPreviewTargetsDto {\n total: number;\n /** Up to `PREVIEW_TARGET_SAMPLE_SIZE` targets, in the run's own resolution order. */\n sample: OperationPreviewTargetDto[];\n /** True when `sample.length < total`. */\n truncated: boolean;\n /** Targets recorded for this step on its most recent run; null when it never ran. */\n previousTotal: number | null;\n /** Always populated, so \"no warning\" is never mistaken for \"no growth\". */\n driftNote: string;\n /**\n * Non-null when the count grew past `OPERATIONS_TARGET_DRIFT_WARN_PCT` since the last\n * run — the \"I meant 4 VMs, not 400\" guard (docs/31 §8.3).\n */\n driftWarning: string | null;\n}\n\n/** The governed plan for one action step, aggregated across its targets. */\nexport interface OperationPreviewActionPlanDto {\n actionVersionId: string;\n actionKey: string;\n actionName: string;\n /** True when the run or the step forces simulation. */\n dryRun: boolean;\n /** Whether the pinned action declares a rollback; false means `not_reversible`. */\n reversible: boolean;\n /** Merged verdict: approval is required if ANY connection scope requires it. */\n governance: ExecutionPlanGovernance;\n /**\n * ═══ WHICH STEPS WILL DEMAND A RECORD (docs/84 §5) ═══════════════════════════════════\n *\n * The change-control requirement this step's children will meet, or null when no rule\n * matches. Merged across the step's connection scopes by the same rule `governance` uses —\n * the FIRST scope that requires one decides, because a fan-out that straddles a gated\n * environment and an ungated one still has children that need a record.\n *\n * ⚠ IT IS THE STEP'S DECLARED AND RESOLVED SCOPES ONLY. A selector can discover a target in\n * a scope this preview never looked at, whose child could match a rule listed nowhere here.\n * That is why the run dialog offers the field whenever the workspace has ANY enabled\n * change-control rule rather than only when this says so: a preview that drove the question\n * would have false negatives, and a false negative here is a refused child.\n */\n changeControl: ExecutionPlanChangeControl | null;\n /** Declared RBAC ceiling, de-duplicated across the step's scopes. */\n requiredPermissions: RequiredPermission[];\n targets: OperationPreviewTargetsDto;\n /**\n * ═══ ★ EVERY TARGET, CHECKED BEFORE THE RUN (docs/126 §14 B-1) ══════════════════════════\n *\n * For an action whose connector plans its checks, the connector's own `validate` was run for\n * EVERY resolved target — not the sample above — and each comes back with its refusals, its\n * decisions, its warnings and its facts. Otherwise the step says why it was not checked, which is\n * a different fact from \"nothing to report\".\n */\n checks: OperationPreviewStepChecksDto;\n}\n\n/**\n * ═══ WHY A STEP WAS NOT CHECKED BEFORE THE RUN ═══════════════════════════════════════════\n *\n * depends_on_earlier_output its parameters are bound to an earlier step's outputs, which do\n * not exist until that step has run (docs/126 §14 F7)\n * connector_plans_no_checks its action declares `plannedChecks: \"none\"` (§14 F8)\n */\nexport const PREVIEW_UNCHECKED_REASONS = [\n \"depends_on_earlier_output\",\n \"connector_plans_no_checks\",\n] as const;\nexport type PreviewUncheckedReason = (typeof PREVIEW_UNCHECKED_REASONS)[number];\n\n/** The sentence each reason is shown as. Pinned to the union: a new reason is a compile error here. */\nexport const PREVIEW_UNCHECKED_SENTENCE: Record<PreviewUncheckedReason, string> = {\n depends_on_earlier_output:\n \"Not checked before the run: this step's parameters come from an earlier step's outputs, which exist only once that step has run. Each target is checked when its execution is submitted, and a target that would need a decision is not acted on.\",\n connector_plans_no_checks: \"This action runs no checks of its own before the run.\",\n};\n\nexport type OperationPreviewStepChecksDto =\n | { checked: true; targets: OperationPreviewTargetCheckDto[] }\n | { checked: false; reason: PreviewUncheckedReason };\n\n/**\n * One target's pre-flight, sorted into what it is to the requester. A target with any refusal is\n * REFUSED — nobody can decide their way past one; the rest are decided per code, or are ready.\n */\nexport interface OperationPreviewTargetCheckDto {\n /** Provider resource id — the ref `StartOperationRunStepDecisions` answers about. */\n ref: string;\n label: string;\n /** Every `error` check, in the checks' own words. Non-empty means the target is refused. */\n refusals: string[];\n /** Every DECIDE check: its code, and the sentence this target raised it with. */\n decisions: { code: DecisionCode; title: string }[];\n warnings: string[];\n facts: string[];\n}\n\n/**\n * One step of a run preview. `plan` is null exactly when `blockedReason` is set — a step\n * that cannot be planned says so in words rather than presenting a plausible plan for\n * work that would not run.\n */\nexport interface OperationPreviewStepDto {\n stepId: string;\n stepKey: string;\n position: number;\n kind: OperationStepKind;\n /** `wait` steps only. */\n durationSeconds: number | null;\n plan: OperationPreviewActionPlanDto | null;\n blockedReason: string | null;\n}\n\n/**\n * `POST /operations/:id/preview` (docs/31 §8.4, story P3). Built from the SAME resolution\n * path and the same `EXECUTION_FACADE.preview` the run itself uses, so preview and run\n * cannot diverge — which is the entire point of the endpoint.\n */\nexport interface OperationRunPreviewDto {\n operationId: string;\n operationKey: string;\n operationName: string;\n /** The version a run would pin: the latest PUBLISHED one, else the latest draft. */\n operationVersionId: string;\n version: number;\n /** False when the previewed version is still a draft and could not be run yet. */\n versionPublished: boolean;\n dryRun: boolean;\n /** Total child executions this run would create, across every step. */\n totalTargets: number;\n steps: OperationPreviewStepDto[];\n /** Every drift/blocking warning in the plan, so a caller can lead with them. */\n warnings: string[];\n}\n\nexport interface ListOperationsQuery {\n cursor?: string;\n limit?: number;\n lifecycle?: OperationLifecycle;\n /** Verification health filter (docs/31 §12) — \"show me what is broken\". */\n health?: OperationHealth;\n q?: string;\n}\n\nexport interface ListOperationRunsQuery {\n cursor?: string;\n limit?: number;\n operationId?: string;\n status?: OperationRunStatus;\n}\n","// ═══ ONE KIND OF RUN ══════════════════════════════════════════════════════════════════\n//\n// docs/31 §17.5 records the risk in its own words: \"Two run concepts in the UI — Executions\n// and Operation Runs both exist. Mitigation: Execution History groups by run and shows\n// single-action runs as one-step runs, so users see one concept.\" This file is that one\n// concept, expressed as a type.\n//\n// THE DOMAIN STAYS TWO OBJECTS. `Execution` and `OperationRun` are unchanged, separately\n// owned and separately governed (docs/31 §5.3). What is unified is the READER's view: a\n// projection assembled server-side over both, because it cannot be assembled anywhere else\n// and stay true — see §\"Why the server\" below.\n//\n// ─── TWO ORTHOGONAL FACTS, NEVER ONE ENUM ───────────────────────────────────────────────\n//\n// Fact 1 — ORIGIN: how the run came to exist. {@link RunOrigin}, below.\n// Fact 2 — OUTCOME: how it ended. Already closed vocabularies (`ExecutionStatus`,\n// `OperationRunStatus`) and deliberately NOT restated here: a third status\n// vocabulary that had to be kept in sync with two others is how a filter ends up\n// offering \"Rolled back\" but not \"Partially rolled back\".\n//\n// They are orthogonal, so each `RunListItemDto` member carries its origin's own status type\n// and the union discriminates on `origin`. A `status: string` shared across all three would\n// let a trial render with an Operation-run status and compile.\n//\n// ─── WHY THE SERVER ─────────────────────────────────────────────────────────────────────\n//\n// Grouping on the client is not a cheaper version of this — it is a wrong version. A browser\n// that fetches one page of executions and groups them by run renders a 200-target run as a\n// group of 2 when the other 198 are on the next page, and a group that silently describes a\n// subset is worse than no grouping. Pagination therefore has to happen on the RUN, which\n// means the union and the keyset both belong in the query. Same defect class as the audit\n// timeline's latent 50-event cap.\nimport type { ConnectionRef } from \"./connections\";\nimport type {\n Environment,\n ExecutionResult,\n ExecutionStatus,\n RiskLevel,\n RunTriggerKind,\n} from \"./enums\";\nimport { EXECUTION_STATUSES } from \"./enums\";\nimport type { RunExecutionSiteDto } from \"./execution-site\";\nimport type {\n OperationRunStatus,\n OperationRunStepStatus,\n OperationRunTargetStatus,\n OperationStepKind,\n} from \"./operations\";\nimport { OPERATION_RUN_STATUSES } from \"./operations\";\n// ★ FROM THE LEAF, NOT FROM `execution.ts` THAT RE-EXPORTS IT. `validation.ts` exists\n// precisely so a module that needs a validate RESULT does not have to import the whole\n// execution module to describe one — the edge that closed a cycle when docs/57 added\n// `runnerWait`. `pnpm boundaries` is the only thing that ever said so.\nimport type { TargetComparison } from \"./validation\";\nimport type { ChangeRecordCitation, ChangeRecordRef } from \"./change-control\";\n\n/**\n * FACT 1 — how the run came to exist. Closed, and orthogonal to how it ended.\n *\n * - `operation` — an Operation Run: 1+ steps, each resolving to 1+ target executions.\n * Reference `OPR-####`. Expands to its steps and their targets.\n * - `standalone` — one execution submitted from the catalog run wizard. Reference\n * `OPS-####`. Presented as a ONE-STEP run so it reads as the same kind\n * of thing as an Operation Run, which is the whole point of the slice.\n * - `trial` — a trial run of an UNPUBLISHED draft. Reference is the execution's, and\n * it is not a catalog run: presenting it as a governed run of a published\n * action would be a lie about provenance, so the row says so.\n *\n * A SCHEDULED Operation Run is `operation` with schedule provenance — not a fourth origin.\n * How a run was triggered is a third fact again, and it already lives on the row as\n * `triggerKind` / `scheduleId` / `scheduleName`.\n */\nexport const RUN_ORIGINS = [\"operation\", \"standalone\", \"trial\"] as const;\nexport type RunOrigin = (typeof RUN_ORIGINS)[number];\n\n/**\n * Every status a run in this feed can be filtered by: the UNION of the two closed\n * vocabularies, derived from them rather than listed a second time (charter §4.2).\n *\n * Deriving matters more here than usual. The union is asymmetric on purpose — only an\n * Operation Run can be `partially_succeeded`, only an execution can be `queued` — and a\n * hand-written copy would drift the moment either vocabulary gained a member, silently\n * hiding exactly the runs an operator was looking for. A filter value outside a branch's\n * own vocabulary excludes that branch entirely; it never widens to \"close enough\".\n */\nexport type RunFeedStatus = ExecutionStatus | OperationRunStatus;\n\nexport const RUN_FEED_STATUSES: readonly RunFeedStatus[] = [\n ...EXECUTION_STATUSES,\n ...OPERATION_RUN_STATUSES.filter(\n (status) => !(EXECUTION_STATUSES as readonly string[]).includes(status),\n ),\n];\n\n/** True when `value` is a status either branch of the feed understands. */\nexport function isRunFeedStatus(value: string): value is RunFeedStatus {\n return (RUN_FEED_STATUSES as readonly string[]).includes(value);\n}\n\n/**\n * A row's position in the feed's ordering: `(createdAt, id)`, newest first.\n *\n * The id tiebreak is not theoretical. A fan-out writes its child rows inside ONE\n * transaction and PostgreSQL fixes `now()` for a transaction, so equal `created_at` across\n * rows is the normal case there rather than a coincidence — and a keyset on `created_at`\n * alone would loop or skip across that group.\n */\nexport interface RunFeedKey {\n /** ISO-8601. */\n at: string;\n id: string;\n}\n\n/**\n * What the run feed asks `execution` for. Execution answers about its OWN rows only; it is\n * told nothing about Operations and needs to know nothing — the caller removes the\n * executions that belong to an Operation Run, using the link table it owns itself.\n */\nexport interface ExecutionRunFeedQuery {\n /** Strictly older than this key. Absent starts at the newest row. */\n before?: RunFeedKey;\n /**\n * Include the row AT `before` instead of starting strictly below it.\n *\n * How a focused deep link anchors its page on the row it named. Expressed as a flag on\n * the predicate rather than by nudging the cursor's uuid, because `id` is a uuid COLUMN:\n * a \"just above this id\" sentinel is not a uuid and PostgreSQL rejects the comparison.\n */\n inclusive?: boolean;\n limit: number;\n /** Matched against the execution reference and the action's name/key. */\n search?: string;\n status?: ExecutionStatus;\n /**\n * Restrict to executions recorded against ONE actor — the feed's `scope=mine`.\n *\n * ⚠ APPLIED INSIDE THE BRANCH QUERY, never to a merged page (docs/45 §6). The feed reads\n * `limit + 1` per branch and merges them under a frontier rule; filtering afterwards\n * returns short pages, moves the frontier past rows nobody looked at, and silently loses\n * runs at the page boundary. That is why this is a parameter and not a `.filter()`.\n */\n actorId?: string;\n /**\n * Restrict to executions naming ONE change record — the feed's audit population\n * (docs/87 §1). EXACT and case-insensitive; never a prefix and never fuzzy.\n *\n * ⚠ APPLIED INSIDE THE BRANCH QUERY, for the reason written above `actorId` and with more\n * at stake: a short page under a `scope=mine` filter is a nuisance, and a short page under\n * this one is an auditor told a change touched three runs when it touched thirty.\n */\n changeRecordReference?: string;\n}\n\n/**\n * A page of execution KEYS — deliberately not rows.\n *\n * The feed discards the executions that belong to an Operation Run, and hydrating a row\n * costs a catalog lookup for its action's display name. Scanning in keys and hydrating only\n * what survives is what keeps a workspace whose history is mostly fan-out from paying to\n * build hundreds of rows it will immediately throw away.\n */\nexport interface ExecutionRunFeedKeyPage {\n keys: RunFeedKey[];\n /** True when older rows remain beyond the last key — i.e. the page filled its limit. */\n hasMore: boolean;\n}\n\n/** Facts every row shows, whatever its origin. */\ninterface RunListItemBase {\n /**\n * The row's sort key, ISO-8601. The feed is ordered `(createdAt, id)` DESC across both\n * origins and paginated by KEYSET on that pair — never by offset, which duplicates and\n * skips rows under a list that is being appended to while someone reads it.\n */\n createdAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n /** Wall-clock milliseconds, or null until the run finishes. */\n durationMs: number | null;\n /** Human reference — `OPR-####` for an Operation Run, `OPS-####` for an execution. */\n reference: string;\n /** What this run DID, in the reader's words: the Operation's name, or the action's. */\n title: string;\n dryRun: boolean;\n /**\n * How many steps this run has. A standalone or trial run is `1` — it is a one-step run,\n * not a run with no steps, and saying `0` would make it read as a different kind of thing.\n */\n stepCount: number;\n /**\n * How many targets this run acted on, TRUE — counted in the database over the whole run,\n * never over the targets that happened to fit on a page. A standalone run is its own\n * single target, so `1`.\n *\n * The scale win of this list is stated by this field: a 200-target run is ONE row with\n * `targetCount: 200`, not 200 rows.\n */\n targetCount: number;\n /**\n * ═══ THE RESOLVED ACTOR — ONE CONCEPT, ON EVERY ROW (docs/45 §4.1) ══════════════════\n *\n * The `app_user.id` whose authority this run went out under. It is\n * `operation_run.triggered_by` on one branch and `execution.created_by` on the other,\n * and those were TWO SPELLINGS OF ONE CONCEPT — charter §4.2's defect, in the data\n * model. The feed already normalises two sources into one row shape, so it is normalised\n * HERE, once, rather than by two callers that can drift.\n *\n * \"Whose authority\", not \"who was at the keyboard\": a schedule is a standing delegation\n * of its owner's authority — the tick handler resolves the owner's context and refuses to\n * fire once that authority lapses — so a schedule-fired run is genuinely recorded against\n * its owner. {@link RunListItemBase.triggerKind} is what stops that from misleading.\n */\n triggeredBy: string;\n /**\n * ═══ THE ACTOR AS A READER CAN READ IT (docs/46 §3.1) ══════════════════════════════\n *\n * {@link RunListItemBase.triggeredBy} is an `app_user.id`. A UUID on a run row is the\n * defect fixed in July when `permissions_held` showed Opera's internal scope id: the\n * field being PRESENT is not the same as the fact being PRESENTABLE.\n *\n * ─── RESOLVED BY THE SERVER, ALWAYS ──────────────────────────────────────────────────\n *\n * The client must never map an id to a person. It does not hold the directory, so it\n * would need a request per row to try — the N+1 this feed's keyset design exists to\n * avoid (docs/46 §6). Each branch resolves its own page's actors in ONE batched read.\n *\n * ─── WHY IT IS JOINED AND NOT DENORMALIZED ───────────────────────────────────────────\n *\n * `scheduleName` is denormalized at fire time because a schedule is genuinely DELETED\n * (`scheduling.repository.ts` — `schedule.deleteMany`), so there would be nothing left\n * to join to. A user is not: deprovisioning is `app_user.status = 'disabled'`\n * (docs/25 §5.2, \"disable, don't delete\"), no delete path exists, and both\n * `execution.created_by` and `operation_run.triggered_by` are REQUIRED foreign keys —\n * PostgreSQL would refuse the delete while any run referenced the row. The join cannot\n * fail for the case §3.1 is about, and denormalizing would additionally FREEZE the\n * name, so one person's rows would disagree with each other across time. On an audit\n * surface that is worse than a stale name.\n *\n * `null` therefore means genuinely unresolvable, not \"deprovisioned\" — the display\n * layer renders it as an unknown user, and never as blank.\n */\n triggeredByName: string | null;\n /**\n * ═══ WHY THE ACTOR IS NOT THE WHOLE ANSWER ═════════════════════════════════════════\n *\n * `triggeredBy` alone cannot separate \"I ran this\" from \"a schedule I own ran this\", and\n * a \"Mine\" list that silently mixes them tells a reader something untrue about their own\n * history. Only `OperationRun` could say which it was; an `Execution` had NO trigger\n * provenance at all, so one filter answered a DIFFERENT question on each half of the\n * feed. docs/45 §4.1 route one closed that: `execution` carries these three columns now\n * (migration 0059), and every row of this feed can say how it came about.\n */\n triggerKind: RunTriggerKind;\n /** The schedule that fired this run, when `triggerKind` is `schedule`. */\n scheduleId: string | null;\n /** Denormalized at fire time, so a deleted schedule still leaves a readable row. */\n scheduleName: string | null;\n}\n\n/**\n * WHOSE RUNS THIS PAGE IS ABOUT (docs/45 §4.2).\n *\n * `all` is the DEFAULT, and not merely the first member. A governance control plane exists\n * so a team can see what is happening in its workspace; defaulting to `mine` hides the\n * workspace and makes the product feel emptier and less trustworthy than it is.\n *\n * ⚠ NOT A PERMISSION BOUNDARY (docs/45 D3). What a reader may see is decided by RLS and by\n * the `execution:read` / `operation:read` gates this feed already applies; `all` cannot\n * widen that by one row. Scope follows role — the filter is a convenience on top of a\n * bound that was already there, never the thing that enforces it.\n */\nexport const RUN_SCOPES = [\"all\", \"mine\"] as const;\nexport type RunScope = (typeof RUN_SCOPES)[number];\n\n/** The scope a request that names none is answered at. */\nexport const DEFAULT_RUN_SCOPE: RunScope = \"all\";\n\n/** One target status and how many targets of this run are in it. */\nexport interface RunTargetOutcomeCount {\n status: OperationRunTargetStatus;\n count: number;\n}\n\n/**\n * ONE ROW OF THE FEED. Discriminated on {@link RunOrigin} so each origin carries its own\n * closed status vocabulary and its own identity — an Operation Run is identified by its\n * run id, an execution row by its execution id, and no consumer can confuse the two.\n */\nexport type RunListItemDto =\n | (RunListItemBase & {\n origin: \"operation\";\n /** `operation_run.id` — what `/operation-runs/{id}` resolves. */\n runId: string;\n operationId: string;\n operationKey: string;\n operationVersionId: string;\n version: number;\n status: OperationRunStatus;\n /**\n * Target outcomes counted over the WHOLE run — what makes partial success legible.\n * A single status word turns \"173 of 200 succeeded, 27 failed\" into \"failed\", which\n * is the state a fan-out actually lands in and the one a reader must be able to act\n * on. Only non-zero counts appear.\n *\n * On the `operation` member ALONE, deliberately: a standalone run has no targets to\n * be partial about, and giving it a synthetic one-entry breakdown would mean mapping\n * an `ExecutionStatus` onto the target vocabulary — a second, lossy copy of a\n * closed set, which is the defect class this slice exists to remove.\n */\n targetOutcomes: RunTargetOutcomeCount[];\n /**\n * ═══ THE CHANGE THIS RUN WAS MADE UNDER — A DECLARATION (docs/87 §1) ═══════════\n *\n * ★ A `ChangeRecordRef` AND NOT A `ChangeRecordCitation`, ON THIS MEMBER ALONE, and\n * that is the compile-time half of docs/84 §3.3. An Operation is not gated, so the\n * reference it carries is what an operator SUPPLIED for the whole run — nothing\n * checked it, and each child execution records how its OWN was established. Giving\n * this row an `assurance` would be this list claiming Opera verified a record it\n * never asked about; the type is what makes that unwritable rather than merely\n * untested.\n *\n * Null when the Operation named no record.\n */\n changeRecord: ChangeRecordRef | null;\n })\n | (RunListItemBase & {\n origin: \"standalone\";\n executionId: string;\n actionKey: string;\n actionVersionId: string;\n status: ExecutionStatus;\n result: ExecutionResult;\n riskLevel: RiskLevel;\n environment: Environment;\n /**\n * ═══ WHERE IT RAN (docs/56 §3.3) ═══════════════════════════════════════════════\n *\n * ★ ON THE TWO EXECUTION-BEARING MEMBERS AND NOT ON `RunListItemBase`, for the same\n * reason `targetOutcomes` is on the `operation` member alone. An Operation Run is N\n * executions across M steps, and each step selects its own pool through its own\n * connection — so the only honest run-level answer would be a SET, and collapsing a\n * set to one word is how \"173 of 200 succeeded\" became \"failed\". The operation\n * branch says it per target, where each target IS one of these rows.\n *\n * Never null: a row that nobody wrote to reads `{ site: \"unknown\" }`, which is a\n * statement, and `null` would be an invitation to substitute a default.\n */\n executedOn: RunExecutionSiteDto;\n /**\n * ═══ DID THIS RUN ACT ON WHAT WAS APPROVED (docs/68 §6) ════════════════════════\n *\n * ★ SO AN AUDITOR REVIEWING 200 RUNS CAN FIND THE ONES THAT DRIFTED WITHOUT OPENING\n * 200 EVIDENCE BUNDLES. Both numbers were already recorded before this slice — the\n * promise on the row, the outcome in the bundle — and the only way to set them beside\n * each other was to download a JSON manifest per run and compare by eye.\n *\n * ★ DERIVED BY THE SERVER THROUGH `compareTargets`, exactly as `executedOn` above is\n * derived through `executionSiteOf`, and read by the run record through the same\n * function over the same two summaries. One author, two callers — which is what stops\n * this list and that drawer saying different things about one run.\n *\n * ⚠ ON THE TWO EXECUTION-BEARING MEMBERS AND NOT ON `RunListItemBase`, for the reason\n * written above `executedOn` and above `targetOutcomes`: an Operation Run is N\n * executions across M steps, each with its own promise and its own outcome, so the only\n * honest run-level answer would be a SET.\n *\n * ⚠ NOT `targetOutcomes`, WHICH IS A DIFFERENT QUESTION ON THE SIBLING MEMBER. That one\n * counts how each TARGET of a fan-out ended; this one compares a count taken at plan\n * time against a count taken at run time.\n */\n targetComparison: TargetComparison;\n /**\n * ═══ THE CHANGE THIS RUN WAS MADE UNDER, AND HOW IT WAS ESTABLISHED ═══════════\n *\n * ★ A `ChangeRecordCitation` — the reference AND its assurance, travelling together,\n * because a reader who sees `CHG0031425` on a row assumes it was checked unless told\n * otherwise (docs/84 §3.3). That rule does not relax because the reader arrived by\n * filtering, so the two cannot be separated HERE either: the type carries both or\n * neither, exactly as `execution`'s triple CHECK constraint (migration 0083) states\n * the same rule in the schema.\n *\n * ⚠ ON THE TWO EXECUTION-BEARING MEMBERS AND NOT ON `RunListItemBase`, for the\n * reason written above `executedOn`: only `execution` carries an assurance, so the\n * sibling member can only honestly offer a {@link ChangeRecordRef}.\n *\n * Null when the run named no record — which is every run a change-control rule did\n * not gate.\n */\n changeRecord: ChangeRecordCitation | null;\n })\n | (RunListItemBase & {\n origin: \"trial\";\n executionId: string;\n actionKey: string;\n actionVersionId: string;\n status: ExecutionStatus;\n result: ExecutionResult;\n riskLevel: RiskLevel;\n environment: Environment;\n /**\n * ═══ WHERE IT RAN (docs/56 §3.3) ═══════════════════════════════════════════════\n *\n * ★ ON THE TWO EXECUTION-BEARING MEMBERS AND NOT ON `RunListItemBase`, for the same\n * reason `targetOutcomes` is on the `operation` member alone. An Operation Run is N\n * executions across M steps, and each step selects its own pool through its own\n * connection — so the only honest run-level answer would be a SET, and collapsing a\n * set to one word is how \"173 of 200 succeeded\" became \"failed\". The operation\n * branch says it per target, where each target IS one of these rows.\n *\n * Never null: a row that nobody wrote to reads `{ site: \"unknown\" }`, which is a\n * statement, and `null` would be an invitation to substitute a default.\n */\n executedOn: RunExecutionSiteDto;\n /**\n * ═══ DID THIS RUN ACT ON WHAT WAS APPROVED (docs/68 §6) ════════════════════════\n *\n * ★ SO AN AUDITOR REVIEWING 200 RUNS CAN FIND THE ONES THAT DRIFTED WITHOUT OPENING\n * 200 EVIDENCE BUNDLES. Both numbers were already recorded before this slice — the\n * promise on the row, the outcome in the bundle — and the only way to set them beside\n * each other was to download a JSON manifest per run and compare by eye.\n *\n * ★ DERIVED BY THE SERVER THROUGH `compareTargets`, exactly as `executedOn` above is\n * derived through `executionSiteOf`, and read by the run record through the same\n * function over the same two summaries. One author, two callers — which is what stops\n * this list and that drawer saying different things about one run.\n *\n * ⚠ ON THE TWO EXECUTION-BEARING MEMBERS AND NOT ON `RunListItemBase`, for the reason\n * written above `executedOn` and above `targetOutcomes`: an Operation Run is N\n * executions across M steps, each with its own promise and its own outcome, so the only\n * honest run-level answer would be a SET.\n *\n * ⚠ NOT `targetOutcomes`, WHICH IS A DIFFERENT QUESTION ON THE SIBLING MEMBER. That one\n * counts how each TARGET of a fan-out ended; this one compares a count taken at plan\n * time against a count taken at run time.\n */\n targetComparison: TargetComparison;\n /** The draft that was exercised, or null once it has been discarded. */\n draftId: string | null;\n /** Denormalized at run time so a discarded draft still leaves a readable row. */\n packageId: string;\n draftName: string;\n /** The change this run was made under, with its assurance. See the `standalone` member. */\n changeRecord: ChangeRecordCitation | null;\n });\n\n/** One target inside an expanded Operation Run step. */\nexport interface RunStepTargetDto {\n id: string;\n executionId: string;\n targetRef: string;\n targetLabel: string;\n status: OperationRunTargetStatus;\n}\n\n/**\n * One step of an expanded Operation Run, with a BOUNDED first page of its targets.\n *\n * `targets.length <= RUN_STEP_TARGET_PAGE` regardless of `targetCount`. Rendering 200\n * targets into a row the reader just opened is how the one run they most needed to\n * understand becomes the one that hangs their browser; the rest are one link away on the\n * run detail page, which is a real destination built for them.\n */\nexport interface RunStepExpansionDto {\n id: string;\n stepKey: string;\n position: number;\n kind: OperationStepKind;\n status: OperationRunStepStatus;\n error: string | null;\n startedAt: string | null;\n finishedAt: string | null;\n /** TRUE count for this step, from the database — not `targets.length`. */\n targetCount: number;\n targets: RunStepTargetDto[];\n}\n\n/** How many targets per step an expanded row renders before deferring to run detail. */\nexport const RUN_STEP_TARGET_PAGE = 5;\n\n/** The expansion of one Operation Run row. */\nexport interface RunExpansionDto {\n runId: string;\n steps: RunStepExpansionDto[];\n /**\n * ═══ A RUN DOES NOT HAVE \"A CONNECTOR\" (docs/46 §3.3) ══════════════════════════════\n *\n * Every DISTINCT connection this run's targets went out under, sorted by name. A set,\n * because an Operation run fans out across targets that may use different connections\n * — docs/45's own test drives three targets across two connectors — and a field that\n * named one when there were two would be worse than one that named none.\n *\n * ─── WHY IT IS HERE AND NOT ON THE ROW ───────────────────────────────────────────────\n *\n * The expansion reads ONE run, so the aggregate is bounded by that run's targets. On\n * the feed it would be bounded by the PAGE's targets — 25 rows × up to 200 targets —\n * which is exactly the cost the feed is built to avoid (docs/46 §6), and it would have\n * to cross `operations → execution` tables to be paid at all. The density decision that\n * follows from it is docs/46 §3.4, recorded in `run-connections.ts`.\n *\n * Empty means no target has resolved a connection yet. It renders as NOTHING, never as\n * an em dash (docs/44 §3.1).\n */\n connections: ConnectionRef[];\n}\n\n/**\n * The answer to `?focus=`, always explicit.\n *\n * A deep link that resolves to nothing must SAY so. Dropping the reader on an unfiltered\n * list is the failure mode: the link looks like it worked, and the row they were sent to\n * see is simply one of the ones they can see, indistinguishable from the rest.\n */\nexport type RunFocusResultDto =\n | {\n found: true;\n /** The keyset cursor of the containing row — the page is anchored to it. */\n rowKey: string;\n origin: RunOrigin;\n /** `operation_run.id` for an Operation Run row, else the execution id. */\n rowId: string;\n /**\n * The execution the link actually named, when it named one. For an `operation` row\n * this is the CHILD inside it, so the expansion can mark which target was meant.\n */\n executionId: string | null;\n }\n | { found: false; query: string };\n\n/** A page of the unified run feed. */\nexport interface RunFeedPageDto {\n data: RunListItemDto[];\n /**\n * Keyset cursor for the next page, or null at the end of the feed. Opaque: it encodes\n * the frontier both branches have been read down to, which is not always the last row.\n */\n nextCursor: string | null;\n /** Present only when the request asked to focus a run; null otherwise. */\n focus: RunFocusResultDto | null;\n}\n\n/** Query for `GET /runs`. */\nexport interface ListRunFeedQuery {\n cursor?: string;\n limit?: number;\n /**\n * Server-side, over BOTH reference kinds (`OPS-####`, `OPR-####`), the action name and\n * the Operation name. A search box that matches only the rows already downloaded is a\n * lie about the size of the answer, so this either searches everything or is not offered.\n */\n search?: string;\n /** Restrict to Operation Runs of one Operation. */\n operationId?: string;\n /** A member of {@link RUN_FEED_STATUSES}; excludes any branch whose vocabulary lacks it. */\n status?: RunFeedStatus;\n /**\n * Whose runs. Absent means {@link DEFAULT_RUN_SCOPE} — every run in the workspace the\n * reader may already see.\n *\n * `mine` resolves to the SIGNED-IN user server-side. There is deliberately no\n * \"actor id\" query parameter: a filter that named an arbitrary user would read as a way\n * to ask about somebody else, and answering it correctly is a different feature with a\n * different permission question.\n */\n scope?: RunScope;\n /**\n * An execution id or a run reference to locate and open. Anchors the page at the\n * containing row and answers {@link RunFeedPageDto.focus} either way.\n */\n focus?: string;\n /**\n * ═══ EVERY RUN UNDER ONE CHANGE RECORD (docs/87 §1) ════════════════════════════════\n *\n * The POPULATION an auditor samples. docs/84 made every gated run carry a change\n * reference; this is the only way to ask for them, and what it returns has to be the\n * whole set or it is worse than nothing.\n *\n * ★ EXACT, AND DELIBERATELY NOT {@link ListRunFeedQuery.search}. `search` is fuzzy and\n * partial — `CHG003` matching `CHG0031425` is useful in a search box and WRONG in an\n * audit answer, where the question is *which runs* and not *which rows mention this*.\n * Teaching `search` a second meaning would leave two ways to ask one question with\n * different semantics (charter §4.2), and the one that silently returns a partial\n * population is the one an auditor would trust.\n *\n * ★ MATCHED HOWEVER IT WAS TYPED. An operator who typed `chg0031425` and one who typed\n * `CHG0031425` named the same change, so matching is case-insensitive — but the stored\n * reference is never re-cased (see `ChangeRecordRef.reference`). A filter that dropped a\n * run over capitalisation would return a population wrong in the direction nobody checks.\n *\n * ★ THE REFERENCE ALONE, AND NOT A `{type, reference}` PAIR. Argued from what a reader\n * can actually supply: an auditor asks \"show me every run under CHG0031425\" and clicks\n * the reference they can see. The TYPE is a closed vocabulary that renders as a label\n * (\"Change request\"), never as a token anybody could type into a URL — so requiring it\n * would make this filter reachable only by clicking, and would split one quoted\n * identifier into two populations for a distinction the asker never made. The row still\n * states its own type, so nothing is hidden by matching on the reference.\n */\n changeRecordReference?: string;\n}\n","// ═══ THE EVIDENCE PACK — ONE OPERATION, PROVABLE (docs/119) ═══════════════════════════\n//\n// The file an auditor is handed for ONE procedure: what it does, who approved it, and every\n// time it ran inside a window. It gathers no new facts — every field below is a column this\n// product already records — and it is served, never stored (docs/119 §8).\n//\n// ★ EVERY SHAPE HERE IS DECLARED, AND THAT IS THE DETERMINISM ARGUMENT. The pack's SHA-256 is\n// returned beside it and written to the audit trail, so the same window exported twice must be\n// the same bytes apart from `generatedAt` and `generatedBy`. A value spread out of a jsonb\n// column cannot promise that — jsonb reorders object keys — so nothing here is typed as an\n// open record: a parameter is a `{ name, value }` ROW, sorted, and every array says what it is\n// sorted by.\n//\n// ⛔ AND THE DIGEST IS NOT A FIELD. A file cannot contain its own hash; the digest travels in\n// {@link EVIDENCE_DIGEST_HEADER} and in the audit row, never inside the document it describes.\n\nimport type { RequiredPermission } from \"./catalog\";\nimport type { ChangeRecordRef } from \"./change-control\";\nimport type { ApprovalDecisionKind, ApprovalStatus, RunTriggerKind } from \"./enums\";\nimport type { CheckLevel } from \"./execution\";\nimport type { ApprovalSubjectKind } from \"./governance\";\nimport type {\n DryRunOutcome,\n OperationLifecycle,\n OperationRunStatus,\n OperationRunStepStatus,\n OperationRunTargetStatus,\n OperationStepKind,\n OperationVerificationLifecycle,\n OperationVerificationResult,\n OperationVerificationTrigger,\n StepFailurePolicy,\n} from \"./operations\";\nimport type { EvidencePackSchemaVersion } from \"./wire-identity\";\n\n/**\n * The response header that carries the pack's digest, as `sha256:<lowercase hex>` over the\n * EXACT bytes of the body.\n *\n * ⚠ THE BROWSER CANNOT READ IT UNLESS THE API EXPOSES IT. The console and the API are\n * different origins, and a custom response header is invisible to cross-origin script unless\n * `Access-Control-Expose-Headers` names it — `platform/http/cors.ts` does, from this constant.\n * Every local test passes without that, because none of them is a browser.\n */\nexport const EVIDENCE_DIGEST_HEADER = \"X-Evidence-Digest\";\n\n/**\n * The audit action an export writes. Declared once because three places spell it: the\n * operations module writes it, the audit read curates it, and the timeline words it.\n */\nexport const EVIDENCE_EXPORTED_AUDIT_ACTION = \"operation.evidence_exported\";\n\n/**\n * The downloaded file's name — `<operationKey>-evidence-<from>-<to>.json`, the instants\n * written compactly (`20260701T000000Z`) because a colon is not a legal filename character on\n * every system an auditor's archive lives on.\n *\n * ONE AUTHOR: the API names the file in `Content-Disposition`, and the console names the\n * download it saves. The console cannot read `Content-Disposition` cross-origin, so without\n * this the two would be two spellings of one name.\n */\nexport function evidencePackFilename(operationKey: string, from: string, to: string): string {\n return `${operationKey}-evidence-${compactInstant(from)}-${compactInstant(to)}.json`;\n}\n\nfunction compactInstant(iso: string): string {\n return iso.replace(/\\.\\d+(?=Z|[+-]\\d{2}:?\\d{2}$)/, \"\").replace(/[-:]/g, \"\");\n}\n\n/**\n * A person the pack names. The id is the product's own, and the email is what an auditor can\n * match to a human. `null` — never invented — when the person has no email address on record,\n * or when the id no longer resolves to a user in this workspace.\n *\n * ⚠ THOSE ARE TWO FACTS AND THIS FIELD CANNOT TELL THEM APART (docs/125). Until docs/125 the\n * first could not happen: an account with no address was given `<subject>@no-email.local`,\n * which put an OIDC subject in this document. Telling the two apart needs a field of its own\n * and a new `schemaVersion`; it is not done here.\n */\nexport interface EvidencePerson {\n userId: string;\n email: string | null;\n}\n\n/** The Operation as it stands at export time — the one part of the pack that is not history. */\nexport interface EvidenceOperation {\n id: string;\n key: string;\n name: string;\n description: string | null;\n owner: EvidencePerson;\n lifecycle: OperationLifecycle;\n createdAt: string;\n}\n\n/** One authored parameter. A literal, or a `{ from: \"<stepKey>.outputs.<name>\" }` binding. */\nexport interface EvidenceParameter {\n name: string;\n /** Canonical JSON: any object inside has its keys in code-point order. */\n value: unknown;\n}\n\n/** The pinned action of a step, and what the catalog can still say about it. */\nexport interface EvidenceStepAction {\n actionVersionId: string;\n actionDefinitionId: string | null;\n /** Null when the catalog can no longer resolve the pinned version — never guessed. */\n key: string | null;\n name: string | null;\n version: string | null;\n}\n\nexport interface EvidenceTargetSelector {\n parameter: string;\n /** Authored order, as stored — jsonb keeps array order. */\n connectionScopeIds: string[];\n mode: \"explicit\" | \"query\";\n explicit: { resourceIds: string[] } | null;\n query: {\n resourceGroups: string[];\n /** Sorted by `key`. */\n tags: { key: string; value: string }[];\n namePrefix: string | null;\n excludeResourceIds: string[];\n } | null;\n limit: number | null;\n}\n\nexport type EvidenceStep =\n | {\n id: string;\n stepKey: string;\n position: number;\n kind: \"action\";\n action: EvidenceStepAction;\n connectionScopeId: string;\n /** Sorted by `name`. */\n parameters: EvidenceParameter[];\n dryRun: boolean;\n onFailure: StepFailurePolicy;\n targetSelector: EvidenceTargetSelector | null;\n }\n | {\n id: string;\n stepKey: string;\n position: number;\n kind: \"wait\";\n durationSeconds: number;\n };\n\n/**\n * One verification check, reduced to what it FOUND.\n *\n * ⛔ NO `detail` AND NO `checkedIdentity` (docs/119 §5). A `permissions_held` check's detail\n * sentence names the connector's principal — \"Checked identity: … (object …, client …)\" — and\n * the pack must never carry a client id. The detail is advice about what to do next; the\n * verdict is the code, the level and the title, and those never name the identity.\n */\nexport interface EvidenceVerificationCheck {\n code: string;\n key: string | null;\n level: CheckLevel;\n title: string;\n scopeLabel: string | null;\n providerScopeId: string | null;\n missingPermissions: RequiredPermission[];\n targetRef: string | null;\n targetLabel: string | null;\n executionId: string | null;\n executionReference: string | null;\n dryRunOutcome: DryRunOutcome | null;\n}\n\n/** One verification attempt of a version, started inside the window. */\nexport interface EvidenceVerification {\n id: string;\n lifecycle: OperationVerificationLifecycle;\n /** Null until the attempt finished — an unfinished one concluded nothing. */\n result: OperationVerificationResult | null;\n triggeredBy: OperationVerificationTrigger;\n dryRun: boolean;\n startedAt: string;\n finishedAt: string | null;\n /** In the order they resolved, as stored. */\n checks: EvidenceVerificationCheck[];\n}\n\n/**\n * ONE VERSION — THE DEFINITION A RUN EXECUTED, not today's. Every run pins its version, so the\n * pack carries each version a run in it executed, plus any verified inside the window.\n */\nexport interface EvidenceVersion {\n id: string;\n version: number;\n publishedAt: string | null;\n createdBy: EvidencePerson;\n createdAt: string;\n /** Sorted by `position`. */\n steps: EvidenceStep[];\n /** Attempts started inside the window, sorted by `startedAt` then `id`. */\n verifications: EvidenceVerification[];\n}\n\nexport interface EvidenceApprovalDecision {\n id: string;\n decision: ApprovalDecisionKind;\n decidedBy: EvidencePerson;\n decidedAt: string;\n comment: string | null;\n}\n\n/**\n * WHO ALLOWED IT. An approval reaches a run two ways, and the pack records both where they\n * happened: a gated fan-out step opens ONE approval whose subject is the run step, and a step\n * that acted on one target is gated by its child execution's own approval.\n */\nexport interface EvidenceApproval {\n id: string;\n subject: ApprovalSubjectKind;\n status: ApprovalStatus;\n /** The group asked, as it was named then; null means any approver. */\n approverGroup: { id: string; name: string } | null;\n requiredApprovals: number;\n requestedBy: EvidencePerson;\n requestedAt: string;\n /** Sorted by `decidedAt` then `id`. */\n decisions: EvidenceApprovalDecision[];\n}\n\nexport interface EvidenceRunTarget {\n id: string;\n targetRef: string;\n targetLabel: string;\n status: OperationRunTargetStatus;\n executionId: string;\n /** The child execution's own gate, when it had one. */\n approval: EvidenceApproval | null;\n}\n\nexport interface EvidenceRunStep {\n id: string;\n stepId: string;\n stepKey: string;\n position: number;\n kind: OperationStepKind;\n status: OperationRunStepStatus;\n startedAt: string | null;\n finishedAt: string | null;\n error: string | null;\n /** Sorted by `name`. */\n outputs: EvidenceParameter[];\n /** The step's own gate — a fan-out approved once for every target. */\n approval: EvidenceApproval | null;\n /** Sorted by `targetRef` then `id`. */\n targets: EvidenceRunTarget[];\n}\n\nexport interface EvidenceRun {\n id: string;\n reference: string;\n operationVersionId: string;\n version: number;\n /** The real status. A run still in flight says so and has no `finishedAt`. */\n status: OperationRunStatus;\n trigger: {\n kind: RunTriggerKind;\n scheduleId: string | null;\n scheduleName: string | null;\n autoApprove: boolean;\n };\n dryRun: boolean;\n triggeredBy: EvidencePerson;\n /**\n * WHY — the record this run named, or `null` when it named none. Both halves or neither, as\n * the database stores them; null is a real answer and is never written as an empty string.\n */\n changeRecord: ChangeRecordRef | null;\n createdAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n /** Sorted by `position`. */\n steps: EvidenceRunStep[];\n}\n\n/**\n * ⛔ A CAP THAT BITES SAYS SO. `truncated` is true exactly when `runsIncluded < runsInRange`,\n * and a reader who sees it knows the pack is a prefix of the window rather than all of it.\n */\nexport interface EvidenceCompleteness {\n runsIncluded: number;\n runsInRange: number;\n truncated: boolean;\n}\n\n/**\n * The document. `covers.from`/`covers.to` are a HALF-OPEN window over when each run was\n * CREATED — `from` inclusive, `to` exclusive — so two adjacent windows never share a run.\n */\nexport interface EvidencePackDto {\n schemaVersion: EvidencePackSchemaVersion;\n generatedAt: string;\n generatedBy: EvidencePerson;\n workspace: { tenantId: string; name: string };\n covers: { operationId: string; operationKey: string; from: string; to: string };\n completeness: EvidenceCompleteness;\n operation: EvidenceOperation;\n /** Sorted by `version`. */\n versions: EvidenceVersion[];\n /** Sorted by `startedAt` (a run not yet started last), then `reference`, then `id`. */\n runs: EvidenceRun[];\n}\n\n/**\n * What an export's audit row records, curated onto the timeline's read (docs/119 §8, history):\n * the window, how much of it the file held, and the digest a holder checks their file against.\n */\nexport interface EvidenceExportAuditRecord {\n from: string;\n to: string;\n runsIncluded: number;\n runsInRange: number;\n truncated: boolean;\n digest: string;\n}\n","/**\n * WHAT ACTUALLY HAPPENED to a package's declared egress allowlist on the substrate that ran it\n * (slice 6b-II).\n *\n * The allowlist was validated at import, stored, shown to the approver and carried into the work\n * item — and on Container Apps Jobs it was then ignored, because enforcing it there is not\n * possible in the way a NET_ADMIN-capable substrate would enforce it. Shipping a security field that means\n * different things on different substrates while SAYING the same thing on every screen is the\n * catalog-that-lies failure (docs/31 §2) in the security dimension, so the mode that applied is\n * recorded and disclosed everywhere the allowlist itself is.\n */\n\n/**\n * The egress modes Opera can actually deliver. Array-first (charter §4.2): declared ONCE, here,\n * with the union derived — and every subset mapping below is a `Record` over the WHOLE\n * vocabulary, so a fourth mode forces a decision at each site instead of silently defaulting to\n * the reassuring answer.\n *\n * - `denied` — the package declares no network, so Opera provisions no egress for it.\n * Whether anything then STOPS it from reaching out is the substrate's\n * business, not this field's: on a substrate that can drop the traffic the run has an empty network\n * namespace and there is genuinely no route, while a container substrate has\n * ordinary outbound whether or not Opera configured anything. That difference\n * is carried by {@link EgressDisclosureDto.substrateBlocksUndeclared}, never\n * folded into the mode, because folding it in is how one word comes to mean\n * two things.\n * - `enforced` — the proxy is the SOLE route out and bypass is impossible: the sandbox runs\n * in a network namespace whose only route is the proxy, with a FORWARD DROP\n * on the veth, so a package that ignores HTTPS_PROXY and dials an IP directly\n * cannot be routed anywhere. This needs NET_ADMIN.\n * - `cooperative` — the proxy is configured for the package process and refuses everything off\n * the allowlist, but the package shares a network namespace with it and a\n * package that deliberately ignores the proxy environment still reaches the\n * internet. It stops accidents — a wrong endpoint, a dependency phoning home,\n * a copy-pasted URL — and does not stop a determined author.\n *\n * There is deliberately no member that reads stronger than it is. \"restricted\", \"sandboxed\" and\n * \"contained\" were all rejected as names for the third member for exactly that reason: a control\n * that is weaker than it appears is worse than no control, because someone will rely on it.\n */\n\nimport { BRAND_SHORT_NAME } from \"./brand\";\n\nexport const EGRESS_MODES = [\"denied\", \"enforced\", \"cooperative\"] as const;\nexport type EgressMode = (typeof EGRESS_MODES)[number];\n\n/** The short label a badge or a table cell gets. Never abbreviated into a claim. */\nexport const EGRESS_MODE_LABEL = {\n denied: \"No network\",\n enforced: \"Enforced\",\n cooperative: \"Configured, not enforced\",\n} as const satisfies Record<EgressMode, string>;\n\n/**\n * Whether a package that IGNORES the egress configuration is stopped by the mode itself.\n *\n * Only `enforced` is a boundary. `denied` is `false` here because the mode alone does not stop\n * anything — it records that Opera provisioned nothing, and on a substrate with ordinary\n * outbound that is not the same as unreachable. `substrateBlocksUndeclared` is the fact that\n * completes it.\n */\nexport const EGRESS_MODE_STOPS_BYPASS = {\n denied: false,\n enforced: true,\n cooperative: false,\n} as const satisfies Record<EgressMode, boolean>;\n\n/**\n * The egress that applied to one run, as an auditor reading an evidence bundle needs it: the\n * mode, the effective allowlist it applied to, and what the substrate itself was worth.\n *\n * The same package gets different modes on different substrates. A bundle that recorded only the\n * allowlist would be indistinguishable between a run that could not have reached anything else\n * and a run that merely was not asked to — which is not evidence.\n */\nexport interface EgressDisclosureDto {\n mode: EgressMode;\n /**\n * The effective allowlist: the manifest's `egressAllowlist` union the hosts of the credential\n * the run was entitled to. Empty when the mode is `denied`.\n */\n allowlist: string[];\n /**\n * Whether the SUBSTRATE stops traffic the package was never configured to send — a fact about\n * the isolation, not about the mode. An empty netns does; a Container Apps replica and\n * the trusted subprocess harness (which runs on the worker's own network) do not.\n *\n * Carried separately because it is the difference between \"could not\" and \"was not asked to\",\n * and every honest sentence about `denied` needs it.\n */\n substrateBlocksUndeclared: boolean;\n}\n\n/**\n * Whether this run's egress was a REAL boundary — something a package could not have got around\n * — as opposed to a configuration it was expected to honour.\n *\n * THE one predicate every surface tones itself on, so no screen can decide for itself that\n * `cooperative` looks reassuring enough. It needs both facts: `enforced` is a boundary by the\n * mode alone, and `denied` is one only where the substrate has no route out at all.\n */\nexport function egressWasABoundary(disclosure: EgressDisclosureDto): boolean {\n return (\n EGRESS_MODE_STOPS_BYPASS[disclosure.mode] ||\n (disclosure.mode === \"denied\" && disclosure.substrateBlocksUndeclared)\n );\n}\n\n/**\n * The one-clause headline: what the reader must know before anything else. Short enough to sit\n * beside a list of hosts without becoming a paragraph, and exhaustive over the vocabulary so a\n * fourth mode cannot be worded here in a way that contradicts the sentence below it.\n */\nexport function egressDisclosureHeadline(disclosure: EgressDisclosureDto): string {\n switch (disclosure.mode) {\n case \"denied\":\n return disclosure.substrateBlocksUndeclared\n ? \"No network — nothing outside was reachable.\"\n : \"No network was configured, and this substrate does not block outbound traffic.\";\n case \"enforced\":\n return \"Only these hosts were reachable — nothing else could be.\";\n case \"cooperative\":\n return \"Configured to reach only these hosts — not prevented from reaching elsewhere.\";\n }\n}\n\n/**\n * THE sentence a human reads, in full. Written once here so the action detail, the approver's\n * plan, the run timeline and the evidence bundle cannot describe the same control differently —\n * and so no surface can quietly upgrade `cooperative` into a claim of enforcement.\n *\n * The `cooperative` wording is the non-negotiable part of this slice. It says what the control\n * actually is, in the approver's language: it guards against a package reaching somewhere by\n * mistake, not against one that sets out to. An approver deciding on a high-risk action is\n * exactly the reader who must not be misled, which is also why this is a sentence on the page\n * and never a tooltip.\n */\nexport function egressDisclosureSentence(disclosure: EgressDisclosureDto): string {\n const hosts = disclosure.allowlist.join(\", \");\n switch (disclosure.mode) {\n case \"denied\":\n return disclosure.substrateBlocksUndeclared\n ? \"This package declares no outbound network. It runs with no route out at all, so \" +\n \"nothing outside is reachable.\"\n : `This package declares no outbound network, so ${BRAND_SHORT_NAME} configures no proxy for it. ` +\n \"The substrate it runs on does not itself block outbound traffic, so a package \" +\n \"that reached out anyway would not be stopped.\";\n case \"enforced\":\n return (\n `The package can reach only ${hosts}. The proxy enforcing that is the run's only ` +\n \"route out, so a package that ignored it could not reach anywhere else either.\"\n );\n case \"cooperative\":\n return (\n `The package process is configured to reach only ${hosts}. This guards against the ` +\n \"package reaching somewhere by mistake — a wrong endpoint, a dependency phoning home \" +\n \"— and not against a package that sets out to go elsewhere: this substrate cannot \" +\n \"stop one that ignores the configuration.\"\n );\n }\n}\n","/** JSON values accepted by the package execution protocol. */\nexport type PackageJsonPrimitive = string | number | boolean | null;\nexport type PackageJsonValue =\n | PackageJsonPrimitive\n | PackageJsonObject\n | PackageJsonValue[];\nexport interface PackageJsonObject {\n [key: string]: PackageJsonValue;\n}\n\n/**\n * THE THREE PHASES of one execution, array-first (charter §4.2).\n *\n * The name is `PackagePhase` for history — the package protocol (docs/22) was the first wire\n * format to carry them — but the concept is the connector lifecycle, and the private-runner\n * channel (docs/49) carries the SAME three. It deliberately does NOT declare a\n * `RunnerStepPhase` alias: a second name for one closed set is the defect charter §4.2 names,\n * not a readability improvement. Renaming this one repo-wide is a cleanup of its own.\n */\nexport const PACKAGE_PHASES = [\"validate\", \"run\", \"rollback\"] as const;\nexport type PackagePhase = (typeof PACKAGE_PHASES)[number];\nexport type PackageResultStatus = \"succeeded\" | \"failed\" | \"cancelled\";\n\n/** Non-secret execution metadata written to /runveric/input/context.json. */\nexport interface PackageExecutionContext {\n protocolVersion: PackageExecutionProtocolVersion;\n executionId: string;\n phase: PackagePhase;\n provider: string;\n providerScopeId: string;\n dryRun: boolean;\n}\n\n/** A structured stdout event prefixed with `RUNVERIC_EVENT `. */\nexport interface PackageRuntimeEvent {\n level: \"info\" | \"warn\" | \"error\" | \"success\";\n message: string;\n data?: PackageJsonObject;\n}\n\nexport interface PackageResultCheck {\n status: \"passed\" | \"warning\" | \"failed\";\n message: string;\n data?: PackageJsonObject;\n}\n\nexport interface PackageResultError {\n code: string;\n message: string;\n retryable?: boolean;\n}\n\n/** Frozen structured result written to /runveric/output/result.json. */\nexport interface PackageResultV1 {\n protocolVersion: PackageResultProtocolVersion;\n status: PackageResultStatus;\n message: string;\n checks?: PackageResultCheck[];\n outputs?: PackageJsonObject;\n rollbackCapture?: PackageJsonObject;\n error?: PackageResultError | null;\n}\n\n/** Serializable input passed through PackagesFacade for one package phase. */\nexport interface PackageRunPhaseInput {\n actionVersionId: string;\n executionId: string;\n phase: PackagePhase;\n parameters: PackageJsonObject;\n dryRun: boolean;\n scope: ResolvedConnectionScopeDto;\n priorResult?: PackageJsonObject;\n /**\n * WHERE THIS RUN EXECUTES (docs/60 §3.3) — which decides the isolation that confines it.\n *\n * ★ IT TRAVELS FROM THE ENGINE, WHICH ALREADY COMPUTED IT. `run-execution.handler.ts` derives\n * `RunExecutionSiteDto` for docs/56 and writes it onto the execution row; this is that same\n * value passed down rather than a second derivation, for the reason docs/58 §3.2 gives —\n * a second answer to \"where did this run go\" is how a plan and a run come to disagree.\n *\n * ⚠ REQUIRED. The isolation a package runs under is a security decision, and the value an\n * omitted field would fall into (`hosted`) is one that silently sends a pool-routed package to\n * a substrate that cannot reach the estate its run was bound to.\n *\n * It carries the POOL as well as the site, because the adapter that dispatches to a runner\n * needs one and a second field holding it could disagree with the first.\n */\n placement: RunPlacementRef;\n}\nimport type {\n PackageExecutionProtocolVersion,\n PackageResultProtocolVersion,\n} from \"./wire-identity\";\nimport type { ResolvedConnectionScopeDto } from \"./connections\";\nimport type { RunPlacementRef } from \"./run-placement\";\n\n/**\n * ═══ WHAT A PACKAGE RUNTIME CONTAINER IS GIVEN, NAMED ONCE (docs/60 §3.4) ════════════════\n *\n * The variable NAMES `bootstrap.ps1` reads on start-up — the only contract between Opera and\n * the container that executes customer code, wherever that container is started.\n *\n * ★ IT LIVES IN CONTRACTS BECAUSE TWO SUBSTRATES NOW COMPOSE IT AND NEITHER MAY REACH THE\n * OTHER. The Container Apps adapter builds this list and hands it to ARM; the private-runner\n * DISPATCHER builds the same list and hands it to `docker run`. The dispatcher's bundle is\n * forbidden from importing anything under `modules/` (`build-runner-bundles.mjs`), so a shared\n * constant in the packages module is not reachable from it — and two hand-written lists that\n * agree today are exactly the drift charter §4.2 is about. docs/60 §3.4's claim that a package\n * container \"receives the same environment\" is therefore true by construction rather than by\n * two files being kept in step.\n *\n * `package-runtime-contract-parity.spec.ts` reads `bootstrap.ps1` from disk and fails if the\n * script stops reading what this declares.\n */\nexport const PACKAGE_CONTAINER_ENV = {\n /** The control-plane origin the container redeems its work item at and reports to. */\n callbackBaseUrl: \"OPERA_CALLBACK_BASE_URL\",\n executionId: \"RUNVERIC_EXECUTION_ID\",\n /** Single-use; spent on the first redemption. Never copied into the package's own env. */\n runToken: \"OPERA_RUN_TOKEN\",\n /** What the bytes it fetched must hash to. Travels beside the work item, never inside it. */\n contentDigest: \"RUNVERIC_CONTENT_DIGEST\",\n /** Which runtime image this is, recorded on the run. */\n runnerImageDigest: \"OPERA_RUNNER_IMAGE_DIGEST\",\n /** Where the PACKAGE's outbound traffic is pointed. Absent when it declared no network. */\n egressProxyUrl: \"RUNVERIC_EGRESS_PROXY_URL\",\n /** The runner-only control channel. Never copied into the package's own env. */\n egressControlUrl: \"RUNVERIC_EGRESS_CONTROL_URL\",\n egressControlToken: \"RUNVERIC_EGRESS_CONTROL_TOKEN\",\n} as const;\n\n/**\n * ═══ HOW THE PACKAGE RUNTIME IMAGE STARTS — ONE ENTRYPOINT, EVERY SUBSTRATE (docs/129 §7 J3) ═══\n *\n * The launcher, never `pwsh … bootstrap.ps1`. `runToken` and `egressControlToken` above arrive in\n * the container's environment — the one channel Container Apps, Docker and Kubernetes all offer —\n * and a package runs as the same user as PID 1, so it can read PID 1's INITIAL environment through\n * `/proc/1/environ` (measured in the real job, docs/129 §7 I1). The launcher moves those two onto a\n * pipe on the bootstrap's standard input and `exec`s the bootstrap without them. Anything that\n * starts the bootstrap another way starts it with the secrets where the package can read them.\n *\n * The image's `ENTRYPOINT` is held to this, and the Container Apps adapter names it in every start\n * body (ACA's `command` REPLACES the entrypoint). The Docker and Kubernetes runners name no command,\n * so they run the image's entrypoint — this. No arguments: the launcher refuses any.\n */\nexport const PACKAGE_RUNNER_ENTRYPOINT = [\"/opt/runveric/runner/launch.sh\"] as const;\n\n/**\n * ═══ THE HEADER A RUN TOKEN ARRIVES IN — DELIBERATELY NOT `Authorization` ══════════════════\n *\n * A browser session, an API client and every other caller in this system present their identity\n * in `Authorization`. Reading the run token from a different header is what makes \"an ordinary\n * session cannot call these routes\" structural rather than conditional: a session does not fail\n * this check, it never reaches it.\n *\n * ★ DECLARED HERE, AND ONCE (docs/128 §18.4). Two controllers read it — the package run callback\n * and the engine run callback — and the action runtime sends it from an image built outside the\n * api. It used to be an export of the package controller, which the runtime cannot import.\n */\nexport const RUN_TOKEN_HEADER = \"x-runveric-run-token\";\n\n/**\n * ONE sentence for every way a run token can fail: unknown, expired, already redeemed, or issued\n * for something other than the path names. They are deliberately indistinguishable — a caller\n * holding a token learns only whether it works right now, and a caller holding someone else's\n * learns nothing at all, least of all which ids exist. Both callback controllers answer with it.\n */\nexport const RUN_TOKEN_REJECTED = \"This run token is not valid for this execution.\";\n","/**\n * ═══ WHAT A RUNNER MEASURED ABOUT ITS OWN SUBSTRATE (docs/70 §3.2) ═════════════════════\n *\n * ★ THE TABLE BECOMES A CEILING AND THE RUNNER REPORTS WHAT IT ACHIEVED. Until this file,\n * \"does the substrate stop traffic the package was never configured to send\" was answered\n * entirely by {@link ISOLATION_BLOCKS_UNDECLARED_EGRESS}, keyed by the isolation. That was\n * correct while `runner` meant exactly one thing — a Docker host, where the answer is\n * TOPOLOGICAL: `container-package-sandbox.ts` puts the package on a `--internal` network, and\n * such a network HAS NO GATEWAY, so there is no route for it to ignore the proxy to. Nothing\n * about that is a configuration anybody could get wrong.\n *\n * A Kubernetes pod ALWAYS has a route. Only a NetworkPolicy removes it, and a NetworkPolicy is\n * not self-verifying. Measured on two `kind` clusters differing only in CNI (2026-09-01):\n *\n * kubectl get networkpolicies — returns the policy on BOTH\n * kubectl describe — prints the full spec on BOTH, with no hint either way\n * a pod the policy selects — BLOCKED on Calico, REACHED on kindnet\n *\n * So the object being accepted proves nothing at all, and on EKS with the VPC CNI enforcement\n * is off by default. A runner that applied a policy, saw it accepted and reported confinement\n * would be claiming a boundary it had not achieved — which this product has shipped once\n * already (docs/54's retired gVisor adapter, which promised runs it could not start).\n *\n * ⚠ THE TABLE'S OWN COMMENT PREDICTED THIS MOMENT: *\"the next confining substrate would inherit\n * `false` silently instead of being asked.\"* It is being asked. What it must not do is inherit\n * `true` silently, which is the same defect pointing the other way and the dangerous direction.\n */\n\n/**\n * ═══ THE PROBE'S WIRE WORDS, DECLARED ONCE (charter §4.2) ══════════════════════════════\n *\n * ★ TWO PROCESSES THAT SHARE NO CODE SAY THESE, WHICH IS WHY THEY ARE HERE AND NOT IN EITHER.\n * The STEP image runs the probe and prints the line; the DISPATCHER reads it and decides a\n * finding. They are separate bundles on purpose — `runner-ephemeral-by-construction.spec.ts`\n * fails the build if anything the dispatcher reaches can touch the connectors, and the step\n * entrypoint reaches all of them — so the dispatcher cannot import the step's constant. Typed\n * on both sides, they would be a matched pair of literals that drift, which is docs/55's defect\n * exactly: a rule one of its readers cannot import is a rule that gets retyped.\n */\n\nimport { BRAND_SHORT_NAME } from \"./brand\";\n\nexport const EGRESS_PROBE_PREFIX = \"runveric.egress-probe\";\nexport const EGRESS_PROBE_REACHED = \"REACHED\";\n/** The prefix of a blocked answer; what follows the colon is the reason and varies. */\nexport const EGRESS_PROBE_BLOCKED = \"BLOCKED\";\n\n/**\n * Five seconds. A confined pod's connect does not fail fast — a NetworkPolicy DROPS rather than\n * rejects, so the honest signal is a timeout, and the budget must be long enough that a merely\n * slow cluster is not read as a confined one. Measured against Calico on `kind` (2026-09-01):\n * the unconfined control connected in well under a second, four times out of four.\n */\nexport const EGRESS_PROBE_TIMEOUT_MS = 5_000;\n\n/**\n * ═══ THE GATE'S WIRE WORD — A DIFFERENT QUESTION FROM THE PROBE'S (docs/71 §3.1) ════════\n *\n * ★ IT IS NOT `EGRESS_PROBE_PREFIX` WITH A NEW MEANING, AND THE SEPARATION IS THE POINT. The\n * probe answers *\"did THIS pod reach THAT address\"* and is deliberately forbidden from ever\n * saying `confined` — only the code that ran BOTH halves may read a finding out of a pair.\n * The gate answers a decision for ONE pod: *may the package container in this pod start.*\n * One word for both would let a reader of either line believe it had the other's authority.\n *\n * ⚠ AND THE DECISION DOES NOT TRAVEL ON THIS LINE. It travels as the init container's EXIT\n * CODE, which is the only signal that can stop the package container from being started at\n * all — the kubelet reads it before it creates the next container, and nothing in this design\n * gets a vote after that. This prefix exists so the dispatcher can put the REASON into the\n * failed run's message; the refusal already happened without it.\n */\nexport const EGRESS_GATE_PREFIX = \"runveric.egress-gate\";\n/** The gate's two answers. `OPEN` is the failure: a route existed that must not have. */\nexport const EGRESS_GATE_OPEN = \"OPEN\";\nexport const EGRESS_GATE_SHUT = \"SHUT\";\n\n/**\n * WHERE A RUNNER RUNS ITS WORK. Two, because there are two install paths and they hold\n * different privileges — not because a Kubernetes runner is a Docker runner with a flag.\n *\n * `docker` mounts the host's container socket, which is root-equivalent on that host; that is\n * unavoidable for a runner that starts step CONTAINERS and every comparable product is in the\n * same position. `kubernetes` mounts nothing, holds no socket, and reaches its cluster through\n * a namespaced RBAC Role — which is the whole reason this vocabulary exists.\n */\nexport const RUNNER_SUBSTRATES = [\"docker\", \"kubernetes\"] as const;\nexport type RunnerSubstrate = (typeof RUNNER_SUBSTRATES)[number];\n\n/** What a substrate is CALLED on a screen. Declared here so no surface titles it twice. */\nexport const RUNNER_SUBSTRATE_LABEL = {\n docker: \"Docker\",\n kubernetes: \"Kubernetes\",\n} as const satisfies Record<RunnerSubstrate, string>;\n\n/**\n * ═══ WHAT THE RUNNER ESTABLISHED, AND `unproven` IS THE MEMBER THAT MATTERS ═════════════\n *\n * The finding a runner reports about undeclared egress on its own substrate.\n *\n * - `confined` — it established that undeclared egress is STOPPED.\n * - `unconfined` — it established that undeclared egress is NOT stopped.\n * - `unproven` — it established NEITHER. The experiment did not run, or ran and said\n * nothing, so there is no finding here at all.\n *\n * ★ THE THIRD MEMBER IS THE WHOLE DISCIPLINE, AND WITHOUT IT THIS VOCABULARY WOULD BE A TRAP.\n * A boolean has room for \"blocked\" and \"not blocked\" and no room for \"the measurement failed\".\n * With only two members, a probe that could never have reached its target — no route out at\n * all, an image that would not pull, a target that was down — reports exactly what a correctly\n * confined pod reports, and the reassuring answer wins by accident. docs/60 established the\n * method that avoids this: a POSITIVE CONTROL. Prove the probe reaches its target when nothing\n * stops it, and only then does its failure under policy mean anything. `unproven` is where a\n * failed positive control lands, and it is why {@link CONFINEMENT_FINDING_BLOCKS_EGRESS} can be\n * a total function over this vocabulary rather than a boolean with a comment beside it.\n *\n * ⚠ `unproven` IS NOT A LOADING STATE. It is a runner's final answer for this installation\n * until it restarts and measures again. A screen that rendered it as \"checking…\" would be\n * inventing a transition that never happens.\n */\nexport const CONFINEMENT_FINDINGS = [\"confined\", \"unconfined\", \"unproven\"] as const;\nexport type ConfinementFinding = (typeof CONFINEMENT_FINDINGS)[number];\n\n/**\n * Whether a finding amounts to \"the substrate stops undeclared egress\".\n *\n * ★ `unproven` ANSWERS `false`, AND IT IS NOT THE SAME `false` AS `unconfined`. Both mean the\n * product may not claim confinement, which is the only thing this table decides. They differ in\n * what a person should DO about it, which is why they are separate members and why\n * {@link CONFINEMENT_FINDING_SENTENCE} says two different things: `unconfined` is a cluster\n * that answered, and `unproven` is a cluster that could not be asked.\n *\n * A `Record` over the whole vocabulary, so a fourth finding is a compile error here rather\n * than a silent `undefined` that reads as falsy — which is the reassuring answer arriving by\n * omission, the exact failure this file exists to prevent.\n */\nexport const CONFINEMENT_FINDING_BLOCKS_EGRESS = {\n confined: true,\n unconfined: false,\n unproven: false,\n} as const satisfies Record<ConfinementFinding, boolean>;\n\n/**\n * ═══ THE CEILING FOR THE ISOLATION A RUNNER EXECUTES UNDER — DECLARED HERE, DERIVED THERE ══\n *\n * The most a runner may ever claim about undeclared egress. `true`, and it is earned by\n * `container-package-sandbox.ts`: a `--internal` network HAS NO GATEWAY, so a container\n * attached to it has no route off it at all.\n *\n * ★ IT LIVES IN THIS LEAF RATHER THAN ONLY IN THE ISOLATION TABLE, AND THAT IS A BOUNDARY FACT\n * RATHER THAN A PREFERENCE. `ISOLATION_BLOCKS_UNDECLARED_EGRESS` is in the packages module's\n * DOMAIN, and `.dependency-cruiser.cjs` §2.1 lets one module import another only through its\n * `*.public.ts`. Two modules now need this number — runners, to refuse a registration that\n * claims more than the isolation permits, and execution, to apply the conjunction at plan time\n * — and neither may read that table. Retyping it in each would be three copies of one fact,\n * which is the defect docs/62 was opened for.\n *\n * ⚠ SO THE TABLE DERIVES FROM THIS, NOT THE OTHER WAY ROUND. `package-runtime.port.ts` spells\n * its `runner` member as this constant, keeping its `satisfies Record<SandboxIsolation,\n * boolean>` intact and keeping ONE author for the answer. Changing the claim means changing it\n * here, and every reader moves together.\n */\nexport const RUNNER_ISOLATION_BLOCKS_UNDECLARED_EGRESS = true;\n\n/**\n * What a runner reports about its own confinement at registration.\n *\n * ★ REQUIRED IN THE TYPE, AND ABSENT-ON-THE-WIRE MEANS `unproven`. Every dispatcher built\n * before 0.4.0 sends `name` and `version` and nothing else, so absent has to mean SOMETHING,\n * and only one reading is safe: read as `confined` it is the silent inheritance §3.2 forbids.\n * `unproven` claims nothing, which is the correct answer about a runner that measured nothing.\n *\n * ⚠ AND THE OBJECTION THAT THIS QUIETLY DOWNGRADES TODAY'S DOCKER RUNNERS DOES NOT SURVIVE THE\n * FLOOR. {@link RUNNER_MINIMUM_VERSION} moved to 0.4.0 in the same release, so every runner\n * that would send an absent report is stood down at its first poll and given no work at all —\n * making the case unreachable in practice rather than merely tolerated. Refusing the\n * REGISTRATION instead was tried and is worse: a bootstrap error exits the container, and\n * docs/53 measured `--restart unless-stopped` looping such a container 7 times in 12 seconds.\n */\nexport interface RunnerConfinementReport {\n substrate: RunnerSubstrate;\n /** What this runner ESTABLISHED, never what it configured. */\n undeclaredEgress: ConfinementFinding;\n}\n\n/**\n * ═══ THE CONJUNCTION — THE CEILING AND THE MEASUREMENT, NEVER EITHER ALONE (§3.3) ══════\n *\n * THE one place the two facts meet. The isolation table says the most this isolation may ever\n * claim; the runner says what it actually achieved on the machine it is installed on; a run is\n * confined only where both agree.\n *\n * ★ IT IS AN `&&` AND NOT A PREFERENCE FOR THE RUNNER'S ANSWER, WHICH IS THE HALF THAT KEEPS\n * IT HONEST IN BOTH DIRECTIONS. Taking the runner's word alone would let a substrate we have\n * never argued for report `confined` and be believed — the same overclaim, relocated from a\n * table into a payload we do not control. Taking the ceiling alone is where this started.\n *\n * *Beats:* adding a fourth `SandboxIsolation` member hard-coded to `false` for Kubernetes. That\n * reads as caution and is a real loss: it surrenders the confinement on every cluster that WOULD\n * have enforced it, permanently, and it would make the isolation vocabulary carry a fact that\n * varies per installation — which is not what an isolation is.\n */\nexport function effectiveBlocksUndeclaredEgress(\n isolationCeiling: boolean,\n finding: ConfinementFinding,\n): boolean {\n return isolationCeiling && CONFINEMENT_FINDING_BLOCKS_EGRESS[finding];\n}\n\n/**\n * Whether a runner has claimed MORE than its isolation permits — a report to refuse rather\n * than to record.\n *\n * ⚠ THIS CANNOT FIRE TODAY AND IS WRITTEN ANYWAY, WHICH IS A CLAIM THAT NEEDS ITS OWN\n * SENTENCE RATHER THAN A QUIET COMMIT. `PLACEMENT_SANDBOX_ISOLATION.runner` is `\"runner\"` for\n * every runner there is, and `ISOLATION_BLOCKS_UNDECLARED_EGRESS.runner` is `true`, so every\n * ceiling a runner can meet today is `true` and no finding exceeds it. This codebase has\n * shipped guards that could not fire and paid for them three times, so: it is here because the\n * conjunction above is only half a rule — `A && B` silently tolerates a `B` that had no right\n * to be true, and the day a runner isolation answers `false` that tolerance becomes a runner\n * asserting a boundary its own isolation says is impossible. `runner-confinement.spec.ts`\n * proves it fires by handing it a `false` ceiling directly, which is an honest test of a real\n * function rather than a fourth isolation invented so a guard has something to catch.\n */\nexport function confinementOverclaims(\n isolationCeiling: boolean,\n finding: ConfinementFinding,\n): boolean {\n return !isolationCeiling && CONFINEMENT_FINDING_BLOCKS_EGRESS[finding];\n}\n\n/**\n * The conjunction for a RUNNER specifically — the ceiling is not a choice at this placement.\n *\n * ★ EVERY SURFACE GOES THROUGH THIS RATHER THAN READING A FINDING DIRECTLY, so no screen and\n * no gate can decide for itself that a runner's word is the product's claim.\n */\nexport function runnerBlocksUndeclaredEgress(finding: ConfinementFinding): boolean {\n return effectiveBlocksUndeclaredEgress(RUNNER_ISOLATION_BLOCKS_UNDECLARED_EGRESS, finding);\n}\n\n/**\n * ═══ WHAT AN OPERATOR READS ABOUT ONE RUNNER'S CONFINEMENT — ONE AUTHOR (docs/62) ══════\n *\n * The pool screen prints these and nothing else prints anything about confinement. A second\n * copy is the defect docs/62 was opened for and docs/55 shipped: a rule moved, its readers kept\n * their copies, and three sentences told an operator to run a command against a container that\n * did not exist.\n *\n * ★ KEYED ON THE FINDING ALONE, NOT ON `substrate × finding`. Six cells would contain at least\n * two nobody can reach — a Docker runner reports `confined` from topology and there is no path\n * that makes it answer `unconfined` — and an unreachable cell is a sentence no reader will ever\n * check, written by somebody guessing. The substrate is shown as its own column, where it is a\n * fact rather than a branch.\n *\n * ⚠ `unproven` GETS ITS OWN SENTENCE AND ITS OWN REMEDY. Collapsing it into `unconfined` would\n * tell somebody to change their CNI when what actually happened is that the probe never ran.\n */\nexport const CONFINEMENT_FINDING_SENTENCE = {\n confined: () =>\n \"Undeclared outbound traffic is blocked here. This runner proved it: a probe that reaches \" +\n \"the network when nothing stops it could not reach anything once the confinement applied.\",\n unconfined: () =>\n \"Undeclared outbound traffic is NOT blocked here. This runner probed its own substrate and \" +\n \"the probe got out, so a package that ignored its egress settings would reach the network. \" +\n \"Packages that need their allowlist enforced will not be sent to this pool.\",\n unproven: () =>\n `This runner could not establish whether undeclared outbound traffic is blocked, so ${BRAND_SHORT_NAME} ` +\n \"does not claim that it is. The check needs one throwaway pod that can reach the network \" +\n \"when nothing stops it; until that succeeds there is no measurement to report.\",\n} as const satisfies Record<ConfinementFinding, () => string>;\n\n/** The short label a badge gets. Never abbreviated into a claim the sentence does not make. */\nexport const CONFINEMENT_FINDING_LABEL = {\n confined: \"Egress confined\",\n unconfined: \"Egress not confined\",\n unproven: \"Confinement unproven\",\n} as const satisfies Record<ConfinementFinding, string>;\n\n/**\n * How a pool's confinement reads ACROSS its runners — the sentence §9.6 asks the pool screen\n * for, derived from the per-runner sentences above rather than written a second time.\n *\n * ★ THE MIXED CASE IS THE ONE WORTH HAVING, and it is why this is not just a count. A pool\n * where some runners confine and some do not is a pool where what a run gets depends on which\n * runner claims it — and since routing does not let an operator choose, the honest thing to say\n * is that the pool as a whole cannot be relied on to confine. This is the same shape docs/57\n * arrived at for presence: state the per-axis finding, never let line order decide.\n */\nexport function poolConfinementSentence(\n findings: readonly ConfinementFinding[],\n): string | null {\n if (findings.length === 0) return null;\n const confined = findings.filter(runnerBlocksUndeclaredEgress).length;\n if (confined === findings.length) return CONFINEMENT_FINDING_SENTENCE.confined();\n if (confined === 0) {\n // Every runner agrees it is not confined. WHICH sentence still depends on why, so the\n // uniform case defers to the single finding rather than inventing a third wording.\n const [first] = findings;\n return findings.every((f) => f === first)\n ? CONFINEMENT_FINDING_SENTENCE[first!]()\n : `${CONFINEMENT_FINDING_SENTENCE.unconfined()} Not every runner here reached that ` +\n \"conclusion the same way — open a runner to see what each one measured.\";\n }\n return (\n `Only ${confined} of ${findings.length} runners in this pool block undeclared outbound ` +\n \"traffic. A run cannot choose which runner claims it, so this pool is not relied on to \" +\n \"confine egress and packages that need their allowlist enforced are not sent here.\"\n );\n}\n","/**\n * ═══ WHAT A PRIVATE RUNNER'S HOST IS TOLD, DECLARED ONCE (docs/110) ════════════════════\n *\n * Every name in this file is read by the DISPATCHER and written into somebody else's system by\n * the WEB: the install command and the manifest (`install-runner-panel.tsx`) put these strings\n * into a customer's shell, cluster and host, and the dispatcher (`apps/api/src/runner/`) reads\n * them back there. Neither side can import the other — the dispatcher bundle may not reach\n * `modules/` (`build-runner-bundles.mjs`) and the web cannot reach `apps/api` at all — so until\n * docs/110 each one was typed TWICE: once where the runner reads it, and once where the page\n * tells a customer to set it.\n *\n * ⛔ AND ONE OF THOSE PAIRS WAS THE CONFINEMENT. The NetworkPolicy the manifest applies selects\n * pods by {@link POD_EGRESS_LABEL} and admits egress only to {@link POD_ROLE_BROKER}; the\n * dispatcher puts those labels on the pods it creates. The two halves agreed because two files\n * happened to spell the same bytes. A rename that reached one of them would have left a policy\n * selecting nothing — a package pod that believes it is confined and is not — with every test\n * on each side green, because each side's tests read its own copy.\n *\n * ★ SO A RENAME OF ANY OF THESE IS AN EDIT TO THIS FILE, and the command, the manifest and the\n * dispatcher follow. It is also the reason this is not `package-execution.ts`: that file is the\n * contract with the PACKAGE-RUNNER image (`bootstrap.ps1`), which is a different artifact with a\n * different clock — see `PACKAGE_CONTAINER_ENV`.\n *\n * ⚠ WHAT THIS FILE DOES NOT CHANGE: which image reads these names. The dispatcher and step\n * images a customer is handed are pinned by digest in Terraform (`private_runner_images`), so a\n * value moved here reaches a customer's manifest when the web rolls and reaches the runner that\n * READS it only when that pair is rebuilt and repinned. The manifest is only ever correct\n * against the pair it is served beside.\n */\n\n/**\n * The environment the install command and the manifest set on the dispatcher, and that\n * `runner-config.ts` reads. ⛔ In the customer's shell history, systemd unit or Deployment.\n */\nexport const RUNNER_HOST_ENV = {\n /** `docker` or `kubernetes`. Absent means `docker`; present and wrong is refused by name. */\n substrate: \"RUNVERIC_RUNNER_SUBSTRATE\",\n /** The https origin the runner long-polls. */\n controlPlaneUrl: \"RUNVERIC_CONTROL_PLANE_URL\",\n /** The operator-chosen name, also the container's and the Deployment's. */\n runnerName: \"RUNVERIC_RUNNER_NAME\",\n /** Single-use; spent by the first registration. */\n registrationToken: \"RUNVERIC_RUNNER_REGISTRATION_TOKEN\",\n /** The image the dispatcher starts one container of per step. */\n stepImage: \"RUNVERIC_RUNNER_STEP_IMAGE\",\n /** Optional. Absent means the runner runs built-in actions only. */\n packageImage: \"RUNVERIC_RUNNER_PACKAGE_IMAGE\",\n /** Where the credential and the stashed reports live across restarts. */\n reportDirectory: \"RUNVERIC_RUNNER_REPORT_DIR\",\n} as const;\n\n/**\n * The namespace the printed manifest installs into.\n *\n * ★ A CONSTANT RATHER THAN A FIELD THE OPERATOR FILLS IN, for docs/55 §4's reason: the one\n * placeholder the install command ever had produced a real outage on a real host. Everything\n * the manifest creates is namespaced, so a fixed name is a complete install; an operator who\n * needs a different one is editing a manifest rather than filling in a blank, which is a thing\n * they can do correctly because the whole object is in front of them.\n *\n * ⚠ THE DISPATCHER NEVER READS THIS. It learns its namespace from its own service-account\n * mount (`kubernetes.client.ts`), so it works in whatever namespace the operator applied. This\n * value is read by the WEB — the manifest's `metadata.namespace` and the remedy a human types\n * (`kubectl -n … delete deployment …`) — and by nothing else. That is why it is not the same\n * declaration as {@link POD_MANAGED_BY_VALUE}, whatever their bytes (docs/110 §3.3).\n */\nexport const RUNNER_NAMESPACE = \"runveric-runner\";\n\n/**\n * What every runner's objects on the customer's side are called: `containerNameFor(name)` is\n * this plus the operator's runner name — the Docker container on their host, and the\n * Deployment, ServiceAccount, Role and RoleBinding in their cluster.\n *\n * ⛔ THE WIRE CENSUS CANNOT SEE THIS VALUE, AND docs/110 FOUND IT BY RENDERING THE MANIFEST. A\n * brand word followed only by a joiner is invisible to the scanner by design (rule 3 — it is\n * what keeps a bare `opera-` in prose from being 146 findings), and the name is completed at run\n * time, so no literal anywhere spells a whole one. The registry that the slice's scope was\n * derived from therefore never listed the most repeated brand string in the manifest: after the\n * namespace moved, five objects inside `runveric-runner` would still have been called `opera-…`.\n * Its guard is a literal witness of `containerNameFor`'s OUTPUT (`runner-name.spec.ts`).\n *\n * ⚠ LIKE THE NAMESPACE, A CHANGED PREFIX IS A SECOND OBJECT, NOT A RENAMED ONE: `kubectl apply`\n * creates a second Deployment and `docker run --name` a second container, and every remedy the\n * pool screen prints then names the new one.\n */\nexport const RUNNER_CONTAINER_PREFIX = \"runveric-\";\n\n/** The dispatcher's state volume: the manifest mounts it, `runner-config.ts` defaults into it. */\nexport const RUNNER_STATE_DIRECTORY = \"/var/lib/runveric-runner\";\n/** Where the credential file and stashed reports are written, inside the state volume. */\nexport const RUNNER_REPORT_DIRECTORY = `${RUNNER_STATE_DIRECTORY}/reports`;\n\n/**\n * The NetworkPolicy's `metadata.name`. ⛔ `kubectl apply` is keyed on it: a changed name\n * CREATES a second policy beside the first rather than replacing it (docs/110 §3.2).\n */\nexport const RUNNER_NETWORK_POLICY_NAME = \"runveric-confined-egress\";\n\n/**\n * ═══ THE LABELS ON EVERY POD THE DISPATCHER CREATES, AND THE TWO READERS THAT SELECT ON THEM\n *\n * the operator's NetworkPolicy {@link POD_EGRESS_LABEL}=confined, egress to {@link POD_ROLE}=broker\n * the dispatcher's orphan sweep {@link POD_MANAGED_BY}={@link POD_MANAGED_BY_VALUE}, {@link POD_RUNNER}=<name>\n *\n * ⛔ A KEY AND ITS VALUE ARE ONE SELECTOR. Rename either half while pods carry the old one and\n * the reader stops matching them: the policy confines nothing, or the sweep leaves pods nothing\n * will ever reap.\n */\nexport const POD_MANAGED_BY = \"runveric.dev/managed-by\";\n/**\n * The value of {@link POD_MANAGED_BY}. Written by the dispatcher on every pod and read back\n * only by its own sweep, so the one thing that could still hold an old value is a pod an OLDER\n * dispatcher created.\n *\n * ★ IT NAMES THE DISPATCHER, AND IT DELIBERATELY NO LONGER SPELLS THE NAMESPACE (docs/110 §3.3).\n * Until docs/110 both were `opera-runner`: one string, two objects, two readers that never meet\n * — the web reads {@link RUNNER_NAMESPACE}, the dispatcher's sweep reads this. With identical\n * bytes no instrument keyed on text could tell a site of one from a site of the other, so the\n * registry had to declare them as ONE family and the census pinned their equality as if it were\n * a property. Distinct bytes are what make the honest declaration — two families — expressible.\n */\nexport const POD_MANAGED_BY_VALUE = \"runveric-dispatcher\";\nexport const POD_ROLE = \"runveric.dev/role\";\n/**\n * WHICH runner owns this pod.\n *\n * ★ IT EXISTS SO THE STARTUP SWEEP CANNOT DELETE SOMEBODY ELSE'S WORK. One namespace can hold\n * several runners — an operator installs two into one pool — and the managed-by label is true\n * of all of them. A sweep keyed on that alone would delete a sibling's step MID-RUN, which is a\n * customer's run ended by our own cleanup.\n */\nexport const POD_RUNNER = \"runveric.dev/runner\";\n/** Selects pods the operator's NetworkPolicy confines. Set by us, enforced by the cluster. */\nexport const POD_EGRESS_LABEL = \"runveric.dev/egress\";\nexport const POD_EGRESS_CONFINED = \"confined\";\n/** The one role a confined pod may reach, and the one the operator's policy names. */\nexport const POD_ROLE_BROKER = \"egress-broker\";\n","/**\n * ═══ WHAT AN ACTION AUTHOR EXPORTS FOR THE PUBLISHED CLI, DECLARED ONCE ═══════════════════\n *\n * The CLI reads these from an author's shell or CI; the Author page tells authors to set one of\n * them. Neither can import the other, so until `@runveric/cli` 0.1.2 each was typed on both\n * sides — the same second-author shape `runner-install.ts` removed for the runner host.\n *\n * ⛔ TWO CLOCKS, AND THIS FILE IS ON THE SLOWER ONE. These names are read by whatever CLI version\n * an author INSTALLED from npm, not by this repository. A value here takes effect for authors\n * only when a CLI carrying it is PUBLISHED — so the Author page may render a name from here only\n * once that version is on npm and advertised (`cli-release.md`, step 7), never before.\n */\nexport const AUTHORING_CLI_ENV = {\n /** `runveric publish`: the access token. */\n token: \"RUNVERIC_TOKEN\",\n /** `runveric publish`: the control plane's origin. */\n url: \"RUNVERIC_URL\",\n /** `runveric test`: the runner image to run in, digest-pinned — the Author page shows it. */\n runnerImage: \"RUNVERIC_RUNNER_IMAGE\",\n} as const;\n\n/**\n * What `@runveric/cli` 0.1.1 read. ⛔ NEVER READ NOW — named only so a stale export is refused BY\n * NAME. Reading the old value as a fallback would keep the old name alive in every pipeline\n * forever and hide the rename from the one person who can fix it; a refusal that names both is\n * fixed by renaming one line.\n */\nexport const RETIRED_AUTHORING_CLI_ENV = {\n token: \"OPERA_TOKEN\",\n url: \"OPERA_URL\",\n runnerImage: \"OPERA_RUNNER_IMAGE\",\n} as const satisfies Record<keyof typeof AUTHORING_CLI_ENV, string>;\n","// Private runners — the channel (docs/49 S1). The shapes shared by three processes that\n// share nothing else: the control plane, the runner DISPATCHER in the customer's network,\n// and the STEP CONTAINER the dispatcher starts for one phase of one execution.\n//\n// ─── THE ONE PROPERTY EVERY SHAPE HERE PROTECTS ─────────────────────────────────────────\n//\n// The control plane never opens a connection to a runner (docs/49 §4.3). That is not a rule\n// somebody remembers — it is a fact about these types: **no shape in this file carries a\n// runner's address.** There is no url, host, port, endpoint or callback field on a runner,\n// its pool, or its registration, so there is nothing for a future dispatch path to dial even\n// if someone wanted to. `runner-has-no-address.spec.ts` asserts it over this file AND over\n// the live table, because a column would be just as good an address as a field.\nimport { RUNNER_PROTOCOL_VERSION, type RunnerProtocolVersion } from \"./wire-identity\";\nimport type { PackagePhase, PackageJsonObject } from \"./package-execution\";\nimport { PACKAGE_PROVENANCE_KINDS, type PackageProvenanceKind } from \"./package-provenance\";\nimport type { ConfinementFinding, RunnerConfinementReport, RunnerSubstrate } from \"./runner-confinement\";\nimport { RUNNER_CONTAINER_PREFIX } from \"./runner-install\";\nimport type { ResolvedConnectionScopeDto } from \"./connections\";\nimport type { TargetCounts, ValidationCheck } from \"./validation\";\n\n/**\n * The header a runner presents its SESSION credential in, and the one it presents a\n * single-use REGISTRATION token in.\n *\n * DELIBERATELY NOT `Authorization`, for the reason `RUN_TOKEN_HEADER` already gives: a\n * browser session and an API client both authenticate in `Authorization`, so reading a\n * runner's credential from a different header makes \"an ordinary session cannot call the\n * channel\" structural rather than conditional — a session does not fail the check, it never\n * reaches it.\n */\nexport const RUNNER_REGISTRATION_TOKEN_HEADER = \"x-runveric-runner-registration-token\";\nexport const RUNNER_CREDENTIAL_HEADER = \"x-runveric-runner-credential\";\n/** The single-use secret that authorizes ONE claimed work item's result. */\nexport const RUNNER_AUTHORIZATION_TOKEN_HEADER = \"x-runveric-runner-authorization\";\n\n/** A runner pool as an admin sees it. A pool with no runner is a legitimate state. */\nexport interface RunnerPoolDto {\n id: string;\n name: string;\n description: string | null;\n /** How many runners have registered into this pool and not been removed. */\n runnerCount: number;\n /**\n * ═══ WHICH ACTION PACKAGES THIS POOL'S OWNER HAS VOUCHED FOR (docs/59 §3.1) ══════════\n *\n * A package whose provenance is NOT in this set is refused at plan time with the existing\n * `runner_pool` cause, exactly as every package was before docs/59. **Empty is the default\n * and empty is today's behaviour** — see {@link RUNNER_POOL_DEFAULT_ACCEPTS_PROVENANCE}.\n *\n * ★ A SET, NOT A BOOLEAN, AND THE SET IS THE DESIGN. One \"allow packages here\" toggle would\n * let an admin reason about `authored` — code their own people wrote, in this tenant, with a\n * name attached — and silently also accept `public_git`, which is code neither Opera nor\n * their organisation wrote. Those are different risks, so they are different switches\n * (charter §4.2's orthogonal-facts rule, the same one that produced docs/57's per-axis pool\n * notice).\n *\n * ★ IT IS CONSENT, NOT CAPABILITY. Opera is not asserting that a package is safe to run on\n * this host; the pool's owner is asserting that they accept it. docs/54's measurement stands\n * — a step container on a runner shares the host's kernel and reaches the host's network —\n * and it is not a reason to refuse, because the host, the network, the credential and (for\n * an authored package) the code are all the customer's. The refusal that remains exists so\n * that acceptance is DELIBERATE, not so that Opera decides.\n */\n acceptsProvenance: readonly PackageProvenanceKind[];\n createdAt: string;\n}\n\n/**\n * ═══ WHAT A POOL ACCEPTS BEFORE ANYBODY DECIDES — AND WHY IT IS A `Record` ══════════════\n *\n * ★★ THE VALUE TYPE IS THE LITERAL `false`, NOT `boolean`, AND THAT IS THE WHOLE SAFETY\n * PROPERTY OF THIS SLICE MADE UNEXPRESSIBLE RATHER THAN MERELY TESTED. A future provenance\n * cannot be declared open by default here: `public_git_v2: true` is a compile error, not a\n * review comment. `Record<PackageProvenanceKind, boolean>` — the shape\n * {@link PACKAGE_PROVENANCE_IS_REVOCABLE} uses, because THAT question has both answers — would\n * have left the one dangerous answer available to a hurried edit.\n *\n * ★ AND IT IS KEYED BY THE UNION, so a fourth `PACKAGE_PROVENANCE_KINDS` member is a missing\n * property here until somebody decides what a pool does with it. Deciding is free — the only\n * legal answer is `false` — but it cannot be SKIPPED, which is the point: a new provenance\n * must not reach a customer's host because nobody thought about it.\n *\n * ⚠ The database says this a second time (`accepts_provenance … DEFAULT '{}'`, migration 0066)\n * and that is not a second spelling of the vocabulary: it is a default on a NOT NULL column,\n * which is what makes an INSERT that forgets the field land closed instead of null. The\n * derived list below is asserted equal to `[]` in `pool-provenance-consent.spec.ts`, so the\n * two cannot drift into disagreement.\n */\nexport const RUNNER_POOL_ACCEPTS_PROVENANCE_BY_DEFAULT: Record<PackageProvenanceKind, false> = {\n // Imported from a Git source this tenant connected. Still not accepted by default: a pool\n // is a machine inside a customer's network, and nothing about it is implied by connecting a\n // repository somewhere else.\n git_source: false,\n // Code neither Opera nor this organisation wrote. The one an admin must never reach by\n // accident, which is why there is no toggle that reaches it alongside another.\n public_git: false,\n // Written in Opera, by a named user of this tenant. Still `false`: the customer decides\n // whose machines run it, and a default is not a decision.\n authored: false,\n};\n\n/**\n * The default set, DERIVED from the declaration above rather than written as `[]`.\n *\n * ★ A literal `[]` would be a second, unchecked spelling of \"nothing is accepted\" — and the\n * day somebody adds a provenance that a pool SHOULD accept by default, the literal keeps\n * compiling while saying the opposite of the Record. Deriving it means the two are one fact.\n */\nexport const RUNNER_POOL_DEFAULT_ACCEPTS_PROVENANCE: readonly PackageProvenanceKind[] =\n PACKAGE_PROVENANCE_KINDS.filter((kind) => RUNNER_POOL_ACCEPTS_PROVENANCE_BY_DEFAULT[kind]);\n\n/**\n * ═══ HAS THIS POOL'S OWNER VOUCHED FOR THIS CODE? (docs/59 §3.1) ════════════════════════\n *\n * The whole rule, in one total function, declared beside the vocabulary it reads rather than\n * inline at the gate that calls it. Two things follow, and both are the reason it is here:\n *\n * ★ IT CAN BE EXERCISED DIRECTLY, over EVERY member of `PACKAGE_PROVENANCE_KINDS`, without\n * constructing an execution. Written inline as `pool.acceptsProvenance.includes(provenance)`\n * the fail-closed decision would live inside an `if` in a private method, reachable only\n * through a service with eleven constructor dependencies — and the `null` case would be a\n * nullability puzzle somebody solves with a `!` at 3am rather than a branch somebody reads.\n *\n * ★ AND THE SET IS A REQUIRED ARGUMENT, so there is nowhere to put a permissive fallback. A\n * caller cannot reach this with a missing set that quietly means \"everything\": it would have\n * to write that fallback out at the call site, in the diff, where a reviewer sees it.\n *\n * ⚠ `null` PROVENANCE REFUSES, and that is a policy decision rather than a type accident. It\n * means a package-backed action version whose `package_version` row could not be read. A pool\n * cannot have consented to a provenance nobody can name, so \"we could not tell\" takes the\n * refusal — never the exemption.\n */\nexport function poolAcceptsProvenance(\n accepts: readonly PackageProvenanceKind[],\n provenance: PackageProvenanceKind | null,\n): boolean {\n if (provenance === null) return false;\n return accepts.includes(provenance);\n}\n\n/**\n * What an admin may change about a pool's consent. One provenance and one direction per call,\n * because that is what the audit trail records (docs/59 judgement 4) — a request that could\n * carry \"the new set\" would make one audit row stand for several decisions.\n */\nexport interface SetPoolProvenanceInput {\n provenance: PackageProvenanceKind;\n /** `true` accepts it, `false` revokes it. Revoking is not retroactive — see docs/59 §4. */\n accepted: boolean;\n}\n\n/**\n * A registered runner. Version is recorded at registration because it is a fact the\n * registration carried; docs/49 S4 is what makes a stale version REFUSE work.\n *\n * `lastSeenAt` is written by the channel itself — every authenticated call from a runner\n * slides it — so \"connected\" is derived from something the runner did, never from something\n * it claimed.\n */\nexport interface RunnerDto {\n id: string;\n poolId: string;\n name: string;\n version: string;\n registeredAt: string;\n lastSeenAt: string;\n /**\n * When this runner's session credential stops being accepted. Slid forward by every\n * authenticated call, so on a live runner it is always ~`RUNNER_CREDENTIAL_TTL_MS` ahead.\n *\n * ★ IT IS ON THE DTO SO THE UI CAN STATE A FACT INSTEAD OF INFERRING ONE. Past this\n * instant the runner cannot resume — it must re-register (§the credential note above) —\n * which is a different problem from \"it has not polled for a while\", needs different copy,\n * and is the boundary {@link runnerPresence} uses to tell the two apart.\n */\n credentialExpiresAt: string;\n /**\n * Whether this runner is holding a step right now — it has claimed an authorization that\n * has neither completed nor expired.\n *\n * ★ A SECOND AXIS, NEVER A FOURTH PRESENCE VALUE. `busy` and {@link RunnerPresence} are\n * orthogonal facts and the truth table has four filled cells, which is what proves they\n * cannot share an enum (charter §4.2, docs/43's tone-vs-state rule):\n *\n * busy=false busy=true\n * online polling, ready for work running a step\n * quiet not polling, holds nothing not polling, HOLDING A STEP ← the\n * one that matters: a step nobody is\n * reporting on, which the authorization's\n * own expiry will end.\n * offline gone gone mid-step\n *\n * Collapsed into one enum, the second row is inexpressible and a pool would show a runner\n * as merely quiet while a customer's run sat inside it.\n */\n busy: boolean;\n /**\n * What an OPERATOR intends for this runner — the third axis, and the one nobody observes\n * (docs/53 §4.2). See {@link RunnerLifecycle} for why it cannot share an enum with presence.\n */\n lifecycle: RunnerLifecycle;\n /**\n * When the lifecycle last changed, or null while it has never left `active`.\n *\n * NULL IS NOT \"AT REGISTRATION\". A runner that was never drained or revoked has no lifecycle\n * event to date, and stamping `registeredAt` here would invent one — a screen would then say\n * \"active since 3 days ago\" about a fact nobody ever asserted.\n */\n lifecycleChangedAt: string | null;\n /**\n * Who changed it, resolved to a display name on the server — the docs/46 rule that WHO did\n * it belongs on the line, not one join away. Null when the lifecycle has never changed, and\n * also when the person who changed it has since been removed: the runner's state survives\n * its author, and a dangling id rendered as a name would be worse than an honest absence.\n */\n lifecycleChangedBy: string | null;\n /**\n * Where this runner runs its work — recorded because the registration carried it, exactly\n * like `version` above. A FOURTH axis, and it shares an enum with nothing: an operator can\n * install a Docker runner and a Kubernetes runner into one pool, and the pool screen has to\n * be able to say which is which without inferring it from anything else.\n */\n substrate: RunnerSubstrate;\n /**\n * What this runner MEASURED about undeclared egress on its own substrate (docs/70 §3.2).\n *\n * ⚠ IT IS THE RUNNER'S FINDING, NOT THE EFFECTIVE ANSWER. What a run actually gets is\n * `effectiveBlocksUndeclaredEgress(ceiling, this)` — the conjunction with the isolation's\n * own ceiling. Rendering this field as though it were the whole answer is the mistake the\n * conjunction exists to prevent, which is why every surface goes through that function.\n */\n undeclaredEgress: ConfinementFinding;\n}\n\n/**\n * ═══ WHAT THIS RUNNER'S CONTAINER IS CALLED ON ITS HOST ════════════════════════════════\n *\n * ★ IT LIVES IN THE CHANNEL BECAUSE THREE PROCESSES SAY IT OUT LOUD, and this file is the one\n * they share. The pool screen prints `--name` in the install command and prints the remedy for\n * removing that container again; the DISPATCHER, inside the customer's network, names the same\n * container in the two log lines that tell an operator how to stop it. Declared in the browser\n * — which is where it started — the dispatcher could not reach it and typed the name instead.\n *\n * ⚠ AND THAT IS NOT A HYPOTHETICAL, IT IS WHY THIS MOVED. docs/55 made the container name\n * per-runner and updated the INSTALL command; the drain remedy and both dispatcher log lines\n * were left holding the constant `opera-runner`, which stopped existing that day. Three\n * sentences told an operator to run a command against a container that is not there. A rule\n * one of its readers cannot import is a rule that gets retyped, and a retyped rule drifts.\n *\n * ★ PREFIXED ({@link RUNNER_CONTAINER_PREFIX}), SO THE HOST STILL SAYS WHOSE IT IS. The original\n * command hardcoded `--name opera-runner`, which was self-describing and could only ever exist\n * once. Prefixing the operator's name keeps the first property and drops the second: the\n * default `runner-1` yields `runveric-runner-1`, and a second install on the same host yields\n * `runveric-runner-2` instead of the daemon's \"name is already in use\".\n *\n * The GRAMMAR that makes the result a legal container name is NOT here — it is the entry\n * field's refusal (`refuseRunnerName` in the web app), because it exists for the person\n * typing, and this exists for the three processes that spend what they typed.\n */\nexport function containerNameFor(runnerName: string): string {\n return `${RUNNER_CONTAINER_PREFIX}${runnerName.trim()}`;\n}\n\n/**\n * ═══ WHAT AN OPERATOR INTENDED — AND WHY IT IS NOT A PRESENCE VALUE (docs/53 §4.2) ═════\n *\n * active it may claim work. The state every runner registers into.\n * draining it may not claim, and it finishes what it already holds. COOPERATIVE.\n * revoked its credential stops being honoured. NOT cooperative — see below.\n *\n * ★ TWO AXES, BECAUSE ONE OF THEM IS OBSERVED AND THE OTHER IS DECIDED. {@link RunnerPresence}\n * is derived from two timestamps and nobody chooses it; this is stored, and only an operator\n * writes it. Collapsed into a single enum, \"draining but currently quiet\" — a runner that was\n * told to stand down and whose host then dropped off the network — becomes inexpressible, and\n * that is a state somebody meets on a bad day. The full table has nine cells and eight of them\n * are reachable:\n *\n * active draining revoked\n * online claiming work standing down, polling ⌀ (see below)\n * quiet restarting, or a slow drained and waiting to ⌀\n * network be removed\n * offline gone; credential expired drained and gone revoked\n *\n * ★ THE TWO EMPTY CELLS ARE A CONSEQUENCE, NOT A COLLAPSE. Revoking sets\n * `credentialExpiresAt` to the instant of the revoke (docs/53 §4.3), so a revoked runner reads\n * `offline` from {@link runnerPresence} immediately and by arithmetic rather than by a second\n * rule. That is deliberate: without it a revoked runner would keep saying \"Connected\" for the\n * whole 90-second quiet window — a pool screen claiming to hear a runner we have just refused\n * to hear. The axes stay orthogonal in the TYPE; it is revocation's own meaning that fills\n * only one row of them.\n */\nexport type RunnerLifecycle = \"active\" | \"draining\" | \"revoked\";\n\nexport const RUNNER_LIFECYCLES: readonly RunnerLifecycle[] = [\"active\", \"draining\", \"revoked\"];\n\n/**\n * ═══ WHEN \"NOT POLLING\" BECOMES \"NOT THERE\" — 90 SECONDS, AND WHY ══════════════════════\n *\n * A healthy runner is SILENT most of the time. It holds a long poll open waiting for work,\n * and an empty one was MEASURED at 20.034 s in S1 — so between two touches of `lastSeenAt`\n * there is a perfectly ordinary ~20-second gap with nothing happening at all.\n *\n * A threshold has to clear that gap by enough that the ordinary case never flickers:\n *\n * 20.034 s one empty long poll, measured\n * ~21 s plus the reconnect the dispatcher makes immediately afterwards\n * 90 s this. FOUR consecutive missed polls before a runner is called quiet.\n *\n * Four, not one, because the things that eat a poll here are common and self-healing — a\n * container restart, a proxy dropping an idle socket, a claim that takes longer than the\n * poll it interrupted. At 60 s (three polls) a single restart would paint a working runner\n * red; at 300 s a runner that died would still look healthy five minutes into an incident,\n * which is the failure that matters on this screen.\n *\n * ⚠ THIS IS A DISPLAY THRESHOLD AND NOTHING ELSE. It gates no dispatch and refuses no work —\n * a \"quiet\" runner is still perfectly able to claim (docs/49 S4 owns drain and refusal). A\n * constant that decided both would make a UI tweak change what the platform will run.\n */\nexport const RUNNER_QUIET_AFTER_MS = 90_000;\n\n/**\n * What a pool screen can truthfully say about one runner, from two timestamps.\n *\n * Three values rather than two, because \"offline\" is the only one of them that is a FACT:\n *\n * online seen inside {@link RUNNER_QUIET_AFTER_MS}. It is polling.\n * quiet seen longer ago than that, credential still valid. AN INFERENCE — it may be\n * mid-restart, or its network may be slow, and it can come back on its own.\n * offline its credential has expired. It CANNOT come back without re-registering, so\n * this one needs no hedging and takes a different next action.\n *\n * Collapsing `quiet` and `offline` was the tempting simplification and it is wrong: they are\n * two different problems with two different remedies, which is exactly the distinction B5\n * asserts about empty states one layer up.\n */\nexport type RunnerPresence = \"online\" | \"quiet\" | \"offline\";\n\nexport const RUNNER_PRESENCES: readonly RunnerPresence[] = [\"online\", \"quiet\", \"offline\"];\n\n/**\n * Derive presence from the runner's own timestamps. Pure, and shared, so the pool list, the\n * pool summary and any test all answer the question the same way — a second copy of this\n * arithmetic is how a row and the count above it come to disagree (charter §4.2).\n */\nexport function runnerPresence(\n runner: Pick<RunnerDto, \"lastSeenAt\" | \"credentialExpiresAt\">,\n now: number,\n): RunnerPresence {\n if (new Date(runner.credentialExpiresAt).getTime() <= now) return \"offline\";\n return now - new Date(runner.lastSeenAt).getTime() < RUNNER_QUIET_AFTER_MS\n ? \"online\"\n : \"quiet\";\n}\n\n/**\n * ═══ VERSION SKEW, AS A POOL SCREEN HAS TO SAY IT (docs/53 §4.5) ═══════════════════════\n *\n * current the build this deployment installs. Nothing to do.\n * behind an older build that this control plane still accepts. It runs work.\n * unsupported below the floor. THE CONTROL PLANE REFUSES IT WORK — see below.\n *\n * ★ THREE VALUES, NOT A BOOLEAN, BECAUSE TWO OF THEM TAKE OPPOSITE ACTIONS. S5 shipped\n * `runner.version !== install.version` and rendered one warning for it. That predicate is\n * wrong in both directions once a floor exists: it calls a runner one patch behind \"older\n * build · still claims work\" — true, and not worth a badge — while giving a runner the\n * control plane will not dispatch to the exact same badge and the same sentence. One of\n * those is a note and the other is why a customer's run is sitting unclaimed.\n *\n * ⚠ AND `behind` IS NOT A FAILURE. A pool mid-upgrade is the ordinary state during a\n * release, and painting it red would train an operator to ignore the colour that means\n * `unsupported`.\n */\nexport type RunnerVersionStanding = \"current\" | \"behind\" | \"unsupported\";\n\n/**\n * What this deployment installs, and the oldest build it will hand work to. Both served\n * on {@link RunnerInstallDto} rather than compiled into the browser, for the reason that\n * DTO already gives about the image: they are facts about THIS deployment.\n */\nexport interface RunnerVersionPolicy {\n version: string;\n minimumVersion: string;\n}\n\n/**\n * Where one runner's build stands. Pure and shared, so the row badge, the pool summary and\n * the control plane's own refusal cannot disagree about which runners are unsupported —\n * the same reason {@link runnerPresence} is here rather than copied into a screen.\n *\n * ★ AN UNPARSEABLE VERSION IS `unsupported`, AND THE DIRECTION MATTERS. `version` is a\n * string a runner sent us; it is validated for length and nothing else. Treating something\n * we cannot read as `current` would fail OPEN — the one runner whose build we cannot\n * identify would be the one runner allowed to claim anything. So it fails closed, and the\n * pool screen says the version is not one we recognise rather than silently trusting it.\n */\nexport function runnerVersionStanding(\n runnerVersion: string,\n policy: RunnerVersionPolicy,\n): RunnerVersionStanding {\n const runner = parseRunnerVersion(runnerVersion);\n if (runner === null) return \"unsupported\";\n if (compareRunnerVersions(runner, parseRunnerVersion(policy.minimumVersion) ?? [0, 0, 0]) < 0) {\n return \"unsupported\";\n }\n const installed = parseRunnerVersion(policy.version);\n if (installed !== null && compareRunnerVersions(runner, installed) < 0) return \"behind\";\n return \"current\";\n}\n\n/**\n * `major.minor.patch`, with any pre-release or build suffix DISCARDED.\n *\n * ⚠ THAT DISCARD IS A DECISION AND IT IS THE LENIENT ONE. `0.2.0-rc.1` is treated as\n * `0.2.0` — ordered as its release rather than below it, which is the opposite of semver's\n * own rule. It is right here because the thing being ordered is OUR OWN runner build: a\n * pre-release of 0.2.0 is a build that speaks 0.2.0's channel, and ranking it under the\n * floor would refuse work to the exact image somebody is trialling before a release. It is\n * also what keeps the e2e's `0.1.0-test` honest — it sorts as 0.1.0, which is what it is.\n */\nfunction parseRunnerVersion(value: string): [number, number, number] | null {\n const match = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:[-+].*)?$/.exec(value.trim());\n if (!match) return null;\n return [Number(match[1]), Number(match[2]), Number(match[3])];\n}\n\nfunction compareRunnerVersions(\n a: [number, number, number],\n b: [number, number, number],\n): number {\n for (let i = 0; i < 3; i += 1) {\n if (a[i] !== b[i]) return a[i] - b[i];\n }\n return 0;\n}\n\n/**\n * A connection scope bound to a pool, NAMED on both sides (docs/49 §5.4).\n *\n * The ids alone would force every reader to join two more collections to render one\n * sentence, and the sentence — \"runs using <connection> / <scope> execute in <pool>\" — is\n * the whole content of a binding. Resolved once, on the server, which also means a reader\n * who can see the binding cannot be shown a name for a connection they cannot see.\n */\nexport interface RunnerPoolBindingDto {\n connectionScopeId: string;\n connectionId: string;\n connectionName: string;\n poolId: string;\n poolName: string;\n}\n\n/**\n * The facts an install command is made of that are NOT product facts — they belong to THIS\n * deployment — served rather than written into the UI (the `AuthoringToolingDto` precedent,\n * for the same reason).\n *\n * ★ `image` IS NULL RATHER THAN A GUESS. A deployment that has not pinned a runner image has\n * no install command, and printing a plausible-looking one would send an operator to debug a\n * registry that was never involved. The screen says so instead.\n *\n * ⚠ AND IT CARRIES NO CONTROL-PLANE URL, WHICH IS NOT AN OVERSIGHT. `runner-has-no-address`\n * asserts that NO shape in this file holds an address, and it found this DTO the first time\n * one was added: an address here is an address a future dispatch path could dial, whatever\n * the field is nominally for. The install command still needs an origin, and the browser\n * assembling it already has the right one — it is talking to the control plane, so\n * `API_BASE_URL` is a demonstrably reachable answer rather than a configured guess.\n */\nexport interface RunnerInstallDto {\n /**\n * The two digest-pinned images an install needs, or null when this deployment has pinned\n * neither.\n *\n * ★ ONE NULLABLE PAIR, NOT TWO NULLABLE STRINGS (docs/52 §5). A private runner is two images\n * with two different privileges — the dispatcher holds the host's container socket, the step\n * image holds nothing — and they are released together. Two independently-nullable fields\n * would make \"the dispatcher is pinned and the step image is not\" a state this type can\n * express, and the screen would then have to invent copy for a deployment that is half\n * configured. It cannot arise: Terraform supplies both from one object variable, the api\n * REFUSES TO START if exactly one is set, and this shape leaves nowhere to put the half.\n */\n images: RunnerInstallImages | null;\n /** The runner build those images contain, so a pool can say which of its runners is old. */\n version: string;\n /**\n * The oldest build this control plane will hand work to (docs/53 §4.5).\n *\n * ★ SERVED, NOT NULLABLE, AND NOT DERIVED FROM `version`. It is a fact about the CHANNEL —\n * which builds can still honour the contract — while `version` is a fact about the IMAGE\n * this deployment happens to have pinned. They move for different reasons: a release bumps\n * `version` every time and the floor only when the wire changes underneath it, and a\n * deployment that pinned no image at all still has a floor. A screen that inferred one from\n * the other would call every runner unsupported on the day of a routine release.\n */\n minimumVersion: string;\n}\n\nexport interface RunnerInstallImages {\n /** What the operator runs. It is given the host's container socket. */\n dispatcher: string;\n /**\n * What the dispatcher starts per step. It is given no socket and no mount.\n *\n * It is also what the EGRESS BROKER runs (docs/60 §3.2). Not a third image: a broker holds\n * exactly this image's privileges — no socket, no mount, non-root, destroyed with the phase\n * — and the only thing that differs is an argv the dispatcher composes. A separate image\n * would assert a third privilege level that does not exist, and would add a digest to pin,\n * publish and keep in build-parity for bytes already sitting on the host.\n */\n step: string;\n /**\n * What the dispatcher starts to execute an ACTION PACKAGE (docs/60).\n *\n * ★ A THIRD IMAGE HERE IS NOT THE SAME DECISION AS THE BROKER. This one carries the\n * interpreters — pwsh, bash, python — that customer code actually executes in, so it is a\n * Debian image an order of magnitude larger than the two above and it is the SUPPLY-CHAIN\n * pin (docs/31 slice 6c) rather than a deployment detail. Sharing the step image would mean\n * putting three language runtimes into the container that runs Opera's own connectors.\n *\n * ⚠ IT IS NULLABLE AND THE OTHER TWO ARE NOT, and that is the one half-configured state this\n * type is allowed to express. A deployment that pins the pair but not this one runs built-in\n * actions on runners and refuses packages there — which is precisely the product as it stood\n * before this slice, and a state an operator may deliberately choose. It is NOT the \"half a\n * pair\" state {@link RunnerInstallDto.images} exists to forbid: those two are one release\n * artifact and this is a different one.\n */\n package: string | null;\n}\n\n/** What an admin gets back when minting a registration token. The token is shown ONCE. */\nexport interface RunnerRegistrationTokenDto {\n /** The bearer value. Never stored — the server keeps only its sha256. */\n token: string;\n poolId: string;\n expiresAt: string;\n}\n\nexport interface CreateRunnerPoolInput {\n name: string;\n description?: string | null;\n}\n\n/** What a runner sends to exchange its single-use registration token for an identity. */\nexport interface RunnerRegistrationRequest {\n /** Operator-chosen, for the pool list. Not an identity — the credential is. */\n name: string;\n /** The runner build. `RUNNER_PROTOCOL_VERSION` below is what the CHANNEL speaks. */\n version: string;\n /**\n * ═══ WHAT THIS RUNNER MEASURED ABOUT ITS OWN SUBSTRATE (docs/70 §3.3) ════════════════\n *\n * ★ THE FIRST THING A RUNNER HAS EVER REPORTED ABOUT ITSELF BEYOND ITS NAME AND BUILD, and\n * that is precisely the gap docs/70 opened on: the control plane decided what a runner could\n * confine from a CONSTANT keyed by isolation, which was right while `runner` meant one Docker\n * host and became an overclaim the moment it could also mean a Kubernetes cluster whose CNI\n * may or may not enforce policy at all.\n *\n * ⚠ REQUIRED HERE, AND THAT IS WHY THE FLOOR MOVES WITH IT. See\n * {@link RunnerConfinementReport}: a runner too old to send this is below\n * {@link RUNNER_MINIMUM_VERSION}, so its report reads `unproven` — claiming nothing — and it\n * is stood down at its first poll rather than refused at registration, which would loop it.\n */\n confinement: RunnerConfinementReport;\n}\n\n/**\n * The wire version of the channel, so a runner and a control plane can disagree loudly\n * rather than silently mis-read each other. docs/49 S4 turns a disagreement into a refusal\n * that names both sides; S1 only has to make the disagreement observable.\n *\n * ═══ v2 (docs/60): A CLAIM CARRIES ONE OF TWO KINDS OF WORK ════════════════════════════\n *\n * ★ IT MOVED BECAUSE THE WIRE CHANGED UNDERNEATH A RUNNER, WHICH IS THE ONLY REASON IT EVER\n * MOVES. {@link RunnerWorkAuthorization.invocation} used to BE a step invocation; it is now a\n * discriminated union, and a v1 dispatcher reads `kind` as nothing at all. Handed a package it\n * would fall through every branch it has and start a step container for work that is not a\n * step — which is the failure a version is for.\n *\n * ★★ AND THE DISCRIMINANT IS ON THE INVOCATION RATHER THAN BESIDE IT. A sibling field\n * (`{ kind, invocation }`) would let the two disagree — a `kind: \"step\"` beside a package\n * payload is a shape somebody can write. With the tag INSIDE, `RunnerInvocation` is a union\n * TypeScript narrows, so a dispatcher that does not handle both arms does not compile and a\n * mismatched pair cannot be constructed.\n */\n// Re-exported under its established name — the DECLARATION moved to `./wire-identity`\n// (docs/95), where every frozen wire identifier now sits together, but this is the name\n// the runner channel has always imported and renaming it would be a second change.\nexport { RUNNER_PROTOCOL_VERSION, type RunnerProtocolVersion };\n\n/**\n * The kinds of work a runner can be authorized to do, declared ONCE (charter §4.2).\n *\n * ★ TWO KINDS BECAUSE THEY ARE TWO CONTAINERS WITH TWO JOBS, not because a package is a\n * special step. A step container gets one invocation on stdin, no network flag and no\n * control-plane address; a package container gets a network whose only route is a broker the\n * dispatcher starts beside it, and it fetches its own bytes. Neither shape can carry the\n * other's fields, which is what stops a step container ever being handed a package\n * (`package-reaches-the-runner.spec.ts` is the assertion, and it stays green because of this\n * split rather than in spite of it).\n */\nexport const RUNNER_WORK_KINDS = [\"step\", \"package\"] as const;\nexport type RunnerWorkKind = (typeof RUNNER_WORK_KINDS)[number];\n\nexport interface RunnerRegistrationResponse {\n protocolVersion: typeof RUNNER_PROTOCOL_VERSION;\n runnerId: string;\n poolId: string;\n poolName: string;\n /**\n * The runner's session credential — 256 bits of randomness, stored only as a sha256.\n *\n * IT IS THE ONE BEARER SECRET IN THIS DESIGN, and its properties are what keep it from\n * being the \"long-lived shared secret\" docs/49 §5.2 refuses: it is minted per runner (never\n * shared), never written down anywhere a person reads, and it EXPIRES — every authenticated\n * call slides `expiresAt` forward, so an active runner never expires and an idle one is\n * dead within the TTL. A runner that comes back after that re-registers rather than\n * resumes, which is exactly what docs/49 §6 asks for.\n */\n credential: string;\n /** ISO-8601. Slides forward on every authenticated call. */\n credentialExpiresAt: string;\n}\n\n/**\n * What the step container is asked to do — ONE phase of ONE execution.\n *\n * This is the whole of what leaves the control plane for a step, and it travels to the step\n * container over the DISPATCHER'S STDIN: not argv (readable in `ps`), not env (readable in\n * `docker inspect` and, on Container Apps, on the execution resource for anyone with Reader),\n * not a file (at rest for the life of the container). The same reasoning that keeps the\n * package work item's token unwritten (`package-work-item.port.ts`), applied one layer out.\n */\nexport interface RunnerStepInvocation {\n /** The discriminant. See {@link RUNNER_WORK_KINDS}. */\n kind: \"step\";\n protocolVersion: typeof RUNNER_PROTOCOL_VERSION;\n phase: PackagePhase;\n /** The catalog `connector_key` the step container selects its connector by. */\n connectorKey: string;\n actionKey: string;\n executionId: string;\n tenantId: string;\n /**\n * The user the run acts for. Carried for the same reason `PackageWorkItem.requestedBy` is:\n * the credential brokered at CLAIM must be minted in the name it would have been minted in at\n * dispatch. Deferring WHEN a token is issued must not quietly change WHO it is issued for.\n */\n requestedBy: string;\n correlationId: string;\n actionVersionId: string;\n scope: ResolvedConnectionScopeDto;\n subscriptionId: string;\n parameters: PackageJsonObject;\n dryRun: boolean;\n priorResult?: PackageJsonObject;\n /**\n * The credential, minted by the CONTROL PLANE exactly as it is for a hosted run and handed\n * over the authorized channel (docs/49 §4.4). Minted at CLAIM, not at authorization, so no\n * token is ever at rest waiting for a runner to come and get it.\n *\n * It is a token PER AUDIENCE, not one token. An Azure access token is audience-bound, so a\n * single opaque string would silently be the wrong token for any connector needing a second\n * resource — the silent-discard shape this codebase keeps finding. A connector that asks for\n * an audience this list does not carry is REFUSED by name (see the step's credential), which\n * is why `runnerExecution: \"supported\"` is a per-connector claim and not a global switch.\n */\n credential: RunnerStepCredential;\n}\n\nexport interface RunnerStepCredential {\n tokens: RunnerScopedToken[];\n}\n\nexport interface RunnerScopedToken {\n /** The AAD scope this token was minted for, e.g. `https://management.azure.com/.default`. */\n scope: string;\n token: string;\n /** Epoch millis. */\n expiresOnTimestamp: number;\n}\n\n/**\n * ═══ WHAT A PACKAGE CONTAINER IS ASKED TO DO — ONE PHASE, ON THE CUSTOMER'S OWN HOST ═════\n *\n * docs/60. A package does NOT execute in a step container and this is not a step invocation\n * with extra fields; it is the other arm of {@link RunnerInvocation}, and the difference is the\n * whole slice. The dispatcher starts TWO containers for one of these — an egress broker on a\n * network with no gateway, and the package runtime attached to that network only — so a\n * package's declared allowlist is the sole route out. That is what lets the `runner` isolation\n * answer `enforced` where Container Apps can only answer `cooperative`.\n *\n * ─── WHAT IS DELIBERATELY ABSENT, AND WHY EACH ABSENCE IS LOAD-BEARING ──────────────────\n *\n * · NO CONTROL-PLANE ORIGIN. No `url`, `host` or `callback` field — the same rule every shape\n * in this file obeys, and `runner-has-no-address.spec.ts` enforces it by name. The package\n * container needs one and the DISPATCHER has one: it long-polls a control plane on outbound\n * 443, which is the whole of docs/49. An origin the control plane SENT would be an address\n * travelling on a channel whose entire design is that no address does.\n *\n * · NO IMAGE. The package runtime image is pinned by the OPERATOR, in the install command they\n * pasted, exactly as the step image is. A control plane that named an image would be telling\n * a customer's host which bytes to execute at run time — a supply-chain decision that belongs\n * in a digest under review, not in a row.\n *\n * · NO RUNTIME, ENTRYPOINT, PARAMETERS OR CREDENTIAL ENTITLEMENT. All of that is in the work\n * item the container fetches for itself, unchanged since slice 6b-I. Copying any of it here\n * would be a second spelling of the package protocol on a second substrate — which is the one\n * thing docs/60 §5 says this design beats.\n */\nexport interface RunnerPackageInvocation {\n /** The discriminant. See {@link RUNNER_WORK_KINDS}. */\n kind: \"package\";\n protocolVersion: typeof RUNNER_PROTOCOL_VERSION;\n phase: PackagePhase;\n executionId: string;\n /**\n * ═══ THE ONE SECRET IN THIS SHAPE, AND WHY IT IS HERE RATHER THAN MINTED AT CLAIM ══════\n *\n * A single-use token authorizing exactly one work item: fetch these bytes, post this result,\n * once, expiring with the run. `StoredRunnerStepInvocation` deliberately carries NO\n * credential because an Azure token at rest is a standing key to a customer's subscription,\n * and that property is UNCHANGED here — a package's Azure credential is still brokered at\n * REDEMPTION and is written down nowhere.\n *\n * ★ WHAT THIS TOKEN IS WORTH IS ALREADY DECIDED, AND BY THE OTHER SUBSTRATE. The Container\n * Apps adapter puts this exact value into an ARM execution resource, where it is readable by\n * anyone holding Reader on the resource group for as long as that record lives — its own\n * comment says so. A row in Opera's own tenant-isolated database is a strictly narrower\n * audience than that, so treating the same value as unwritable here would be a rule this\n * product does not actually hold.\n *\n * *Beats:* minting it at claim, like the step credential. That requires the code that mints\n * to reach the package work-item store, which lives in another module — and the runners\n * module importing packages, while packages dispatches through the runners facade, is the\n * import CYCLE `.dependency-cruiser.cjs` forbids. A port would move the cycle rather than\n * remove it, since the implementation still has to be provided by one of the two.\n *\n * ⚠ AND ITS WINDOW IS CLOSED FROM BOTH ENDS. The adapter discards the work item in a\n * `finally`, so an authorization nobody claims leaves no redeemable item behind; redemption\n * is a single atomic statement, so a second redeemer fails the run loudly rather than\n * quietly succeeding beside it.\n */\n runToken: string;\n /**\n * The digest the container re-verifies the bytes it fetched against — travelling HERE and not\n * in the work item, for the reason slice 6b-I gives: both would have to be compromised for a\n * substituted artifact to run.\n */\n contentDigest: string;\n /**\n * The package's DECLARED allowlist, exactly as the approver was shown it.\n *\n * ★ IT IS THE DECLARATION, NEVER THE BROKER'S EFFECTIVE PERMIT SET. The broker additionally\n * permits the ONE origin this run's own protocol needs — the control plane the container\n * fetches and reports on — and the dispatcher adds that from its own configuration, where it\n * is visibly not part of what a package asked for. Merging the two here would widen an\n * allowlist a human read, silently, which is this codebase's house defect.\n */\n egressAllowlist: string[];\n}\n\n/**\n * The two arms of a claim, as a union TypeScript narrows on `kind`.\n *\n * ★ A DISPATCHER THAT HANDLES ONLY ONE DOES NOT COMPILE. That is the entire reason the tag is a\n * required field on both members rather than an optional one on the new member: an optional\n * discriminant would let a v1-shaped row parse as a step forever, which is exactly the silent\n * mis-read {@link RUNNER_PROTOCOL_VERSION} exists to turn into a named refusal.\n */\nexport type RunnerInvocation = RunnerStepInvocation | RunnerPackageInvocation;\n\n/**\n * ═══ WHAT THE RUNNER SAYS ABOUT A PACKAGE PHASE — WHICH IS NOT WHAT THE RUN CONCLUDED ════\n *\n * ★ THE TWO ANSWERS HAVE TWO OWNERS AND THIS IS THE SMALLER ONE. A package reports its own\n * result to the control plane through the callback it has spoken since slice 6b-I: the checks,\n * the outcome, the events, the egress denials. The RUNNER never sees any of that — it started\n * two containers and watched one exit. So its report answers only \"did the substrate run it\",\n * exactly as ARM's execution status does on the other substrate, and the adapter treats the\n * package's own posted result as authoritative wherever both exist.\n *\n * ★★ WHICH IS ALSO WHY IT IS A SEPARATE SHAPE RATHER THAN A {@link RunnerStepReport}. That type\n * is asymmetric on purpose — a `validate` report carries targets and checks and MUST NOT carry\n * an outcome, because \"an error-level check blocks the run\" is a decision the control plane\n * makes. A runner that had to fill that shape for a package's validate phase would have to\n * invent checks it never read. Reusing it would have meant either a lie or a fourth phase-shaped\n * special case in the parser.\n */\nexport interface RunnerPackageReport {\n protocolVersion: typeof RUNNER_PROTOCOL_VERSION;\n phase: PackagePhase;\n /**\n * `succeeded` means BOTH containers ran and the package container exited 0. It does NOT mean\n * the package succeeded — that is in the result the package posted for itself, and a package\n * can exit 0 having reported a failure.\n */\n status: \"succeeded\" | \"failed\";\n message: string;\n events: RunnerStepEvent[];\n}\n\n/**\n * The two report shapes.\n *\n * ⚠ NEITHER CARRIES A `kind`, AND THE ASYMMETRY WITH {@link RunnerInvocation} IS DELIBERATE.\n * The control plane TELLS a runner what kind of work it has, so the invocation must carry the\n * tag — the runner has no other way to know. Nothing works the other way: the server already\n * holds the authorization row, so it knows which shape it is entitled to, and letting a report\n * declare its own kind would be letting the far end choose which validator judges it.\n */\nexport type RunnerReport = RunnerStepReport | RunnerPackageReport;\n\n/** One structured log line the step streams; mirrors `ConnectorEvent` on the wire. */\nexport interface RunnerStepEvent {\n type: \"log\" | \"target_resolved\" | \"check\";\n level?: \"info\" | \"warn\" | \"error\" | \"success\";\n message: string;\n data?: PackageJsonObject;\n}\n\n/**\n * What the runner reports for one authorization.\n *\n * A `validate` report carries `targets` + `checks` and NO outcome; a `run`/`rollback` report\n * carries an outcome and neither. That asymmetry is deliberate: the rule \"an error-level check\n * blocks the run\" is a PLATFORM rule (`run-execution.handler.ts`), and it stays in the control\n * plane. A report that could carry both would let a runner validate and execute in one breath,\n * which is the second policy engine docs/45 D2 refuses and docs/49 §7 names.\n */\nexport interface RunnerStepReport {\n protocolVersion: typeof RUNNER_PROTOCOL_VERSION;\n phase: PackagePhase;\n /**\n * ⚠ A COUNT A RUNNER TOOK, NEVER AN ABSENCE (docs/66 §3.1). A runner runs the connector and\n * the connector counts or throws; \"we did not count, and why\" is a conclusion the CONTROL\n * PLANE draws about a call IT made, and there is no such call on this wire. The narrower type\n * is also what keeps this contract byte-identical for a runner built before docs/66.\n */\n targets?: TargetCounts;\n checks?: ValidationCheck[];\n outcome?: RunnerStepOutcome;\n events: RunnerStepEvent[];\n}\n\nexport interface RunnerStepOutcome {\n status: \"succeeded\" | \"failed\" | \"cancelled\";\n message: string;\n data?: PackageJsonObject;\n}\n\n/**\n * ═══ WHY A RUNNER'S OWN CREDENTIAL STOPPED WORKING (docs/53 §4.1) ══════════════════════\n *\n * revoked an operator revoked it. It is not coming back.\n * expired it sat idle past `RUNNER_CREDENTIAL_TTL_MS`. Also not coming back — a runner\n * away that long re-registers rather than resumes.\n * unknown the credential hashes to no row at all. Either it was never ours, or the POOL\n * it belonged to was deleted, which cascades the runner row away with it.\n *\n * ★ THE THIRD VALUE IS AN HONEST MERGE, NOT A LAZY ONE. Deleting a pool leaves nothing that\n * remembers this runner existed, so the server genuinely cannot tell a deleted pool from a\n * fabricated credential — and inventing a `pool-deleted` value it could never actually\n * return would be a state with no way to reach it. The RUNNER can say more than the server,\n * because it knows its credential once worked; its copy names all three possibilities.\n *\n * ⚠ AND THE CAUSE IS ONLY EVER NAMED TO A CALLER WHOSE CREDENTIAL HASHES TO A ROW, which is\n * a caller that has already proved possession. `RUNNER_REJECTED` deliberately says one\n * sentence for every failure, so a prober learns nothing; that argument covers the sentence\n * shown to somebody holding a value we do not recognise, and it does not cover the operator\n * on the host whose own runner just stopped. Naming `unknown` costs nothing (it is what a\n * prober gets), and naming `revoked` or `expired` requires having held the real secret.\n */\nexport type RunnerCredentialRefusal = \"revoked\" | \"expired\" | \"unknown\";\n\n/**\n * ═══ WHICH OF THE REPORT ROUTE'S TWO CREDENTIALS WAS NOT ACCEPTED ══════════════════════\n *\n * `POST /internal/runners/authorizations/:id/report` is the ONLY route a runner calls with two\n * secrets — the session credential says WHICH RUNNER, the authorization token says WHICH WORK —\n * so it is the only route where a 401 is ambiguous. It has two causes and they demand opposite\n * responses:\n *\n * runner this runner's session is over. Nothing it does next can work: HALT.\n * authorization this ROW will not take this result. The runner is healthy and its next\n * poll is fine: report the loss, keep working.\n *\n * ★ WITHOUT THIS FIELD THE RUNNER HAD TO GUESS, AND IT GUESSED \"HALT\" — which turned one bad\n * report into a dead host that claimed nothing until somebody noticed. Measured on the dev\n * estate 2026-08-25: a package that ran to `succeeded` in 28 seconds was refused because its\n * authorization's clock had started 5m32s before any runner existed, and the runner read that\n * refusal as its own revocation.\n *\n * ⚠ IT IS A SUBJECT, NOT A SEVERITY. The temptation is a boolean (`fatal`) — but \"fatal\" is the\n * runner's CONCLUSION, and the server is not entitled to it: the server knows which secret it\n * looked up and nothing about what the far end should do. Naming the subject leaves the decision\n * where the facts are, and it stays true if a third credential ever appears on this route.\n *\n * ⚠⚠ AND ITS ABSENCE IS NOT \"runner\". A control plane older than this field says nothing, and a\n * runner that read silence as revocation would reintroduce the defect against exactly the estate\n * most likely to hit it. Absent means UNKNOWN SUBJECT, and an unknown subject does not halt —\n * see {@link RUNNER_REFUSAL_SUBJECTS}. A genuinely revoked runner is still stopped within one\n * poll, because `GET /internal/runners/work` carries ONE credential and its 401 is unambiguous.\n */\nexport const RUNNER_REFUSAL_SUBJECTS = [\"runner\", \"authorization\"] as const;\nexport type RunnerRefusalSubject = (typeof RUNNER_REFUSAL_SUBJECTS)[number];\n\n/**\n * ═══ WHY AN AUTHORIZATION WOULD NOT ACCEPT A RESULT ════════════════════════════════════\n *\n * expired the row is real and this runner holds it, and its reporting window has closed.\n * unknown no row answers to (this id, this token, this runner). Never authorized, a token\n * that is not this row's, or a result for work another runner claimed.\n *\n * ★ `expired` IS NAMED SEPARATELY BECAUSE IT IS THE ONLY ONE AN OPERATOR CAN ACT ON, and\n * because it is the one that happens to a runner that did everything right. The others mean a\n * caller asked for something that was never theirs; this one means the work was theirs and the\n * clock beat them. A runner that cannot tell them apart reports \"the control plane refused me\"\n * for both, which is how an hour of live forensics starts.\n *\n * ⚠ IT COSTS A SECOND READ AND ONLY ON THE BRANCH THAT ALREADY FAILED — the same shape\n * `diagnoseRefusal` uses for a credential (docs/53 §4.1). It cannot change the answer, which was\n * \"no\" before it ran; it can only turn one sentence into the right one of two. And it is\n * reachable only by a caller that presented this row's own single-use token, so it discloses\n * nothing to anybody who was not already holding the secret.\n */\nexport const RUNNER_AUTHORIZATION_REFUSALS = [\"expired\", \"unknown\"] as const;\nexport type RunnerAuthorizationRefusal = (typeof RUNNER_AUTHORIZATION_REFUSALS)[number];\n\n/**\n * The 401 body the report route returns, for BOTH subjects.\n *\n * `refusal` keeps the place and the meaning it has had since docs/53 on the claim path, so a\n * reader of either route finds the cause in one field; `subject` says which credential that\n * cause is about. A caller that knows only the old shape still reads a correct `refusal` — it\n * simply cannot tell the two apart, which is the state this field exists to end.\n */\nexport interface RunnerReportRefusalDto {\n statusCode: 401;\n /** What a stranger is entitled to. One sentence for every failure. */\n message: string;\n /** What the operator on the host is entitled to, once they have proved possession. */\n detail: string;\n subject: RunnerRefusalSubject;\n refusal: RunnerCredentialRefusal | RunnerAuthorizationRefusal;\n}\n\n/**\n * ═══ THE POLL ANSWERS THREE THINGS, AND THE STATUS LINE CARRIES THE DIFFERENCE ═════════\n *\n * 200 here is work\n * 204 nothing right now — poll again\n * 403 you are still you, and you may not claim ← this\n * 401 your credential is not honoured at all ← {@link RunnerCredentialRefusal}\n *\n * ★ THE ASYMMETRY BETWEEN DRAIN AND REVOKE IS ON THE WIRE (docs/53 §4.3). A draining runner\n * is authenticated and trusted to finish what it holds, so it is refused with 403 — the\n * status that means \"understood, and refused anyway\". A revoked runner is not trusted at\n * all, so it never reaches this decision: `authenticateRunner` turns it away first, and it\n * gets 401. Drain is cooperative; revoke is not, and the two could not be told apart if\n * both arrived as the same status with a different word in the body.\n *\n * ⚠ 403 IS AN ANSWER, NOT AN ERROR, and the controller returns it rather than throwing for\n * that reason: this is the vocabulary a healthy standing-down runner speaks every 30\n * seconds, and routing it through an exception filter would file a normal operating state\n * under the same machinery as a bug.\n */\nexport type RunnerStandDownReason = \"draining\" | \"unsupported\";\n\n/**\n * The body of a 403. It carries the machine-readable reason AND the sentence, because the\n * two have different readers: the dispatcher branches on `reason`, and the sentence is what\n * lands in a customer's `docker logs` where nothing of ours is there to interpret it.\n */\nexport interface RunnerStandDownDto {\n reason: RunnerStandDownReason;\n message: string;\n}\n\n/**\n * What one poll came back with, as the dispatcher must handle it.\n *\n * ★ A DISCRIMINATED UNION SO THE DRAIN CANNOT BE IGNORED. S1's client returned\n * `RunnerWorkAuthorization | null`, and a third answer added to that shape would have been\n * `null` again — indistinguishable from \"nothing to do\", which is precisely the bug: a\n * drained runner would poll forever, cheerfully. With three arms, a dispatcher that does\n * not handle `stand-down` does not compile.\n */\nexport type RunnerClaimOutcome =\n | { kind: \"work\"; authorization: RunnerWorkAuthorization }\n | { kind: \"idle\" }\n | { kind: \"stand-down\"; standDown: RunnerStandDownDto };\n\n/**\n * A claimed work item — an AUTHORIZATION, not an instruction (docs/49 §4.3).\n *\n * Single-use, scoped to exactly one phase of one execution, with its own expiry. The runner\n * cannot widen it: the phase, the execution and the pool are all fixed on the server side,\n * and `token` opens nothing except this one row's result endpoint, once.\n */\nexport interface RunnerWorkAuthorization {\n protocolVersion: typeof RUNNER_PROTOCOL_VERSION;\n authorizationId: string;\n /**\n * Single-use. Minted at CLAIM and returned exactly once — before a runner claims, no token\n * for this row exists anywhere, so there is nothing at rest to steal.\n */\n token: string;\n /** ISO-8601. After this the control plane refuses the result, whatever the runner believes. */\n expiresAt: string;\n /** How long the runner should let the step run before giving up on it. */\n timeoutMs: number;\n invocation: RunnerInvocation;\n}\n","import type { RunnerScopedToken } from \"./runners\";\n\n/**\n * ═══ A CREDENTIAL MADE OF MINTED BYTES, AND NOTHING THAT CAN GET MORE (docs/49 §4.4) ═══════\n *\n * The credential a process runs under when it is not the control plane: the exact tokens the\n * control plane minted for it, per audience, and NOTHING it can use to get another. Two\n * processes hold one today, and both import THIS class:\n *\n * · a private runner's STEP CONTAINER (`apps/api/src/runner/step/execute-step.ts`) — a\n * different process on a different machine, handed tokens over the runner channel;\n * · an ENGINE ACTION (docs/128 §5) — `ctx.azure` in the action SDK, built only from the\n * tokens in its invocation.\n *\n * ★ WHY IT LIVES IN CONTRACTS (docs/128 Slice A). It was `src/runner/step/static-scoped-\n * credential.ts`, inside the api. The action SDK is a workspace package the api depends on, so it\n * cannot import from the api — by packaging, not by policy — and a second implementation in the\n * SDK is exactly the copy the slice forbids. `@runveric/contracts` is the one package both reach.\n *\n * It is structurally a `TokenCredential` — `getToken(scopes) → { token, expiresOnTimestamp }` —\n * so it can be handed to any Azure SDK client, and to the api's `AzureCredential` port, without\n * either type being imported here.\n *\n * ★ A HOLDER THAT OUTLIVES ITS TOKEN SAYS SO IN A SENTENCE. There is no refresh here by design —\n * the bytes are all there is — so an expired token is a dead end, and the honest thing is to end\n * at it by name rather than send it and let ARM answer 401 about \"an invalid authentication\n * token\". BEST-EFFORT, AND THAT IS WORTH SAYING: this fires only when the SDK asks again. One\n * that cached the token at the start of a long call still presents an expired one and still gets\n * Azure's 401 — this narrows the failure, it does not close it. What closes it is the holder's\n * deadline being far shorter than an AAD token's life (`RUNNER_STEP_TIMEOUT_MS` is 10 minutes; a\n * minted token has tens of minutes left).\n *\n * ★ AN AUDIENCE IT WAS NOT GIVEN IS A NAMED REFUSAL, NOT A NEAREST MATCH. Azure access tokens\n * are audience-bound: handing back the ARM token when code asks for Key Vault's data plane\n * would produce an authentication failure deep inside an SDK call, about a resource nobody\n * would think to look at. That is the silent-discard shape this codebase keeps finding, so the\n * answer is a sentence naming the scope that was asked for and the ones that exist.\n */\nexport class StaticScopedCredential {\n private readonly byScope: Map<string, RunnerScopedToken>;\n\n constructor(\n tokens: readonly RunnerScopedToken[],\n private readonly now: () => number = Date.now,\n /** Who holds these tokens — the subject of both refusals and where the fix lives. */\n private readonly holder: ScopedTokenHolder = RUNNER_STEP_TOKEN_HOLDER,\n ) {\n this.byScope = new Map(tokens.map((token) => [token.scope, token]));\n }\n\n async getToken(\n scopes: string | string[],\n ): Promise<{ token: string; expiresOnTimestamp: number }> {\n const requested = typeof scopes === \"string\" ? [scopes] : scopes;\n for (const scope of requested) {\n const token = this.byScope.get(scope);\n if (token) {\n if (token.expiresOnTimestamp <= this.now()) {\n throw new RunnerStepCredentialExpiredError(\n scope,\n token.expiresOnTimestamp,\n this.now(),\n this.holder,\n );\n }\n return { token: token.token, expiresOnTimestamp: token.expiresOnTimestamp };\n }\n }\n throw new RunnerStepCredentialError(requested, [...this.byScope.keys()], this.holder);\n }\n}\n\n/**\n * ═══ WHO HOLDS THE BYTES — THE ONLY THING THE TWO HOLDERS SAY DIFFERENTLY ═══════════════\n *\n * The rule is one; the sentence a person reads names the thing they have to fix, and that is\n * different for a runner's connector (its `azureAudiences`) and an engine action (its manifest's\n * `execution.audiences`). Everything else about the credential is shared.\n */\nexport interface ScopedTokenHolder {\n /** The subject of both refusals: `step`, `action`. */\n readonly noun: string;\n /** Where the audiences were declared — so where the fix is. A whole sentence. */\n readonly whereDeclared: string;\n /** Why no further token can be had. A whole sentence. */\n readonly whyNoMore: string;\n}\n\n/** A private runner's step container — the wording these refusals had before docs/128. */\nexport const RUNNER_STEP_TOKEN_HOLDER: ScopedTokenHolder = {\n noun: \"step\",\n whereDeclared:\n \"The channel mints exactly what a connector's azureAudiences declares, so this connector \" +\n \"reaches an Azure resource it does not say it reaches.\",\n whyNoMore:\n \"A step container is handed minted bytes and nothing it can use to get another, so the \" +\n \"step ran longer than its own credential and cannot continue.\",\n};\n\n/** An engine action's handler (docs/128 §5) — `ctx.azure`. */\nexport const ENGINE_ACTION_TOKEN_HOLDER: ScopedTokenHolder = {\n noun: \"action\",\n whereDeclared:\n \"The engine mints exactly the audiences an action's manifest declares in execution.audiences, \" +\n \"so this action reaches an Azure resource it does not say it reaches.\",\n whyNoMore:\n \"An action is handed minted bytes and nothing it can use to get another, so it ran longer \" +\n \"than its own credential and cannot continue.\",\n};\n\n/**\n * ═══ NOT A FACT ABOUT THE RESOURCE — THE MARKER BOTH REFUSALS CARRY ═════════════════════\n *\n * MEASURED, not imagined (docs/50). Declaring `azure.keyvault.rotateSecret` as reaching ARM and\n * driving it on a real runner produced a step whose credential refused BY NAME — and the\n * connector's own tolerant catch turned that sentence into \"it may be disabled\", after which a\n * dry run reported SUCCESS. A connector's \"the resource might not be there\" probe tests for this\n * marker (`isStepCredentialFailure`) so it never swallows a credential refusal.\n *\n * A boolean marker rather than an `instanceof`: the code that checks it runs on both sides of\n * the channel, and coupling it to a class identity would couple it to one copy of a module.\n */\nexport const STEP_CREDENTIAL_FAILURE = \"runvericStepCredentialFailure\" as const;\n\n/**\n * Code reaching for an audience this credential did not carry.\n *\n * Since docs/50 the channel mints exactly what a connector's `azureAudiences` declares (and since\n * docs/128 the engine mints exactly what an action's manifest declares), so this no longer means\n * \"the channel cannot carry it\" — it means THE CODE ASKED FOR SOMETHING IT DID NOT DECLARE. That\n * is a smaller and more specific mistake, and the message says so, because the fix is one line\n * in a declaration rather than work on the channel.\n */\nexport class RunnerStepCredentialError extends Error {\n constructor(\n requested: readonly string[],\n available: readonly string[],\n holder: ScopedTokenHolder = RUNNER_STEP_TOKEN_HOLDER,\n ) {\n super(\n `This ${holder.noun} was authorized for ${available.length > 0 ? available.map(quote).join(\", \") : \"no scopes\"} ` +\n `and asked for ${requested.map(quote).join(\", \")}. ${holder.whereDeclared}`,\n );\n this.name = \"RunnerStepCredentialError\";\n }\n /** Not a fact about the resource — see {@link STEP_CREDENTIAL_FAILURE}. */\n readonly [STEP_CREDENTIAL_FAILURE] = true;\n}\n\n/**\n * The holder ran longer than the credential it was handed. Distinct from the refusal above: the\n * audience was right, and the clock is what ran out.\n */\nexport class RunnerStepCredentialExpiredError extends Error {\n constructor(\n scope: string,\n expiresOnTimestamp: number,\n now: number,\n holder: ScopedTokenHolder = RUNNER_STEP_TOKEN_HOLDER,\n ) {\n super(\n `This ${holder.noun}'s token for ${quote(scope)} expired ${Math.round((now - expiresOnTimestamp) / 1_000)}s ago, ` +\n `at ${new Date(expiresOnTimestamp).toISOString()}. ${holder.whyNoMore}`,\n );\n this.name = \"RunnerStepCredentialExpiredError\";\n }\n /** Not a fact about the resource — see {@link STEP_CREDENTIAL_FAILURE}. */\n readonly [STEP_CREDENTIAL_FAILURE] = true;\n}\n\nfunction quote(scope: string): string {\n return `\"${scope}\"`;\n}\n","// ═══ THE ACTION CONTRACT — `runveric.dev/action-protocol/v1` (docs/128 §4) ══════════════════\n//\n// The messages between the engine and an action runtime. An engine action is an image built in\n// its own repository; the engine runs it in an isolated job and talks to it through THIS — the\n// invocation the runtime fetches once, and the events, the checkpoint and the report it posts\n// back. Every message is PARSED by a function in this file, never cast, on whichever side\n// receives it: the runtime parses the invocation and the checkpoint's acknowledgement; the\n// engine parses everything else.\n//\n// ★ IT IS runner-channel v2 GENERALISED, NOT A NEW INVENTION (docs/128 §4.1). The same token\n// model (short-lived bytes per audience, minted at the moment of use), the same asymmetry (a\n// validate report carries checks and never a success), and the same rule: the engine parses\n// everything and decides what it means. The one check parser both channels use is\n// `validationCheckOf` in `./validation`.\n//\n// ⚠ THE PHASE IS SPELLED `run`, NOT `execute` — a deliberate departure from docs/128 §4.1's\n// sketch. The lifecycle is declared ONCE, as `PACKAGE_PHASES` (`validate`, `run`, `rollback`),\n// whose own comment refuses a second name for that closed set; runner-channel v2 already carries\n// `run` on the wire. The HANDLER an author writes is still called `execute`, exactly as\n// `ActionConnector.execute` runs the `run` phase today.\n//\n// ★ WHAT THE ENGINE NEVER DELEGATES (docs/128 §4.2) IS NOT IN THESE SHAPES AT ALL. A report\n// carries facts — checks per target, or an outcome — and cannot carry a settled level, an\n// answered decision or an approval: there is no field to put one in. `settleDecisionChecks`\n// runs in the engine on every report.\n\nimport { ACTION_PROTOCOL_V1 } from \"./wire-identity\";\nimport type { DecisionsInHand, RecordedDecision } from \"./decisions\";\nimport type {\n PackageJsonObject,\n PackageJsonValue,\n PackagePhase,\n PackageResultStatus,\n} from \"./package-execution\";\nimport { PACKAGE_PHASES } from \"./package-execution\";\nimport type { RunnerStepEvent } from \"./runners\";\nimport { isDecisionCode, validationCheckOf, type ValidationCheck } from \"./validation\";\n\n// ─── §4.3 WHICH CONTRACTS THIS ENGINE SPEAKS ────────────────────────────────────────────\n\n/**\n * The contracts this engine speaks, array-first (charter §4.2). A manifest declaring any other\n * is refused at plan, pin and sync; a runtime handed any other refuses the invocation. A new\n * contract version ships BESIDE the old one and the old one stays for at least twelve months\n * after (docs/128 §4.3) — so this list grows, and a member leaves it only on that clock.\n */\nexport const ACTION_CONTRACTS = [ACTION_PROTOCOL_V1] as const;\nexport type ActionContract = (typeof ACTION_CONTRACTS)[number];\n\nexport function isActionContract(value: unknown): value is ActionContract {\n return typeof value === \"string\" && (ACTION_CONTRACTS as readonly string[]).includes(value);\n}\n\n/**\n * ═══ ⛔ THE ENGINE'S CONNECTOR KEY — A COLUMN VALUE, AND AN AUTHORED ONE ════════════════\n *\n * One generic connector dispatches every engine action (docs/128 §6): a manifest saying\n * `execution.kind: engine` names this key, and a manifest naming this key says\n * `execution.kind: engine` — the catalog validator refuses either half without the other.\n * `action_definition.connector_key` holds it, and `ConnectorRegistry.get()` throws on a key it\n * does not know, so it is as frozen as `PACKAGE_RUNNER_CONNECTOR_KEY`.\n */\nexport const ENGINE_CONNECTOR_KEY = \"runveric.engine\";\n\n/**\n * How an action version is executed. ABSENT means a built-in: its `connectorKey` names\n * TypeScript in the api image (docs/128 §3). Array-first so a second kind is a deliberate edit.\n */\nexport const ACTION_EXECUTION_KINDS = [\"engine\"] as const;\nexport type ActionExecutionKind = (typeof ACTION_EXECUTION_KINDS)[number];\n\n/** The `execution` block of an engine action's manifest (docs/128 §6). */\nexport interface EngineExecutionDeclaration {\n kind: ActionExecutionKind;\n /**\n * The contract the action DECLARES — a string, not an {@link ActionContract}, because a\n * declaration can name one this engine does not speak; every reader judges it with\n * {@link isActionContract} (the manifest validator, and the engine before it runs anything).\n */\n contract: string;\n /** `host:port` — the ONLY destinations the job may reach. */\n egress: string[];\n /** https origins — the token audiences the action needs. */\n audiences: string[];\n}\n\n// ─── THE LIMITS, DECLARED ONCE ──────────────────────────────────────────────────────────\n\n/**\n * ═══ HOW MUCH AN ACTION MAY SAY — DECLARED ONCE (docs/128 §4.1, §10 T5) ═════════════════\n *\n * The engine copies these into every invocation and parses every message against ITS OWN copy\n * — never against limits an action claims. An action that exceeds one has sent a malformed\n * message, and a malformed message is a failed run.\n */\nexport const ACTION_PROTOCOL_LIMITS = {\n maxEvents: 500,\n maxEventBytes: 2_048,\n maxReportBytes: 262_144,\n maxRestorePointBytes: 65_536,\n} as const;\n\n/**\n * At most this many targets in ONE plan-mode validate: one job checks a whole fan-out step\n * (docs/128 §4.1). The same 200 a fan-out step may resolve to (`QUOTA_MAX_TARGETS_PER_RUN`'s\n * default), so a step the platform admits is a step one invocation can check.\n */\nexport const MAX_PLAN_VALIDATE_TARGETS = 200;\n\n// ─── THE JOB AND ITS CALLBACK (docs/128 §18.4, §18.7) ───────────────────────────────────\n\n/**\n * ═══ WHAT AN ACTION'S JOB IS GIVEN — EXACTLY FOUR VARIABLES, NAMED ONCE ═══════════════════\n *\n * The runtime's entrypoint reads these and nothing else; an executor sets these and nothing else.\n * A run token, where to spend it, which run it is for, and which image this is — no credential and\n * no parameter, because everything else is in the invocation the token redeems (docs/128 E2, R9).\n *\n * ★ `runId`, NOT `executionId` — a departure from docs/128 §18.7, measured. The job serves one\n * ENGINE RUN (one phase), and a plan's checks have no execution at all: `preview` and a fan-out's\n * per-target checks run the connector before any execution row exists\n * (`execution.service.ts`, `PLAN_PREVIEW_EXECUTION_ID`). An execution id could not address them.\n *\n * ★ `imageDigest` IS A CROSS-CHECK, as the package runner's content digest is: the runtime refuses\n * an invocation whose image is not `…@<imageDigest>`, so the engine and the executor would both\n * have to be wrong for an invocation to run under another image.\n *\n * ⚠ NAMES OF THEIR OWN. The package runner's container contract (`PACKAGE_CONTAINER_ENV`) is another\n * image's start-up contract; sharing a name would tie a rename of one to the other.\n */\nexport const ACTION_CONTAINER_ENV = {\n runToken: \"RUNVERIC_ACTION_RUN_TOKEN\",\n callbackBaseUrl: \"RUNVERIC_ACTION_CALLBACK_BASE_URL\",\n runId: \"RUNVERIC_ACTION_RUN_ID\",\n imageDigest: \"RUNVERIC_ACTION_IMAGE_DIGEST\",\n} as const;\n\n/**\n * ═══ THE RUNTIME'S PROBE MODE — FOR AN OPERATOR, NEVER FOR A RUN (docs/128 §19.2 F10) ════════════\n *\n * `node /runtime/main.js --probe` answers, in labels only, what the sandbox lets the image's code do:\n * whether an identity endpoint exists and what a token request for each identity answers (its HTTP\n * status — never a token), what the egress proxy says to two CONNECTs, and whether the callback origin\n * answers. It needs only `ACTION_CONTAINER_ENV.callbackBaseUrl`; the identities to ask about are a\n * comma-separated list of resource ids (or client ids) in `ACTION_PROBE_ENV.identities`.\n *\n * ⚠ DECLARED HERE, AND OWNED BY THE SAME CENSUS FAMILY AS `ACTION_CONTAINER_ENV`, because a bare\n * `RUNVERIC_` value has claimed new names silently twice (§17.13, §18.12). The executor's own recipe\n * never sets it: only `pnpm engine:probe` adds it, with the flag.\n */\nexport const ACTION_RUNTIME_PROBE_FLAG = \"--probe\";\nexport const ACTION_PROBE_ENV = {\n identities: \"RUNVERIC_PROBE_IDENTITIES\",\n} as const;\n\n/**\n * The engine's callback for one run: `<callback>/internal/engine-runs/<runId>/<message>`. Declared\n * once, because the controller that answers and the runtime that asks are built apart — the second\n * in an image published from this repository and run in someone else's job.\n */\nexport const ENGINE_RUN_ROUTES = {\n base: \"internal/engine-runs\",\n invocation: \"invocation\",\n events: \"events\",\n checkpoint: \"checkpoint\",\n report: \"report\",\n} as const;\n\nexport type EngineRunMessage = Exclude<keyof typeof ENGINE_RUN_ROUTES, \"base\">;\n\n/** The URL one message of one run is sent to. */\nexport function engineRunUrl(callbackBaseUrl: string, runId: string, message: EngineRunMessage): string {\n const origin = callbackBaseUrl.replace(/\\/+$/, \"\");\n return `${origin}/${ENGINE_RUN_ROUTES.base}/${encodeURIComponent(runId)}/${ENGINE_RUN_ROUTES[message]}`;\n}\n\nexport interface ActionLimits {\n /** ISO-8601. The runtime aborts the handler's signal here. */\n deadline: string;\n maxEvents: number;\n maxEventBytes: number;\n maxReportBytes: number;\n maxRestorePointBytes: number;\n}\n\n// ─── THE SHAPES (docs/128 §4.1) ─────────────────────────────────────────────────────────\n\n/** One target: the resource it names, and its parameters (validated against the pinned schema). */\nexport interface ActionTarget {\n ref: string;\n parameters: PackageJsonObject;\n}\n\n/**\n * One minted token. The AUDIENCE is the resource (`https://management.azure.com`), never a scope\n * string: a runtime turns it into the scope an Azure SDK asks for with {@link actionTokenScope}.\n */\nexport interface ActionToken {\n audience: string;\n token: string;\n /** ISO-8601. */\n expiresOn: string;\n}\n\n/** The decisions a run carries — always a run's, never a plan's. */\nexport type RunDecisions = Extract<DecisionsInHand, { phase: \"run\" }>;\n\ninterface ActionInvocationBase {\n protocol: ActionContract;\n /** `image` is addressed by DIGEST, always — nothing resolves a tag at run time (docs/128 §13.2). */\n action: { key: string; version: string; image: string };\n execution: { id: string; tenantId: string; correlationId: string; dryRun: boolean };\n targets: ActionTarget[];\n credentials: { tokens: ActionToken[] };\n limits: ActionLimits;\n}\n\n/**\n * ★ `mode` AND `decisions.phase` ARE THE SAME FACT, AND THE PARSER REFUSES THEM DISAGREEING.\n * docs/128 §4.1 carries both; the mode is what an author's handler branches on, the decisions\n * are what it may read. A plan-mode validate with recorded decisions — or a run-mode one asking\n * — is a message no engine of ours builds.\n */\nexport interface ValidateInvocation extends ActionInvocationBase {\n phase: \"validate\";\n mode: DecisionsInHand[\"phase\"];\n decisions: DecisionsInHand;\n restorePoint: null;\n priorResult: null;\n}\n\n/** The act. Carries the restore point its predecessor made durable, on a redelivery. */\nexport interface RunInvocation extends ActionInvocationBase {\n phase: \"run\";\n decisions: RunDecisions;\n restorePoint: PackageJsonObject | null;\n priorResult: null;\n}\n\n/** The inverse. Restores from the restore point the act recorded, and nothing else. */\nexport interface RollbackInvocation extends ActionInvocationBase {\n phase: \"rollback\";\n decisions: RunDecisions;\n restorePoint: PackageJsonObject | null;\n priorResult: PackageJsonObject | null;\n}\n\nexport type ActionInvocation = ValidateInvocation | RunInvocation | RollbackInvocation;\n\n/** The level of an event — the vocabulary every run event already uses. */\nexport type ActionEventLevel = NonNullable<RunnerStepEvent[\"level\"]>;\n\nexport interface ActionEvent {\n level: ActionEventLevel;\n message: string;\n data?: PackageJsonObject;\n}\n\n/**\n * Sent BEFORE the first destructive call. The engine makes the record durable on the run and\n * only THEN acknowledges; without the acknowledgement the handler must not act (docs/128 §4.1).\n */\nexport interface ActionCheckpoint {\n kind: \"restore_point\";\n record: PackageJsonObject;\n}\n\n/** The engine's answer to a checkpoint — sent only after the record is durable. */\nexport interface CheckpointAck {\n acknowledged: true;\n}\n\nexport interface ActionOutcome {\n status: PackageResultStatus;\n message: string;\n data?: PackageJsonObject;\n}\n\n/**\n * The report, as a runtime SENDS it. A validate report answers with checks keyed by target ref —\n * or, when the checks could not run at all, with a FAILED outcome and nothing else; a run or\n * rollback report answers with an outcome. A validate report can never claim success.\n */\nexport type ActionReport =\n | { phase: \"validate\"; checks: Record<string, ValidationCheck[]> }\n | { phase: \"validate\"; outcome: ActionOutcome & { status: \"failed\" } }\n | { phase: \"run\" | \"rollback\"; outcome: ActionOutcome };\n\n/** One target's checks, as the engine READ them — in the order the invocation listed targets. */\nexport interface TargetChecks {\n ref: string;\n checks: ValidationCheck[];\n}\n\n/** The report, as the engine READ it. */\nexport type ParsedActionReport =\n | { readonly phase: \"validate\"; readonly checks: readonly TargetChecks[] }\n | { readonly phase: PackagePhase; readonly outcome: ActionOutcome };\n\n// ─── THE RULES SHARED WITH THE MANIFEST ─────────────────────────────────────────────────\n\n/**\n * ═══ WHAT AN AUDIENCE IS — ONE RULE, FOR THE MANIFEST AND THE WIRE ══════════════════════\n *\n * An https origin, lowercase, with no port, path or trailing slash: `https://management.azure.com`.\n * One spelling per resource, because the engine matches a declared audience to the token it\n * mints by equality — two spellings of one resource would be two audiences, and the second would\n * be refused at mint for a reason nobody could see in the manifest.\n *\n * `null` when it is one; otherwise the sentence the refusal says.\n */\nexport function actionAudienceRefusal(value: unknown): string | null {\n if (typeof value === \"string\" && AUDIENCE_ORIGIN.test(value)) return null;\n return (\n `\"${String(value)}\" is not an audience. An audience is the https origin of the resource a ` +\n `token is for — lowercase, with no port, path or trailing slash, e.g. \"https://management.azure.com\".`\n );\n}\n\nconst AUDIENCE_ORIGIN =\n /^https:\\/\\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;\n\n/**\n * The AAD scope a token for this audience is minted for and an Azure SDK asks for: the resource's\n * `/.default`. One derivation, so the engine's mint and the runtime's credential agree on which\n * scope a token answers.\n */\nexport function actionTokenScope(audience: string): string {\n return `${audience}/.default`;\n}\n\n/** What a redacted secret reads as, wherever it was found. */\nexport const REDACTED_SECRET = \"[redacted]\";\n\n/**\n * ═══ EVERY TOKEN VALUE OUT OF A MESSAGE — EXACT MATCH, EVERYWHERE IN IT (docs/128 §10 T3) ══\n *\n * Applied twice — by the runtime before it sends, and by the engine after it parses — so an\n * action that formats a token into an event, a check title or an outcome never puts it in a\n * run's record. EXACT MATCH: each token's whole value is replaced wherever it occurs inside a\n * string or a key; nothing is pattern-guessed, so nothing that is not a token is touched.\n */\nexport function redactSecrets<T>(value: T, secrets: readonly string[]): T {\n const present = secrets.filter((secret) => secret.length > 0);\n if (present.length === 0) return value;\n return mapStrings(value, (text) =>\n present.reduce((out, secret) => out.split(secret).join(REDACTED_SECRET), text),\n );\n}\n\n/**\n * ═══ WHAT A JWT LOOKS LIKE — THE ONE PATTERN, DECLARED ONCE (docs/128 §18.2 E3) ═════════════\n *\n * Three base64url segments joined by dots, the first starting `eyJ` — which is `{\"` encoded, the\n * opening of every JWT header. Azure's access tokens are exactly this shape.\n *\n * ★ WHY A SHAPE AT ALL, BESIDE {@link redactSecrets}' EXACT MATCH. Since Slice B.2 the engine\n * judges each message in whichever api replica receives it, from the stored run, and the tokens\n * minted at redemption are written nowhere — so the engine no longer HOLDS the values to match.\n * What it can still recognise is the shape. The runtime, which does hold them, keeps redacting by\n * exact value; the engine redacts by shape, and refuses a restore point that carries one.\n *\n * ⚠ IT OVER-MATCHES ON PURPOSE. A signature segment may be empty (an unsigned token is still a\n * token), and nothing tries to decode the segments: a string that merely looks like a JWT is\n * replaced, which costs a log line its value and never leaks a credential.\n *\n * Not global: a global `RegExp` carries `lastIndex` between calls. The functions below build the\n * global copy they need.\n */\nexport const JWT_SHAPE = /eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]*/;\n\n/** Every JWT-shaped string in a message, replaced — in values and in keys, everywhere in it. */\nexport function redactJwtShaped<T>(value: T): T {\n const everyMatch = new RegExp(JWT_SHAPE.source, \"g\");\n return mapStrings(value, (text) => text.replace(everyMatch, REDACTED_SECRET));\n}\n\n/** Whether any string in a message — a value or a key — is JWT-shaped. */\nexport function carriesJwtShaped(value: unknown): boolean {\n let found = false;\n mapStrings(value, (text) => {\n found ||= JWT_SHAPE.test(text);\n return text;\n });\n return found;\n}\n\n/** The one walk every redaction takes: each string value and each key, through `scrub`. */\nfunction mapStrings<T>(value: T, scrub: (text: string) => string): T {\n const walk = (node: unknown): unknown => {\n if (typeof node === \"string\") return scrub(node);\n if (Array.isArray(node)) return node.map(walk);\n if (node !== null && typeof node === \"object\") {\n return Object.fromEntries(Object.entries(node).map(([key, item]) => [scrub(key), walk(item)]));\n }\n return node;\n };\n return walk(value) as T;\n}\n\n/** The serialized size of a JSON value, in UTF-8 bytes — what the wire would carry. */\nexport function jsonByteLength(value: unknown): number {\n const text = JSON.stringify(value) ?? \"\";\n let bytes = 0;\n for (const char of text) {\n const point = char.codePointAt(0) ?? 0;\n bytes += point < 0x80 ? 1 : point < 0x800 ? 2 : point < 0x10000 ? 3 : 4;\n }\n return bytes;\n}\n\n// ─── THE PARSERS — ONE PER MESSAGE ──────────────────────────────────────────────────────\n\n/** A message that does not match the contract. A malformed message is a failed run. */\nexport class ActionProtocolError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ActionProtocolError\";\n }\n}\n\n/**\n * The invocation, as a RUNTIME reads it — and as the engine checks what it built before sending,\n * so the engine cannot send what a runtime would refuse.\n *\n * ★ THE TARGET COUNT IS PART OF THE CONTRACT. A plan-mode validate checks 1 to\n * {@link MAX_PLAN_VALIDATE_TARGETS} targets in one job; a run-mode validate, a run and a rollback\n * act on exactly ONE — breadth is an Operation's fan-out, never an invocation's.\n */\nexport function parseActionInvocation(body: unknown): ActionInvocation {\n const raw = objectOf(body, \"The invocation\");\n onlyKeys(raw, INVOCATION_KEYS, \"The invocation\");\n\n if (!isActionContract(raw.protocol)) {\n throw new ActionProtocolError(\n `The invocation speaks ${String(raw.protocol)}, and this runtime speaks ${ACTION_CONTRACTS.join(\", \")}.`,\n );\n }\n const phase = raw.phase;\n if (typeof phase !== \"string\" || !(PACKAGE_PHASES as readonly string[]).includes(phase)) {\n throw new ActionProtocolError(`An invocation phase of \"${String(phase)}\" is not in the vocabulary.`);\n }\n\n const actionRaw = objectOf(raw.action, \"The invocation's action\");\n onlyKeys(actionRaw, [\"key\", \"version\", \"image\"], \"The invocation's action\");\n const action = {\n key: nonEmpty(actionRaw.key, \"The action's key\"),\n version: nonEmpty(actionRaw.version, \"The action's version\"),\n image: digestPinned(actionRaw.image),\n };\n\n const executionRaw = objectOf(raw.execution, \"The invocation's execution\");\n onlyKeys(executionRaw, [\"id\", \"tenantId\", \"correlationId\", \"dryRun\"], \"The invocation's execution\");\n if (typeof executionRaw.dryRun !== \"boolean\") {\n throw new ActionProtocolError(\"The invocation's execution must say whether it is a dry run.\");\n }\n const execution = {\n id: nonEmpty(executionRaw.id, \"The execution's id\"),\n tenantId: nonEmpty(executionRaw.tenantId, \"The execution's tenant\"),\n correlationId: nonEmpty(executionRaw.correlationId, \"The execution's correlation id\"),\n dryRun: executionRaw.dryRun,\n };\n\n const limits = parseLimits(raw.limits);\n const decisions = parseDecisions(raw.decisions);\n const targets = parseTargets(raw.targets);\n const credentials = { tokens: parseTokens(objectOf(raw.credentials, \"The invocation's credentials\")) };\n const restorePoint = nullableObject(raw.restorePoint, \"The invocation's restore point\");\n const priorResult = nullableObject(raw.priorResult, \"The invocation's prior result\");\n if (restorePoint !== null && jsonByteLength(restorePoint) > limits.maxRestorePointBytes) {\n throw new ActionProtocolError(\n `The invocation's restore point is larger than ${limits.maxRestorePointBytes} bytes.`,\n );\n }\n\n const base = { protocol: raw.protocol, action, execution, targets, credentials, limits };\n\n if (phase === \"validate\") {\n if (raw.mode !== \"plan\" && raw.mode !== \"run\") {\n throw new ActionProtocolError(`A validate invocation's mode of \"${String(raw.mode)}\" is not \"plan\" or \"run\".`);\n }\n if (raw.mode !== decisions.phase) {\n throw new ActionProtocolError(\n `A validate invocation in ${raw.mode} mode carries ${decisions.phase}-phase decisions; the two are the same fact.`,\n );\n }\n assertTargetCount(targets.length, raw.mode === \"plan\" ? MAX_PLAN_VALIDATE_TARGETS : 1, `A ${raw.mode}-mode validate`);\n if (restorePoint !== null || priorResult !== null) {\n throw new ActionProtocolError(\"A validate invocation carries no restore point and no prior result.\");\n }\n return { ...base, phase, mode: raw.mode, decisions, restorePoint: null, priorResult: null };\n }\n\n if (raw.mode !== undefined) {\n throw new ActionProtocolError(`A ${phase} invocation has no mode — only a validate is asked in a mode.`);\n }\n if (decisions.phase !== \"run\") {\n throw new ActionProtocolError(`A ${phase} invocation carries a run's decisions, never a plan's.`);\n }\n assertTargetCount(targets.length, 1, `A ${phase}`);\n if (phase === \"run\") {\n if (priorResult !== null) {\n throw new ActionProtocolError(\"A run invocation carries no prior result — only a rollback reads one.\");\n }\n return { ...base, phase, decisions, restorePoint, priorResult: null };\n }\n return { ...base, phase: \"rollback\", decisions, restorePoint, priorResult };\n}\n\n/**\n * One event, as the engine reads it. `alreadyReceived` is how many this run has accepted so far:\n * the count limit is a property of the run, so the caller holding the run holds the count.\n */\nexport function parseActionEvent(\n body: unknown,\n limits: ActionLimits,\n alreadyReceived: number,\n): ActionEvent {\n if (alreadyReceived >= limits.maxEvents) throw tooManyEvents(limits);\n const raw = objectOf(body, \"An event\");\n onlyKeys(raw, [\"level\", \"message\", \"data\"], \"An event\");\n if (jsonByteLength(raw) > limits.maxEventBytes) {\n throw new ActionProtocolError(`An event is larger than ${limits.maxEventBytes} bytes.`);\n }\n if (typeof raw.level !== \"string\" || !Object.hasOwn(EVENT_LEVELS, raw.level)) {\n throw new ActionProtocolError(`An event level of \"${String(raw.level)}\" is not in the vocabulary.`);\n }\n const message = nonEmpty(raw.message, \"An event's message\");\n if (raw.data === undefined) return { level: raw.level as ActionEventLevel, message };\n return { level: raw.level as ActionEventLevel, message, data: jsonObject(raw.data, \"An event's data\") };\n}\n\n/**\n * The count limit's refusal — ONE sentence, said by {@link parseActionEvent} when the caller's count\n * is already at the limit, and by the engine when its conditional increment lost the race to the\n * last slot (docs/128 §18.5): two replicas can both read 499 of 500, and only one may write.\n */\nexport function tooManyEvents(limits: Pick<ActionLimits, \"maxEvents\">): ActionProtocolError {\n return new ActionProtocolError(`The action sent more than ${limits.maxEvents} events.`);\n}\n\n/** The checkpoint, as the engine reads it — before it persists anything. */\nexport function parseActionCheckpoint(body: unknown, limits: ActionLimits): ActionCheckpoint {\n const raw = objectOf(body, \"A checkpoint\");\n onlyKeys(raw, [\"kind\", \"record\"], \"A checkpoint\");\n if (raw.kind !== \"restore_point\") {\n throw new ActionProtocolError(`A checkpoint of kind \"${String(raw.kind)}\" is not one this contract knows.`);\n }\n const record = jsonObject(raw.record, \"A checkpoint's record\");\n if (jsonByteLength(record) > limits.maxRestorePointBytes) {\n throw new ActionProtocolError(`A restore point is larger than ${limits.maxRestorePointBytes} bytes.`);\n }\n return { kind: \"restore_point\", record };\n}\n\n/** The engine's acknowledgement, as the runtime reads it. Anything else is no acknowledgement. */\nexport function parseCheckpointAck(body: unknown): CheckpointAck {\n const raw = objectOf(body, \"A checkpoint acknowledgement\");\n onlyKeys(raw, [\"acknowledged\"], \"A checkpoint acknowledgement\");\n if (raw.acknowledged !== true) {\n throw new ActionProtocolError(\"The checkpoint was not acknowledged.\");\n }\n return { acknowledged: true };\n}\n\n/**\n * The report, as the engine reads it — judged against the invocation the ENGINE sent, never\n * against anything the report says about itself.\n *\n * ★ EVERY TARGET ANSWERED, NONE INVENTED. A validate report's checks are keyed by exactly the\n * invocation's target refs: a target left out would read as \"nothing to say\" about a resource\n * nobody checked, and one added would be a verdict on a resource nobody asked about.\n */\nexport function parseActionReport(\n body: unknown,\n sent: Pick<ActionInvocation, \"phase\" | \"targets\" | \"limits\">,\n): ParsedActionReport {\n const raw = objectOf(body, \"The report\");\n onlyKeys(raw, [\"phase\", \"checks\", \"outcome\"], \"The report\");\n if (jsonByteLength(raw) > sent.limits.maxReportBytes) {\n throw new ActionProtocolError(`The report is larger than ${sent.limits.maxReportBytes} bytes.`);\n }\n if (raw.phase !== sent.phase) {\n throw new ActionProtocolError(\n `The report is for phase \"${String(raw.phase)}\", but this invocation is for \"${sent.phase}\".`,\n );\n }\n\n if (sent.phase === \"validate\") {\n if ((raw.checks === undefined) === (raw.outcome === undefined)) {\n throw new ActionProtocolError(\n \"A validate report carries checks, or — when they could not run — a failed outcome; exactly one of the two.\",\n );\n }\n if (raw.outcome !== undefined) {\n const outcome = parseOutcome(raw.outcome);\n if (outcome.status !== \"failed\") {\n throw new ActionProtocolError(\n `A validate report's outcome can only say the checks failed to run, never \"${outcome.status}\" — the engine decides what checks mean.`,\n );\n }\n return { phase: \"validate\", outcome };\n }\n const byRef = objectOf(raw.checks, \"A validate report's checks\");\n const expected = new Set(sent.targets.map((target) => target.ref));\n for (const ref of Object.keys(byRef)) {\n if (!expected.has(ref)) {\n throw new ActionProtocolError(`The report answers for \"${ref}\", which is not one of the targets it was given.`);\n }\n }\n const checks = sent.targets.map(({ ref }): TargetChecks => {\n if (!Object.hasOwn(byRef, ref)) {\n throw new ActionProtocolError(`The report says nothing about \"${ref}\", one of the targets it was given.`);\n }\n const list = byRef[ref];\n if (!Array.isArray(list)) {\n throw new ActionProtocolError(`The checks for \"${ref}\" must be an array.`);\n }\n return {\n ref,\n checks: list.map((entry) => {\n const parsed = validationCheckOf(entry);\n if (\"refusal\" in parsed) throw new ActionProtocolError(`The checks for \"${ref}\": ${parsed.refusal}`);\n return parsed.check;\n }),\n };\n });\n return { phase: \"validate\", checks };\n }\n\n if (raw.checks !== undefined) {\n throw new ActionProtocolError(\n `A ${sent.phase} report carries an outcome, never checks — those are the validate phase's answer.`,\n );\n }\n return { phase: sent.phase, outcome: parseOutcome(raw.outcome) };\n}\n\n// ─── THE PIECES ─────────────────────────────────────────────────────────────────────────\n\nconst INVOCATION_KEYS = [\n \"protocol\",\n \"action\",\n \"phase\",\n \"mode\",\n \"execution\",\n \"targets\",\n \"decisions\",\n \"restorePoint\",\n \"priorResult\",\n \"credentials\",\n \"limits\",\n] as const;\n\n/**\n * The event levels and outcome statuses, pinned to the types every run already uses. A `Record`\n * rather than an exported array: these are not new vocabularies, and a `Record` over the existing\n * union is a compile error the day that union grows.\n */\nconst EVENT_LEVELS: Record<ActionEventLevel, true> = { info: true, warn: true, error: true, success: true };\nconst OUTCOME_STATUSES: Record<PackageResultStatus, true> = { succeeded: true, failed: true, cancelled: true };\n\nfunction parseOutcome(value: unknown): ActionOutcome {\n if (value === undefined) {\n throw new ActionProtocolError(\"A run or rollback report must carry an outcome.\");\n }\n const raw = objectOf(value, \"An outcome\");\n onlyKeys(raw, [\"status\", \"message\", \"data\"], \"An outcome\");\n if (typeof raw.status !== \"string\" || !Object.hasOwn(OUTCOME_STATUSES, raw.status)) {\n throw new ActionProtocolError(`An outcome status of \"${String(raw.status)}\" is not in the vocabulary.`);\n }\n const status = raw.status as PackageResultStatus;\n const message = nonEmpty(raw.message, \"An outcome's message\");\n if (raw.data === undefined) return { status, message };\n return { status, message, data: jsonObject(raw.data, \"An outcome's data\") };\n}\n\nfunction parseLimits(value: unknown): ActionLimits {\n const raw = objectOf(value, \"The invocation's limits\");\n onlyKeys(\n raw,\n [\"deadline\", \"maxEvents\", \"maxEventBytes\", \"maxReportBytes\", \"maxRestorePointBytes\"],\n \"The invocation's limits\",\n );\n return {\n deadline: isoInstant(raw.deadline, \"The deadline\"),\n maxEvents: positiveInteger(raw.maxEvents, \"maxEvents\"),\n maxEventBytes: positiveInteger(raw.maxEventBytes, \"maxEventBytes\"),\n maxReportBytes: positiveInteger(raw.maxReportBytes, \"maxReportBytes\"),\n maxRestorePointBytes: positiveInteger(raw.maxRestorePointBytes, \"maxRestorePointBytes\"),\n };\n}\n\n/**\n * The decisions, read STRICTLY. `recordedDecisionsOf` drops what it cannot read, which is right\n * for a stored row (an unreadable decision was not made). On the wire the engine is the only\n * author, so an entry that does not parse is a malformed message, and an unknown code is refused.\n */\nfunction parseDecisions(value: unknown): DecisionsInHand {\n const raw = objectOf(value, \"The invocation's decisions\");\n if (raw.phase === \"plan\") {\n onlyKeys(raw, [\"phase\"], \"A plan's decisions\");\n return { phase: \"plan\" };\n }\n if (raw.phase !== \"run\") {\n throw new ActionProtocolError(`A decisions phase of \"${String(raw.phase)}\" is not \"plan\" or \"run\".`);\n }\n onlyKeys(raw, [\"phase\", \"recorded\"], \"A run's decisions\");\n if (!Array.isArray(raw.recorded)) {\n throw new ActionProtocolError(\"A run's decisions must carry the recorded list, even when it is empty.\");\n }\n const recorded: RecordedDecision[] = raw.recorded.map((entry) => {\n const decision = objectOf(entry, \"A recorded decision\");\n onlyKeys(decision, [\"code\", \"acknowledgedBy\", \"acknowledgedAt\"], \"A recorded decision\");\n if (!isDecisionCode(decision.code)) {\n throw new ActionProtocolError(`A recorded decision of \"${String(decision.code)}\" is not in the vocabulary.`);\n }\n return {\n code: decision.code,\n acknowledgedBy: nonEmpty(decision.acknowledgedBy, \"Who acknowledged a decision\"),\n acknowledgedAt: isoInstant(decision.acknowledgedAt, \"When a decision was acknowledged\"),\n };\n });\n if (new Set(recorded.map((decision) => decision.code)).size !== recorded.length) {\n throw new ActionProtocolError(\"A run's decisions record one code twice.\");\n }\n return { phase: \"run\", recorded };\n}\n\nfunction parseTargets(value: unknown): ActionTarget[] {\n if (!Array.isArray(value)) {\n throw new ActionProtocolError(\"The invocation's targets must be an array.\");\n }\n const targets = value.map((entry): ActionTarget => {\n const raw = objectOf(entry, \"A target\");\n onlyKeys(raw, [\"ref\", \"parameters\"], \"A target\");\n return {\n ref: nonEmpty(raw.ref, \"A target's ref\"),\n parameters: jsonObject(raw.parameters, \"A target's parameters\"),\n };\n });\n if (new Set(targets.map((target) => target.ref)).size !== targets.length) {\n throw new ActionProtocolError(\"The invocation names one target twice.\");\n }\n return targets;\n}\n\nfunction assertTargetCount(count: number, max: number, what: string): void {\n if (count < 1 || count > max) {\n throw new ActionProtocolError(\n max === 1\n ? `${what} acts on exactly one target; this invocation names ${count}.`\n : `${what} checks between 1 and ${max} targets; this invocation names ${count}.`,\n );\n }\n}\n\nfunction parseTokens(credentials: Record<string, unknown>): ActionToken[] {\n onlyKeys(credentials, [\"tokens\"], \"The invocation's credentials\");\n if (!Array.isArray(credentials.tokens)) {\n throw new ActionProtocolError(\"The invocation's credentials must carry a tokens array, even when it is empty.\");\n }\n const tokens = credentials.tokens.map((entry): ActionToken => {\n const raw = objectOf(entry, \"A token\");\n onlyKeys(raw, [\"audience\", \"token\", \"expiresOn\"], \"A token\");\n const refusal = actionAudienceRefusal(raw.audience);\n if (refusal !== null) throw new ActionProtocolError(refusal);\n return {\n audience: raw.audience as string,\n token: nonEmpty(raw.token, \"A token's value\"),\n expiresOn: isoInstant(raw.expiresOn, \"A token's expiry\"),\n };\n });\n if (new Set(tokens.map((token) => token.audience)).size !== tokens.length) {\n throw new ActionProtocolError(\"The invocation carries two tokens for one audience.\");\n }\n return tokens;\n}\n\n/** `registry/repository@sha256:<64 hex>` — and nothing a tag could move. */\nconst DIGEST_PINNED_IMAGE = /^[a-z0-9][a-z0-9._\\-/:]*@sha256:[0-9a-f]{64}$/;\n\nfunction digestPinned(value: unknown): string {\n if (typeof value !== \"string\" || !DIGEST_PINNED_IMAGE.test(value)) {\n throw new ActionProtocolError(\n `The action's image \"${String(value)}\" is not addressed by digest. Nothing on the execution ` +\n \"path resolves a tag (docs/128 §13.2).\",\n );\n }\n return value;\n}\n\nfunction objectOf(value: unknown, what: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ActionProtocolError(`${what} must be an object.`);\n }\n return value as Record<string, unknown>;\n}\n\n/** A field the contract does not name is refused by name, never silently dropped. */\nfunction onlyKeys(raw: Record<string, unknown>, allowed: readonly string[], what: string): void {\n for (const key of Object.keys(raw)) {\n if (!allowed.includes(key)) {\n throw new ActionProtocolError(`${what} carries \"${key}\", which this contract does not have.`);\n }\n }\n}\n\nfunction nonEmpty(value: unknown, what: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new ActionProtocolError(`${what} must be a non-empty string.`);\n }\n return value;\n}\n\nfunction positiveInteger(value: unknown, what: string): number {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 1) {\n throw new ActionProtocolError(`The limit \"${what}\" must be a positive integer.`);\n }\n return value;\n}\n\nfunction isoInstant(value: unknown, what: string): string {\n if (typeof value !== \"string\" || Number.isNaN(Date.parse(value))) {\n throw new ActionProtocolError(`${what} must be an ISO-8601 instant.`);\n }\n return value;\n}\n\nfunction nullableObject(value: unknown, what: string): PackageJsonObject | null {\n return value === null ? null : jsonObject(value, what);\n}\n\nfunction jsonObject(value: unknown, what: string): PackageJsonObject {\n if (!isJsonObject(value)) {\n throw new ActionProtocolError(`${what} must be a JSON object.`);\n }\n return value;\n}\n\nfunction isJsonObject(value: unknown): value is PackageJsonObject {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return false;\n return Object.values(value).every(isJsonValue);\n}\n\nfunction isJsonValue(value: unknown): value is PackageJsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (Array.isArray(value)) return value.every(isJsonValue);\n return isJsonObject(value);\n}\n","// ═══ HOW AN ENGINE ACTION'S IMAGE IS SIGNED, AND WHAT A VERSION RECORDS (docs/128 §17) ═══════\n//\n// An engine action runs an image built in its own repository. The platform runs it only when a\n// trusted key signed it — cosign v3's Sigstore bundle, key-signed, with no transparency log\n// (docs/128 §17.1 C2–C6) — and one verifier, ours, in Node, reads that bundle.\n//\n// ★ EVERY STRING THE VERIFIER COMPARES AGAINST IS DECLARED HERE, ONCE. They are SIGSTORE's and\n// in-toto's identifiers, not ours: we read them, we never choose them. Measured on the bundle\n// cosign v3.1.3 writes (`apps/api/test/fixtures/action-signature/`, produced by\n// `tools/action-signature-fixtures.sh`). A second spelling anywhere would be a second author of a\n// value another system defines — so every reader imports these.\n\nimport type { ActionCapabilities } from \"./catalog\";\n\n/** The bundle's own `mediaType`, and the OCI `artifactType` of the manifest that carries it (C3, C4). */\nexport const SIGSTORE_BUNDLE_MEDIA_TYPE = \"application/vnd.dev.sigstore.bundle.v0.3+json\";\n\n/** The DSSE envelope's `payloadType`: the payload is an in-toto statement (C4). */\nexport const DSSE_IN_TOTO_PAYLOAD_TYPE = \"application/vnd.in-toto+json\";\n\n/** The statement's `_type` (C5). */\nexport const IN_TOTO_STATEMENT_TYPE = \"https://in-toto.io/Statement/v1\";\n\n/** The statement's `predicateType` for a plain `cosign sign` (C5). Its predicate is `{}`. */\nexport const COSIGN_SIGN_PREDICATE_TYPE = \"https://sigstore.dev/cosign/sign/v1\";\n\n/**\n * The OCI image config label that says which repository an image was built in (docs/128 §17.4a).\n * The value it must hold is `actionSourceRepository(key)` (`./action-repository`).\n *\n * ⚠ THE SAME OCI KEY, ANOTHER CONCEPT: the CLI writes it as a MANIFEST ANNOTATION on every catalog\n * artifact (`action-cli/src/catalog/artifact.ts`), which GHCR reads to link a package to its\n * repository and nothing here reads. This one is an IMAGE LABEL the resolver reads and refuses on.\n */\nexport const IMAGE_SOURCE_LABEL = \"org.opencontainers.image.source\";\n\n/**\n * The OCI image config label that says which commit an image was built at (docs/128 §20 G3). It\n * must equal the artifact's `provenance.commit`: the image and the manifest it runs under come from\n * one commit. ⚠ The CLI writes the same key as a catalog-artifact ANNOTATION, as with\n * {@link IMAGE_SOURCE_LABEL}; this is the image LABEL the one rule reads (`./action-image`).\n */\nexport const IMAGE_REVISION_LABEL = \"org.opencontainers.image.revision\";\n\n/**\n * ═══ WHERE EVERY ENGINE ACTION'S SIGNATURE LIVES — ONE PACKAGE (docs/128 §20 G1) ═══════════════\n *\n * The catalog release workflow signs with `COSIGN_REPOSITORY` set to this, so cosign writes the\n * bundle here and never into the image's own repository (§20.1 Z4, measured again 2026-10-09: with\n * it set, the image repository's `sha256-<hex>` tag stays 404). Discovery asks THIS repository for\n * an image digest's signature; §17.4a still reads the image itself in the action's own package.\n *\n * ★ WHY ONE PACKAGE: an action repository's workflow token can push its own image, but nothing it\n * holds can write here — so a compromised action repository can publish an image and never a\n * signature for it (docs/128 §10 T1), and no package needs a per-repository grant.\n */\nexport const ACTION_SIGNATURE_REPOSITORY = \"ghcr.io/runveric/action-signatures\";\n\n/**\n * A verified Sigstore bundle, as a JSON value. Verification reads its FIELDS, and the signature\n * covers the decoded payload string, so storing it as jsonb — which reorders keys and drops\n * whitespace — loses nothing anyone checks (docs/128 §17.7).\n */\nexport type SigstoreBundleJson = { [field: string]: unknown };\n\n/**\n * ═══ WHAT ONE PUBLISHED ENGINE VERSION IS — ITS OWN FACTS, NEVER ITS DEFINITION'S (docs/128 §17.7) ═══\n *\n * The eight `action_version.engine_*` columns, all or none. A version's IDENTITY is\n * `(manifestSha256, imageDigest)`: the manifest fixes what it declares, the digest fixes the code,\n * and a release may never change either under one version string (D4). `capabilities` is the\n * manifest's block as this VERSION was published with it (D4a) — the definition row describes the\n * newest manifest, so an older pinned image never reads its rules from there.\n *\n * ⚠ SERVER-SIDE ONLY. `signature` is the stored bundle the engine re-verifies before every start;\n * nothing serialises an `ActionVersionContract` to a browser (docs/128 §17.6).\n */\nexport interface EngineVersionFacts {\n /** sha256 of the manifest's bytes, 64 lowercase hex — the lock's `manifestSha256`. */\n manifestSha256: string;\n /** The contract the manifest declares (`execution.contract`). */\n contract: string;\n /** `host:port` — the only destinations the job may reach. */\n egress: string[];\n /** https origins — the token audiences the action may be minted. */\n audiences: string[];\n /** The manifest's `capabilities` block, as this version was published. */\n capabilities: ActionCapabilities;\n /** The artifact's own repository, which holds the image (docs/128 D2). */\n imageRepository: string;\n /** `sha256:` and 64 lowercase hex — what runs, and what the signature binds. */\n imageDigest: string;\n /** The verified bundle, as stored. */\n signature: SigstoreBundleJson;\n}\n","// ═══ THE FOUR MANIFEST MEDIA TYPES A REGISTRY MAY ANSWER WITH — DECLARED ONCE (docs/128 §17.4a) ═══\n//\n// The OCI client asks for all four (its `Accept`), so an index is RECEIVED and refused by name\n// rather than missed by content negotiation; every reader then checks the type it actually got.\n// They are the OCI image specification's and Docker's, not ours.\n//\n// ★ IN CONTRACTS SINCE docs/128 §20 G3: the api's resolver and the CLI's `catalog verify-image` run\n// ONE rule over an engine action's image (`./action-image`), and that rule reads the last list below.\n// The api's fetcher, the resolver and the CLI's registry client all import these.\n\n/** One image (or artifact): config + layers. What every catalog artifact and every signature is. */\nexport const OCI_IMAGE_MANIFEST = \"application/vnd.oci.image.manifest.v1+json\";\n/** Docker's v2 schema 2 image manifest — what `docker push` writes for a single-platform image. */\nexport const DOCKER_IMAGE_MANIFEST = \"application/vnd.docker.distribution.manifest.v2+json\";\n/** A list of manifests: a multi-platform image, or the referrers of a subject. */\nexport const OCI_IMAGE_INDEX = \"application/vnd.oci.image.index.v1+json\";\n/** Docker's multi-platform list. */\nexport const DOCKER_MANIFEST_LIST = \"application/vnd.docker.distribution.manifest.list.v2+json\";\n\n/** Everything a manifest request may receive. */\nexport const MANIFEST_MEDIA_TYPES = [\n OCI_IMAGE_MANIFEST,\n DOCKER_IMAGE_MANIFEST,\n OCI_IMAGE_INDEX,\n DOCKER_MANIFEST_LIST,\n] as const;\n\n/** The two that address exactly ONE image — what an engine action's digest must name. */\nexport const IMAGE_MANIFEST_MEDIA_TYPES: readonly string[] = [OCI_IMAGE_MANIFEST, DOCKER_IMAGE_MANIFEST];\n","// ═══ AN ENGINE ACTION'S IMAGE — BUILT WHERE IT SAYS, AT THE COMMIT IT SAYS: ONE RULE (docs/128 §17.4a, §20 G3) ═══\n//\n// The signature binds a DIGEST, never a name (§17.1 C5). The digest covers the image manifest, the\n// manifest covers the config, and the config carries the labels — so the labels are signed, and\n// they are what binds an image to ONE action and ONE commit:\n//\n// the image digest addresses one image manifest, not an index (what Container Apps Jobs run)\n// its config says linux/amd64\n// its source label = https://github.com/runveric/<the action's repository> §17.4a — no replay\n// the artifact's provenance.repository = the same\n// its revision label = the artifact's provenance.commit §20 G3 — one commit\n//\n// ★ ONE FUNCTION, TWO CALLERS. The api's resolver runs it at plan, pin, sync and vendor; the CLI runs\n// it in `catalog publish-action --image` (before an artifact names an image) and in `catalog\n// verify-image` (before the catalog release workflow signs one). The CLI bundles THIS compiled code\n// (`action-cli/tsup.config.ts`), so the two cannot disagree about an image —\n// `action-image-rule-is-one-function.spec.ts` holds them to the same sentence for every refusal.\n//\n// ⚠ IT JUDGES DOCUMENTS, NOT BYTES. Each caller fetches by digest and refuses bytes that do not hash\n// to what it asked for, then parses them — that is transport, and this package has no crypto. What\n// is judged here is what the verified bytes SAY.\n\nimport { actionSourceRepository } from \"./action-repository\";\nimport { IMAGE_REVISION_LABEL, IMAGE_SOURCE_LABEL } from \"./action-signing\";\nimport { IMAGE_MANIFEST_MEDIA_TYPES } from \"./oci-media-types\";\n\n/**\n * Where the action runtime image is published (docs/128 §19.2 F9) — the repository\n * `tools/publish-action-runtime.mjs` pushes to.\n */\nexport const ACTION_RUNTIME_REPOSITORY = \"ghcr.io/runveric/action-runtime\";\n\n/**\n * ★ THE RUNTIME EVERY ENGINE ACTION IS BUILT `FROM`, BY DIGEST (docs/128 §19.6). Published by the\n * founder from `421267e1` (docs/131 Slice A: Node 24.21.0 on the declared `node-debian` base, whose\n * whole layer list is this image's first five) and verified anonymously by the architect:\n * linux/amd64, uid 65532, entrypoint `node /runtime/main.js`. Until docs/131 it was `0774c076…`, built\n * on node:20-bookworm-slim's last build (2026-04-22). The engine action publish workflow's\n * template is FILLED from this (`{{ACTION_RUNTIME_IMAGE}}`) by the tools that plant it — never typed.\n * Moving it is a deliberate per-action bump: a new digest here, then the sync tool's pull requests.\n */\nexport const ACTION_RUNTIME_IMAGE =\n `${ACTION_RUNTIME_REPOSITORY}@sha256:55126390dc54a79668e8475757f6de6dabc8c052242079d48d888eca4fdd5963`;\n\n/** An image manifest names one config and a handful of layers; more than this is not one of ours. */\nexport const MAX_IMAGE_MANIFEST_BYTES = 64 * 1024;\n\n/** What an action artifact says about where its manifest came from — the half of provenance the rule reads. */\nexport interface ActionImageProvenance {\n repository: string;\n commit: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * WHICH BLOB TO FETCH NEXT: the config descriptor of ONE image manifest, or `null` when the document\n * is not one (an index, a manifest of no declared type, a config that is not a descriptor).\n *\n * It judges nothing — {@link actionImageRefusal} says why a `null` is refused. It exists so a caller\n * never fetches a \"config\" out of an index, and never parses a manifest a second way to find one.\n */\nexport function imageConfigDescriptor(manifest: unknown): { digest: string; size: number } | null {\n if (!isRecord(manifest) || typeof manifest.mediaType !== \"string\") return null;\n if (!IMAGE_MANIFEST_MEDIA_TYPES.includes(manifest.mediaType) || manifest.schemaVersion !== 2) return null;\n const config = manifest.config;\n if (!isRecord(config) || typeof config.digest !== \"string\") return null;\n if (typeof config.size !== \"number\" || !Number.isInteger(config.size) || config.size < 0) return null;\n return { digest: config.digest, size: config.size };\n}\n\n/**\n * ═══ THE RULE — why this image cannot run under action `key`'s manifest, or `null` when it can ═══\n *\n * `image` is `<repository>@<digest>`, for the sentences. `manifest` is the image manifest the digest\n * addresses and `config` the blob its descriptor names (`null` when there is none), each already\n * verified by the caller to hash to what it was fetched by. `provenance` is the ARTIFACT's.\n *\n * Every refusal names the action and what the image says instead.\n */\nexport function actionImageRefusal(input: {\n key: string;\n image: string;\n manifest: unknown;\n config: unknown;\n provenance: ActionImageProvenance;\n}): string | null {\n const { key, image, manifest, config, provenance } = input;\n\n // The type it says it is, read BEFORE the shape: an index is RECEIVED (every client asks for all\n // four types) and refused by name, never mistaken for a malformed manifest.\n const mediaType = isRecord(manifest) ? manifest.mediaType : undefined;\n if (typeof mediaType !== \"string\" || !IMAGE_MANIFEST_MEDIA_TYPES.includes(mediaType)) {\n return (\n `${image} is ${typeof mediaType === \"string\" ? `a ${mediaType}` : \"a manifest of no declared type\"}, not ` +\n `one image. An engine action's digest names exactly one linux/amd64 image manifest — never an ` +\n `index of several.`\n );\n }\n if (imageConfigDescriptor(manifest) === null) {\n return `${image} is not an image manifest — it names no config descriptor (schemaVersion 2, a digest and a size).`;\n }\n if (!isRecord(config)) {\n return `${image}'s config is not a JSON object, so it cannot say what it was built for.`;\n }\n\n const platform = `${String(config.os)}/${String(config.architecture)}`;\n if (platform !== \"linux/amd64\") {\n return (\n `${image} is built for ${platform}; an engine action runs on linux/amd64, which is what Container ` +\n `Apps Jobs run.`\n );\n }\n\n const labels = isRecord(config.config) && isRecord(config.config.Labels) ? config.config.Labels : {};\n const expected = actionSourceRepository(key);\n const source = labels[IMAGE_SOURCE_LABEL];\n if (source !== expected) {\n return (\n `the image of action \"${key}\" says it was built in ${source === undefined ? \"no repository (it carries no \" + IMAGE_SOURCE_LABEL + \" label)\" : JSON.stringify(source)}, ` +\n `not ${expected}. A signature binds a digest and never a name, so an image built for another ` +\n `action cannot run under this one's manifest.`\n );\n }\n if (provenance.repository !== expected) {\n return (\n `the artifact of action \"${key}\" says it was authored in ${JSON.stringify(provenance.repository)}, not ` +\n `${expected}, which its image names.`\n );\n }\n\n // ★ §20 G3. Without it, an image built from ANY commit of the right repository could ride under a\n // manifest published from another — a reviewed manifest over unreviewed code.\n const revision = labels[IMAGE_REVISION_LABEL];\n if (revision !== provenance.commit) {\n return (\n `the image of action \"${key}\" says it was built at ${revision === undefined ? \"no commit (it carries no \" + IMAGE_REVISION_LABEL + \" label)\" : JSON.stringify(revision)}, ` +\n `not ${provenance.commit}, the commit its artifact was published from. An image and the manifest ` +\n `it runs under come from one commit, so neither can be swapped for another's.`\n );\n }\n return null;\n}\n","// ═══ WHAT A POOL CAN TAKE RIGHT NOW, AND THE ONE SENTENCE THAT SAYS IT (docs/57 §3.1) ═══\n//\n// ★ THIS MOVED HERE FROM `apps/web/src/lib/runners/presence.ts`, AND THE MOVE IS THE SLICE.\n// docs/57 asks a WAITING RUN to explain itself \"in the same words the pool screen uses\". The\n// pool screen's words lived in the browser, so the only way for the control plane to say them\n// was to write a second copy — and the second copy is how \"no runner has polled recently\"\n// comes to be phrased two ways, one of which somebody edits.\n//\n// So the ARITHMETIC and the SENTENCE both live here, beside `runnerPresence`, for exactly the\n// reason that function already gives: it is a fact about the channel that a server, a client\n// and a test must all answer identically. What stayed in the web app is the part that is\n// genuinely display — the badge label and its `BadgeTone` — which contracts may not import.\n//\n// The founder's scenario is what this is for: he stopped his runners, submitted an action, and\n// watched a run sit silent while THIS notice, on the pool screen, said plainly that runs bound\n// to the pool would wait. The control plane knew and the run did not say.\nimport type {\n RunnerDto,\n RunnerLifecycle,\n RunnerPresence,\n RunnerVersionPolicy,\n RunnerVersionStanding,\n} from \"./runners\";\nimport { runnerPresence, runnerVersionStanding } from \"./runners\";\nimport { BRAND_SHORT_NAME } from \"./brand\";\n\n/** How many runners are in each state — the counts a person reads before any row. */\nexport interface PoolPresence {\n online: number;\n quiet: number;\n offline: number;\n total: number;\n /** Connected runners currently holding a step. Never more than `online`. */\n busy: number;\n /** Runners one or more releases behind, which still claim work. */\n behind: number;\n /**\n * Runners BELOW the floor. These claim nothing — counted apart from `behind` because they\n * are the answer to \"why is my run not starting\" and `behind` never is.\n */\n unsupported: number;\n /** Runners an operator has told to stop taking work. */\n draining: number;\n /** Runners whose credential an operator has revoked. */\n revoked: number;\n /**\n * ★ THE ONE THE NOTICE ACTUALLY NEEDS: connected, active, and supported. Everything else on\n * this object counts a reason a runner is NOT available, and a screen that had to add up\n * three exclusions itself would eventually add up two.\n */\n available: number;\n /**\n * ★ `available`'s SIBLING, AND THE TWO ANSWER DIFFERENT QUESTIONS (docs/61 §3.3).\n * `available` is \"able NOW\"; this is \"able EVENTUALLY, with nobody doing anything\".\n *\n * ⚠ IT CANNOT BE DERIVED FROM THE OTHER COUNTS, which is why it is a field and not a\n * function of this object. A runner is recoverable only if ALL THREE axes say so, and the\n * marginal counts above do not carry the joint distribution: 12 offline, 4 revoked and 6\n * unsupported out of 18 is satisfied both by a pool where nothing can recover and by one\n * where several runners can. It is counted HERE, in the loop that already visits every\n * runner, so §6's eighty waiting children cost nothing extra.\n */\n recoverable: number;\n}\n\n/**\n * ═══ WHAT THE POOL IS, PLUS WHAT AN ADMIN MAY DO ABOUT IT (docs/64 §6) ═════════════════\n *\n * ★★ A SEPARATE TYPE, AND THE REASON IS A COLUMN IN THE DATABASE. `RunnerWaitRecordDto`\n * PERSISTS a `PoolPresence` as jsonb — ten rows of it in production, written 2026-08-26 to\n * 2026-08-28 — and `isRunnerWaitRecord` refuses any record missing a count by name. Adding a\n * twelfth count to `PoolPresence` would therefore have made all ten historical records\n * unreadable, and every surface renders an unreadable record as \"nobody wrote it down\". That\n * is precisely the sentence docs/65 shipped a slice to STOP showing.\n *\n * ⚠ AND REFUSING IS THE GUARD BEING RIGHT, NOT BEING AWKWARD. It caught this in the gate. The\n * lesson it was pointing at is that `removable` is not a presence count at all: every member\n * of {@link PoolPresence} says what STATE some runners are in, and this says what an operator\n * may DO — a verdict, not an observation, and one nothing reading a stored record ever asks\n * for. It belongs where it is derived and nowhere else.\n */\nexport interface PoolSummary extends PoolPresence {\n /**\n * How many of these rows an admin may remove right now.\n *\n * ★ COUNTED IN THE SAME LOOP FOR `recoverable`'S REASON, and it is the same reason twice: it\n * is a fold over the whole list that no combination of the marginal counts can reproduce. `7\n * revoked` does not tell you 7 are removable — one of them may still be holding a step — and\n * a screen that added up `revoked + offline` to size its own button would be inventing a\n * second removability rule in the place hardest to test.\n *\n * The pool with 40 runners, 30 revoked by a rolling upgrade, is what this is for: the bulk\n * control has to say a NUMBER before it is pressed, and this is that number.\n */\n removable: number;\n}\n\n/**\n * ═══ CAN THIS RUNNER BECOME ABLE WITHOUT ANYONE DOING ANYTHING? (docs/61 §3.3) ═════════\n *\n * The split already existed — as PROSE, in two of the findings below: *\"none can come back on\n * its own\"* against *\"if they are restarting this clears on its own\"*. Two sentences that a\n * reader has to compare to learn which of two situations they are in, and which nothing else\n * in the product could read. This promotes it to a value.\n *\n * ★ THREE TABLES OVER THE THREE VOCABULARIES THAT ALREADY EXIST, not one new enum. A runner's\n * fate is decided on three INDEPENDENT axes — the same three docs/57 refused to collapse into\n * an ordered chain — so the answer is an AND across them, and each axis is pinned to its own\n * closed set. A new presence, lifecycle or standing is a compile error in exactly one of these\n * until somebody decides which side it is on, the way `ISOLATION_CONFINES_UNTRUSTED_CODE`\n * makes a new isolation declare itself.\n *\n * ★★ THE FOLD'S IDENTITY IS `true`, WHICH IS THE ★ IN §3.3 MADE MECHANICAL. A runner is\n * non-recoverable only if some axis explicitly SAYS SO; anything unclassified stays on the\n * recoverable side. Getting it wrong in that direction costs a quieter badge. Getting it wrong\n * the other way makes the product shout at a run that would have been fine — and only one of\n * those is a lie. It is also why `summarisePool` treats a pool whose install facts failed to\n * load as `current`: a loading state is not a verdict.\n */\nexport const PRESENCE_CAN_RECOVER: Record<RunnerPresence, boolean> = {\n // Polling now. Nothing to recover from.\n online: true,\n // AN INFERENCE, and the credential is still live: it may be mid-restart or on a slow\n // network, and it comes back by itself. This is the single most important `true` here —\n // one quiet runner among thirty-nine revoked ones means the pool is NOT terminal (§6).\n quiet: true,\n // A FACT: the credential has expired. Re-registration needs a token a human must mint.\n offline: false,\n};\n\nexport const LIFECYCLE_CAN_RECOVER: Record<RunnerLifecycle, boolean> = {\n active: true,\n // Somebody chose this, and only somebody can undo it. It clears on nobody's own.\n draining: false,\n // One-way by design (docs/53). Revoking also expires the credential, which is why a revoked\n // runner is `offline` on the presence axis too — one act seen from two directions.\n revoked: false,\n};\n\nexport const VERSION_STANDING_CAN_RECOVER: Record<RunnerVersionStanding, boolean> = {\n current: true,\n // Older, and it still claims work. Not a blocker at all.\n behind: true,\n // Below the floor. It needs new images and a new registration token — and it will be\n // refused again when it reconnects, which is why reconnecting is not recovery.\n unsupported: false,\n};\n\n// ═══ WHAT ENDS A RUNNER (docs/64 §3.2) ═══════════════════════════════════════════════════\n//\n// ★ THE THREE TABLES ABOVE SAY WHAT CAN COME BACK. NONE OF THEM SAYS WHAT ENDS. A runner row\n// has been immortal since docs/49: it registers, it goes quiet, it is drained or revoked, and\n// then it stays on the pool screen forever. The founder's `teste` pool read `0 able to take\n// work · 10 offline · 7 revoked` after six days, and there was no control anywhere that could\n// remove any of them. Unbounded growth in a customer-visible list is the defect; a record\n// class that never declared what ends it is the cause.\n//\n// So this is the fourth table over the SAME lifecycle vocabulary, and it answers the one\n// question the other three do not: when is this runner over?\n\n/**\n * How long a runner whose credential has died is kept before it counts as abandoned.\n *\n * ★ 30 DAYS, AND THE NUMBER IS ANCHORED THE WAY {@link RUNNER_QUIET_AFTER_MS} IS.\n *\n * 1 h `RUNNER_CREDENTIAL_TTL_MS` — a runner that stops polling reads `offline` one\n * hour later. That is when the clock below STARTS, not when it ends.\n * 14 d GitHub's automatic removal window for a non-ephemeral self-hosted runner.\n * 30 d this. Twice GitHub's, and it has to clear a change freeze, a holiday, and a\n * host somebody unplugged before a two-week release window.\n * 90 d GitLab's stale-runner cleanup — whose published bug is *\"Stale runner cleanup\n * deletes active runners\"*. A long window is not what made that safe or unsafe.\n *\n * ⚠ WHAT MAKES IT SAFE HERE IS NOT THE LENGTH, IT IS THAT NOTHING SWEEPS. This window gates a\n * button an admin presses; there is no worker, no cron and no default-on cleanup in this\n * slice, because GitLab shipped that order and deleted runners that were working. Erring long\n * costs a row on a screen. Erring short deletes the record of a machine that ran production\n * work, and only one of those is recoverable.\n */\nexport const RUNNER_ABANDONED_AFTER_MS = 30 * 24 * 60 * 60 * 1_000;\n\n/**\n * ═══ WHAT ENDS A RUNNER IN THIS LIFECYCLE STATE ════════════════════════════════════════\n *\n * Two ways a runner ends, and which one applies is a property OF THE LIFECYCLE VALUE:\n *\n * `ended` this state IS the ending. Nobody can undo it, and nothing further has to\n * happen before an admin may remove the row.\n * `abandonment` this state is not an ending. Only silence ends it: the credential has\n * expired AND nothing has polled for `afterMs`.\n *\n * ★ A FOURTH LIFECYCLE VALUE IS A COMPILE ERROR HERE UNTIL IT SAYS WHICH — the same shape as\n * `ISOLATION_CONFINES_UNTRUSTED_CODE` and the three tables above, and the whole reason this\n * slice is cheap. Removability is DERIVED from this and from {@link PRESENCE_CAN_RECOVER};\n * there is deliberately no second rule anywhere about which runners are disposable.\n *\n * ★★ `ended` MUST AGREE WITH {@link LIFECYCLE_CAN_RECOVER}, and that is asserted rather than\n * hoped for: a lifecycle that can recover on its own and also declares itself an ending is\n * GitLab's first published bug written straight into a table. See the guard in\n * `runner-removability.spec.ts`.\n */\nexport type RunnerEnding =\n | { readonly kind: \"ended\" }\n | { readonly kind: \"abandonment\"; readonly afterMs: number };\n\nexport const LIFECYCLE_ENDING: Record<RunnerLifecycle, RunnerEnding> = {\n // Working, or between polls. Only going away for a month ends it.\n active: { kind: \"abandonment\", afterMs: RUNNER_ABANDONED_AFTER_MS },\n // ★ NOT `ended`, THOUGH `LIFECYCLE_CAN_RECOVER` SAYS DRAINING CANNOT RECOVER ON ITS OWN.\n // The two tables answer different questions and this is the cell that proves it: draining\n // clears on nobody's own — that is why it is `false` up there — but an operator can Resume\n // it, and a runner somebody can put back to work in one click is not over. Removing a\n // drained-by-mistake host would take away the button that fixes the mistake.\n draining: { kind: \"abandonment\", afterMs: RUNNER_ABANDONED_AFTER_MS },\n // One-way by design (docs/53). Revoking expires the credential in the same statement, so\n // there is nothing left to wait for: the row cannot authenticate again, and no state change\n // here can mint another credential. This `kind` is also what {@link setLifecycle} reads to\n // refuse a transition OUT of revoked — the rule has one author, not two.\n revoked: { kind: \"ended\" },\n};\n\n/**\n * ═══ MAY THIS RUNNER BE REMOVED, AND IF NOT, WHY NOT (docs/64 §3.1, §3.3) ══════════════\n *\n * The facts this reads are exactly the facts {@link runnerPresence} reads — `lastSeenAt` and\n * `credentialExpiresAt` — plus `busy` and the lifecycle. It reads NO name, NO count, and NO\n * absence of recent runs, because GitLab's second published bug is an identity bug: a runner\n * re-registering under the operator's old name was matched to the record being pruned. Here a\n * registration mints a new `runnerId` and a name recurs across generations of host by design\n * (§6), so nothing that decides removal may look at one.\n */\nexport type RunnerRemovalGround =\n /** Its lifecycle is an ending. An admin may remove it now. */\n | \"ended\"\n /** Its credential died and nothing has polled since, for longer than the window. */\n | \"abandoned\";\n\nexport type RunnerKeptReason =\n /**\n * ★ THE GITLAB BUG, AND IT IS CHECKED FIRST FOR EVERY GROUND. Its credential is still\n * honoured, which is the same thing as \"it can still poll\" and the same thing as \"an\n * operator can still Resume it\". Nothing below can override this.\n */\n | \"connected\"\n /** It claimed a step that has not completed and has not expired. */\n | \"holding-a-step\"\n /** Its credential died, but not long enough ago. */\n | \"within-retention\";\n\nexport type RunnerRemovability =\n | { readonly removable: true; readonly because: RunnerRemovalGround }\n | { readonly removable: false; readonly kept: RunnerKeptReason };\n\n/**\n * ⚠ THIS IS AN ORDERED CHAIN AND THAT IS SAFE HERE, WHICH IS NOT TRUE IN GENERAL — docs/57\n * §3.1 is the counter-example, where an ordered `if` decided eight pairs by line order and a\n * branch asserted a fact it had never read. The difference: every clause below is a REFUSAL\n * that stands on its own fact alone, so the order changes only which sentence a person reads,\n * never whether the runner is removed. The two `removable: true` returns are last, after\n * every refusal has had its say, so a new refusal cannot be added below them by accident.\n */\nexport function runnerRemovability(\n runner: Pick<RunnerDto, \"lastSeenAt\" | \"credentialExpiresAt\" | \"busy\" | \"lifecycle\">,\n now: number,\n): RunnerRemovability {\n // Its credential is live. It is polling, or it is between polls and will be back — and\n // either way an operator can still Drain, Resume or Revoke it. Nothing that can still work\n // is removable, on any ground, and that is why this clause is outside the ending switch.\n if (PRESENCE_CAN_RECOVER[runnerPresence(runner, now)]) {\n return { removable: false, kept: \"connected\" };\n }\n // It went away holding a customer's step, and the step is still OPEN — that is the whole of\n // this refusal and it is about the run, not about the row's shape. The result path matches a\n // report against the `runner_id` that claimed it (`completeAuthorization`), so removing the\n // runner now would blank the one column that lets the work it is still holding be reported\n // at all. The authorization's own expiry ends this within minutes.\n //\n // ⚠ THIS CLAUSE ONCE CARRIED A SECOND REASON AND docs/67 REMOVED IT, NOT THIS GUARD. Blanking\n // `runner_id` no longer turns \"we are waiting on this host\" into \"nobody claimed it\":\n // `runner_authorization.runner_name` keeps that fact after the reference is released. The\n // refusal above is unchanged because the open run was always the real reason.\n if (runner.busy) return { removable: false, kept: \"holding-a-step\" };\n\n const ending = LIFECYCLE_ENDING[runner.lifecycle];\n if (ending.kind === \"ended\") return { removable: true, because: \"ended\" };\n\n const silentForMs = now - new Date(runner.lastSeenAt).getTime();\n if (silentForMs < ending.afterMs) return { removable: false, kept: \"within-retention\" };\n return { removable: true, because: \"abandoned\" };\n}\n\n/**\n * Why a runner was kept, in the words a person reads — and there is exactly one copy of them.\n *\n * The server refuses a removal with this sentence and the pool screen puts it on the disabled\n * control's tooltip. docs/57's rule: a sentence the control plane and the browser both say is\n * a sentence with one author, or one of the two gets edited.\n */\nexport const RUNNER_KEPT_SENTENCE: Record<RunnerKeptReason, (name: string) => string> = {\n connected: (name) =>\n `“${name}” still has a working credential, so it can still be told to stand down or ` +\n `brought back. Revoke it first — that is what ends a runner you want gone now.`,\n \"holding-a-step\": (name) =>\n `“${name}” is still holding a step. Removing it now would leave the run that is waiting ` +\n `on it unable to say who claimed the work. It clears by itself when the step expires.`,\n \"within-retention\": (name) =>\n `“${name}” has not been heard from for less than ${Math.round(\n RUNNER_ABANDONED_AFTER_MS / (24 * 60 * 60 * 1_000),\n )} days. Revoke it if you want it gone now, or leave it — a host that comes back keeps ` +\n `its place until then.`,\n};\n\n/**\n * Summarise a pool. Derived from the SAME `runnerPresence` and `runnerVersionStanding` every\n * row uses, so the counts above the list and the badges inside it cannot disagree — the defect\n * a second copy of the arithmetic would eventually produce.\n *\n * `policy` is nullable because a screen whose install read failed makes NO version claim, and\n * guessing would let it report a skew that does not exist.\n */\nexport type PoolPresenceRunner = Pick<\n RunnerDto,\n \"lastSeenAt\" | \"credentialExpiresAt\" | \"busy\" | \"lifecycle\" | \"version\"\n>;\n\n/**\n * ═══ IS THIS RUNNER ONE OF THE ONES `busy` COUNTS? (docs/72 §3.2) ══════════════════════\n *\n * ★ ONE AUTHOR FOR THE CONJUNCTION, because two sides now ask it. {@link summarisePool} folds\n * it into `PoolPresence.busy`; the control plane asks it again about the SUBSET of runners\n * holding one particular execution's work, to fill {@link PoolNoticeReader}. Written out\n * twice, \"counted as busy\" would have two definitions, and the subtraction in `poolNotice`\n * would quietly stop matching the number it subtracts from — a count larger than the total,\n * or a saturation claim that survives the fix.\n *\n * ⚠ `presence === \"online\"` IS PART OF IT AND IS NOT INCIDENTAL. A runner that went away\n * holding a step is `busy` on its row and is NOT congestion: nothing is going to finish and\n * free it, and the pool's real problem is that it is gone. That is `runnerActivity`'s \"Went\n * away holding a step\", and it is why this reads presence rather than the boolean alone.\n */\nexport function countsAsBusy(\n runner: Pick<PoolPresenceRunner, \"lastSeenAt\" | \"credentialExpiresAt\" | \"busy\">,\n now: number,\n): boolean {\n return runnerPresence(runner, now) === \"online\" && runner.busy;\n}\n\nexport function summarisePool(\n /**\n * ★ THE FIVE FIELDS IT ACTUALLY READS, not a whole `RunnerDto`. The control plane counts the\n * same pool from database ROWS while a screen counts it from DTOs (docs/57 §3.1); demanding\n * the full DTO would have made the server build one just to be counted, and a shape built\n * only to satisfy a signature is a shape somebody fills in with plausible values.\n */\n runners: readonly PoolPresenceRunner[],\n now: number,\n policy: RunnerVersionPolicy | null,\n): PoolSummary {\n const summary: PoolSummary = {\n online: 0,\n quiet: 0,\n offline: 0,\n total: runners.length,\n busy: 0,\n behind: 0,\n unsupported: 0,\n draining: 0,\n revoked: 0,\n available: 0,\n recoverable: 0,\n removable: 0,\n };\n for (const runner of runners) {\n const presence = runnerPresence(runner, now);\n summary[presence] += 1;\n if (countsAsBusy(runner, now)) summary.busy += 1;\n if (runner.lifecycle === \"draining\") summary.draining += 1;\n if (runner.lifecycle === \"revoked\") summary.revoked += 1;\n // A deployment whose install facts failed to load makes NO version claim — the same\n // reason S5 guarded on a null install version. It is a loading state, not a verdict.\n const standing = policy === null ? \"current\" : runnerVersionStanding(runner.version, policy);\n if (standing === \"behind\") summary.behind += 1;\n if (standing === \"unsupported\") summary.unsupported += 1;\n if (presence === \"online\" && runner.lifecycle === \"active\" && standing !== \"unsupported\") {\n summary.available += 1;\n }\n /*\n * An AND across the three axes, each answered by its own table. Note what it does NOT\n * read: `busy`. A busy runner is online, active and supported — it finishes its step and\n * takes the next one — so it is recoverable, which is what stops a healthy pool under\n * load from reading as a dead one.\n */\n if (\n PRESENCE_CAN_RECOVER[presence] &&\n LIFECYCLE_CAN_RECOVER[runner.lifecycle] &&\n VERSION_STANDING_CAN_RECOVER[standing]\n ) {\n summary.recoverable += 1;\n }\n // The SAME function the row's control calls, so the button's label and the button's\n // behaviour cannot disagree — the defect a second copy of this arithmetic would produce,\n // and the one `runnerPresence` already exists to prevent one axis over.\n if (runnerRemovability(runner, now).removable) summary.removable += 1;\n }\n return summary;\n}\n\n/**\n * The one thing a pool's state is worth saying, with the tone it should be said in — or null\n * when the pool is simply working.\n *\n * ⚠ THE TONE IS PART OF THE ANSWER, NOT A CHOICE FOR THE CALL SITE. \"Every runner is busy\" is\n * a pool working exactly as designed and \"every runner is offline\" is a pool that cannot run\n * anything; a caller handed only a string would have to guess which, and the same banner\n * would end up carrying both. Two facts, one return value, no cell the caller can fill wrong.\n */\nexport interface PoolNotice {\n tone: \"neutral\" | \"warning\" | \"danger\";\n message: string;\n}\n\n/**\n * ═══ WHY THIS IS COMPOSED AND NOT SELECTED ═════════════════════════════════════════════\n *\n * ★ THE DEFECT THIS REPLACES, AND IT SHIPPED. The notice used to be a chain of\n * `if (summary.X === summary.total)` branches returning one pre-written sentence, first match\n * wins. The version branch was written first and its sentence contained the clause\n *\n * \"They are still connected — this is a version problem, not a network one.\"\n *\n * It never consulted a connection count. A pool whose runners are BOTH offline AND below the\n * version floor satisfies `unsupported === total` and `offline === total` at once, so the\n * version branch won by POSITION and the screen printed \"They are still connected\" directly\n * above rows each reading \"Offline / Not connected\" — photographed against `docs52-proof`.\n * Worse than the contradiction: it named a cause and RULED ONE OUT, sending an operator to\n * pull images when the host was down.\n *\n * ─── THE ROOT CAUSE IS THE CHAIN, NOT THAT ONE CLAUSE ──────────────────────────────────\n *\n * `unsupported` is a VERSION fact, `offline` is a CONNECTION fact, `draining` is a LIFECYCLE\n * fact. They are three INDEPENDENT axes — a runner can be any combination — and the chain\n * modelled them as one ordered enum. Enumerated over every pool of up to three runners,\n * EIGHT distinct pairs satisfy two `X === total` tests simultaneously and are decided purely\n * by line order:\n *\n * unsupported × offline unsupported × quiet unsupported × draining\n * unsupported × revoked revoked × offline revoked × quiet\n * draining × offline draining × quiet\n *\n * (`offline × quiet` and `revoked × draining` never co-occur — they are two values of ONE\n * axis. That they are absent is the negative control on the enumeration.)\n *\n * Only the version clause was outright FALSE; the other seven silently dropped a fact the\n * operator still needed. Reordering the branches would have fixed one screenshot and left\n * seven coin-flips and the dropped version fact behind.\n *\n * ─── THE SHAPE, AND WHAT IT BEATS ──────────────────────────────────────────────────────\n *\n * Each axis produces its own finding, from a function that receives ONLY that axis's counts.\n * A version finding therefore has no connection count in scope: \"they are still connected\" is\n * not a sentence it can be written to say. That is the mistake made unexpressible rather than\n * merely corrected.\n *\n * *Beats:* moving `offline` above `unsupported`. One screenshot correct, the class untouched,\n * and the version fact — which the operator still needs, because those hosts will be refused\n * again when they come back — thrown away.\n *\n * *Beats:* deleting the \"still connected\" clause. When the runners genuinely ARE connected it\n * is the most useful sentence on the screen: it is what stops somebody investigating the\n * network. It survives, and it is now EARNED — see {@link crossAxisClause}.\n *\n * *Beats:* one `Record<Situation, string>` keyed on a composite of the three axes. That is the\n * same enum-collapse with a bigger key: 27 cells, most of which nobody would ever write, and\n * a new axis multiplies it again.\n *\n * ⚠ THE ONE PLACE BOTH AXES ARE VISIBLE IS THE COMPOSER, and the type cannot police what a\n * free string says there. `runner-pool-presence.spec.ts` sweeps EVERY reachable summary and\n * fails if a message asserts connectivity that `online === total` does not support — with a\n * litmus that runs the same sweep over the old chain and requires it to go red.\n */\n/**\n * ⚠ NAMED FOR THE RUNNER, NOT FOR THE POOL, AND THE RENAME IS PART OF A FIX (docs/62). These\n * are the axes a RUNNER is blocked on; a pool is blocked when a whole count of them is. The\n * per-runner row on the pool screen has had exactly these three sentences all along — the\n * presence one, the lifecycle one, the version one — and while this type said \"Pool\" the fact\n * that they were the same three axes was invisible, so the causal link below was filed here as\n * a pool detail and the row never got it. A name that describes the smaller thing is what\n * stops the next axis fact being filed on the bigger one again.\n */\nexport type RunnerBlockerAxis = \"connection\" | \"lifecycle\" | \"version\";\n\n/**\n * ═══ WHICH AXIS'S FINDING A LIFECYCLE ALREADY ACCOUNTS FOR (docs/62 §3.2) ═══════════════\n *\n * ★ THE SPLIT ALREADY EXISTED AS PROSE, IN THREE PLACES, AND THIS PROMOTES IT TO A VALUE —\n * the same move docs/61 made for {@link LIFECYCLE_CAN_RECOVER}, for the same reason. The fact\n * is that revoking EXPIRES the credential in the same statement (docs/53), so `runnerPresence`\n * reads a revoked runner as `offline` by ARITHMETIC. Its offline-ness is not a second problem;\n * it is the revoke, seen from the other axis.\n *\n * It was written out as English in {@link LIFECYCLE_CAN_RECOVER}'s `revoked` comment, again in\n * the web app's `runnerActivity`, and as a VALUE in exactly one place — `lifecycleFinding`'s\n * hand-written `explains: [\"connection\"]`. So the pool notice suppressed the redundant sentence\n * and the per-runner row, which cannot reach inside a function-local object literal, did not:\n * a runner revoked thirty seconds ago showed the revoke sentence AND \"a runner away this long\n * re-registers rather than resumes\". True of nothing, and it repeated the other's remedy.\n *\n * ★ IT IS A DECLARED CAUSAL LINK, NOT A PRIORITY ORDER. It says WHY the other finding is\n * redundant, which a positional `if` could only imply — and which is what lets two surfaces\n * with completely different copy agree about the same suppression without sharing a sentence.\n *\n * ⚠ AND A FOURTH LIFECYCLE CANNOT COMPILE UNTIL IT ANSWERS. `Record<RunnerLifecycle, …>` over\n * the whole vocabulary (charter §4.2 R2), so the default a forgotten member falls into is not\n * silently \"explains nothing\" — it is a type error, at the declaration and at every reader.\n */\nexport const LIFECYCLE_EXPLAINS: Record<RunnerLifecycle, readonly RunnerBlockerAxis[]> = {\n // Nothing was decided about this runner, so nothing about it explains anything else.\n active: [],\n /*\n * ⚠ DRAINING EXPLAINS NOTHING, AND THAT EMPTY ARRAY IS A DECISION RATHER THAN AN OMISSION.\n * A draining runner keeps its credential and keeps polling — it is ordinarily CONNECTED, and\n * that is the whole of the difference between asking a runner to stop and revoking it. If a\n * draining runner is also offline, those are two separate things that happened to it and the\n * reader needs both.\n */\n draining: [],\n // Revoking expires the credential in the same statement, so the connection axis is reporting\n // this same act. See `runner-lifecycle.e2e.spec.ts` for the statement itself.\n revoked: [\"connection\"],\n};\n\n/**\n * One axis's verdict. `finding` states what is true about THAT axis and nothing else;\n * `continuation` is the same fact worded to follow another finding, so a composed message\n * reads as a sentence rather than as two sentences stapled together.\n */\ninterface PoolFinding {\n axis: RunnerBlockerAxis;\n tone: \"warning\" | \"danger\";\n finding: string;\n continuation: string;\n remedy: string;\n /**\n * Axes whose finding this one ALREADY ACCOUNTS FOR, so the message does not say one fact\n * twice from two directions.\n *\n * ★ THE REAL CASE, AND IT IS LIVE TODAY: revoking EXPIRES the credential in the same\n * statement (docs/53), so `runnerPresence` reads a revoked runner as `offline` by\n * arithmetic. An all-revoked pool is ALWAYS also an all-offline pool. \"Their credentials\n * have expired\" is not a second problem there — it is the revoke, seen from the other axis.\n *\n * This is a declared causal link between axes, not a priority order: it says WHY the other\n * finding is redundant, which a positional `if` could only imply.\n */\n explains?: readonly RunnerBlockerAxis[];\n}\n\n/** Only the counts that describe whether runners are reachable. */\nfunction connectionFinding(c: {\n online: number;\n quiet: number;\n offline: number;\n total: number;\n}): PoolFinding | null {\n if (c.offline === c.total) {\n return {\n axis: \"connection\",\n tone: \"danger\",\n finding:\n \"Every runner in this pool is offline: their credentials have expired, so none can \" +\n \"come back on its own.\",\n continuation: \"They are also offline, so none can come back on its own.\",\n remedy: \"Runs bound to this pool will wait until one is installed again.\",\n };\n }\n if (c.quiet === c.total) {\n return {\n axis: \"connection\",\n tone: \"warning\",\n finding: \"No runner in this pool has polled recently, so runs bound to it will wait.\",\n continuation: \"None of them has polled recently either.\",\n remedy:\n \"If they are restarting this clears on its own; if not, check they can still reach \" +\n \"this control plane on 443 outbound.\",\n };\n }\n return null;\n}\n\n/** Only the counts that describe what an operator has told these runners to do. */\nfunction lifecycleFinding(l: {\n draining: number;\n revoked: number;\n total: number;\n}): PoolFinding | null {\n if (l.revoked === l.total) {\n return {\n axis: \"lifecycle\",\n tone: \"danger\",\n finding:\n \"Every runner in this pool has been revoked, so none can claim work and none can \" +\n \"come back.\",\n continuation: \"Every one of them has also been revoked, so none can come back.\",\n remedy:\n \"Revoking is one-way: issue a new registration token and install a runner again on \" +\n \"each host that should run work here.\",\n // READ, NOT RESTATED. This used to be a hand-written `[\"connection\"]` here, which made\n // this function the only place the causal link existed — see {@link LIFECYCLE_EXPLAINS}.\n explains: LIFECYCLE_EXPLAINS.revoked,\n };\n }\n if (l.draining === l.total) {\n return {\n axis: \"lifecycle\",\n tone: \"warning\",\n finding: \"Every runner in this pool is draining, so runs bound to it will wait.\",\n continuation: \"Every one of them is also draining.\",\n remedy:\n \"That is a state somebody chose here — resume a runner below to put it back to work, \" +\n \"or install a replacement before removing the last one.\",\n explains: LIFECYCLE_EXPLAINS.draining,\n };\n }\n return null;\n}\n\n/**\n * Only the counts that describe which BUILD these runners are on.\n *\n * ★ IT CANNOT SAY ANYTHING ABOUT THE NETWORK, and that is the point of the signature. The\n * clause that shipped — \"They are still connected\" — is not expressible here: there is no\n * connection count in scope to have checked.\n */\nfunction versionFinding(v: { unsupported: number; total: number }): PoolFinding | null {\n if (v.unsupported !== v.total) return null;\n return {\n axis: \"version\",\n tone: \"danger\",\n finding:\n `Every runner in this pool is running a build this ${BRAND_SHORT_NAME} will not hand work to, so ` +\n \"runs bound to it will wait indefinitely.\",\n continuation:\n `They are also on a build this ${BRAND_SHORT_NAME} will not hand work to, so they will still be ` +\n \"refused when they reconnect.\",\n remedy:\n \"Pull the current runner images and start each host again with a new registration token.\",\n };\n}\n\n/**\n * The one sentence that spans two axes, and the ONLY place a connectivity claim is made.\n *\n * ★ IT IS EARNED HERE, NOT ASSERTED. \"Not a network one\" rules out an axis, so it may only be\n * said having looked at that axis: it requires `online === total`, which is the strongest\n * connection fact there is. When the pool is version-blocked AND offline, this returns null\n * and the composed message carries both findings instead.\n */\nfunction crossAxisClause(\n findings: readonly PoolFinding[],\n connection: { online: number; total: number },\n): string | null {\n const onlyVersion = findings.length === 1 && findings[0]!.axis === \"version\";\n if (!onlyVersion) return null;\n return connection.online === connection.total\n ? \"They are still connected — this is a version problem, not a network one.\"\n : null;\n}\n\n/**\n * ═══ WHOSE RUN IS ASKING, AND HOW MUCH OF THIS POOL IS ITS OWN WORK (docs/72 §3.2) ═════\n *\n * ★★ THE DEFECT THIS EXISTS FOR, LIVE AS `OPS-8016`. Two log lines, one second apart:\n *\n * Handed to runner pool “teste”, and nothing there can take work right now. Every runner\n * here that can take work is busy … install another runner in the same pool to widen it.\n * Claimed by runner “runner-1” after 1s.\n *\n * The pool told a run that the pool was full — of that run's own work. `busy` counts a runner\n * holding ANY open claimed authorization, and a run's own phases are separately authorized\n * (`execute-step.ts`), so a one-runner pool serving one run looks saturated to that run.\n *\n * ★ THE COUNT IS RIGHT AND THE SENTENCE IS WRONG — docs/61's rule, *record the counts, derive\n * the sentence*, meeting a case nobody had. `busy` is not narrowed and must not be:\n * `listRunners` produces ONE `busy` boolean and docs/67's removal guard reads the same one\n * (`runnerRemovability` below), where narrowing it would make a runner mid-step REMOVABLE and\n * blank `runner_id` on an open authorization. So the fact stays and only this sentence moves.\n *\n * ⚠ AND IT IS REQUIRED, NOT OPTIONAL — docs/63, exactly. `waitsUpToMs` reached a default\n * because the argument did not carry the fact and an optional parameter let a caller reach the\n * wrong answer BY SAYING NOTHING. An optional reader here would do the same thing to this\n * sentence: every call site that forgot it would go on making the claim that was wrong.\n *\n * `null` is a CLAIM and the only road to \"describe this pool to a bystander\": nobody's run is\n * reading. The pool SCREEN passes it because a screen is not a run; a plan preview passes it\n * because a run that has not been dispatched holds nothing in the pool to be counted.\n */\nexport interface PoolNoticeReader {\n /**\n * How many of `PoolPresence.busy` are holding THIS run's own work.\n *\n * ★ IT IS A SUBSET OF `busy` BY CONSTRUCTION — {@link countsAsBusy} is what both this and\n * `summarisePool` are counted with, so \"how many are mine\" cannot exceed \"how many are\n * busy\" by two functions disagreeing about what busy means.\n */\n busyWithThisRun: number;\n}\n\nexport function poolNotice(\n summary: PoolPresence,\n reader: PoolNoticeReader | null,\n): PoolNotice | null {\n // The empty pool is a designed state of its own, not a warning printed over nothing.\n if (summary.total === 0) return null;\n\n /*\n * ★ THE TEST IS `available`, NOT `online`. A pool of fifty connected runners that are all\n * draining, or all below the version floor, is a pool where every badge says \"Connected\"\n * and not one run will start. An operator's first question when a run sits unclaimed is\n * \"is anything able to take it\", and this is that question.\n */\n if (summary.available > 0) {\n /*\n * ★ THE READER'S OWN WORK IS NOT CONGESTION, AND SUBTRACTING IT IS THE WHOLE FIX. What\n * this branch is for is \"somebody ELSE has them all\" — the reader's next move is to widen\n * the pool. A runner busy with this run's own earlier phase frees up the moment that\n * phase ends, and telling its owner to install a second runner for it is advice that\n * cannot help.\n *\n * ⚠ `busy` ITSELF IS UNTOUCHED. This subtraction is local to the sentence: the counts this\n * summary carries — including the ones a wait record persists — still describe the pool\n * as it is, and docs/67's removal guard reads a boolean this line cannot reach.\n */\n const busyElsewhere = summary.busy - (reader?.busyWithThisRun ?? 0);\n if (busyElsewhere < summary.available) return null;\n return {\n tone: \"neutral\",\n message:\n \"Every runner here that can take work is busy. New runs wait for one to finish — \" +\n \"install another runner in the same pool to widen it.\",\n };\n }\n\n // ── NOTHING CAN TAKE WORK. WHICH AXES SAY SO — all of them that do, not the first ──────\n const found = [\n connectionFinding(summary),\n lifecycleFinding(summary),\n versionFinding(summary),\n ].filter((finding): finding is PoolFinding => finding !== null);\n\n // A finding another one already accounts for is not a second problem. See `explains`.\n const explained = new Set(found.flatMap((finding) => finding.explains ?? []));\n const findings = found.filter((finding) => !explained.has(finding.axis));\n\n if (findings.length === 0) {\n /*\n * Nothing is uniformly true — the runners are blocked for DIFFERENT reasons. Naming any\n * one of them would be the positional lie in another costume, so this says what it knows\n * and points at the rows, which do have the per-runner answer.\n *\n * ★★ THIS IS THE BRANCH THE FOUNDER'S POOL FALLS INTO, AND IT WAS THE QUIET ONE. `teste`\n * on 2026-08-26 held 8 offline, 4 revoked and 6 below the floor — measured as 18 runners,\n * 12 offline (revoking expires the credential too), 0 available. No axis is uniformly\n * true, so every per-axis finding declines and the message lands here — at `warning`,\n * the same tone as a pool whose containers are merely restarting. Nothing in that pool\n * could recover, and this branch was the one place unable to say so, because terminality\n * was not a value anything could read (docs/61 §3.3).\n *\n * ⚠ THE TONE MOVES; THE SENTENCE DOES NOT. docs/61 §8 forbids new copy, and none is\n * needed: the reader's next action is what tone encodes, and here it changes from \"wait,\n * this may clear\" to \"nothing will change until you act\". The uniform branches above\n * already work exactly this way — `offline` reads danger and `quiet` reads warning for\n * the same reason.\n */\n return {\n tone: poolCanRecover(summary) ? \"warning\" : \"danger\",\n message:\n \"No runner in this pool can take work right now — they are variously not connected, \" +\n \"draining, revoked, or on too old a build. Runs bound to this pool will wait until \" +\n // ⚠ \"The list BELOW\" was true of the one screen this sentence was written for and\n // became false the moment a RUN borrowed it: there is no list below a run's detail.\n // A borrowed sentence has to be true wherever it is borrowed to, which is the whole\n // point of there being only one of it.\n \"one is available. Each runner's own row says which it is.\",\n };\n }\n\n const cross = crossAxisClause(findings, summary);\n const [first, ...rest] = findings;\n const message = [\n first!.finding,\n ...rest.map((finding) => finding.continuation),\n cross,\n ...findings.map((finding) => finding.remedy),\n ]\n .filter((part): part is string => Boolean(part))\n .join(\" \");\n\n return {\n // The worst contributing axis decides. A pool that is merely draining reads `warning`; one\n // that is also offline reads `danger`, because the reader's next action is different.\n tone: findings.some((finding) => finding.tone === \"danger\") ? \"danger\" : \"warning\",\n message,\n };\n}\n\n/**\n * ═══ CAN ANYTHING IN THIS POOL BECOME ABLE ON ITS OWN? (docs/61 §3.3) ══════════════════\n *\n * ★★ THE QUESTION IS NEVER \"IS ANYTHING ABLE RIGHT NOW\". That is `available`, and it is 0 for\n * a pool whose only runner is BUSY — a pool working exactly as designed. This asks whether\n * waiting is a plan: will this clear by itself, or is a person needed?\n *\n * ★ AN EMPTY POOL ANSWERS `true`, AND IT IS NOT A FALLBACK (§3.4). A pool with no runners has\n * nothing in it that CANNOT recover; installing one is the documented next step and the\n * command is on the same screen. Left to the fold below, an empty pool would answer `false` by\n * vacuous truth — \"every runner here is unrecoverable\" over no runners — and the product would\n * declare a brand-new pool beyond help. The question is unanswered, and the default for\n * unanswered is the recoverable side.\n *\n * ⚠ ONE RECOVERABLE RUNNER IS ENOUGH. §6 asks which way this errs and this is the answer: a\n * pool of 40 with 39 revoked and one quiet is NOT terminal, because that one may be a\n * container mid-restart and the whole pool is one poll away from working.\n *\n * ⚠ AND IT DECIDES NOTHING ABOUT WHETHER A RUN HAPPENS. docs/61 §1.1 and §8: this changes how\n * loudly a wait is stated and never whether it is permitted. Kubernetes, GitHub Actions and\n * HCP Terraform all hold and explain; none refuses.\n */\nexport function poolCanRecover(summary: PoolPresence): boolean {\n if (summary.total === 0) return true;\n return summary.recoverable > 0;\n}\n\n// ═══ AND WHAT A RUN SAYS WHILE IT WAITS FOR ONE (docs/57 §3.1, §3.2) ═══════════════════\n//\n// The only `emit` on the runner path replayed the RUNNER'S OWN events out of its report, so a\n// step nobody claimed produced zero events BY CONSTRUCTION — measured, and the whole defect.\n// The ending was already right (`RunnerStepAbandonedError` distinguishes \"nobody claimed it\"\n// from \"claimed and vanished\"); everything BEFORE it was missing.\n//\n// ★ THE MOMENT IS A NAMED VALUE, NOT A BOOLEAN AND NOT `waitedMs === 0`. \"Handed to pool X\"\n// and \"still waiting, 4m left\" are different sentences, and the side that knows which moment\n// it is — the dispatcher, which calls from two places — is not the side that renders. So the\n// dispatcher SETS the moment and the renderer switches on it exhaustively: the renderer cannot\n// pick wrong because it does not pick, and a third moment added later fails the switch rather\n// than falling into whichever branch was last.\n\n/** How long a run waits for a runner before the control plane gives up, as a person reads it. */\nexport function formatWaitDuration(ms: number): string {\n const seconds = Math.max(0, Math.round(ms / 1_000));\n if (seconds < 60) return `${seconds}s`;\n const minutes = Math.floor(seconds / 60);\n const rest = seconds % 60;\n // Whole minutes read as \"10m\", not \"10m 00s\" — the deadline is a round number and printing\n // two zeroes onto it makes a reader look for a precision that is not there.\n return rest === 0 ? `${minutes}m` : `${minutes}m ${String(rest).padStart(2, \"0\")}s`;\n}\n\n/** Everything a waiting run knows about where its work went and how long it has to wait. */\nexport interface RunnerWait {\n poolName: string;\n presence: PoolPresence;\n /** How long this run has been waiting. */\n waitedMs: number;\n /** How long is left before the authorization expires and the run is settled as abandoned. */\n remainingMs: number;\n /**\n * How many of `presence.busy` are holding THIS RUN'S OWN work (docs/72 §3.2).\n *\n * ★ IT TRAVELS WITH THE COUNTS RATHER THAN BEING LOOKED UP HERE, for the reason `presence`\n * itself does: the side that read the pool is the side that can answer, and a renderer that\n * went and asked would be describing a second, later pool.\n */\n busyWithThisRun: number;\n}\n\n/**\n * WHY a waiting run is speaking right now. Closed, and set by the dispatcher.\n *\n * · `handoff` — the authorization has just been written and nobody has had a chance to claim.\n * · `waiting` — nobody has, and the run is saying so again so the reader can see it is alive.\n * · `changed` — nobody has, AND the pool's condition is different from the last thing said.\n *\n * ★ THE THIRD MEMBER WAS FOUND BY RENDERING IT. With two, every minute repeated the full\n * remedy — \"…check they can still reach this control plane on 443 outbound\" — identically,\n * ~250 characters at a time. That is the doc's \"scrolls with noise\" arriving through the back\n * door: the COUNT was right and the reader still had nothing new to read, which teaches them\n * to skip the line that eventually does say something new. The countdown is the news while\n * nothing changes; the notice is the news when it does.\n */\nexport const RUNNER_WAIT_MOMENTS = [\"handoff\", \"waiting\", \"changed\"] as const;\nexport type RunnerWaitMoment = (typeof RUNNER_WAIT_MOMENTS)[number];\n\n/** The one renderer. Exhaustive over {@link RUNNER_WAIT_MOMENTS}. */\nexport function runnerWaitSentence(wait: RunnerWait, moment: RunnerWaitMoment): string {\n switch (moment) {\n case \"handoff\":\n return handoffSentence(wait);\n case \"waiting\":\n return stillWaitingSentence(wait, false);\n case \"changed\":\n return stillWaitingSentence(wait, true);\n }\n}\n\n/**\n * ★ THE LINE THE FOUNDER NEVER SAW. Emitted the instant the authorization is written — before\n * any runner has had a chance to claim — so a run bound to a dead pool explains itself in\n * SECONDS rather than after eleven minutes of silence.\n *\n * It always names the pool and always names the deadline, whether or not the pool is healthy:\n * a run that says nothing when things are fine and speaks only when they are not is a run\n * whose silence a reader cannot interpret.\n */\nfunction handoffSentence(wait: RunnerWait): string {\n const deadline = `It waits up to ${formatWaitDuration(wait.remainingMs)} for one to claim it.`;\n // THE READER IS THIS RUN, and it is the whole of `OPS-8016`: without it this line told a run\n // that the pool was full of work that was its own, one second before that pool claimed it.\n const notice = poolNotice(wait.presence, { busyWithThisRun: wait.busyWithThisRun });\n if (wait.presence.available > 0 && !notice) {\n const n = wait.presence.available;\n return (\n `Handed to runner pool “${wait.poolName}” — ${n} runner${n === 1 ? \"\" : \"s\"} able to ` +\n `take it. ${deadline}`\n );\n }\n // ★ THE POOL SCREEN'S OWN SENTENCE, NOT A PARAPHRASE. `poolNotice` is the function that\n // screen renders; borrowing it is what makes the run and the pool screen agree by\n // construction rather than by two people keeping two strings in step.\n return (\n `Handed to runner pool “${wait.poolName}”, and nothing there can take work right now. ` +\n `${notice?.message ?? \"\"} ${deadline}`.replace(/\\s+/gu, \" \").trim()\n );\n}\n\n/**\n * ★ THE LINE THAT PROVES THE RUN IS STILL ALIVE. Ten minutes with one log line is\n * indistinguishable from a crashed worker, and the reader's only recourse is to guess.\n *\n * It names the elapsed time and what is left, so the reader can see the wait moving rather\n * than infer it — and it re-states the pool's condition, because the interesting case is the\n * one where that condition CHANGES while the run waits.\n */\nfunction stillWaitingSentence(wait: RunnerWait, conditionChanged: boolean): string {\n const head =\n `Still waiting for a runner in pool “${wait.poolName}” — ` +\n `${formatWaitDuration(wait.waitedMs)} so far, ` +\n `${formatWaitDuration(wait.remainingMs)} before this run gives up.`;\n if (!conditionChanged) return head;\n // The pool is not what it was when this run last spoke. THAT is worth the full sentence\n // again — including a pool that got BETTER, which is a reader's cue to stop investigating.\n const notice = poolNotice(wait.presence, { busyWithThisRun: wait.busyWithThisRun });\n return notice ? `${head} ${notice.message}` : `${head} Something here can take work now.`;\n}\n\n/**\n * ═══ THE RUN'S OWN STATE WHILE IT WAITS (docs/61 §3.1) ═════════════════════════════════\n *\n * docs/57 gave the wait a VOICE — the sentences above. It did not give it a STATE: a run\n * whose work had been offered to a pool and not claimed still reported `running`, with a\n * spinner, which is the same word a run uses while a container is executing its step.\n *\n * ★ A CLOSED PAIR, NOT A BOOLEAN, and not a nullable pool. These are the two events the\n * execution row switches on, and each carries exactly what its own case needs: `offered`\n * names where the work went, `claimed` carries nothing because there is nothing left to say\n * — the wait is over. A `{ waiting: boolean; pool?: … }` shape would have a fourth cell\n * (claimed, with a pool) that means nothing, and somebody would eventually fill it.\n *\n * ⚠ IT IS RAISED PER PHASE, NOT PER RUN. A runner-executed step is two authorizations —\n * the pre-flight and the act — and each waits on its own (docs/49 §4.3). Both are real waits\n * of the same kind, and a model that named only the first would leave the founder's\n * complaint alive on the second one.\n */\nexport type RunnerHandoff =\n | ({ kind: \"offered\" } & RunnerWaitRecordDto)\n | { kind: \"claimed\" };\n\n/**\n * ═══ WHY A RUN IS WAITING, AS A FACT THE ROW KEEPS (docs/61 §3.2) ══════════════════════\n *\n * docs/57 emits the reason every 60 seconds as a `log` event. That was right for a countdown\n * and is not enough for a state: a reader arriving at a stalled run should see WHY without\n * scrolling a log.\n *\n * ★★ IT RECORDS THE COUNTS AND DERIVES THE SENTENCE — the whole decision, and it is not the\n * same call docs/58 made. docs/58 RECORDED `routed_pool_id` because re-deriving it let a pool\n * deleted between submit and dispatch silently reroute a queued run: that value is a DECISION\n * ALREADY ACTED UPON, so it must be stable, and re-deriving would produce a different answer\n * from the one taken. This is the opposite kind of value. A pool's condition is a live\n * description whose inputs change by the second, and a recorded SENTENCE would go stale the\n * instant a runner came back — the run would read \"Every runner in this pool is offline\" beside\n * a pool screen showing a healthy pool. Recording the prose would CAUSE the disagreement this\n * slice exists to prevent.\n *\n * So both halves take the argument that fits them:\n *\n * · the COUNTS are recorded, because they are unrecoverable. What a pool looked like at the\n * moment this run waited is not derivable an hour later — the runners will have changed —\n * and for an abandoned run it is the single most useful fact on the record. That is the\n * same \"recover the truth rather than guess it\" rule docs/58 applied, aimed at the fact\n * rather than at the wording.\n * · the SENTENCE is derived, by {@link poolNotice} — the function the pool screen renders.\n * One source of copy, so the run and the pool screen cannot disagree, and improving a\n * sentence improves every historical row instead of leaving a museum of old wordings.\n *\n * ⚠ AND IT IS STAMPED. `observedAt` is why the counts may be recorded at all: the row says what\n * was true AT A NAMED INSTANT rather than asserting a live claim it cannot support. A reader\n * who needs \"right now\" has the pool screen, one link away.\n *\n * *Beats:* re-deriving per read. §6's eighty children would each cost a pool query on a surface\n * that is a list; the dispatcher already holds this summary, having computed it for the notice.\n *\n * *Beats:* storing the composed message. Stale on arrival, and a copy of the pool screen's\n * words that nobody would ever diff against them again.\n */\nexport interface RunnerWaitRecordDto {\n poolId: string;\n poolName: string;\n /** The same counts the pool screen shows — {@link poolNotice} is what reads them. */\n presence: PoolPresence;\n /** ISO-8601: the instant these counts were read from the pool. */\n observedAt: string;\n /**\n * ═══ HOW MUCH OF `presence.busy` WAS THIS RUN'S OWN (docs/72 §3.2) ═══════════════════\n *\n * ★ IT IS RECORDED FOR THE REASON THE COUNTS ARE: it is unrecoverable. An hour later\n * nothing can say which of the busy runners were holding this run's own phase — the\n * authorizations are discarded when their step ends — so a record without it can only\n * render the sentence that was wrong.\n *\n * ⚠ `null` IS \"NOT RECORDED\", NEVER \"NONE OF THEM\". The ten records production wrote\n * between 2026-08-26 and 2026-08-28 never took this count, and reading their absence as\n * zero would be asserting, on their behalf, the very claim docs/72 exists to stop making.\n * {@link waitRecordReader} is the one place that translation happens, and it answers\n * `null` — \"nobody's run is asking\" — which renders exactly what those records said when\n * they were written.\n */\n busyWithThisRun: number | null;\n}\n\n/**\n * ═══ THE RECORD AS THE COLUMN MAY ACTUALLY HOLD IT ═════════════════════════════════════\n *\n * ★★ A SEPARATE TYPE FOR THE SAME REASON `PoolSummary` IS ONE, and the reason is the same\n * column. docs/64 tried to add a count to {@link PoolPresence} and the gate caught it: the\n * guard refuses a record missing a count by name, so every historical row would have read as\n * \"nobody wrote it down\" — the sentence docs/65 shipped a slice to STOP showing.\n *\n * So the guard's answer is about the DOCUMENT, where the new field may legitimately be absent,\n * and {@link runnerWaitRecordOf} is what turns that document into the DTO every surface reads.\n * A predicate that claimed a 2026-08-26 row already had this field would be the cast this file\n * refuses on the line above.\n */\ntype StoredRunnerWaitRecord = Omit<RunnerWaitRecordDto, \"busyWithThisRun\"> & {\n busyWithThisRun?: number | null;\n};\n\n/**\n * Read a stored wait record into the shape every surface uses — absence made explicit.\n *\n * ★ ONE PLACE DECIDES WHAT A MISSING COUNT MEANS, which is what stops a second surface\n * deciding it means zero. See {@link RunnerWaitRecordDto.busyWithThisRun}.\n */\nexport function runnerWaitRecordOf(value: unknown): RunnerWaitRecordDto | null {\n if (!isRunnerWaitRecord(value)) return null;\n return {\n poolId: value.poolId,\n poolName: value.poolName,\n presence: value.presence,\n observedAt: value.observedAt,\n busyWithThisRun: typeof value.busyWithThisRun === \"number\" ? value.busyWithThisRun : null,\n };\n}\n\n/**\n * Whose run a stored record was about, for {@link poolNotice}.\n *\n * ★ A RECORD THAT NEVER TOOK THE COUNT MAKES NO CLAIM ABOUT IT. `null` renders what that\n * record said when it was written, which is the honest reading of a row from before docs/72 —\n * and it is the same `null` the pool screen passes, meaning \"nobody's run is asking\".\n */\nexport function waitRecordReader(record: RunnerWaitRecordDto): PoolNoticeReader | null {\n /*\n * ⚠ `typeof === \"number\"`, NOT `!== null`, AND THE DIFFERENCE IS A DEPLOY ORDER. This record\n * crosses the wire on `ExecutionDto.runnerWait`, so a web build ahead of its api reads a\n * document where the field is simply ABSENT — `undefined`, which `!== null` admits and which\n * would then reach `poolNotice` as the reader's count. It survives the subtraction there\n * (`?? 0`), but by luck: the type says the value is a number and it would not be. Answering\n * `null` says the honest thing — nobody counted — for a skewed deploy and for a pre-docs/72\n * row alike, which are the same fact seen from two directions.\n */\n return typeof record.busyWithThisRun === \"number\"\n ? { busyWithThisRun: record.busyWithThisRun }\n : null;\n}\n\n/**\n * Is this jsonb a wait record? Read back through a guard rather than cast, for the reason\n * `isExecutionSite` exists beside it: a column whose shape is asserted by a cast is a column\n * that reports whatever an older release happened to write, and this product's characteristic\n * defect is the value that is computed, stored and then silently misread.\n */\nexport function isRunnerWaitRecord(value: unknown): value is StoredRunnerWaitRecord {\n if (typeof value !== \"object\" || value === null) return false;\n const record = value as Partial<StoredRunnerWaitRecord>;\n if (typeof record.poolId !== \"string\" || typeof record.poolName !== \"string\") return false;\n if (typeof record.observedAt !== \"string\") return false;\n /*\n * ★ ABSENT IS ALLOWED AND A WRONG TYPE IS NOT (docs/72). Absent is what every record written\n * before docs/72 looks like and it has a truthful reading; a string or an object in this\n * field is a document nothing wrote on purpose, and admitting it would put a non-number into\n * the subtraction `poolNotice` does with it.\n */\n if (\n record.busyWithThisRun !== undefined &&\n record.busyWithThisRun !== null &&\n typeof record.busyWithThisRun !== \"number\"\n ) {\n return false;\n }\n const presence = record.presence as Partial<PoolPresence> | undefined;\n if (typeof presence !== \"object\" || presence === null) return false;\n // Every count, by name. A partial summary would make `poolNotice` answer from `undefined`\n // comparisons — which are all false, so it would report a working pool.\n return (\n typeof presence.online === \"number\" &&\n typeof presence.quiet === \"number\" &&\n typeof presence.offline === \"number\" &&\n typeof presence.total === \"number\" &&\n typeof presence.busy === \"number\" &&\n typeof presence.behind === \"number\" &&\n typeof presence.unsupported === \"number\" &&\n typeof presence.draining === \"number\" &&\n typeof presence.revoked === \"number\" &&\n typeof presence.available === \"number\" &&\n /*\n * ★ AND THIS ONE ESPECIALLY. `poolCanRecover` reads `recoverable > 0`; against `undefined`\n * that is FALSE, so a record written before this count existed would not read as \"unknown\"\n * — it would read as a pool where NOTHING CAN RECOVER, and the product would shout at a\n * run that was fine. Refusing the whole record instead makes it `null`, which every\n * surface already renders as \"nobody wrote it down\". The guard errs recoverable, like\n * everything else on this axis.\n */\n typeof presence.recoverable === \"number\"\n );\n}\n\n/**\n * The wait ENDING, said out loud so the last thing a reader saw is not a stale \"still waiting\".\n * docs/57 §4: a runner appearing mid-wait must resolve the waiting state cleanly.\n */\nexport function runnerClaimedSentence(runnerName: string, waitedMs: number): string {\n return `Claimed by runner “${runnerName}” after ${formatWaitDuration(waitedMs)}.`;\n}\n\n// ═══ AND THE WARNING A PLAN CARRIES, WHICH IS NOT A REFUSAL (docs/57 §3.3) ══════════════\n//\n// ★★ THIS IS DELIBERATELY NOT AN `ActionRunnabilityCause`, AND THE REASON IS THE WHOLE\n// DECISION. docs/54 put `runner_pool` in that vocabulary for a STRUCTURAL reason: an action\n// package can NEVER execute on a runner, so the catalog is right to refuse it forever. \"No\n// runner is alive right now\" is TRANSIENT — it clears by itself the moment somebody's\n// container finishes restarting.\n//\n// Put a transient fact into a structural vocabulary and every action reads as permanently\n// unrunnable in the catalog while a host reboots: orthogonal facts sharing one type, which is\n// the defect this codebase keeps paying for.\n//\n// *Beats:* refusing the run outright when the pool is empty. A runner restarting for thirty\n// seconds would refuse work that was about to be perfectly servable, and docs/51 §4.5 already\n// decided the answer is to wait VISIBLY rather than to refuse.\n//\n// A WARNING AND A REFUSAL ARE DIFFERENT SHAPES. This is the warning; it lives on its own\n// field, it never sets `runnable: false`, and `runner-pool-warning-is-not-a-refusal.spec.ts`\n// asserts that a pool with nothing alive produces no structural cause at all.\n\n/** A pool that will make a run wait, as the plan states it before anybody submits. */\nexport interface PoolWaitWarningDto {\n poolId: string;\n poolName: string;\n /** The same counts the pool screen shows, so the sentence below is the screen's sentence. */\n presence: PoolPresence;\n /**\n * ★ THE WHOLE WINDOW, NOT `RUNNER_STEP_TIMEOUT_MS`. An authorization expires at the step\n * timeout PLUS the reporting grace, and that later instant is when the run actually gives\n * up — so it is the number a waiting run prints. The plan says the same one: a plan\n * promising \"10m\" above a run that says \"11m\" is two deadlines for one wait.\n */\n waitsUpToMs: number;\n}\n\n/**\n * What the plan preview and the approval card say. Present tense, and it says what WILL\n * happen rather than what is wrong — the run is going to be accepted either way.\n */\nexport function poolWaitWarningSentence(warning: PoolWaitWarningDto): string {\n /*\n * ★ NO READER, AND IT IS A FACT RATHER THAN A SHORTCUT (docs/72 §3.2). This sentence is said\n * about a run that has NOT been dispatched — the plan preview and the approval card, both\n * before submit — so this run holds no authorization in that pool and can be holding none of\n * `busy`. `{ busyWithThisRun: 0 }` would say the same number and claim to have counted it.\n */\n const notice = poolNotice(warning.presence, null);\n const consequence =\n `This run will be accepted and will wait up to ` +\n `${formatWaitDuration(warning.waitsUpToMs)} for a runner to take it.`;\n return notice ? `${notice.message} ${consequence}` : consequence;\n}\n","// ═══ WHICH POOL A RUN GOES TO — DECIDED BY THE TARGET, NOT BY THE CREDENTIAL (docs/58) ═══\n//\n// A runner pool was bound to a CONNECTION SCOPE, exactly one pool per scope, enforced by\n// `runner_pool_binding_tenant_id_connection_scope_id_key`. A connection scope is a CREDENTIAL\n// boundary and it is not a network boundary: one Azure subscription routinely holds resources\n// reachable from the public internet and resources reachable only from inside one VNet on one\n// continent. Reachability — the single reason private runners exist — is a property of the\n// TARGET RESOURCE, so the binding named the wrong subject and forced an untrue choice:\n// everything in that subscription through the Asia runner, or nothing.\n//\n// ─── ★ THE MATCH VOCABULARY IS NOT NEW, AND THAT IS THE LOAD-BEARING DECISION ────────────\n//\n// A rule matches over {@link TargetSelectorQuery} — the SAME four fields, with the same\n// AND/OR semantics, that fan-out target selection has used since docs/31 §8.1. A second\n// spelling of a closed set is charter §4.2's defect class, which has already cost this\n// codebase ~21 duplicated copies.\n//\n// It also beats an expression language, and for a sharper reason than taste. `TargetSelectorQuery`\n// says of itself (operations.ts:335) that it has \"deliberately no operators, no expressions and\n// no negation beyond `excludeResourceIds`, because an operator must always be able to answer\n// 'why did this match?' without reading a grammar\". That requirement is STRONGER here than it is\n// for targets, because the answer decides which machines a customer's credentials are handed to.\n//\n// ★★ AND IT IS WHAT MAKES {@link runnerPoolRulesOverlap} COMPUTABLE AT ALL. Overlap of two\n// matches is decidable precisely BECAUSE the vocabulary has no operators: every field is an\n// equality, a set membership or a prefix, so a witness resource can be CONSTRUCTED rather than\n// searched for (see the proof in that function's comment). Adding one operator — a negation, an\n// OR across keys, a glob — would cost that property, and with it the write-time refusal that is\n// the whole reason this design needs no precedence rule. That is the price of the next feature\n// somebody asks for here, stated now while it is cheap to say.\nimport { HOSTED_EXECUTION_LABEL } from \"./run-placement\";\nimport type { ExecutionSiteRef } from \"./execution-site\";\nimport type { RoutableTarget } from \"./routable-target\";\nimport type { TargetSelectorQuery } from \"./operations\";\nimport type { PackageProvenanceKind } from \"./package-provenance\";\n\n/**\n * ═══ DECLARED IN `routable-target.ts` SINCE docs/69, RE-EXPORTED HERE ══════════════════\n *\n * The shape did not change and no importer moved. What changed is that `ExecutionDto` now\n * carries resolved identities, and reaching them through this module closed a cycle:\n * `execution → target-identity → runner-pool-routing → operations → execution`. A resource's\n * identity is a leaf; a routing rule depends on it, not the other way round. The full argument\n * is at the top of that file.\n */\nexport type { RoutableTarget } from \"./routable-target\";\n\n/**\n * A rule: on this connection scope, resources matching THIS run in THAT pool.\n *\n * ─── ★ WHY A RULE HAS A NAME, AND WHAT THE NAME COSTS (docs/58 judgement 3) ─────────────\n *\n * Because every refusal this slice adds has to name the thing an admin must go and edit, and\n * the alternative sentence is measurably worse:\n *\n * \"conflicts with the rule matching tags {network: private}, name prefix web-\"\n * \"conflicts with the rule named “asia-private”\"\n *\n * The first is a re-derivation of the row; the second is the row. At 14 rules the first is\n * ambiguous the moment two rules share a criterion.\n *\n * ⚠ AND A NAME IS A THING THAT CAN DRIFT FROM WHAT IT MATCHES. A rule called `asia-private`\n * whose match was later edited to `tags={network: public}` is a lie with a friendly face. Two\n * properties keep it honest, and both are enforced rather than hoped for:\n *\n * · THE NAME IS NEVER READ BY THE MATCHER. {@link matchesRunnerPoolRule} takes a\n * {@link TargetSelectorQuery} and cannot see a name, so a drifted name can misdescribe a\n * rule but can never misroute a run.\n * · THE NAME IS NEVER RENDERED ALONE. Every surface that prints a name prints\n * {@link describeRunnerPoolMatch} beside it, so the criteria are on screen next to the\n * label that claims to summarise them. A drifted name is then a visible contradiction\n * rather than a hidden one — the same posture `tone`/`state` naming took in docs/43.\n */\nexport interface RunnerPoolRuleDto {\n id: string;\n /** Unique within the connection scope — which is the blast radius of every refusal below. */\n name: string;\n connectionScopeId: string;\n connectionId: string;\n connectionName: string;\n poolId: string;\n poolName: string;\n /** At least one POSITIVE criterion, enforced by {@link runnerPoolMatchIsEmpty}. */\n match: TargetSelectorQuery;\n createdAt: string;\n}\n\n/** What a caller may write. The server owns every other field on {@link RunnerPoolRuleDto}. */\nexport interface CreateRunnerPoolRuleInput {\n name: string;\n connectionScopeId: string;\n poolId: string;\n match: TargetSelectorQuery;\n}\n\n/**\n * ═══ HOW MANY RULES ONE SCOPE MAY CARRY, AND WHY THERE IS A NUMBER AT ALL ═══════════════\n *\n * docs/58 §6 designs against 14 rules and asks what happens at 500. This is the answer, and it\n * is a refusal with a number in it rather than a slow screen.\n *\n * Neither cost actually forces a cap — the save check is O(n) comparisons of two small objects\n * and the run-time match is O(rules × targets) in memory, so 500 × 80 is ~40k field\n * comparisons and finishes in single-digit milliseconds. The cap exists because an UNBOUNDED\n * rule set is loaded into memory on every run through that scope, and \"it was fast when we\n * measured it\" is not a bound. 100 is ~7× the design point.\n */\nexport const RUNNER_POOL_RULES_PER_SCOPE_MAX = 100;\n\n/**\n * ═══ WHERE A RUN WILL EXECUTE, RESOLVED FROM ITS TARGETS ════════════════════════════════\n *\n * Three outcomes, and `ambiguous` is a value rather than a thrown error because it has to\n * travel to a plan the wizard renders (docs/58 §3.3) instead of failing a request.\n *\n * ★ THERE IS NO \"COULD NOT DECIDE\" MEMBER, deliberately. A caller either holds the target\n * facts or the scope has no rules to need them; {@link routeRunnerPool} is a pure function of\n * what it was given, and a fourth state would be a place for a caller to put its own\n * uncertainty and have it read as `hosted` downstream. That is the silent-discard shape this\n * codebase keeps paying for.\n */\nexport type PoolRouting =\n | { kind: \"hosted\" }\n | { kind: \"pool\"; pool: RoutedPoolRef; via: PoolRoutingVia }\n | { kind: \"ambiguous\"; matches: readonly PoolRoutingMatch[] };\n\n/**\n * ═══ A POOL AS ROUTING RESOLVES IT: ITS IDENTITY, PLUS WHAT IT HAS VOUCHED FOR ══════════\n *\n * ★ THE CONSENT TRAVELS WITH THE POOL, WHICH IS WHAT KEEPS IT ONE QUESTION (docs/59).\n * `runnabilityOf` must know whether this pool accepts this package's provenance. It could ask\n * the runners facade — and that is precisely the defect docs/56 §3.4 wrote a comment about\n * when it stopped `runnabilityOf` asking for the pool: two answers to one question inside one\n * request is how a plan that says \"Opera's cloud\" comes to sit above a run that went to Asia.\n *\n * So the answer arrives with the routing that already names the pool. It costs NOTHING extra:\n * `bindingsForConnectionScope` already selects the pool row to read its id and name, and this\n * is one more column in that same `select` — which is also docs/59 §6's requirement that\n * resolving a plan must not become a lookup per target.\n *\n * ⚠ IT DOES NOT REACH {@link PoolRoutingMatch}, and that is deliberate rather than an\n * oversight. The ambiguous branch groups destinations INCLUDING a hosted sentinel that is not a\n * pool at all; giving that sentinel an `acceptsProvenance` would mean writing a consent policy\n * for Opera's own cloud, where the question does not arise (a hosted step is confined — docs/59\n * §7). An empty set there would read as \"Opera's cloud accepts nothing\", which is false and is\n * exactly the kind of value a later reader trusts.\n */\nexport interface RoutedPoolRef extends ExecutionSiteRef {\n /** Empty by default and empty for every pool that has never been changed (docs/59 §3.1). */\n acceptsProvenance: readonly PackageProvenanceKind[];\n /**\n * ═══ HOW MUCH OF THIS POOL CAN CONFINE UNDECLARED EGRESS (docs/70 §3.3) ═══════════════\n *\n * ★ IT TRAVELS WITH THE POOL FOR THE REASON `acceptsProvenance` DOES, and it is one more\n * column on a read that was already happening. docs/59 §6 requires that resolving a plan not\n * become a per-target lookup; this is a nested select on the pool row the binding loader\n * already fetches, so a pool's confinement arrives WITH the pool and the runnability oracle\n * never asks a second time.\n *\n * ⚠ COUNTS, NOT A BOOLEAN, AND THE MIXED POOL IS WHY. One runner that confines and one that\n * does not is a pool where what a run gets depends on which runner claims it — and routing\n * gives nobody a choice about that. A boolean would have to pick a side and would be wrong\n * half the time; the counts let the refusal say how much of the pool it is talking about,\n * which is the difference between a sentence an operator can check and one they must trust.\n *\n * `total` counts runners that could CLAIM — `lifecycle: \"active\"`. A revoked or draining\n * runner will not take this work, so including it would refuse a run over a machine that was\n * never going to run it.\n */\n confinement: PoolConfinementCounts;\n}\n\n/** Both numbers, so `confined === total` is a comparison rather than two reads. */\nexport interface PoolConfinementCounts {\n confined: number;\n total: number;\n}\n\n/**\n * WHICH of the two levels answered — the sentence an operator needs when they ask why a run\n * went where it went, available without reading any other row.\n */\nexport type PoolRoutingVia =\n | { source: \"default\" }\n | { source: \"rule\"; rule: RunnerPoolRuleRef };\n\n/** A rule, named — enough to render a refusal or an explanation without a second read. */\nexport interface RunnerPoolRuleRef {\n id: string;\n name: string;\n match: TargetSelectorQuery;\n}\n\n/** One pool a run's targets resolved to, and a resource that took it there. */\nexport interface PoolRoutingMatch {\n pool: ExecutionSiteRef;\n via: PoolRoutingVia;\n /** A resource that resolved to this pool — the witness, so a refusal can be checked. */\n exampleResourceId: string;\n /** How many of the run's targets resolved here. */\n targetCount: number;\n}\n\n/** The rule set + default a scope resolves through. Loaded once per run (docs/58 §6). */\nexport interface RunnerPoolBindings {\n /** The scope-wide fallback — today's `runner_pool_binding` row. Null means hosted. */\n default: RoutedPoolRef | null;\n rules: readonly RunnerPoolRuleWithPool[];\n}\n\nexport interface RunnerPoolRuleWithPool extends RunnerPoolRuleRef {\n pool: RoutedPoolRef;\n}\n\n/**\n * ═══ RULE → SCOPE DEFAULT → HOSTED, AND NOTHING ELSE (docs/58 §3.2) ═════════════════════\n *\n * ★ NO PRIORITY INTEGER, NO \"MOST SPECIFIC WINS\", NO ORDERING — and the absence is the\n * feature, not an omission. A precedence column is a grammar by another name: it makes \"why\n * did this match?\" require reading every other row in the table, and it makes the answer\n * change when an unrelated rule is edited. Overlap is refused when the SECOND RULE IS SAVED\n * ({@link runnerPoolRulesOverlap}), which puts the error in front of the one person who can\n * fix it at the moment they caused it, and leaves run time a LOOKUP rather than an evaluation.\n *\n * ─── WHY A SPLIT RUN IS NOT AN OPTION (docs/58 §3.3) ────────────────────────────────────\n *\n * When a fan-out's targets resolve to two pools this returns `ambiguous` and the run is\n * refused before anything is created. Three reasons, in order of weight:\n *\n * 1. THE RECORD CANNOT HOLD IT. `execution.executed_pool_id` is one column on one row\n * (migration 0064). A split run writes a lie there or forces a schema change.\n * 2. THE APPROVER CANNOT JUDGE IT. docs/56 exists so a human sees WHERE a run will execute\n * as one sentence. \"Partly in Frankfurt and partly on machines in Singapore\" is exactly\n * the sentence that screen was built to avoid.\n * 3. IT IS RECOVERABLE. Narrowing the selector and running twice is a real remedy. A\n * silently split run is not something an operator can undo.\n *\n * `targets` is empty only for a caller that has no resources in hand at all, which the run\n * path never is: `enforceTargetRails` refuses a zero-target fan-out outright, and a single run\n * always has its one resource. An empty list therefore falls to the default, which is what a\n * scope with no rules would have answered anyway.\n */\nexport function routeRunnerPool(\n bindings: RunnerPoolBindings,\n targets: readonly RoutableTarget[],\n): PoolRouting {\n /*\n * ★ THE ENTRY KEEPS THE REAL POOL BESIDE THE RENDERABLE MATCH (docs/59). `PoolRoutingMatch`\n * exists to be RENDERED in an ambiguity message, so its `pool` may be the hosted sentinel —\n * a destination that is not a pool and therefore has no consent policy. The single-destination\n * branch below needs the genuine {@link RoutedPoolRef}, so it is carried here rather than\n * recovered from the match, which cannot tell the sentinel from a pool named \"Opera's cloud\".\n * `null` is hosted, and it is the same `null` the caller's `pool` variable already means.\n */\n const byPool = new Map<string, { match: PoolRoutingMatch; pool: RoutedPoolRef | null }>();\n\n for (const target of targets) {\n const rule = bindings.rules.find((candidate) =>\n matchesRunnerPoolRule(target, candidate.match),\n );\n // No rule matched THIS resource, so it takes the scope default — the level below, per the\n // order above. A scope with no default sends it to hosted, and a run that mixes a\n // rule-matched resource with a hosted one is genuinely two places: `ambiguous` says so\n // rather than quietly promoting one of them.\n const pool = rule ? rule.pool : bindings.default;\n const via: PoolRoutingVia = rule\n ? { source: \"rule\", rule: { id: rule.id, name: rule.name, match: rule.match } }\n : { source: \"default\" };\n const key = pool ? `pool:${pool.id}` : \"hosted\";\n\n const seen = byPool.get(key);\n if (seen) {\n seen.match.targetCount += 1;\n continue;\n }\n byPool.set(key, {\n match: {\n // A hosted destination still needs an entry so it can PARTICIPATE in the ambiguity\n // above; the sentinel id is never rendered, because a `matches` list is only ever read\n // when there are two or more and the copy names each entry through its own `via`.\n pool: pool ?? HOSTED_ROUTING_DESTINATION,\n via,\n exampleResourceId: target.resourceId,\n targetCount: 1,\n },\n pool,\n });\n }\n\n if (byPool.size > 1) {\n return { kind: \"ambiguous\", matches: [...byPool.values()].map((entry) => entry.match) };\n }\n\n const only = [...byPool.values()][0];\n // Nothing to route: no targets were supplied, so no rule could be evaluated and the scope\n // default is the whole answer — byte-for-byte the pre-docs/58 behaviour.\n if (!only) {\n return bindings.default\n ? { kind: \"pool\", pool: bindings.default, via: { source: \"default\" } }\n : { kind: \"hosted\" };\n }\n // ⚠ THE NULL POOL IS THE TEST, NOT THE SENTINEL ID. Comparing ids would ask a rendered value\n // a structural question, and the sentinel's id is the empty string — a value a real pool can\n // never hold today and exactly the kind of coincidence that stops being true.\n if (!only.pool) return { kind: \"hosted\" };\n return { kind: \"pool\", pool: only.pool, via: only.match.via };\n}\n\n/**\n * The stand-in for \"Opera's cloud\" inside {@link routeRunnerPool}'s grouping, so hosted is one\n * destination among the others while ambiguity is being decided. It never leaves this module as\n * a pool: a single-destination hosted result returns `{ kind: \"hosted\" }`, and the `ambiguous`\n * branch is rendered through each match's `via`.\n */\nconst HOSTED_ROUTING_DESTINATION: ExecutionSiteRef = { id: \"\", name: HOSTED_EXECUTION_LABEL };\n\n/**\n * Does this resource satisfy this match?\n *\n * ★ IT IS THE SAME PREDICATE `applyQueryFilters` APPLIES TO A FAN-OUT, field for field —\n * resource groups ORed within the field, tags ANDed ACROSS KEYS, a case-insensitive name\n * prefix, and excluded ids dropped after everything else matched. Tag KEYS compare\n * case-insensitively (Azure treats them so) and VALUES exactly, because `env=Prod` and\n * `env=prod` are different values to whoever set them.\n *\n * A rule with no positive criterion cannot exist ({@link runnerPoolMatchIsEmpty} refuses it at\n * save), so this never degenerates into \"matches everything\" — that is what the scope DEFAULT\n * is, and having two ways to spell it is charter §4.2 again.\n */\nexport function matchesRunnerPoolRule(\n target: RoutableTarget,\n match: TargetSelectorQuery,\n): boolean {\n const groups = lowerSet(match.resourceGroups);\n if (groups && !groups.has((target.resourceGroup ?? \"\").trim().toLowerCase())) return false;\n\n const excluded = lowerSet(match.excludeResourceIds);\n if (excluded?.has(target.resourceId.trim().toLowerCase())) return false;\n\n const prefix = match.namePrefix?.trim().toLowerCase();\n if (prefix && !target.name.trim().toLowerCase().startsWith(prefix)) return false;\n\n for (const [key, value] of Object.entries(match.tags ?? {})) {\n if (findTagValue(target.tags, key) !== value) return false;\n }\n return true;\n}\n\n/**\n * ═══ COULD ONE RESOURCE SATISFY BOTH RULES? (docs/58 §3.2, judgement 1) ═════════════════\n *\n * ★★ THIS IS DECIDABLE, AND HERE IS THE PROOF RATHER THAN THE CLAIM.\n *\n * The three positive fields are INDEPENDENT dimensions of a resource: its resource group, its\n * tag map, and its name. So two matches overlap iff each field is INDIVIDUALLY co-satisfiable —\n * and when they are, a witness resource can be CONSTRUCTED, which is what makes this an\n * equivalence and not a conservative approximation:\n *\n * | field | co-satisfiable when | witness component |\n * |-----------------|--------------------------------------------|--------------------------|\n * | resourceGroups | absent on either side, or the sets INTERSECT| any g ∈ G₁ ∩ G₂ |\n * | tags | every SHARED key carries the SAME value | T₁ ∪ T₂ (consistent) |\n * | namePrefix | one prefix is a prefix of the other | the LONGER of the two |\n *\n * A key named by only one side is satisfied by simply carrying that tag, so shared keys are the\n * only obstruction. Two prefixes that diverge at any character (\"web-\" and \"db-\") admit no\n * name at all; otherwise the longer one satisfies both by construction.\n *\n * ─── ⚠ `excludeResourceIds` IS IGNORED, AND THAT IS A DECISION ──────────────────────────\n *\n * It removes FINITELY many ids from an unbounded, changing universe of resources, so it can\n * never make two otherwise-overlapping rules disjoint — tomorrow's new VM matches both again.\n * A checker that credited exclusions would therefore admit pairs that overlap in practice,\n * which is the direction that MATTERS: it would let an ambiguous routing be saved and only\n * surface as a refused run at 2am. Ignoring it can only refuse a pair that some cleverer\n * analysis might have allowed, and the remedy for that is one word of narrowing in the match.\n *\n * COST. Comparing two rules is O(|G₁|+|G₂|+|T₁|+|T₂|+min(|P₁|,|P₂|)) — the size of the two\n * rules, not of the estate. Saving a rule checks it against every other rule on that scope, so\n * a save is O(n) such comparisons; at docs/58 §6's 14 rules that is 14, and at 500 it is 500 —\n * except that 500 cannot arise, because {@link RUNNER_POOL_RULES_PER_SCOPE_MAX} refuses the\n * 101st rule by name. Nothing here is ever O(n²): the full pairwise check is never run, since\n * the invariant is maintained on every write rather than verified on read.\n */\nexport function runnerPoolRulesOverlap(a: TargetSelectorQuery, b: TargetSelectorQuery): boolean {\n const groupsA = lowerSet(a.resourceGroups);\n const groupsB = lowerSet(b.resourceGroups);\n if (groupsA && groupsB && ![...groupsA].some((group) => groupsB.has(group))) return false;\n\n const tagsA = lowerKeyed(a.tags);\n const tagsB = lowerKeyed(b.tags);\n for (const [key, value] of tagsA) {\n if (tagsB.has(key) && tagsB.get(key) !== value) return false;\n }\n\n const prefixA = a.namePrefix?.trim().toLowerCase() ?? \"\";\n const prefixB = b.namePrefix?.trim().toLowerCase() ?? \"\";\n if (!prefixA.startsWith(prefixB) && !prefixB.startsWith(prefixA)) return false;\n\n return true;\n}\n\n/**\n * A match with no POSITIVE criterion matches every resource, which is precisely what the scope\n * default already means — so it is refused rather than stored as a second way to spell one\n * thing (charter §4.2).\n *\n * ⚠ `excludeResourceIds` ALONE DOES NOT COUNT as a criterion. \"Everything except these three\"\n * is still everything, for every resource created after the rule was written.\n */\nexport function runnerPoolMatchIsEmpty(match: TargetSelectorQuery): boolean {\n return (\n (match.resourceGroups?.filter((group) => group.trim()).length ?? 0) === 0 &&\n Object.keys(match.tags ?? {}).length === 0 &&\n !match.namePrefix?.trim()\n );\n}\n\n/**\n * The criteria as one operator-readable clause — rendered BESIDE the rule's name everywhere,\n * so a name that has drifted from its match is a contradiction on screen (see\n * {@link RunnerPoolRuleDto}).\n *\n * Deliberately the same phrasing `describeSelector` uses for a fan-out's criteria. An admin who\n * reads \"tags (all of): network=private\" on a target selector must read the same words here,\n * because it is the same match doing the same thing.\n */\nexport function describeRunnerPoolMatch(match: TargetSelectorQuery): string {\n const parts: string[] = [];\n const groups = match.resourceGroups?.filter((group) => group.trim());\n if (groups?.length) parts.push(`resource groups: ${groups.join(\", \")}`);\n const tags = Object.entries(match.tags ?? {});\n if (tags.length) {\n parts.push(`tags (all of): ${tags.map(([key, value]) => `${key}=${value}`).join(\", \")}`);\n }\n if (match.namePrefix?.trim()) parts.push(`name prefix: \"${match.namePrefix.trim()}\"`);\n const excluded = match.excludeResourceIds?.filter((id) => id.trim());\n if (excluded?.length) {\n parts.push(`${excluded.length} excluded resource ${excluded.length === 1 ? \"id\" : \"ids\"}`);\n }\n // Unreachable through the API — `runnerPoolMatchIsEmpty` refuses it — but a stored row from\n // a future migration must still render as something a person can read.\n return parts.length > 0 ? parts.join(\"; \") : \"every resource in this connection\";\n}\n\n/** Why a run went where it went, in one clause. Used by the plan and by the pool screens. */\nexport function poolRoutingSentence(via: PoolRoutingVia): string {\n return via.source === \"default\"\n ? \"this connection's default pool\"\n : `the rule “${via.rule.name}” (${describeRunnerPoolMatch(via.rule.match)})`;\n}\n\nfunction lowerSet(values: readonly string[] | undefined): Set<string> | null {\n if (!values || values.length === 0) return null;\n const set = new Set<string>();\n for (const value of values) {\n const key = value.trim().toLowerCase();\n if (key) set.add(key);\n }\n return set.size > 0 ? set : null;\n}\n\n/** Tag keys lowered for comparison; values kept EXACTLY, per {@link matchesRunnerPoolRule}. */\nfunction lowerKeyed(tags: Record<string, string> | undefined): Map<string, string> {\n const map = new Map<string, string>();\n for (const [key, value] of Object.entries(tags ?? {})) {\n const normalized = key.trim().toLowerCase();\n if (normalized) map.set(normalized, value);\n }\n return map;\n}\n\n/** Look a tag up case-insensitively by key, returning its exact stored value. */\nfunction findTagValue(\n tags: Record<string, string> | undefined,\n key: string,\n): string | undefined {\n if (!tags) return undefined;\n const wanted = key.trim().toLowerCase();\n for (const [tagKey, value] of Object.entries(tags)) {\n if (tagKey.trim().toLowerCase() === wanted) return value;\n }\n return undefined;\n}\n","// ═══ WHICH RESOURCES — NOT ONLY HOW MANY (docs/69) ═════════════════════════════════════\n//\n// docs/66 gave a plan an honest COUNT and docs/68 set the plan's count beside the run's. Both\n// slices left the same hole: an approver was told \"1 eligible target\" about a resource this\n// system could name precisely. `azure-vm-resize.connector.ts` read `resourceGroup` and `vm` out\n// of the parameters in order to validate them, one line before returning the number 1 — and\n// `execution.repository.ts` then wrote `id: \"stub-target-1\"` into `target_resolution`, a\n// fabricated identity that reached no screen only because nothing had ever read that table.\n//\n// In a governance product, approving an unnamed resource is approving blind.\n//\n// ─── ★ THE COUNTS ARE NOT TOUCHED, AND THIS IS NOT A SECOND SPELLING OF THEM ───────────\n//\n// `TargetCounts`, `UncountedTargets`, `compareTargets` and their sentences are exactly what\n// docs/66 and docs/68 left. This file is the OTHER fact — which resources, when we can say —\n// and it reuses two vocabularies rather than minting a third:\n//\n// · the identity itself is `RoutableTarget` (docs/58), the shape a pool routing rule already\n// matches on. A second target-identity type is charter §4.2's defect, found four times in\n// this codebase already;\n// · the ABSENCE of an identity is `TargetCountAbsence` (docs/66) — `no_scope`, `unavailable`,\n// `not_attempted`. Three words already exist for \"why is this not here\", their remedies are\n// already distinct, and a fourth would tell the owner of a package action something new and\n// wrong.\n//\n// ─── ★ A COUNT WITHOUT NAMES IS LEGITIMATE, AND MUST NOT READ AS AN UNKNOWN RESOURCE ───\n//\n// \"1 eligible target, not named\" is a true and ordinary sentence: an action version whose\n// parameters carry no `discover` declaration names nothing this system can identify, and a\n// vault has an ARM id whose resource group nothing in the run carries (`resources.ts`,\n// `keyVault.identity`). The resource is not unknown to the system — it is unnamed HERE — and\n// every sentence below is worded so a reader cannot come away believing otherwise.\n\n// ★ FROM THE LEAF, NOT FROM `runner-pool-routing.ts`. Importing the routing module here is\n// what closed `execution → target-identity → runner-pool-routing → operations → execution`;\n// the identity is a leaf and this is the edge that proved it (docs/69).\nimport type { RoutableTarget } from \"./routable-target\";\nimport type { TargetCountAbsence } from \"./validation\";\nimport { BRAND_SHORT_NAME } from \"./brand\";\n\n/**\n * The resources a resolution named. `unnamed` is present and `undefined` for the same reason\n * `TargetCounts.uncounted` is (docs/66): it is what makes `if (resolved.unnamed)` narrow in\n * BOTH directions, and what makes the mixed shape — a list of names beside a reason there are\n * none — unbuildable rather than merely discouraged.\n *\n * Measured: `{ targets: [t], unnamed: \"no_scope\" }` is `Object literal may only specify known\n * properties`.\n */\nexport interface NamedTargets {\n targets: readonly RoutableTarget[];\n unnamed?: undefined;\n}\n\n/**\n * No identities, and WHICH of docs/66's three reasons is why:\n *\n * | member | what happened | what a person would do |\n * |-----------------|--------------------------------------------------|-------------------------|\n * | `no_scope` | this action names nothing Opera can identify | nothing — it is normal |\n * | `unavailable` | it names something and a value to identify it is missing | fix the parameter |\n * | `not_attempted` | nobody has resolved this phase yet | validate, or run it |\n */\nexport interface UnnamedTargets {\n unnamed: TargetCountAbsence;\n /**\n * What was actually missing, in the words of whatever could not answer. Only meaningful for\n * `unavailable` — the same rule, and the same reason, as {@link UncountedTargets.detail}.\n */\n detail?: string;\n}\n\nexport type ResolvedTargets = NamedTargets | UnnamedTargets;\n\n/**\n * The identities a run holds: what the PLAN resolved, and what the RUN resolved.\n *\n * ★ TWO FIELDS, NEVER ONE OVERWRITTEN BY THE OTHER — docs/68 §1's rule, applied to identity\n * rather than to arithmetic. What was promised and what was touched are two facts, and a record\n * that keeps only the second cannot be audited. They are two ROWS of `target_resolution`,\n * distinguished by the `phase` column that has been in the schema since migration 0004 waiting\n * for exactly this.\n */\nexport interface TargetIdentities {\n /** `phase = 'validation'` — what the approver said yes to. */\n planned: ResolvedTargets;\n /** `phase = 'execution'` — what the run resolved when it actually ran. */\n executed: ResolvedTargets;\n}\n\n/**\n * Named, in the order the resolver produced them.\n *\n * ⚠ AN EMPTY LIST IS \"WE NAMED NOTHING\", WHICH IS NOT \"WE COULD NOT NAME\". Callers that mean\n * the second must say {@link targetsUnnamed}; this is why the union exists at all, and it is\n * docs/66 §5's argument about `0/0/0` on the identity axis.\n */\nexport function namedTargets(targets: readonly RoutableTarget[]): ResolvedTargets {\n return { targets };\n}\n\n/** No identities, and why. `detail` is what could not be filled. */\nexport function targetsUnnamed(reason: TargetCountAbsence, detail?: string): ResolvedTargets {\n return detail ? { unnamed: reason, detail } : { unnamed: reason };\n}\n\n/**\n * Nobody has resolved this phase. The value a phase with no `target_resolution` row reads back\n * as, and — after migration 0074 — the value every row written before docs/69 reads back as,\n * because every identity ever written to that table was `stub-target-N`.\n */\nexport const TARGETS_NOT_NAMED: ResolvedTargets = { unnamed: \"not_attempted\" };\n\n/**\n * This action names no resource Opera can identify. Permanent and a property of the action\n * version, exactly as {@link TARGETS_NO_SCOPE} is on the count axis — a package declares its own\n * targets, and an action version whose parameters carry no `discover` declaration declares none.\n */\nexport const TARGETS_HAVE_NO_NAME: ResolvedTargets = { unnamed: \"no_scope\" };\n\n/**\n * ═══ WHAT AN OPERATOR READS FOR ONE RESOURCE — ONE AUTHOR (docs/62) ════════════════════\n *\n * The resource group is included when there is one, because a name alone is ambiguous across\n * resource groups and \"which `data-01` did we just clone?\" is not a question a run record may\n * leave open.\n *\n * ★ IT MOVED HERE FROM `operation-run-advance.handler.ts`, where it was a file-private\n * `targetLabelFor` serving the Operation fan-out's run detail. docs/69 gives the approval card\n * and the run record the same job; a second copy is how one resource comes to be written two\n * ways on two screens, which is the class docs/62 found three times in one evening.\n */\nexport function targetLabel(target: RoutableTarget): string {\n const name = target.name.trim();\n const group = target.resourceGroup?.trim();\n return group ? `${name} (${group})` : name;\n}\n\n/**\n * ═══ WHY THERE ARE NO NAMES — AND NEVER THE WORD \"UNKNOWN\" (docs/69 §3.2) ══════════════\n *\n * ★ THE WORDING IS THE REQUIREMENT, not decoration. A count without identities is a legitimate\n * answer, and a reader who takes \"not named here\" for \"we do not know what this run touches\"\n * has been told the opposite of the truth: the resource is in the run's own parameters, on the\n * same screen, under Parameters. Every branch says where the limit is — in what the action\n * DECLARED, or in a value that is missing — and none of them says the resource is unknown.\n */\nexport function unnamedTargetsSentence(unnamed: UnnamedTargets): string {\n switch (unnamed.unnamed) {\n case \"no_scope\":\n return `This action does not declare a resource ${BRAND_SHORT_NAME} can name — the run's parameters say what it acts on.`;\n case \"unavailable\":\n return unnamed.detail\n ? `${BRAND_SHORT_NAME} could not name this run's resource — ${unnamed.detail}.`\n : `${BRAND_SHORT_NAME} could not name this run's resource.`;\n case \"not_attempted\":\n return `${BRAND_SHORT_NAME} has not resolved this run's resources yet.`;\n }\n}\n\n/** The short form, for a label above a list. The same three reasons, in two or three words. */\nexport function unnamedTargetsLabel(unnamed: UnnamedTargets): string {\n switch (unnamed.unnamed) {\n case \"no_scope\":\n return \"None declared\";\n case \"unavailable\":\n return \"Could not name\";\n case \"not_attempted\":\n return \"Not resolved\";\n }\n}\n\n/**\n * ═══ READING BACK WHAT WAS STORED (docs/66's `targetSummaryOf`, on the identity axis) ═══\n *\n * `target_resolution.eligible` is jsonb and `unnamed` is a nullable text column beside it, so\n * the type says nothing about what is actually there. Anything this cannot recognise is\n * `not_attempted`, because a row nothing legible was written to has not been resolved — never\n * an empty NAMED list, which would claim the resolver ran and found nothing.\n *\n * ★ AND A ROW WITH BOTH IS READ AS UNNAMED. The union makes that unwritable in TypeScript, but\n * the database has no union: a mid-roll write by an older image, or a hand-repaired row, can\n * hold a list and a reason at once. The reason wins, because a list written beside \"I could not\n * name these\" is the fabrication this slice removes, and honouring it would let it back in.\n */\nexport function resolvedTargetsOf(stored: {\n targets: unknown;\n unnamed: unknown;\n detail?: unknown;\n}): ResolvedTargets {\n if (typeof stored.unnamed === \"string\") {\n return isTargetIdentityAbsence(stored.unnamed)\n ? targetsUnnamed(\n stored.unnamed,\n typeof stored.detail === \"string\" && stored.detail.trim() ? stored.detail : undefined,\n )\n : TARGETS_NOT_NAMED;\n }\n if (!Array.isArray(stored.targets)) return TARGETS_NOT_NAMED;\n const targets = stored.targets.flatMap((entry) => {\n const target = routableTargetOf(entry);\n return target ? [target] : [];\n });\n // A list that held entries and lost every one of them to the parser is not \"named nothing\":\n // something illegible was stored, and reporting an empty resolution would be this function\n // inventing the very answer the shape above exists to keep separate.\n if (stored.targets.length > 0 && targets.length === 0) return TARGETS_NOT_NAMED;\n return namedTargets(targets);\n}\n\n/** One stored identity, or `undefined` when it carries neither of the two required fields. */\nfunction routableTargetOf(value: unknown): RoutableTarget | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n const entry = value as Record<string, unknown>;\n const resourceId = typeof entry.resourceId === \"string\" ? entry.resourceId.trim() : \"\";\n const name = typeof entry.name === \"string\" ? entry.name.trim() : \"\";\n if (!resourceId || !name) return undefined;\n const resourceGroup =\n typeof entry.resourceGroup === \"string\" && entry.resourceGroup.trim()\n ? entry.resourceGroup.trim()\n : undefined;\n return { resourceId, name, ...(resourceGroup ? { resourceGroup } : {}) };\n}\n\n/**\n * True for a stored reason this vocabulary understands. It reads docs/66's list rather than one\n * of its own — the whole point of reusing the absences is that there is one list.\n */\nfunction isTargetIdentityAbsence(value: string): value is TargetCountAbsence {\n return value === \"no_scope\" || value === \"unavailable\" || value === \"not_attempted\";\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════════════\n// ★ WHICH ONES DIFFER (docs/69 §6)\n// ═══════════════════════════════════════════════════════════════════════════════════════\n//\n// docs/68 answered *did the run act on what was approved?* with two numbers. When they disagree\n// the next question is immediate and, until now, unanswerable without downloading two JSON\n// documents and comparing four hundred lines by eye: WHICH ones.\n//\n// ⚠ IT IS A DERIVATION AND NEVER A COLUMN, for the reason `compareTargets` is not one and\n// `poolNotice` is not one (docs/61 §3.2): a stored sentence keeps saying what it said when it\n// was written, after the vocabulary underneath it has moved.\n\n/**\n * The two named sets, set beside each other. Matched on `resourceId`, case-insensitively,\n * because ARM ids are case-insensitive and `mergeDiscoveredTargets` already de-duplicates on\n * exactly that key — a second matching rule here would make one resource two.\n */\nexport interface TargetIdentityDrift {\n /** Named by the plan, absent from the run. */\n dropped: readonly RoutableTarget[];\n /** Named by the run, absent from the plan — nobody approved these. */\n added: readonly RoutableTarget[];\n /** Named by both. */\n kept: readonly RoutableTarget[];\n}\n\n/**\n * ⚠ NULL WHEN EITHER SIDE IS UNNAMED, AND THAT IS NOT A GAP. There is no difference to state\n * between a set and an absence — the pair of COUNTS already says what happened there, in\n * `targetComparisonSentence`, and a second notice repeating it in different words would be the\n * docs/62 defect this file is otherwise careful about.\n */\nexport function compareTargetIdentities(\n planned: ResolvedTargets,\n executed: ResolvedTargets,\n): TargetIdentityDrift | null {\n if (planned.unnamed || executed.unnamed) return null;\n const key = (target: RoutableTarget) => target.resourceId.trim().toLowerCase();\n const executedIds = new Set(executed.targets.map(key));\n const plannedIds = new Set(planned.targets.map(key));\n return {\n dropped: planned.targets.filter((target) => !executedIds.has(key(target))),\n added: executed.targets.filter((target) => !plannedIds.has(key(target))),\n kept: planned.targets.filter((target) => executedIds.has(key(target))),\n };\n}\n\n/** True when the run resolved exactly the set the plan did. */\nexport function targetIdentitiesAgree(drift: TargetIdentityDrift): boolean {\n return drift.dropped.length === 0 && drift.added.length === 0;\n}\n\n/**\n * How many resources a SENTENCE names before it counts the rest. Three, not\n * {@link TARGET_LIST_SHOWN}'s twenty, because this is prose in a notice and that is a scrollable\n * list: a paragraph naming twenty machines is not read, and the list beneath it is where a\n * reader goes for all of them.\n */\nexport const TARGET_NAMES_IN_A_SENTENCE = 3;\n\n/**\n * ═══ THE ONE PLACE A DIFFERENCE IN IDENTITY BECOMES WORDS (docs/69 §9.5) ═══════════════\n *\n * The run record's notice and the resolved-target list's heading both read this. Change the\n * wording here and both move; there is nowhere else a {@link TargetIdentityDrift} is turned into\n * a sentence, which `targets-render-through-one-module.spec.ts` pins by grepping the call sites.\n *\n * ★ IT NAMES THE RESOURCES RATHER THAN COUNTING THEM, up to\n * {@link TARGET_NAMES_IN_A_SENTENCE}. \"3 resources differ\" sends the reader somewhere else to\n * find out which; the whole slice is that they should not have to.\n *\n * ⚠ NULL WHEN NOTHING DIFFERS. A notice on every matching run buries the ones that matter —\n * the rule `targetComparisonLabel` already established for the feed row's marker.\n */\nexport function targetIdentityDriftSentence(drift: TargetIdentityDrift): string | null {\n if (drift.dropped.length === 0 && drift.added.length === 0) return null;\n const separable = labelsSeparate(drift);\n const clauses: string[] = [];\n if (drift.dropped.length > 0) {\n clauses.push(\n `did not act on ${countedResources(drift.dropped.length)} the plan named` +\n (separable ? ` — ${nameList(drift.dropped)}` : \"\"),\n );\n }\n if (drift.added.length > 0) {\n clauses.push(\n `acted on ${countedResources(drift.added.length)} the plan did not name` +\n (separable ? ` — ${nameList(drift.added)}` : \"\"),\n );\n }\n return (\n `This run ${clauses.join(\"; and it \")}.` +\n (separable ? \"\" : \" Their names do not tell them apart — the ids below do.\")\n );\n}\n\n/**\n * ═══ WHETHER NAMING THEM HELPS, OR MISLEADS (measured in a browser) ════════════════════\n *\n * ★ THIS EXISTS BECAUSE THE SCREEN SHOWED IT AND NO TEST DID. Driving a real drifted run —\n * a connection scope re-pointed at another subscription between approval and execution — the\n * notice rendered:\n *\n * \"This run did not act on 1 resource the plan named — payments (rg-data-prod); and it\n * acted on 1 resource the plan did not name — payments (rg-data-prod).\"\n *\n * The same words, twice, about two genuinely different databases. {@link targetLabel} shows a\n * name and its resource group, which docs/58 chose because a name alone is ambiguous ACROSS\n * RESOURCE GROUPS — and that is exactly as far as it goes. Across SUBSCRIPTIONS it separates\n * nothing, and a sentence that names two different resources with one string reads as a bug in\n * the product rather than as a fact about the estate.\n *\n * ★ SO THE SENTENCE COUNTS INSTEAD, AND SAYS WHY. It does not reach for the resource id: an ARM\n * id is 130 characters of prose nobody reads, and the list directly beneath already shows both\n * ids against their markers. What the sentence owes the reader here is the honest reason it is\n * not naming them, which is the last clause.\n *\n * ⚠ THE TEST IS ACROSS THE TWO SIDES, NOT WITHIN ONE. Two dropped resources sharing a label are\n * still listed as two rows with two ids and nothing is confusing; what misleads is the SAME\n * words appearing on both sides of \"and it\".\n */\nfunction labelsSeparate(drift: TargetIdentityDrift): boolean {\n const dropped = new Set(drift.dropped.map(targetLabel));\n return drift.added.every((target) => !dropped.has(targetLabel(target)));\n}\n\nfunction countedResources(total: number): string {\n return `${total} ${total === 1 ? \"resource\" : \"resources\"}`;\n}\n\n/** `a, b and 2 more` — the sentence's own bound, applied in one place. */\nfunction nameList(targets: readonly RoutableTarget[]): string {\n const shown = targets.slice(0, TARGET_NAMES_IN_A_SENTENCE).map(targetLabel);\n const rest = targets.length - shown.length;\n if (rest > 0) shown.push(`${rest} more`);\n if (shown.length === 1) return shown[0]!;\n return `${shown.slice(0, -1).join(\", \")} and ${shown[shown.length - 1]}`;\n}\n\n/**\n * ═══ HOW MANY RESOURCES A SCREEN RENDERS BEFORE IT SUMMARISES (docs/69 §6) ═════════════\n *\n * > An Operation fanning out over a tag that matches 400 VMs, of which 12 are excluded and 3\n * > blocked — approved by a person who has 30 seconds to decide.\n *\n * The RECORD holds all of them; the screen shows enough to decide and says how many it is not\n * showing. Rendering four hundred rows into an approval card is a defect and not thoroughness.\n *\n * ★ THE NUMBER IS SHARED, THE SENTENCE IS NOT — deliberately, and it is the one place this file\n * lets two surfaces word something for themselves. The Approval Center's line ends \"Approving\n * covers all 415\", which is a statement about a DECISION and is false on a run record; the run\n * record's is about a list. What must not differ is the BOUND, because a reader comparing an\n * approval against the run it produced would otherwise be comparing two different prefixes of\n * the same set.\n */\nexport const TARGET_LIST_SHOWN = 20;\n","/**\n * ═══ TWO QUESTIONS THAT BOTH SAY \"ENTRA\", NAMED APART (docs/73 §3.3) ═══════════════════\n *\n * A prospect asked: *\"Since we have WorkOS now, do we need the Entra ID app installation in\n * the customer tenant, or is that taken care of by WorkOS? The sign-in screen shows different\n * methods.\"* Two unrelated things wear the same word, and nothing in the product said so:\n *\n * signing in WHO THE HUMAN IS. Nothing is installed in their directory.\n * connecting Azure WHAT OPERA MAY DO. A service principal in their tenant, always.\n *\n * ★ THE SENTENCES LIVE HERE BECAUSE THEY ARE ONE ANSWER GIVEN IN TWO PLACES. A surface that\n * re-types them is a second author for a fact that already had one, and the day one of them is\n * edited the two screens disagree with nothing to say which is current (docs/62). Publishing\n * them from the barrel also enrols them in `no-sentence-copies.spec.ts`, whose corpus is walked\n * from the exports at run time — so these are guarded the moment they exist, by nobody\n * remembering anything.\n *\n * ═══ ★ THE SIGN-IN HALF STOPPED NAMING A CLOUD, 2026-09-10 (docs/81 §3) ════════════════\n *\n * `SIGN_IN_ENTRA_SENTENCE` used to end \"letting Opera act on your AZURE resources is a separate\n * step\". Correct — `connections/domain/providers/` holds exactly one adapter — and still wrong\n * in kind: it named one cloud on the screen that is about IDENTITY, on a platform meant to\n * reach more than one. The sentence did two jobs and they are now split by SUBJECT:\n *\n * sign-in screen the directory question, answered without a vendor. Both clauses of the\n * prospect's answer survive: signing in installs nothing, AND acting on\n * resources is a separate step that does need an identity. Only the cloud\n * name left, because only the cloud name dates.\n * cloud-connect `AZURE_CONNECTION_ENTRA_SENTENCE`, which ALREADY carried the\n * screen cloud-specific half (\"connecting Azure is a different question from\n * signing in\") on the screen where Azure is the subject. Nothing had to\n * be merged — the half simply stopped being said twice, in one of which\n * places the reader has not chosen a cloud yet.\n *\n * ⚠ THE REASSURANCE IS NOT WEAKENED, and deleting it would be a regression to before docs/73:\n * the prospect's question was whether WorkOS removed the need for an app registration, and a\n * sign-in screen silent about directories does not answer it.\n *\n * ⚠ THE COPY BELOW IS LOAD-BEARING AND EVERY CLAUSE OF IT WAS MEASURED, 2026-09-07 — and the\n * clause that moved took its evidence with it:\n *\n * SIGN_IN_ENTRA_SENTENCE\n * \"installs nothing\" `entra.verifier.ts` accepts exactly ONE issuer, Opera's own\n * tenant. Sign-in never reaches a customer directory at all.\n * \"a separate step ... `connections/` is reached by no sign-in path, and every adapter's\n * does need an identity\" `onboardingSchema` asks for a principal in the reader's own\n * directory. True of the one adapter that exists and of the shape\n * `provider-adapter.port.ts` requires of the next one.\n *\n * AZURE_CONNECTION_ENTRA_SENTENCE / AZURE_CONNECTION_PRINCIPAL_SENTENCE\n * \"Azure\", \"subscription\" MEASURED 2026-09-10: `connections/domain/providers/` holds one\n * adapter, `azure-provider.adapter.ts`. Naming the cloud is correct\n * HERE because the reader is on the screen that connects it.\n * \"app registration or\n * managed identity\" `azure-provider.adapter.ts` `onboardingSchema` asks for\n * `azureTenantId` + `clientId`, titled either way by mechanism.\n * \"no secret leaves\" `buildTrust` issues a FEDERATED credential; there is no secret\n * field on the schema.\n * \"only what your Azure\n * role assignments allow\" the adapter's own step 3, and `discoverScopes` sees exactly the\n * subscriptions RBAC grants it.\n * \"never asks for\n * Microsoft Graph\" `AZURE_AUDIENCES` is `arm` + `key-vault-data` and nothing else;\n * `graph.microsoft.com` appears NOWHERE in this repository.\n * \"revoke\" removing the federated credential or the role assignment is done\n * wholly in the customer's portal — Opera holds nothing to revoke.\n *\n * ★ AND WHAT THESE SENTENCES DELIBERATELY DO NOT SAY: anything about the reader's own\n * directory. We do not know whether they run Entra ID, whether their tenant already has an app\n * registration, or how their SSO is arranged. Every clause is about what OPERA needs and what\n * OPERA asks for — the only two things we can actually speak to.\n */\n\n/**\n * On the sign-in screen. Answers the question at the moment it is asked, rather than in a\n * help-centre article the confused reader is not reading (docs/73 §3.3).\n *\n * ⚠ NAMES NO CLOUD AND NO IDENTITY VENDOR, ON PURPOSE (docs/81 §3). A reader on this screen has\n * not chosen a cloud and may not run Entra; the sentence is about what OPERA does, which is the\n * only thing we can speak to. `AZURE_CONNECTION_ENTRA_SENTENCE` names the cloud on the screen\n * where the reader has picked one.\n */\n\nimport { BRAND_SHORT_NAME } from \"./brand\";\n\nexport const SIGN_IN_ENTRA_SENTENCE =\n `Signing in installs nothing in your identity directory. Letting ${BRAND_SHORT_NAME} act on your cloud ` +\n \"resources is a separate step, set up later, and that one does need an identity in the \" +\n \"directory that owns them.\";\n\n/** On the Azure-connection screen, naming which Entra this one is. */\nexport const AZURE_CONNECTION_ENTRA_SENTENCE =\n \"This is the other Entra. Connecting Azure is a different question from signing in: this \" +\n `step is about the Microsoft Entra tenant that owns the subscription you want ${BRAND_SHORT_NAME} to act ` +\n \"on.\";\n\n/**\n * The same screen, stating the principal plainly: that it is required, what it can do, and\n * that revoking it is entirely theirs to do (docs/73 §9.5).\n */\nexport const AZURE_CONNECTION_PRINCIPAL_SENTENCE =\n `${BRAND_SHORT_NAME} needs a service principal in that tenant — an app registration or a managed identity ` +\n \"— and it is required: there is no way to act on your resources without one. No secret \" +\n \"leaves your tenant; the trust is a federated credential you create below. It can do only \" +\n \"what your Azure role assignments allow, on the subscriptions or resource groups you pick, \" +\n `and ${BRAND_SHORT_NAME} never asks for Microsoft Graph or any directory permission. You can revoke it at ` +\n \"any time in your own portal by removing the federated credential or the role assignment.\";\n","/**\n * ═══ THE APP ASKS BEFORE IT FORKS (docs/75 §3.2) ═══════════════════════════════════════\n *\n * WorkOS's own documentation is the line that decides this vocabulary:\n *\n * \"WorkOS doesn't magically decide when a user may create a company workspace. Normally\n * your application provides the 'Create organization' UI, then calls the WorkOS\n * Organization API.\"\n *\n * Until docs/75 Opera decided for them. A new self-serve user with no invitation was handed\n * `\"<localpart>'s workspace\"` and made its admin, silently — which is how the founder signed\n * in through a second door on 2026-09-06 and was given an empty second workspace beside the\n * one holding his connections, runners and history.\n *\n * ★ THREE QUESTIONS, NOT ONE. The previous draft of this work (docs/74, withdrawn) would have\n * ANNOUNCED the silent fork after the fact. What replaced it is not a better announcement, it\n * is asking — and the question is not the same question for everybody:\n *\n * pending invitation │ verified domain │ what the app asks\n * ───────────────────┼─────────────────┼──────────────────────────────────────────────────\n * yes │ either │ NAMED \"Join Acme — Alice invited you\"\n * no │ yes │ OFFERED \"Your colleagues are in Acme. Join?\"\n * no │ no │ ASKED \"What should we call your workspace?\"\n *\n * An invitation outranks a domain match because somebody specifically asked for THIS person,\n * and it carries role grants a domain match cannot (`Invitation.roles`, `scopeType`/`scopeId`).\n * Offering \"create or join\" to a reader with nothing to join is a worse screen than asking\n * them to name their company, which is why `create` is a QUESTION and not a third option\n * printed beside two dead ones.\n *\n * ⚠ THE UNION IS THE POINT. A single flat DTO with three optional halves would let a screen\n * render \"Alice invited you\" beside an empty workspace-name field, and nothing would notice.\n * Discriminating on `ask` means a renderer that forgets a case does not compile.\n */\nimport type { RoleKey } from \"./enums\";\n\n/**\n * WHAT THE APP ASKS a user who has no workspace yet.\n *\n * `ask` is the discriminant and the three arms are exhaustive: every authenticated user with\n * no Opera tenant falls in exactly one, decided server-side. The client never computes it —\n * a browser cannot see another tenant's invitations, and must not be told about them.\n */\nexport type OnboardingQuestion =\n | InvitedQuestion\n | DomainMatchQuestion\n | NameYourWorkspaceQuestion;\n\n/**\n * Somebody invited this person by name. The workspace and the inviter are stated, because\n * \"you have been invited\" without saying BY WHOM to WHAT is the announcement docs/74 was\n * withdrawn for.\n */\nexport interface InvitedQuestion {\n ask: \"invited\";\n invitation: {\n id: string;\n /** The workspace they are joining, as its members see it. */\n workspaceName: string;\n /** Who sent it — a display name, never an email. */\n invitedByName: string;\n /** The grants Opera will apply on accept. Shown so the reader knows what they get. */\n roles: RoleKey[];\n expiresAt: string;\n };\n /**\n * Declining an invitation does not strand the reader: they fall through to whatever they\n * would otherwise have been asked. Carried on the SAME document so the screen never has to\n * ask the server a second question to render its own secondary action.\n */\n otherwise: DomainMatchQuestion | NameYourWorkspaceQuestion;\n}\n\n/**\n * Nobody invited them, but their verified email address is at a domain some existing workspace\n * has PROVED it holds.\n *\n * ★ WHY THAT IS AN OFFER AND NOT A TAKEOVER VECTOR, STATED CORRECTLY (docs/78, docs/81 §2).\n * Opera provides BOTH properties this rests on, and WorkOS provides neither:\n *\n * the proof a DNS TXT record the workspace published and a check confirmed, held in\n * `workspace_domain` and re-confirmed on a schedule (docs/79 §3).\n * the exclusivity the partial unique index `workspace_domain_domain_verified_key`, so at\n * most one workspace in the estate can hold a domain verified.\n *\n * WorkOS holds the published CONSEQUENCE — the organization's domain policy — and is told when\n * the domain changes. It is downstream of the decision, never the thing that makes it.\n *\n * ⚠ THIS COMMENT USED TO SAY THE OPPOSITE, AND THAT IS WHY IT SAYS SO MUCH. It gave \"WorkOS\n * holds a domain against ONE organization per environment\" as the reason the offer is safe.\n * MEASURED FALSE 2026-09-08 against the real WorkOS staging API: three organizations were\n * given the same domain and two of them were flipped to `verified` beside each other, all\n * accepted. The behaviour here was already correct; the stated reason was not, and a future\n * decision made from it would have been wrong.\n */\nexport interface DomainMatchQuestion {\n ask: \"domain\";\n domain: {\n /** The organization they may join. */\n workspaceName: string;\n /** The WorkOS organization id — echoed back on accept, never invented by the client. */\n organizationId: string;\n /** The matched domain, so the reader can see WHY they are being offered this. */\n domain: string;\n };\n /** Joining is an offer, not a redirect: creating their own remains available. */\n otherwise: NameYourWorkspaceQuestion;\n}\n\n/**\n * Neither. This is the only arm that asks for a workspace NAME, and the only one that calls\n * `organizations.create`.\n */\nexport interface NameYourWorkspaceQuestion {\n ask: \"create\";\n /**\n * A starting point for the name field, derived from the email domain (`acme.com` → `Acme`),\n * or null when there is nothing honest to suggest. A SUGGESTION, not a default that gets\n * committed if the reader says nothing — saying nothing is how the old defect worked.\n */\n suggestedName: string | null;\n /**\n * The domain this workspace MAY claim, or null when it must not be offered at all.\n *\n * ⚠ NULL FOR A PUBLIC EMAIL PROVIDER, AND THAT CONCLUSION IS NOT NEGOTIABLE. A workspace\n * that held `gmail.com` verified would be offered to every Gmail sign-up in the estate, for\n * ever, and by the partial unique index no second workspace could ever hold it.\n *\n * The protections that make this survivable are Opera's own, and none of them is a WorkOS\n * property (docs/81 §2 — the reason given here before was measured false):\n *\n * a claim is ONE WORKSPACE WIDE the unique index admits exactly one holder, so the\n * first mailbox provider to be claimed is also the last.\n * it GRANTS NOTHING UNVERIFIED a claim admits nobody until a DNS TXT record in that\n * zone is published AND confirmed — which nobody outside\n * the zone's operator can do (docs/78 §3.1).\n * mailbox providers are REFUSED `workspace-domain.ts` names them, and a named domain is\n * BY NAME never offered in the first place.\n * a PERSON IS ASKED nothing is claimed by a page loading; the offer names\n * the exact domain and can be declined.\n *\n * The name list is a floor and not a fence — it cannot be complete — so the three protections\n * above are the ones carrying the weight, and they hold for a provider nobody listed.\n */\n claimableDomain: string | null;\n}\n\n/** Body of `POST /onboarding/workspace` — the create arm, and the only one that names. */\nexport interface CreateWorkspaceInput {\n name: string;\n /**\n * Let anybody with a verified email at this domain join without an invitation. Must equal\n * the `claimableDomain` the server offered, or be absent. The client cannot widen it.\n */\n claimDomain?: string;\n}\n\n/**\n * Body of `POST /onboarding/join` — the two join arms, discriminated the same way the\n * question was. An `organizationId` and an `invitationId` are different facts with different\n * consequences (a domain join gets the conservative default role; an invitation gets the\n * grants it carries), so they are not one nullable field.\n */\nexport type JoinWorkspaceInput =\n | { join: \"invitation\"; invitationId: string }\n | { join: \"domain\"; organizationId: string };\n\n/**\n * What both onboarding actions return: the workspace now joined. The client's next move is\n * always the same — re-fetch `/me` — so this carries only what a confirmation screen needs.\n */\nexport interface WorkspaceJoinedDto {\n tenantId: string;\n workspaceName: string;\n /** The WorkOS organization this tenant maps to, one-to-one (docs/75 §1). */\n organizationId: string;\n /** The grants Opera applied. Applied BY OPERA — WorkOS never sees a RoleKey (§3.1). */\n roles: RoleKey[];\n}\n\n/**\n * ★ THE MACHINE CODE ON THE 403 that says \"you are signed in and you have no workspace\".\n *\n * Not a 401. A 401 tells the client its token was rejected, and the shell's only sane\n * response to that is to sign the user out — which would put a brand-new user in a loop\n * between AuthKit and a rejection, signed in and unable to stay. This user's token is\n * perfectly good; what they lack is a tenant, and the answer is a screen, not a sign-out.\n *\n * Published here so the shell branches on a CONSTANT rather than re-spelling the string —\n * the class of defect `problem.ts` exists for.\n */\nexport const NO_WORKSPACE_CODE = \"NO_WORKSPACE\";\n","/**\n * ═══ A DOMAIN IS VERIFIED WHEN DNS SAYS SO, AND NOT BEFORE (docs/78 §3.1) ═══════════════\n *\n * Until docs/78 a workspace's domain was written to WorkOS as `verified` at sign-up, because\n * the person signing up had a MAILBOX at it. No record was ever requested, published, polled\n * or read. Controlling one inbox is not controlling a domain, and a \"verified\" domain is the\n * authorization boundary that lets every later sign-up at that domain into the workspace.\n *\n * ★ MEASURED 2026-09-08 AGAINST THE REAL WORKOS STAGING API, and it changes the model: WorkOS\n * does NOT make a domain exclusive to one organization. Three organizations were given the\n * same domain — two `pending`, one `verified` — and a second was then flipped to `verified`\n * beside the first, all accepted. So the two properties this feature rests on, PROOF and\n * EXCLUSIVITY, are both Opera's to provide. WorkOS holds the published consequence.\n *\n * This file is the vocabulary of that proof: what a workspace must publish, what a check can\n * find, and the sentence each outcome owes the reader.\n */\n\n/**\n * Where a claim stands. Three values (docs/79 §3.5):\n *\n * pending no proof yet — the workspace must publish the record below\n * verified this workspace holds the domain AND the proof is current\n * unconfirmed this workspace holds the domain AND the proof is not currently confirmable:\n * the last check found the zone answering without the record, or no check has\n * confirmed it for {@link DOMAIN_PROOF_MAX_AGE_DAYS} days. The grant is\n * suspended; the domain is NOT surrendered, and the record is NOT changed.\n *\n * `unconfirmed` earns its place over reusing `pending` because the reader's next move differs:\n * a pending workspace needs to publish a record; an unconfirmed one needs the record it\n * ALREADY published to be visible again. The sentence \"not verified\" is wrong for it.\n *\n * ★ PINNED, NOT BRANCHED. Every consumer keys a `Record<WorkspaceDomainState, …>` on this\n * union — the sentences below, the screen's badge tone and label — so a member added here\n * cannot compile until each consumer has answered for it (charter §4.2). Measured before the\n * pin existed: the domain screen collapsed this to `state === \"verified\"`, and a third member\n * would have rendered as \"not verified\" — telling an admin to publish a record they had\n * already published. The pin went in first, as its own commit; this member came second.\n *\n * ★ THE STATE IS NEVER STORED. It is derived by {@link workspaceDomainState} — the ONE author\n * of the freshness rule — from two timestamps and the clock.\n */\nexport const WORKSPACE_DOMAIN_STATES = [\"pending\", \"verified\", \"unconfirmed\"] as const;\nexport type WorkspaceDomainState = (typeof WORKSPACE_DOMAIN_STATES)[number];\n\n/**\n * ═══ HOW LONG A PROOF OF DOMAIN CONTROL STAYS CURRENT (docs/79 §2) ═══════════════════════\n *\n * The CA/Browser Forum has a dated schedule for exactly this question — how long may proof of\n * domain control be REUSED before it must be redone. Ballot SC081v3 shrinks it deliberately:\n * 398 days before 2026-03-15, **200 days now**, 100 days from 2027-03-15, **10 days** from\n * 2029-03-15. Their stated reason is ours: \"organizations can no longer rely on occasional,\n * manual validation.\" Two closer anchors: Let's Encrypt caches a domain authorization for\n * **30 days** and then redoes the challenge — a TXT record, an automated re-check, no human,\n * the nearest working system to this one; and PyPI, after 1,800 accounts were exposed to\n * expired-domain takeover, re-checks **every 30 days** and marks the address UNVERIFIED rather\n * than deleting it — which is the suspend-never-surrender rule of docs/79 §3.3.\n *\n * So: stricter than the ceiling, no stricter than Let's Encrypt, and tight is free because\n * the re-check is one DNS query with no human in it. The direction of the field's schedule is\n * the finding; this number sits inside every published bound today and in 2029.\n */\nexport const DOMAIN_PROOF_MAX_AGE_DAYS = 30;\nexport const DOMAIN_PROOF_MAX_AGE_MS = DOMAIN_PROOF_MAX_AGE_DAYS * 24 * 60 * 60 * 1000;\n\n/** The two timestamps a claim row carries; the state is a function of them and the clock. */\nexport interface DomainProofTimestamps {\n /** Since when this workspace holds the domain; null until a check first finds the record. */\n verifiedAt: Date | null;\n /** The last moment a check CONFIRMED the record; null when the last check found it absent. */\n lastVerifiedAt: Date | null;\n}\n\n/**\n * ═══ THE FRESHNESS RULE, DECLARED ONCE (docs/79 §3.4) ════════════════════════════════════\n *\n * The one expression, and nothing else decides it:\n *\n * current ⇔ verifiedAt ≠ null ∧ lastVerifiedAt ≠ null ∧ age(lastVerifiedAt) ≤ 30 days\n *\n * The join gate, the DTO the screen renders, the sweep's audit transitions and every test\n * call THIS. Positive evidence of absence (`lastVerifiedAt = null`) suspends immediately;\n * absence of evidence (no check reached DNS) ages out — that asymmetry is the security\n * argument, and it is safe because an attacker who controls the domain cannot make our\n * resolver fail; they can only fail to publish our record, which is the immediate branch.\n *\n * ★ Deliberately NOT in a sweep: a design whose security depends on a cron running fails\n * OPEN the day the cron breaks. With the test here, a broken sweep means proofs age out and\n * the gate stops granting — it fails closed, and the admin's manual check still refreshes.\n */\nexport function workspaceDomainState(\n proof: DomainProofTimestamps,\n now: Date,\n): WorkspaceDomainState {\n const current =\n proof.verifiedAt !== null &&\n proof.lastVerifiedAt !== null &&\n now.getTime() - proof.lastVerifiedAt.getTime() <= DOMAIN_PROOF_MAX_AGE_MS;\n if (current) return \"verified\";\n return proof.verifiedAt === null ? \"pending\" : \"unconfirmed\";\n}\n\n/**\n * What ONE check can conclude. Array-first (charter §4.2); the sentences below are keyed by\n * it so a new outcome cannot compile until it has words.\n *\n * verified the record was found and the domain is now verified\n * record_missing the zone answered and the record is not there (`found` says what is)\n * domain_unknown the domain itself does not resolve — NXDOMAIN\n * dns_unreachable no answer, or a server failure — a fact about the check, not the domain\n * challenge_expired the record would not be accepted even if present; mint a new one\n * held_elsewhere another workspace holds this domain verified AND its record is still\n * published — the DNS owner has to choose\n */\nexport const DOMAIN_CHECK_OUTCOMES = [\n \"verified\",\n \"record_missing\",\n \"domain_unknown\",\n \"dns_unreachable\",\n \"challenge_expired\",\n \"held_elsewhere\",\n] as const;\nexport type DomainCheckOutcome = (typeof DOMAIN_CHECK_OUTCOMES)[number];\n\n/** The record a workspace is asked to publish. A TXT at the apex, prefixed so it can coexist. */\nexport interface DomainRecord {\n /** The DNS name to publish at — the domain itself. */\n name: string;\n type: \"TXT\";\n /** `runveric-domain-verification=<token>`. */\n value: string;\n}\n\n/**\n * The prefix that makes the value recognisable among the SPF and vendor records an apex\n * already carries. One author for it: the api mints values with it, the check looks for it,\n * and the screen renders what the api sent.\n */\nexport const DOMAIN_VERIFICATION_RECORD_PREFIX = \"runveric-domain-verification=\";\n\n/** Pure: the record a given challenge token asks for. */\nexport function domainVerificationRecord(domain: string, token: string): DomainRecord {\n return { name: domain, type: \"TXT\", value: `${DOMAIN_VERIFICATION_RECORD_PREFIX}${token}` };\n}\n\n/**\n * What the last check looked for and what it found — BOTH, always. \"Could not verify\" is\n * named by the field as the sentence that kills this flow (docs/78 §2), and this codebase\n * has closed that defect three times before.\n */\nexport interface DomainCheckDto {\n at: string;\n outcome: DomainCheckOutcome;\n /** The record the check looked for. */\n expected: DomainRecord;\n /** Every TXT value the zone answered with, verbatim. Empty when nothing answered. */\n found: string[];\n /** The resolver's own error code when the check could not complete (`dns_unreachable`). */\n detail: string | null;\n}\n\nexport interface WorkspaceDomainDto {\n id: string;\n domain: string;\n /** Derived server-side by {@link workspaceDomainState}; the screen never compares clocks. */\n state: WorkspaceDomainState;\n claimedAt: string;\n /**\n * Since when this workspace holds the domain — set by the first check that found the\n * record, unchanged by later ones. Cleared only by a decision (release, or a lost contest).\n */\n verifiedAt: string | null;\n /**\n * The last moment a check CONFIRMED the record. Null before the first proof, and null again\n * when the last check found the zone answering without it (docs/79 §3.4).\n */\n lastVerifiedAt: string | null;\n challenge: {\n record: DomainRecord;\n /** Null once verified: the record must stay published and is re-read on every check. */\n expiresAt: string | null;\n /** Derived server-side so the screen never compares clocks. */\n expired: boolean;\n };\n lastCheck: DomainCheckDto | null;\n}\n\n/**\n * The domain screen's whole answer. `claimable` is computed SERVER-SIDE from the caller's\n * verified email — the same rule sign-up uses — so the screen offers only what the server\n * would accept, and never has to know what a mailbox provider is.\n */\nexport interface WorkspaceDomainsDto {\n domains: WorkspaceDomainDto[];\n /** The domain this caller could claim now, or null: nothing claimable, or already claimed. */\n claimable: string | null;\n}\n\nexport interface ClaimWorkspaceDomainInput {\n domain: string;\n}\n\n/**\n * The sentence each outcome owes the reader, with the RECORD and the DOMAIN supplied by the\n * structured fields beside it rather than baked in here. Constants, not a function: docs/62's\n * copy guard walks this package's exported strings, and prose inside a function is outside\n * its corpus. Each is at least seven words so the guard's window can see it.\n */\nexport const DOMAIN_CHECK_OUTCOME_SENTENCE: Record<DomainCheckOutcome, string> = {\n verified: \"The record was found and this domain is verified for this workspace.\",\n record_missing:\n \"The zone answered, but the record this workspace must publish was not among its TXT values.\",\n domain_unknown:\n \"This domain does not resolve at all, so no record could be looked for on it yet.\",\n dns_unreachable:\n \"The DNS check could not complete, which says nothing about the record itself yet.\",\n challenge_expired:\n \"The challenge has expired and a record carrying it would not be accepted any more.\",\n held_elsewhere:\n \"Another workspace holds this domain verified and its own record is still published there.\",\n};\n\n/**\n * The sentence each STATE owes the reader on the claim card, beside the badge. Keyed by the\n * state so a new state cannot compile without words; constants, not a function, for the\n * docs/62 copy guard's sake. The date a proof was taken is a structured field beside it.\n */\nexport const WORKSPACE_DOMAIN_STATE_SENTENCE: Record<WorkspaceDomainState, string> = {\n pending: \"Nobody can join by this domain until the record below is found in its zone.\",\n // The number is DERIVED from the constant above, never typed here: one author for both.\n verified:\n \"Colleagues with an address at this domain can join without an invitation. The record \" +\n \"must stay published: it is read again by later checks, and a proof that no check can \" +\n `confirm for ${DOMAIN_PROOF_MAX_AGE_DAYS} days lapses until one does.`,\n // Never \"not verified\": the reader published the record already. What they need is for the\n // value they published to be visible again, not a different one.\n unconfirmed:\n \"This workspace still holds the domain, but its record could not be confirmed recently, \" +\n \"so nobody can join by it until a check finds the record again. The record itself has \" +\n \"not changed; make the value below visible in the zone, then check again.\",\n};\n\n/**\n * What releasing the claim costs, by state — the confirmation dialog's one sentence. A\n * verified domain is an authorization boundary and the dialog must say what closes; a\n * pending claim is an intention and the dialog says only what is discarded.\n */\nexport const WORKSPACE_DOMAIN_RELEASE_CONSEQUENCE: Record<WorkspaceDomainState, string> = {\n pending:\n \"The claim and its record are discarded. You can claim the domain again later, with a new record.\",\n verified:\n \"Colleagues will no longer be able to join by this domain. Members already in the workspace keep their access.\",\n unconfirmed:\n \"The workspace gives up the domain it still holds. Claiming it again later means publishing a new record, and another workspace may take it meanwhile.\",\n};\n","/**\n * ═══ A CAPABILITY THAT IS BOUGHT, NOT DEPLOYED (docs/80 §3.2) ═══════════════════════════\n *\n * Every capability toggle in this codebase before this file is DEPLOYMENT-WIDE: about twenty\n * `*_ENABLED` entries in `apps/api/src/platform/config/config.ts`, each one true or false for\n * the whole estate at once. That shape is right for a thing we either built or did not build\n * — `WORKOS_ENABLED`, `PACKAGE_RUNNER_ENABLED` — and it is wrong for a thing a workspace BUYS.\n *\n * Directory sync is bought per workspace. WorkOS Directory Sync is USD 125 per connection, so\n * \"is directory sync on\" has as many answers as there are workspaces, and an `*_ENABLED` flag\n * would have to be torn out on the day pricing lands. It is declared here instead, as a\n * vocabulary of features a workspace may hold, backed by a per-tenant store.\n *\n * ★ WHAT PRICING MUST DO WHEN IT ARRIVES, RECORDED NOW SO IT IS NOT REDISCOVERED: write rows\n * into `workspace_entitlement`, keyed by tenant and by one of these feature keys. Nothing else\n * about directory sync will need to change. There is deliberately no plan, no price, no\n * billing and no self-service upgrade in this slice — until pricing exists the grant is an\n * operator action and `docs/azure-deploy.md` carries the SQL.\n *\n * ─── ARRAY-FIRST, AND WHAT PINS IT (charter §4.2) ────────────────────────────────────────\n *\n * The array is the vocabulary. {@link WORKSPACE_FEATURE_COPY} is `as const satisfies\n * Record<WorkspaceFeature, …>`, which is checked in BOTH directions — a feature added to the\n * array without copy here is a missing-property error, and copy for a feature the array does\n * not declare is an excess-property error. Every consumer keys a `Record<WorkspaceFeature, …>`\n * the same way, so a second member cannot compile until each of them has answered for it.\n * That is the moment somebody is actually in a position to say what the new feature costs and\n * what its screen says.\n */\n\n/** Every feature a workspace may be entitled to. One member today, and that is honest. */\n\nimport { BRAND_SHORT_NAME } from \"./brand\";\n\nexport const WORKSPACE_FEATURES = [\"directory_sync\"] as const;\n\nexport type WorkspaceFeature = (typeof WORKSPACE_FEATURES)[number];\n\n/** What a feature is called, and what a workspace without it reads. */\nexport interface WorkspaceFeatureCopy {\n /** The feature's name wherever it is named. Declared once so two screens cannot differ. */\n name: string;\n /**\n * The sentence for a workspace that does not hold it.\n *\n * Its audience is somebody who may become a customer, so it names the remedy and who owns\n * it — and stops there. A settings screen is not a place to be sold to; it is a place to\n * find out why a control will not work and who can change that.\n */\n notEntitled: string;\n}\n\nexport const WORKSPACE_FEATURE_COPY = {\n directory_sync: {\n name: \"Directory sync\",\n notEntitled:\n `Group membership is managed here in ${BRAND_SHORT_NAME}. Mirroring groups from your identity provider is a paid add-on — contact ${BRAND_SHORT_NAME} to turn it on for this workspace.`,\n },\n} as const satisfies Record<WorkspaceFeature, WorkspaceFeatureCopy>;\n\n/**\n * Is this stored string one of the features this build knows?\n *\n * ⚠ A ROW NAMING A FEATURE THIS BUILD HAS NEVER HEARD OF IS IGNORED, NOT AN ERROR, and that\n * is deliberate rather than lax. The pricing system will one day write grants, and it may\n * write a grant for a feature whose api revision has not rolled yet. An older api must read\n * such a row as \"not a feature I can serve\" and carry on; it must never crash a sign-in over\n * a row it does not recognise, and it must never DELETE it. The row stays; the newer revision\n * reads it. This is a version skew resolved by time, not a silent discard of anybody's intent.\n */\nexport function isWorkspaceFeature(value: string): value is WorkspaceFeature {\n return (WORKSPACE_FEATURES as readonly string[]).includes(value);\n}\n","/**\n * ═══ WHETHER A GROUP CAN BE LINKED TO A DIRECTORY, AND WHY NOT (docs/80 §3.1/§3.3) ══════\n *\n * Settings → Groups has offered \"link this group to a directory group\" since docs/25. The\n * route, the service, the repository, the schema (`group.source` / `directory_ref` /\n * `directory_synced_at`) and the screen all exist and all work. Nothing has ever populated\n * them, and the chain is short enough to state:\n *\n * the reconciler runs only on a claim `identity.repository.ts` `externalGroupIds !== undefined`\n * the ONE producer of that value `auth.guard.ts` `externalGroupIds: claims.groups`\n * the ONE setter of that claim `entra.verifier.ts` `groups: groupsFrom(payload)`\n * the WorkOS verifier `managed-idp.verifier.ts` never sets `groups`\n * production `opera-api` no `ENTRA_*` env at all\n *\n * It was built for Entra token group claims. docs/73 and docs/75 replaced that door with\n * WorkOS, which does not put groups in a token — its answer is Directory Sync, a separate\n * product at USD 125 per connection. The feature did not break; its source of truth was\n * removed out from under it and nothing said so.\n *\n * Nothing is over-granted by this: a directory group has no members, so it contributes no\n * roles and the system fails closed. What is wrong is the BELIEF. An admin who links a group\n * thinks they have delegated administration to their identity provider. They have not.\n *\n * ─── TWO REASONS FOR NO, BECAUSE THEY HAVE DIFFERENT AUDIENCES ───────────────────────────\n *\n * not_entitled this workspace's plan does not include directory sync → we fix it\n * not_connected entitled, but no directory is connected → their admin\n * available both, and an adapter that can actually be asked\n *\n * Collapsing the two into one \"unavailable\" today and splitting them later is precisely the\n * rework this vocabulary exists to prevent: the moment Directory Sync ships, *entitled but\n * not yet connected* is a real and common state, and its sentence is not \"not on your plan\".\n *\n * ★ `available` IS NOT REACHABLE IN PRODUCTION AFTER THIS SLICE, and that is a property of\n * the slice rather than an accident. Zero real provider adapters are registered, and a\n * connection naming a provider nobody serves is not a connection — see\n * `directory-membership.provider.ts`. It is reachable in a test with a fake adapter\n * registered, and proving the whole path through that fake is the point of docs/80 §4:\n * shipping this for real must be one adapter and no other change.\n *\n * ★ PINNED, NOT BRANCHED. Every consumer keys a `Record<DirectorySyncAvailabilityState, …>`\n * on this union — the sentences below, the screen's badge tone and label, the route's gate —\n * so a fourth arm cannot compile until each of them has answered for it (charter §4.2). The\n * precedent and the argument for `as const satisfies Record<…, true>` over a bare `as const`\n * array are in `execution.ts` (`ACTION_RUNNABILITY_CAUSE_KIND_SET`): an array literal pins\n * nothing, because `[\"a\"] as const` compiles perfectly beside a three-member union.\n */\n\nimport type { ProblemDocument } from \"./problem\";\nimport { BRAND_SHORT_NAME } from \"./brand\";\n\n/**\n * The ONE answer, computed by the api and by nothing else.\n *\n * The screen RENDERS this value and the route ENFORCES it. Two implementations of one\n * question is how docs/54's catalog came to show **Available** for an action the run path\n * refused; a form that disables itself while the route still accepts the request is the same\n * defect wearing a different hat.\n */\nexport type DirectorySyncAvailabilityState =\n | \"not_entitled\"\n | \"not_connected\"\n | \"available\";\n\nconst DIRECTORY_SYNC_AVAILABILITY_STATE_SET = {\n not_entitled: true,\n not_connected: true,\n available: true,\n} as const satisfies Record<DirectorySyncAvailabilityState, true>;\n\n/** Derived, so the two spellings of this vocabulary cannot drift apart at all. */\nexport const DIRECTORY_SYNC_AVAILABILITY_STATES = Object.keys(\n DIRECTORY_SYNC_AVAILABILITY_STATE_SET,\n) as readonly DirectorySyncAvailabilityState[];\n\n/** What one state owes its reader: the fact, and then whose move it is. */\nexport interface DirectorySyncSentence {\n /** The fact, as a label — short enough for a badge or a panel heading. */\n headline: string;\n /** What it means and who can change it. Never a pitch; never an apology. */\n detail: string;\n}\n\n/**\n * Declared once and read by every surface — the panel on Settings → Groups, the group detail\n * screen, and the `detail` of the route's own refusal. A reader who is refused by the api\n * and a reader who is looking at the screen must not be told two different things.\n */\nexport const DIRECTORY_SYNC_AVAILABILITY_SENTENCE = {\n not_entitled: {\n headline: \"Directory sync is not enabled for this workspace\",\n detail:\n `Group membership is managed here in ${BRAND_SHORT_NAME}. Mirroring groups from your identity provider is a paid add-on — contact ${BRAND_SHORT_NAME} to turn it on for this workspace.`,\n },\n not_connected: {\n headline: \"No directory is connected\",\n detail:\n \"Directory sync is enabled for this workspace, but no identity directory is connected to it yet. Once one is connected, its groups can be linked here and their membership is mirrored at sign-in.\",\n },\n available: {\n headline: \"Directory sync is on\",\n detail:\n `A group linked to your directory mirrors its membership every time one of its members signs in. Roles stay attached here in ${BRAND_SHORT_NAME}.`,\n },\n} as const satisfies Record<DirectorySyncAvailabilityState, DirectorySyncSentence>;\n\n/**\n * What an EXISTING directory-linked group says while nothing is maintaining it.\n *\n * docs/80 §3.5: groups linked before this slice are not deleted, not converted to local and\n * not stripped of their roles — those roles are somebody's deliberate configuration and no\n * migration gets to decide about them. What changes is that the screen stops implying a sync\n * is merely pending. \"Last synced: Never\" is true and reads as \"not yet\"; this says \"not at\n * all, and here is why\".\n */\nexport const DIRECTORY_GROUP_UNMAINTAINED = {\n /**\n * One line beside a row in a list, where there is room for a fact and not for a paragraph.\n * The list is where an admin first sees that something is wrong; the group's own screen is\n * where they find out what.\n */\n short: \"Membership is not being maintained — no directory is connected.\",\n /** The whole truth, on the group's own screen, where there is room for it. */\n detail:\n \"This group is linked to a directory that is not connected, so nobody is added to it or removed from it automatically, and nothing is synced. Its roles still apply to whoever is already a member.\",\n} as const;\n\n/** `GET /groups/directory-sync` — the one server-computed answer, for the screens. */\nexport interface DirectorySyncAvailabilityDto {\n state: DirectorySyncAvailabilityState;\n}\n\n/**\n * The machine code on the route's refusal. For a log and a support conversation, never for a\n * reader — the reader gets `detail`, which is the sentence above (docs/42 §3.4).\n */\nexport const DIRECTORY_SYNC_UNAVAILABLE_CODE = \"DIRECTORY_SYNC_UNAVAILABLE\";\n\n/**\n * The refusal `POST /groups/link-directory` emits, with the cause on it as a MEMBER rather\n * than only inside a sentence.\n *\n * RFC 9457 allows extensions and this codebase declares the ones a client reads beside where\n * they are read (`problem.ts`). `detail` already differs between the two causes, but a\n * sentence is not something a caller can branch on or a test can assert without matching\n * prose. This member is what makes \"the two causes are distinguished in the response\" a\n * mechanical fact.\n */\nexport interface DirectorySyncRefusalProblem extends ProblemDocument {\n /** Which of the two things was missing. Never `available` — that answer is not a refusal. */\n directorySync: Exclude<DirectorySyncAvailabilityState, \"available\">;\n}\n","/**\n * ═══ ONE CLIENT ID, ONE AUTHOR (docs/89) ═══════════════════════════════════════════════\n *\n * The value that identifies this deployment to WorkOS has TWO AUTHORS IN TWO SYSTEMS and FOUR\n * appearances, and nothing compared the two authors. Measured live on `opera-api` / web `v164`,\n * 2026-09-13 (docs/89 §3, as corrected):\n *\n * 1 api container env `WORKOS_CLIENT_ID` ★ AUTHORED — `var.workos_client_id`\n * 2 api container env `WORKOS_ISSUER` derived — `backend/main.tf` interpolated (1)\n * 3 the web build arg `NEXT_PUBLIC_WORKOS_CLIENT_ID`\n * ★ AUTHORED — typed by hand into `az acr build`\n * 4 the served bundle, `layout-e8d1a1b3e81c58a5.js`, derived — (3), inlined and unchangeable\n *\n * They agreed. ★ **The defect is the two AUTHORED copies**, because they live in different\n * systems — a Terraform variable applied to a container app, and a string typed into a shell\n * command that bakes an immutable bundle. Neither is reachable by the type system, and a WorkOS\n * environment move rewrites both by hand on the day the stakes are highest.\n *\n * `NEXT_PUBLIC_*` are inlined at build time, so a missing or mismatched arg CANNOT fail the\n * build. It fails the browser. Web **v136** did exactly that on 2026-08-23:\n * `NoClientIdProvidedException` before a single control painted, three minutes of no sign-in. The\n * remedy written at the time was \"diff your command against the ARG list\", and that checklist was\n * already there.\n *\n * This file is what replaces the checklist. Appearance (2) stops existing — the issuer is derived\n * HERE from the client id and the host, so Terraform states the id and nothing restates it — and\n * author (3) stops being typed: the runbook's build command reads the value from the deployed api.\n * What remains is one author, and a product that compares the two DEPLOYABLES rather than asking\n * a person to.\n *\n * ★ WHAT IS SAFE TO PUT ON A PUBLIC SURFACE, AND WHAT IS NEVER.\n * A WorkOS client id is public BY CONSTRUCTION — it travels in the OAuth redirect URL and is\n * inlined in every bundle we serve (copy 4 above is a `curl` away). Publishing it reveals\n * nothing that is not already served. The **API KEY is the opposite** and must never appear on\n * a response, in a log line, in a fixture, or in a comment. The environment is therefore named\n * by its DECLARED WORD below, never by any part of the key.\n */\n\n/**\n * ═══ THE TWO WORKOS ENVIRONMENTS ═══════════════════════════════════════════════════════\n *\n * staging Opera is here today (`production-readiness.md` §1, the file's one ★★★ item).\n * Every person who signs in is a user in a WorkOS Staging environment. Proven\n * interchangeable with production for everything docs/75 uses, against the real\n * API on 2026-09-07.\n * production Requires billing. An environment change RESETS every identity — new user ids,\n * new organizations — so it costs nothing today and costs a customer their\n * workspace the day after the first external sign-up.\n *\n * Array-first and compile-pinned (charter §4.2), so a third environment cannot be added\n * without every `Record<WorkosEnvironment, …>` below answering for it.\n */\nexport const WORKOS_ENVIRONMENTS = [\"staging\", \"production\"] as const;\nexport type WorkosEnvironment = (typeof WORKOS_ENVIRONMENTS)[number];\n\n/**\n * ═══ HOW A KEY SAYS WHICH ENVIRONMENT IT IS IN ═════════════════════════════════════════\n *\n * ⚠ MEASURED, NOT ASSUMED. Read from `.env.stage` (gitignored, `.gitignore:203`) on\n * 2026-09-13 by reading the PREFIX ONLY: the live key begins `sk_test_`. The production form\n * `sk_live_` is WorkOS's documented counterpart and is recorded in `production-readiness.md`\n * §1 step 3. Nothing after the prefix was read, and nothing after it appears anywhere in this\n * repository.\n *\n * ★ A `Record` KEYED ON THE UNION, NOT A FREE-STANDING LIST. A third environment added above\n * is a compile error here until somebody states its prefix — the shape that stops a new member\n * defaulting to \"unclassifiable\" in silence. (Same argument as `AZURE_SUPPORTS`.)\n */\nexport const WORKOS_ENVIRONMENT_KEY_PREFIXES: Record<WorkosEnvironment, string> = {\n staging: \"sk_test_\",\n production: \"sk_live_\",\n};\n\n/**\n * Which environment a WorkOS API key belongs to, or `null` when its prefix is not one we know.\n *\n * ★ IT RETURNS A WORD FROM THE CLOSED SET ABOVE AND NOTHING ELSE — never the key, never a\n * slice of it, never a length. Every caller therefore has a value it is safe to log, render\n * and put in a refusal, and no caller is ever tempted to quote the input to explain itself.\n *\n * ⚠ `null` MUST BE REFUSED BY THE CALLER, NOT ABSORBED. An unreadable key is not agreement; it\n * is a check that cannot fire, which is worse than no check because it reads as verified. If\n * WorkOS ever changes the prefix format, the api must stop and say so rather than quietly\n * trusting whatever the declaration claimed.\n */\nexport function workosEnvironmentOfApiKey(apiKey: string): WorkosEnvironment | null {\n for (const environment of WORKOS_ENVIRONMENTS) {\n if (apiKey.startsWith(WORKOS_ENVIRONMENT_KEY_PREFIXES[environment])) {\n return environment;\n }\n }\n return null;\n}\n\n/**\n * The shape of a WorkOS client id: `client_` and a 26-character Crockford base32 id.\n *\n * Held here so the guard that proves the literal is written ONCE\n * (`apps/api/test/one-client-id.spec.ts`) and any future validator share one spelling of\n * \"that is a client id\" — a guard with its own private regex is a second author of the thing\n * it is policing.\n */\nexport const WORKOS_CLIENT_ID_PATTERN = /client_[0-9A-HJKMNP-TV-Z]{26}/;\n\n/**\n * ═══ WHERE WORKOS LIVES — A VARIABLE, DELIBERATELY, NOT A CONSTANT ═════════════════════\n *\n * The default. It is a *default* and not a literal in the derivations below because a custom\n * auth domain is exactly what moves it, and that flip is one build arg away from happening:\n * `providers.tsx:38` already reads `devMode={!WORKOS_API_HOSTNAME}` and hands AuthKit\n * `apiHostname` the moment it has a value, moving the session from `localStorage` to a secure\n * httpOnly cookie. Hard-coding `api.workos.com` inside the derivation would freeze the next\n * identity change in place — the one change this vocabulary exists to make cheap.\n */\nexport const WORKOS_DEFAULT_API_HOSTNAME = \"api.workos.com\";\n\n/**\n * ═══ THE ISSUER IS DERIVED, AND A DERIVED VALUE CANNOT HAVE A WRONG DEFAULT ════════════\n *\n * ⚠ THIS SHAPE WAS MEASURED AGAINST WORKOS ITSELF, not inferred from one deployment.\n * `GET https://api.workos.com/user_management/<clientId>/.well-known/openid-configuration`\n * (public, no API key) answered on 2026-09-13:\n *\n * \"issuer\": \"https://api.workos.com/user_management/client_01KXXMRBH3TMEVW40K581F8Q8J\"\n * \"jwks_uri\": \"https://api.workos.com/sso/jwks/client_01KXXMRBH3TMEVW40K581F8Q8J\"\n *\n * That is WorkOS's own discovery document — the documented contract rather than an observation\n * of one environment — and it is parameterised by CLIENT ID, not by environment. Both\n * derivations below reproduce it exactly. **Re-measure at that URL** if either ever looks\n * wrong; inventing a derivation here would break every sign-in, which is the failure docs/89\n * exists to prevent.\n *\n * ★ WHAT THIS DELETES. `config.ts:391` used to declare\n * `WORKOS_ISSUER: z.string().default(\"https://api.workos.com/\")` while the DEPLOYED value was\n * `…/user_management/client_01KXX…`. `ManagedIdpVerifier.canVerify` compares a token's issuer\n * against that value exactly, so any deployment that forgot the variable got a default no real\n * token could ever match: sign-in refused, one `Token verification failed` warning, and no\n * statement of why. That default was not a fallback. It was a wrong answer shaped like one,\n * and it is unreachable now because nobody configures the issuer at all.\n */\nexport function workosIssuer(apiHostname: string, clientId: string): string {\n return `https://${apiHostname}/user_management/${clientId}`;\n}\n\n/**\n * Where the signing keys for that issuer are published. Derived from the same two values, for\n * the same reason — and it closes a FIFTH spelling of the host that the docs/89 census missed:\n * `managed-idp.verifier.ts:62` built this URL with `api.workos.com` written into it, so a\n * custom auth domain would have moved the issuer and left the JWKS lookup behind.\n */\nexport function workosJwksUri(apiHostname: string, clientId: string): string {\n return `https://${apiHostname}/sso/jwks/${clientId}`;\n}\n\n/**\n * ═══ WHAT THE API SAYS IT IS BOUND TO (docs/89 §4.3) ═══════════════════════════════════\n *\n * The answer of a `@Public()` route, so that a web bundle whose sign-in has ALREADY FAILED can\n * find out whether the two deployables disagree — and which of them is stale.\n *\n * ⚠ THERE IS NO FIELD HERE FOR THE API KEY AND THERE MUST NEVER BE ONE. The environment is the\n * declared word; `auth-binding-states-no-secret.spec.ts` asserts the response body and the log\n * line contain no substring of the key, and proves that assertion can fail.\n */\nexport interface AuthBindingResponse {\n /** Whether this api authenticates anyone through WorkOS at all. */\n readonly workosEnabled: boolean;\n /**\n * The client id this api expects tokens to have been issued for — `null` only when WorkOS is\n * disabled, which for a deployment serving sign-ins cannot happen (`config.ts` refuses).\n */\n readonly clientId: string | null;\n /** The environment this deployment DECLARES, checked against the key at boot. */\n readonly environment: WorkosEnvironment | null;\n}\n\n/**\n * ═══ THE ONE SENTENCE THAT SAYS WHAT THIS DEPLOYMENT IS BOUND TO ═══════════════════════\n *\n * Written at startup into the api's container log, so an operator reading `az containerapp logs`\n * during a release can see the binding without asking the running api anything. The same facts\n * the `@Public()` route serves, in words.\n *\n * ⚠ IT IS BUILT FROM THIS DTO AND NOTHING ELSE, which is the property that keeps it safe: the\n * DTO has no field for the API key, so there is no key in scope to interpolate and no future\n * edit that \"adds a bit more detail\" can reach one. The environment is the declared WORD.\n * `auth-binding-states-no-secret.spec.ts` asserts it, and proves the assertion can fail.\n */\nexport function workosBindingSentence(binding: AuthBindingResponse): string {\n if (!binding.workosEnabled) {\n return \"WorkOS is disabled: this process authenticates nobody through it.\";\n }\n return (\n `WorkOS binding: client ${binding.clientId ?? \"(none)\"}, ` +\n `environment ${binding.environment ?? \"(not declared)\"}.`\n );\n}\n","// @runveric/contracts — single source of truth for types shared between web and api.\n// No runtime logic beyond pure helpers; no DB types; no NestJS/Prisma imports (docs/11 §4).\n\nexport * from \"./enums\";\n// ═══ THE BRAND VOCABULARY (docs/95) — TWO FILES, AND THE SPLIT IS THE POINT ═══════════\n// `./brand` is the one value that is going to change; `./wire-identity` is everything another\n// system parses and may never change. Both are LEAVES with no imports, and `./wire-identity`\n// may not import `./brand` — a rebrand that could reach a protocol id would refuse every\n// customer package already published against it.\nexport * from \"./brand\";\nexport * from \"./wire-identity\";\nexport * from \"./problem\";\nexport * from \"./permissions\";\nexport * from \"./request-context\";\nexport * from \"./role-permissions\";\nexport * from \"./me\";\nexport * from \"./tenant-users\";\nexport * from \"./invitations\";\nexport * from \"./groups\";\n// A leaf with no imports: which global actions one workspace may use (docs/112). Declared\n// before `./catalog`, whose detail DTO carries the answer, and `./execution`, whose refusal\n// names it.\nexport * from \"./catalog-policy\";\nexport * from \"./catalog\";\n// Which catalog release is live for every workspace, and the two artifact formats (docs/121).\n// Reads only `./wire-identity`, the frozen layer.\nexport * from \"./catalog-release\";\n// One action, one name: the key grammar and the key ⇄ repository-name mapping (docs/127 §5). A\n// leaf. Then the two files around a release that never leave this side of the registry — the\n// release.yaml a person proposes and the lock that says which release the in-image directory\n// copies (docs/127 §3, §4.1); both read the two above.\nexport * from \"./action-repository\";\nexport * from \"./catalog-release-spec\";\nexport * from \"./catalog-lock\";\n// The brand placeholders a catalog manifest may write, shared by the validator and the\n// repository-creation script (docs/97 §4.3, docs/127 §4.2). Reads only `./brand`.\nexport * from \"./catalog-manifest-placeholders\";\n// The change-control vocabulary — a LEAF with no imports at all, declared BEFORE\n// `./governance` and `./execution`, both of which read it (docs/83 §3). A rule requires\n// record types, a plan states the requirement, and a refused run cites the same sentence.\nexport * from \"./change-control\";\nexport * from \"./execution\";\n// What a person decided about a plan's DECIDE checks (docs/126 §3). Reads only the check\n// vocabulary `./execution` re-exports, and is read by `./governance`, whose approval plan carries\n// each decision to the approver.\nexport * from \"./decisions\";\nexport * from \"./execution-site\";\nexport * from \"./run-placement\";\nexport * from \"./connections\";\nexport * from \"./resources\";\nexport * from \"./governance\";\nexport * from \"./audit\";\nexport * from \"./notifications\";\nexport * from \"./scheduling\";\nexport * from \"./operations\";\nexport * from \"./runs\";\n// One Operation, provable (docs/119): the pack an auditor is handed, and what its export\n// records. Declared after `./operations`, `./governance` and `./change-control`, which it reads.\nexport * from \"./evidence-pack\";\n// Declared before `./packages`, which re-exports it — the vocabulary is a leaf and reads as\n// one (see `package-provenance.ts` for the cycle that put it there).\n// `PackageTier` is a leaf for the same reason — `catalog.ts` renders the badge and would\n// otherwise close a cycle back through `packages.ts`. See `package-tier.ts`.\nexport * from \"./package-tier\";\nexport * from \"./package-provenance\";\nexport * from \"./packages\";\nexport * from \"./package-egress\";\nexport * from \"./package-execution\";\n// A leaf, declared before `./runners`, which carries a report of it on the registration —\n// same reason as `package-provenance` above: the vocabulary reads as a vocabulary and cannot\n// join a cycle it has no imports to make.\nexport * from \"./runner-confinement\";\n// A leaf with no imports: every name the install command and the manifest put into a\n// customer's system and the dispatcher reads back there, declared once (docs/110).\nexport * from \"./runner-install\";\n// A leaf: the environment an action author exports for the PUBLISHED CLI (0.1.2).\nexport * from \"./authoring-cli\";\nexport * from \"./runners\";\n// A credential made of minted bytes and nothing that can get more — the one implementation a\n// runner's step container and an engine action's SDK both hold (docs/128 Slice A). Reads only a\n// type from `./runners`.\nexport * from \"./scoped-credential\";\n// The engine ⇄ action-runtime contract, `runveric.dev/action-protocol/v1` (docs/128 §4): the\n// shapes, the limits declared once, and one parser per message. Reads `./wire-identity`, the\n// check vocabulary, `./decisions`, `./package-execution` and a type from `./runners`; nothing\n// here reads it back.\nexport * from \"./action-protocol\";\n// What an engine action's signed image is, and what a published engine version records\n// (docs/128 §17): Sigstore's identifiers, read by the one verifier, and `EngineVersionFacts`.\nexport * from \"./action-signing\";\n// The four manifest media types a registry may answer with — a leaf, the OCI's and Docker's.\n// Then the ONE rule over an engine action's image (docs/128 §17.4a, §20 G3) and the runtime it is\n// built FROM; it reads `./action-repository`, `./action-signing` and the media types, and the api's\n// resolver and the CLI both call it.\nexport * from \"./oci-media-types\";\nexport * from \"./action-image\";\nexport * from \"./runner-pool-presence\";\n// The identity of ONE resource — a leaf, declared before the two modules that read it\n// (`runner-pool-routing` re-exports it, `target-identity` records it).\nexport * from \"./routable-target\";\nexport * from \"./runner-pool-routing\";\n// Declared AFTER `./runner-pool-routing` and `./execution`, both of which it reads: an\n// identity is a `RoutableTarget` (docs/58) and its absence is a `TargetCountAbsence`\n// (docs/66). It mints neither (docs/69 §8).\nexport * from \"./target-identity\";\n// Pure copy with no imports at all — the answer to \"which Entra do you mean?\", given once\n// and rendered by both the sign-in screen and the Azure-connection screen (docs/73 §3.3).\nexport * from \"./which-entra\";\n// The three questions the app asks a user with no workspace, and the code on the 403 that\n// says so. A leaf: it reads `RoleKey` and nothing else (docs/75 §3.2).\nexport * from \"./onboarding\";\n// The proof behind a workspace's domain — what to publish, what a check found, and the\n// sentence each outcome owes (docs/78 §3.3). A leaf: no imports at all.\nexport * from \"./workspace-domain\";\n// What a workspace may be ENTITLED to — the vocabulary a pricing system will one day write\n// against, per tenant rather than per deployment (docs/80 §3.2). A leaf: no imports at all.\nexport * from \"./workspace-features\";\n// Whether a group can be linked to a directory, and which of the two things is missing when\n// it cannot (docs/80 §3.1/§3.3). Declared AFTER `./problem`, whose document its refusal\n// extends.\nexport * from \"./directory-sync\";\n// What this deployment is BOUND to in WorkOS — the two environments, how a key says which\n// one it is in, and the derivations that let the issuer stop being configured beside the\n// client id (docs/89 §4). A leaf: no imports at all.\nexport * from \"./workos-binding\";\n\nexport interface Page<T> {\n data: T[];\n nextCursor: string | null;\n}\n","import {\n BRAND_SHORT_NAME,\n PACKAGE_RUNTIME_KINDS,\n type PackageInterpreter,\n type PackageRuntime,\n type PackageRuntimeKind,\n} from \"@runveric/contracts\";\n\n/**\n * The runtime DECLARATION rules: how a `runtime` value is read (whatever shape it was\n * written in), and what makes an OCI image reference acceptable.\n *\n * Pure domain, no I/O. Nothing here reaches the network: an image reference is judged by\n * its FORM, never by asking a registry whether it exists — that is a run-time concern, and\n * a validator that needs egress is a validator that fails in CI.\n */\n\nexport class PackageRuntimeDeclarationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PackageRuntimeDeclarationError\";\n }\n}\n\n/**\n * A registry host: lowercase DNS labels with an optional port. `localhost:5000` and\n * `registry.example.com:5000` both qualify.\n */\nconst REGISTRY_HOST = String.raw`[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*(?::\\d{1,5})?`;\n/** One repository path component, per the OCI distribution grammar (lowercase only). */\nconst PATH_COMPONENT = String.raw`[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*`;\nconst IMAGE_NAME = new RegExp(\n String.raw`^(?:${REGISTRY_HOST}/)?${PATH_COMPONENT}(?:/${PATH_COMPONENT})*$`,\n);\n/** Only sha256, and only the canonical lowercase 64-hex form. */\nconst SHA256_DIGEST = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * Why the rule exists and how to satisfy it, appended to every rejection. The author who\n * hits this is doing the normal thing — publishing `:1.2.0` — so the error has to teach,\n * not just refuse.\n */\nconst DIGEST_PIN_GUIDANCE =\n `${BRAND_SHORT_NAME} runs OCI actions only from a digest-pinned reference ` +\n \"(<registry>/<repository>@sha256:<64 hex characters>). A digest names the exact image \" +\n \"bytes, so a published action cannot change under the workspaces that adopted it; a tag is \" +\n \"a mutable pointer and can be moved to different bytes at any time. Get the digest for an \" +\n \"image you have published with `docker buildx imagetools inspect \" +\n \"<registry>/<repository>:<tag>`, or for a local build with \" +\n \"`docker inspect --format='{{index .RepoDigests 0}}' <image>`, then pin the `@sha256:…` \" +\n \"value it prints.\";\n\nexport type OciImageCheck = { ok: true } | { ok: false; message: string };\n\n/**\n * THE SECURITY CORE of the OCI runtime contract: an image is accepted only when it is\n * digest-pinned. A tag is refused ALWAYS — this is the direct answer to the tj-actions class\n * of attack (docs/31 §10.4), where a retagged release silently changed what 23,000\n * repositories executed. Opera cannot make that impossible for a tag, so it does not accept\n * one.\n *\n * Deliberately NOT checked here: whether the image exists, is pullable, or is signed. Those\n * need a registry round-trip and belong to the substrate half (docs/31 §10.3).\n */\nexport function checkOciImageReference(image: unknown): OciImageCheck {\n if (typeof image !== \"string\" || image.trim().length === 0) {\n return { ok: false, message: `An OCI runtime requires an \"image\" reference. ${DIGEST_PIN_GUIDANCE}` };\n }\n if (image !== image.trim()) {\n return { ok: false, message: `Image reference \"${image}\" has leading or trailing whitespace.` };\n }\n\n const separator = image.indexOf(\"@\");\n if (separator === -1) {\n // Either `repo:tag` or a bare `repo`. Both mean \"whatever those bytes are today\".\n const lastColon = image.lastIndexOf(\":\");\n const tagged = lastColon > image.lastIndexOf(\"/\");\n return {\n ok: false,\n message: tagged\n ? `Image reference \"${image}\" is pinned by tag, not by digest. ${DIGEST_PIN_GUIDANCE}`\n : `Image reference \"${image}\" has no digest. ${DIGEST_PIN_GUIDANCE}`,\n };\n }\n\n // `repository:tag@sha256:…` is accepted: the digest is authoritative, so the tag is inert\n // decoration (CI tooling emits this form) and the guarantee we care about — these exact\n // bytes — still holds. Rejecting it would be a technicality with a misleading message.\n const reference = image.slice(0, separator);\n const tagStart = reference.lastIndexOf(\":\") > reference.lastIndexOf(\"/\")\n ? reference.lastIndexOf(\":\")\n : -1;\n const name = tagStart === -1 ? reference : reference.slice(0, tagStart);\n const digest = image.slice(separator + 1);\n if (!IMAGE_NAME.test(name)) {\n return {\n ok: false,\n message:\n `Image reference \"${image}\" does not name a valid registry/repository: expected ` +\n \"lowercase name components (letters, digits, and `.`, `_`, `-` separators) with an \" +\n \"optional registry host and port, such as \" +\n \"registry.example.com:5000/team/rotate-secret.\",\n };\n }\n if (!SHA256_DIGEST.test(digest)) {\n // A value can only be reported as declaring an algorithm when it actually declares one —\n // i.e. a colon is present. Without this guard the whole value is read as the algorithm\n // name (`slice(0, undefined)` returns the entire string), so pasting just the hex out of\n // `repo@sha256:<hex>` was answered with \"pinned with the \"aaaa…\" digest algorithm\", which\n // tells the author their hex is an algorithm. A colon-less value is a malformed DIGEST.\n const colon = digest.indexOf(\":\");\n const algorithm = colon === -1 ? undefined : digest.slice(0, colon);\n return {\n ok: false,\n message:\n algorithm && algorithm !== \"sha256\"\n ? `Image reference \"${image}\" is pinned with the \"${algorithm}\" digest algorithm; ` +\n `${BRAND_SHORT_NAME} requires sha256. ${DIGEST_PIN_GUIDANCE}`\n : `Image reference \"${image}\" has a malformed digest; expected sha256 followed by ` +\n `exactly 64 lowercase hex characters. ${DIGEST_PIN_GUIDANCE}`,\n };\n }\n return { ok: true };\n}\n\n/**\n * THE ONE compatibility function. Every boundary that reads an authored or persisted\n * `runtime` value routes through here, so the legacy shape is understood in exactly one\n * place.\n *\n * `{ name, version }` with no `kind` — the shape every manifest in the wild is written in\n * and every `package_version.runtime` row already holds — normalizes to an `interpreter`\n * runtime. That shape is accepted FOREVER, not deprecated: those authors did nothing wrong,\n * their packages are immutable by design, and there is no rewrite Opera could perform on\n * their behalf. Do not \"tidy this up\" later — deleting it invalidates every package ever\n * authored against Opera, which is strictly worse than the problem the `kind` field solved.\n *\n * Returns exactly the closed contract shape, so no caller has to wonder whether the value it\n * holds is the authored one or the normalized one.\n */\nexport function normalizePackageRuntime(value: unknown): PackageRuntime {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new PackageRuntimeDeclarationError(\n `Package runtime must be an object, got ${describe(value)}.`,\n );\n }\n const runtime = value as Record<string, unknown>;\n const kind = runtime.kind === undefined ? legacyKind(runtime) : runtime.kind;\n\n if (kind === \"interpreter\") {\n if (typeof runtime.name !== \"string\" || typeof runtime.version !== \"string\") {\n throw new PackageRuntimeDeclarationError(\n 'An interpreter runtime requires string \"name\" and \"version\" fields.',\n );\n }\n // The NAME is not judged here, and that is deliberate. This function also reads rows\n // persisted before `PACKAGE_INTERPRETERS` existed, where `name` can be anything an author\n // once wrote. Refusing here would turn such a row into a thrown normalizer error — a 500\n // on every surface that merely LISTS the action. The vocabulary is enforced at import\n // (validateRuntime), and an unknown name that is already stored is refused honestly by the\n // runnability oracle as `interpreter_unavailable`, which names what this deployment runs.\n return {\n kind: \"interpreter\",\n name: runtime.name as PackageInterpreter,\n version: runtime.version,\n };\n }\n if (kind === \"oci\") {\n if (typeof runtime.image !== \"string\" || runtime.image.length === 0) {\n throw new PackageRuntimeDeclarationError('An OCI runtime requires a string \"image\" field.');\n }\n return { kind: \"oci\", image: runtime.image };\n }\n throw new PackageRuntimeDeclarationError(\n `Package runtime kind ${describe(runtime.kind)} is not one of: ${PACKAGE_RUNTIME_KINDS.join(\", \")}.`,\n );\n}\n\n/**\n * A `kind`-less value is the legacy interpreter shape — but ONLY when it actually looks like\n * one. Guessing \"interpreter\" for arbitrary garbage would turn a corrupt row into a\n * confusing \"requires name and version\" instead of naming the real problem.\n */\nfunction legacyKind(runtime: Record<string, unknown>): PackageRuntimeKind | undefined {\n return typeof runtime.name === \"string\" && typeof runtime.version === \"string\"\n ? \"interpreter\"\n : undefined;\n}\n\nfunction describe(value: unknown): string {\n if (value === undefined) return \"undefined\";\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"an array\";\n return typeof value === \"string\" ? `\"${value}\"` : typeof value;\n}\n","// These value sets live in contracts (docs/29 D2, charter §4.2); re-exported — never\n// re-listed — for existing importers of this schema module.\nexport { ACTION_CATEGORIES, PROVIDERS, RISK_LEVELS } from \"@runveric/contracts\";\nimport { PARAMETER_ORDER_KEY } from \"@runveric/contracts\";\n\nexport const MANIFEST_FIELDS = [\n \"apiVersion\",\n \"id\",\n \"name\",\n \"author\",\n \"version\",\n \"summary\",\n \"category\",\n \"providers\",\n \"connectorKey\",\n \"runtime\",\n \"executionTimeout\",\n \"parametersRef\",\n \"entrypoint\",\n \"rollback\",\n \"rollbackEntrypoint\",\n \"validateEntrypoint\",\n \"riskLevel\",\n \"requiredPermissions\",\n \"capabilities\",\n \"requiresNetwork\",\n \"egressAllowlist\",\n \"secrets\",\n \"credentialScopes\",\n \"license\",\n \"minRunvericVersion\",\n] as const;\n\nexport const PACKAGE_ID_PATTERN = /^[a-z0-9-]+\\/[a-z0-9-]+$/;\nexport const SEMVER_PATTERN = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$/;\nexport const DURATION_PATTERN = /^[1-9]\\d*(?:ms|s|m|h)$/;\nexport const SPDX_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9.-]*$/;\n// A least-privilege AAD app-token scope, e.g. `https://vault.azure.net/.default`. Daemon\n// (app-identity) token flows use the `/.default` resource scope; delegated scopes are not\n// applicable to an unattended sandbox, so we require the `/.default` suffix.\nexport const CREDENTIAL_SCOPE_PATTERN =\n /^https:\\/\\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+\\/\\.default$/;\n\nexport const PARAMETER_SCHEMA_FIELDS = [\n \"$schema\",\n \"type\",\n \"properties\",\n \"required\",\n \"additionalProperties\",\n // Our own annotation, carried INSIDE the schema it orders rather than in a second\n // column: the two would otherwise separate, and a schema whose order lives elsewhere is a\n // schema that renders in the wrong order the first time one of them is copied without the\n // other. Allowed here so a normalized schema round-trips through this validator rather than\n // being rejected as an unknown field.\n //\n // ⛔ THIS LIST IS A REJECT-UNKNOWN ALLOWLIST. `x-opera-order` left it LAST in docs/108 —\n // after the writer stopped stamping it, 0089 stripped it from every row, and the readers\n // stopped reading it. Nothing re-validates a STORED schema (every caller of this validator\n // is handed authored bytes), so the order was safe; an author's file that still carries the\n // retired key is now refused by name, as any unknown field is.\n PARAMETER_ORDER_KEY,\n] as const;\nexport const PARAMETER_PROPERTY_FIELDS = [\n \"type\",\n \"title\",\n \"description\",\n \"enum\",\n \"default\",\n \"control\",\n \"discover\",\n \"dependsOn\",\n] as const;\nexport const PARAMETER_CONTROLS = [\"select\", \"text\", \"switch\", \"info\"] as const;\n","import { createHash } from \"node:crypto\";\nimport { isIP } from \"node:net\";\nimport type {\n ActionPackageManifest,\n ManifestValidationError,\n ManifestValidationWarning,\n PackageRuntime,\n PackageRuntimeKind,\n ParameterSchema,\n ParsedDiscoveryType,\n Provider,\n} from \"@runveric/contracts\";\nimport {\n BRAND_SHORT_NAME,\n DISCOVERY_TYPE_PATTERN,\n PACKAGE_INTERPRETERS,\n PACKAGE_RUNTIME_KINDS,\n PARAMETER_ORDER_KEY,\n discoveryTypeSpec,\n formatDiscoveryType,\n} from \"@runveric/contracts\";\nimport {\n checkOciImageReference,\n normalizePackageRuntime,\n} from \"./package-runtime-declaration\";\nimport { ACTION_MANIFEST_API_VERSION } from \"@runveric/contracts\";\nimport { parseDocument } from \"yaml\";\nimport {\n ACTION_CATEGORIES,\n CREDENTIAL_SCOPE_PATTERN,\n DURATION_PATTERN,\n MANIFEST_FIELDS,\n PACKAGE_ID_PATTERN,\n PARAMETER_CONTROLS,\n PARAMETER_PROPERTY_FIELDS,\n PARAMETER_SCHEMA_FIELDS,\n PROVIDERS,\n RISK_LEVELS,\n SEMVER_PATTERN,\n SPDX_ID_PATTERN,\n} from \"./manifest.schema\";\n\n// `canonicalContentDigest` is deliberately NOT re-exported here any more. It hashes a\n// materialized artifact, which is the control plane's job — this module validates a manifest,\n// and it now runs in two processes (the API and the authoring CLI). Its importers reach for it\n// where it lives, in the API's artifact layer.\n\n// Hard on authoring bugs, soft on capability gaps (docs/29 D3): errors fail the\n// import; warnings surface in the import response and the affected field degrades to\n// free text. The `ok` branch carries a NORMALIZED copy of the input (canonical\n// `discover` ids) — callers pin that copy, never the raw input.\nexport type ValidationResult<T> =\n | { ok: true; value: T; warnings: ManifestValidationWarning[] }\n | { ok: false; errors: ManifestValidationError[] };\n\n/**\n * The manifest's own result type. Deliberately NOT `ValidationResult<ActionPackageManifest>`:\n * it carries `manifestHash`, which is meaningless for the parameter-schema path that shares the\n * generic type.\n *\n * `manifestHash` is the sha256 of the canonicalized manifest **as the author wrote it**, while\n * `value` is the NORMALIZED manifest. Two different things with two different purposes, and they\n * must not be unified:\n *\n * - The hash is part of the reproducibility identity tuple (docs/21 §8.4), so it has to be\n * stable across Opera versions. Hashing the normalized form would make it depend on OPERA's\n * normalization, so two deployments running different Opera versions would compute different\n * hashes for the same immutable package — destroying exactly the comparison the field exists\n * to support. The authored bytes are also already covered immutably by `contentDigest`.\n * - The normalized value is the READ shape: what gets pinned into `package_version.runtime` so\n * no reader has to interpret the legacy `{name, version}` form again.\n */\nexport type ManifestValidationResult =\n | {\n ok: true;\n value: ActionPackageManifest;\n manifestHash: string;\n warnings: ManifestValidationWarning[];\n }\n | { ok: false; errors: ManifestValidationError[] };\n\nexport function parseAndValidateManifest(source: string): ManifestValidationResult {\n const document = parseDocument(source, { uniqueKeys: true });\n if (document.errors.length > 0) {\n return {\n ok: false,\n errors: document.errors.map((error) => ({\n path: \"action.yaml\",\n message: error.message,\n keyword: \"yaml\",\n })),\n };\n }\n return validateManifest(document.toJS());\n}\n\nexport function validateManifest(value: unknown): ManifestValidationResult {\n const errors: ManifestValidationError[] = [];\n if (!isRecord(value)) {\n return invalid(\"action.yaml\", \"Expected a YAML object.\", \"type\");\n }\n rejectUnknown(value, MANIFEST_FIELDS, \"\", errors);\n\n requiredConst(value, \"apiVersion\", ACTION_MANIFEST_API_VERSION, errors);\n requiredString(value, \"id\", errors, PACKAGE_ID_PATTERN, \"publisher/name\");\n requiredString(value, \"name\", errors);\n requiredString(value, \"author\", errors);\n requiredString(value, \"version\", errors, SEMVER_PATTERN, \"MAJOR.MINOR.PATCH\");\n const summary = requiredString(value, \"summary\", errors);\n if (summary && summary.length > 200) add(errors, \"summary\", \"Must be at most 200 characters.\", \"maxLength\");\n requiredEnum(value, \"category\", ACTION_CATEGORIES, errors);\n requiredStringArray(value, \"providers\", errors, { nonEmpty: true, unique: true, values: PROVIDERS });\n requiredString(value, \"connectorKey\", errors);\n const runtime = validateRuntime(value.runtime, errors);\n requiredString(value, \"executionTimeout\", errors, DURATION_PATTERN, \"a duration such as 5m\");\n requiredSafePath(value, \"parametersRef\", errors, false);\n requiredSafePath(value, \"entrypoint\", errors, true);\n const rollback = requiredBoolean(value, \"rollback\", errors);\n if (rollback === true) requiredSafePath(value, \"rollbackEntrypoint\", errors, true);\n if (rollback === false && value.rollbackEntrypoint !== undefined) {\n add(errors, \"rollbackEntrypoint\", \"Must be absent when rollback is false.\", \"conditional\");\n }\n if (value.validateEntrypoint !== undefined) optionalSafePath(value, \"validateEntrypoint\", errors, true);\n requiredEnum(value, \"riskLevel\", RISK_LEVELS, errors);\n validatePermissions(value.requiredPermissions, errors);\n validateCapabilities(value.capabilities, errors);\n if (\n typeof rollback === \"boolean\" &&\n isRecord(value.capabilities) &&\n typeof value.capabilities.rollback === \"boolean\" &&\n value.capabilities.rollback !== rollback\n ) {\n add(errors, \"capabilities.rollback\", \"Must match the top-level rollback declaration.\", \"consistency\");\n }\n const requiresNetwork = requiredBoolean(value, \"requiresNetwork\", errors);\n validateEgressAllowlist(value.egressAllowlist, requiresNetwork, errors);\n requiredStringArray(value, \"secrets\", errors, { unique: true });\n validateCredentialScopes(value.credentialScopes, errors);\n requiredString(value, \"license\", errors, SPDX_ID_PATTERN, \"an SPDX identifier\");\n requiredString(value, \"minRunvericVersion\", errors, SEMVER_PATTERN, \"MAJOR.MINOR.PATCH\");\n\n return errors.length === 0 && runtime !== undefined\n ? {\n ok: true,\n // The normalized runtime replaces the authored one, exactly as `discover` ids are\n // normalized above: the caller pins this copy, so a legacy `{name, version}` manifest\n // persists as `{kind: \"interpreter\", …}` and no read path has to guess again.\n value: { ...value, runtime } as unknown as ActionPackageManifest,\n // Hashed HERE, from `value` — the authored document, which only this scope still holds\n // unnormalized. See ManifestValidationResult for why it must not be the normalized copy.\n manifestHash: sha256Hex(canonicalJson(value)),\n warnings: [],\n }\n : { ok: false, errors };\n}\n\n/**\n * Validate Opera's closed ParameterSchema subset plus the discovery annotations\n * (docs/29 D3). `context.providers` is the manifest's declared providers — production\n * always passes it; without it (bare unit-test calls) only the context-free discover\n * rules (1–3) apply and no normalization happens. The `ok` branch returns a\n * normalized COPY of the schema (bare `discover` values resolved to canonical\n * `provider/type` ids); the caller's object is never mutated.\n */\nexport function validateParameterSchema(\n value: unknown,\n context?: { providers?: readonly Provider[] },\n): ValidationResult<ParameterSchema> {\n const errors: ManifestValidationError[] = [];\n const warnings: ManifestValidationWarning[] = [];\n if (!isRecord(value)) return invalid(\"parameters\", \"Expected a JSON object.\", \"type\");\n rejectUnknown(value, PARAMETER_SCHEMA_FIELDS, \"parameters\", errors);\n requiredConst(\n value,\n \"$schema\",\n \"https://json-schema.org/draft/2020-12/schema\",\n errors,\n \"parameters.$schema\",\n );\n requiredConst(value, \"type\", \"object\", errors, \"parameters.type\");\n if (value.additionalProperties !== false) {\n add(errors, \"parameters.additionalProperties\", \"Must be false.\", \"const\");\n }\n const normalizedProperties: Record<string, unknown> = {};\n if (!isRecord(value.properties)) {\n add(errors, \"parameters.properties\", \"Expected an object.\", \"type\");\n } else {\n // THE AUTHORED ORDER, and the only place it still exists. `JSON.parse` preserved the order\n // the author wrote; the jsonb column this schema is about to be stored in will not. It is\n // read here for the dependency check below and stamped on in `withParameterOrder`.\n const declarationOrder = Object.keys(value.properties);\n for (const [name, property] of Object.entries(value.properties)) {\n const declaredType = validateParameterProperty(name, property, errors);\n normalizedProperties[name] = isRecord(property)\n ? validateDiscoveryAnnotations(\n name,\n property,\n declaredType,\n value.properties,\n declarationOrder,\n context?.providers,\n errors,\n warnings,\n )\n : property;\n }\n validateParameterOrder(\n value[PARAMETER_ORDER_KEY],\n PARAMETER_ORDER_KEY,\n declarationOrder,\n errors,\n );\n }\n if (!Array.isArray(value.required) || !value.required.every(isString)) {\n add(errors, \"parameters.required\", \"Expected an array of property names.\", \"type\");\n } else {\n const seen = new Set<string>();\n for (const name of value.required) {\n if (seen.has(name)) add(errors, \"parameters.required\", `Duplicate property \"${name}\".`, \"unique\");\n seen.add(name);\n if (!isRecord(value.properties) || !(name in value.properties)) {\n add(errors, \"parameters.required\", `Unknown property \"${name}\".`, \"reference\");\n }\n }\n }\n return errors.length === 0\n ? {\n ok: true,\n value: { ...value, properties: normalizedProperties } as unknown as ParameterSchema,\n warnings,\n }\n : { ok: false, errors };\n}\n\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(sortJson(value));\n}\n\nexport function sha256Hex(value: string | Buffer): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nexport function isSafeRelativePath(value: string): boolean {\n if (!value || value.startsWith(\"/\") || value.includes(\"\\\\\") || value.includes(\"\\0\")) return false;\n const parts = value.split(\"/\").filter(Boolean);\n return parts.length > 0 && parts.every((part) => part !== \".\" && part !== \"..\");\n}\n\nfunction validateEgressAllowlist(\n value: unknown,\n requiresNetwork: boolean | undefined,\n errors: ManifestValidationError[],\n): void {\n if (value === undefined) {\n if (requiresNetwork === true) {\n add(errors, \"egressAllowlist\", \"A non-empty allowlist is required when network access is enabled.\", \"conditional\");\n }\n return;\n }\n if (!Array.isArray(value) || !value.every(isString)) {\n add(errors, \"egressAllowlist\", \"Expected an array of host or host:port strings.\", \"type\");\n return;\n }\n if (value.length > 64) add(errors, \"egressAllowlist\", \"Must contain at most 64 destinations.\", \"maxItems\");\n if (new Set(value).size !== value.length) add(errors, \"egressAllowlist\", \"Items must be unique.\", \"uniqueItems\");\n if (requiresNetwork === false && value.length > 0) {\n add(errors, \"egressAllowlist\", \"Must be empty when network access is disabled.\", \"conditional\");\n }\n if (requiresNetwork === true && value.length === 0) {\n add(errors, \"egressAllowlist\", \"A non-empty allowlist is required when network access is enabled.\", \"conditional\");\n }\n value.forEach((destination, index) => {\n if (!isEgressDestination(destination)) {\n add(\n errors,\n `egressAllowlist.${index}`,\n \"Expected a lowercase public DNS name with an optional port; schemes, paths, IPs, and local names are forbidden.\",\n \"pattern\",\n );\n }\n });\n}\n\nfunction validateCredentialScopes(value: unknown, errors: ManifestValidationError[]): void {\n // Optional. Absent → the broker defaults to the provider's management scope (docs/21 §12.5).\n if (value === undefined) return;\n if (!Array.isArray(value) || !value.every(isString)) {\n add(errors, \"credentialScopes\", \"Expected an array of AAD scope strings.\", \"type\");\n return;\n }\n if (value.length === 0) add(errors, \"credentialScopes\", \"Must be omitted rather than empty.\", \"minItems\");\n if (value.length > 8) add(errors, \"credentialScopes\", \"Must contain at most 8 scopes.\", \"maxItems\");\n if (new Set(value).size !== value.length) add(errors, \"credentialScopes\", \"Items must be unique.\", \"uniqueItems\");\n value.forEach((scope, index) => {\n if (!CREDENTIAL_SCOPE_PATTERN.test(scope)) {\n add(\n errors,\n `credentialScopes.${index}`,\n \"Expected a least-privilege AAD scope such as https://vault.azure.net/.default.\",\n \"pattern\",\n );\n }\n });\n}\n\n/**\n * ★ THE ONE GRAMMAR FOR \"A HOST AN ISOLATED JOB MAY REACH\" — a lowercase public DNS name, an\n * optional `*.` wildcard and an optional port; no scheme, path, IP or local name. A package's\n * `egressAllowlist` is judged by it, and since docs/128 so is an engine action's\n * `execution.egress` (which additionally requires the port). Exported so the second caller reads\n * this rule rather than writing its own.\n */\nexport function isEgressDestination(destination: string): boolean {\n if (destination.length === 0 || destination.length > 253 || destination !== destination.toLowerCase()) {\n return false;\n }\n if (destination.includes(\"://\") || destination.includes(\"/\") || destination.includes(\"@\")) return false;\n const withoutWildcard = destination.startsWith(\"*.\") ? destination.slice(2) : destination;\n const host = withoutWildcard.replace(/:\\d+$/, \"\");\n if (isIP(host) !== 0 || host === \"localhost\" || host.endsWith(\".localhost\") || host.endsWith(\".local\")) {\n return false;\n }\n const match = /^(?:\\*\\.)?([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+)(?::([1-9]\\d{0,4}))?$/.exec(destination);\n if (!match) return false;\n const port = match[2] ? Number(match[2]) : undefined;\n return port === undefined || port <= 65_535;\n}\n\n/**\n * The runtime declaration, in either shape (docs/21 §11.4):\n *\n * { name, version } — legacy, and permanently valid (no `kind`)\n * { kind: interpreter, name, version } — the same thing, said explicitly\n * { kind: oci, image } — a digest-pinned OCI image\n *\n * Returns the NORMALIZED runtime for the manifest's `ok` branch, so what gets pinned and\n * persisted is the closed contract shape rather than whichever shape the author wrote. On any\n * error it returns undefined and the manifest fails; the field paths and keywords are the\n * ones the import UI already renders.\n */\nfunction validateRuntime(\n value: unknown,\n errors: ManifestValidationError[],\n): PackageRuntime | undefined {\n if (!isRecord(value)) {\n add(errors, \"runtime\", \"Expected an object.\", \"type\");\n return undefined;\n }\n const before = errors.length;\n if (value.kind !== undefined && !PACKAGE_RUNTIME_KINDS.includes(value.kind as PackageRuntimeKind)) {\n add(errors, \"runtime.kind\", `Must be one of: ${PACKAGE_RUNTIME_KINDS.join(\", \")}.`, \"enum\");\n return undefined;\n }\n if (value.kind === \"oci\") {\n // `name`/`version` on an OCI runtime are named as errors rather than ignored: an author\n // who wrote both believes the interpreter pin still applies, and silently dropping it\n // would leave them thinking they pinned something they did not.\n rejectUnknown(value, [\"kind\", \"image\"], \"runtime\", errors);\n const image = requiredString(value, \"image\", errors, undefined, undefined, \"runtime.image\");\n if (image !== undefined) {\n const check = checkOciImageReference(image);\n if (!check.ok) add(errors, \"runtime.image\", check.message, \"digestPinned\");\n }\n } else {\n rejectUnknown(value, [\"kind\", \"name\", \"version\"], \"runtime\", errors);\n // A CLOSED vocabulary since Phase 1, and refused HERE rather than at a runtime. An\n // interpreter name Opera does not know used to import cleanly, sit in the catalog looking\n // runnable, and fail at the adapter with \"powershell@7.4 is required\" — a comparison\n // against a literal that no author or operator could see. The refusal now names what IS\n // supported, at the moment the author can still change it.\n requiredEnum(value, \"name\", PACKAGE_INTERPRETERS, errors, \"runtime.name\");\n requiredString(value, \"version\", errors, undefined, undefined, \"runtime.version\");\n }\n // Normalize only what this function judged clean — normalizePackageRuntime throws, and a\n // manifest problem must surface as a rendered field error, never as a 500.\n return errors.length === before ? normalizePackageRuntime(value) : undefined;\n}\n\nfunction validateCapabilities(value: unknown, errors: ManifestValidationError[]): void {\n if (!isRecord(value)) {\n add(errors, \"capabilities\", \"Expected an object.\", \"type\");\n return;\n }\n rejectUnknown(value, [\"dryRun\", \"idempotent\", \"rollback\"], \"capabilities\", errors);\n for (const key of [\"dryRun\", \"idempotent\", \"rollback\"] as const) {\n requiredBoolean(value, key, errors, `capabilities.${key}`);\n }\n}\n\nfunction validatePermissions(value: unknown, errors: ManifestValidationError[]): void {\n if (!Array.isArray(value)) {\n add(errors, \"requiredPermissions\", \"Expected an array.\", \"type\");\n return;\n }\n value.forEach((permission, index) => {\n const path = `requiredPermissions.${index}`;\n if (!isRecord(permission)) {\n add(errors, path, \"Expected an object.\", \"type\");\n return;\n }\n rejectUnknown(permission, [\"provider\", \"actions\", \"scope\"], path, errors);\n requiredEnum(permission, \"provider\", PROVIDERS, errors, `${path}.provider`);\n requiredStringArray(permission, \"actions\", errors, {\n nonEmpty: true,\n unique: true,\n path: `${path}.actions`,\n });\n requiredString(permission, \"scope\", errors, undefined, undefined, `${path}.scope`);\n });\n}\n\nfunction validateParameterProperty(\n name: string,\n value: unknown,\n errors: ManifestValidationError[],\n): \"string\" | \"boolean\" | undefined {\n const path = `parameters.properties.${name}`;\n if (!isRecord(value)) {\n add(errors, path, \"Expected an object.\", \"type\");\n return undefined;\n }\n rejectUnknown(value, PARAMETER_PROPERTY_FIELDS, path, errors);\n const type = requiredEnum(value, \"type\", [\"string\", \"boolean\"], errors, `${path}.type`);\n requiredString(value, \"title\", errors, undefined, undefined, `${path}.title`);\n if (value.description !== undefined && !isString(value.description)) add(errors, `${path}.description`, \"Expected a string.\", \"type\");\n requiredEnum(value, \"control\", PARAMETER_CONTROLS, errors, `${path}.control`);\n if (value.enum !== undefined) {\n if (!Array.isArray(value.enum) || !value.enum.every(isString)) add(errors, `${path}.enum`, \"Expected an array of strings.\", \"type\");\n else if (type === \"boolean\") add(errors, `${path}.enum`, \"Boolean properties cannot declare string enum values.\", \"type\");\n else {\n if (value.enum.length === 0) add(errors, `${path}.enum`, \"Must contain at least one value.\", \"minItems\");\n if (new Set(value.enum).size !== value.enum.length) add(errors, `${path}.enum`, \"Values must be unique.\", \"uniqueItems\");\n if (isString(value.default) && !value.enum.includes(value.default)) {\n add(errors, `${path}.default`, \"Default must be one of the enum values.\", \"enum\");\n }\n }\n }\n if (value.default !== undefined && type && typeof value.default !== type) {\n add(errors, `${path}.default`, `Expected a ${type}.`, \"type\");\n }\n return type;\n}\n\n/**\n * The docs/29 D3 rule table for `discover` + `dependsOn`. Hard-fails only genuine\n * authoring bugs (malformed id, boolean target, unknown/mismatched provider, bad\n * reference); an unimplemented-but-well-formed type merely WARNS (the field degrades\n * to free text). Returns the property to pin: a copy with the canonical `discover`\n * id when a bare value was normalized, otherwise the input property unchanged.\n */\nfunction validateDiscoveryAnnotations(\n name: string,\n property: Record<string, unknown>,\n declaredType: \"string\" | \"boolean\" | undefined,\n properties: Record<string, unknown>,\n declarationOrder: readonly string[],\n providers: readonly Provider[] | undefined,\n errors: ManifestValidationError[],\n warnings: ManifestValidationWarning[],\n): Record<string, unknown> {\n const path = `parameters.properties.${name}`;\n let normalized = property;\n let resolved: ParsedDiscoveryType | null = null;\n\n if (property.discover !== undefined) {\n const match = isString(property.discover)\n ? DISCOVERY_TYPE_PATTERN.exec(property.discover)\n : null;\n if (!match) {\n add(\n errors,\n `${path}.discover`,\n 'Expected \"provider/resourceType\" (e.g. \"azure/virtualMachine\") or a bare resource type.',\n \"pattern\",\n );\n } else if (declaredType === \"boolean\") {\n add(errors, `${path}.discover`, \"Discovery applies only to string parameters.\", \"type\");\n } else {\n const [, prefix, type] = match;\n if (prefix !== undefined) {\n const provider = PROVIDERS.find((p) => p === prefix);\n if (!provider) {\n add(errors, `${path}.discover`, `Unknown provider namespace \"${prefix}\".`, \"enum\");\n } else if (providers && !providers.includes(provider)) {\n add(\n errors,\n `${path}.discover`,\n `Discovery provider \"${provider}\" is not declared in the manifest's providers.`,\n \"providerMismatch\",\n );\n } else {\n resolved = { provider, type: type! };\n }\n } else if (providers) {\n if (providers.length === 1) {\n resolved = { provider: providers[0]!, type: type! };\n normalized = {\n ...property,\n discover: formatDiscoveryType(resolved.provider, resolved.type),\n };\n } else {\n add(\n errors,\n `${path}.discover`,\n 'Bare discovery types are ambiguous in a multi-provider package; use \"provider/type\".',\n \"ambiguous\",\n );\n }\n }\n if (resolved && providers && !discoveryTypeSpec(resolved.provider, resolved.type)) {\n warnings.push({\n path: `${path}.discover`,\n message: `\"${formatDiscoveryType(resolved.provider, resolved.type)}\" is not implemented by this ${BRAND_SHORT_NAME} version; the field will render as free text.`,\n keyword: \"unknownDiscoveryType\",\n });\n }\n }\n }\n\n // dependsOn: array form (each item is a sibling param name AND its scope key) or\n // object form (scope key → sibling param name). Allowed without `discover` (inert).\n let covers: ((scopeKey: string) => boolean) | undefined;\n if (property.dependsOn === undefined) {\n covers = () => false;\n } else if (Array.isArray(property.dependsOn) && property.dependsOn.every(isString)) {\n const names = property.dependsOn;\n for (const dependency of names) {\n validateDependency(name, dependency, properties, declarationOrder, path, errors);\n }\n covers = (scopeKey) => names.includes(scopeKey);\n } else if (\n isRecord(property.dependsOn) &&\n Object.values(property.dependsOn).every(isString)\n ) {\n const mapping = property.dependsOn as Record<string, string>;\n for (const dependency of Object.values(mapping)) {\n validateDependency(name, dependency, properties, declarationOrder, path, errors);\n }\n covers = (scopeKey) => scopeKey in mapping;\n } else {\n add(\n errors,\n `${path}.dependsOn`,\n \"Expected an array of property names or an object mapping scope keys to property names.\",\n \"type\",\n );\n }\n\n // Coverage lint: a known cascading type whose required scope keys are not all\n // declared imports fine, but its picker would stay empty — warn (docs/29 D3).\n //\n // Reads `requires`, NOT `identifiedBy`, and that is the deliberate choice: this warning\n // is about whether a LISTING can be made at all, which is exactly what `requires`\n // means. `identifiedBy` answers a different question — which scope a fanned-out CHILD\n // must be bound with — and is enforced where it belongs, in TargetResolver.plan. So\n // `virtualMachine` (requires: [], identifiedBy: [\"resourceGroup\"]) correctly emits no\n // warning: its picker works with or without a declared resource group, and a package\n // author pushed into declaring one would only narrow their own fan-out for no reason.\n if (resolved && covers) {\n const spec = discoveryTypeSpec(resolved.provider, resolved.type);\n const missing = spec?.requires.filter((scopeKey) => !covers(scopeKey)) ?? [];\n if (missing.length > 0) {\n warnings.push({\n path: `${path}.dependsOn`,\n message:\n `Discovery of \"${formatDiscoveryType(resolved.provider, resolved.type)}\" needs ` +\n `scope key(s) ${missing.map((scopeKey) => `\"${scopeKey}\"`).join(\", \")}; declare ` +\n \"them in dependsOn or the picker will stay empty.\",\n keyword: \"cascadeScopeMissing\",\n });\n }\n }\n\n return normalized;\n}\n\nfunction validateDependency(\n name: string,\n dependency: string,\n properties: Record<string, unknown>,\n declarationOrder: readonly string[],\n path: string,\n errors: ManifestValidationError[],\n): void {\n if (dependency === name) {\n add(errors, `${path}.dependsOn`, \"A property cannot depend on itself.\", \"reference\");\n return;\n }\n if (!(dependency in properties)) {\n add(errors, `${path}.dependsOn`, `Unknown property \"${dependency}\".`, \"reference\");\n return;\n }\n // A FORM THAT ASKS FOR A FIELD BEFORE ITS DEPENDENCY IS BROKEN, and since the authored order\n // is now what the wizard renders, this is the difference between a usable form and one that\n // asks somebody to choose a virtual machine before the resource group that scopes the list.\n //\n // Refused rather than silently reordered. Reordering would produce a working form and leave\n // the author believing they wrote one — and the next reader of the manifest would see a\n // declaration that contradicts the screen. Import-time only: published versions are\n // immutable, so this affects new versions and nothing already in a catalog.\n if (declarationOrder.indexOf(dependency) > declarationOrder.indexOf(name)) {\n add(\n errors,\n `${path}.dependsOn`,\n `\"${name}\" depends on \"${dependency}\", which is declared after it. Parameters are ` +\n `shown in the order you declare them, so \"${dependency}\" must be declared before ` +\n `\"${name}\" — otherwise the form asks for \"${name}\" before the value that scopes it.`,\n \"order\",\n );\n }\n}\n\n/**\n * The order key is written by us at import ({@link withParameterOrder}), from the order the\n * properties were authored in. A schema may already carry one — a re-validated normalized copy\n * does — and that is accepted; what is refused is one that DISAGREES with the properties it\n * orders, because the two would then be two answers to the same question and the array wins on\n * every screen. Rejecting is better than silently overwriting: overwriting discards something\n * the author wrote and tells them nothing.\n */\nfunction validateParameterOrder(\n value: unknown,\n key: string,\n declarationOrder: readonly string[],\n errors: ManifestValidationError[],\n): void {\n if (value === undefined) return;\n const path = `parameters.${key}`;\n if (!Array.isArray(value) || !value.every(isString)) {\n add(errors, path, \"Expected an array of property names.\", \"type\");\n return;\n }\n if (\n value.length !== declarationOrder.length ||\n value.some((name, index) => name !== declarationOrder[index])\n ) {\n add(\n errors,\n path,\n \"Must list every property exactly once, in the order the properties are declared \" +\n `(${declarationOrder.join(\", \")}). ${BRAND_SHORT_NAME} writes this field at import to preserve your ` +\n \"field order through storage; it is not a second place to choose an order.\",\n \"consistency\",\n );\n }\n}\n\nfunction requiredSafePath(record: Record<string, unknown>, key: string, errors: ManifestValidationError[], directory: boolean): string | undefined {\n const value = requiredString(record, key, errors);\n if (value && (!isSafeRelativePath(value) || (directory && !value.endsWith(\"/\")))) {\n add(errors, key, directory ? \"Expected a safe relative directory path ending in /.\" : \"Expected a safe relative file path.\", \"path\");\n }\n return value;\n}\n\nfunction optionalSafePath(record: Record<string, unknown>, key: string, errors: ManifestValidationError[], directory: boolean): void {\n if (!isString(record[key]) || !record[key]) add(errors, key, \"Expected a non-empty string.\", \"type\");\n else if (!isSafeRelativePath(record[key]) || (directory && !record[key].endsWith(\"/\"))) add(errors, key, \"Expected a safe relative directory path ending in /.\", \"path\");\n}\n\nfunction requiredString(record: Record<string, unknown>, key: string, errors: ManifestValidationError[], pattern?: RegExp, expected?: string, path = key): string | undefined {\n const value = record[key];\n if (!isString(value) || value.trim().length === 0) {\n add(errors, path, \"Expected a non-empty string.\", \"required\");\n return undefined;\n }\n if (pattern && !pattern.test(value)) add(errors, path, `Expected ${expected ?? \"the required format\"}.`, \"pattern\");\n return value;\n}\n\nfunction requiredBoolean(record: Record<string, unknown>, key: string, errors: ManifestValidationError[], path = key): boolean | undefined {\n if (typeof record[key] !== \"boolean\") {\n add(errors, path, \"Expected a boolean.\", \"type\");\n return undefined;\n }\n return record[key];\n}\n\nfunction requiredConst(record: Record<string, unknown>, key: string, expected: string, errors: ManifestValidationError[], path = key): void {\n if (record[key] !== expected) add(errors, path, `Must equal \"${expected}\".`, \"const\");\n}\n\nfunction requiredEnum<T extends string>(record: Record<string, unknown>, key: string, values: readonly T[], errors: ManifestValidationError[], path = key): T | undefined {\n const value = record[key];\n if (!isString(value) || !values.includes(value as T)) {\n add(errors, path, `Must be one of: ${values.join(\", \")}.`, \"enum\");\n return undefined;\n }\n return value as T;\n}\n\nfunction requiredStringArray(record: Record<string, unknown>, key: string, errors: ManifestValidationError[], options: { nonEmpty?: boolean; unique?: boolean; values?: readonly string[]; path?: string } = {}): string[] | undefined {\n const path = options.path ?? key;\n const value = record[key];\n if (!Array.isArray(value) || !value.every(isString)) {\n add(errors, path, \"Expected an array of strings.\", \"type\");\n return undefined;\n }\n if (options.nonEmpty && value.length === 0) add(errors, path, \"Must contain at least one item.\", \"minItems\");\n value.forEach((item, index) => {\n if (item.trim().length === 0) add(errors, `${path}.${index}`, \"Expected a non-empty string.\", \"minLength\");\n });\n if (options.unique && new Set(value).size !== value.length) add(errors, path, \"Items must be unique.\", \"uniqueItems\");\n const allowedValues = options.values;\n if (allowedValues) value.forEach((item, index) => {\n if (!allowedValues.includes(item)) add(errors, `${path}.${index}`, `Must be one of: ${allowedValues.join(\", \")}.`, \"enum\");\n });\n return value;\n}\n\nfunction rejectUnknown(record: Record<string, unknown>, fields: readonly string[], prefix: string, errors: ManifestValidationError[]): void {\n for (const key of Object.keys(record)) if (!fields.includes(key)) add(errors, prefix ? `${prefix}.${key}` : key, \"Unknown field.\", \"additionalProperties\");\n}\n\nfunction add(errors: ManifestValidationError[], path: string, message: string, keyword?: string): void {\n errors.push({ path, message, ...(keyword ? { keyword } : {}) });\n}\n\n/** The failure branch only, so it satisfies every result type in this module. */\nfunction invalid(\n path: string,\n message: string,\n keyword: string,\n): { ok: false; errors: ManifestValidationError[] } {\n return { ok: false, errors: [{ path, message, keyword }] };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction isString(value: unknown): value is string { return typeof value === \"string\"; }\n\nfunction sortJson(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortJson);\n if (!isRecord(value)) return value;\n return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortJson(value[key])]));\n}\n","import type {\n PackageJsonObject,\n PackagePhase,\n PackageResultCheck,\n PackageResultError,\n PackageResultV1,\n} from \"@runveric/contracts\";\n// ★ THE LITERAL THAT USED TO BE HERE WAS NOT SLOPPINESS, IT WAS A LAYER (docs/95 §3).\n// This package is a DEPENDENCY of `@runveric/api`, so it could not reach the declaration that\n// lived in `apps/api/.../package-runtime-protocol.ts` — not by policy, by packaging. The\n// declaration moved down to `@runveric/contracts`, which both layers already depend on, and the\n// acceptor and the emitters now read the same one.\nimport { PACKAGE_RESULT_PROTOCOL_VERSION } from \"@runveric/contracts\";\n\nconst RESULT_FIELDS = [\n \"protocolVersion\",\n \"status\",\n \"message\",\n \"checks\",\n \"outputs\",\n \"rollbackCapture\",\n \"error\",\n] as const;\nconst CHECK_FIELDS = [\"status\", \"message\", \"data\"] as const;\nconst ERROR_FIELDS = [\"code\", \"message\", \"retryable\"] as const;\nconst MAX_MESSAGE_LENGTH = 4_096;\nconst MAX_CHECKS = 100;\nconst MAX_JSON_DEPTH = 16;\nconst MAX_JSON_KEYS = 1_000;\n\nexport class PackageProtocolError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PackageProtocolError\";\n }\n}\n\n/** Closed validation for the only result protocol accepted from package code. */\nexport function validatePackageResult(value: unknown, phase: PackagePhase): PackageResultV1 {\n const result = record(value, \"result\");\n rejectUnknown(result, RESULT_FIELDS, \"result\");\n if (result.protocolVersion !== PACKAGE_RESULT_PROTOCOL_VERSION) {\n fail(`result.protocolVersion must equal \"${PACKAGE_RESULT_PROTOCOL_VERSION}\".`);\n }\n if (!isOneOf(result.status, [\"succeeded\", \"failed\", \"cancelled\"] as const)) {\n fail(\"result.status must be succeeded, failed, or cancelled.\");\n }\n requiredBoundedString(result.message, \"result.message\");\n\n const checks = result.checks === undefined ? undefined : validateChecks(result.checks);\n const outputs = result.outputs === undefined ? undefined : jsonObject(result.outputs, \"result.outputs\");\n const rollbackCapture = result.rollbackCapture === undefined\n ? undefined\n : jsonObject(result.rollbackCapture, \"result.rollbackCapture\");\n const error = result.error === undefined || result.error === null\n ? result.error as null | undefined\n : validateError(result.error);\n\n if (phase === \"validate\") {\n if (outputs !== undefined || rollbackCapture !== undefined) {\n fail(\"Validate results cannot contain outputs or rollbackCapture.\");\n }\n } else if (checks !== undefined) {\n fail(`${phase} results cannot contain validation checks.`);\n }\n if (phase !== \"run\" && rollbackCapture !== undefined) {\n fail(\"rollbackCapture is allowed only in run results.\");\n }\n // A FAILED RESULT MUST CARRY A STRUCTURED REASON. That was always the rule; \"the reason is\n // `error`\" was the mistake, and it made the validate phase unable to report its own failure.\n //\n // Validate exists to PRODUCE CHECKS — one entry per pre-flight, each passed/warning/failed.\n // When one of them failed, the checks ARE the structured reason, and demanding `error` on top\n // makes an author state the same fact twice. The package that found this supplied `error`\n // faithfully in run/main.ps1 and reasonably assumed checks sufficed where checks are the\n // point; docs/22 never said otherwise, because this requirement was never documented at all.\n //\n // Only validate can take this route: run and rollback forbid `checks` outright a few lines\n // above, so a failed run result still has exactly one way to say why. This widens what is\n // accepted — nothing that validated before validates any less now.\n if (result.status === \"failed\" && error === undefined) {\n const reportedByChecks =\n phase === \"validate\" && (checks ?? []).some((check) => check.status === \"failed\");\n if (!reportedByChecks) {\n // The message NAMES THE PHASE and both routes, because the author reading it is looking\n // at one phase's script and needs to know what that phase may supply — not the general\n // rule. \"A failed result must contain result.error\" sent this author looking for a field\n // they had already used correctly somewhere else.\n fail(\n phase === \"validate\"\n ? \"A failed validate result must contain result.error, or at least one entry in \" +\n 'result.checks with status \"failed\".'\n : `A failed ${phase} result must contain result.error.`,\n );\n }\n }\n if (result.status !== \"failed\" && error !== undefined && error !== null) {\n fail(\"Only a failed result may contain result.error.\");\n }\n\n return {\n protocolVersion: PACKAGE_RESULT_PROTOCOL_VERSION,\n status: result.status,\n message: result.message as string,\n ...(checks ? { checks } : {}),\n ...(outputs ? { outputs } : {}),\n ...(rollbackCapture ? { rollbackCapture } : {}),\n ...(error !== undefined ? { error } : {}),\n };\n}\n\nfunction validateChecks(value: unknown): PackageResultCheck[] {\n if (!Array.isArray(value) || value.length > MAX_CHECKS) {\n fail(`result.checks must be an array of at most ${MAX_CHECKS} checks.`);\n }\n return value.map((item, index) => {\n const check = record(item, `result.checks.${index}`);\n rejectUnknown(check, CHECK_FIELDS, `result.checks.${index}`);\n if (!isOneOf(check.status, [\"passed\", \"warning\", \"failed\"] as const)) {\n fail(`result.checks.${index}.status is invalid.`);\n }\n requiredBoundedString(check.message, `result.checks.${index}.message`);\n const data = check.data === undefined\n ? undefined\n : jsonObject(check.data, `result.checks.${index}.data`);\n return {\n status: check.status,\n message: check.message as string,\n ...(data ? { data } : {}),\n };\n });\n}\n\nfunction validateError(value: unknown): PackageResultError {\n const error = record(value, \"result.error\");\n rejectUnknown(error, ERROR_FIELDS, \"result.error\");\n requiredBoundedString(error.code, \"result.error.code\");\n requiredBoundedString(error.message, \"result.error.message\");\n if (error.retryable !== undefined && typeof error.retryable !== \"boolean\") {\n fail(\"result.error.retryable must be a boolean.\");\n }\n return {\n code: error.code as string,\n message: error.message as string,\n ...(typeof error.retryable === \"boolean\" ? { retryable: error.retryable } : {}),\n };\n}\n\nfunction jsonObject(value: unknown, path: string): PackageJsonObject {\n const object = record(value, path);\n let keys = 0;\n validateJson(object, path, 0, () => {\n keys += 1;\n if (keys > MAX_JSON_KEYS) fail(`${path} contains too many keys.`);\n });\n return object as PackageJsonObject;\n}\n\nfunction validateJson(\n value: unknown,\n path: string,\n depth: number,\n keySeen: () => void,\n): void {\n if (depth > MAX_JSON_DEPTH) fail(`${path} exceeds the maximum JSON depth.`);\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\" ||\n (typeof value === \"number\" && Number.isFinite(value))\n ) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((item, index) => validateJson(item, `${path}.${index}`, depth + 1, keySeen));\n return;\n }\n if (typeof value === \"object\" && value !== null) {\n for (const [key, nested] of Object.entries(value)) {\n keySeen();\n validateJson(nested, `${path}.${key}`, depth + 1, keySeen);\n }\n return;\n }\n fail(`${path} must contain JSON values only.`);\n}\n\nfunction record(value: unknown, path: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n fail(`${path} must be an object.`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction rejectUnknown(\n value: Record<string, unknown>,\n fields: readonly string[],\n path: string,\n): void {\n for (const key of Object.keys(value)) {\n if (!fields.includes(key)) fail(`${path}.${key} is not allowed.`);\n }\n}\n\nfunction requiredBoundedString(value: unknown, path: string): void {\n if (typeof value !== \"string\" || value.length === 0 || value.length > MAX_MESSAGE_LENGTH) {\n fail(`${path} must be a non-empty string of at most ${MAX_MESSAGE_LENGTH} characters.`);\n }\n}\n\nfunction isOneOf<T extends string>(value: unknown, allowed: readonly T[]): value is T {\n return typeof value === \"string\" && allowed.includes(value as T);\n}\n\nfunction fail(message: string): never {\n throw new PackageProtocolError(message);\n}\n","import type {\n ActionPackageManifest,\n ManifestValidationError,\n ManifestValidationWarning,\n ParameterSchema,\n Provider,\n} from \"@runveric/contracts\";\nimport { BRAND_ARTICLE, BRAND_SHORT_NAME, withParameterOrder } from \"@runveric/contracts\";\nimport { parseAndValidateManifest, validateParameterSchema } from \"./manifest-validator\";\n\n/**\n * ─── THE VALIDATION, ONCE ───────────────────────────────────────────────────────────────\n *\n * Everything Opera decides about a package from the package ALONE: its manifest, its layout,\n * and its parameter schema. Nothing here reads configuration, asks a database, or touches the\n * network, which is precisely what makes it runnable in three places:\n *\n * 1. `runveric check`, offline, on an author's laptop before anything is pushed;\n * 2. the import path, when a version arrives from a Git source;\n * 3. the authoring path, when a version is published from inside Opera.\n *\n * There is no second implementation, and there must never be one. A local check that disagrees\n * with the server is worse than no local check: it is a tool that tells an author they are done\n * and then lets the server tell them they are not, which is the exact commit-push-wait loop\n * this feature exists to close.\n *\n * WHAT IS DELIBERATELY NOT HERE: the deployment's capability gates — whether this deployment\n * can broker egress, whether organization sandboxing is on, whether the runner ships the\n * declared interpreter. Those are facts about a SERVER, an author's laptop cannot know them,\n * and pretending to check them offline would be the drift this module exists to prevent. They\n * stay where they are, on the import path, and `check` does not claim to have run them.\n */\n\nexport const MANIFEST_FILE = \"action.yaml\";\n\n/** Files every package must ship, whatever it does. */\nexport const REQUIRED_PACKAGE_FILES = [\"README.md\", \"LICENSE\"] as const;\n\n/**\n * A DISCRIMINATED result, so `ok` carries the products with it. The alternative — one shape\n * with three optional fields — makes every caller write a non-null assertion right after\n * checking `ok`, and an assertion is how a refactor eventually returns `ok: true` with no\n * manifest and nobody notices until a run.\n */\nexport type ActionPackageValidation =\n | {\n ok: true;\n errors: readonly [];\n warnings: ManifestValidationWarning[];\n /** The NORMALIZED manifest — legacy runtime shapes already resolved. */\n manifest: ActionPackageManifest;\n /** sha256 of the canonicalized manifest AS AUTHORED, never of the normalized copy. */\n manifestHash: string;\n /** The NORMALIZED parameter schema, carrying the author's field order. */\n parameterSchema: ParameterSchema;\n }\n | {\n ok: false;\n errors: ManifestValidationError[];\n warnings: ManifestValidationWarning[];\n /** Present when the manifest itself validated and something else did not. */\n manifest?: ActionPackageManifest;\n manifestHash?: string;\n parameterSchema?: ParameterSchema;\n };\n\n/**\n * Validate a materialized package.\n *\n * Errors are ACCUMULATED across stages rather than thrown at the first one. An author who has\n * a typo in `runtime.name` and a missing LICENSE should learn both now, not on the next round\n * trip. Stages that genuinely cannot run without an earlier one — the parameter schema is\n * located by a manifest field — are skipped, and their absence is not reported as a second\n * problem.\n */\nexport function validateActionPackage(\n files: ReadonlyMap<string, Buffer>,\n): ActionPackageValidation {\n const errors: ManifestValidationError[] = [];\n const warnings: ManifestValidationWarning[] = [];\n\n const manifestSource = files.get(MANIFEST_FILE);\n if (!manifestSource) {\n return {\n ok: false,\n errors: [\n { path: MANIFEST_FILE, message: \"Required file is missing.\", keyword: \"required\" },\n ],\n warnings,\n };\n }\n\n const parsed = parseAndValidateManifest(manifestSource.toString(\"utf8\"));\n const manifest = parsed.ok ? parsed.value : undefined;\n if (parsed.ok) warnings.push(...parsed.warnings);\n else errors.push(...parsed.errors);\n\n errors.push(...layoutErrors(files, manifest));\n\n let parameterSchema: ParameterSchema | undefined;\n if (manifest) {\n const schema = parameterSchemaOf(files, manifest.parametersRef, manifest.providers);\n if (schema.ok) {\n parameterSchema = schema.value;\n warnings.push(...schema.warnings);\n } else {\n errors.push(...schema.errors);\n }\n }\n\n if (errors.length === 0 && manifest && parsed.ok && parameterSchema) {\n return {\n ok: true,\n errors: [],\n warnings,\n manifest,\n manifestHash: parsed.manifestHash,\n parameterSchema,\n };\n }\n return {\n ok: false,\n // A package with no reported error but a missing product would otherwise return `ok: false`\n // with an empty list, which reads as \"nothing is wrong and it still failed\". That can only\n // happen if a stage above silently produced nothing, which is a defect in THIS file.\n errors:\n errors.length > 0\n ? errors\n : [\n {\n path: MANIFEST_FILE,\n message:\n \"The package could not be validated, and no specific problem was reported. \" +\n `This is ${BRAND_ARTICLE} ${BRAND_SHORT_NAME} defect, not a problem with the package.`,\n keyword: \"internal\",\n },\n ],\n warnings,\n ...(manifest ? { manifest } : {}),\n ...(parsed.ok ? { manifestHash: parsed.manifestHash } : {}),\n ...(parameterSchema ? { parameterSchema } : {}),\n };\n}\n\n/**\n * The files a package must ship, and the entrypoint directories its manifest points at.\n *\n * The directory check is deliberately loose — \"something in the bundle starts with this path\" —\n * because WHICH file inside it is executed depends on the interpreter, and that belongs to the\n * authoring lint where it can name the expected filename and the one that is actually there.\n */\nfunction layoutErrors(\n files: ReadonlyMap<string, Buffer>,\n manifest: ActionPackageManifest | undefined,\n): ManifestValidationError[] {\n const errors: ManifestValidationError[] = [];\n for (const required of REQUIRED_PACKAGE_FILES) {\n if (!files.has(required)) {\n errors.push({ path: required, message: \"Required file is missing.\", keyword: \"required\" });\n }\n }\n if (!manifest) return errors;\n const entrypoints = [\n manifest.entrypoint,\n manifest.rollbackEntrypoint,\n manifest.validateEntrypoint,\n ];\n for (const path of entrypoints) {\n if (path && ![...files.keys()].some((file) => file.startsWith(path))) {\n errors.push({\n path,\n message: \"Entrypoint directory is missing or empty.\",\n keyword: \"reference\",\n });\n }\n }\n return errors;\n}\n\ntype SchemaResult =\n | { ok: true; value: ParameterSchema; warnings: ManifestValidationWarning[] }\n | { ok: false; errors: ManifestValidationError[] };\n\nfunction parameterSchemaOf(\n files: ReadonlyMap<string, Buffer>,\n reference: string,\n providers: readonly Provider[],\n): SchemaResult {\n const file = files.get(reference);\n if (!file) {\n return {\n ok: false,\n errors: [\n {\n path: \"parametersRef\",\n message: `Referenced file \"${reference}\" is missing.`,\n keyword: \"reference\",\n },\n ],\n };\n }\n let value: unknown;\n try {\n value = JSON.parse(file.toString(\"utf8\"));\n } catch {\n return {\n ok: false,\n errors: [{ path: reference, message: \"File is not valid JSON.\", keyword: \"json\" }],\n };\n }\n // THE AUTHOR'S FIELD ORDER IS RECORDED HERE, AND CAN ONLY BE RECORDED HERE.\n //\n // `JSON.parse` preserves the order the author wrote their properties in, so this scope — and\n // nothing downstream of it — still holds it. One step later the schema is pinned into a jsonb\n // column, which normalizes object keys by LENGTH and destroys it. `withParameterOrder` copies\n // the order into an ARRAY, which survives.\n //\n // It happens inside the SHARED validator rather than in the import service so that every\n // publishing path gets it: an authored package built in the browser has exactly the same\n // problem and used to be nowhere near this line.\n const validated = validateParameterSchema(value, { providers });\n if (!validated.ok) return validated;\n return { ...validated, value: withParameterOrder(validated.value) };\n}\n","import { parseDocument } from \"yaml\";\nimport type { Node } from \"yaml\";\n\n/**\n * ─── WHERE A FINDING IS, IN THE AUTHOR'S OWN FILE ───────────────────────────────────────\n *\n * The validator reports a PATH (`parameters.properties.vmName.dependsOn`) because that is what\n * a control plane needs — it has no file, only a bundle. An author has a file open, and a\n * finding they have to go hunting for is a finding they learn to ignore.\n *\n * So this maps a validator path back to a line and column. It parses with the YAML parser for\n * BOTH file kinds deliberately: JSON is a subset of YAML, the parser records exact source\n * ranges for every node, and one implementation cannot drift from itself. A hand-rolled text\n * search would find the wrong `\"name\"` the first time a package declared two.\n *\n * A path that cannot be resolved yields no location rather than a guessed one. Pointing at the\n * wrong line is worse than pointing at none: it sends the reader to edit something correct.\n */\n\nexport interface SourceLocation {\n /** 1-indexed. */\n line: number;\n /** 1-indexed. */\n column: number;\n}\n\n/** Split a dotted validator path into node keys, with numeric segments as array indexes. */\nexport function pathSegments(path: string): (string | number)[] {\n return path\n .split(\".\")\n .filter((segment) => segment.length > 0)\n .map((segment) => (/^\\d+$/.test(segment) ? Number(segment) : segment));\n}\n\n/**\n * The line/column of `path` inside `source`, or null when the path does not resolve.\n *\n * `path` is a validator path relative to the DOCUMENT — so callers strip any file prefix the\n * validator adds first (the parameter-schema validator prefixes everything with `parameters.`,\n * which is not a key in `parameters.json`).\n */\nexport function locate(source: string, path: string): SourceLocation | null {\n const segments = pathSegments(path);\n let document;\n try {\n document = parseDocument(source);\n } catch {\n return null;\n }\n if (document.errors.length > 0) return null;\n\n // Walk to the deepest ANCESTOR that resolves. A path ending in a key the author has not\n // written yet (`egressAllowlist` on a manifest that omits it) still points somewhere useful:\n // the object the key belongs in, which is where they have to type.\n let node: unknown = null;\n for (let depth = segments.length; depth > 0; depth -= 1) {\n node = document.getIn(segments.slice(0, depth), true);\n if (isRangedNode(node)) break;\n node = null;\n }\n if (!isRangedNode(node)) {\n // Nothing in the path resolves — the whole document is the honest answer only when the\n // path was empty; otherwise say nothing.\n return segments.length === 0 ? { line: 1, column: 1 } : null;\n }\n return offsetToLocation(source, node.range[0]);\n}\n\n/** Line/column of the first occurrence of `offset` in `source`, both 1-indexed. */\nexport function offsetToLocation(source: string, offset: number): SourceLocation {\n const before = source.slice(0, Math.max(0, Math.min(offset, source.length)));\n const lines = before.split(\"\\n\");\n return { line: lines.length, column: (lines[lines.length - 1]?.length ?? 0) + 1 };\n}\n\nfunction isRangedNode(value: unknown): value is Node & { range: [number, number, number] } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"range\" in value &&\n Array.isArray((value as { range: unknown }).range) &&\n typeof (value as { range: number[] }).range[0] === \"number\"\n );\n}\n","import type { ManifestValidationError, ManifestValidationWarning } from \"@runveric/contracts\";\nimport { locate } from \"./source-location\";\nimport { BRAND_SHORT_NAME } from \"@runveric/contracts\";\n\n/**\n * ─── WHAT `check` TELLS AN AUTHOR ───────────────────────────────────────────────────────\n *\n * One shape for everything `runveric check` and the in-app Check button report, whether it\n * came from the manifest validator or from the authoring lint.\n *\n * Every finding names THE FILE, THE LINE and THE FIX. That is not decoration: a finding an\n * author cannot act on is a finding that trains them to ignore the tool, and a tool people\n * ignore is worse than no tool because it also carries the ones that matter.\n */\n\nexport type FindingSeverity = \"error\" | \"warning\";\n\nexport interface AuthoringFinding {\n severity: FindingSeverity;\n /** Stable slug, so a finding can be suppressed, searched for, or referred to in a review. */\n rule: string;\n /** Package-relative path of the file the author has to open. */\n file: string;\n /** 1-indexed. Absent when the location could not be resolved — never guessed. */\n line?: number;\n column?: number;\n /** What is wrong, in one sentence. */\n message: string;\n /** What to do about it, imperative. */\n fix: string;\n /**\n * HOW LOUD, and WHETHER IT GATES, are two different facts. `severity` is the first; this is\n * the second.\n *\n * An advisory ERROR is reported at full volume — red, counted as an error, first in the list —\n * and still does not by itself refuse a publish. That combination exists for exactly one kind\n * of rule: one whose detection is necessarily a HEURISTIC, where being wrong would block a\n * package that is actually correct. A lint that blocks a valid package is a lint people learn\n * to bypass, and then it stops carrying the rules that are certain.\n *\n * `--strict` still fails on these, so a team that wants the gate has one.\n */\n advisory?: boolean;\n /**\n * The validator path this finding is about. Two producers can legitimately find the same\n * defect — the validator knows the rule, the lint knows the line — and this is how the\n * report keeps the better of the two instead of printing both.\n */\n subject?: string;\n}\n\n/**\n * FIXES, BY VALIDATOR KEYWORD.\n *\n * The validator's `message` says what is wrong; the author still has to work out what to type.\n * Keyed by the keyword the validator already emits so a new rule inherits a sensible line\n * rather than shipping with none, and the specific ones below say something worth reading.\n */\nconst FIX_BY_KEYWORD: Record<string, string> = {\n yaml: \"Fix the YAML syntax — the file could not be parsed at all, so nothing else was checked.\",\n json: \"Fix the JSON syntax — the file could not be parsed at all.\",\n required: \"Add this field. Every manifest field is required unless it is documented optional.\",\n type: \"Change the value to the type this field expects.\",\n pattern: \"Rewrite the value in the format named above.\",\n const: \"This field has exactly one legal value; use it verbatim.\",\n enum: \"Use one of the listed values — the vocabulary is closed, so anything else is refused at import.\",\n minItems: \"Add at least one item, or remove the field entirely if it is optional.\",\n maxItems: \"Remove items until the list is within the limit.\",\n minLength: \"Replace the empty entry with a real value, or remove it.\",\n maxLength: \"Shorten the value.\",\n uniqueItems: \"Remove the duplicate entries.\",\n additionalProperties:\n \"Remove this field. The manifest vocabulary is closed, so an unknown key is either a typo \" +\n \"or a field that does not exist — both silently do nothing at run time.\",\n conditional: \"Make the two fields agree; one of them is describing a package the other is not.\",\n consistency: \"Make the two declarations agree.\",\n reference: \"Point this at something that exists in the package.\",\n path: \"Use a safe relative path inside the package (no leading /, no .., directories end in /).\",\n order: \"Move the declaration so the parameter it depends on comes first.\",\n digestPinned:\n \"Pin the image by digest (`registry/repo@sha256:…`). A tag is a mutable pointer; a digest \" +\n \"is the content, and only the second is reproducible.\",\n providerMismatch: \"Add the provider to `providers`, or discover from one already declared.\",\n ambiguous: 'Qualify the discovery type as \"provider/type\".',\n runnerCapability:\n \"Either drop the capability from the manifest, or ask an administrator to enable the \" +\n \"runtime feature named above on this deployment.\",\n untrustedCapability:\n `Import through a tenant-owned Git source, or author the package in ${BRAND_SHORT_NAME} — both reach ` +\n \"organization tier, which may declare these.\",\n organizationCapability:\n \"Ask an administrator to enable organization-package sandboxing on this deployment.\",\n unknownDiscoveryType:\n `Leave it if the type is coming; the field renders as free text until this ${BRAND_SHORT_NAME} version ` +\n \"implements it.\",\n cascadeScopeMissing: \"Add the named scope keys to `dependsOn`, or the picker will stay empty.\",\n};\n\nconst GENERIC_FIX = \"Correct the value this field is reported on.\";\n\n/**\n * Turn one validator error/warning into a finding, resolving its line inside the file it is\n * about. `pathPrefix` is what the validator prepends and the file does not have: the parameter\n * schema validator reports `parameters.properties.x`, and `parameters.` is not a key in\n * `parameters.json`.\n */\nexport function findingFromValidation(\n problem: ManifestValidationError | ManifestValidationWarning,\n options: {\n severity: FindingSeverity;\n file: string;\n source: string;\n pathPrefix?: string;\n },\n): AuthoringFinding {\n const prefix = options.pathPrefix ? `${options.pathPrefix}.` : \"\";\n const documentPath = problem.path.startsWith(prefix)\n ? problem.path.slice(prefix.length)\n : problem.path;\n const at = locate(options.source, documentPath);\n return {\n severity: options.severity,\n rule: `manifest/${problem.keyword ?? \"invalid\"}`,\n file: options.file,\n ...(at ? { line: at.line, column: at.column } : {}),\n message: `${problem.path}: ${problem.message}`,\n fix: (problem.keyword && FIX_BY_KEYWORD[problem.keyword]) ?? GENERIC_FIX,\n subject: problem.path,\n };\n}\n\n/**\n * Merge findings from every producer, keeping ONE per subject.\n *\n * The validator and the lint can find the same defect from different angles — the validator\n * knows which rule it broke, the lint knows which line it is on. Printing both makes a clean\n * package look broken twice, so the one carrying a LINE wins: a location is the part the\n * author cannot reconstruct.\n *\n * Findings with no subject are never merged; they are about different things by construction.\n */\nexport function mergeFindings(...groups: readonly AuthoringFinding[][]): AuthoringFinding[] {\n const bySubject = new Map<string, AuthoringFinding>();\n const unkeyed: AuthoringFinding[] = [];\n for (const finding of groups.flat()) {\n if (finding.subject === undefined) {\n unkeyed.push(finding);\n continue;\n }\n const existing = bySubject.get(finding.subject);\n if (!existing || (existing.line === undefined && finding.line !== undefined)) {\n bySubject.set(finding.subject, finding);\n }\n }\n return sortFindings([...bySubject.values(), ...unkeyed]);\n}\n\n/** Errors before warnings, then by file, then by line — the order somebody fixes them in. */\nexport function sortFindings(findings: readonly AuthoringFinding[]): AuthoringFinding[] {\n const rank = (severity: FindingSeverity): number => (severity === \"error\" ? 0 : 1);\n return [...findings].sort(\n (left, right) =>\n rank(left.severity) - rank(right.severity) ||\n left.file.localeCompare(right.file) ||\n (left.line ?? Number.MAX_SAFE_INTEGER) - (right.line ?? Number.MAX_SAFE_INTEGER) ||\n left.rule.localeCompare(right.rule),\n );\n}\n","import { PACKAGE_INTERPRETERS, type PackageInterpreter } from \"@runveric/contracts\";\n\n/**\n * ─── HOW EACH INTERPRETER IS STARTED ────────────────────────────────────────────────────\n *\n * The one table that says, for each member of {@link PACKAGE_INTERPRETERS}: which binary the\n * runner image provides, which arguments it is started with, and which FILE inside the\n * declared entrypoint directory is the package's entrypoint.\n *\n * WHY IT LIVES HERE. It used to exist only inside `infra/docker/package-runner/bootstrap.ps1`,\n * which is fine while the runner is the only thing that starts a package. It is not any more:\n * `runveric test` starts the same package, in the same image, on an author's laptop. Two\n * copies of \"bash packages are called `main.sh` and run with `-euo pipefail`\" is exactly the\n * shape of defect that makes a local run pass and a real run fail — the failure this whole\n * feature exists to eliminate.\n *\n * The bootstrap cannot import TypeScript, so it keeps its own copy in PowerShell and\n * `apps/api/test/package-runtime-contract-parity.spec.ts` reads that file from disk and fails\n * if the two stop agreeing. Declared once, guarded across the language boundary.\n *\n * Keyed by the {@link PackageInterpreter} union (charter §4.2 R2), so adding an interpreter is\n * a COMPILE ERROR here until somebody says how it is started.\n */\nexport interface InterpreterLaunch {\n /** Absolute path of the interpreter binary INSIDE the runner image. */\n readonly fileName: string;\n /** Arguments passed before the script path. The script path is always last. */\n readonly arguments: readonly string[];\n /** The entrypoint file the runner looks for inside the declared entrypoint directory. */\n readonly entryFile: string;\n /**\n * The AUTHOR'S file, beside the entrypoint. The runner never looks for it — the scaffold's\n * entrypoint does, starting it with the `fileName` and `arguments` above, which is why it\n * belongs in this table rather than beside the scaffold's prose: the wrapper Opera writes\n * starts the body exactly the way the runner starts the wrapper.\n *\n * The split is the fix for a headline defect: pasting a script over `main.*` kept the work and\n * deleted the result contract, so every pasted action failed at run. One file is the author's,\n * one is Opera's, and a paste can only reach the first.\n */\n readonly bodyFile: string;\n}\n\nexport const PACKAGE_INTERPRETER_LAUNCH: Record<PackageInterpreter, InterpreterLaunch> = {\n powershell: {\n fileName: \"/usr/local/bin/pwsh\",\n // -File must stay LAST: everything after it is the script's own arguments.\n arguments: [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-File\"],\n entryFile: \"main.ps1\",\n bodyFile: \"body.ps1\",\n },\n bash: {\n // -e: a failing command ends the run. -u: an unset variable is an error rather than an\n // empty string, which is how a shell script silently deletes the wrong path. -o pipefail:\n // a failure mid-pipeline is not hidden by a successful `tee`.\n fileName: \"/bin/bash\",\n arguments: [\"-euo\", \"pipefail\"],\n entryFile: \"main.sh\",\n bodyFile: \"body.sh\",\n },\n python: {\n // -u: unbuffered stdout, or a package's progress lines arrive only at exit — and if it is\n // killed at its timeout, never.\n fileName: \"/usr/bin/python3\",\n arguments: [\"-u\"],\n entryFile: \"main.py\",\n bodyFile: \"body.py\",\n },\n};\n\n/** The entrypoint file each interpreter expects, as a sentence a refusal can carry. */\nexport function interpreterEntryFileList(): string {\n return PACKAGE_INTERPRETERS.map(\n (name) => `${name} → ${PACKAGE_INTERPRETER_LAUNCH[name].entryFile}`,\n ).join(\", \");\n}\n\n/**\n * ─── WHICH INTERPRETER A FILE IMPLIES ───────────────────────────────────────────────────\n *\n * The extension, and nothing cleverer. A package provides exactly one interpreter, and the file\n * that runs is the only thing that could decide which (docs/32 D4) — so this table is what an\n * import reads to answer \"what language is this\", both for the entrypoint (which decides) and\n * for every other file (which may warn).\n *\n * Keyed by {@link PackageInterpreter} so adding an interpreter is a COMPILE ERROR here until\n * somebody says what its files are called. Derived from `entryFile` rather than written out a\n * second time: `main.ps1` already states that PowerShell files end in `.ps1`.\n *\n * DELIBERATELY NOT EXHAUSTIVE OVER FILENAMES. Nothing here reads a shebang or sniffs content. A\n * file whose extension we do not recognise is DATA — it ships with the package and warns about\n * nothing — because a PowerShell package with a `config.json`, a `.csv` and a README is\n * entirely normal, and a rule that guessed would block it.\n */\nexport const PACKAGE_INTERPRETER_EXTENSIONS: Record<PackageInterpreter, string> = {\n powershell: extensionOf(PACKAGE_INTERPRETER_LAUNCH.powershell.entryFile),\n bash: extensionOf(PACKAGE_INTERPRETER_LAUNCH.bash.entryFile),\n python: extensionOf(PACKAGE_INTERPRETER_LAUNCH.python.entryFile),\n};\n\nfunction extensionOf(entryFile: string): string {\n const dot = entryFile.lastIndexOf(\".\");\n // A launch table entry with no extension would silently make every file match, so it is a\n // build-time error rather than a runtime surprise.\n if (dot <= 0) throw new Error(`Entry file \"${entryFile}\" has no extension.`);\n return entryFile.slice(dot);\n}\n\n/**\n * The interpreter a path implies, or null when the path is DATA rather than a script.\n *\n * Case-insensitive on the extension: Windows authors ship `Deploy.PS1`, and telling somebody\n * their own script is not a script because of its capitalisation would be indefensible.\n */\nexport function interpreterForPath(path: string): PackageInterpreter | null {\n const lower = path.toLowerCase();\n return (\n PACKAGE_INTERPRETERS.find((name) => lower.endsWith(PACKAGE_INTERPRETER_EXTENSIONS[name])) ??\n null\n );\n}\n","import type { PackageInterpreter, Provider } from \"@runveric/contracts\";\nimport { BRAND_SHORT_NAME, PACKAGE_INTERPRETERS } from \"@runveric/contracts\";\nimport type { AuthoringFinding } from \"./findings\";\nimport { sortFindings } from \"./findings\";\nimport { PACKAGE_INTERPRETER_LAUNCH } from \"./interpreter-launch\";\nimport { locate } from \"./source-location\";\n\n/**\n * ─── THE AUTHORING LINT ─────────────────────────────────────────────────────────────────\n *\n * Rules about a package that are TRUE but that no schema can express, because they are about\n * the relationship between a manifest and the script it describes.\n *\n * Each rule here was chosen because it has already cost somebody real time. The first one cost\n * five review cycles and blocked the first customer package run: a PowerShell variable followed\n * by `?` silently ate the resource name, and nothing in the product would tell you.\n *\n * The bar for adding a rule: it must be actionable, and it must be right nearly always. A lint\n * that cries wolf is not a weaker version of a good lint — it is worse than nothing, because it\n * teaches the author to skim past the rule that would have saved them.\n */\n\nexport interface LintInput {\n /** Every file in the package: package-relative path → UTF-8 contents. */\n files: ReadonlyMap<string, string>;\n /**\n * The manifest as parsed. Deliberately `unknown`-shaped: the lint runs even when the manifest\n * FAILED validation, because an author staring at a broken manifest is exactly who most needs\n * to be told their entrypoint file is also missing.\n */\n manifest: Record<string, unknown> | undefined;\n /** The raw `action.yaml` text, so manifest findings can name a line. */\n manifestSource: string | undefined;\n}\n\nconst MANIFEST_FILE = \"action.yaml\";\n\nexport function lintActionPackage(input: LintInput): AuthoringFinding[] {\n return sortFindings([\n ...lintPowerShellOptionalVariable(input),\n ...lintEntrypointFiles(input),\n ...lintDependsOnOrder(input),\n ...lintNetworkAllowlist(input),\n ...lintPermissionProviders(input),\n ...lintUnusedPermissions(input),\n ...lintUnreferencedEgressHosts(input),\n ...lintPhaseWritesNoResult(input),\n ]);\n}\n\n/**\n * ─── RULE 1: `$Name?` ───────────────────────────────────────────────────────────────────\n *\n * THE defect this whole feature exists because of.\n *\n * `?` is a legal character in an unbraced PowerShell variable name. So `\"Reimaging $Name?\"`\n * does not interpolate `$Name` and then print a question mark — it interpolates a variable\n * called `Name?`, which nobody declared, which expands to the empty string. The sentence still\n * reads fine. The resource name is simply gone.\n *\n * It cost five review cycles and was found in two minutes by running the script outside Opera.\n * There is nothing subtle about the fix — `${Name}?` — and nothing about the failure that\n * announces itself, which is the worst combination a defect can have.\n */\nfunction lintPowerShellOptionalVariable(input: LintInput): AuthoringFinding[] {\n const findings: AuthoringFinding[] = [];\n const pattern = /(?<!`)\\$(?!\\{)([A-Za-z_][A-Za-z0-9_]*)\\?/g;\n for (const [file, source] of input.files) {\n if (!file.endsWith(\".ps1\")) continue;\n source.split(/\\r?\\n/).forEach((text, index) => {\n // A `?` inside a comment is inert, and flagging it is the noise that makes a rule\n // ignorable. Only whole-line comments are skipped — a trailing `#` could be inside a\n // string, and guessing wrong there would suppress a real finding.\n if (text.trimStart().startsWith(\"#\")) return;\n for (const match of text.matchAll(pattern)) {\n const name = match[1]!;\n findings.push({\n severity: \"error\",\n rule: \"powershell/optional-variable\",\n file,\n line: index + 1,\n column: (match.index ?? 0) + 1,\n message:\n `\"$${name}?\" is read by PowerShell as a variable named \"${name}?\", not as ` +\n `$${name} followed by a question mark. \"${name}?\" is undefined, so it expands to ` +\n \"nothing and the value silently disappears from the output.\",\n fix: `Write \\${${name}}? — the braces end the variable name before the \"?\".`,\n });\n }\n });\n }\n return findings;\n}\n\n/**\n * ─── RULE 2: the entrypoint FILE ────────────────────────────────────────────────────────\n *\n * The manifest declares a DIRECTORY, and the import validator checks that directory is not\n * empty. Which file inside it gets executed depends on the declared interpreter — `main.ps1`,\n * `main.sh` or `main.py` — and that is checked nowhere until a runner cannot find it, at which\n * point the author is reading a failed run instead of an editor.\n *\n * The classic shape is an author who wrote `run/main.sh` and left the scaffolded\n * `runtime.name: powershell` in place.\n */\nfunction lintEntrypointFiles(input: LintInput): AuthoringFinding[] {\n const manifest = input.manifest;\n if (!manifest) return [];\n const runtime = manifest.runtime;\n if (typeof runtime !== \"object\" || runtime === null || Array.isArray(runtime)) return [];\n const declaration = runtime as Record<string, unknown>;\n // An OCI package brings its own image, and what it calls its entrypoint is that image's\n // business. Only the interpreter kind has a filename Opera decides.\n if (declaration.kind === \"oci\") return [];\n const name = declaration.name;\n if (typeof name !== \"string\" || !isInterpreter(name)) return [];\n const entryFile = PACKAGE_INTERPRETER_LAUNCH[name].entryFile;\n\n const findings: AuthoringFinding[] = [];\n for (const { field, phase } of ENTRYPOINT_PHASES) {\n const directory = manifest[field];\n if (typeof directory !== \"string\" || directory.length === 0) continue;\n const expected = `${directory}${entryFile}`;\n if (input.files.has(expected)) continue;\n const present = [...input.files.keys()].filter((path) => path.startsWith(directory));\n const misnamed = present.find((path) =>\n PACKAGE_INTERPRETERS.some(\n (other) => path === `${directory}${PACKAGE_INTERPRETER_LAUNCH[other].entryFile}`,\n ),\n );\n findings.push({\n severity: \"error\",\n rule: \"package/entrypoint-file-missing\",\n file: MANIFEST_FILE,\n ...(input.manifestSource ? locationOf(input.manifestSource, field) : {}),\n message:\n `This package declares runtime \"${name}\", so its ${phase} phase runs \"${expected}\" — ` +\n (misnamed\n ? `and the package ships \"${misnamed}\" instead.`\n : present.length === 0\n ? `and \"${directory}\" contains no files at all.`\n : `and \"${directory}\" contains ${present.join(\", \")}.`),\n fix: misnamed\n ? `Rename \"${misnamed}\" to \"${expected}\", or change runtime.name to the interpreter ` +\n \"that file is written for.\"\n : `Add \"${expected}\".`,\n });\n }\n return findings;\n}\n\n/**\n * ─── RULE 3: a dependency declared later ────────────────────────────────────────────────\n *\n * The import validator already refuses this, and refuses it with the right reasoning. What it\n * cannot do is say which LINE, because it is handed a schema and not a file. This rule finds\n * the same defect in the author's own parameters file and carries the location, and the report\n * keeps whichever of the two is more useful (see `mergeFindings`).\n */\nfunction lintDependsOnOrder(input: LintInput): AuthoringFinding[] {\n const reference = input.manifest?.parametersRef;\n if (typeof reference !== \"string\") return [];\n const source = input.files.get(reference);\n if (source === undefined) return [];\n let schema: unknown;\n try {\n schema = JSON.parse(source);\n } catch {\n return [];\n }\n if (!isRecord(schema) || !isRecord(schema.properties)) return [];\n const order = Object.keys(schema.properties);\n const findings: AuthoringFinding[] = [];\n for (const [name, property] of Object.entries(schema.properties)) {\n if (!isRecord(property)) continue;\n for (const dependency of dependencyNames(property.dependsOn)) {\n if (!order.includes(dependency)) continue;\n if (order.indexOf(dependency) <= order.indexOf(name)) continue;\n const path = `properties.${name}.dependsOn`;\n findings.push({\n severity: \"error\",\n rule: \"parameters/depends-on-declared-later\",\n file: reference,\n ...locationOf(source, path),\n message:\n `\"${name}\" depends on \"${dependency}\", which is declared after it. Parameters are ` +\n `shown in the order you declare them, so the form would ask for \"${name}\" before ` +\n `the value that scopes it.`,\n fix: `Move \"${dependency}\" above \"${name}\" in the properties object.`,\n subject: `parameters.${path}`,\n });\n }\n }\n return findings;\n}\n\n/**\n * ─── RULE 4: network with nothing to reach ──────────────────────────────────────────────\n *\n * `requiresNetwork: true` with no allowlist is refused at import. It is worth catching here\n * anyway, because the field an author reaches for is `requiresNetwork` and the field they have\n * to ALSO write is one they may not know exists.\n */\nfunction lintNetworkAllowlist(input: LintInput): AuthoringFinding[] {\n const manifest = input.manifest;\n if (!manifest || manifest.requiresNetwork !== true) return [];\n const allowlist = manifest.egressAllowlist;\n if (Array.isArray(allowlist) && allowlist.length > 0) return [];\n return [\n {\n severity: \"error\",\n rule: \"package/network-without-allowlist\",\n file: MANIFEST_FILE,\n ...(input.manifestSource ? locationOf(input.manifestSource, \"requiresNetwork\") : {}),\n message:\n `This package declares outbound network access but names no destinations. ${BRAND_SHORT_NAME} never ` +\n \"runs a network package without its allowlist in force, so there is nothing it could \" +\n \"be allowed to reach.\",\n fix:\n \"List the hosts the script actually contacts in `egressAllowlist` (e.g. \" +\n \"`api.example.com`), or set `requiresNetwork: false`.\",\n subject: \"egressAllowlist\",\n },\n ];\n}\n\n/**\n * ─── RULE 5: a permission for a provider the package does not declare ───────────────────\n *\n * Precise, not heuristic: a `requiredPermissions` entry naming a provider absent from\n * `providers` describes access the package could never exercise, and it is shown to whoever\n * approves the adoption as privilege they are being asked to grant.\n */\nfunction lintPermissionProviders(input: LintInput): AuthoringFinding[] {\n const manifest = input.manifest;\n if (!manifest || !Array.isArray(manifest.requiredPermissions)) return [];\n const declared = Array.isArray(manifest.providers)\n ? manifest.providers.filter((value): value is Provider => typeof value === \"string\")\n : [];\n if (declared.length === 0) return [];\n const findings: AuthoringFinding[] = [];\n manifest.requiredPermissions.forEach((permission, index) => {\n if (!isRecord(permission)) return;\n const provider = permission.provider;\n if (typeof provider !== \"string\" || declared.includes(provider as Provider)) return;\n findings.push({\n severity: \"error\",\n rule: \"package/permission-provider-undeclared\",\n file: MANIFEST_FILE,\n ...(input.manifestSource\n ? locationOf(input.manifestSource, `requiredPermissions.${index}.provider`)\n : {}),\n message:\n `This permission is for provider \"${provider}\", which is not in this package's ` +\n `providers (${declared.join(\", \")}). ${BRAND_SHORT_NAME} would ask an approver to grant access the ` +\n \"package has no connection to use.\",\n fix: `Add \"${provider}\" to providers, or remove this permission.`,\n });\n });\n return findings;\n}\n\n/**\n * ─── RULE 6: a permission nothing in the package looks like it uses ─────────────────────\n *\n * A HEURISTIC, and labelled as one in the message. It cannot be otherwise: the only way to\n * prove a permission is unexercised is to run every path of an arbitrary script.\n *\n * It is tuned to almost never fire falsely rather than to catch everything. The permission is\n * considered used if ANY of its tokens appears anywhere in any script: the whole ARM action\n * string, each path segment of it (`virtualMachines`, `restart`), and the singular form of the\n * resource noun. A script that restarts a VM mentions \"vm\" or \"restart\" or \"virtualMachines\"\n * somewhere; a permission left behind from a copied manifest usually mentions none of them.\n *\n * A warning, never an error, because the cost of being wrong is asymmetric: a false error\n * blocks a correct package, a false warning is one line the author reads and dismisses.\n */\nfunction lintUnusedPermissions(input: LintInput): AuthoringFinding[] {\n const manifest = input.manifest;\n if (!manifest || !Array.isArray(manifest.requiredPermissions)) return [];\n const haystack = scriptText(input).toLowerCase();\n if (haystack.length === 0) return [];\n const findings: AuthoringFinding[] = [];\n manifest.requiredPermissions.forEach((permission, index) => {\n if (!isRecord(permission) || !Array.isArray(permission.actions)) return;\n permission.actions.forEach((action, actionIndex) => {\n if (typeof action !== \"string\" || action.includes(\"*\")) return;\n if (permissionTokens(action).some((token) => haystack.includes(token))) return;\n findings.push({\n severity: \"warning\",\n rule: \"package/permission-possibly-unused\",\n file: MANIFEST_FILE,\n ...(input.manifestSource\n ? locationOf(\n input.manifestSource,\n `requiredPermissions.${index}.actions.${actionIndex}`,\n )\n : {}),\n message:\n `Nothing in this package's scripts mentions \"${action}\" or any part of it. Every ` +\n \"declared permission is privilege an approver is asked to grant, so a stale one \" +\n \"makes the package look more dangerous than it is. (Text search — if the script \" +\n \"builds the call dynamically, this is a false alarm.)\",\n fix: `Remove this permission if the package no longer needs it.`,\n });\n });\n });\n return findings;\n}\n\n/**\n * ─── RULE 7: an allowlisted host nothing contacts ───────────────────────────────────────\n *\n * The same argument as rule 6 and a far tighter search: hostnames appear literally in scripts.\n * An allowlist is read by an approver as \"what this package talks to\", so an entry nothing\n * talks to is a widened boundary bought for nothing.\n */\nfunction lintUnreferencedEgressHosts(input: LintInput): AuthoringFinding[] {\n const manifest = input.manifest;\n if (!manifest || !Array.isArray(manifest.egressAllowlist)) return [];\n const haystack = scriptText(input).toLowerCase();\n if (haystack.length === 0) return [];\n const findings: AuthoringFinding[] = [];\n manifest.egressAllowlist.forEach((destination, index) => {\n if (typeof destination !== \"string\") return;\n const host = destination.replace(/^\\*\\./, \"\").replace(/:\\d+$/, \"\").toLowerCase();\n if (host.length === 0 || haystack.includes(host)) return;\n findings.push({\n severity: \"warning\",\n rule: \"package/egress-host-unreferenced\",\n file: MANIFEST_FILE,\n ...(input.manifestSource\n ? locationOf(input.manifestSource, `egressAllowlist.${index}`)\n : {}),\n message:\n `No script in this package mentions \"${host}\". Whoever adopts this action reads the ` +\n \"allowlist as the list of things it talks to.\",\n fix: `Remove \"${destination}\" from egressAllowlist if nothing contacts it.`,\n });\n });\n return findings;\n}\n\n/**\n * ─── RULE 8: a phase that cannot report anything ────────────────────────────────────────\n *\n * `RUNVERIC_RESULT_FILE` is the only channel Opera reads. A phase whose scripts never mention it\n * has no way to say what happened, so the run ends at \"exited with code 0 without writing a\n * valid result.json\" — after printing output that made it look like it worked.\n *\n * DEFENCE IN DEPTH, NOT THE FIX. The scaffold's entrypoint is a wrapper that always writes a\n * result, and a pasted script lands in the BODY file beside it, so the default path cannot\n * produce a non-reporting action at all. This rule is for the author who edited the wrapper out\n * — and it must not be mistaken for the thing that makes pasting safe.\n *\n * ADVISORY, and that is the whole design of it. The detection is necessarily a heuristic: a\n * script may write the result through a path no static read can see — a helper it invokes, a\n * variable it assembles, a file another tool produces. So it is an ERROR by volume (an author\n * must not skim past a package that will report nothing) and advisory by effect (a deliberate\n * author publishes anyway). `--strict` still fails on it for a team that wants the gate.\n */\nfunction lintPhaseWritesNoResult(input: LintInput): AuthoringFinding[] {\n const manifest = input.manifest;\n if (!manifest) return [];\n const runtime = manifest.runtime;\n if (typeof runtime !== \"object\" || runtime === null || Array.isArray(runtime)) return [];\n const declaration = runtime as Record<string, unknown>;\n // An OCI package's image writes the result, and nothing about how is in this bundle.\n if (declaration.kind === \"oci\") return [];\n const name = declaration.name;\n if (typeof name !== \"string\" || !isInterpreter(name)) return [];\n const entryFile = PACKAGE_INTERPRETER_LAUNCH[name].entryFile;\n\n const findings: AuthoringFinding[] = [];\n for (const { field, phase } of ENTRYPOINT_PHASES) {\n const directory = manifest[field];\n if (typeof directory !== \"string\" || directory.length === 0) continue;\n const scripts = [...input.files].filter(\n ([path]) => path.startsWith(directory) && SCRIPT_EXTENSIONS.some((ext) => path.endsWith(ext)),\n );\n // Nothing to read is rule 2's finding, not this one. Two errors about one missing file is\n // how a report starts looking longer than the problem.\n if (scripts.length === 0) continue;\n // COMMENTS DO NOT COUNT, for the reason rules 6 and 7 strip them: every file the scaffold\n // writes explains the contract in its header, so a comment-inclusive search would find\n // `RUNVERIC_RESULT_FILE` in a package whose code never touches it — a rule that silently\n // never fires is a rule that is not there.\n if (scripts.some(([, source]) => codeOf(source).includes(RESULT_FILE_VARIABLE))) continue;\n findings.push({\n severity: \"error\",\n advisory: true,\n rule: \"package/phase-writes-no-result\",\n file: `${directory}${entryFile}`,\n message:\n `Nothing under \"${directory}\" writes ${RESULT_FILE_VARIABLE}, so this package's ` +\n `${phase} phase has no way to report what it did. ${BRAND_SHORT_NAME} reads that file and nothing ` +\n \"else: a package that exits 0 without writing one is a FAILED run, whatever it \" +\n \"printed. (Text search — if the result is written somewhere this cannot see, publish \" +\n \"anyway; this does not block you.)\",\n fix:\n `Write the result as the last thing \"${directory}${entryFile}\" does, on every path ` +\n `including the ones that fail — or let ${BRAND_SHORT_NAME}'s wrapper do it, which is what the ` +\n \"scaffolded entrypoint is for: put your work in the phase's body file and it reports \" +\n \"for you.\",\n // Keyed per phase so the run and rollback findings are separate facts, and so neither\n // can be merged away by a validator finding about a different thing.\n subject: `${field}.result`,\n });\n }\n return findings;\n}\n\nconst SCRIPT_EXTENSIONS = [\".ps1\", \".sh\", \".py\"] as const;\nconst RESULT_FILE_VARIABLE = \"RUNVERIC_RESULT_FILE\";\n\n/** The three fields that name a phase directory, and what each phase is called. */\nconst ENTRYPOINT_PHASES = [\n { field: \"entrypoint\", phase: \"run\" },\n { field: \"validateEntrypoint\", phase: \"validate\" },\n { field: \"rollbackEntrypoint\", phase: \"rollback\" },\n] as const;\n\n/**\n * Every executable file's CODE, concatenated — the corpus rules 6 and 7 search.\n *\n * WHOLE-LINE COMMENTS ARE STRIPPED, and that is load-bearing rather than tidy. These rules ask\n * \"does this package's code do anything with this privilege\", and a comment does nothing. The\n * scaffold's own header contains the phrase \"non-secret run metadata\", which was enough to make\n * `Microsoft.KeyVault/vaults/secrets/delete` look used in a package that never touches a vault\n * — a rule that silently never fires is a rule that is not there.\n *\n * Only whole-line comments, not trailing ones: a `#` mid-line could be inside a string, and\n * guessing wrong there would suppress a real finding. Conservative in the direction of silence.\n */\nfunction scriptText(input: LintInput): string {\n return [...input.files]\n .filter(([path]) => SCRIPT_EXTENSIONS.some((extension) => path.endsWith(extension)))\n .map(([, source]) => codeOf(source))\n .join(\"\\n\");\n}\n\n/** One file's code, with whole-line comments removed. See {@link scriptText} for why. */\nfunction codeOf(source: string): string {\n return source\n .split(/\\r?\\n/)\n .filter((line) => !line.trimStart().startsWith(\"#\"))\n .join(\"\\n\");\n}\n\n/**\n * The tokens that count as \"this permission is used\": the whole action, each meaningful path\n * segment of it, and the singular of each segment (`virtualMachines` → `virtualmachine`).\n *\n * The trailing segment of an ARM action is always the ACCESS VERB — `read`, `write`, `action`,\n * `delete` — and matching on those means matching on nothing: the word \"action\" appears in\n * every Opera package's own comments, so the rule would silently never fire. Dropping the verb\n * and requiring five characters leaves the tokens that actually identify a resource.\n */\nfunction permissionTokens(action: string): string[] {\n const lower = action.toLowerCase();\n const segments = lower\n .split(\"/\")\n .slice(0, -1)\n .filter((segment) => segment.length >= 5);\n const singulars = segments\n .filter((segment) => segment.endsWith(\"s\"))\n .map((segment) => segment.slice(0, -1));\n return [lower, ...segments, ...singulars];\n}\n\nfunction dependencyNames(value: unknown): string[] {\n if (Array.isArray(value)) return value.filter((item): item is string => typeof item === \"string\");\n if (isRecord(value)) {\n return Object.values(value).filter((item): item is string => typeof item === \"string\");\n }\n return [];\n}\n\n/** `{line, column}` when the path resolves, `{}` when it does not — never a guessed line. */\nfunction locationOf(source: string, path: string): { line?: number; column?: number } {\n const at = locate(source, path);\n return at ? { line: at.line, column: at.column } : {};\n}\n\nfunction isInterpreter(value: string): value is PackageInterpreter {\n return (PACKAGE_INTERPRETERS as readonly string[]).includes(value);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { parseDocument } from \"yaml\";\nimport type { PackageParametersUnresolvedReason } from \"@runveric/contracts\";\nimport { isSafeRelativePath } from \"./manifest-validator\";\nimport { MANIFEST_FILE } from \"./package-validation\";\n\n/**\n * ═══ WHERE A PACKAGE'S PARAMETERS LIVE ═════════════════════════════════════════════════\n *\n * `action.yaml` declares `parametersRef`, and that declaration is the ONLY answer to \"which file\n * holds this package's parameters\". The validator reads it, `check` reads it, the lint reads it,\n * and the publish path reads it.\n *\n * THE EDITOR USED TO KEEP A PRIVATE OPINION — a `PARAMETERS_FILE = \"parameters.json\"` constant in\n * the browser. It agreed with the manifest for exactly as long as every package was scaffolded,\n * because the scaffold writes that name into the manifest itself. Slice B let authors bring their\n * own package, and a manifest saying `parametersRef: parameters.schema.json` met an editor that\n * looked for `parameters.json`, found nothing, showed \"No parameters yet\" — and then silently\n * DISCARDED every parameter the author added, because its write mapped over the files replacing\n * only the one whose path matched and nothing matched.\n *\n * So this is the one resolver, and the browser gets its answer over the wire rather than growing\n * a manifest parser of its own. `apps/web` does not depend on this package and must not start:\n * a second parser would ship a YAML engine into every page AND could disagree with the one that\n * publishes, which is the same defect one layer down.\n *\n * ─── DELIBERATELY LENIENT ───────────────────────────────────────────────────────────────\n *\n * This does NOT require the manifest to VALIDATE. `validateManifest` fails on any bad field, and\n * an author halfway through fixing `riskLevel` would otherwise lose the Parameters tab and be\n * told to fix something unrelated to parameters. The same reasoning the lint already runs on:\n * \"the lint's whole value is to a package that does not validate yet\".\n *\n * What it will NOT do is resolve an UNSAFE path. `parametersRef` is author-controlled and this\n * answer becomes a write destination, so a path that escapes the package root is unresolvable and\n * says so — refused here rather than accepted and rejected later at the storage edge, which is\n * the difference between an editor that explains itself and one that eats keystrokes.\n */\n\n/**\n * A DISCRIMINATED result, so a resolved location carries its path and an unresolved one carries\n * its reason. The alternative — `{ path: string | null; reason: Reason | null }` — is two\n * nullable fields with an invariant nobody enforces, and every caller writes a non-null\n * assertion right after checking. `ActionPackageValidation` is discriminated for the same reason.\n */\nexport type ParametersFileLocation =\n | { resolved: true; path: string }\n | { resolved: false; reason: PackageParametersUnresolvedReason };\n\n/**\n * Where a package's parameters live, according to the package itself.\n *\n * Takes the manifest SOURCE rather than a file map so both callers can use it: the drafts\n * service holds files as text, and `check` holds the already-decoded manifest.\n */\nexport function resolveParametersFile(manifestSource: string | undefined): ParametersFileLocation {\n if (manifestSource === undefined) {\n return { resolved: false, reason: \"manifest_missing\" };\n }\n const manifest = readManifest(manifestSource);\n if (!manifest) return { resolved: false, reason: \"manifest_unparseable\" };\n const reference = manifest.parametersRef;\n if (typeof reference !== \"string\" || reference.length === 0) {\n return { resolved: false, reason: \"parameters_ref_missing\" };\n }\n // THE SAME PATH RULE the manifest validator applies to this field. Resolved here too because\n // this answer is written to, and a destination is a stronger claim than a declaration.\n if (!isSafeRelativePath(reference)) {\n return { resolved: false, reason: \"parameters_ref_unsafe\" };\n }\n return { resolved: true, path: reference };\n}\n\n/** Convenience for callers holding a whole package rather than one file's text. */\nexport function resolveParametersFileOf(\n files: ReadonlyMap<string, string>,\n): ParametersFileLocation {\n return resolveParametersFile(files.get(MANIFEST_FILE));\n}\n\n/**\n * The manifest as a plain record, WITHOUT requiring it to be valid — the one lenient read.\n *\n * It lived privately inside `check.ts`, which is where the leniency was first needed. A second\n * copy here would be a second YAML-reading path with its own idea of what \"unparseable\" means,\n * so `check` now calls this instead.\n */\nexport function readManifest(source: string): Record<string, unknown> | undefined {\n try {\n const document = parseDocument(source);\n if (document.errors.length > 0) return undefined;\n const value: unknown = document.toJS();\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n","import { lintActionPackage } from \"./authoring-lint\";\nimport type { AuthoringFinding } from \"./findings\";\nimport { findingFromValidation, mergeFindings } from \"./findings\";\nimport { readManifest } from \"./parameters-location\";\nimport type { ActionPackageValidation } from \"./package-validation\";\nimport { MANIFEST_FILE, validateActionPackage } from \"./package-validation\";\n\n/**\n * ─── `check`, THE WHOLE OF IT ───────────────────────────────────────────────────────────\n *\n * The validator says whether Opera would accept the package. The lint says whether the package\n * does what its author thinks it does. `check` is both, reported as one list an author works\n * down, and it is the SAME call behind `runveric check` and the Check button in the app.\n *\n * The two are kept separate underneath on purpose. `ok` is the validator's answer and only the\n * validator's: a lint warning must never be able to make a valid package look rejected, and a\n * lint error must never be able to make an invalid one look accepted. What `check` adds is the\n * part the validator structurally cannot give — a file, a line, and a fix.\n */\n\nexport interface CheckReport {\n /**\n * The verdict, and the products that come with it. Deliberately NOT re-exposed as a separate\n * `ok` boolean on this object: two ways to ask \"would Opera accept this\" is two things that\n * can disagree, and `ActionPackageValidation` already discriminates on `ok` so a caller that\n * narrows it also gets the manifest and the schema.\n */\n validation: ActionPackageValidation;\n findings: AuthoringFinding[];\n /** Findings that would block, and findings that are advice. Convenience for reporters. */\n errorCount: number;\n warningCount: number;\n /**\n * How many of `errorCount` are ADVISORY — reported at full volume, gating nothing. See\n * {@link AuthoringFinding.advisory}: a heuristic rule that blocked a correct package would\n * teach authors to bypass the lint, and take the certain rules with it.\n */\n advisoryCount: number;\n /**\n * True when the LINT found a blocking problem the import validator does not reject. Such a\n * package imports cleanly and misbehaves at run time — the `$Name?` shape — so it is called\n * out separately rather than folded into `ok`, which has to keep meaning exactly one thing.\n *\n * Advisory findings are excluded BY CONSTRUCTION, which is what \"does not block publishing\"\n * means in code rather than in a comment: this is the flag `publish` and the CLI read.\n */\n lintBlocked: boolean;\n}\n\nexport function checkActionPackage(files: ReadonlyMap<string, Buffer>): CheckReport {\n const validation = validateActionPackage(files);\n const text = new Map([...files].map(([path, contents]) => [path, decode(contents)]));\n const manifestSource = text.get(MANIFEST_FILE);\n\n const validatorFindings: AuthoringFinding[] = [];\n const parametersRef = validation.manifest?.parametersRef;\n for (const [problems, severity] of [\n [validation.errors, \"error\"],\n [validation.warnings, \"warning\"],\n ] as const) {\n for (const problem of problems) {\n // Which FILE a validator path is about, and the prefix that file does not carry. The\n // parameter validator reports `parameters.properties.x`; `parameters.` is its own name\n // for the document, not a key inside it.\n const inParameters = problem.path === \"parameters\" || problem.path.startsWith(\"parameters.\");\n const file = inParameters && parametersRef ? parametersRef : MANIFEST_FILE;\n const source = text.get(file);\n validatorFindings.push(\n findingFromValidation(problem, {\n severity,\n file,\n source: source ?? \"\",\n ...(inParameters ? { pathPrefix: \"parameters\" } : {}),\n }),\n );\n }\n }\n\n const lint = lintActionPackage({\n files: text,\n // The LENIENT read, shared with the parameters resolver. The lint's whole value is to a\n // package that does not validate yet, so it must not depend on validation having succeeded —\n // and one YAML-reading path means the two cannot disagree about what \"unparseable\" means.\n manifest: manifestSource ? readManifest(manifestSource) : undefined,\n manifestSource,\n });\n\n const findings = mergeFindings(validatorFindings, lint);\n const errors = findings.filter((finding) => finding.severity === \"error\");\n return {\n findings,\n validation,\n errorCount: errors.length,\n warningCount: findings.filter((finding) => finding.severity === \"warning\").length,\n advisoryCount: errors.filter((finding) => finding.advisory === true).length,\n lintBlocked:\n validation.ok &&\n lint.some((finding) => finding.severity === \"error\" && finding.advisory !== true),\n };\n}\n\nfunction decode(contents: Buffer): string {\n return contents.toString(\"utf8\");\n}\n","import type {\n DetectedParameterDto,\n DetectedParametersDto,\n UnrepresentableParameterDto,\n} from \"@runveric/contracts\";\nimport { BRAND_ARTICLE_CAPITALISED, BRAND_SHORT_NAME } from \"@runveric/contracts\";\n\n/**\n * ═══ READING A `param()` BLOCK, AND MAPPING IT ONTO OPERA'S MODEL ══════════════════════\n *\n * Two halves, and the split is the point.\n *\n * {@link POWERSHELL_PARAM_PROBE} is PowerShell source. It ASKS PowerShell what an author\n * declared, because PowerShell's own parser is exact where anything we wrote would be an\n * approximation of a grammar we do not own (docs/32 D1).\n *\n * {@link mapDeclaredParameters} is TypeScript. It decides what each declaration becomes in\n * Opera's model — which is a question about OPERA, not about PowerShell, and belongs where the\n * model lives.\n *\n * Neither half does I/O. Running the probe is the API's job (it owns the child process); this\n * package stays pure so the same mapping can be reached from the CLI, the server and a test\n * without any of them needing a subprocess to agree with the others.\n *\n * ─── PARSE, NEVER EXECUTE (D2, S7) ──────────────────────────────────────────────────────\n *\n * `[Parser]::ParseFile` builds an AST and runs nothing. `Get-Help`, dot-sourcing and\n * `Import-Module` all EXECUTE TOP-LEVEL CODE. For an untrusted customer script the difference\n * between those calls is the difference between reading it and running it BEFORE any governance\n * gate has been consulted — so the probe uses the parser and only the parser, and\n * `apps/api/test/parameter-detection.spec.ts` is the regression test that keeps it true: it\n * detects a fixture whose top-level code writes a file, and asserts the file is not there.\n *\n * `SafeGetValue()` is the other half of that promise: it evaluates CONSTANT expressions only —\n * a string, a number, `$true`, an array literal — and throws for anything that would need an\n * engine. So `[string] $Owner = (Get-AzContext).Name` yields no default rather than a call.\n */\n\n/** One parameter exactly as PowerShell reported it. The probe's JSON, typed. */\nexport interface DeclaredParameter {\n /** `$Environment` → `Environment`. */\n name: string;\n /** The .NET type PowerShell resolved the declaration to — `System.String`, `System.Int32`. */\n staticType: string;\n /** What the author wrote, whitespace-collapsed: `[ValidateSet('dev','prod')] [string]`. */\n declaredType: string;\n mandatory: boolean;\n /** `[Parameter(HelpMessage=…)]`, or null. */\n helpMessage: string | null;\n /** The `.PARAMETER <name>` comment help, or null. Read from the AST, never from Get-Help. */\n commentHelp: string | null;\n /** `[ValidateSet(...)]`'s members, or null when there is no such attribute. */\n validateSet: string[] | null;\n /** The declared default as a constant, or null when there is none or it is not constant. */\n defaultValue: string | number | boolean | null;\n sourceLine: number;\n sourceText: string;\n}\n\n/** The probe's whole answer. */\nexport interface DeclaredParameterBlock {\n /** PowerShell's parser errors. Non-empty means the file does not compile. */\n parseErrors: string[];\n /** False for a valid script with no `param()` block — a real state, not an error. */\n hasParamBlock: boolean;\n parameters: DeclaredParameter[];\n}\n\n/**\n * ─── THE PROBE ──────────────────────────────────────────────────────────────────────────\n *\n * Started as `pwsh -NoLogo -NoProfile -NonInteractive -File <this> <script>` and prints ONE\n * JSON object on stdout. It reads the script's path from `$args` rather than having it spliced\n * in, so a filename containing a quote is data here and can never become syntax.\n *\n * `-Depth 8` and `-Compress`, because the caller parses this and a human never reads it.\n *\n * WHY `$ErrorActionPreference = 'Stop'`: a probe that half-fails and prints half an object is\n * worse than one that fails. The caller sees a non-zero exit and reports the failure rather than\n * a partial parameter list the author would have to notice was short.\n */\nexport const POWERSHELL_PARAM_PROBE = `$ErrorActionPreference = 'Stop'\nSet-StrictMode -Version Latest\n\n# THE ONE CALL THAT READS THE AUTHOR'S FILE. It builds an abstract syntax tree and executes\n# nothing — not the top-level code, not a default value, not an attribute argument. Every other\n# way to learn a script's parameters (Get-Help, dot-sourcing, Import-Module) runs it first.\n$operaTokens = $null\n$operaParseErrors = $null\n$operaAst = [System.Management.Automation.Language.Parser]::ParseFile(\n $args[0], [ref] $operaTokens, [ref] $operaParseErrors)\n\n# Comment-based help, from the SAME AST. GetHelpContent walks the comment tokens the parser\n# already produced; it does not invoke Get-Help, which would load and run the script.\n$operaHelp = $null\ntry { $operaHelp = $operaAst.GetHelpContent() } catch { $operaHelp = $null }\n\nfunction Get-OperaConstant($operaNode) {\n if ($null -eq $operaNode) { return $null }\n # CONSTANTS ONLY. SafeGetValue throws for anything that would need the engine, which is\n # exactly the line this probe must not cross — an author's \\`= (Get-Date)\\` yields no default\n # rather than a call.\n try { return $operaNode.SafeGetValue() } catch { return $null }\n}\n\n$operaResult = [ordered]@{\n parseErrors = @($operaParseErrors | ForEach-Object { $_.Message })\n hasParamBlock = ($null -ne $operaAst.ParamBlock)\n parameters = @()\n}\n\nif ($null -ne $operaAst.ParamBlock) {\n $operaResult.parameters = @($operaAst.ParamBlock.Parameters | ForEach-Object {\n $operaParam = $_\n $operaName = $operaParam.Name.VariablePath.UserPath\n $operaMandatory = $false\n $operaHelpMessage = $null\n $operaValidateSet = $null\n foreach ($operaAttribute in $operaParam.Attributes) {\n if ($operaAttribute -isnot [System.Management.Automation.Language.AttributeAst]) { continue }\n switch ($operaAttribute.TypeName.Name) {\n 'Parameter' {\n foreach ($operaNamed in $operaAttribute.NamedArguments) {\n if ($operaNamed.ArgumentName -eq 'Mandatory') {\n # \\`[Parameter(Mandatory)]\\` omits the expression and means $true;\n # \\`Mandatory = $true\\` carries it. Both are the same declaration.\n $operaMandatory = if ($operaNamed.ExpressionOmitted) { $true }\n else { [bool] (Get-OperaConstant $operaNamed.Argument) }\n }\n if ($operaNamed.ArgumentName -eq 'HelpMessage') {\n $operaHelpMessage = Get-OperaConstant $operaNamed.Argument\n }\n }\n }\n 'ValidateSet' {\n $operaValidateSet = @($operaAttribute.PositionalArguments |\n ForEach-Object { Get-OperaConstant $_ })\n }\n }\n }\n # GetHelpContent keys its parameter map by UPPERCASE name, and PowerShell parameter\n # names are case-insensitive, so the lookup is too.\n $operaComment = $null\n $operaKey = $operaName.ToUpperInvariant()\n if ($null -ne $operaHelp -and $operaHelp.Parameters.ContainsKey($operaKey)) {\n $operaComment = $operaHelp.Parameters[$operaKey]\n }\n # THE TYPE CONSTRAINT ALONE — \\`[string]\\`, \\`[int]\\`, \\`[string[]]\\` — and not every\n # attribute. It is the author's own text for the one thing a refusal has to name, and\n # \\`[Parameter(Mandatory = $true, HelpMessage = '…')] [string]\\` names it inside a\n # sentence nobody can read. Empty for an untyped \\`param($X)\\`, which maps to\n # System.Object and is proposed as text with the assumption SAID — see MAPPED_TYPES.\n $operaDeclared = (($operaParam.Attributes |\n Where-Object { $_ -is [System.Management.Automation.Language.TypeConstraintAst] } |\n ForEach-Object { $_.Extent.Text }) -join ' ')\n [ordered]@{\n name = $operaName\n staticType = $operaParam.StaticType.FullName\n declaredType = ($operaDeclared -replace '\\\\s+', ' ').Trim()\n mandatory = $operaMandatory\n helpMessage = $operaHelpMessage\n commentHelp = $operaComment\n validateSet = $operaValidateSet\n defaultValue = Get-OperaConstant $operaParam.DefaultValue\n sourceLine = $operaParam.Extent.StartLineNumber\n sourceText = (($operaParam.Extent.Text -replace '\\\\s+', ' ').Trim())\n }\n })\n}\n\n$operaResult | ConvertTo-Json -Depth 8 -Compress\n`;\n\n/**\n * ─── OPERA'S MODEL IS NARROWER THAN POWERSHELL'S TYPE SYSTEM ────────────────────────────\n *\n * `ParameterProperty.type` is `\"string\" | \"boolean\"` and `ParameterControl` is\n * `select | text | switch | info`. Every PowerShell type has to land in that, be proposed with\n * the difference NAMED, or be refused. Three outcomes, and the table below is the whole rule.\n *\n * Keyed by the .NET type PowerShell resolved, not by the text the author wrote, because\n * `[string]`, `[String]` and `[System.String]` are one declaration written three ways.\n */\ntype Mapping =\n | { kind: \"exact\"; type: \"string\" | \"boolean\" }\n /** Carried as text, with the widening SAID in the row. See {@link WIDENED_NOTE}. */\n | { kind: \"widened\" }\n /** No type was declared at all. Text is an ASSUMPTION, and it is said. See {@link ASSUMED_NOTE}. */\n | { kind: \"assumed\" };\n\nconst MAPPED_TYPES: Record<string, Mapping> = {\n \"System.String\": { kind: \"exact\", type: \"string\" },\n \"System.Boolean\": { kind: \"exact\", type: \"boolean\" },\n // `[switch]` is a boolean an operator answers with a switch. PowerShell distinguishes the two\n // at the call site; an operator answering a run form does not, and should not have to.\n \"System.Management.Automation.SwitchParameter\": { kind: \"exact\", type: \"boolean\" },\n // ─── AN UNTYPED `param($X)` IS PROPOSED, NOT REFUSED ─────────────────────────────────\n //\n // PowerShell resolves it to System.Object, which does accept a hashtable as readily as a word\n // — so refusing it is the defensible reading, and it was the first one shipped. It is the\n // wrong trade in practice. `param($ResourceGroupName)` is ordinary style in real operational\n // scripts, and refusing it means the headline feature reads NOTHING from a large share of the\n // scripts it exists for, while the author's alternative is to type every parameter by hand.\n //\n // The asymmetry decides it. Proposing an untyped parameter that was meant as text — nearly\n // always — is exactly right. Proposing one that was meant as a hashtable costs a single click\n // in a review step that exists to catch precisely that. Refusing costs every author of the\n // common case the whole feature. Detection PROPOSES and the author DISPOSES (D5); refusing to\n // propose is the one thing that takes the choice away.\n \"System.Object\": { kind: \"assumed\" },\n \"System.Int32\": { kind: \"widened\" },\n \"System.Int64\": { kind: \"widened\" },\n \"System.Decimal\": { kind: \"widened\" },\n \"System.Double\": { kind: \"widened\" },\n \"System.DateTime\": { kind: \"widened\" },\n};\n\n/**\n * WHY A NUMBER OR A DATE IS PROPOSED AS TEXT, said in the row the author reviews.\n *\n * This is safe ONLY because the wrapper binds through the author's OWN `param()` block, so\n * their `[int]` cast is what validates the operator's answer — Opera re-implements nothing and\n * a value that is not a number fails at the boundary the author already wrote. It does NOT\n * generalise: a `[string[]]` has no cast that turns a text box into an array, which is why it is\n * refused below rather than widened.\n */\n/**\n * WHY AN UNTYPED PARAMETER IS PROPOSED AS TEXT, said in the row the author reviews.\n *\n * DELIBERATELY NOT {@link WIDENED_NOTE}. That sentence promises \"your own cast still validates\n * what an operator types\", which is TRUE for `[int]` and FALSE here — an untyped parameter has\n * no cast, so nothing checks the answer on the way in. Reusing it would be the product claiming\n * a guarantee it does not have, in the one sentence an author reads before accepting.\n */\nconst ASSUMED_NOTE =\n `Declared without a type, so ${BRAND_SHORT_NAME} proposes a text box. Nothing checks the answer on the way ` +\n \"in — add [string] to say that is what you meant, or a stronger type if it is not.\";\n\nconst WIDENED_NOTE =\n `${BRAND_SHORT_NAME} parameters are text or true/false, so this is proposed as a text box. Your own cast ` +\n \"still validates what an operator types.\";\n\n/**\n * WHY A DECLARATION IS REFUSED, and what the author can do instead.\n *\n * ONE SENTENCE FOR EVERY REFUSED TYPE, and that is now the whole rule. It used to be a per-type\n * table, whose only entry explained an untyped `param($X)` — which is no longer refused at all\n * (see MAPPED_TYPES). An empty lookup behind a function that always fell through to this string\n * is a mechanism pretending to make a decision, so it is gone; the remaining refusals —\n * `[string[]]`, `[hashtable]`, `[pscredential]` — genuinely share this reason. Bring the table\n * back when a type needs a DIFFERENT fix, not before.\n *\n * IT NAMES NEITHER THE PARAMETER NOR ITS TYPE. Both are separate fields on\n * {@link UnrepresentableParameterDto} and the review row already shows them, so repeating them\n * here reads as the product saying the same thing twice. No markdown either: this goes into a\n * DOM node, where a backtick meant as code renders as a backtick.\n */\nconst REFUSAL_REASON =\n `${BRAND_ARTICLE_CAPITALISED} ${BRAND_SHORT_NAME} parameter is text or true/false. A text box pretending to be this type would ` +\n \"produce a run that fails on something the operator was never warned about, so it is not \" +\n \"proposed — read this one inside your script instead.\";\n\nexport interface MappedParameters {\n parameters: DetectedParameterDto[];\n unrepresentable: UnrepresentableParameterDto[];\n}\n\n/** What detection can say about a PowerShell file. The interpreter question is decided above. */\nexport type PowerShellDetection = Omit<DetectedParametersDto, \"unavailableReason\">;\n\n/**\n * ─── THE WHOLE POWERSHELL ANSWER, FROM ONE PARSE ────────────────────────────────────────\n *\n * A FILE THAT DOES NOT COMPILE YIELDS NO PROPOSAL. PowerShell's parser recovers from an error\n * and still hands back whatever param block it managed to read — for `param([string]$N` with no\n * closing parenthesis it reports `$N` quite happily. Proposing from that would build a run form\n * out of a script that cannot run at all, and the author would meet the syntax error one screen\n * later with six parameters already accepted. So the errors are reported instead, as a FAILURE:\n * the draft is still creatable, and Check names the same error against the same file.\n */\nexport function powerShellDetection(\n block: DeclaredParameterBlock,\n fromFile: string,\n): PowerShellDetection {\n if (block.parseErrors.length > 0) {\n return {\n source: \"none\",\n fromFile,\n parameters: [],\n unrepresentable: [],\n failure:\n `\\`${fromFile}\\` is not valid PowerShell, so its parameters cannot be read: ` +\n `${block.parseErrors[0]} Fix it and detect again — Check reports the same error.`,\n };\n }\n return {\n // \"powershell_param\" EVEN WHEN THE LIST IS EMPTY. A valid script with no param() block was\n // read successfully and declares nothing, which is a different answer from \"this interpreter\n // has nothing to read\" — and the two must not collapse, because only one of them is worth\n // telling the author to go and fix.\n source: \"powershell_param\",\n fromFile,\n ...mapDeclaredParameters(block),\n failure: null,\n };\n}\n\n/**\n * The probe's stdout as a {@link DeclaredParameterBlock}, or null when it is not one.\n *\n * VALIDATED FIELD BY FIELD rather than cast. This JSON is produced by a child process parsing an\n * untrusted file; a cast would let a malformed shape reach the mapper as `undefined.length`\n * three layers down, where the failure names neither the file nor the child.\n */\nexport function parseProbeOutput(stdout: string): DeclaredParameterBlock | null {\n let value: unknown;\n try {\n value = JSON.parse(stdout);\n } catch {\n return null;\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n const record = value as Record<string, unknown>;\n if (typeof record.hasParamBlock !== \"boolean\") return null;\n if (!Array.isArray(record.parseErrors) || !Array.isArray(record.parameters)) return null;\n const parameters: DeclaredParameter[] = [];\n for (const entry of record.parameters) {\n if (typeof entry !== \"object\" || entry === null) return null;\n const parameter = entry as Record<string, unknown>;\n if (typeof parameter.name !== \"string\" || typeof parameter.staticType !== \"string\") return null;\n if (typeof parameter.sourceLine !== \"number\") return null;\n parameters.push({\n name: parameter.name,\n staticType: parameter.staticType,\n declaredType: typeof parameter.declaredType === \"string\" ? parameter.declaredType : \"\",\n mandatory: parameter.mandatory === true,\n helpMessage: typeof parameter.helpMessage === \"string\" ? parameter.helpMessage : null,\n commentHelp: typeof parameter.commentHelp === \"string\" ? parameter.commentHelp : null,\n validateSet: Array.isArray(parameter.validateSet)\n ? parameter.validateSet.filter((item): item is string => typeof item === \"string\")\n : null,\n defaultValue: constantOf(parameter.defaultValue),\n sourceLine: parameter.sourceLine,\n sourceText: typeof parameter.sourceText === \"string\" ? parameter.sourceText : \"\",\n });\n }\n return {\n parseErrors: record.parseErrors.filter((item): item is string => typeof item === \"string\"),\n hasParamBlock: record.hasParamBlock,\n parameters,\n };\n}\n\n/** A JSON scalar, or null for anything else — an array or object default is not one. */\nfunction constantOf(value: unknown): string | number | boolean | null {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n return null;\n}\n\n/**\n * The declarations, mapped — IN THE ORDER THE AUTHOR WROTE THEM.\n *\n * The sequence an author declared is the sequence operators are asked, carried through\n * the order key (charter §4.2). Nothing here sorts, and nothing may: a jsonb column already\n * destroys object key order once, and re-ordering here would destroy it before storage ever\n * had the chance.\n */\nexport function mapDeclaredParameters(block: DeclaredParameterBlock): MappedParameters {\n const parameters: DetectedParameterDto[] = [];\n const unrepresentable: UnrepresentableParameterDto[] = [];\n\n for (const declared of block.parameters) {\n const mapping = MAPPED_TYPES[declared.staticType];\n if (!mapping) {\n unrepresentable.push({\n name: declared.name,\n declaredType: declared.declaredType || declared.staticType,\n reason: REFUSAL_REASON,\n sourceLine: declared.sourceLine,\n sourceText: declared.sourceText,\n });\n continue;\n }\n\n const type = mapping.kind === \"exact\" ? mapping.type : \"string\";\n // A `[ValidateSet]` on a boolean is legal PowerShell and meaningless as a dropdown — the\n // switch already offers both values. Only a string's set becomes choices.\n const enumValues =\n type === \"string\" && declared.validateSet ? [...declared.validateSet] : [];\n parameters.push({\n name: declared.name,\n // The author's own word. See DetectedParameterDto.title for why nothing prettifies it.\n title: declared.name,\n declaredType: declared.declaredType || declared.staticType,\n type,\n control: type === \"boolean\" ? \"switch\" : enumValues.length > 0 ? \"select\" : \"text\",\n required: declared.mandatory,\n enumValues,\n defaultValue: defaultOf(declared, type),\n // HelpMessage FIRST, comment help second, and never both: they are two ways of saying the\n // same thing and an author who wrote both meant the one attached to the parameter.\n description: (declared.helpMessage ?? declared.commentHelp ?? \"\").trim(),\n note:\n mapping.kind === \"widened\"\n ? WIDENED_NOTE\n : mapping.kind === \"assumed\"\n ? ASSUMED_NOTE\n : null,\n sourceLine: declared.sourceLine,\n sourceText: declared.sourceText,\n });\n }\n\n return { parameters, unrepresentable };\n}\n\n/**\n * The declared default, as Opera would store it.\n *\n * A DEFAULT THAT IS NOT ONE OF THE CHOICES IS DROPPED, because the parameter editor refuses that\n * combination and a proposal the author cannot accept is worse than no proposal. It happens for\n * real: `[ValidateSet('dev','prod')] [string] $Env = ''`.\n */\nfunction defaultOf(\n declared: DeclaredParameter,\n type: \"string\" | \"boolean\",\n): string | boolean | null {\n const value = declared.defaultValue;\n if (value === null) return null;\n if (type === \"boolean\") return typeof value === \"boolean\" ? value : null;\n // A widened `[int] $Retry = 3` stores \"3\": the schema's type is string, and a number in a\n // string field is a schema the validator refuses at publish.\n const text = String(value);\n if (declared.validateSet && !declared.validateSet.includes(text)) return null;\n return text;\n}\n","import type { PackageInterpreter } from \"@runveric/contracts\";\n// The scaffold EMITS these two identifiers into an author's starter package — a manifest\n// the server will validate and result JSON the server will accept — so a copy here is a\n// copy that ships to a customer's laptop and is only caught the first time they publish.\nimport {\n ACTION_MANIFEST_API_VERSION,\n BRAND_ARTICLE,\n BRAND_SHORT_NAME,\n PACKAGE_RESULT_PROTOCOL_VERSION,\n PACKAGE_RUNNER_CONNECTOR_KEY,\n} from \"@runveric/contracts\";\nimport { PACKAGE_INTERPRETER_LAUNCH } from \"./interpreter-launch\";\n// The manifest's own filename, from the module that enforces it. Two spellings of \"action.yaml\"\n// is two things that can drift, and the validator's is the one that decides.\nimport { MANIFEST_FILE } from \"./package-validation\";\n\n/**\n * ─── WHAT `runveric init` WRITES ────────────────────────────────────────────────────\n *\n * A WORKING action, not a skeleton with TODOs. It passes `check` and it passes `test` the\n * moment it exists, before the author edits a line — because the first thing an author needs to\n * know is that the loop works, and a scaffold that fails on its first run teaches them the\n * opposite about the platform rather than about their code.\n *\n * PRESCRIPTIVE, DELIBERATELY. Every choice this scaffold offers is a choice an author can get\n * wrong, and the research is unambiguous that a fixed shape (Terraform's registry) beats a\n * flexible one (Backstage's \"where do I put everything\"). So `init` asks for three things — the\n * id, a display name, an interpreter — and decides the other twenty-two:\n *\n * riskLevel: high the safe default. An author who knows better lowers it deliberately.\n * rollback: false declaring a rollback you have not written is worse than none.\n * requiresNetwork: false / secrets: [] deny by default; both are privilege an approver\n * has to grant, and both are one line to add when actually needed.\n *\n * `validate/` and `rollback/` ship COMMENTED OUT rather than documented. Showing the shape\n * costs two files and removes the step where the author goes looking for a reference; the\n * manifest lines that enable them sit next to the ones that do not, so enabling one is\n * uncommenting rather than authoring.\n *\n * ─── TWO FILES IN `run/`, AND WHY ───────────────────────────────────────────────────────\n *\n * `run/main.*` is OPERA'S WRAPPER and `run/body.*` is the AUTHOR'S SCRIPT. The wrapper reads\n * the parameters file, starts the body, and writes `RUNVERIC_RESULT_FILE`; the body is whatever\n * the author wants to run.\n *\n * It used to be one file, and that cost a founder their first action: pasting a script over the\n * entrypoint kept the work and deleted the result contract, so the run printed its output and\n * then failed with \"exited with code 0 without writing a valid result.json\". The runtime is\n * right to refuse — a package that reports nothing has not reported success, and every check,\n * output and rollbackCapture in the product depends on that strictness. What was wrong was an\n * authoring path that produced scripts violating it.\n *\n * TWO FILES RATHER THAN AN EDIT-BETWEEN-THESE-MARKERS REGION, deliberately. A marked region is\n * a convention a paste can destroy — markers included — which is the same class of failure as\n * the one being fixed. A file boundary is not a convention; it is a boundary. And the ownership\n * is visible without reading anything: one file is yours, one is the contract.\n */\n\nexport interface ScaffoldInput {\n /** `publisher/name`, the manifest id. */\n id: string;\n /** What an operator sees in the catalog. */\n name: string;\n interpreter: PackageInterpreter;\n /** Written into `author` and the LICENSE. */\n author: string;\n /** Defaults to the current year; injected so the scaffold is deterministic under test. */\n year: number;\n /**\n * The author's own script, when they pasted one. It becomes `run/body.*` and NOTHING ELSE —\n * the wrapper that carries the result contract is byte-identical either way, which is the\n * property `authoring.e2e` asserts and the reason a pasted `echo \"hello World\"` is a working\n * action rather than a run that fails on a protocol detail nobody told the author about.\n */\n body?: string;\n}\n\n/** Package-relative path → file contents. Exactly what `init` writes to disk. */\nexport function scaffoldActionPackage(input: ScaffoldInput): Map<string, string> {\n const { entryFile, bodyFile } = PACKAGE_INTERPRETER_LAUNCH[input.interpreter];\n const files = new Map<string, string>();\n files.set(MANIFEST_FILE, manifest(input, true));\n files.set(PARAMETERS_FILE, parameters());\n // `run/body.*` is ONE CASE of the general wrapper, not a second code path beside it. The\n // scaffold's body happens to sit next to the wrapper; an imported script sits wherever its\n // author put it; the wrapper resolves both the same way, from the package root.\n files.set(`run/${entryFile}`, wrapperScript(input.interpreter, authoredBodyPath(input.interpreter)));\n files.set(`run/${bodyFile}`, input.body ?? BODY_SCRIPT[input.interpreter]);\n files.set(`validate/${entryFile}`, commented(VALIDATE_SCRIPT[input.interpreter]));\n files.set(`rollback/${entryFile}`, commented(ROLLBACK_SCRIPT[input.interpreter]));\n files.set(\"README.md\", readme(input));\n files.set(\"LICENSE\", license(input));\n files.set(\".gitignore\", GITIGNORE);\n return files;\n}\n\n/** `run/body.sh` — the path a paste writes, as a sentence the app and the CLI can both print. */\nexport function authoredBodyPath(interpreter: PackageInterpreter): string {\n return `run/${PACKAGE_INTERPRETER_LAUNCH[interpreter].bodyFile}`;\n}\n\n/**\n * ─── WHICH FILE THIS PACKAGE ACTUALLY RUNS ──────────────────────────────────────────────\n *\n * The wrapper is the one thing that decides, because it is what the runner starts and it is what\n * starts the body. So this reads the wrapper's own declaration back rather than a second record\n * of it: a stored copy would go stale the moment somebody edited `run/main.*`, and the runner\n * would obey the file while every other surface obeyed the copy.\n *\n * It matters for exactly one thing, and that thing is worth the marker: RE-DETECTING parameters\n * has to read the file the wrapper will BIND against. Reading a `param()` block from any other\n * file would propose a form whose answers are delivered nowhere — the silent-discard shape this\n * slice exists to remove, reintroduced by the feature meant to remove it.\n *\n * NULL when the marker is absent, which is what an edited or pre-Slice-C wrapper looks like.\n * Callers REFUSE on null rather than guessing; a guess here is the defect above.\n */\nexport function authoredEntrypointOf(\n files: ReadonlyMap<string, string>,\n interpreter: PackageInterpreter,\n): string | null {\n const wrapper = files.get(`run/${PACKAGE_INTERPRETER_LAUNCH[interpreter].entryFile}`);\n if (wrapper === undefined) return null;\n const marker = `# ${ENTRYPOINT_MARKER}`;\n for (const line of wrapper.split(\"\\n\")) {\n const trimmed = line.trimEnd();\n if (!trimmed.endsWith(marker)) continue;\n return LITERAL_READERS[interpreter](trimmed.slice(0, -marker.length));\n }\n return null;\n}\n\n/**\n * The comment that makes the wrapper's body path findable. A marker rather than a line number,\n * because a line number is a promise about a file somebody may reformat.\n */\nconst ENTRYPOINT_MARKER = \"opera:entrypoint\";\n\n/**\n * ═══ WHAT OPERA ADDS TO AN IMPORTED SCRIPT ═════════════════════════════════════════════\n *\n * An author arrives with files that already exist. Opera writes the three things a package\n * needs and their script does not have — a manifest, a parameter schema, and a wrapper pointed\n * AT THEIR ENTRYPOINT — and touches nothing else. Their files are stored at the paths they\n * arrived with, byte for byte (docs/32 D3).\n *\n * TWO CLASSES OF GENERATED PATH, and the difference matters:\n *\n * RESERVED — `action.yaml`, `parameters.json`, `run/<entryFile>`. These are Opera's, they\n * carry the contract, and an upload that already occupies one is a COLLISION: a refusal\n * naming the file, never an overwrite. Silently clobbering a file somebody just handed us\n * is the worst outcome available.\n *\n * GAP-FILLED — `README.md` and `LICENSE`. The validator requires both\n * ({@link REQUIRED_PACKAGE_FILES}), so a draft without them cannot pass Check and cannot\n * trial-run. But a real script folder very often HAS a README, and refusing an import\n * because the author brought one would be absurd. So Opera writes these only when they are\n * absent, and the author's own always wins.\n *\n * An upload carrying its own `action.yaml` never reaches here. That is already an Opera package\n * — exported, cloned from a colleague, or produced by the CLI — and Opera generates NOTHING for\n * one: overwriting an author's manifest would destroy the riskLevel, requiredPermissions and\n * egress declarations that took them the longest to get right.\n */\nexport interface ImportInput {\n /** `publisher/name`, the manifest id. */\n id: string;\n /** What an operator sees in the catalog. */\n name: string;\n author: string;\n year: number;\n /**\n * The interpreter, ALREADY DECIDED by the entrypoint's extension (docs/32 D4). Passed rather\n * than derived here so there is exactly one place that maps an extension to an interpreter,\n * and it is the one the import plan showed the author.\n */\n interpreter: PackageInterpreter;\n /** Which of the author's files runs, package-relative. Never moved, never renamed. */\n entrypoint: string;\n /** Every path the upload carries — read to detect collisions and gaps, never modified. */\n uploadedPaths: readonly string[];\n}\n\nexport interface GeneratedImport {\n /** Path → contents Opera ADDS. Gap-fillers the author already provided are absent. */\n files: Map<string, string>;\n /** Reserved paths the upload already occupies. Non-empty means the import is REFUSED. */\n collisions: string[];\n}\n\nexport function generateImportedPackage(input: ImportInput): GeneratedImport {\n const { entryFile } = PACKAGE_INTERPRETER_LAUNCH[input.interpreter];\n const uploaded = new Set(input.uploadedPaths);\n const scaffoldInput: ScaffoldInput = {\n id: input.id,\n name: input.name,\n interpreter: input.interpreter,\n author: input.author,\n year: input.year,\n };\n\n const reserved = new Map<string, string>([\n [MANIFEST_FILE, manifest(scaffoldInput, false)],\n [PARAMETERS_FILE, parameters()],\n // THE WRAPPER, POINTED AT THEIR FILE. The same function the scaffold calls, with a different\n // path — one code path, so a change to the result contract reaches both at once.\n [`run/${entryFile}`, wrapperScript(input.interpreter, input.entrypoint)],\n ]);\n const collisions = [...reserved.keys()].filter((path) => uploaded.has(path));\n if (collisions.length > 0) return { files: new Map(), collisions };\n\n const files = new Map(reserved);\n if (!uploaded.has(\"README.md\")) files.set(\"README.md\", importReadme(input));\n if (!uploaded.has(\"LICENSE\")) files.set(\"LICENSE\", license(scaffoldInput));\n return { files, collisions: [] };\n}\n\n/** The paths Opera reserves for an imported package — the collision set, named once. */\nexport function reservedImportPaths(interpreter: PackageInterpreter): string[] {\n return [MANIFEST_FILE, PARAMETERS_FILE, `run/${PACKAGE_INTERPRETER_LAUNCH[interpreter].entryFile}`];\n}\n\n/** Named once and interpolated into the manifest's own `parametersRef`, so the two agree. */\nconst PARAMETERS_FILE = \"parameters.json\";\n\n/**\n * `phaseFilesPresent` is what the scaffold ships and an import does not: the commented-out\n * `validate/` and `rollback/` files. The manifest tells the author how to enable a phase, and\n * \"uncomment that file\" is only true when there is a file to uncomment — an import gets \"add\"\n * instead. A comment that names a file the package does not contain is the kind of small lie\n * that teaches an author to stop reading the comments.\n */\nfunction manifest(input: ScaffoldInput, phaseFilesPresent: boolean): string {\n const entryFile = PACKAGE_INTERPRETER_LAUNCH[input.interpreter].entryFile;\n const version = INTERPRETER_VERSION[input.interpreter];\n const enable = phaseFilesPresent ? \"uncomment\" : \"add\";\n return `# The action's contract. Every field here is read by ${BRAND_SHORT_NAME}; nothing is decorative.\n# \\`runveric check\\` validates this file with the SAME validator the server uses, so a\n# manifest that passes here is a manifest that imports.\napiVersion: ${ACTION_MANIFEST_API_VERSION}\n\n# ── Identity ──────────────────────────────────────────────────────────────────\nid: ${input.id}\nname: ${yamlString(input.name)}\nauthor: ${yamlString(input.author)}\nversion: 0.1.0\nsummary: ${yamlString(`${input.name} — describe in one line what an operator gets.`)}\ncategory: compute\nproviders:\n - azure\nconnectorKey: ${PACKAGE_RUNNER_CONNECTOR_KEY}\n\n# ── How it runs ───────────────────────────────────────────────────────────────\nruntime:\n kind: interpreter\n name: ${input.interpreter}\n version: \"${version}\"\nexecutionTimeout: 5m\nparametersRef: ${PARAMETERS_FILE}\nentrypoint: run/\n\n# ── Phases ────────────────────────────────────────────────────────────────────\n# ${BRAND_SHORT_NAME} runs \\`validate\\` before \\`run\\` when you declare it, and \\`rollback\\` when a run has\n# to be undone. Both are OPTIONAL and both start commented out, because declaring a phase\n# you have not written is worse than not having one.\n#\n# To enable the pre-flight: uncomment the line below and ${enable} validate/${entryFile}.\n# validateEntrypoint: validate/\n#\n# To enable rollback: set \\`rollback: true\\`, uncomment the entrypoint, ${enable}\n# rollback/${entryFile}, and set capabilities.rollback to true — all four, or check refuses.\nrollback: false\n# rollbackEntrypoint: rollback/\n\n# ── What it is allowed to do ──────────────────────────────────────────────────\n# high is the SAFE default. Lower it when you know the action is safe, not before.\nriskLevel: high\n# Every entry is privilege somebody has to approve. Declare the least that works.\nrequiredPermissions: []\ncapabilities:\n dryRun: true\n idempotent: true\n rollback: false\n# Deny by default. Set requiresNetwork: true only with a non-empty egressAllowlist —\n# ${BRAND_SHORT_NAME} never runs a network package without its allowlist in force.\nrequiresNetwork: false\nsecrets: []\n\n# ── Publishing ────────────────────────────────────────────────────────────────\nlicense: MIT\nminRunvericVersion: 1.0.0\n`;\n}\n\n/**\n * ORDER IS THE CONTRACT. Opera asks an operator for these in the order they are written here,\n * and stamps that order into the order key at import so a jsonb column cannot lose it.\n *\n * The order key is NOT written here, deliberately: the importer writes it, and a scaffold that\n * pre-writes it would teach the author it is a second place to choose an order. It is not.\n * The parameter vocabulary is also CLOSED, so there is no comment key to explain any of this\n * inside the file — that is what the README is for.\n */\nfunction parameters(): string {\n return `{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"note\": {\n \"type\": \"string\",\n \"title\": \"Note\",\n \"description\": \"Shown back in the run output. Replace this with a parameter your action actually needs.\",\n \"control\": \"text\",\n \"default\": \"hello from a new ${BRAND_SHORT_NAME} action\"\n }\n },\n \"required\": []\n}\n`;\n}\n\nconst INTERPRETER_VERSION: Record<PackageInterpreter, string> = {\n powershell: \"7.4\",\n bash: \"5.2\",\n python: \"3.11\",\n};\n\n/** `#` for all three — PowerShell, bash and Python share the line-comment character. */\nfunction commented(source: string): string {\n return source\n .split(\"\\n\")\n .map((line) => (line.length === 0 ? \"#\" : `# ${line}`))\n .join(\"\\n\");\n}\n\n/**\n * THE HEADER EVERY WRAPPER CARRIES. Said in the file rather than only in the README, because\n * the author who is about to paste over something is looking at the file, not at the docs.\n */\nfunction wrapperHeader(interpreter: PackageInterpreter, sigil: string, bodyPath: string): string {\n const { entryFile } = PACKAGE_INTERPRETER_LAUNCH[interpreter];\n return `# ─────────────────────────────────────────────────────────────────────────────────────────\n# OPERA'S WRAPPER. This file is the CONTRACT; ${bodyPath} is YOURS.\n#\n# ${BRAND_SHORT_NAME} reads exactly one thing from a package: the JSON at ${sigil}RUNVERIC_RESULT_FILE. A script\n# that exits 0 without writing one has reported nothing, and ${BRAND_SHORT_NAME} says so rather than inventing\n# a result. This file is what makes that impossible to get wrong by accident:\n#\n# * it starts ${bodyPath} — your script, unchanged;\n# * if your script wrote ${sigil}RUNVERIC_RESULT_FILE itself, this file leaves it exactly alone;\n# * otherwise it writes one for you — succeeded when your script exits 0, failed with the exit\n# code and a result.error when it does not — carrying whatever your script printed as the\n# message.\n#\n# So a script that only prints something is already a complete, working action. Edit this file\n# when you want more control: it is ordinary code, in a file you own.\n#\n# WHERE YOUR SCRIPT RUNS. This file moves to the PACKAGE ROOT before starting yours, so a\n# relative path in your script means what it meant on your laptop — \\`source ./lib/util.sh\\` and\n# \\`. ./lib/helpers.ps1\\` resolve against the package, not against wherever the runner happened\n# to start. The package root is READ-ONLY and NON-EXECUTABLE: write to ${sigil}RUNVERIC_WORK_DIR,\n# and call another script through your interpreter (\\`bash ./tool.sh\\`) rather than executing it\n# directly. ${sigil}RUNVERIC_PACKAGE_ROOT is exported so your script can be explicit rather than\n# assume.\n#\n# THE CONTRACT (docs/22), identical in every language:\n# ${sigil}RUNVERIC_PARAMETERS_FILE the operator's answers, as JSON\n# ${sigil}RUNVERIC_CONTEXT_FILE non-secret run metadata (execution id, provider, scope)\n# ${sigil}RUNVERIC_RESULT_FILE where the result is WRITTEN — the only result channel\n# ${sigil}RUNVERIC_DRY_RUN \"true\" when the operator asked for a rehearsal. PASSED\n# THROUGH, never acted on here: only your script knows which of\n# its steps change anything.\n# ${sigil}RUNVERIC_WORK_DIR scratch space; nothing else is writable\n# ${sigil}RUNVERIC_PACKAGE_ROOT this package's root, and the working directory\n# Anything printed to stdout becomes a log line. A line starting with RUNVERIC_EVENT becomes a\n# structured event.\n#\n# The runner starts run/${entryFile} the same way this file starts ${bodyPath}.\n# ─────────────────────────────────────────────────────────────────────────────────────────\n`;\n}\n\n/**\n * THE WRAPPER'S RESULT RULE, WRITTEN ONCE. Embedded verbatim in both the bash wrapper (which\n * already shells out to python3 for JSON, as the old scaffold did) and the python one, so two\n * of the three cannot drift. PowerShell restates it below; three interpreters is three\n * languages, and no amount of factoring changes that.\n */\nconst FALLBACK_RESULT_PYTHON = `def opera_result(status, output, body):\n \"\"\"The result ${BRAND_SHORT_NAME} gets when the body wrote none — the body's own output as the message.\"\"\"\n output = output.strip()\n # result.message is bounded at 4096 characters. Keep the TAIL, which is where a failure says\n # why, and mark that something was dropped rather than silently truncating.\n if len(output) > 4000:\n output = \"…\" + output[-4000:]\n if status == 0:\n return {\n \"protocolVersion\": \"${PACKAGE_RESULT_PROTOCOL_VERSION}\",\n \"status\": \"succeeded\",\n \"message\": output or (body + \" completed and printed no output.\"),\n }\n return {\n \"protocolVersion\": \"${PACKAGE_RESULT_PROTOCOL_VERSION}\",\n \"status\": \"failed\",\n \"message\": \"%s exited with code %d.\" % (body, status),\n \"error\": {\"code\": \"body_failed\", \"message\": output or (body + \" printed no output.\")},\n }`;\n\n/**\n * ─── THE WRAPPER, AND THE PATH IT LEARNS ────────────────────────────────────────────────\n *\n * `bodyPath` is the author's entrypoint, RELATIVE TO THE PACKAGE ROOT. The scaffold passes\n * `run/body.*`; an import passes wherever the author's file actually is — `deploy.ps1`,\n * `scripts/restart.sh`. ONE code path, because the alternative — moving an imported script to\n * `run/body.*` — breaks the author's own `source ./lib/util.sh`, whose path stops existing the\n * moment the file moves (docs/32 D3).\n *\n * SO IT RESOLVES FROM THE PACKAGE ROOT, not from its own directory, and it MOVES there first.\n * A relative path inside the author's script has to mean what it meant on their laptop, and\n * that is only true if the working directory is the package root. The runner and\n * `runveric test` both start this file with the working directory set to the SCRATCH dir,\n * deliberately — so moving is this file's job, and it is done here rather than by changing the\n * substrate, which would change it for OCI packages too.\n *\n * NOTHING ALREADY PUBLISHED IS AFFECTED, and no migration is owed. A wrapper is written into a\n * package's files when the package is created and a published version is immutable, so every\n * existing package keeps the wrapper it shipped with. This is what NEW packages get.\n *\n * THE PACKAGE ROOT IS THIS FILE'S PARENT, which holds because Opera writes the manifest that\n * declares `entrypoint: run/` and writes this file into that one directory. A manifest declaring\n * a deeper entrypoint is an author's own package, and it carries its own wrapper.\n *\n * The launch command is interpolated from {@link PACKAGE_INTERPRETER_LAUNCH} — the same table\n * `bootstrap.ps1` is parity-checked against — so the wrapper starts the body exactly the way the\n * runner starts the wrapper, and neither the binary nor its arguments is written down twice.\n */\nfunction wrapperScript(interpreter: PackageInterpreter, bodyPath: string): string {\n const launch = PACKAGE_INTERPRETER_LAUNCH[interpreter];\n if (interpreter === \"powershell\") {\n const command = [launch.fileName, ...launch.arguments].map((part) => `'${part}'`).join(\" \");\n return `${wrapperHeader(interpreter, \"$env:\", bodyPath)}\nSet-StrictMode -Version Latest\n# NOT 'Stop'. A native command's stderr arrives in this pipeline as an error record, and\n# stopping on it would kill the wrapper before it could report the body's failure — which is\n# the one job this file has.\n$ErrorActionPreference = 'Continue'\n\n# THE PACKAGE ROOT, and the working directory your script starts in. Set-Location moves\n# PowerShell's own location; [Environment]::CurrentDirectory moves the PROCESS's, which is what\n# a child process and every .NET relative-path API read. The two do not follow each other, and\n# setting only the first is a classic way to get a script that resolves paths differently from\n# the tools it calls.\n$operaPackageRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path\n$env:RUNVERIC_PACKAGE_ROOT = $operaPackageRoot\nSet-Location -LiteralPath $operaPackageRoot\n[Environment]::CurrentDirectory = $operaPackageRoot\n\n# THE ONE PLACE the author's path is written into this file. Everything below refers to the\n# variable, so an entrypoint containing a quote is a string here and cannot become syntax.\n#\n# It is also the only record of WHICH FILE THIS PACKAGE RUNS, which is why the marker below is\n# on it: \\`authoredEntrypointOf\\` reads this line back so that re-detecting parameters reads the\n# same file the runner binds. Writer and reader are guarded against each other by a round-trip\n# test — see interpreter-launch.ts for why that is how this codebase keeps one fact in one place.\n$operaBodyPath = ${powershellLiteral(bodyPath)} # ${ENTRYPOINT_MARKER}\n$operaBody = Join-Path $operaPackageRoot $operaBodyPath\n$operaCaptured = [System.Collections.Generic.List[string]]::new()\n\n# ─── THE OPERATOR'S ANSWERS, BOUND TO YOUR OWN param() BLOCK ─────────────────────────────\n#\n# ${BRAND_SHORT_NAME} delivers the operator's answers as JSON at $env:RUNVERIC_PARAMETERS_FILE. A script written\n# outside ${BRAND_SHORT_NAME} receives its values through its param() block. THOSE ARE DIFFERENT MECHANISMS,\n# and nothing joins them unless this file does — so without the lines below a run form built from\n# a param() block would collect six answers and hand your script none of them.\n#\n# WHAT YOU GET FROM THIS: your own declaration is still the contract. The values go through YOUR\n# param() block, so a [ValidateSet] still rejects, an [int] still coerces, a\n# [Parameter(Mandatory)] still refuses a missing answer, and the failure names the parameter.\n# ${BRAND_SHORT_NAME} re-implements none of that, which is why it cannot disagree with your script about it.\n#\n# READ AT LAUNCH, NOT BAKED IN. The declaration is parsed every run, so editing your param()\n# block takes effect immediately. A list captured when the package was created would go stale the\n# moment you added a parameter, and a stale list silently drops one.\n#\n# PARSE, NEVER EXECUTE. ParseFile builds an abstract syntax tree and runs nothing; your script is\n# started exactly once, below.\n#\n# An answer your script does not declare is IGNORED, not an error — your script is the authority\n# on what it takes. A script with no param() block gets no arguments at all and reads\n# $env:RUNVERIC_PARAMETERS_FILE itself, exactly as before.\n$operaDeclared = @()\ntry {\n $operaTokens = $null\n $operaParseErrors = $null\n $operaScriptAst = [System.Management.Automation.Language.Parser]::ParseFile(\n $operaBody, [ref] $operaTokens, [ref] $operaParseErrors)\n if ($null -ne $operaScriptAst -and $null -ne $operaScriptAst.ParamBlock) {\n $operaDeclared = @($operaScriptAst.ParamBlock.Parameters |\n ForEach-Object { $_.Name.VariablePath.UserPath })\n }\n} catch {\n # A body ${BRAND_SHORT_NAME} cannot parse gets no arguments. PowerShell reports the syntax error itself\n # when it starts the file below, which is the message you need — inventing a second one here\n # would report the wrapper's problem instead of yours.\n $operaDeclared = @()\n}\n\n$operaArguments = @()\nif ($operaDeclared.Count -gt 0 -and (Test-Path -LiteralPath $env:RUNVERIC_PARAMETERS_FILE)) {\n $operaAnswers = $null\n try {\n $operaAnswers = Get-Content -LiteralPath $env:RUNVERIC_PARAMETERS_FILE -Raw | ConvertFrom-Json\n } catch {\n $operaAnswers = $null\n }\n if ($null -ne $operaAnswers) {\n foreach ($operaName in $operaDeclared) {\n if (-not ($operaAnswers.PSObject.Properties.Name -contains $operaName)) { continue }\n $operaAnswer = $operaAnswers.$operaName\n if ($null -eq $operaAnswer) { continue }\n if ($operaAnswer -is [bool]) {\n # A BOOLEAN NEEDS THE COLON FORM. Every argument after -File is a literal string,\n # and binding the string \"False\" to a [bool] is an error, not $false — so\n # -Name:$false is the only spelling that reaches a [bool] or a [switch] as the\n # value the operator actually chose.\n $operaArguments += ('-{0}:\\${1}' -f $operaName, $operaAnswer.ToString().ToLowerInvariant())\n } elseif (([string] $operaAnswer).StartsWith('-')) {\n # A VALUE THAT BEGINS WITH A HYPHEN is read as another parameter NAME when it is\n # passed as its own argument — an answer of \"-Force\" beside a -Force parameter\n # refuses to bind at all. Attached after a colon it cannot be mistaken for one.\n $operaArguments += ('-{0}:{1}' -f $operaName, [string] $operaAnswer)\n } else {\n # TWO ARGUMENTS FOR EVERYTHING ELSE, deliberately. pwsh converts the literals\n # $true, $false and $null when they appear after a colon, so an operator whose\n # answer IS the text \"$false\" would have it silently changed to \"False\". Passed\n # as its own argument it stays exactly what they typed.\n $operaArguments += ('-{0}' -f $operaName)\n $operaArguments += [string] $operaAnswer\n }\n }\n }\n}\n\n# Both streams merged, so the transcript below is in the order the operator saw, and every line\n# is still printed as it arrives rather than held until the body ends.\n#\n# COLOUR IS STRIPPED. PowerShell renders an error record with ANSI escapes whether or not it is\n# talking to a terminal, and nothing here is: these lines become log events and the run's result\n# message, where \"\\`e[31;1mWrite-Error:\" is noise in the one sentence somebody reads afterwards.\n#\n# -File AND NOT -Command, still. It is how the runner starts this file, and it is the only launch\n# whose EXIT CODE means what it has always meant: your \\`exit 3\\` is 3, a terminating error is 1,\n# and a trailing native command that failed is not silently promoted to a failure. Splatting an\n# empty $operaArguments is byte-for-byte the command this file has always run.\n& ${command} $operaBody @operaArguments 2>&1 | ForEach-Object {\n $line = [string] $_ -replace \"\\`e\\\\[[0-9;]*[a-zA-Z]\", ''\n Write-Output $line\n $operaCaptured.Add($line)\n}\n$operaStatus = $LASTEXITCODE\n\n# THE BODY'S OWN RESULT WINS. The wrapper fills a gap; it never overwrites what an author\n# reported for themselves — outputs, checks and rollbackCapture all arrive this way.\n$operaWritten = (Test-Path -LiteralPath $env:RUNVERIC_RESULT_FILE) -and\n ((Get-Item -LiteralPath $env:RUNVERIC_RESULT_FILE).Length -gt 0)\nif (-not $operaWritten) {\n $operaOutput = ($operaCaptured -join \"\\`n\").Trim()\n # result.message is bounded at 4096 characters. Keep the TAIL, which is where a failure says\n # why, and mark that something was dropped rather than silently truncating.\n if ($operaOutput.Length -gt 4000) {\n $operaOutput = '…' + $operaOutput.Substring($operaOutput.Length - 4000)\n }\n $operaResult = if ($operaStatus -eq 0) {\n [ordered]@{\n protocolVersion = '${PACKAGE_RESULT_PROTOCOL_VERSION}'\n status = 'succeeded'\n message = if ($operaOutput) { $operaOutput } else { \"$operaBodyPath completed and printed no output.\" }\n }\n } else {\n [ordered]@{\n protocolVersion = '${PACKAGE_RESULT_PROTOCOL_VERSION}'\n status = 'failed'\n message = \"$operaBodyPath exited with code $operaStatus.\"\n error = [ordered]@{\n code = 'body_failed'\n message = if ($operaOutput) { $operaOutput } else { \"$operaBodyPath printed no output.\" }\n }\n }\n }\n $operaResult | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $env:RUNVERIC_RESULT_FILE -Encoding utf8\n}\n\n# The body's exit code is this package's exit code. ${BRAND_SHORT_NAME} cross-checks the two — a result that\n# says succeeded from a process that crashed is reported as the failure it was.\nexit $operaStatus\n`;\n }\n if (interpreter === \"bash\") {\n const command = [launch.fileName, ...launch.arguments].map((part) => `'${part}'`).join(\" \");\n return `${wrapperHeader(interpreter, \"$\", bodyPath)}\n# THE PACKAGE ROOT, and the working directory your script starts in — so \\`source ./lib/util.sh\\`\n# resolves against the package rather than against the scratch directory the runner starts in.\nRUNVERIC_PACKAGE_ROOT=\"$(cd \"$(dirname \"\\${BASH_SOURCE[0]}\")/..\" && pwd)\"\nexport RUNVERIC_PACKAGE_ROOT\ncd \"\\${RUNVERIC_PACKAGE_ROOT}\"\n\n# THE ONE PLACE the author's path is written into this file. Everything below refers to the\n# variable, so an entrypoint containing a quote or a \\`$\\` is a string here and cannot become\n# syntax. The marker is how \\`authoredEntrypointOf\\` reads this line back — see that function.\nopera_body_path=${bashLiteral(bodyPath)} # ${ENTRYPOINT_MARKER}\nopera_body=\"\\${RUNVERIC_PACKAGE_ROOT}/\\${opera_body_path}\"\nopera_capture=\"\\${RUNVERIC_WORK_DIR}/.runveric-body-output\"\n\n# Both streams merged, so the transcript below is in the order the operator saw; \\`tee\\` keeps\n# every line arriving live rather than held until the body ends. errexit is lifted for exactly\n# this pipeline: a failing body is a result to report, not a wrapper that dies before it can.\nset +e\n${command} \"\\${opera_body}\" 2>&1 | tee \"\\${opera_capture}\"\nopera_status=\"\\${PIPESTATUS[0]}\"\nset -e\n\n# THE BODY'S OWN RESULT WINS. The wrapper fills a gap; it never overwrites what an author\n# reported for themselves — outputs, checks and rollbackCapture all arrive this way.\nif [ ! -s \"\\${RUNVERIC_RESULT_FILE}\" ]; then\n RUNVERIC_BODY_STATUS=\"\\${opera_status}\" RUNVERIC_BODY_CAPTURE=\"\\${opera_capture}\" \\\\\n RUNVERIC_BODY_PATH=\"\\${opera_body_path}\" \\\\\n python3 - > \"\\${RUNVERIC_RESULT_FILE}\" <<'PY'\nimport json, os\n\n${FALLBACK_RESULT_PYTHON}\n\nwith open(os.environ[\"RUNVERIC_BODY_CAPTURE\"], encoding=\"utf-8\", errors=\"replace\") as handle:\n captured = handle.read()\nprint(json.dumps(opera_result(int(os.environ[\"RUNVERIC_BODY_STATUS\"]), captured, os.environ[\"RUNVERIC_BODY_PATH\"])))\nPY\nfi\n\n# The body's exit code is this package's exit code. ${BRAND_SHORT_NAME} cross-checks the two — a result that\n# says succeeded from a process that crashed is reported as the failure it was.\nexit \"\\${opera_status}\"\n`;\n }\n const command = [launch.fileName, ...launch.arguments].map((part) => `\"${part}\"`).join(\", \");\n return `${wrapperHeader(interpreter, \"\", bodyPath)}\nimport json\nimport os\nimport subprocess\nimport sys\n\n${FALLBACK_RESULT_PYTHON}\n\n# THE PACKAGE ROOT, and the working directory your script starts in — so a relative \\`open()\\`\n# or \\`import\\` resolves against the package rather than against the scratch directory the runner\n# starts in. os.chdir moves this process, and the body inherits it.\nopera_package_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nos.environ[\"RUNVERIC_PACKAGE_ROOT\"] = opera_package_root\nos.chdir(opera_package_root)\n\n# THE ONE PLACE the author's path is written into this file. Everything below refers to the\n# variable, so an entrypoint containing a quote is a string here and cannot become syntax.\n# The marker is how \\`authoredEntrypointOf\\` reads this line back — see that function.\nopera_body_path = ${pythonLiteral(bodyPath)} # ${ENTRYPOINT_MARKER}\nopera_body = os.path.join(opera_package_root, opera_body_path)\n\n# Both streams merged, so the transcript below is in the order the operator saw, and every line\n# is printed as it arrives rather than held until the body ends.\nopera_process = subprocess.Popen(\n [${command}, opera_body],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n errors=\"replace\",\n)\nopera_captured = []\nfor opera_line in opera_process.stdout:\n opera_line = opera_line.rstrip(\"\\\\n\")\n print(opera_line)\n opera_captured.append(opera_line)\nopera_status = opera_process.wait()\n\n# THE BODY'S OWN RESULT WINS. The wrapper fills a gap; it never overwrites what an author\n# reported for themselves — outputs, checks and rollbackCapture all arrive this way.\nopera_result_file = os.environ[\"RUNVERIC_RESULT_FILE\"]\nopera_written = os.path.exists(opera_result_file) and os.path.getsize(opera_result_file) > 0\nif not opera_written:\n with open(opera_result_file, \"w\", encoding=\"utf-8\") as handle:\n json.dump(\n opera_result(opera_status, \"\\\\n\".join(opera_captured), opera_body_path),\n handle,\n )\n\n# The body's exit code is this package's exit code. ${BRAND_SHORT_NAME} cross-checks the two — a result that\n# says succeeded from a process that crashed is reported as the failure it was.\nsys.exit(opera_status)\n`;\n}\n\n/**\n * THE DEFAULT BODY — the file an author edits, and the file a paste replaces wholesale.\n *\n * It reports NOTHING itself, on purpose: it prints, and the wrapper turns what it printed into\n * the run's result. That is the shape a pasted script already has, so the scaffold teaches the\n * shape the paste flow produces rather than a second one only `init` users ever see.\n */\nconst BODY_SCRIPT: Record<PackageInterpreter, string> = {\n powershell: `# YOUR SCRIPT. run/main.ps1 — ${BRAND_SHORT_NAME}'s wrapper — starts this file and writes the run's result\n# from whether it exits 0 and what it printed. Anything that runs is a working action.\n#\n# What you are given:\n# $env:RUNVERIC_PARAMETERS_FILE the operator's answers, as JSON\n# $env:RUNVERIC_CONTEXT_FILE non-secret run metadata (execution id, provider, scope)\n# $env:RUNVERIC_DRY_RUN \"true\" when the operator asked for a rehearsal — HONOUR IT if\n# anything below changes something\n# $env:RUNVERIC_WORK_DIR scratch space; nothing else is writable\n# Anything you print becomes a log line, and becomes the run's message.\n#\n# WHERE YOU ARE. Your script runs from the package root — $env:RUNVERIC_PACKAGE_ROOT — so\n# \\`. ./lib/helpers.ps1\\` resolves the way it does on your laptop. That directory is READ-ONLY\n# and NON-EXECUTABLE: write to $env:RUNVERIC_WORK_DIR, and start another script through its\n# interpreter (\\`pwsh ./tool.ps1\\`) rather than executing it directly.\n#\n# WANT MORE THAN A MESSAGE — outputs, a rollbackCapture, your own error code? Write that JSON\n# to $env:RUNVERIC_RESULT_FILE yourself and the wrapper leaves it alone. run/main.ps1 says how.\n\nSet-StrictMode -Version Latest\n$ErrorActionPreference = 'Stop'\n\n$parameters = Get-Content -LiteralPath $env:RUNVERIC_PARAMETERS_FILE -Raw | ConvertFrom-Json\n$context = Get-Content -LiteralPath $env:RUNVERIC_CONTEXT_FILE -Raw | ConvertFrom-Json\n$dryRun = $env:RUNVERIC_DRY_RUN -eq 'true'\n\n# Strict mode makes reading an absent property an error rather than an empty string, so an\n# optional parameter is asked for explicitly. That is the point of strict mode: the failure\n# you want is the loud one.\n$note = if ($parameters.PSObject.Properties.Name -contains 'note') { [string] $parameters.note } else { '' }\n\n# CAREFUL WITH \"?\" AFTER A VARIABLE. PowerShell reads \"$note?\" as a variable named \"note?\",\n# which nobody declared, so it expands to nothing and your value vanishes silently. Write\n# \"\\${note}?\" instead. \\`runveric check\\` fails on this — it cost five review cycles once.\nWrite-Output \"Running for execution $($context.executionId).\"\nWrite-Output \"Note: \\${note}\"\n\nif ($dryRun) {\n Write-Output 'RUNVERIC_EVENT {\"level\":\"info\",\"message\":\"Dry run — nothing was changed.\"}'\n} else {\n # Do the real work here.\n Write-Output 'RUNVERIC_EVENT {\"level\":\"success\",\"message\":\"Nothing to change yet — this is a new action.\"}'\n}\n`,\n bash: `# YOUR SCRIPT. run/main.sh — ${BRAND_SHORT_NAME}'s wrapper — starts this file and writes the run's result\n# from whether it exits 0 and what it printed. Anything that runs is a working action.\n#\n# What you are given:\n# $RUNVERIC_PARAMETERS_FILE the operator's answers, as JSON\n# $RUNVERIC_CONTEXT_FILE non-secret run metadata (execution id, provider, scope)\n# $RUNVERIC_DRY_RUN \"true\" when the operator asked for a rehearsal — HONOUR IT if\n# anything below changes something\n# $RUNVERIC_WORK_DIR scratch space; nothing else is writable\n# Anything you print becomes a log line, and becomes the run's message.\n#\n# WHERE YOU ARE. Your script runs from the package root — $RUNVERIC_PACKAGE_ROOT — so\n# \\`source ./lib/util.sh\\` resolves the way it does on your laptop. That directory is READ-ONLY\n# and NON-EXECUTABLE: write to $RUNVERIC_WORK_DIR, and start another script through its\n# interpreter (\\`bash ./tool.sh\\`) rather than executing it directly.\n#\n# WANT MORE THAN A MESSAGE — outputs, a rollbackCapture, your own error code? Write that JSON\n# to $RUNVERIC_RESULT_FILE yourself and the wrapper leaves it alone. run/main.sh says how.\n#\n# Started with \\`bash -euo pipefail\\`, so a failing command ends the run instead of continuing\n# past it.\n\nnote=\"$(python3 -c 'import json,os,sys; print(json.load(open(os.environ[\"RUNVERIC_PARAMETERS_FILE\"])).get(\"note\",\"\"))')\"\nexecution_id=\"$(python3 -c 'import json,os,sys; print(json.load(open(os.environ[\"RUNVERIC_CONTEXT_FILE\"]))[\"executionId\"])')\"\n\necho \"Running for execution \\${execution_id}.\"\necho \"Note: \\${note}\"\n\nif [ \"\\${RUNVERIC_DRY_RUN}\" = \"true\" ]; then\n echo 'RUNVERIC_EVENT {\"level\":\"info\",\"message\":\"Dry run — nothing was changed.\"}'\nelse\n # Do the real work here.\n echo 'RUNVERIC_EVENT {\"level\":\"success\",\"message\":\"Nothing to change yet — this is a new action.\"}'\nfi\n`,\n python: `# YOUR SCRIPT. run/main.py — ${BRAND_SHORT_NAME}'s wrapper — starts this file and writes the run's result\n# from whether it exits 0 and what it printed. Anything that runs is a working action.\n#\n# What you are given:\n# RUNVERIC_PARAMETERS_FILE the operator's answers, as JSON\n# RUNVERIC_CONTEXT_FILE non-secret run metadata (execution id, provider, scope)\n# RUNVERIC_DRY_RUN \"true\" when the operator asked for a rehearsal — HONOUR IT if\n# anything below changes something\n# RUNVERIC_WORK_DIR scratch space; nothing else is writable\n# Anything you print becomes a log line, and becomes the run's message.\n#\n# WHERE YOU ARE. Your script runs from the package root — RUNVERIC_PACKAGE_ROOT — so a relative\n# \\`open()\\` or \\`import\\` resolves the way it does on your laptop. That directory is READ-ONLY\n# and NON-EXECUTABLE: write to RUNVERIC_WORK_DIR, and start another script through its interpreter\n# (\\`python3 ./tool.py\\`) rather than executing it directly.\n#\n# WANT MORE THAN A MESSAGE — outputs, a rollbackCapture, your own error code? Write that JSON\n# to RUNVERIC_RESULT_FILE yourself and the wrapper leaves it alone. run/main.py says how.\n\nimport json\nimport os\n\nwith open(os.environ[\"RUNVERIC_PARAMETERS_FILE\"], encoding=\"utf-8\") as handle:\n parameters = json.load(handle)\nwith open(os.environ[\"RUNVERIC_CONTEXT_FILE\"], encoding=\"utf-8\") as handle:\n context = json.load(handle)\n\ndry_run = os.environ.get(\"RUNVERIC_DRY_RUN\") == \"true\"\nnote = parameters.get(\"note\", \"\")\n\nprint(f\"Running for execution {context['executionId']}.\")\nprint(f\"Note: {note}\")\n\nif dry_run:\n print('RUNVERIC_EVENT {\"level\":\"info\",\"message\":\"Dry run — nothing was changed.\"}')\nelse:\n # Do the real work here.\n print('RUNVERIC_EVENT {\"level\":\"success\",\"message\":\"Nothing to change yet — this is a new action.\"}')\n`,\n};\n\nconst VALIDATE_SCRIPT: Record<PackageInterpreter, string> = {\n powershell: `The VALIDATE phase — a pre-flight that changes nothing.\nEnable it with \\`validateEntrypoint: validate/\\` in action.yaml, then uncomment this file.\n\nA validate result carries CHECKS and no outputs. One entry per thing you checked, each\npassed / warning / failed. If any check failed, set status to \"failed\" — the checks ARE the\nreason, you do not also need result.error.\n\nSet-StrictMode -Version Latest\n$ErrorActionPreference = 'Stop'\n$parameters = Get-Content -LiteralPath $env:RUNVERIC_PARAMETERS_FILE -Raw | ConvertFrom-Json\n\n$checks = @(\n [ordered]@{ status = 'passed'; message = 'The note is present.' }\n)\n$failed = @($checks | Where-Object { $_.status -eq 'failed' }).Count -gt 0\n\n[ordered]@{\n protocolVersion = '${PACKAGE_RESULT_PROTOCOL_VERSION}'\n status = if ($failed) { 'failed' } else { 'succeeded' }\n message = if ($failed) { 'Pre-flight found a blocking problem.' } else { 'Pre-flight passed.' }\n checks = $checks\n} | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $env:RUNVERIC_RESULT_FILE -Encoding utf8`,\n bash: `The VALIDATE phase — a pre-flight that changes nothing.\nEnable it with \\`validateEntrypoint: validate/\\` in action.yaml, then uncomment this file.\n\nA validate result carries CHECKS and no outputs. One entry per thing you checked, each\npassed / warning / failed. If any check failed, set status to \"failed\" — the checks ARE the\nreason, you do not also need result.error.\n\npython3 - <<'PY' > \"\\${RUNVERIC_RESULT_FILE}\"\nimport json\nchecks = [{\"status\": \"passed\", \"message\": \"The note is present.\"}]\nfailed = any(check[\"status\"] == \"failed\" for check in checks)\nprint(json.dumps({\n \"protocolVersion\": \"${PACKAGE_RESULT_PROTOCOL_VERSION}\",\n \"status\": \"failed\" if failed else \"succeeded\",\n \"message\": \"Pre-flight found a blocking problem.\" if failed else \"Pre-flight passed.\",\n \"checks\": checks,\n}))\nPY`,\n python: `The VALIDATE phase — a pre-flight that changes nothing.\nEnable it with \\`validateEntrypoint: validate/\\` in action.yaml, then uncomment this file.\n\nA validate result carries CHECKS and no outputs. One entry per thing you checked, each\npassed / warning / failed. If any check failed, set status to \"failed\" — the checks ARE the\nreason, you do not also need result.error.\n\nimport json\nimport os\n\nchecks = [{\"status\": \"passed\", \"message\": \"The note is present.\"}]\nfailed = any(check[\"status\"] == \"failed\" for check in checks)\n\nwith open(os.environ[\"RUNVERIC_RESULT_FILE\"], \"w\", encoding=\"utf-8\") as handle:\n json.dump(\n {\n \"protocolVersion\": \"${PACKAGE_RESULT_PROTOCOL_VERSION}\",\n \"status\": \"failed\" if failed else \"succeeded\",\n \"message\": \"Pre-flight found a blocking problem.\" if failed else \"Pre-flight passed.\",\n \"checks\": checks,\n },\n handle,\n )`,\n};\n\nconst ROLLBACK_SCRIPT: Record<PackageInterpreter, string> = {\n powershell: `The ROLLBACK phase — undo what the run phase did.\nEnable it by setting \\`rollback: true\\`, \\`rollbackEntrypoint: rollback/\\` and\n\\`capabilities.rollback: true\\` in action.yaml, then uncomment this file.\n\nRollback reads what the run phase captured, at $env:RUNVERIC_PRIOR_RESULT_FILE. That is why a\nrun that intends to be undoable writes \\`rollbackCapture\\` into its result — this phase has\nnothing else to work from.\n\nSet-StrictMode -Version Latest\n$ErrorActionPreference = 'Stop'\n$prior = Get-Content -LiteralPath $env:RUNVERIC_PRIOR_RESULT_FILE -Raw | ConvertFrom-Json\n\n[ordered]@{\n protocolVersion = '${PACKAGE_RESULT_PROTOCOL_VERSION}'\n status = 'succeeded'\n message = 'Rolled back.'\n} | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $env:RUNVERIC_RESULT_FILE -Encoding utf8`,\n bash: `The ROLLBACK phase — undo what the run phase did.\nEnable it by setting \\`rollback: true\\`, \\`rollbackEntrypoint: rollback/\\` and\n\\`capabilities.rollback: true\\` in action.yaml, then uncomment this file.\n\nRollback reads what the run phase captured, at $RUNVERIC_PRIOR_RESULT_FILE. That is why a run\nthat intends to be undoable writes \\`rollbackCapture\\` into its result — this phase has\nnothing else to work from.\n\npython3 - <<'PY' > \"\\${RUNVERIC_RESULT_FILE}\"\nimport json\nprint(json.dumps({\n \"protocolVersion\": \"${PACKAGE_RESULT_PROTOCOL_VERSION}\",\n \"status\": \"succeeded\",\n \"message\": \"Rolled back.\",\n}))\nPY`,\n python: `The ROLLBACK phase — undo what the run phase did.\nEnable it by setting \\`rollback: true\\`, \\`rollbackEntrypoint: rollback/\\` and\n\\`capabilities.rollback: true\\` in action.yaml, then uncomment this file.\n\nRollback reads what the run phase captured, at RUNVERIC_PRIOR_RESULT_FILE. That is why a run\nthat intends to be undoable writes \\`rollbackCapture\\` into its result — this phase has\nnothing else to work from.\n\nimport json\nimport os\n\nwith open(os.environ[\"RUNVERIC_PRIOR_RESULT_FILE\"], encoding=\"utf-8\") as handle:\n prior = json.load(handle)\n\nwith open(os.environ[\"RUNVERIC_RESULT_FILE\"], \"w\", encoding=\"utf-8\") as handle:\n json.dump(\n {\n \"protocolVersion\": \"${PACKAGE_RESULT_PROTOCOL_VERSION}\",\n \"status\": \"succeeded\",\n \"message\": \"Rolled back.\",\n },\n handle,\n )`,\n};\n\nfunction readme(input: ScaffoldInput): string {\n const { entryFile, bodyFile } = PACKAGE_INTERPRETER_LAUNCH[input.interpreter];\n return `# ${input.name}\n\nDescribe in one paragraph what an operator gets when they run this action. ${BRAND_SHORT_NAME} shows this\nparagraph in the catalog, so write it for the person deciding whether to press the button —\nnot for the person maintaining the script.\n\n## What it does\n\nRight now: reads the \\`note\\` parameter and reports it back. That is a working action, and the\npoint of it is that the loop below works before you have written anything.\n\n## Two files in \\`run/\\`, and which one is yours\n\n**\\`run/${bodyFile}\\` is your script. \\`run/${entryFile}\\` is ${BRAND_SHORT_NAME}'s wrapper.**\n\n${BRAND_SHORT_NAME} reads exactly one thing from a package: the JSON at \\`RUNVERIC_RESULT_FILE\\`. A package that\nexits 0 without writing one has reported nothing, and ${BRAND_SHORT_NAME} refuses it rather than inventing a\nresult — that strictness is what makes every check, output and rollback capture in the product\nworth trusting.\n\n\\`run/${entryFile}\\` is what keeps you on the right side of it. It starts \\`run/${bodyFile}\\`,\nand then:\n\n- if your script wrote \\`RUNVERIC_RESULT_FILE\\` itself, it leaves that result exactly alone;\n- otherwise it writes one — **succeeded** when your script exits 0, **failed** with the exit\n code and a \\`result.error\\` when it does not — carrying whatever your script printed as the\n message.\n\nSo a script that only prints something is already a complete action. Put your work in\n\\`run/${bodyFile}\\`; edit \\`run/${entryFile}\\` when you want full control over the result. Both\nare ordinary files you own — the split exists so that replacing one of them cannot delete the\ncontract carried by the other.\n\n## The loop\n\n\\`\\`\\`sh\nrunveric check # offline. The same validator the server runs.\nrunveric test --phase run # in the real runner image, with your own credentials.\nrunveric test --phase run --dry-run\n\\`\\`\\`\n\nNeither needs ${BRAND_ARTICLE} ${BRAND_SHORT_NAME} account, a Git remote, or a push.\n\n## Layout\n\n| Path | What it is |\n| --- | --- |\n| \\`action.yaml\\` | The contract. Identity, runtime, permissions, risk. |\n| \\`parameters.json\\` | What an operator is asked for, **in the order they are asked**. |\n| \\`run/${bodyFile}\\` | **Your script.** The run phase's work. |\n| \\`run/${entryFile}\\` | ${BRAND_SHORT_NAME}'s wrapper. Reads the parameters, starts your script, writes the result. |\n| \\`validate/${entryFile}\\` | An optional pre-flight. Commented out; uncomment to enable. |\n| \\`rollback/${entryFile}\\` | An optional undo. Commented out; uncomment to enable. |\n\n## Parameters\n\n| Name | Type | Required | Description |\n| --- | --- | --- | --- |\n| \\`note\\` | string | no | Shown back in the run output. |\n\n## Permissions\n\nNone yet. Add each one to \\`requiredPermissions\\` in \\`action.yaml\\` as you need it — every\nentry is privilege somebody has to approve, so declare the least that works.\n`;\n}\n\n/**\n * The README for an IMPORTED package. It differs from the scaffold's in the only way that\n * matters: it names the author's own entrypoint rather than `run/body.*`, because that is the\n * file they will open, and a layout table pointing at a file the package does not contain is\n * how a document stops being read.\n *\n * Written only when the upload has no README of its own — see {@link generateImportedPackage}.\n */\nfunction importReadme(input: ImportInput): string {\n const { entryFile } = PACKAGE_INTERPRETER_LAUNCH[input.interpreter];\n return `# ${input.name}\n\nDescribe in one paragraph what an operator gets when they run this action. ${BRAND_SHORT_NAME} shows this\nparagraph in the catalog, so write it for the person deciding whether to press the button —\nnot for the person maintaining the script.\n\n## Your files, where you put them\n\nThis action was imported from files you already had. **Every one of them is stored at the path\nit arrived with** — nothing was moved, renamed or rewritten — so \\`${input.entrypoint}\\` still\nfinds whatever it referenced beside it.\n\n**\\`${input.entrypoint}\\` is what runs.** \\`run/${entryFile}\\` is ${BRAND_SHORT_NAME}'s wrapper: it starts your\nscript and reports the result.\n\n## The result contract, and why the wrapper is there\n\n${BRAND_SHORT_NAME} reads exactly one thing from a package: the JSON at \\`RUNVERIC_RESULT_FILE\\`. A package that\nexits 0 without writing one has reported nothing, and ${BRAND_SHORT_NAME} refuses it rather than inventing a\nresult — that strictness is what makes every check, output and rollback capture in the product\nworth trusting.\n\n\\`run/${entryFile}\\` keeps you on the right side of it. It starts \\`${input.entrypoint}\\`, and then:\n\n- if your script wrote \\`RUNVERIC_RESULT_FILE\\` itself, it leaves that result exactly alone;\n- otherwise it writes one — **succeeded** when your script exits 0, **failed** with the exit\n code and a \\`result.error\\` when it does not — carrying whatever your script printed as the\n message.\n\nSo a script that only prints something is already a complete action.\n\n## Where your script runs\n\nFrom the **package root**, which is also \\`RUNVERIC_PACKAGE_ROOT\\`. That is what makes\n\\`source ./lib/util.sh\\` and \\`. ./lib/helpers.ps1\\` resolve the way they do on your laptop.\n\nTwo things about that directory are worth knowing before your first run:\n\n- it is **read-only** — write to \\`RUNVERIC_WORK_DIR\\`, the only writable location;\n- it is **non-executable** — start another script through its interpreter\n (\\`bash ./tool.sh\\`, \\`pwsh ./tool.ps1\\`) rather than executing it directly.\n\n## One interpreter per package\n\nThis package provides **${input.interpreter}**, because \\`${input.entrypoint}\\` is what runs. Files\nin another language ship into the sandbox with everything else and will not execute — data files\n(\\`.json\\`, \\`.csv\\`, \\`.md\\`) are entirely normal and are not affected.\n\n## Before you publish\n\n\\`action.yaml\\` was generated with the SAFE defaults, not with knowledge of what your script\ndoes. ${BRAND_SHORT_NAME} cannot read intent out of a script, and guessing would be worse than asking:\n\n| Field | Generated as | Why you should revisit it |\n| --- | --- | --- |\n| \\`riskLevel\\` | \\`high\\` | Lower it when you know the action is safe, not before. |\n| \\`requiredPermissions\\` | \\`[]\\` | Every entry is privilege an approver grants. Declare the least that works. |\n| \\`requiresNetwork\\` | \\`false\\` | Set it true only with a non-empty \\`egressAllowlist\\`. |\n| \\`parameters.json\\` | one placeholder | Replace it with what your script actually needs. |\n\n\\`\\`\\`sh\nrunveric check # offline. The same validator the server runs.\nrunveric test --phase run # in the real runner image, with your own credentials.\n\\`\\`\\`\n`;\n}\n\nfunction license(input: ScaffoldInput): string {\n return `MIT License\n\nCopyright (c) ${input.year} ${input.author}\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n`;\n}\n\nconst GITIGNORE = `# runveric test writes its scratch here.\n.runveric/\n*.log\n`;\n\n/**\n * A YAML double-quoted scalar. Always quoted, never bare: a display name is free text, and the\n * first author whose action is called `No: really` would otherwise ship a manifest that parses\n * into something else entirely.\n */\nfunction yamlString(value: string): string {\n return `\"${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/**\n * ─── AN AUTHOR'S PATH, AS A LITERAL IN A GENERATED SCRIPT ───────────────────────────────\n *\n * The entrypoint path is the AUTHOR'S — it is whatever they named a file — and it is written\n * into a script Opera generates. `assertSafePackagePath` already refuses the paths that would\n * escape the package root, but it does not refuse a quote, a `$` or a backtick, because those\n * are legal in a filename and refusing them would be Opera telling somebody to rename their\n * file for our convenience.\n *\n * So the path is ESCAPED for the language it lands in rather than restricted. Three small\n * functions, one per language, each used exactly once — because a value spliced into generated\n * code without escaping is the same defect whatever the blast radius happens to be.\n */\n\n/**\n * ─── AND READING ONE BACK ───────────────────────────────────────────────────────────────\n *\n * The exact inverse of each writer above, keyed by {@link PackageInterpreter} so a fourth\n * interpreter is a COMPILE ERROR here rather than a wrapper nothing can read. Each takes the\n * text BEFORE the marker comment and returns the path, or null when there is no literal in it —\n * which is what an edited wrapper looks like, and the case callers must refuse rather than guess.\n *\n * `scaffold.spec.ts` round-trips a path full of quotes through every writer and reader, because\n * \"these two are inverses\" is a claim, and this codebase has been bitten by an unguarded one.\n */\nconst LITERAL_READERS: Record<PackageInterpreter, (line: string) => string | null> = {\n powershell: (line) => singleQuoted(line, /''/g, \"'\"),\n // bash closes the quote, escapes, and reopens: `'\\''`. Undoing that is the same substitution\n // read the other way round.\n bash: (line) => singleQuoted(line, /'\\\\''/g, \"'\"),\n python: (line) => {\n const open = line.indexOf('\"');\n const close = line.lastIndexOf('\"');\n if (open < 0 || close <= open) return null;\n try {\n const value: unknown = JSON.parse(line.slice(open, close + 1));\n return typeof value === \"string\" ? value : null;\n } catch {\n return null;\n }\n },\n};\n\n/** The text between the first and last `'` on a line, with one escape sequence undone. */\nfunction singleQuoted(line: string, escaped: RegExp, plain: string): string | null {\n const open = line.indexOf(\"'\");\n const close = line.lastIndexOf(\"'\");\n if (open < 0 || close <= open) return null;\n return line.slice(open + 1, close).replace(escaped, plain);\n}\n\n/** A PowerShell single-quoted string: nothing expands inside one, and `'` doubles to escape. */\nfunction powershellLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\n/** A bash single-quoted word: nothing expands inside one, and `'` cannot appear — so it ends\n * the quote, escapes a literal `'`, and reopens. The classic, and the only form that is safe\n * for every byte a filename may carry. */\nfunction bashLiteral(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * A Python string literal. `JSON.stringify` produces exactly one — JSON's escapes (`\\\"`, `\\\\`,\n * `\\n`, `\\uXXXX`) are all valid Python, and a Python source file is UTF-8 by default so any\n * character it passes through unescaped is legal too.\n */\nfunction pythonLiteral(value: string): string {\n return JSON.stringify(value);\n}\n","/**\n * ─── @runveric/action-manifest ─────────────────────────────────────────────────────────────\n *\n * THE Action Package validator, and everything an author-facing tool needs to sit on top of it.\n *\n * It is a package rather than a folder in the API for exactly one reason: `runveric check`\n * runs on a laptop with no server, and it must reach the same verdict the import path reaches.\n * Two implementations of \"is this manifest valid\" is the defect this package exists to make\n * impossible — a local check that disagrees with the server is worse than no local check.\n *\n * Nothing here does I/O, reads configuration, or touches the network. That is what lets the\n * same code run in the control plane, in the CLI, and behind the in-app Check button.\n */\n\nexport {\n parseAndValidateManifest,\n validateManifest,\n validateParameterSchema,\n canonicalJson,\n sha256Hex,\n isSafeRelativePath,\n isEgressDestination,\n type ManifestValidationResult,\n type ValidationResult,\n} from \"./manifest-validator\";\n\nexport {\n ACTION_CATEGORIES,\n PROVIDERS,\n RISK_LEVELS,\n MANIFEST_FIELDS,\n PACKAGE_ID_PATTERN,\n SEMVER_PATTERN,\n DURATION_PATTERN,\n SPDX_ID_PATTERN,\n CREDENTIAL_SCOPE_PATTERN,\n PARAMETER_SCHEMA_FIELDS,\n PARAMETER_PROPERTY_FIELDS,\n PARAMETER_CONTROLS,\n} from \"./manifest.schema\";\n\nexport {\n PackageRuntimeDeclarationError,\n checkOciImageReference,\n normalizePackageRuntime,\n type OciImageCheck,\n} from \"./package-runtime-declaration\";\n\nexport {\n PackageProtocolError,\n validatePackageResult,\n} from \"./package-result-validator\";\n\nexport {\n MANIFEST_FILE,\n REQUIRED_PACKAGE_FILES,\n validateActionPackage,\n type ActionPackageValidation,\n} from \"./package-validation\";\n\nexport { checkActionPackage, type CheckReport } from \"./check\";\n\nexport {\n readManifest,\n resolveParametersFile,\n resolveParametersFileOf,\n type ParametersFileLocation,\n} from \"./parameters-location\";\n\nexport {\n findingFromValidation,\n mergeFindings,\n sortFindings,\n type AuthoringFinding,\n type FindingSeverity,\n} from \"./findings\";\n\nexport { lintActionPackage, type LintInput } from \"./authoring-lint\";\n\nexport {\n PACKAGE_INTERPRETER_LAUNCH,\n PACKAGE_INTERPRETER_EXTENSIONS,\n interpreterEntryFileList,\n interpreterForPath,\n type InterpreterLaunch,\n} from \"./interpreter-launch\";\n\nexport {\n locate,\n offsetToLocation,\n pathSegments,\n type SourceLocation,\n} from \"./source-location\";\n\nexport {\n POWERSHELL_PARAM_PROBE,\n mapDeclaredParameters,\n parseProbeOutput,\n powerShellDetection,\n type DeclaredParameter,\n type DeclaredParameterBlock,\n type MappedParameters,\n type PowerShellDetection,\n} from \"./powershell-param-detection\";\n\nexport {\n authoredBodyPath,\n authoredEntrypointOf,\n generateImportedPackage,\n reservedImportPaths,\n scaffoldActionPackage,\n type GeneratedImport,\n type ImportInput,\n type ScaffoldInput,\n} from \"./scaffold\";\n","{\n \"name\": \"@runveric/cli\",\n \"version\": \"0.4.0\",\n \"description\": \"runveric — author, check and run a Runveric action locally. No Runveric account required.\",\n \"bin\": {\n \"runveric\": \"dist/runveric.mjs\",\n \"rv\": \"dist/runveric.mjs\"\n },\n \"main\": \"./dist/runveric.mjs\",\n \"files\": [\n \"dist\"\n ],\n \"scripts\": {\n \"build\": \"tsup && node -e \\\"require('fs').chmodSync('dist/runveric.mjs', 0o755)\\\"\",\n \"typecheck\": \"tsc -p tsconfig.json --noEmit && tsc -p tsconfig.vitest.json\",\n \"lint\": \"eslint src --max-warnings 0\",\n \"test\": \"vitest run\",\n \"prepublishOnly\": \"pnpm run build && pnpm run lint && pnpm run test\"\n },\n \"dependencies\": {\n \"yaml\": \"^2.8.1\"\n },\n \"devDependencies\": {\n \"@runveric/action-manifest\": \"workspace:*\",\n \"@runveric/contracts\": \"workspace:*\",\n \"@runveric/tsconfig\": \"workspace:*\",\n \"@types/node\": \"^22\",\n \"@typescript-eslint/eslint-plugin\": \"^7.18.0\",\n \"@typescript-eslint/parser\": \"^7.18.0\",\n \"eslint\": \"^8.57.0\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.5.4\",\n \"vitest\": \"^2.0.5\"\n },\n \"engines\": {\n \"node\": \">=22\"\n },\n \"license\": \"Apache-2.0\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/runveric/runveric.git\",\n \"directory\": \"packages/action-cli\"\n },\n \"homepage\": \"https://github.com/runveric/runveric/tree/develop/packages/action-cli#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/runveric/runveric/issues\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"keywords\": [\n \"runveric\",\n \"action\",\n \"automation\",\n \"cli\",\n \"powershell\",\n \"runbook\",\n \"azure\",\n \"devops\",\n \"sre\"\n ]\n}\n","import type { AuthoringFinding } from \"@runveric/action-manifest\";\nimport type { PackageResultV1, PackageRuntimeEvent } from \"@runveric/contracts\";\n\n/**\n * ─── WHAT AN AUTHOR SEES ────────────────────────────────────────────────────────────────\n *\n * The terminal output is the product here. `check` and `test` are only as useful as the thing\n * they print, and the rule for all of it is the same: show what an OPERATOR would see, plus\n * exactly the extra an author needs to fix it.\n *\n * Colour is applied only when stdout is a TTY and NO_COLOR is unset, so piping into a file or\n * a CI log yields plain text rather than escape sequences somebody has to strip.\n */\n\nconst useColour = process.stdout.isTTY === true && !process.env.NO_COLOR;\n\nconst paint = (code: string) => (text: string): string =>\n useColour ? `\u001b[${code}m${text}\u001b[0m` : text;\n\nexport const style = {\n bold: paint(\"1\"),\n dim: paint(\"2\"),\n red: paint(\"31\"),\n green: paint(\"32\"),\n yellow: paint(\"33\"),\n blue: paint(\"34\"),\n grey: paint(\"90\"),\n};\n\nexport function print(line = \"\"): void {\n process.stdout.write(`${line}\\n`);\n}\n\nexport function printError(line: string): void {\n process.stderr.write(`${line}\\n`);\n}\n\n/**\n * One finding, in the shape editors and humans both parse: `file:line:col message`, then the\n * fix on its own indented line. The fix is never omitted and never generic-only — it is the\n * part that makes the finding worth reading.\n */\nexport function printFinding(finding: AuthoringFinding): void {\n // ADVISORY IS SAID ON THE LINE, not left for the summary. It is still red and still called an\n // error — an author must not skim past it — and the parenthesis is the whole difference: this\n // one is a heuristic, so it will not stop a publish and does not need arguing with.\n const badge =\n finding.severity === \"error\"\n ? style.red(finding.advisory === true ? \"error (advisory)\" : \"error\")\n : style.yellow(\"warning\");\n const at =\n finding.line === undefined\n ? finding.file\n : `${finding.file}:${finding.line}:${finding.column ?? 1}`;\n print(` ${badge} ${style.bold(at)}`);\n print(` ${finding.message}`);\n print(` ${style.green(\"fix:\")} ${finding.fix}`);\n print(` ${style.grey(finding.rule)}`);\n print();\n}\n\n/** The one-line verdict, always printed, whether or not there were findings. */\nexport function printCheckSummary(counts: { errors: number; warnings: number }): void {\n if (counts.errors === 0 && counts.warnings === 0) {\n print(style.green(\"✓ No problems found.\"));\n return;\n }\n const parts: string[] = [];\n if (counts.errors > 0) parts.push(`${counts.errors} error${counts.errors === 1 ? \"\" : \"s\"}`);\n if (counts.warnings > 0) {\n parts.push(`${counts.warnings} warning${counts.warnings === 1 ? \"\" : \"s\"}`);\n }\n const summary = parts.join(\", \");\n print(counts.errors > 0 ? style.red(`✗ ${summary}.`) : style.yellow(`${summary}.`));\n}\n\n/** A runtime event, exactly as the execution log renders it. */\nexport function printEvent(event: PackageRuntimeEvent): void {\n const marker = {\n info: style.grey(\"·\"),\n warn: style.yellow(\"!\"),\n error: style.red(\"✗\"),\n success: style.green(\"✓\"),\n }[event.level];\n print(` ${marker} ${event.message}`);\n if (event.data) {\n print(` ${style.grey(JSON.stringify(event.data))}`);\n }\n}\n\n/**\n * The result, as an operator reads it: the status, the message, then the checks (validate) and\n * the outputs (run). Never a raw object dump — a package's result is a contract with named\n * parts, and printing it as JSON would make the author work out which part is which.\n */\nexport function printResult(result: PackageResultV1): void {\n const status = {\n succeeded: style.green(\"succeeded\"),\n failed: style.red(\"failed\"),\n cancelled: style.yellow(\"cancelled\"),\n }[result.status];\n print();\n print(`${style.bold(\"Result\")} ${status}`);\n print(` ${result.message}`);\n if (result.checks?.length) {\n print();\n print(` ${style.bold(\"Checks\")}`);\n for (const check of result.checks) {\n const marker = {\n passed: style.green(\"✓\"),\n warning: style.yellow(\"!\"),\n failed: style.red(\"✗\"),\n }[check.status];\n print(` ${marker} ${check.message}`);\n if (check.data) print(` ${style.grey(JSON.stringify(check.data))}`);\n }\n }\n if (result.outputs && Object.keys(result.outputs).length > 0) {\n print();\n print(` ${style.bold(\"Outputs\")}`);\n for (const [name, value] of Object.entries(result.outputs)) {\n print(` ${name} = ${JSON.stringify(value)}`);\n }\n }\n if (result.rollbackCapture && Object.keys(result.rollbackCapture).length > 0) {\n print();\n print(` ${style.bold(\"Rollback capture\")} ${style.grey(\"(what a rollback would read)\")}`);\n for (const [name, value] of Object.entries(result.rollbackCapture)) {\n print(` ${name} = ${JSON.stringify(value)}`);\n }\n }\n if (result.error) {\n print();\n print(` ${style.red(\"Error\")} ${result.error.code}`);\n print(` ${result.error.message}`);\n if (result.error.retryable !== undefined) {\n print(` ${style.grey(result.error.retryable ? \"retryable\" : \"not retryable\")}`);\n }\n }\n print();\n}\n","import { readFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport {\n actionPackageRefusal,\n CATALOG_ACTION_ARTIFACT_SCHEMA_V1,\n CATALOG_ACTION_ARTIFACT_SCHEMA_V2,\n} from \"@runveric/contracts\";\nimport { buildArtifact, defaultTag, parseRepository, provenance, pushArtifact, requireTag } from \"./artifact\";\nimport { parseCatalogFlags } from \"./flags\";\nimport { imageRefusal, parseImageReference } from \"./image\";\n\n/**\n * ═══ `runveric catalog publish-action` — PUBLISH ONE ACTION'S ARTIFACT (docs/121 §3.1, docs/127 §6) ═══\n *\n * Wraps one catalog manifest — its bytes VERBATIM — with `schemaVersion` and provenance, pushes it\n * as an immutable OCI artifact, and reports the digest THE REGISTRY reports for it. That digest is\n * what a catalog release names.\n *\n * ⚠ IT DOES NOT VALIDATE THE MANIFEST, AND NOTHING MAY RELY ON IT HAVING DONE SO. The server runs\n * THE validator on every artifact a release names, at plan, at pin and at sync. Publishing makes\n * an artifact AVAILABLE — only a pin makes anything live.\n *\n * ★ IT DOES REFUSE A PACKAGE NOT NAMED FOR ITS KEY, before the push (docs/127 §5) — the sentence\n * the server would refuse the release with later, said while the mistake is cheap. A convenience:\n * the server never trusts that it ran.\n *\n * ★ AND A `definition+version` MANIFEST IS PUBLISHED ONLY UNDER ITS OWN VERSION, so the tag a\n * person reads in the action repository and the version a run records cannot disagree. Without\n * `--tag` the version IS the tag; with one, it must equal `version:`. A `definition-only` manifest\n * carries no version, so its tag is a provenance label and anything is accepted (the UTC second by\n * default). This lived in the publish workflow as shell over `yq` until docs/127 A.1 — untested,\n * and a second YAML reader beside this one.\n *\n * ★ AN ENGINE ACTION IS PUBLISHED WITH `--image <repository>@<digest>` (docs/128 §20 G4): the image\n * its publish workflow just pushed, by digest. The artifact is then `catalog-action/v2` and carries\n * `image: { digest }` and nothing that names a repository — the image lives in the artifact's own\n * package (D2). Before anything is pushed it refuses: an image in any other repository; a manifest\n * declaring `execution` without `--image`, or `--image` for one declaring none (the server refuses\n * both kinds at plan); and an image the ONE rule refuses — another action's, another commit's, an\n * index, not linux/amd64 (`./image.ts`, `actionImageRefusal` in contracts).\n *\n * stdout, one line, for scripts: <key>=<repository>@<digest> — the line a release takes.\n * Everything else goes to stderr.\n */\n\nexport const PUBLISH_ACTION_USAGE =\n \"runveric catalog publish-action --manifest <file.yaml> --to <registry>/<namespace>/<repository>\\n\" +\n \" [--image <repository>@<digest>] [--tag <tag>]\\n\" +\n \" [--repository <source url>] [--commit <sha>]\";\n\nconst isMapping = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport async function runPublishAction(argv: readonly string[]): Promise<void> {\n const { single: flags } = parseCatalogFlags(argv, [\"manifest\", \"to\", \"image\", \"tag\", \"repository\", \"commit\"]);\n if (!flags.manifest || !flags.to) throw new Error(\"--manifest and --to are required.\");\n const repository = parseRepository(flags.to, \"--to\");\n const image = flags.image === undefined ? null : parseImageReference(flags.image, \"--image\");\n if (image !== null && image.repository.ref !== repository.ref) {\n throw new Error(\n `--image ${image.ref} is outside the artifact's repository ${repository.ref}. An engine action's ` +\n `image lives in its own package, so its artifact names it by digest alone (docs/128 §17.2 D2) — ` +\n `push the image to ${repository.ref}.`,\n );\n }\n const path = resolve(flags.manifest);\n const manifest = readFileSync(path, \"utf8\");\n\n // Read for the name check, the tag rule and the output line only. The manifest is published as\n // written, and the server is what validates it — at plan, pin and sync, every time.\n let parsed: unknown;\n try {\n parsed = parseYaml(manifest);\n } catch (cause) {\n throw new Error(`${flags.manifest} is not valid YAML. (${cause instanceof Error ? cause.message : String(cause)})`);\n }\n const fields: Record<string, unknown> = isMapping(parsed) ? parsed : {};\n const key = typeof fields.key === \"string\" && fields.key.length > 0 ? fields.key : null;\n if (key === null) throw new Error(`${flags.manifest} declares no top-level \\`key:\\` — is it a catalog manifest?`);\n const misnamed = actionPackageRefusal(key, repository.ref);\n if (misnamed !== null) throw new Error(`--to: ${misnamed}`);\n const executes = isMapping(fields.execution);\n if (executes && image === null) {\n throw new Error(\n `${flags.manifest} declares execution, so it is an engine action: publish it with --image ` +\n `<repository>@<digest>, the image its workflow built. Without one the server refuses it at plan.`,\n );\n }\n if (!executes && image !== null) {\n throw new Error(\n `${flags.manifest} declares no execution, so nothing would ever run --image ${image.ref}. A built-in ` +\n `action is published without one.`,\n );\n }\n\n let tag: string;\n if (fields.declares === \"definition+version\") {\n const version = typeof fields.version === \"string\" ? fields.version : null;\n if (version === null) throw new Error(`${flags.manifest} declares \"definition+version\" and no version:.`);\n if (flags.tag !== undefined && flags.tag !== version) {\n throw new Error(\n `${flags.manifest} declares version ${version}, and the tag is ${flags.tag}. Tag the commit ` +\n `${version}, or change version: in ${flags.manifest} first.`,\n );\n }\n tag = version;\n } else {\n tag = flags.tag ?? defaultTag();\n }\n requireTag(tag, flags.tag !== undefined ? \"--tag\" : `${flags.manifest}'s version`);\n\n const recorded = provenance(flags, dirname(path));\n if (image !== null) {\n const refusal = await imageRefusal(image, key, recorded);\n if (refusal !== null) throw new Error(`--image: ${refusal}`);\n }\n const artifact = buildArtifact(\n image === null\n ? { schemaVersion: CATALOG_ACTION_ARTIFACT_SCHEMA_V1, manifest, provenance: recorded }\n : { schemaVersion: CATALOG_ACTION_ARTIFACT_SCHEMA_V2, manifest, provenance: recorded, image: { digest: image.digest } },\n );\n\n const digest = await pushArtifact(repository, artifact, tag);\n process.stderr.write(`✓ ${key} published to ${repository.ref}:${tag}${image === null ? \"\" : `, naming the image ${image.digest}`}\\n`);\n process.stderr.write(` the registry reports ${digest} — the digest a release must name.\\n`);\n process.stdout.write(`${key}=${repository.ref}@${digest}\\n`);\n}\n","import { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport {\n ARTIFACT_DIGEST_PATTERN,\n ARTIFACT_REPOSITORY_PATTERN,\n CATALOG_ARTIFACT_MEDIA_TYPE,\n MANIFEST_MEDIA_TYPES,\n OCI_IMAGE_MANIFEST,\n type CatalogArtifactProvenance,\n} from \"@runveric/contracts\";\n\n/**\n * ═══ ONE CATALOG ARTIFACT, BUILT AND PUSHED — SHARED BY THE TWO PUBLISHING COMMANDS (docs/121) ═══\n *\n * `catalog publish-action` and `catalog publish-release` publish two different documents in ONE\n * wrapper: an OCI image manifest whose single layer is the document's bytes. The api's resolver\n * (`catalog-release-resolver.ts`) reads exactly this shape, and `catalog-release-publishing.spec.ts`\n * publishes with the BUILT CLI and resolves with that resolver, so a drift between the two is a\n * red suite rather than a release nobody can pin.\n *\n * ★ MOVED HERE FROM `tools/catalog-artifact.mjs` (docs/127 §6), which only the monorepo could run:\n * it `require`d `packages/contracts/dist` by path. The vocabulary — the schema identifiers, the\n * media type, the repository and digest grammar — is still read from @runveric/contracts, now\n * BUNDLED into this CLI (tsup.config.ts), so an action repository's workflow runs the same bytes.\n *\n * ★ THE DIGEST PRINTED IS THE REGISTRY'S, NOT OURS. A digest IS the sha256 of the stored bytes,\n * and anything between us and the registry that re-encodes a manifest makes it a different\n * digest. So after the push this asks the registry what the tag resolves to, reads\n * `Docker-Content-Digest`, refuses if that is not the digest of the bytes it sent, and reports\n * the registry's answer.\n *\n * ⛔ NO DOCKER CLIENT, NO KEYCHAIN. Plain HTTPS OCI. A credential is read only from GHCR_TOKEN —\n * or, in a workflow, GITHUB_TOKEN with `packages: write` — held in memory and never printed. A\n * loopback registry (`tools/oci-registry-dev.mjs`) is spoken to over plain HTTP; every other host\n * is HTTPS.\n *\n * ★ READS ARE BY DIGEST AND CHECKED (docs/128 §20 G3, G4). `catalog publish-action --image` and\n * `catalog verify-image` read an image and an artifact back: every manifest and blob is asked for by\n * its digest, and refused unless the bytes that arrived hash to it — the resolver's own rule. A read\n * asks only for a PULL token, so the catalog repository's workflow can read an action's public\n * package without asking to write it.\n */\n\nexport interface Repository {\n ref: string;\n host: string;\n path: string;\n /** Everything but the last segment — a release's actions must share it. */\n namespace: string;\n}\n\n/** A bare registry repository, or a refusal naming the flag it came from. */\nexport function parseRepository(ref: string, flag: string): Repository {\n if (!ARTIFACT_REPOSITORY_PATTERN.test(ref)) {\n throw new Error(\n `${flag} \"${ref}\" is not a bare registry repository (host[:port]/path, lowercase, no scheme, ` +\n `no tag, no digest). A catalog artifact is addressed by digest; tags are for humans.`,\n );\n }\n const cut = ref.indexOf(\"/\");\n return {\n ref,\n host: ref.slice(0, cut),\n path: ref.slice(cut + 1),\n namespace: ref.slice(0, ref.lastIndexOf(\"/\")),\n };\n}\n\nexport const isDigest = (value: string): boolean => ARTIFACT_DIGEST_PATTERN.test(value);\n\n/** The OCI distribution spec's tag grammar. A tag outside it fails at the registry, after blobs. */\nconst TAG_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$/;\n\n/** Refuse, before any network, a tag the registry would refuse halfway through a push. */\nexport function requireTag(tag: string, origin: string): void {\n if (!TAG_PATTERN.test(tag)) {\n throw new Error(\n `${origin} gives the tag \"${tag}\", which a registry cannot hold: letters, digits, \"_\", \".\" ` +\n `and \"-\", starting with a letter, digit or \"_\", at most 128 characters. Pass --tag.`,\n );\n }\n}\n\nconst LOOPBACK = /^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:[0-9]+)?$/;\nconst origin = (host: string): string => `${LOOPBACK.test(host) ? \"http\" : \"https\"}://${host}`;\nconst sha256 = (bytes: Uint8Array): string => `sha256:${createHash(\"sha256\").update(bytes).digest(\"hex\")}`;\n\n/** The OCI \"empty\" config — `{}` — which an artifact manifest names when it has no config. */\nconst EMPTY_CONFIG = Buffer.from(\"{}\");\nconst EMPTY_CONFIG_DESCRIPTOR = {\n mediaType: \"application/vnd.oci.empty.v1+json\",\n digest: sha256(EMPTY_CONFIG),\n size: EMPTY_CONFIG.length,\n};\n/** Every manifest type a read may receive — an index is RECEIVED and refused by name by its reader. */\nconst MANIFEST_ACCEPT = MANIFEST_MEDIA_TYPES.join(\", \");\n\nexport interface ProvenanceFlags {\n repository?: string;\n commit?: string;\n}\n\n/**\n * Provenance: the flags win; else GitHub Actions' environment (GITHUB_SERVER_URL/GITHUB_REPOSITORY\n * and GITHUB_SHA); else git in `dir`. A refusal when none of them can say: an artifact without\n * provenance is refused by the resolver, so it is refused here first rather than published\n * unreadable.\n */\nexport function provenance(flags: ProvenanceFlags, dir: string): CatalogArtifactProvenance {\n const git = (...args: string[]): string => {\n try {\n return execFileSync(\"git\", [\"-C\", dir, ...args], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n } catch {\n return \"\";\n }\n };\n const actions =\n process.env.GITHUB_SERVER_URL && process.env.GITHUB_REPOSITORY\n ? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`\n : \"\";\n const repository = flags.repository ?? (actions || git(\"remote\", \"get-url\", \"origin\"));\n const commit = flags.commit ?? (process.env.GITHUB_SHA || git(\"rev-parse\", \"HEAD\"));\n if (!repository || !commit) {\n throw new Error(\n \"Provenance is required and could not be determined. Pass --repository <url> and --commit \" +\n \"<sha> (in GitHub Actions, GITHUB_REPOSITORY and GITHUB_SHA supply them).\",\n );\n }\n return { repository, commit, publishedAt: new Date().toISOString() };\n}\n\nexport interface BuiltArtifact {\n documentBytes: Buffer;\n manifestBytes: Buffer;\n manifestDigest: string;\n}\n\n/** The document's bytes and the OCI manifest that names them — what will be pushed, exactly. */\nexport function buildArtifact<D extends { provenance: CatalogArtifactProvenance }>(document: D): BuiltArtifact {\n const documentBytes = Buffer.from(`${JSON.stringify(document, null, 2)}\\n`);\n const manifest = {\n schemaVersion: 2,\n mediaType: OCI_IMAGE_MANIFEST,\n artifactType: CATALOG_ARTIFACT_MEDIA_TYPE,\n config: EMPTY_CONFIG_DESCRIPTOR,\n layers: [\n { mediaType: CATALOG_ARTIFACT_MEDIA_TYPE, digest: sha256(documentBytes), size: documentBytes.length },\n ],\n /*\n * ★ SOURCE AND REVISION ARE FOR THE REGISTRY, NOT THE RESOLVER (docs/127 A.1). GHCR connects\n * a package to its repository through `org.opencontainers.image.source`, and that link is what\n * lets the repository's workflow token keep publishing to the package its first run created.\n * The resolver reads none of these — the document's own provenance is the record — so an\n * artifact published without them still resolves.\n */\n annotations: {\n \"org.opencontainers.image.created\": document.provenance.publishedAt,\n \"org.opencontainers.image.source\": document.provenance.repository,\n \"org.opencontainers.image.revision\": document.provenance.commit,\n },\n };\n const manifestBytes = Buffer.from(JSON.stringify(manifest));\n return { documentBytes, manifestBytes, manifestDigest: sha256(manifestBytes) };\n}\n\n// ── Talking to the registry ────────────────────────────────────────────────────────────\n\n/**\n * The Basic credential the token endpoint is asked with: GHCR_TOKEN (any username), else a\n * workflow's GITHUB_TOKEN as its actor — the pair GitHub documents for ghcr.io. Neither: no\n * credential, which a loopback registry accepts and ghcr.io refuses by name.\n */\nfunction basicCredential(): string | undefined {\n const pat = process.env.GHCR_TOKEN;\n if (pat) return Buffer.from(`x:${pat}`).toString(\"base64\");\n const workflow = process.env.GITHUB_TOKEN;\n if (workflow) return Buffer.from(`${process.env.GITHUB_ACTOR || \"x\"}:${workflow}`).toString(\"base64\");\n return undefined;\n}\n\n/** What a token is asked for: a read never asks to write. */\ntype Access = \"pull\" | \"pull,push\";\n\n/** Tokens by repository AND access — a pull token is never used to push. */\nconst tokens = new Map<string, string>();\n\nasync function token(repository: Repository, challenge: string | null, access: Access): Promise<string> {\n const field = (name: string): string | undefined =>\n new RegExp(`${name}=\"([^\"]*)\"`).exec(challenge ?? \"\")?.[1];\n const realm = field(\"realm\");\n if (!realm) throw new Error(`${repository.host} asked for credentials without a Bearer challenge.`);\n const url = new URL(realm);\n const service = field(\"service\");\n if (service) url.searchParams.set(\"service\", service);\n url.searchParams.set(\"scope\", `repository:${repository.path}:${access}`);\n const credential = basicCredential();\n const answer = await fetch(url, {\n headers: credential ? { Authorization: `Basic ${credential}` } : {},\n });\n if (!answer.ok) {\n throw new Error(\n `${repository.host} refused a ${access === \"pull\" ? \"pull\" : \"push\"} token for ${repository.path}: HTTP ${answer.status}` +\n (credential || access === \"pull\"\n ? \".\"\n : \" — set GHCR_TOKEN to a token with write:packages, or in a workflow GITHUB_TOKEN with packages: write.\"),\n );\n }\n const body = (await answer.json()) as { token?: string; access_token?: string };\n const value = body.token ?? body.access_token ?? \"\";\n tokens.set(`${repository.path} ${access}`, value);\n return value;\n}\n\nasync function call(\n repository: Repository,\n method: string,\n path: string,\n { headers = {}, body, access = \"pull,push\" }: { headers?: Record<string, string>; body?: Uint8Array; access?: Access } = {},\n): Promise<Response> {\n const url = path.startsWith(\"http\") ? path : `${origin(repository.host)}/v2/${repository.path}/${path}`;\n const send = (bearer: string | undefined): Promise<Response> =>\n fetch(url, {\n method,\n body,\n redirect: \"follow\",\n headers: { ...headers, ...(bearer ? { Authorization: `Bearer ${bearer}` } : {}) },\n });\n let answer = await send(tokens.get(`${repository.path} ${access}`));\n if (answer.status === 401) answer = await send(await token(repository, answer.headers.get(\"www-authenticate\"), access));\n return answer;\n}\n\nasync function pushBlob(repository: Repository, bytes: Buffer): Promise<string> {\n const digest = sha256(bytes);\n if ((await call(repository, \"HEAD\", `blobs/${digest}`)).ok) return digest;\n const started = await call(repository, \"POST\", \"blobs/uploads/\");\n if (started.status !== 202) throw new Error(`${repository.host} refused an upload: HTTP ${started.status}`);\n const location = new URL(started.headers.get(\"location\") ?? \"\", `${origin(repository.host)}/`);\n location.searchParams.set(\"digest\", digest);\n const put = await call(repository, \"PUT\", location.toString(), {\n headers: { \"Content-Type\": \"application/octet-stream\", \"Content-Length\": String(bytes.length) },\n body: bytes,\n });\n if (put.status !== 201) throw new Error(`${repository.host} rejected blob ${digest}: HTTP ${put.status} ${await put.text()}`);\n return digest;\n}\n\n/** Does the registry hold a manifest at this digest? Read before naming it in a release. */\nexport async function manifestExists(repository: Repository, digest: string): Promise<boolean> {\n const answer = await call(repository, \"HEAD\", `manifests/${digest}`, { headers: { Accept: OCI_IMAGE_MANIFEST } });\n return answer.ok;\n}\n\n/**\n * The bytes at `<repository>@<digest>` — a manifest or a blob — refused unless they hash to `digest`\n * (and, for a blob whose size is known, are that size). A digest this code did not compute is not\n * a pin.\n */\nasync function readVerified(\n repository: Repository,\n kind: \"manifests\" | \"blobs\",\n digest: string,\n size: number | null = null,\n): Promise<Buffer> {\n if (!isDigest(digest)) throw new Error(`\"${digest}\" is not a digest, so ${repository.ref} cannot be asked for it.`);\n const answer = await call(repository, \"GET\", `${kind}/${digest}`, {\n access: \"pull\",\n headers: kind === \"manifests\" ? { Accept: MANIFEST_ACCEPT } : {},\n });\n if (!answer.ok) {\n throw new Error(`${repository.ref}@${digest} could not be read: HTTP ${answer.status}${answer.status === 404 ? \" — it is not in the registry\" : \"\"}.`);\n }\n const bytes = Buffer.from(await answer.arrayBuffer());\n const served = sha256(bytes);\n if (served !== digest || (size !== null && bytes.length !== size)) {\n throw new Error(\n `${repository.host} served ${bytes.length} bytes hashing to ${served} for ${repository.ref}@${digest}` +\n `${size === null ? \"\" : ` (${size} bytes named)`}. Refused: a digest this command did not compute is not a pin.`,\n );\n }\n return bytes;\n}\n\n/** A manifest by digest, its bytes checked. */\nexport const readManifest = (repository: Repository, digest: string): Promise<Buffer> =>\n readVerified(repository, \"manifests\", digest);\n\n/** A blob by digest, its bytes and size checked. */\nexport const readBlob = (repository: Repository, digest: string, size: number): Promise<Buffer> =>\n readVerified(repository, \"blobs\", digest, size);\n\n/** UTF-8 JSON, or a refusal naming what it was. */\nexport function parseJsonBytes(bytes: Uint8Array, what: string): unknown {\n try {\n return JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n } catch (cause) {\n throw new Error(`${what} is not UTF-8 JSON. (${cause instanceof Error ? cause.message : String(cause)})`);\n }\n}\n\n/**\n * The document a catalog artifact carries — the one layer of the wrapper `buildArtifact` writes —\n * read by digest, every byte checked. The resolver is what validates it; this is read to find the\n * image an engine action's artifact names, before that image is signed.\n */\nexport async function readArtifactDocument(repository: Repository, digest: string): Promise<unknown> {\n const what = `${repository.ref}@${digest}`;\n const manifest = parseJsonBytes(await readManifest(repository, digest), `the manifest of ${what}`) as {\n mediaType?: unknown;\n layers?: { mediaType?: unknown; digest?: unknown; size?: unknown }[];\n } | null;\n const layers = Array.isArray(manifest?.layers) ? manifest.layers : [];\n const layer = layers[0];\n if (\n manifest?.mediaType !== OCI_IMAGE_MANIFEST ||\n layers.length !== 1 ||\n layer?.mediaType !== CATALOG_ARTIFACT_MEDIA_TYPE ||\n typeof layer.digest !== \"string\" ||\n typeof layer.size !== \"number\"\n ) {\n throw new Error(`${what} is not a catalog artifact: expected one OCI manifest with exactly one ${CATALOG_ARTIFACT_MEDIA_TYPE} layer.`);\n }\n return parseJsonBytes(await readBlob(repository, layer.digest, layer.size), `the document of ${what}`);\n}\n\n/**\n * Push an artifact and return the digest THE REGISTRY reports for what it stored.\n *\n * The manifest is PUT by digest — content-addressed, so nothing mutable decides what lands — and\n * then under `tag`, for humans and for the \"ask the registry\" step. Nothing reads a tag back to\n * resolve anything.\n */\nexport async function pushArtifact(repository: Repository, artifact: BuiltArtifact, tag: string): Promise<string> {\n await pushBlob(repository, EMPTY_CONFIG);\n await pushBlob(repository, artifact.documentBytes);\n for (const reference of [artifact.manifestDigest, tag]) {\n const put = await call(repository, \"PUT\", `manifests/${reference}`, {\n headers: { \"Content-Type\": OCI_IMAGE_MANIFEST },\n body: artifact.manifestBytes,\n });\n if (put.status !== 201) {\n throw new Error(`${repository.host} rejected the manifest (${reference}): HTTP ${put.status} ${await put.text()}`);\n }\n }\n const asked = await call(repository, \"HEAD\", `manifests/${tag}`, { headers: { Accept: OCI_IMAGE_MANIFEST } });\n const reported = asked.headers.get(\"docker-content-digest\");\n if (!asked.ok || !reported) {\n throw new Error(`${repository.host} could not say what :${tag} resolves to (HTTP ${asked.status}).`);\n }\n if (reported !== artifact.manifestDigest) {\n throw new Error(\n `${repository.host} reports :${tag} as ${reported}, but the bytes sent hash to ` +\n `${artifact.manifestDigest}. Something re-encoded the manifest; nothing printed here would ` +\n `name what is stored. Refusing to report a digest.`,\n );\n }\n return reported;\n}\n\n/** One tag per publish, unless given: the UTC second it was published. For humans only. */\nexport const defaultTag = (): string =>\n new Date().toISOString().replace(/[-:]/g, \"\").replace(/\\..*$/, \"\").toLowerCase();\n","/**\n * `--flag value` (or `--flag=value`) pairs; repeated flags collected; anything unrecognised is\n * refused. Stricter than the authoring verbs' parser in `main.ts`, on purpose and as before\n * (`tools/catalog-artifact.mjs`): a misspelt `--tga` on a command that pushes to a public registry\n * must stop it, not be ignored.\n */\nexport function parseCatalogFlags<K extends string>(\n argv: readonly string[],\n known: readonly K[],\n repeated: readonly K[] = [],\n): { single: Partial<Record<K, string>>; many: Partial<Record<K, string[]>> } {\n const single: Partial<Record<K, string>> = {};\n const many: Partial<Record<K, string[]>> = {};\n for (let index = 0; index < argv.length; index += 1) {\n const argument = argv[index]!;\n const separator = argument.indexOf(\"=\");\n const name = (separator === -1 ? argument.slice(2) : argument.slice(2, separator)) as K;\n if (!argument.startsWith(\"--\") || !known.includes(name)) throw new Error(`Unknown argument: ${argument}`);\n let value: string | undefined;\n if (separator !== -1) {\n value = argument.slice(separator + 1);\n } else {\n value = argv[index + 1];\n index += 1;\n }\n if (value === undefined || value === \"\" || value.startsWith(\"--\")) throw new Error(`--${name} needs a value.`);\n if (repeated.includes(name)) (many[name] ??= []).push(value);\n else single[name] = value;\n }\n return { single, many };\n}\n","import {\n actionImageRefusal,\n imageConfigDescriptor,\n MAX_IMAGE_MANIFEST_BYTES,\n type ActionImageProvenance,\n} from \"@runveric/contracts\";\nimport { isDigest, parseJsonBytes, parseRepository, readBlob, readManifest, type Repository } from \"./artifact\";\n\n/**\n * ═══ AN ENGINE ACTION'S IMAGE, JUDGED BY THE ONE RULE (docs/128 §17.4a, §20 G3) ═══════════════════\n *\n * `catalog publish-action --image` asks this before an artifact may NAME an image, and `catalog\n * verify-image` before the release workflow may SIGN one. Both read the image the way the api's\n * resolver does — the manifest by its digest, then the config its descriptor names, every byte\n * hashed — and hand what the bytes say to `actionImageRefusal` in @runveric/contracts: the function\n * the resolver calls at plan, pin, sync and vendor, bundled here as the same compiled code. So a\n * refusal here is the sentence the server would refuse the release with, said before anything is\n * published or signed.\n *\n * ⛔ NO RULE OF ITS OWN. Nothing here compares a label, a platform or a commit; `action-image-rule-is-\n * one-function.spec.ts` holds this file and the resolver to that, and to the same sentences.\n */\n\nexport interface ImageReference {\n repository: Repository;\n digest: string;\n /** `<repository>@<digest>`, as a release, cosign and every sentence write it. */\n ref: string;\n}\n\n/** `<repository>@<digest>` — a digest, never a tag — or a refusal naming where it came from. */\nexport function parseImageReference(value: string, origin: string): ImageReference {\n const at = value.lastIndexOf(\"@\");\n const digest = at === -1 ? \"\" : value.slice(at + 1);\n if (at === -1 || !isDigest(digest)) {\n throw new Error(\n `${origin} \"${value}\" is not <repository>@<digest>. An engine action's image is named by its ` +\n `digest — sha256: and 64 lowercase hex — never by a tag, which a registry can repoint.`,\n );\n }\n const repository = parseRepository(value.slice(0, at), origin);\n return { repository, digest, ref: `${repository.ref}@${digest}` };\n}\n\n/** Why `image` cannot run under action `key`'s manifest, published with `provenance` — or `null`. */\nexport async function imageRefusal(\n image: ImageReference,\n key: string,\n provenance: ActionImageProvenance,\n): Promise<string | null> {\n const manifestBytes = await readManifest(image.repository, image.digest);\n if (manifestBytes.length > MAX_IMAGE_MANIFEST_BYTES) {\n return `the image manifest of ${image.ref} is ${manifestBytes.length} bytes; the limit is ${MAX_IMAGE_MANIFEST_BYTES}.`;\n }\n const manifest = parseJsonBytes(manifestBytes, `the image manifest of ${image.ref}`);\n // An index names no config, so nothing is fetched for it: the rule refuses it by name.\n const descriptor = imageConfigDescriptor(manifest);\n const config =\n descriptor === null\n ? null\n : parseJsonBytes(\n await readBlob(image.repository, descriptor.digest, descriptor.size),\n `the image config of ${image.ref}`,\n );\n return actionImageRefusal({ key, image: image.ref, manifest, config, provenance });\n}\n","import { readFileSync } from \"node:fs\";\nimport { parse as parseYaml } from \"yaml\";\nimport {\n actionPackageRefusal,\n CATALOG_RELEASE_SCHEMA_V1,\n parseCatalogReleaseSpec,\n type CatalogReleaseSpecAction,\n} from \"@runveric/contracts\";\nimport {\n buildArtifact,\n defaultTag,\n isDigest,\n manifestExists,\n parseRepository,\n provenance,\n pushArtifact,\n requireTag,\n} from \"./artifact\";\nimport { parseCatalogFlags } from \"./flags\";\n\n/**\n * ═══ `runveric catalog publish-release` — ASSEMBLE AND PUBLISH A CATALOG RELEASE (docs/121 §3.1, docs/127 §6) ═══\n *\n * A catalog release is one immutable artifact naming each action artifact BY DIGEST. This writes\n * that document, pushes it, and reports the digest THE REGISTRY reports. Pinning that digest is\n * the only step that makes anything live.\n *\n * The actions come from `--from release.yaml` (the catalog repository's file, docs/127 §4.1) or\n * from repeated `--action <key>=<repository>@<digest>` flags — never both — and every entry gets\n * the same refusals either way, before anything is pushed:\n *\n * an action outside the release's namespace a duplicate key a tag where a digest belongs\n * a package not named for its key (docs/127 §5) a digest the registry lacks\n *\n * It does not validate manifests — the server does that, on every artifact, every time.\n *\n * ★ FROM release.yaml, THE TAG IS THE RELEASE'S OWN VERSION LABEL unless `--tag` says otherwise\n * (docs/127 A.1), so the catalog repository's workflow passes no tag and reads no YAML of its own.\n * The tag is for humans; nothing ever resolves by it. With `--action` flags it stays the UTC second.\n *\n * stdout, one line: <repository>@<digest> — the release to plan and pin.\n */\n\nexport const PUBLISH_RELEASE_USAGE =\n \"runveric catalog publish-release (--from <release.yaml> | --action <key>=<repository>@<digest> …)\\n\" +\n \" --to <registry>/<namespace>/<repository> [--version <label>]\\n\" +\n \" [--tag <tag>] [--repository <source url>] [--commit <sha>]\";\n\ninterface Entry extends CatalogReleaseSpecAction {\n /** How a refusal names where the entry came from: `--action <key>` or `release.yaml's <key>`. */\n label: string;\n}\n\n/** `--action` values, parsed as before: `<key>=<repository>@<digest>`. */\nfunction entriesFromFlags(values: readonly string[]): Entry[] {\n return values.map((value) => {\n const match = /^([^=]+)=([^@]+)@(.+)$/.exec(value);\n if (!match) throw new Error(`--action \"${value}\" is not <key>=<repository>@<digest>.`);\n const [, key = \"\", artifactRef = \"\", digest = \"\"] = match;\n return { key, artifactRef, digest, label: `--action ${key}` };\n });\n}\n\nfunction specFromFile(path: string): { version: string; entries: Entry[] } {\n let value: unknown;\n try {\n value = parseYaml(readFileSync(path, \"utf8\"));\n } catch (cause) {\n throw new Error(`--from ${path} could not be read as YAML. (${cause instanceof Error ? cause.message : String(cause)})`);\n }\n const spec = parseCatalogReleaseSpec(value);\n return {\n version: spec.version,\n entries: spec.actions.map((action) => ({ ...action, label: `${path}'s ${action.key}` })),\n };\n}\n\nexport async function runPublishRelease(argv: readonly string[]): Promise<void> {\n const { single: flags, many } = parseCatalogFlags(\n argv,\n [\"to\", \"version\", \"action\", \"from\", \"tag\", \"repository\", \"commit\"],\n [\"action\"],\n );\n const actionFlags = many.action ?? [];\n if (flags.from !== undefined && actionFlags.length > 0) {\n throw new Error(\"--from and --action are alternatives: name the release's actions in release.yaml or as flags, not both.\");\n }\n if (flags.from !== undefined && flags.version !== undefined) {\n throw new Error(\"--version is read from release.yaml when --from is given; pass one or the other.\");\n }\n if (!flags.to || (flags.from === undefined && (!flags.version || actionFlags.length === 0))) {\n throw new Error(\"--to and either --from, or --version and at least one --action, are required.\");\n }\n const release = parseRepository(flags.to, \"--to\");\n const { version, entries } =\n flags.from !== undefined\n ? specFromFile(flags.from)\n : { version: flags.version!, entries: entriesFromFlags(actionFlags) };\n\n const tag = flags.tag ?? (flags.from !== undefined ? version : defaultTag());\n requireTag(tag, flags.tag !== undefined ? \"--tag\" : `${flags.from}'s version`);\n\n const seen = new Set<string>();\n const actions = entries.map((entry) => {\n if (seen.has(entry.key)) throw new Error(`${entry.label} names \"${entry.key}\" twice.`);\n seen.add(entry.key);\n const repository = parseRepository(entry.artifactRef, entry.label);\n if (repository.namespace !== release.namespace) {\n throw new Error(\n `${entry.label} lives in \"${repository.namespace}\", outside the release's namespace ` +\n `\"${release.namespace}\". The server refuses a release that sends it to another host or org.`,\n );\n }\n if (!isDigest(entry.digest)) {\n throw new Error(`${entry.label}: \"${entry.digest}\" is not a digest. A release names artifacts by digest only.`);\n }\n const misnamed = actionPackageRefusal(entry.key, entry.artifactRef);\n if (misnamed !== null) throw new Error(`${entry.label}: ${misnamed}`);\n return { ...entry, repository };\n });\n\n for (const action of actions) {\n if (!(await manifestExists(action.repository, action.digest))) {\n throw new Error(`${action.artifactRef}@${action.digest} (${action.key}) is not in the registry.`);\n }\n }\n\n const artifact = buildArtifact({\n schemaVersion: CATALOG_RELEASE_SCHEMA_V1,\n version,\n provenance: provenance(flags, process.cwd()),\n actions: actions.map(({ key, artifactRef, digest }) => ({ key, artifactRef, digest })),\n });\n\n const digest = await pushArtifact(release, artifact, tag);\n process.stderr.write(\n `✓ catalog release ${version} (${actions.length} action artifact(s)) published to ${release.ref}:${tag}\\n`,\n );\n process.stderr.write(` the registry reports ${digest} — the digest to plan and pin.\\n`);\n process.stdout.write(`${release.ref}@${digest}\\n`);\n}\n","import { readFileSync } from \"node:fs\";\nimport { parse as parseYaml } from \"yaml\";\nimport {\n actionPackageRefusal,\n actionSourceRepository,\n CATALOG_ACTION_ARTIFACT_SCHEMA_V1,\n CATALOG_ACTION_ARTIFACT_SCHEMA_V2,\n parseCatalogReleaseSpec,\n type ActionImageProvenance,\n} from \"@runveric/contracts\";\nimport { isDigest, parseRepository, readArtifactDocument } from \"./artifact\";\nimport { parseCatalogFlags } from \"./flags\";\nimport { imageRefusal, parseImageReference, type ImageReference } from \"./image\";\n\n/**\n * ═══ `runveric catalog verify-image` — WHAT THE RELEASE WORKFLOW MAY SIGN (docs/128 §20 G5) ═══════\n *\n * The catalog release workflow signs an engine action's image with our Key Vault key; this is the\n * gate in front of that. It runs the ONE rule over the image in the registry (`./image.ts`,\n * `actionImageRefusal` in contracts) — one linux/amd64 image, built in the action's own repository,\n * at the commit its artifact was published from — and prints, one per line on stdout, each image\n * that passed: `<repository>@<digest>`, exactly what cosign is then handed. An image that fails is\n * refused with the server's own sentence, exit 1, and the workflow signs nothing and releases nothing.\n *\n * verify-image <repository>@<digest> --key <action key> --commit <sha>\n * One image, judged as published from <sha> in the action's own repository.\n *\n * verify-image --from release.yaml\n * Every ENGINE action the release names: each artifact is read by its digest, and its image is\n * judged against the key the release gives it and the provenance the artifact records — so the\n * commit is the artifact's own, never one a workflow typed. A built-in (v1) has no image and\n * prints nothing. ★ The `--from` form exists because §20 G5 signs \"each engine action\n * release.yaml names\", and the single-image form cannot find them; it is the same check, looped.\n *\n * ⚠ VERIFYING IS NOT SIGNING, AND NOT TRUSTING. The server judges every image again at plan, pin and\n * sync — this only keeps our key off an image the server would refuse.\n */\n\nexport const VERIFY_IMAGE_USAGE =\n \"runveric catalog verify-image (<repository>@<digest> --key <action key> --commit <sha> | --from <release.yaml>)\";\n\nconst COMMIT = /^[0-9a-f]{40}$/;\n\ninterface Candidate {\n key: string;\n image: ImageReference;\n provenance: ActionImageProvenance;\n label: string;\n}\n\nconst isMapping = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** The single-image form: the key names the repository the image must say it was built in. */\nfunction single(value: string, flags: Partial<Record<\"key\" | \"commit\", string>>): Candidate {\n if (!flags.key || !flags.commit) throw new Error(`verify-image ${value} needs --key <action key> and --commit <sha>.`);\n if (!COMMIT.test(flags.commit)) throw new Error(`--commit \"${flags.commit}\" is not a 40-hex commit.`);\n const image = parseImageReference(value, \"verify-image\");\n const misnamed = actionPackageRefusal(flags.key, image.repository.ref);\n if (misnamed !== null) throw new Error(misnamed);\n return {\n key: flags.key,\n image,\n provenance: { repository: actionSourceRepository(flags.key), commit: flags.commit },\n label: `--key ${flags.key}`,\n };\n}\n\n/** The `--from` form: every engine action the release names, as its artifact records it. */\nasync function fromRelease(path: string): Promise<Candidate[]> {\n let value: unknown;\n try {\n value = parseYaml(readFileSync(path, \"utf8\"));\n } catch (cause) {\n throw new Error(`--from ${path} could not be read as YAML. (${cause instanceof Error ? cause.message : String(cause)})`);\n }\n const candidates: Candidate[] = [];\n for (const action of parseCatalogReleaseSpec(value).actions) {\n const label = `${path}'s ${action.key}`;\n const misnamed = actionPackageRefusal(action.key, action.artifactRef);\n if (misnamed !== null) throw new Error(`${label}: ${misnamed}`);\n if (!isDigest(action.digest)) throw new Error(`${label}: \"${action.digest}\" is not a digest.`);\n const repository = parseRepository(action.artifactRef, label);\n const read = await readArtifactDocument(repository, action.digest);\n const document: Record<string, unknown> = isMapping(read) ? read : {};\n const schemaVersion = document.schemaVersion;\n if (schemaVersion === CATALOG_ACTION_ARTIFACT_SCHEMA_V1) continue;\n if (schemaVersion !== CATALOG_ACTION_ARTIFACT_SCHEMA_V2) {\n throw new Error(\n `${label}: ${repository.ref}@${action.digest} declares schemaVersion ${JSON.stringify(schemaVersion)}; ` +\n `this CLI reads ${CATALOG_ACTION_ARTIFACT_SCHEMA_V1} and ${CATALOG_ACTION_ARTIFACT_SCHEMA_V2}.`,\n );\n }\n const image = isMapping(document.image) ? document.image.digest : undefined;\n const recorded = isMapping(document.provenance) ? document.provenance : {};\n if (typeof image !== \"string\" || typeof recorded.repository !== \"string\" || typeof recorded.commit !== \"string\") {\n throw new Error(`${label}: its ${CATALOG_ACTION_ARTIFACT_SCHEMA_V2} artifact carries no image digest or no provenance.`);\n }\n candidates.push({\n key: action.key,\n // ★ The image lives in the artifact's own package (D2) — the artifact names a digest, never a place.\n image: parseImageReference(`${repository.ref}@${image}`, label),\n provenance: { repository: recorded.repository, commit: recorded.commit },\n label,\n });\n }\n return candidates;\n}\n\nexport async function runVerifyImage(argv: readonly string[]): Promise<void> {\n // The image, when given, comes first; anything else that is not a flag is refused by the parser.\n const image = argv[0] !== undefined && !argv[0].startsWith(\"--\") ? argv[0] : undefined;\n const { single: flags } = parseCatalogFlags(image === undefined ? argv : argv.slice(1), [\"key\", \"commit\", \"from\"]);\n if (image !== undefined && flags.from !== undefined) {\n throw new Error(\"An image and --from are alternatives: verify one image, or every engine action release.yaml names.\");\n }\n if (image === undefined && flags.from === undefined) {\n throw new Error(`Name an image or a release. Usage: ${VERIFY_IMAGE_USAGE}`);\n }\n if (flags.from !== undefined && (flags.key !== undefined || flags.commit !== undefined)) {\n throw new Error(\"--key and --commit are read from each artifact when --from is given; pass one or the other.\");\n }\n\n const candidates = image !== undefined ? [single(image, flags)] : await fromRelease(flags.from!);\n for (const candidate of candidates) {\n const refusal = await imageRefusal(candidate.image, candidate.key, candidate.provenance);\n if (refusal !== null) throw new Error(`${candidate.label}: ${refusal} Nothing was signed.`);\n }\n for (const candidate of candidates) {\n process.stderr.write(`✓ ${candidate.key}: ${candidate.image.ref} — built in ${candidate.provenance.repository} at ${candidate.provenance.commit}\\n`);\n process.stdout.write(`${candidate.image.ref}\\n`);\n }\n if (candidates.length === 0) process.stderr.write(`✓ ${flags.from} names no engine action — no image to sign.\\n`);\n}\n","import { printError } from \"../report\";\nimport { PUBLISH_ACTION_USAGE, runPublishAction } from \"./publish-action\";\nimport { PUBLISH_RELEASE_USAGE, runPublishRelease } from \"./publish-release\";\nimport { runVerifyImage, VERIFY_IMAGE_USAGE } from \"./verify-image\";\n\n/**\n * ═══ `runveric catalog` — PUBLISHING FIRST-PARTY CATALOG CONTENT (docs/127 §6) ═══════════\n *\n * Not one of the four authoring verbs, and deliberately set apart from them: those author a\n * customer's ACTION PACKAGE; these publish the artifacts the product's own catalog is pinned from\n * — one action's manifest (with its image, for an engine action), a release naming actions by\n * digest — and judge an engine action's image before the release workflow signs it. They run in the action and\n * catalog repositories' workflows (`npx @<scope>/cli@<exact version> catalog …`), which is why\n * they live in the published CLI rather than in this monorepo's `tools/`.\n *\n * A refusal is one `✗` line on stderr and exit 1, exactly as the scripts it replaced did.\n */\n\nexport const CATALOG_USAGE = `runveric catalog — publish first-party catalog artifacts (docs/127)\n\n ${PUBLISH_ACTION_USAGE}\n Publish one action's manifest, verbatim, as an artifact — with --image, an engine action's\n artifact naming its image by digest. stdout: <key>=<repository>@<digest>\n\n ${PUBLISH_RELEASE_USAGE}\n Publish a release naming each action artifact by digest. stdout: <repository>@<digest>\n\n ${VERIFY_IMAGE_USAGE}\n Judge an engine action's image by the server's rule before it is signed.\n stdout: one <repository>@<digest> per image that passed\n\n Credentials: GHCR_TOKEN (write:packages), or in a workflow GITHUB_TOKEN with packages: write.\n Provenance: --repository/--commit, else GITHUB_SERVER_URL/GITHUB_REPOSITORY and GITHUB_SHA, else git.`;\n\nconst SUBCOMMANDS: Record<string, (argv: readonly string[]) => Promise<void>> = {\n \"publish-action\": runPublishAction,\n \"publish-release\": runPublishRelease,\n \"verify-image\": runVerifyImage,\n};\n\nexport async function runCatalog(argv: readonly string[]): Promise<number> {\n const [subcommand, ...rest] = argv;\n if (subcommand === undefined || subcommand === \"--help\" || rest.includes(\"--help\")) {\n process.stdout.write(`${CATALOG_USAGE}\\n`);\n return subcommand === undefined ? 1 : 0;\n }\n const run = SUBCOMMANDS[subcommand];\n if (run === undefined) {\n printError(`✗ \"catalog ${subcommand}\" is not a command. There are ${Object.keys(SUBCOMMANDS).length}: ${Object.keys(SUBCOMMANDS).join(\", \")}.`);\n return 1;\n }\n try {\n await run(rest);\n return 0;\n } catch (error) {\n printError(`✗ ${error instanceof Error ? error.message : String(error)}`);\n return 1;\n }\n}\n","import { resolve } from \"node:path\";\nimport { checkActionPackage } from \"@runveric/action-manifest\";\nimport { readPackageDirectory } from \"./package-dir\";\nimport { print, printCheckSummary, printError, printFinding, style } from \"./report\";\nimport { BRAND_SHORT_NAME } from \"@runveric/contracts\";\n\n/**\n * ─── `runveric check` ───────────────────────────────────────────────────────────────\n *\n * Offline. No network, no Opera, no cloud, no account.\n *\n * It runs `checkActionPackage` from @runveric/action-manifest — the SAME call the import path and\n * the in-app publish path make, not a local re-implementation of it. That is the whole promise\n * of this command: import never rejects something `check` accepted. `check-agrees-with-import`\n * in the API test suite drives a shared fixture corpus through both and fails if it ever stops\n * being true.\n *\n * WHAT IT DOES NOT CLAIM. Three things about a package depend on the DEPLOYMENT, not the\n * package: whether the runner there ships the declared interpreter, whether it can broker\n * egress, and whether organization-package sandboxing is on. A laptop cannot know any of them,\n * so `check` does not pretend to — and says so, rather than leaving the author to discover the\n * gap the first time an import is refused for a reason `check` never mentioned.\n */\n\nexport interface CheckOptions {\n directory?: string;\n /**\n * Exit non-zero on warnings and advisory errors too. For CI, where a warning nobody reads is\n * a warning — and where a team that wants the heuristic rules to gate can have that, without\n * imposing it on the author whose package the heuristic is wrong about.\n */\n strict?: boolean;\n}\n\nexport async function runCheck(options: CheckOptions): Promise<number> {\n const directory = resolve(options.directory ?? \".\");\n let files;\n try {\n files = await readPackageDirectory(directory);\n } catch (error) {\n printError(style.red(error instanceof Error ? error.message : String(error)));\n return 1;\n }\n\n const report = checkActionPackage(files);\n\n print();\n print(`${style.bold(\"check\")} ${style.grey(directory)}`);\n print();\n for (const finding of report.findings) printFinding(finding);\n printCheckSummary({ errors: report.errorCount, warnings: report.warningCount });\n\n // The two verdicts are reported SEPARATELY, because they are different facts and collapsing\n // them is how a tool starts lying. `ok` is \"Opera would accept this\"; `lintBlocked` is\n // \"Opera would accept this and it would then misbehave\" — which is the `$Name?` shape, and\n // the more dangerous of the two precisely because import says nothing about it.\n if (!report.validation.ok) {\n print();\n print(style.red(\"This package would be REFUSED at import.\"));\n } else if (report.lintBlocked) {\n print();\n print(\n style.red(\"This package would be ACCEPTED at import — and then misbehave.\") +\n ` The errors above are not things ${BRAND_SHORT_NAME} checks; they are things that go wrong at run ` +\n \"time, silently.\",\n );\n }\n // Said separately from the two verdicts above, and never instead of them. An advisory error\n // is a real problem reported by a rule that could be wrong, so the author is told both facts:\n // what it found, and that nothing here will stop them.\n if (report.advisoryCount > 0) {\n print();\n print(\n style.red(\n `${report.advisoryCount} of the errors above ${\n report.advisoryCount === 1 ? \"is\" : \"are\"\n } ADVISORY.`,\n ) +\n \" They are found by a text search that cannot be certain, so they do not refuse a \" +\n \"publish — `check --strict` does, if you want the gate.\",\n );\n }\n\n if (report.validation.ok && !report.lintBlocked) {\n print();\n print(\n style.grey(\n \"Not checked here (they depend on the deployment, not the package): whether its \" +\n \"runner ships your interpreter, whether it can broker outbound network, and whether \" +\n \"organization packages are enabled. Those are answered at import.\",\n ),\n );\n print();\n print(`Next: ${style.bold(\"runveric test --phase run\")}`);\n }\n print();\n\n const strictFailure =\n options.strict === true && (report.warningCount > 0 || report.advisoryCount > 0);\n const failed = !report.validation.ok || report.lintBlocked || strictFailure;\n return failed ? 1 : 0;\n}\n","import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join, relative, sep } from \"node:path\";\n\n/**\n * Reading an action package off disk.\n *\n * The result is the same `path → Buffer` map the server builds from a Git archive, with\n * FORWARD SLASHES on every platform. That is not cosmetic: `entrypoint: run/` is compared\n * against these keys, and on Windows a backslash would make a perfectly good package look like\n * it has no entrypoint — a defect that only ever appears on the machines we do not develop on.\n */\n\n/** Directories never part of a package. Skipped whole, so a stray node_modules cannot hash in. */\nconst IGNORED_DIRECTORIES = new Set([\n \".git\",\n \".runveric\",\n \"node_modules\",\n \".venv\",\n \"__pycache__\",\n \".DS_Store\",\n]);\n\n/** A ceiling on what `check` and `publish` will read, so a mistyped path is not a hang. */\nconst MAX_FILES = 2_000;\nconst MAX_TOTAL_BYTES = 16 * 1024 * 1024;\n\nexport class PackageDirectoryError extends Error {}\n\nexport async function readPackageDirectory(root: string): Promise<Map<string, Buffer>> {\n const properties = await stat(root).catch(() => null);\n if (!properties?.isDirectory()) {\n throw new PackageDirectoryError(`${root} is not a directory.`);\n }\n const files = new Map<string, Buffer>();\n let totalBytes = 0;\n\n const walk = async (directory: string): Promise<void> => {\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n if (IGNORED_DIRECTORIES.has(entry.name)) continue;\n const full = join(directory, entry.name);\n if (entry.isDirectory()) {\n await walk(full);\n continue;\n }\n // Symlinks are skipped rather than followed. A package is a set of bytes, and following a\n // link would let a published package's content depend on something outside it.\n if (!entry.isFile()) continue;\n if (files.size >= MAX_FILES) {\n throw new PackageDirectoryError(\n `This directory holds more than ${MAX_FILES} files. That is almost certainly not a ` +\n \"single action package — run this from the package directory itself.\",\n );\n }\n const contents = await readFile(full);\n totalBytes += contents.byteLength;\n if (totalBytes > MAX_TOTAL_BYTES) {\n throw new PackageDirectoryError(\n `This directory holds more than ${MAX_TOTAL_BYTES / (1024 * 1024)}MB. An action ` +\n \"package is source, not artifacts — add build output to .gitignore.\",\n );\n }\n files.set(toPackagePath(root, full), contents);\n }\n };\n\n await walk(root);\n return files;\n}\n\n/** Package-relative, forward-slashed, on every platform. */\nexport function toPackagePath(root: string, full: string): string {\n return relative(root, full).split(sep).join(\"/\");\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { BRAND_SHORT_NAME, PACKAGE_INTERPRETERS, type PackageInterpreter } from \"@runveric/contracts\";\nimport { PACKAGE_ID_PATTERN, scaffoldActionPackage } from \"@runveric/action-manifest\";\nimport { print, printError, style } from \"./report\";\n\n/**\n * ─── `runveric init` ────────────────────────────────────────────────────────────────\n *\n * Three questions, and only because none of them has a defensible default: the id (it must be\n * unique), the display name (it is the product decision), and the interpreter (it is the\n * language the author is going to write in).\n *\n * Everything else is decided — see the argument in `scaffoldActionPackage`. A first action is\n * six fields an author fills in, not twenty-five, and the twenty-five are all there in the file\n * with sane values so the author can see what exists without going to find documentation.\n *\n * All three are also acceptable as flags, so `init` is scriptable and so the tests can drive it\n * without a pseudo-terminal.\n */\n\nexport interface InitOptions {\n directory?: string;\n id?: string;\n name?: string;\n interpreter?: string;\n author?: string;\n /** Answer every prompt from the flags and defaults; fail rather than ask. */\n yes?: boolean;\n /** Injected in tests so a scaffold is byte-stable. */\n year?: number;\n}\n\nexport async function runInit(options: InitOptions): Promise<number> {\n const interactive = process.stdin.isTTY === true && options.yes !== true;\n const ask = interactive ? prompter() : null;\n\n try {\n const id = await resolveId(options.id, ask);\n if (!id) return 1;\n const suggestedName = titleCase(id.split(\"/\")[1] ?? id);\n const name = options.name?.trim() || (await ask?.(\"Display name\", suggestedName)) || suggestedName;\n const interpreter = await resolveInterpreter(options.interpreter, ask);\n if (!interpreter) return 1;\n const author = options.author?.trim() || (await ask?.(\"Author\", id.split(\"/\")[0]!)) || id.split(\"/\")[0]!;\n\n const directory = resolve(options.directory ?? id.split(\"/\")[1] ?? \"action\");\n const files = scaffoldActionPackage({\n id,\n name,\n interpreter,\n author,\n year: options.year ?? new Date().getFullYear(),\n });\n\n for (const [path, contents] of files) {\n const target = join(directory, path);\n await mkdir(dirname(target), { recursive: true });\n // `wx` — never overwrite. An `init` that silently replaces an author's work is a data\n // loss bug, and the recovery (\"git checkout\") is one they may not have.\n await writeFile(target, contents, { flag: \"wx\" }).catch((error: NodeJS.ErrnoException) => {\n throw error.code === \"EEXIST\"\n ? new Error(\n `${join(directory, path)} already exists. init never overwrites — remove the ` +\n \"directory, or run init somewhere else.\",\n )\n : error;\n });\n }\n\n print();\n print(`${style.green(\"✓\")} Created ${style.bold(directory)}`);\n print();\n for (const path of files.keys()) print(` ${style.grey(path)}`);\n print();\n print(\"It already works. Prove it before you change anything:\");\n print();\n print(` ${style.bold(\"cd\")} ${directory}`);\n print(` ${style.bold(\"runveric check\")}`);\n print(` ${style.bold(\"runveric test --phase run\")}`);\n print();\n return 0;\n } catch (error) {\n printError(style.red(error instanceof Error ? error.message : String(error)));\n return 1;\n } finally {\n ask?.close();\n }\n}\n\nasync function resolveId(\n supplied: string | undefined,\n ask: Prompter | null,\n): Promise<string | null> {\n const value = supplied?.trim() || (await ask?.(\"Action id (publisher/name)\", \"\"));\n if (!value) {\n printError(\n style.red(\"An id is required.\") +\n ' Use --id publisher/name, e.g. --id \"contoso/restart-web-tier\".',\n );\n return null;\n }\n if (!PACKAGE_ID_PATTERN.test(value)) {\n printError(\n style.red(`\"${value}\" is not a valid action id.`) +\n \" It is `publisher/name`, lowercase letters, digits and hyphens — e.g. \" +\n \"`contoso/restart-web-tier`. The publisher half is how an operator tells your actions \" +\n \"from somebody else's in the catalog.\",\n );\n return null;\n }\n return value;\n}\n\nasync function resolveInterpreter(\n supplied: string | undefined,\n ask: Prompter | null,\n): Promise<PackageInterpreter | null> {\n const value =\n supplied?.trim() ||\n (await ask?.(`Interpreter (${PACKAGE_INTERPRETERS.join(\" / \")})`, \"bash\")) ||\n \"bash\";\n if (!isInterpreter(value)) {\n printError(\n style.red(`\"${value}\" is not an interpreter ${BRAND_SHORT_NAME} runs.`) +\n ` The runner image ships ${PACKAGE_INTERPRETERS.join(\", \")}.`,\n );\n return null;\n }\n return value;\n}\n\ntype Prompter = ((question: string, fallback: string) => Promise<string>) & { close(): void };\n\nfunction prompter(): Prompter {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const ask = (async (question: string, fallback: string): Promise<string> => {\n const suffix = fallback ? ` ${style.grey(`(${fallback})`)}` : \"\";\n const answer = (await rl.question(`${question}${suffix}: `)).trim();\n return answer || fallback;\n }) as Prompter;\n ask.close = () => rl.close();\n return ask;\n}\n\nfunction isInterpreter(value: string): value is PackageInterpreter {\n return (PACKAGE_INTERPRETERS as readonly string[]).includes(value);\n}\n\n/** `restart-web-tier` → `Restart Web Tier`. A suggestion, always editable. */\nfunction titleCase(value: string): string {\n return value\n .split(/[-_]/)\n .filter(Boolean)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\" \");\n}\n","import { resolve } from \"node:path\";\nimport { checkActionPackage } from \"@runveric/action-manifest\";\nimport {\n AUTHORING_CLI_ENV,\n BRAND_ARTICLE,\n BRAND_SHORT_NAME,\n parseProblemDocument,\n problemFieldErrors,\n RETIRED_AUTHORING_CLI_ENV,\n} from \"@runveric/contracts\";\nimport type { PackageImportResultDto } from \"@runveric/contracts\";\nimport { readPackageDirectory } from \"./package-dir\";\nimport { renamedVariableRefusal } from \"./renamed-variable\";\nimport { print, printCheckSummary, printError, printFinding, style } from \"./report\";\n\n/**\n * ─── `runveric publish` ─────────────────────────────────────────────────────────────\n *\n * The only verb here that needs an Opera account. It uploads the directory as an AUTHORED\n * package version — the same provenance a package pasted into the app gets, reaching\n * organization tier on the strength of the authenticated principal rather than a Git source.\n *\n * It is last, and it is the one to cut if anything has to be cut. `init`, `check` and `test`\n * are the loop; `publish` is a convenience over an HTTP endpoint that the app can also drive.\n *\n * It runs `check` first and refuses on an error, including a LINT error. That is stricter than\n * the server, deliberately: the server cannot refuse a `$Name?` because it is valid YAML, and\n * this is the last place anybody looks at the package before an operator does.\n */\n\nexport interface PublishOptions {\n directory?: string;\n to?: string;\n token?: string;\n /** Publish despite lint errors. Never bypasses the server's own validation. */\n force?: boolean;\n}\n\n/** Declared in `@runveric/contracts` (`authoring-cli.ts`), the one place the Author page reads too. */\nexport const TOKEN_ENV = AUTHORING_CLI_ENV.token;\nexport const URL_ENV = AUTHORING_CLI_ENV.url;\n\nexport async function runPublish(options: PublishOptions): Promise<number> {\n const directory = resolve(options.directory ?? \".\");\n const baseUrl = (options.to ?? process.env[URL_ENV] ?? \"\").trim().replace(/\\/+$/, \"\");\n const token = (options.token ?? process.env[TOKEN_ENV] ?? \"\").trim();\n\n // ★ A STALE EXPORT FROM 0.1.1 IS REFUSED BY NAME, BEFORE THE GENERIC \"set X\" SENTENCES BELOW,\n // which are true and would not tell an author their variable was renamed. A flag wins: an\n // author who passed --to or --token is not relying on the environment at all.\n const stale = [\n options.to === undefined ? renamedVariableRefusal(URL_ENV, RETIRED_AUTHORING_CLI_ENV.url) : null,\n options.token === undefined\n ? renamedVariableRefusal(TOKEN_ENV, RETIRED_AUTHORING_CLI_ENV.token)\n : null,\n ].filter((sentence): sentence is string => sentence !== null);\n if (stale.length > 0) {\n for (const sentence of stale) printError(style.red(sentence));\n return 1;\n }\n\n if (!baseUrl) {\n printError(\n style.red(\"Where to?\") +\n ` Pass --to https://your-runveric.example.com, or set ${URL_ENV}.`,\n );\n return 1;\n }\n if (!token) {\n printError(\n style.red(`Publishing needs ${BRAND_ARTICLE} ${BRAND_SHORT_NAME} access token.`) +\n ` Set ${TOKEN_ENV}, or pass --token. (init, check and test need no account at all.)`,\n );\n return 1;\n }\n\n let files;\n try {\n files = await readPackageDirectory(directory);\n } catch (error) {\n printError(style.red(error instanceof Error ? error.message : String(error)));\n return 1;\n }\n\n const report = checkActionPackage(files);\n if (!report.validation.ok || (report.lintBlocked && options.force !== true)) {\n print();\n for (const finding of report.findings.filter((f) => f.severity === \"error\")) {\n printFinding(finding);\n }\n printCheckSummary({ errors: report.errorCount, warnings: report.warningCount });\n printError(\n style.red(\"\\nNot published.\") +\n (report.validation.ok\n ? ` ${BRAND_SHORT_NAME} would accept this, but the problems above make it misbehave at run time. ` +\n \"Fix them, or pass --force if you disagree.\"\n : \" Fix the errors above and publish again.\"),\n );\n return 1;\n }\n\n // ADVISORY ERRORS DO NOT REFUSE, AND ARE NOT SWALLOWED EITHER. They are found by a heuristic\n // that could be wrong about this package, so blocking would be the worse mistake — but this\n // is the last place anybody looks at the package before an operator does, and a problem that\n // was noticed and not mentioned is the same as one that was never found.\n if (report.advisoryCount > 0) {\n print();\n for (const finding of report.findings.filter((f) => f.advisory === true)) {\n printFinding(finding);\n }\n print(\n style.yellow(\"Publishing anyway.\") +\n \" The above cannot be checked with certainty, so it does not refuse a publish.\",\n );\n }\n\n const manifest = report.validation.manifest;\n print();\n print(`${style.bold(\"publish\")} ${manifest.id} ${manifest.version} → ${baseUrl}`);\n\n // The wire shape is deliberately the plainest thing that works: the files, base64-encoded,\n // in one JSON body. Not a tarball — an author debugging a failed publish can read a JSON\n // body in their proxy log, and cannot read a gzip stream.\n const body = JSON.stringify({\n files: [...files].map(([path, contents]) => ({\n path,\n contentBase64: contents.toString(\"base64\"),\n })),\n });\n\n let response: Response;\n try {\n response = await fetch(`${baseUrl}/packages/authored`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${token}`,\n },\n body,\n });\n } catch (error) {\n printError(\n style.red(`Could not reach ${baseUrl}.`) +\n `\\n ${error instanceof Error ? error.message : String(error)}`,\n );\n return 1;\n }\n\n const text = await response.text();\n if (!response.ok) {\n printError(style.red(`\\nPublish refused (${response.status}).`));\n printError(formatProblem(text));\n return 1;\n }\n\n let version: PackageImportResultDto;\n try {\n version = JSON.parse(text) as PackageImportResultDto;\n } catch {\n printError(style.red(`${BRAND_SHORT_NAME} accepted the package but returned a response we cannot read.`));\n return 1;\n }\n print();\n print(`${style.green(\"✓\")} Published ${style.bold(`${version.packageId} ${version.semanticVersion}`)}`);\n print(` version id ${version.id}`);\n print(` content digest ${version.contentDigest}`);\n print(` tier ${version.tier} ${style.grey(`(${version.provenance})`)}`);\n print();\n print(\n style.grey(\n `It is an immutable version now. Adopt it in ${BRAND_SHORT_NAME} to put it in the catalog — publishing ` +\n \"does not adopt, so nobody can run it until somebody chooses to.\",\n ),\n );\n print();\n return 0;\n}\n\n/**\n * An RFC 9457 problem body, rendered as the field errors it carries. Falling back to the raw\n * text rather than to a generic sentence: a response we cannot parse is one the author may\n * still be able to read, and hiding it helps nobody.\n *\n * ⚠ THE THIRD PLACE THIS SHAPE WAS WRITTEN BY HAND (docs/42 D2), and the only one that ships\n * to a customer's laptop. It read `errors?: { path, message }[]`, which is right for the\n * manifest 422 this endpoint usually answers with and silently WRONG for the parameter 422 it\n * can also answer with — `error.path` would be `undefined` and the author would be told\n * \"undefined: Required.\" about a file they cannot find. `problemFieldErrors` knows both\n * vocabularies because it is declared beside the api that emits them.\n */\nfunction formatProblem(text: string): string {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return ` ${text}`;\n }\n const problem = parseProblemDocument(parsed);\n if (!problem) return ` ${text}`;\n\n const lines: string[] = [];\n if (problem.detail) lines.push(` ${problem.detail}`);\n for (const error of problemFieldErrors(problem)) {\n // An entry that names nothing is still a sentence worth printing; it just has no bold head.\n lines.push(error.field ? ` ${style.bold(error.field)}: ${error.message}` : ` ${error.message}`);\n }\n return lines.length > 0 ? lines.join(\"\\n\") : ` ${text}`;\n}\n","/**\n * ─── A RENAMED VARIABLE SAYS SO (0.1.2) ─────────────────────────────────────────────────\n *\n * 0.1.1 read `OPERA_TOKEN`, `OPERA_URL` and `OPERA_RUNNER_IMAGE`. An author whose shell or CI\n * still exports one of them would otherwise meet this release as \"Publishing needs an access\n * token\" or a silent fall-back to a locally built image — true, and no help: nothing in either\n * sentence says the variable they set was renamed. So when the current variable is unset and\n * the retired one IS set, the CLI stops and names both.\n *\n * ⛔ IT NEVER READS THE RETIRED VALUE. A fallback would work today and keep the old name alive in\n * every pipeline indefinitely, with nobody ever told to change it.\n */\nexport function renamedVariableRefusal(\n current: string,\n retired: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n if (env[current]?.trim()) return null;\n if (!env[retired]?.trim()) return null;\n return (\n `${retired} is set, but this CLI reads ${current} — the variable was renamed in 0.1.2. ` +\n `Rename the export in your shell or CI; ${retired} is no longer read.`\n );\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { AUTHORING_CLI_ENV, BRAND_SHORT_NAME, RETIRED_AUTHORING_CLI_ENV } from \"@runveric/contracts\";\nimport { renamedVariableRefusal } from \"./renamed-variable\";\n\nconst run = promisify(execFile);\n\n/**\n * ─── WHICH IMAGE `test` RUNS IN, AND WHY IT MATTERS MORE THAN ANYTHING ELSE HERE ────────\n *\n * \"It worked locally\" is worth exactly nothing if locally is a different substrate. A local\n * approximation of the runner — a bare `bash`, a `python:3.11` image, the author's own pwsh —\n * would produce a green run for a package that fails in production because the interpreter\n * version differs, or a tool is present locally and absent there, or the filesystem layout is\n * not the one the contract promises.\n *\n * So `test` runs the PUBLISHED runner image, and it PRINTS which one on every run. An author\n * who cannot see which substrate they tested on has not really tested on it.\n *\n * Resolution order, most explicit first:\n * 1. --image the author said exactly what to run\n * 2. RUNVERIC_RUNNER_IMAGE the environment their deployment configured\n * 3. runveric-package-runner:local what `pnpm build:package-runner` produces in this repo\n *\n * The fallback is NAMED as a fallback in the output, so nobody mistakes a locally-built image\n * for the one their Opera actually runs.\n */\n\nexport const LOCAL_RUNNER_IMAGE = \"runveric-package-runner:local\";\n/** Declared in `@runveric/contracts` (`authoring-cli.ts`); the Author page renders it. */\nexport const RUNNER_IMAGE_ENV = AUTHORING_CLI_ENV.runnerImage;\n\n/** A stale 0.1.1 export: refused by name rather than silently replaced by a local build. */\nexport class RenamedVariableError extends Error {}\n\nexport interface ResolvedRunnerImage {\n reference: string;\n origin: \"flag\" | \"environment\" | \"local-build\";\n}\n\nexport function resolveRunnerImage(flag: string | undefined): ResolvedRunnerImage {\n const explicit = flag?.trim();\n if (explicit) return { reference: explicit, origin: \"flag\" };\n const configured = process.env[RUNNER_IMAGE_ENV]?.trim();\n if (configured) return { reference: configured, origin: \"environment\" };\n // ⚠ Falling back to a LOCAL image here would test on different bytes from the ones the author\n // pointed at — the one outcome `test` exists to prevent — and say so only in a grey note.\n const stale = renamedVariableRefusal(RUNNER_IMAGE_ENV, RETIRED_AUTHORING_CLI_ENV.runnerImage);\n if (stale) throw new RenamedVariableError(stale);\n return { reference: LOCAL_RUNNER_IMAGE, origin: \"local-build\" };\n}\n\nexport function runnerImageNote(image: ResolvedRunnerImage): string {\n switch (image.origin) {\n case \"flag\":\n return \"from --image\";\n case \"environment\":\n return `from ${RUNNER_IMAGE_ENV}`;\n case \"local-build\":\n return `locally built — NOT the image your ${BRAND_SHORT_NAME} runs; set ${RUNNER_IMAGE_ENV} to match it`;\n }\n}\n\nexport class DockerMissingError extends Error {}\n\n/**\n * Confirm Docker is usable BEFORE materializing anything, so the failure is one sentence at the\n * start rather than a spawn error in the middle of a run.\n */\nexport async function assertDockerAvailable(): Promise<void> {\n try {\n await run(\"docker\", [\"version\", \"--format\", \"{{.Server.Version}}\"]);\n } catch {\n throw new DockerMissingError(\n `Docker is not available. \\`runveric test\\` runs your package in the real ${BRAND_SHORT_NAME} ` +\n \"runner image, which needs a container runtime — install Docker Desktop (or start \" +\n \"it), then try again. `runveric check` needs nothing and still works.\",\n );\n }\n}\n\n/** Whether the image is already present locally, so `test` can say it is pulling one. */\nexport async function imageIsPresent(reference: string): Promise<boolean> {\n try {\n await run(\"docker\", [\"image\", \"inspect\", reference]);\n return true;\n } catch {\n return false;\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { mkdir, mkdtemp, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { StringDecoder } from \"node:string_decoder\";\nimport {\n PACKAGE_INTERPRETER_LAUNCH,\n checkActionPackage,\n validatePackageResult,\n} from \"@runveric/action-manifest\";\nimport type {\n PackageExecutionContext,\n PackageInterpreter,\n PackagePhase,\n PackageJsonObject,\n PackageResultV1,\n PackageRuntimeEvent,\n ParameterSchema,\n} from \"@runveric/contracts\";\nimport { acquireAzureCredential, AzureCredentialError } from \"./azure-credential\";\nimport { readPackageDirectory } from \"./package-dir\";\nimport { print, printError, printEvent, printResult, style } from \"./report\";\nimport {\n assertDockerAvailable,\n imageIsPresent,\n resolveRunnerImage,\n runnerImageNote,\n type ResolvedRunnerImage,\n} from \"./runner-image\";\nimport {\n BRAND_SHORT_NAME,\n PACKAGE_EXECUTION_PROTOCOL_VERSION,\n PACKAGE_RESULT_PROTOCOL_VERSION,\n} from \"@runveric/contracts\";\n\n/**\n * ═══ `runveric test` — THE HEART OF THIS FEATURE ════════════════════════════════════\n *\n * The commit-push-wait cycle is the single most cited complaint about authoring CI/automation\n * units. `act` exists entirely to shorten it. This is Opera's answer: run one phase, read the\n * events and the result, WITHOUT pushing, importing, or holding an Opera account.\n *\n * Three things make it worth trusting, and each one is load-bearing:\n *\n * 1. THE SAME IMAGE. Not an approximation — the published runner image, named in the output.\n * 2. THE SAME LAYOUT AND ENVIRONMENT. `/runveric/package`, `/runveric/input`, `/runveric/output`,\n * `/runveric/scratch`, `/runveric/creds`, and the identical `RUNVERIC_*` contract, built from the\n * same interpreter launch table `bootstrap.ps1` uses.\n * 3. THE SAME RESULT VALIDATOR. `validatePackageResult`, the exact call the control plane\n * makes, so a result Opera would reject fails HERE first — which is the only way an author\n * finds out about it before an operator does.\n *\n * WHAT IS DELIBERATELY DIFFERENT, and printed so nobody has to guess:\n * - the credential is the AUTHOR'S (`az account get-access-token`), not Opera's brokered\n * least-privilege lease, so a local pass does not prove the connector has the permissions;\n * - egress is the machine's, not the allowlisting proxy. A package that declares network is\n * tested with network, and told that its allowlist was not enforced here.\n * Both of those are stated rather than simulated. A fake that is nearly the real thing is how\n * a tool starts producing confident wrong answers.\n */\n\nexport interface TestOptions {\n directory?: string;\n phase?: string;\n dryRun?: boolean;\n /** `--param name=value`, repeatable. Overrides the schema default. */\n param?: string[];\n /** A JSON file of parameters. Overridden by any `--param`. */\n paramsFile?: string;\n image?: string;\n /** Skip `az`. For a package that touches no cloud, or an author who is not logged in. */\n noCredential?: boolean;\n /** The prior run's result.json, for `--phase rollback`. */\n priorResult?: string;\n /** Keep the materialized /runveric tree for inspection instead of deleting it. */\n keep?: boolean;\n}\n\nconst PHASES: readonly PackagePhase[] = [\"validate\", \"run\", \"rollback\"];\n\n/** The in-container layout. Identical to SANDBOX_PATHS and to bootstrap.ps1's directories. */\nconst CONTAINER = {\n packageRoot: \"/runveric/package\",\n input: \"/runveric/input\",\n output: \"/runveric/output\",\n scratch: \"/runveric/scratch\",\n creds: \"/runveric/creds\",\n} as const;\n\nexport async function runTest(options: TestOptions): Promise<number> {\n const directory = resolve(options.directory ?? \".\");\n const phase = (options.phase ?? \"run\") as PackagePhase;\n if (!PHASES.includes(phase)) {\n printError(\n style.red(`\"${options.phase}\" is not a phase.`) +\n ` ${BRAND_SHORT_NAME} runs ${PHASES.join(\", \")} — one at a time, so you can read each one's result.`,\n );\n return 1;\n }\n\n let files: Map<string, Buffer>;\n try {\n files = await readPackageDirectory(directory);\n } catch (error) {\n printError(style.red(error instanceof Error ? error.message : String(error)));\n return 1;\n }\n\n // VALIDATE BEFORE RUNNING, always. Starting a container for a package Opera would refuse\n // wastes a minute to reach a worse version of an answer `check` gives instantly.\n const report = checkActionPackage(files);\n if (!report.validation.ok) {\n printError(\n style.red(\"This package would be refused at import, so there is nothing to test.\") +\n \" Run `runveric check` to see why.\",\n );\n return 1;\n }\n const { manifest, parameterSchema } = report.validation;\n if (manifest.runtime.kind !== \"interpreter\") {\n printError(\n style.red(\"`test` runs interpreter packages.\") +\n ` This one declares an OCI image (${manifest.runtime.image}); run that image directly.`,\n );\n return 1;\n }\n const interpreter = manifest.runtime.name;\n\n const entrypoint = entrypointFor(manifest, phase);\n if (!entrypoint) {\n printError(\n style.red(`This package declares no ${phase} phase.`) +\n (phase === \"validate\"\n ? \" Add `validateEntrypoint: validate/` to action.yaml to enable the pre-flight.\"\n : phase === \"rollback\"\n ? \" Set `rollback: true` and `rollbackEntrypoint: rollback/` in action.yaml.\"\n : \"\"),\n );\n return 1;\n }\n\n let parameters: PackageJsonObject;\n try {\n parameters = await resolveParameters(parameterSchema, options);\n } catch (error) {\n printError(style.red(error instanceof Error ? error.message : String(error)));\n return 1;\n }\n\n let image: ResolvedRunnerImage;\n try {\n image = resolveRunnerImage(options.image);\n } catch (error) {\n printError(style.red(error instanceof Error ? error.message : String(error)));\n return 1;\n }\n try {\n await assertDockerAvailable();\n } catch (error) {\n printError(style.red(error instanceof Error ? error.message : String(error)));\n return 1;\n }\n\n let credential = null;\n if (options.noCredential !== true) {\n try {\n credential = await acquireAzureCredential();\n } catch (error) {\n if (!(error instanceof AzureCredentialError)) throw error;\n printError(style.red(error.message));\n return 1;\n }\n }\n\n const workspace = await mkdtemp(join(tmpdir(), \"runveric-\"));\n try {\n const layout = await materialize(workspace, {\n files,\n parameters,\n phase,\n dryRun: options.dryRun === true,\n subscriptionId: credential?.account.subscriptionId ?? \"local-test\",\n priorResult: options.priorResult\n ? await readJsonFile(options.priorResult)\n : undefined,\n credentialToken: credential?.token,\n });\n\n print();\n print(`${style.bold(\"test\")} ${manifest.id} ${manifest.version} ${style.grey(`phase ${phase}`)}`);\n print(` runner image ${image.reference} ${style.grey(`(${runnerImageNote(image)})`)}`);\n print(` interpreter ${interpreter}@${manifest.runtime.version}`);\n print(` entrypoint ${entrypoint}${PACKAGE_INTERPRETER_LAUNCH[interpreter].entryFile}`);\n print(\n ` identity ${\n credential\n ? `${credential.account.name} ${style.grey(`— YOUR access, not ${BRAND_SHORT_NAME}'s brokered least-privilege identity`)}`\n : style.grey(\"none (--no-credential)\")\n }`,\n );\n if (manifest.requiresNetwork) {\n print(\n ` network ${style.yellow(\"open\")} ${style.grey(\n `— your allowlist (${(manifest.egressAllowlist ?? []).join(\", \")}) is NOT enforced here; ${BRAND_SHORT_NAME} enforces it`,\n )}`,\n );\n } else {\n print(` network ${style.grey(\"none — this package declares requiresNetwork: false\")}`);\n }\n if (options.dryRun) print(` ${style.bold(\"dry run\")} RUNVERIC_DRY_RUN=true`);\n if (!(await imageIsPresent(image.reference))) {\n print(` ${style.grey(\"pulling the image (first run only)…\")}`);\n }\n print();\n print(style.bold(\"Events\"));\n\n const events: PackageRuntimeEvent[] = [];\n const exit = await runContainer({\n image: image.reference,\n interpreter,\n entrypoint,\n layout,\n phase,\n dryRun: options.dryRun === true,\n requiresNetwork: manifest.requiresNetwork,\n credentialEnv: credential?.env,\n timeoutMs: 15 * 60 * 1000,\n onEvent: (event) => {\n events.push(event);\n printEvent(event);\n },\n });\n if (events.length === 0) print(style.grey(\" (the package printed nothing)\"));\n\n return await reportOutcome({\n exit,\n resultPath: join(layout.output, \"result.json\"),\n phase,\n workspace,\n keep: options.keep === true,\n });\n } finally {\n if (options.keep === true) {\n print(style.grey(` kept ${workspace}`));\n } else {\n await rm(workspace, { recursive: true, force: true });\n }\n }\n}\n\n/** Which directory this phase's entrypoint lives in, or null when the phase is not declared. */\nfunction entrypointFor(\n manifest: { entrypoint: string; validateEntrypoint?: string; rollbackEntrypoint?: string },\n phase: PackagePhase,\n): string | null {\n if (phase === \"run\") return manifest.entrypoint;\n if (phase === \"validate\") return manifest.validateEntrypoint ?? null;\n return manifest.rollbackEntrypoint ?? null;\n}\n\n/**\n * The parameters this phase runs with: schema defaults, then a `--params-file`, then each\n * `--param`. A required parameter with no value REFUSES rather than passing undefined — the\n * package would fail on it a second later with a message about its own code instead.\n */\nasync function resolveParameters(\n schema: ParameterSchema,\n options: TestOptions,\n): Promise<PackageJsonObject> {\n const properties = (schema.properties ?? {}) as Record<\n string,\n { type?: string; default?: unknown }\n >;\n const parameters: PackageJsonObject = {};\n for (const [name, property] of Object.entries(properties)) {\n if (property.default !== undefined) parameters[name] = property.default as never;\n }\n if (options.paramsFile) {\n const supplied = await readJsonFile(options.paramsFile);\n for (const [name, value] of Object.entries(supplied)) parameters[name] = value;\n }\n for (const pair of options.param ?? []) {\n const separator = pair.indexOf(\"=\");\n if (separator <= 0) {\n throw new Error(`--param expects name=value; got \"${pair}\".`);\n }\n const name = pair.slice(0, separator);\n const raw = pair.slice(separator + 1);\n if (!(name in properties)) {\n throw new Error(\n `\"${name}\" is not a parameter of this action. It declares: ${\n Object.keys(properties).join(\", \") || \"(none)\"\n }.`,\n );\n }\n // Typed from the SCHEMA, not guessed from the text: `--param force=false` must reach a\n // boolean parameter as `false`, and reach a string parameter as the word \"false\".\n parameters[name] =\n properties[name]?.type === \"boolean\" ? raw === \"true\" : raw;\n }\n const missing = (schema.required ?? []).filter((name) => parameters[name] === undefined);\n if (missing.length > 0) {\n throw new Error(\n `These parameters are required and have no value: ${missing.join(\", \")}. Supply them ` +\n `with --param ${missing[0]}=… (repeatable), or --params-file params.json.`,\n );\n }\n return parameters;\n}\n\ninterface Layout {\n packageRoot: string;\n input: string;\n output: string;\n scratch: string;\n creds: string;\n hasCredential: boolean;\n hasPriorResult: boolean;\n}\n\n/**\n * Build the /runveric tree on the host, exactly as the sandbox bind-mounts it and the runner\n * bootstrap writes it. Same file names, same JSON, same places.\n */\nasync function materialize(\n workspace: string,\n input: {\n files: ReadonlyMap<string, Buffer>;\n parameters: PackageJsonObject;\n phase: PackagePhase;\n dryRun: boolean;\n subscriptionId: string;\n priorResult?: PackageJsonObject;\n credentialToken?: string;\n },\n): Promise<Layout> {\n const layout: Layout = {\n packageRoot: join(workspace, \"package\"),\n input: join(workspace, \"input\"),\n output: join(workspace, \"output\"),\n scratch: join(workspace, \"scratch\"),\n creds: join(workspace, \"creds\"),\n hasCredential: input.credentialToken !== undefined,\n hasPriorResult: input.priorResult !== undefined,\n };\n await Promise.all(\n [layout.packageRoot, layout.input, layout.output, layout.scratch, layout.creds].map(\n (directory) => mkdir(directory, { recursive: true }),\n ),\n );\n\n for (const [path, contents] of input.files) {\n const target = join(layout.packageRoot, path);\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, contents);\n }\n\n const context: PackageExecutionContext = {\n protocolVersion: PACKAGE_EXECUTION_PROTOCOL_VERSION,\n // A recognisable id rather than a random uuid: it appears in the package's own log lines,\n // and \"local-test\" tells the reader instantly that this was not a real run.\n executionId: \"local-test\",\n phase: input.phase,\n provider: \"azure\",\n providerScopeId: input.subscriptionId,\n dryRun: input.dryRun,\n };\n await writeFile(join(layout.input, \"context.json\"), JSON.stringify(context, null, 2));\n await writeFile(\n join(layout.input, \"parameters.json\"),\n JSON.stringify(input.parameters, null, 2),\n );\n if (input.priorResult) {\n await writeFile(\n join(layout.input, \"prior-result.json\"),\n JSON.stringify(input.priorResult, null, 2),\n );\n }\n if (input.credentialToken) {\n // 0400, like the runner. A local test that leaves a bearer token world-readable in the\n // temp directory is a local test that teaches a bad habit.\n await writeFile(join(layout.creds, \"azure-token\"), input.credentialToken, { mode: 0o400 });\n }\n return layout;\n}\n\n/**\n * Start the container and stream its output as events, using the EXACT launch the runner uses:\n * the binary, the arguments and the entrypoint filename all come from\n * `PACKAGE_INTERPRETER_LAUNCH`, the one table `bootstrap.ps1` is parity-checked against.\n */\nasync function runContainer(options: {\n image: string;\n interpreter: PackageInterpreter;\n entrypoint: string;\n layout: Layout;\n phase: PackagePhase;\n dryRun: boolean;\n requiresNetwork: boolean;\n credentialEnv?: Record<string, string>;\n timeoutMs: number;\n onEvent(event: PackageRuntimeEvent): void;\n}): Promise<{ code: number | null; timedOut: boolean }> {\n const launch = PACKAGE_INTERPRETER_LAUNCH[options.interpreter];\n const script = `${CONTAINER.packageRoot}/${options.entrypoint}${launch.entryFile}`;\n\n const environment: Record<string, string> = {\n RUNVERIC_PROTOCOL_VERSION: PACKAGE_RESULT_PROTOCOL_VERSION,\n RUNVERIC_PHASE: options.phase,\n RUNVERIC_CONTEXT_FILE: `${CONTAINER.input}/context.json`,\n RUNVERIC_PARAMETERS_FILE: `${CONTAINER.input}/parameters.json`,\n RUNVERIC_RESULT_FILE: `${CONTAINER.output}/result.json`,\n RUNVERIC_WORK_DIR: CONTAINER.scratch,\n RUNVERIC_CANCEL_FILE: `${CONTAINER.input}/cancel.requested`,\n RUNVERIC_DRY_RUN: options.dryRun ? \"true\" : \"false\",\n // HONEST, and matching the ACA runner's own reasoning: this flag means \"there is no route\n // out at all\". A container with `--network none` genuinely has none; one with a network\n // does not, whether or not an allowlist would have applied.\n RUNVERIC_NETWORK_ISOLATED: options.requiresNetwork ? \"false\" : \"true\",\n LANG: \"C.UTF-8\",\n LC_ALL: \"C.UTF-8\",\n POWERSHELL_TELEMETRY_OPTOUT: \"1\",\n DOTNET_CLI_TELEMETRY_OPTOUT: \"1\",\n ...(options.layout.hasPriorResult\n ? { RUNVERIC_PRIOR_RESULT_FILE: `${CONTAINER.input}/prior-result.json` }\n : {}),\n ...(options.layout.hasCredential\n ? { RUNVERIC_AZURE_TOKEN_FILE: `${CONTAINER.creds}/azure-token` }\n : {}),\n ...(options.credentialEnv ?? {}),\n };\n\n const args = [\n \"run\",\n \"--rm\",\n \"--interactive=false\",\n // The package must not inherit a shell, a working directory or an identity from the host.\n \"--workdir\",\n CONTAINER.scratch,\n // A package that declares no network gets none. This is the one production guarantee a\n // laptop CAN reproduce exactly, so it does.\n ...(options.requiresNetwork ? [] : [\"--network\", \"none\"]),\n \"--mount\",\n `type=bind,source=${options.layout.packageRoot},target=${CONTAINER.packageRoot},readonly`,\n \"--mount\",\n `type=bind,source=${options.layout.input},target=${CONTAINER.input},readonly`,\n \"--mount\",\n `type=bind,source=${options.layout.output},target=${CONTAINER.output}`,\n \"--mount\",\n `type=bind,source=${options.layout.scratch},target=${CONTAINER.scratch}`,\n ...(options.layout.hasCredential\n ? [\"--mount\", `type=bind,source=${options.layout.creds},target=${CONTAINER.creds},readonly`]\n : []),\n ...Object.entries(environment).flatMap(([name, value]) => [\"--env\", `${name}=${value}`]),\n // The image's own ENTRYPOINT is the work-item bootstrap, which fetches from a control\n // plane that does not exist here. Overriding it runs the package the same way the\n // bootstrap would have — same binary, same arguments, same script path.\n \"--entrypoint\",\n launch.fileName,\n options.image,\n ...launch.arguments,\n script,\n ];\n\n return await new Promise((resolvePromise, reject) => {\n const child = spawn(\"docker\", args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGKILL\");\n }, options.timeoutMs);\n\n const consume = (stderr: boolean): ((chunk: Buffer) => void) => {\n const decoder = new StringDecoder(\"utf8\");\n let pending = \"\";\n return (chunk: Buffer): void => {\n pending += decoder.write(chunk);\n const lines = pending.split(/\\r?\\n/);\n pending = lines.pop() ?? \"\";\n for (const line of lines) emitLine(line, stderr, options.onEvent);\n };\n };\n child.stdout.on(\"data\", consume(false));\n child.stderr.on(\"data\", consume(true));\n child.once(\"error\", (error) => {\n clearTimeout(timer);\n reject(error);\n });\n child.once(\"close\", (code) => {\n clearTimeout(timer);\n resolvePromise({ code, timedOut });\n });\n });\n}\n\n/**\n * One output line as the control plane would see it: an `RUNVERIC_EVENT ` line on stdout is the\n * structured channel, everything else is a log line at info (stdout) or warn (stderr).\n *\n * Malformed structured JSON becomes a WARNING rather than a hard failure — the same thing the\n * runner does — because the author needs to be told their event was malformed while still\n * seeing the rest of their run.\n */\nfunction emitLine(\n line: string,\n stderr: boolean,\n onEvent: (event: PackageRuntimeEvent) => void,\n): void {\n if (line.length === 0) return;\n const prefix = \"RUNVERIC_EVENT \";\n if (!stderr && line.startsWith(prefix)) {\n try {\n const parsed: unknown = JSON.parse(line.slice(prefix.length));\n if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n onEvent(parsed as PackageRuntimeEvent);\n return;\n }\n } catch {\n // falls through to the warning below\n }\n onEvent({ level: \"warn\", message: \"Package emitted malformed RUNVERIC_EVENT JSON.\" });\n return;\n }\n onEvent({ level: stderr ? \"warn\" : \"info\", message: line });\n}\n\n/**\n * Read `result.json` and judge it with THE control plane's validator.\n *\n * This is where a local run earns its keep: a package that exits 0 without writing a result, or\n * writes one Opera would refuse, fails HERE — with the reason the runner would have given,\n * never a stack trace.\n */\nasync function reportOutcome(options: {\n exit: { code: number | null; timedOut: boolean };\n resultPath: string;\n phase: PackagePhase;\n workspace: string;\n keep: boolean;\n}): Promise<number> {\n if (options.exit.timedOut) {\n printError(\n style.red(\"\\nThe package did not finish within 15 minutes and was killed.\") +\n ` ${BRAND_SHORT_NAME} enforces the \\`executionTimeout\\` in your manifest; this is the local ceiling.`,\n );\n return 1;\n }\n\n const exists = await stat(options.resultPath).catch(() => null);\n if (!exists?.isFile() || exists.size === 0) {\n printError(\n style.red(\"\\nThe package wrote no result.\") +\n `\\n result.json is the only channel ${BRAND_SHORT_NAME} reads. Exiting ${\n options.exit.code ?? \"with a signal\"\n } without writing $RUNVERIC_RESULT_FILE is a FAILED run, whatever the script printed.` +\n \"\\n Write it as the last thing your script does, on every path — including the ones \" +\n \"that fail.\",\n );\n return 1;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(await readFile(options.resultPath, \"utf8\"));\n } catch {\n printError(\n style.red(\"\\nresult.json is not valid JSON.\") +\n ` ${BRAND_SHORT_NAME} refuses the run rather than guessing what the package meant.`,\n );\n return 1;\n }\n\n let result: PackageResultV1;\n try {\n // THE SAME VALIDATOR THE CONTROL PLANE USES. Not a copy of its rules — the function itself.\n result = validatePackageResult(parsed, options.phase);\n } catch (error) {\n printError(\n style.red(`\\n${BRAND_SHORT_NAME} would REFUSE this result.`) +\n `\\n ${error instanceof Error ? error.message : String(error)}` +\n \"\\n This is the same check the control plane runs, so fixing it here fixes it there.\",\n );\n return 1;\n }\n\n printResult(result);\n if (options.exit.code !== 0) {\n print(\n style.yellow(\n `The package exited ${options.exit.code} but wrote a valid result. ${BRAND_SHORT_NAME} reads the ` +\n \"result, not the exit code — but a non-zero exit usually means something failed \" +\n \"after the result was written.\",\n ),\n );\n print();\n }\n return result.status === \"succeeded\" ? 0 : 1;\n}\n\nasync function readJsonFile(path: string): Promise<PackageJsonObject> {\n let source: string;\n try {\n source = await readFile(resolve(path), \"utf8\");\n } catch {\n throw new Error(`Could not read ${path}.`);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(source);\n } catch {\n throw new Error(`${path} is not valid JSON.`);\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(`${path} must contain a JSON object.`);\n }\n return parsed as PackageJsonObject;\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst run = promisify(execFile);\n\n/**\n * ─── THE AUTHOR'S OWN CLOUD CREDENTIAL ──────────────────────────────────────────────────\n *\n * A package that talks to Azure has to talk to a real Azure to be worth testing, and the\n * credential an author already has is their `az login`. So `test` mints a token with the Azure\n * CLI and hands it to the container the SAME way the sandbox does: in a FILE at\n * `/runveric/creds/azure-token`, never in an environment variable.\n *\n * That is not caution for its own sake — it is the production contract. The runner writes the\n * brokered token to a file precisely because a container's environment is readable afterwards\n * by anyone with Reader on the resource, and a package that learned to read `$AZURE_TOKEN`\n * locally would be a package that does not work in production.\n *\n * IT IS THE AUTHOR'S OWN IDENTITY, NOT OPERA'S. A local test therefore has whatever access the\n * author has, which is usually MORE than the least-privilege identity Opera brokers. `test`\n * says so, because \"it worked for me\" is the most expensive way to discover a permission your\n * package needs and the connector does not have.\n */\n\nexport interface AzureCredential {\n token: string;\n /** The environment the sandbox sets alongside the token file. */\n env: Record<string, string>;\n /** What the author's own identity is, for the line `test` prints. */\n account: { name: string; subscriptionId: string; tenantId: string };\n}\n\nexport class AzureCredentialError extends Error {}\n\nconst MANAGEMENT_RESOURCE = \"https://management.azure.com\";\n\nexport async function acquireAzureCredential(): Promise<AzureCredential> {\n const account = await azJson<{ name?: string; id?: string; tenantId?: string }>([\n \"account\",\n \"show\",\n \"--output\",\n \"json\",\n ]);\n if (!account.id || !account.tenantId) {\n throw new AzureCredentialError(\n \"`az account show` returned no subscription. Run `az login` and `az account set \" +\n \"--subscription <id>` first.\",\n );\n }\n const token = await azJson<{ accessToken?: string }>([\n \"account\",\n \"get-access-token\",\n \"--resource\",\n MANAGEMENT_RESOURCE,\n \"--output\",\n \"json\",\n ]);\n if (!token.accessToken) {\n throw new AzureCredentialError(\"`az account get-access-token` returned no access token.\");\n }\n return {\n token: token.accessToken,\n // The identical names the credential adapter puts in a lease, so a package reads the same\n // environment here and in production.\n env: {\n AZURE_SUBSCRIPTION_ID: account.id,\n AZURE_TENANT_ID: account.tenantId,\n },\n account: {\n name: account.name ?? account.id,\n subscriptionId: account.id,\n tenantId: account.tenantId,\n },\n };\n}\n\nasync function azJson<T>(args: string[]): Promise<T> {\n let stdout: string;\n try {\n ({ stdout } = await run(\"az\", args, { maxBuffer: 8 * 1024 * 1024 }));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new AzureCredentialError(\n message.includes(\"ENOENT\")\n ? \"The Azure CLI (`az`) is not installed. Install it and run `az login`, or run with \" +\n \"--no-credential to test a package that does not call Azure.\"\n : `\\`az ${args.join(\" \")}\\` failed. Run \\`az login\\` and try again.\\n${message.trim()}`,\n );\n }\n try {\n return JSON.parse(stdout) as T;\n } catch {\n throw new AzureCredentialError(`\\`az ${args.join(\" \")}\\` did not return JSON.`);\n }\n}\n","#!/usr/bin/env node\n// Read from the package manifest rather than duplicated here: a version constant in source is a\n// version constant that goes stale on the first release nobody remembers to edit. The bundler\n// inlines it at build time, and the manifest it is inlined FROM is the one published in the same\n// tarball by the same build — so `--version` cannot report a version the package does not have.\n// `tarball.spec.ts` asserts that equality against a real packed artifact.\nimport { version } from \"../package.json\";\nimport { runCatalog } from \"./catalog\";\nimport { runCheck } from \"./check\";\nimport { runInit } from \"./init\";\nimport { print, printError, style } from \"./report\";\nimport { runPublish, TOKEN_ENV, URL_ENV } from \"./publish\";\nimport { RUNNER_IMAGE_ENV } from \"./runner-image\";\nimport { runTest } from \"./test\";\nimport { BRAND_ARTICLE, BRAND_SHORT_NAME } from \"@runveric/contracts\";\n\n/**\n * ═══ runveric ══════════════════════════════════════════════════════════════════════\n *\n * FOUR VERBS. Not five, and not four with sub-verbs.\n *\n * init scaffold a working action\n * check validate it, offline, with the server's own validator\n * test run one phase in the real runner image\n * publish upload it as an authored version (the only one that needs an account)\n *\n * Every option this tool offers is an option an author can get wrong. The research is\n * unambiguous that a prescriptive shape beats a flexible one — Terraform's registry works\n * because the shape is fixed; Backstage's plugin ecosystem struggles on \"where do I put\n * everything\". So there is one way to do each thing, and the flags exist only where a default\n * would be a guess.\n *\n * ★ AND ONE NAMESPACE THAT IS NOT AN AUTHORING VERB (docs/127 §6). `runveric catalog\n * publish-action | publish-release` publishes the artifacts the product's OWN catalog is pinned\n * from. It is not part of the authoring loop and an author never needs it; it lives here because\n * the action and catalog repositories' workflows must run it, and this is the one tool of ours\n * they can install. It is dispatched before the parser below and parses strictly — see\n * `catalog/index.ts`.\n *\n * The argument parser is hand-written and about forty lines, which is smaller than the\n * dependency that would replace it and leaves this package with two workspace dependencies and\n * nothing else — so `npx @runveric/cli` is a fast install rather than a tree.\n */\n\nconst USAGE = `\n${style.bold(\"runveric\")} — author ${BRAND_ARTICLE} ${BRAND_SHORT_NAME} action, without pushing anything.\n\n${style.bold(\"USAGE\")}\n runveric <command> [options]\n\n${style.bold(\"COMMANDS\")}\n init [directory] Scaffold a working action. It passes check and test immediately.\n check Validate the package. Offline — no account, no cloud, no network.\n test Run one phase in the real ${BRAND_SHORT_NAME} runner image.\n publish Upload it to ${BRAND_SHORT_NAME} as an authored version. Needs an account.\n catalog <command> Publish first-party catalog artifacts. Not for authoring: see \\`runveric catalog --help\\`.\n\n${style.bold(\"init\")}\n --id <publisher/name> The action id. Required.\n --name <text> What an operator sees. Defaults from the id.\n --interpreter <name> powershell | bash | python. Defaults to bash.\n --author <text> Defaults to the publisher half of the id.\n --yes Do not prompt; use the flags and defaults.\n\n${style.bold(\"check\")}\n --strict Exit non-zero on warnings too. For CI.\n\n${style.bold(\"test\")}\n --phase <name> validate | run | rollback. Defaults to run.\n --dry-run Sets RUNVERIC_DRY_RUN=true, as an operator's rehearsal does.\n --param <name=value> A parameter value. Repeatable. Defaults come from your schema.\n --params-file <path> A JSON object of parameters. --param overrides it.\n --prior-result <path> The run's result.json. Required shape for --phase rollback.\n --image <ref> The runner image. Defaults to $${RUNNER_IMAGE_ENV}.\n --no-credential Skip \\`az account get-access-token\\`.\n --keep Keep the materialized /runveric tree for inspection.\n\n${style.bold(\"publish\")}\n --to <url> Your ${BRAND_SHORT_NAME} URL. Defaults to $${URL_ENV}.\n --token <token> Access token. Defaults to $${TOKEN_ENV}.\n --force Publish despite lint errors. Never bypasses ${BRAND_SHORT_NAME}'s validation.\n\n${style.bold(\"EVERYWHERE\")}\n --dir <path> The package directory. Defaults to the current directory.\n --help, --version\n`;\n\ninterface Parsed {\n command: string | undefined;\n positional: string[];\n flags: Map<string, string[]>;\n}\n\n/**\n * `--name value`, `--name=value` and boolean `--flag`. A flag repeated collects its values, so\n * `--param a=1 --param b=2` works without a special case anywhere else.\n */\nfunction parseArgv(argv: readonly string[]): Parsed {\n const positional: string[] = [];\n const flags = new Map<string, string[]>();\n let command: string | undefined;\n\n for (let index = 0; index < argv.length; index += 1) {\n const argument = argv[index]!;\n if (!argument.startsWith(\"--\")) {\n if (command === undefined) command = argument;\n else positional.push(argument);\n continue;\n }\n const separator = argument.indexOf(\"=\");\n const name = separator === -1 ? argument.slice(2) : argument.slice(2, separator);\n let value: string;\n if (separator !== -1) {\n value = argument.slice(separator + 1);\n } else if (argv[index + 1] !== undefined && !argv[index + 1]!.startsWith(\"--\")) {\n value = argv[index + 1]!;\n index += 1;\n } else {\n value = \"true\";\n }\n flags.set(name, [...(flags.get(name) ?? []), value]);\n }\n return { command, positional, flags };\n}\n\nconst first = (parsed: Parsed, name: string): string | undefined => parsed.flags.get(name)?.[0];\nconst bool = (parsed: Parsed, name: string): boolean => parsed.flags.get(name)?.[0] === \"true\";\n\nasync function main(): Promise<number> {\n const argv = process.argv.slice(2);\n // Before the parser: `catalog publish-release --version <label>` must not read as `--version`.\n if (argv[0] === \"catalog\") return runCatalog(argv.slice(1));\n const parsed = parseArgv(argv);\n\n if (parsed.flags.has(\"version\")) {\n print(version);\n return 0;\n }\n if (parsed.command === undefined || parsed.flags.has(\"help\") || parsed.command === \"help\") {\n print(USAGE);\n return parsed.command === undefined && !parsed.flags.has(\"help\") ? 1 : 0;\n }\n\n const directory = first(parsed, \"dir\");\n\n switch (parsed.command) {\n case \"init\":\n return runInit({\n ...(parsed.positional[0] !== undefined ? { directory: parsed.positional[0] } : {}),\n ...(directory !== undefined ? { directory } : {}),\n ...pick(parsed, [\"id\", \"name\", \"interpreter\", \"author\"]),\n yes: bool(parsed, \"yes\"),\n });\n case \"check\":\n return runCheck({\n ...(directory !== undefined ? { directory } : {}),\n strict: bool(parsed, \"strict\"),\n });\n case \"test\":\n return runTest({\n ...(directory !== undefined ? { directory } : {}),\n ...pick(parsed, [\"phase\", \"image\"]),\n ...(first(parsed, \"params-file\") !== undefined\n ? { paramsFile: first(parsed, \"params-file\")! }\n : {}),\n ...(first(parsed, \"prior-result\") !== undefined\n ? { priorResult: first(parsed, \"prior-result\")! }\n : {}),\n ...(parsed.flags.has(\"param\") ? { param: parsed.flags.get(\"param\")! } : {}),\n dryRun: bool(parsed, \"dry-run\"),\n noCredential: bool(parsed, \"no-credential\"),\n keep: bool(parsed, \"keep\"),\n });\n case \"publish\":\n return runPublish({\n ...(directory !== undefined ? { directory } : {}),\n ...pick(parsed, [\"to\", \"token\"]),\n force: bool(parsed, \"force\"),\n });\n default:\n printError(\n style.red(`\"${parsed.command}\" is not a command.`) +\n \" There are four: init, check, test, publish — and catalog, which publishes first-party catalog artifacts.\",\n );\n return 1;\n }\n}\n\nfunction pick<K extends string>(parsed: Parsed, names: readonly K[]): Partial<Record<K, string>> {\n const picked: Partial<Record<K, string>> = {};\n for (const name of names) {\n const value = first(parsed, name);\n if (value !== undefined) picked[name] = value;\n }\n return picked;\n}\n\nmain()\n .then((code) => {\n process.exitCode = code;\n })\n .catch((error: unknown) => {\n // An unexpected throw is a defect in THIS tool, and is labelled as one. An author who\n // cannot tell \"your package is wrong\" from \"our tool broke\" wastes their time on the wrong\n // one, which is exactly the trap `check` exists to avoid.\n printError(\n style.red(\"runveric hit an unexpected error. This is a bug in the tool, not in your package.\"),\n );\n printError(error instanceof Error ? (error.stack ?? error.message) : String(error));\n process.exitCode = 1;\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,YAAA,eAAA;AA0IA,YAAA,2BAAA;AA9La,YAAA,YAAY;MAAC;MAAS;MAAO;MAAO;;AAIpC,YAAA,sBAAsB;MACjC;MACA;MACA;MACA;MACA;;AAKW,YAAA,oBAAoB;MAAC;MAAS;MAAU;;AAIx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AAI,OAAA,IAAW;UAAEY,OAAOjB,OAAOjB,MAAMe,IAAI,OAAA;QAAU,IAAI,CAAC;QACzEoB,QAAQjB,KAAKD,QAAQ,SAAA;QACrBmB,cAAclB,KAAKD,QAAQ,eAAA;QAC3BoB,MAAMnB,KAAKD,QAAQ,MAAA;MACrB,CAAA;IACF,KAAK;AACH,aAAOqB,WAAW;QAChB,GAAIb,cAAclB,SAAY;UAAEkB;QAAU,IAAI,CAAC;QAC/C,GAAGE,KAAKV,QAAQ;UAAC;UAAM;SAAQ;QAC/BsB,OAAOrB,KAAKD,QAAQ,OAAA;MACtB,CAAA;IACF;AACEuB,iBACElD,MAAMmD,IAAI,IAAIxB,OAAOf,OAAO,qBAAqB,IAC/C,gHAAA;AAEJ,aAAO;EACX;AACF;AA1DeiB;AA4Df,SAASQ,KAAuBV,QAAgByB,OAAmB;AACjE,QAAMC,SAAqC,CAAC;AAC5C,aAAWhC,QAAQ+B,OAAO;AACxB,UAAM7B,QAAQG,MAAMC,QAAQN,IAAAA;AAC5B,QAAIE,UAAUN,OAAWoC,QAAOhC,IAAAA,IAAQE;EAC1C;AACA,SAAO8B;AACT;AAPShB;AASTR,KAAAA,EACGyB,KAAK,CAACC,SAAAA;AACLzB,UAAQ0B,WAAWD;AACrB,CAAA,EACCE,MAAM,CAACC,UAAAA;AAINR,aACElD,MAAMmD,IAAI,mFAAA,CAAA;AAEZD,aAAWQ,iBAAiBC,QAASD,MAAME,SAASF,MAAMG,UAAWC,OAAOJ,KAAAA,CAAAA;AAC5E5B,UAAQ0B,WAAW;AACrB,CAAA;","names":["parseProblemDocument","problemFieldErrors","run","actionSourceRepository","actionPackageRefusal","first","parseCatalogReleaseSpec","isMapping","version","provenance","provenance","provenance","first","provenance","tokens","token","origin","tokens","token","imageConfigDescriptor","actionImageRefusal","provenance","first","token","validatePackageResult","isInterpreter","token","readManifest","checkActionPackage","scaffoldActionPackage","version","command","useColour","process","stdout","isTTY","env","NO_COLOR","paint","code","text","style","bold","dim","red","green","yellow","blue","grey","print","line","write","printError","stderr","printFinding","finding","badge","severity","advisory","at","undefined","file","column","message","fix","rule","printCheckSummary","counts","errors","warnings","parts","push","summary","join","printEvent","event","marker","info","warn","error","success","level","data","JSON","stringify","printResult","result","status","succeeded","failed","cancelled","checks","length","check","passed","warning","outputs","Object","keys","name","value","entries","rollbackCapture","retryable","import_contracts","readFileSync","dirname","resolve","parse","parseYaml","execFileSync","createHash","parseRepository","ref","flag","ARTIFACT_REPOSITORY_PATTERN","test","Error","cut","indexOf","host","slice","path","namespace","lastIndexOf","isDigest","value","ARTIFACT_DIGEST_PATTERN","TAG_PATTERN","requireTag","tag","origin","LOOPBACK","sha256","bytes","createHash","update","digest","EMPTY_CONFIG","Buffer","from","EMPTY_CONFIG_DESCRIPTOR","mediaType","size","length","MANIFEST_ACCEPT","MANIFEST_MEDIA_TYPES","join","provenance","flags","dir","git","args","execFileSync","encoding","stdio","trim","actions","process","env","GITHUB_SERVER_URL","GITHUB_REPOSITORY","repository","commit","GITHUB_SHA","publishedAt","Date","toISOString","buildArtifact","document","documentBytes","JSON","stringify","manifest","schemaVersion","OCI_IMAGE_MANIFEST","artifactType","CATALOG_ARTIFACT_MEDIA_TYPE","config","layers","annotations","manifestBytes","manifestDigest","basicCredential","pat","GHCR_TOKEN","toString","workflow","GITHUB_TOKEN","GITHUB_ACTOR","undefined","tokens","Map","token","challenge","access","field","name","RegExp","exec","realm","url","URL","service","searchParams","set","credential","answer","fetch","headers","Authorization","ok","status","body","json","access_token","call","method","startsWith","send","bearer","redirect","get","pushBlob","started","location","put","String","text","manifestExists","Accept","readVerified","kind","arrayBuffer","served","readManifest","readBlob","parseJsonBytes","what","parse","TextDecoder","fatal","decode","cause","message","readArtifactDocument","Array","isArray","layer","pushArtifact","artifact","reference","asked","reported","defaultTag","replace","toLowerCase","parseCatalogFlags","argv","known","repeated","single","many","index","length","argument","separator","indexOf","name","slice","startsWith","includes","Error","value","undefined","push","import_contracts","parseImageReference","value","origin","at","lastIndexOf","digest","slice","isDigest","Error","repository","parseRepository","ref","imageRefusal","image","key","provenance","manifestBytes","readManifest","length","MAX_IMAGE_MANIFEST_BYTES","manifest","parseJsonBytes","descriptor","imageConfigDescriptor","config","readBlob","size","actionImageRefusal","PUBLISH_ACTION_USAGE","isMapping","value","Array","isArray","runPublishAction","argv","single","flags","parseCatalogFlags","manifest","to","Error","repository","parseRepository","image","undefined","parseImageReference","ref","path","resolve","readFileSync","parsed","parseYaml","cause","message","String","fields","key","length","misnamed","actionPackageRefusal","executes","execution","tag","declares","version","defaultTag","requireTag","recorded","provenance","dirname","refusal","imageRefusal","artifact","buildArtifact","schemaVersion","CATALOG_ACTION_ARTIFACT_SCHEMA_V1","CATALOG_ACTION_ARTIFACT_SCHEMA_V2","digest","pushArtifact","process","stderr","write","stdout","import_contracts","readFileSync","parse","parseYaml","PUBLISH_RELEASE_USAGE","entriesFromFlags","values","map","value","match","exec","Error","key","artifactRef","digest","label","specFromFile","path","parseYaml","readFileSync","cause","message","String","spec","parseCatalogReleaseSpec","version","entries","actions","action","runPublishRelease","argv","single","flags","many","parseCatalogFlags","actionFlags","from","undefined","length","to","release","parseRepository","tag","defaultTag","requireTag","seen","Set","entry","has","add","repository","namespace","isDigest","misnamed","actionPackageRefusal","manifestExists","artifact","buildArtifact","schemaVersion","CATALOG_RELEASE_SCHEMA_V1","provenance","process","cwd","pushArtifact","stderr","write","ref","stdout","import_contracts","readFileSync","parse","parseYaml","VERIFY_IMAGE_USAGE","COMMIT","isMapping","value","Array","isArray","single","flags","key","commit","Error","test","image","parseImageReference","misnamed","actionPackageRefusal","repository","ref","provenance","actionSourceRepository","label","fromRelease","path","parseYaml","readFileSync","cause","message","String","candidates","action","parseCatalogReleaseSpec","actions","artifactRef","isDigest","digest","parseRepository","read","readArtifactDocument","document","schemaVersion","CATALOG_ACTION_ARTIFACT_SCHEMA_V1","CATALOG_ACTION_ARTIFACT_SCHEMA_V2","JSON","stringify","undefined","recorded","push","runVerifyImage","argv","startsWith","parseCatalogFlags","slice","from","candidate","refusal","imageRefusal","process","stderr","write","stdout","length","CATALOG_USAGE","PUBLISH_ACTION_USAGE","PUBLISH_RELEASE_USAGE","VERIFY_IMAGE_USAGE","SUBCOMMANDS","runPublishAction","runPublishRelease","runVerifyImage","runCatalog","argv","subcommand","rest","undefined","includes","process","stdout","write","run","printError","Object","keys","length","join","error","Error","message","String","resolve","readdir","readFile","stat","join","relative","sep","IGNORED_DIRECTORIES","Set","MAX_FILES","MAX_TOTAL_BYTES","PackageDirectoryError","Error","readPackageDirectory","root","properties","stat","catch","isDirectory","files","Map","totalBytes","walk","directory","entry","readdir","withFileTypes","has","name","full","join","isFile","size","contents","readFile","byteLength","set","toPackagePath","relative","split","sep","import_contracts","runCheck","options","directory","resolve","files","readPackageDirectory","error","printError","style","red","Error","message","String","report","checkActionPackage","print","bold","grey","finding","findings","printFinding","printCheckSummary","errors","errorCount","warnings","warningCount","validation","ok","lintBlocked","BRAND_SHORT_NAME","advisoryCount","strictFailure","strict","failed","import_contracts","import_action_manifest","mkdir","writeFile","createInterface","dirname","join","resolve","runInit","options","interactive","process","stdin","isTTY","yes","ask","prompter","id","resolveId","suggestedName","titleCase","split","name","trim","interpreter","resolveInterpreter","author","directory","resolve","files","scaffoldActionPackage","year","Date","getFullYear","path","contents","target","join","mkdir","dirname","recursive","writeFile","flag","catch","error","code","Error","print","style","green","bold","keys","grey","printError","red","message","String","close","supplied","value","PACKAGE_ID_PATTERN","test","PACKAGE_INTERPRETERS","isInterpreter","BRAND_SHORT_NAME","rl","createInterface","input","output","stdout","question","fallback","suffix","answer","includes","filter","Boolean","map","word","charAt","toUpperCase","slice","import_action_manifest","import_contracts","resolve","renamedVariableRefusal","current","retired","env","process","trim","TOKEN_ENV","AUTHORING_CLI_ENV","token","URL_ENV","url","runPublish","options","directory","resolve","baseUrl","to","process","env","trim","replace","stale","undefined","renamedVariableRefusal","RETIRED_AUTHORING_CLI_ENV","filter","sentence","length","printError","style","red","BRAND_ARTICLE","BRAND_SHORT_NAME","files","readPackageDirectory","error","Error","message","String","report","checkActionPackage","validation","ok","lintBlocked","force","print","finding","findings","f","severity","printFinding","printCheckSummary","errors","errorCount","warnings","warningCount","advisoryCount","advisory","yellow","manifest","bold","id","version","body","JSON","stringify","map","path","contents","contentBase64","toString","response","fetch","method","headers","authorization","text","status","formatProblem","parse","green","packageId","semanticVersion","contentDigest","tier","grey","provenance","parsed","problem","parseProblemDocument","lines","detail","push","problemFieldErrors","field","join","import_contracts","execFile","promisify","run","promisify","execFile","LOCAL_RUNNER_IMAGE","RUNNER_IMAGE_ENV","AUTHORING_CLI_ENV","runnerImage","RenamedVariableError","Error","resolveRunnerImage","flag","explicit","trim","reference","origin","configured","process","env","stale","renamedVariableRefusal","RETIRED_AUTHORING_CLI_ENV","runnerImageNote","image","BRAND_SHORT_NAME","DockerMissingError","assertDockerAvailable","imageIsPresent","import_action_manifest","spawn","mkdir","mkdtemp","readFile","rm","stat","writeFile","tmpdir","dirname","join","resolve","StringDecoder","execFile","promisify","run","promisify","execFile","AzureCredentialError","Error","MANAGEMENT_RESOURCE","acquireAzureCredential","account","azJson","id","tenantId","token","accessToken","env","AZURE_SUBSCRIPTION_ID","AZURE_TENANT_ID","name","subscriptionId","args","stdout","maxBuffer","error","message","String","includes","join","trim","JSON","parse","import_contracts","PHASES","CONTAINER","packageRoot","input","output","scratch","creds","runTest","options","directory","resolve","phase","includes","printError","style","red","BRAND_SHORT_NAME","join","files","readPackageDirectory","error","Error","message","String","report","checkActionPackage","validation","ok","manifest","parameterSchema","runtime","kind","image","interpreter","name","entrypoint","entrypointFor","parameters","resolveParameters","resolveRunnerImage","assertDockerAvailable","credential","noCredential","acquireAzureCredential","AzureCredentialError","workspace","mkdtemp","tmpdir","layout","materialize","dryRun","subscriptionId","account","priorResult","readJsonFile","undefined","credentialToken","token","print","bold","id","version","grey","reference","runnerImageNote","PACKAGE_INTERPRETER_LAUNCH","entryFile","requiresNetwork","yellow","egressAllowlist","imageIsPresent","events","exit","runContainer","credentialEnv","env","timeoutMs","onEvent","event","push","printEvent","length","reportOutcome","resultPath","keep","rm","recursive","force","validateEntrypoint","rollbackEntrypoint","schema","properties","property","Object","entries","default","paramsFile","supplied","value","pair","param","separator","indexOf","slice","raw","keys","type","missing","required","filter","hasCredential","hasPriorResult","Promise","all","map","mkdir","path","contents","target","dirname","writeFile","context","protocolVersion","PACKAGE_EXECUTION_PROTOCOL_VERSION","executionId","provider","providerScopeId","JSON","stringify","mode","launch","script","environment","RUNVERIC_PROTOCOL_VERSION","PACKAGE_RESULT_PROTOCOL_VERSION","RUNVERIC_PHASE","RUNVERIC_CONTEXT_FILE","RUNVERIC_PARAMETERS_FILE","RUNVERIC_RESULT_FILE","RUNVERIC_WORK_DIR","RUNVERIC_CANCEL_FILE","RUNVERIC_DRY_RUN","RUNVERIC_NETWORK_ISOLATED","LANG","LC_ALL","POWERSHELL_TELEMETRY_OPTOUT","DOTNET_CLI_TELEMETRY_OPTOUT","RUNVERIC_PRIOR_RESULT_FILE","RUNVERIC_AZURE_TOKEN_FILE","args","flatMap","fileName","arguments","resolvePromise","reject","child","spawn","stdio","timedOut","timer","setTimeout","kill","consume","stderr","decoder","StringDecoder","pending","chunk","write","lines","split","pop","line","emitLine","stdout","on","once","clearTimeout","code","prefix","startsWith","parsed","parse","Array","isArray","level","exists","stat","catch","isFile","size","readFile","result","validatePackageResult","printResult","status","source","import_contracts","USAGE","style","bold","BRAND_ARTICLE","BRAND_SHORT_NAME","RUNNER_IMAGE_ENV","URL_ENV","TOKEN_ENV","parseArgv","argv","positional","flags","Map","command","index","length","argument","startsWith","undefined","push","separator","indexOf","name","slice","value","set","get","first","parsed","bool","main","process","runCatalog","has","print","version","directory","runInit","pick","yes","runCheck","strict","runTest","paramsFile","priorResult","param","dryRun","noCredential","keep","runPublish","force","printError","red","names","picked","then","code","exitCode","catch","error","Error","stack","message","String"]}
1
+ {"version":3,"sources":["../../contracts/src/enums.ts","../../contracts/src/brand.ts","../../contracts/src/wire-identity.ts","../../contracts/src/problem.ts","../../contracts/src/permissions.ts","../../contracts/src/request-context.ts","../../contracts/src/role-permissions.ts","../../contracts/dist/me.js","../../contracts/dist/tenant-users.js","../../contracts/dist/invitations.js","../../contracts/dist/groups.js","../../contracts/src/catalog-version.ts","../../contracts/src/catalog-policy.ts","../../contracts/src/catalog.ts","../../contracts/src/catalog-release.ts","../../contracts/src/action-repository.ts","../../contracts/src/catalog-release-spec.ts","../../contracts/src/catalog-lock.ts","../../contracts/src/catalog-manifest-placeholders.ts","../../contracts/src/change-control.ts","../../contracts/src/run-placement.ts","../../contracts/src/package-provenance.ts","../../contracts/src/package-tier.ts","../../contracts/src/packages.ts","../../contracts/src/validation.ts","../../contracts/src/execution.ts","../../contracts/src/decisions.ts","../../contracts/src/execution-site.ts","../../contracts/src/connections.ts","../../contracts/src/resources.ts","../../contracts/src/governance.ts","../../contracts/dist/audit.js","../../contracts/src/notifications.ts","../../contracts/dist/scheduling.js","../../contracts/src/operations.ts","../../contracts/src/runs.ts","../../contracts/src/evidence-pack.ts","../../contracts/src/package-egress.ts","../../contracts/src/package-execution.ts","../../contracts/src/runner-confinement.ts","../../contracts/src/runner-install.ts","../../contracts/src/authoring-cli.ts","../../contracts/src/runners.ts","../../contracts/src/scoped-credential.ts","../../contracts/src/action-protocol.ts","../../contracts/src/action-signing.ts","../../contracts/src/oci-media-types.ts","../../contracts/src/action-image.ts","../../contracts/src/catalog-templates.ts","../../contracts/src/runner-pool-presence.ts","../../contracts/src/runner-pool-routing.ts","../../contracts/src/target-identity.ts","../../contracts/src/declared-targets.ts","../../contracts/src/catalog-parameters.ts","../../contracts/src/engine-run.ts","../../contracts/src/which-entra.ts","../../contracts/src/onboarding.ts","../../contracts/src/workspace-domain.ts","../../contracts/src/workspace-features.ts","../../contracts/src/directory-sync.ts","../../contracts/src/workos-binding.ts","../../contracts/src/index.ts","../../contracts/src/action-sdk.public.ts","../../action-sdk/src/index.ts","../../action-sdk/src/define-action.ts","../../action-sdk/src/context.ts","../../action-sdk/src/credential.ts","../../action-runtime/src/index.ts","../../action-runtime/src/run-action.ts","../../action-runtime/src/transport.ts","../../action-runtime/src/http-transport.ts","../../action-runtime/src/main.ts","../../action-runtime/src/egress-wait.ts","../../action-runtime/src/probe.ts","../../action-manifest/src/package-runtime-declaration.ts","../../action-manifest/src/manifest.schema.ts","../../action-manifest/src/manifest-validator.ts","../../action-manifest/src/package-result-validator.ts","../../action-manifest/src/package-validation.ts","../../action-manifest/src/source-location.ts","../../action-manifest/src/findings.ts","../../action-manifest/src/interpreter-launch.ts","../../action-manifest/src/authoring-lint.ts","../../action-manifest/src/parameters-location.ts","../../action-manifest/src/check.ts","../../action-manifest/src/powershell-param-detection.ts","../../action-manifest/src/scaffold.ts","../../action-manifest/src/index.ts","../package.json","../src/action/index.ts","../src/report.ts","../src/action/init.ts","../src/action/flags.ts","../../../templates/engine-action-repository/.github/workflows/publish.yml","engine-action-template:/home/runner/work/runveric/runveric/templates/engine-action-repository","../../action-sdk/package.json","../../../node_modules/.pnpm/esbuild@0.27.7/node_modules/esbuild/package.json","../../../node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/package.json","../src/action/scaffold.ts","../src/action/arm.ts","../src/action/test.ts","../src/catalog/publish-action.ts","../src/catalog/artifact.ts","../src/catalog/flags.ts","../src/catalog/image.ts","../src/catalog/publish-release.ts","../src/catalog/verify-image.ts","../src/catalog/index.ts","../src/check.ts","../src/package-dir.ts","../src/init.ts","../src/publish.ts","../src/renamed-variable.ts","../src/runner-image.ts","../src/test.ts","../src/azure-credential.ts","../src/main.ts"],"mappings":";;;q0DAiEA,QAAA,aAAA,aA0IA,QAAA,yBAAA,yBA9La,QAAA,UAAY,CAAC,QAAS,MAAO,MAAO,aAIpC,QAAA,oBAAsB,CACjC,oBACA,mBACA,WACA,cACA,aAKW,QAAA,kBAAoB,CAAC,QAAS,SAAU,YAIxC,QAAA,uBAAyB,CACpC,eACA,UACA,UACA,aAIW,QAAA,kBAAoB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ACA,GACA,6GACA,kGACA,mCACA,yDACA,+CACA,UACA,uEACA,oCACA,kFACA,OACA,GACA,0BACA,yCACA,oDACA,qHACA,QACA,uEACA,wGACA,OACA,MACA,IACAK,KAAK,IAAA,CACT,CApDSxB,oCAuDT,SAASI,iBAAAA,CACP,MAAO,CACL0C,aAAc,CAAE3D,cAAeD,oBAAoBC,cAAeC,SAAUF,oBAAoBE,QAAS,EACzG2D,QAAS,CAAEC,OAAQ,YAAaC,QAAS,YAAY/D,oBAAoBE,QAAQ,GAAI,CACvF,CACF,CALSgB,0CAOT,SAASH,YAAYX,MAA0B,CAC7C,MAAM4D,OAAS,OAACC,OAA0BjD,KAAKC,UAAUgD,KAAAA,EAA1C,UACf,MAAO,CACL,oGACA,0FACA,iCACA,QAAQD,OAAO5D,MAAMG,GAAG,CAAA,GACxB,SAASyD,OAAO5D,MAAMQ,IAAI,CAAA,GAC1B,kEACA,4FACA,sBACA,iBAAiBoD,OAAOE,qCAAAA,CAAAA,GACxB,oBACA,4DACA,aACA,mBACA,eAAeF,OAAOG,mCAAAA,CAAAA,GACtB,0GACA,oEACA,eACA,eACA,SAASH,OAAOI,YAAAA,CAAAA,GAChB,gBACA,oBACA,mBACA,0BACA,iBACA,sBACA,sGACA,YAAYJ,OAAOK,qCAAAA,CAAAA,GACnB,UACA,0BACA,8BACA,sBACA,yDACA,qBACA,cACA,wCACA,0FACA,qBACA,wBACA,sBACA,qCACA,qBACA,cACA,8BACA,uBAAuBL,OAAOrE,sBAAAA,CAAAA,GAC9B,mBACA,4BACA,uBACA,qBACA,4BACA,4BACA,YACA,cACA,qBACA,8DACA,cACA,sBACA,oEACA,cACA,mBACA,yFACA,IACA2C,KAAK,IAAA,CACT,CAjESvB,kCAmET,SAASI,OAAOf,MAA4BC,WAAkB,CAC5D,MAAO,CACL,KAAKD,MAAMQ,IAAI,GACf,GACA,KAAKR,MAAMG,GAAG,aAAQyB,8BAAAA,IAAiBC,iCAAAA,6DACvC,yGACA,GACA,cACA,G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AQ2B,SAAWD,IACrB,CAAA,EACCE,MAAOC,OAAAA,CAINR,WACEnD,MAAMoD,IAAI,mFAAA,CAAA,EAEZD,WAAWQ,iBAAiBC,MAASD,MAAME,OAASF,MAAMG,QAAWC,OAAOJ,KAAAA,CAAAA,EAC5E7B,QAAQ2B,SAAW,CACrB,CAAA","names":["parseProblemDocument","problemFieldErrors","version","run","name","actionKeyRefusal","actionRepositoryName","actionSourceRepository","actionPackageRefusal","name","first","parseCatalogReleaseSpec","isMapping","version","provenance","provenance","provenance","settleDecisionChecks","name","first","provenance","tokens","token","redactSecrets","redactJwtShaped","parseActionInvocation","parseActionEvent","parseActionCheckpoint","parseActionReport","origin","objectOf","tokens","token","imageConfigDescriptor","actionImageRefusal","provenance","renderTemplate","workflowValues","name","name","first","name","catalogParameterSchema","engineRunTarget","destructiveSuccessRefusal","token","defineAction","definition","handler","TypeError","rollback","undefined","import_action_sdk","actionCredential","tokens","now","Date","holder","ENGINE_ACTION_TOKEN_HOLDER","StaticScopedCredential","map","token","scope","actionTokenScope","audience","expiresOnTimestamp","parse","expiresOn","RestorePointNotAcknowledgedError","Error","reason","name","validateContext","invocation","channel","signal","commonContext","mode","targets","decisions","executeContext","target","onlyTarget","restorePoint","saveRestorePoint","__name","record","answer","checkpoint","kind","cause","messageOf","parseCheckpointAck","rollbackContext","priorResult","azure","credentials","emit","event","dryRun","execution","action","key","version","id","tenantId","correlationId","length","message","String","import_contracts","runAction","definition","transport","options","now","Date","invocation","parseActionInvocation","fetchInvocation","secrets","credentials","tokens","map","token","handlerSignal","AbortController","deadlineTimer","deadlineReached","Promise","resolve","setTimeout","abort","ActionDeadlineError","limits","deadline","DEADLINE","Math","max","parse","onCancel","__name","cancel","reason","aborted","addEventListener","once","channel","emit","event","postEvent","redactSecrets","checkpoint","postCheckpoint","answered","race","answer","signal","tokenHolder","catch","error","failedReport","isCancel","report","postReport","clearTimeout","removeEventListener","Error","name","Symbol","holder","phase","checks","validate","validateContext","outcome","execute","executeContext","rollback","status","message","action","key","rollbackContext","messageOf","String","length","LoopbackTransport","engine","overTheWire","value","text","JSON","stringify","undefined","EngineRefusedError","HttpTransport","fetch","assertSafeOrigin","callbackBaseUrl","globalThis","response","send","refusalOf","json","method","body","engineRunUrl","runId","redirect","headers","RUN_TOKEN_HEADER","runToken","accept","LOOPBACK_HOSTS","Set","url","URL","protocol","has","hostname","origin","sentence","import_action_sdk","EGRESS_WAIT","timeoutMs","intervalMs","EgressProxyNotListeningError","EgressProxyUrlError","REAL_CLOCK","sleep","ms","egressProxyUrl","env","HTTPS_PROXY","https_proxy","egressProxyAddress","proxyUrl","host","replace","port","Number","waitForEgressProxy","address","connect","netConnect","clock","accepts","settled","socket","finish","accepted","destroy","on","ACTION_ENTRY","RUNTIME_EXIT","reported","failed","misconfigured","refused","main","job","missing","Object","values","ACTION_CONTAINER_ENV","filter","say","join","line","redactJwtShaped","imageDigest","ARTIFACT_DIGEST_PATTERN","test","openTransport","proxy","notRun","actionOf","load","fetched","image","endsWith","refusal","sent","endingOf","loaded","from","candidate","default","defineAction","import_node_net","AZURE_IDENTITY_ENV","endpoint","header","AZURE_IDENTITY_API_VERSION","MANAGEMENT_RESOURCE","PROBE_CONNECT_TARGETS","ANSWER_TIMEOUT_MS","PROBE_EXIT","probed","probe","callback","fetchOf","identities","ACTION_PROBE_ENV","split","id","trim","label","identityLabel","statusOf","searchParams","set","startsWith","neverListened","target","connectStatus","health","Boolean","pop","request","withTimeout","received","timer","write","chunk","toString","end","indexOf","code","exec","slice","promise","reject","then","name","name","validatePackageResult","name","name","isInterpreter","token","readManifest","checkActionPackage","scaffoldActionPackage","readme","version","command","import_contracts","useColour","process","stdout","isTTY","env","NO_COLOR","paint","code","text","style","bold","dim","red","green","yellow","blue","grey","print","line","write","printError","stderr","printFinding","finding","badge","severity","advisory","at","undefined","file","column","message","fix","rule","printCheckSummary","counts","errors","warnings","parts","push","summary","join","printEvent","event","marker","info","warn","error","success","level","data","JSON","stringify","printResult","result","status","succeeded","failed","cancelled","checks","length","check","passed","warning","outputs","Object","keys","name","value","entries","rollbackCapture","retryable","import_contracts","access","mkdir","writeFile","dirname","join","relative","resolve","parseActionFlags","argv","spec","parsed","single","many","on","positional","index","length","argument","startsWith","Error","push","separator","indexOf","name","slice","booleans","includes","values","value","undefined","repeated","name","version","version","version","ARM_AUDIENCE","SKELETON_RESOURCE_TYPE","CLI_BIN","Object","keys","bin","SKELETON_PARAMETERS","resourceGroup","resource","scaffoldEngineAction","input","repository","actionRepositoryName","key","files","Map","set","packageJson","name","tsconfigJson","actionSource","catalogYaml","JSON","stringify","recordedExecute","readme","values","workflowValues","version","path","text","entries","engineActionTemplate","renderTemplate","phase","extra","private","description","BRAND_ARTICLE","BRAND_SHORT_NAME","scripts","typecheck","build","test","join","dependencies","SDK_NAME","SDK_VERSION","devDependencies","CLI_NAME","CLI_VERSION","esbuild","ESBUILD_VERSION","typescript","TYPESCRIPT_VERSION","engines","node","compilerOptions","strict","noEmit","target","module","moduleResolution","types","skipLibCheck","include","restorePoint","outcome","status","message","quoted","value","ENGINE_CONNECTOR_KEY","ACTION_PROTOCOL_V1","ARM_AUDIENCE","FIRST_ACTION_VERSION","ACTION_INIT_USAGE","runActionInit","argv","flags","parseActionFlags","values","positional","key","single","trim","Error","refusal","actionKeyRefusal","name","directory","resolve","actionRepositoryName","files","scaffoldEngineAction","existing","path","keys","access","join","then","push","length","contents","target","mkdir","dirname","recursive","writeFile","flag","catch","error","code","below","relative","process","cwd","shown","startsWith","print","style","green","bold","grey","import_contracts","execFile","access","readFile","createRequire","join","resolve","promisify","parse","parseYaml","runProgram","promisify","execFile","ACTION_TEST_USAGE","PHASES","validate","execute","rollback","CATALOG_PROVIDER","LOCAL_SUBSCRIPTION_ID","LOCAL_DEADLINE_MS","LOCAL_RUN","CLI_BIN","Object","keys","bin","LOCAL_TOKEN_HOLDER","noun","whereDeclared","BRAND_SHORT_NAME","whyNoMore","runActionTest","argv","flags","parseActionFlags","values","repeated","booleans","phase","single","undefined","hasOwn","Error","join","directory","resolve","dir","manifest","engineManifest","entry","access","then","parameters","parametersOf","params","many","param","parameterSchema","catalogParameterSchema","tokens","subscription","on","audiences","includes","ARM_AUDIENCE","fromAz","armTokenFromAz","token","target","engineRunTarget","key","provider","providerScopeId","prior","priorOf","restorePoint","priorResult","invocation","invocationFor","definition","actionOf","createRequire","error","messageOf","secrets","map","shown","value","redactJwtShaped","redactSecrets","print","style","bold","version","grey","ref","length","egress","yellow","engine","LocalEngine","failure","runAction","LoopbackTransport","tokenHolder","events","code","verdict","violation","acknowledged","parsed","sent","event","body","judged","parseActionEvent","limits","printEvent","checkpoint","parseActionCheckpoint","record","green","JSON","stringify","report","parseActionReport","parse","printError","red","refusals","questions","checks","check","settleDecisionChecks","decisions","level","decision","printCheck","outcome","refused","destructiveSuccessRefusal","destructive","dryRun","execution","acknowledgedCheckpoint","printOutcome","message","status","marker","info","warn","what","refusal","title","label","succeeded","failed","cancelled","data","base","protocol","contract","action","image","actionRepositoryName","repeat","id","tenantId","correlationId","targets","credentials","deadline","Date","now","toISOString","ACTION_PROTOCOL_LIMITS","parseActionInvocation","mode","recorded","path","text","readFile","catch","document","objectOf","parseYaml","kind","declared","capabilities","stringOf","stringsOf","Array","isArray","file","pairs","Map","set","name","has","entries","jsonObjectFile","pair","separator","indexOf","slice","raw","get","control","missing","filter","required","stdout","maxBuffer","String","stderr","trim","split","answer","accessToken","expiresAt","expires_on","Number","isFinite","expiresOn","replace","isNaN","getTime","audience","every","ACTION_USAGE","ACTION_INIT_USAGE","ACTION_TEST_USAGE","BRAND_SHORT_NAME","SUBCOMMANDS","init","argv","runActionInit","test","runActionTest","runActionCommand","subcommand","rest","undefined","includes","process","stdout","write","run","printError","Object","keys","length","join","error","Error","message","String","import_contracts","readFileSync","dirname","resolve","parse","parseYaml","import_contracts","execFileSync","createHash","parseRepository","ref","flag","ARTIFACT_REPOSITORY_PATTERN","test","Error","cut","indexOf","host","slice","path","namespace","lastIndexOf","isDigest","value","ARTIFACT_DIGEST_PATTERN","TAG_PATTERN","requireTag","tag","origin","LOOPBACK","sha256","bytes","createHash","update","digest","EMPTY_CONFIG","Buffer","from","EMPTY_CONFIG_DESCRIPTOR","mediaType","size","length","MANIFEST_ACCEPT","MANIFEST_MEDIA_TYPES","join","provenance","flags","dir","git","args","execFileSync","encoding","stdio","trim","actions","process","env","GITHUB_SERVER_URL","GITHUB_REPOSITORY","repository","commit","GITHUB_SHA","publishedAt","Date","toISOString","buildArtifact","document","documentBytes","JSON","stringify","manifest","schemaVersion","OCI_IMAGE_MANIFEST","artifactType","CATALOG_ARTIFACT_MEDIA_TYPE","config","layers","annotations","manifestBytes","manifestDigest","basicCredential","pat","GHCR_TOKEN","toString","workflow","GITHUB_TOKEN","GITHUB_ACTOR","undefined","tokens","Map","token","challenge","access","field","name","RegExp","exec","realm","url","URL","service","searchParams","set","credential","answer","fetch","headers","Authorization","ok","status","body","json","access_token","call","method","startsWith","send","bearer","redirect","get","pushBlob","started","location","put","String","text","manifestExists","Accept","readVerified","kind","arrayBuffer","served","readManifest","readBlob","parseJsonBytes","what","parse","TextDecoder","fatal","decode","cause","message","readArtifactDocument","Array","isArray","layer","pushArtifact","artifact","reference","asked","reported","defaultTag","replace","toLowerCase","parseCatalogFlags","argv","known","repeated","single","many","index","length","argument","separator","indexOf","name","slice","startsWith","includes","Error","value","undefined","push","import_contracts","parseImageReference","value","origin","at","lastIndexOf","digest","slice","isDigest","Error","repository","parseRepository","ref","imageRefusal","image","key","provenance","manifestBytes","readManifest","length","MAX_IMAGE_MANIFEST_BYTES","manifest","parseJsonBytes","descriptor","imageConfigDescriptor","config","readBlob","size","actionImageRefusal","PUBLISH_ACTION_USAGE","isMapping","value","Array","isArray","runPublishAction","argv","single","flags","parseCatalogFlags","manifest","to","Error","repository","parseRepository","image","undefined","parseImageReference","ref","path","resolve","readFileSync","parsed","parseYaml","cause","message","String","fields","key","length","misnamed","actionPackageRefusal","executes","execution","tag","declares","version","defaultTag","requireTag","recorded","provenance","dirname","refusal","imageRefusal","artifact","buildArtifact","schemaVersion","CATALOG_ACTION_ARTIFACT_SCHEMA_V1","CATALOG_ACTION_ARTIFACT_SCHEMA_V2","digest","pushArtifact","process","stderr","write","stdout","import_contracts","readFileSync","parse","parseYaml","PUBLISH_RELEASE_USAGE","entriesFromFlags","values","map","value","match","exec","Error","key","artifactRef","digest","label","specFromFile","path","parseYaml","readFileSync","cause","message","String","spec","parseCatalogReleaseSpec","version","entries","actions","action","runPublishRelease","argv","single","flags","many","parseCatalogFlags","actionFlags","from","undefined","length","to","release","parseRepository","tag","defaultTag","requireTag","seen","Set","entry","has","add","repository","namespace","isDigest","misnamed","actionPackageRefusal","manifestExists","artifact","buildArtifact","schemaVersion","CATALOG_RELEASE_SCHEMA_V1","provenance","process","cwd","pushArtifact","stderr","write","ref","stdout","import_contracts","readFileSync","parse","parseYaml","VERIFY_IMAGE_USAGE","COMMIT","isMapping","value","Array","isArray","single","flags","key","commit","Error","test","image","parseImageReference","misnamed","actionPackageRefusal","repository","ref","provenance","actionSourceRepository","label","fromRelease","path","parseYaml","readFileSync","cause","message","String","candidates","action","parseCatalogReleaseSpec","actions","artifactRef","isDigest","digest","parseRepository","read","readArtifactDocument","document","schemaVersion","CATALOG_ACTION_ARTIFACT_SCHEMA_V1","CATALOG_ACTION_ARTIFACT_SCHEMA_V2","JSON","stringify","undefined","recorded","push","runVerifyImage","argv","startsWith","parseCatalogFlags","slice","from","candidate","refusal","imageRefusal","process","stderr","write","stdout","length","CATALOG_USAGE","PUBLISH_ACTION_USAGE","PUBLISH_RELEASE_USAGE","VERIFY_IMAGE_USAGE","SUBCOMMANDS","runPublishAction","runPublishRelease","runVerifyImage","runCatalog","argv","subcommand","rest","undefined","includes","process","stdout","write","run","printError","Object","keys","length","join","error","Error","message","String","resolve","readdir","readFile","stat","join","relative","sep","IGNORED_DIRECTORIES","Set","MAX_FILES","MAX_TOTAL_BYTES","PackageDirectoryError","Error","readPackageDirectory","root","properties","stat","catch","isDirectory","files","Map","totalBytes","walk","directory","entry","readdir","withFileTypes","has","name","full","join","isFile","size","contents","readFile","byteLength","set","toPackagePath","relative","split","sep","import_contracts","runCheck","options","directory","resolve","files","readPackageDirectory","error","printError","style","red","Error","message","String","report","checkActionPackage","print","bold","grey","finding","findings","printFinding","printCheckSummary","errors","errorCount","warnings","warningCount","validation","ok","lintBlocked","BRAND_SHORT_NAME","advisoryCount","strictFailure","strict","failed","import_contracts","import_action_manifest","mkdir","writeFile","createInterface","dirname","join","resolve","runInit","options","interactive","process","stdin","isTTY","yes","ask","prompter","id","resolveId","suggestedName","titleCase","split","name","trim","interpreter","resolveInterpreter","author","directory","resolve","files","scaffoldActionPackage","year","Date","getFullYear","path","contents","target","join","mkdir","dirname","recursive","writeFile","flag","catch","error","code","Error","print","style","green","bold","keys","grey","printError","red","message","String","close","supplied","value","PACKAGE_ID_PATTERN","test","PACKAGE_INTERPRETERS","isInterpreter","BRAND_SHORT_NAME","rl","createInterface","input","output","stdout","question","fallback","suffix","answer","includes","filter","Boolean","map","word","charAt","toUpperCase","slice","import_action_manifest","import_contracts","resolve","renamedVariableRefusal","current","retired","env","process","trim","TOKEN_ENV","AUTHORING_CLI_ENV","token","URL_ENV","url","runPublish","options","directory","resolve","baseUrl","to","process","env","trim","replace","stale","undefined","renamedVariableRefusal","RETIRED_AUTHORING_CLI_ENV","filter","sentence","length","printError","style","red","BRAND_ARTICLE","BRAND_SHORT_NAME","files","readPackageDirectory","error","Error","message","String","report","checkActionPackage","validation","ok","lintBlocked","force","print","finding","findings","f","severity","printFinding","printCheckSummary","errors","errorCount","warnings","warningCount","advisoryCount","advisory","yellow","manifest","bold","id","version","body","JSON","stringify","map","path","contents","contentBase64","toString","response","fetch","method","headers","authorization","text","status","formatProblem","parse","green","packageId","semanticVersion","contentDigest","tier","grey","provenance","parsed","problem","parseProblemDocument","lines","detail","push","problemFieldErrors","field","join","import_contracts","execFile","promisify","run","promisify","execFile","LOCAL_RUNNER_IMAGE","RUNNER_IMAGE_ENV","AUTHORING_CLI_ENV","runnerImage","RenamedVariableError","Error","resolveRunnerImage","flag","explicit","trim","reference","origin","configured","process","env","stale","renamedVariableRefusal","RETIRED_AUTHORING_CLI_ENV","runnerImageNote","image","BRAND_SHORT_NAME","DockerMissingError","assertDockerAvailable","imageIsPresent","import_action_manifest","spawn","mkdir","mkdtemp","readFile","rm","stat","writeFile","tmpdir","dirname","join","resolve","StringDecoder","execFile","promisify","run","promisify","execFile","AzureCredentialError","Error","MANAGEMENT_RESOURCE","acquireAzureCredential","account","azJson","id","tenantId","token","accessToken","env","AZURE_SUBSCRIPTION_ID","AZURE_TENANT_ID","name","subscriptionId","args","stdout","maxBuffer","error","message","String","includes","join","trim","JSON","parse","import_contracts","PHASES","CONTAINER","packageRoot","input","output","scratch","creds","runTest","options","directory","resolve","phase","includes","printError","style","red","BRAND_SHORT_NAME","join","files","readPackageDirectory","error","Error","message","String","report","checkActionPackage","validation","ok","manifest","parameterSchema","runtime","kind","image","interpreter","name","entrypoint","entrypointFor","parameters","resolveParameters","resolveRunnerImage","assertDockerAvailable","credential","noCredential","acquireAzureCredential","AzureCredentialError","workspace","mkdtemp","tmpdir","layout","materialize","dryRun","subscriptionId","account","priorResult","readJsonFile","undefined","credentialToken","token","print","bold","id","version","grey","reference","runnerImageNote","PACKAGE_INTERPRETER_LAUNCH","entryFile","requiresNetwork","yellow","egressAllowlist","imageIsPresent","events","exit","runContainer","credentialEnv","env","timeoutMs","onEvent","event","push","printEvent","length","reportOutcome","resultPath","keep","rm","recursive","force","validateEntrypoint","rollbackEntrypoint","schema","properties","property","Object","entries","default","paramsFile","supplied","value","pair","param","separator","indexOf","slice","raw","keys","type","missing","required","filter","hasCredential","hasPriorResult","Promise","all","map","mkdir","path","contents","target","dirname","writeFile","context","protocolVersion","PACKAGE_EXECUTION_PROTOCOL_VERSION","executionId","provider","providerScopeId","JSON","stringify","mode","launch","script","environment","RUNVERIC_PROTOCOL_VERSION","PACKAGE_RESULT_PROTOCOL_VERSION","RUNVERIC_PHASE","RUNVERIC_CONTEXT_FILE","RUNVERIC_PARAMETERS_FILE","RUNVERIC_RESULT_FILE","RUNVERIC_WORK_DIR","RUNVERIC_CANCEL_FILE","RUNVERIC_DRY_RUN","RUNVERIC_NETWORK_ISOLATED","LANG","LC_ALL","POWERSHELL_TELEMETRY_OPTOUT","DOTNET_CLI_TELEMETRY_OPTOUT","RUNVERIC_PRIOR_RESULT_FILE","RUNVERIC_AZURE_TOKEN_FILE","args","flatMap","fileName","arguments","resolvePromise","reject","child","spawn","stdio","timedOut","timer","setTimeout","kill","consume","stderr","decoder","StringDecoder","pending","chunk","write","lines","split","pop","line","emitLine","stdout","on","once","clearTimeout","code","prefix","startsWith","parsed","parse","Array","isArray","level","exists","stat","catch","isFile","size","readFile","result","validatePackageResult","printResult","status","source","import_contracts","USAGE","style","bold","BRAND_ARTICLE","BRAND_SHORT_NAME","RUNNER_IMAGE_ENV","URL_ENV","TOKEN_ENV","parseArgv","argv","positional","flags","Map","command","index","length","argument","startsWith","undefined","push","separator","indexOf","name","slice","value","set","get","first","parsed","bool","main","process","runCatalog","runActionCommand","has","print","version","directory","runInit","pick","yes","runCheck","strict","runTest","paramsFile","priorResult","param","dryRun","noCredential","keep","runPublish","force","printError","red","names","picked","then","code","exitCode","catch","error","Error","stack","message","String"]}