Constraint Profiles
Constraint profiles are opt-in design policies, separate from GatePacks that
Constraint profiles
Constraint profiles are opt-in design policies, separate from GatePacks that judge runtime results. A pipeline inherits profiles through the named `CIEnvironment` documents in `CIPipeline.spec.environments`. With no environment profile, projection and validation retain their existing behavior.
The draft-07 contracts live beside CIPipeline and CIEnvironment under `$AIWG_ROOT/agentic/code/frameworks/cicd-complete/schemas/`:
- `constraint-profile.schema.json`: `ConstraintProfile`, API version
`constraints.cicd.aiwg.io/v1alpha1`.
- `constraint-definition.schema.json`: `ConstraintDefinition`, the same API version.
- `ci-environment.schema.json`: optional `spec.constraints` references and overrides.
Select and override
spec:
runner:
labels: [linux]
constraints:
- profile: aiwg:cicd-complete/enterprise-cost
`enterprise-cost` is selectable only through an explicit environment reference. It enables seven advisory capacity constraints, eight blocking pipeline-shape constraints, then seven recovery constraints. Recovery safety controls default to blocking; backpressure and fix-forward default to advisory. The family sections below describe their parameters, enforcement defaults and provider limits. An unprofiled environment is unchanged.
A populated profile references installed definitions by stable dotted `id`:
apiVersion: constraints.cicd.aiwg.io/v1alpha1
kind: ConstraintProfile
metadata:
name: example:reviewed-policy
spec:
constraints:
- id: example.required-input
enforcement: advisory
params: {label: reviewed}
rationale: Explain why this team selected the constraint.
An environment reference can contain `overrides`, an array of `{id, enforcement?, params?}`. At least one override field is required. Enforcement is explicit on every profile entry: `off` skips evaluation, `advisory` emits a warning, and `blocking` refuses projection on a violation. All diagnostics name the constraint ID and the affected job, pool or other subject.
Parameters merge shallowly: definition schemas validate the profile values and the final profile-plus-override values, even for `off`. Nested override objects replace the corresponding profile object. No implicit defaults are inserted. Override IDs must exist in the installed registry and selected profile. Unknown profiles, duplicate IDs, duplicate references and overlapping profiles fail; resolve overlaps explicitly instead of relying on ordering. The unbound environment schema rejects every override ID; the registry binds its `knownConstraintId` definition to an enum of installed IDs before validation. Structural profile validation alone does not establish reference validity.
Define and extend
Definitions live in `constraints/`, one JSON or YAML file per ID. Each has `metadata.name` equal to the stable ID, and `spec` containing:
| Field | Meaning |
|---|---|
| `params` | A strictly compiled draft-07 JSON Schema for parameter objects |
| `rationale` | Why the constraint exists |
| `tradeoff` | The cost or compromise the policy makes |
| `check.phase` | `schema`, `render-time` or `audit-time` |
| `check.validator` | A named checker supplied by the consuming validator host |
The built-in checker `json-schema` also requires `check.target` (`pipeline`, `environment` or `job`) and `check.assertion`, a strict draft-07 schema applied to each target. It checks structural assertions; it does not interpolate parameters. Parameter-dependent families supply named synchronous checker hooks receiving `{pipeline, environment, params, phase}` and returning an array of `{subject, message}` violations. Missing hooks, thrown errors or malformed results fail validation. Loading an extension never executes its code. Schema-phase checks run in every phase; other checks run in their declared phase. A render receipt does not establish an audit-phase result.
Use the existing `WorkflowExtension` in `ADDON.yaml` with `spec.extends: cicd-complete`, `spec.constraints: auto-discover` and optionally `spec.profiles: auto-discover`. Put definitions under `constraints/` and profiles under `profiles/`. Pass installed extension roots explicitly; the validator never scans a user's HOME. Duplicate definitions or profile names fail loading. The offline fixture extension under `test/fixtures/cicd/constraints/extension/` demonstrates this mechanism without shipping an enterprise policy.
Validate before rendering
The shared local validator is `$AIWG_ROOT/agentic/code/frameworks/cicd-complete/validators/constraints.mjs`. Run it before projecting any provider template:
node "$AIWG_ROOT/agentic/code/frameworks/cicd-complete/validators/constraints.mjs" \
pipeline.yaml environment.yaml --profile team-profile.yaml \
--extension installed-extension-directory
Repeat `--profile` and `--extension` as needed. Supply every environment named by the pipeline. The command emits JSON results, diagnostics on stderr, and exits nonzero on blocking violations or invalid contracts. Use `--phase audit-time` for audit checks. It makes no provider calls and writes no workflows.
Programmatic template consumers call `renderWithConstraints(pipeline, environments, registry, project, {warn, validators})`; `project` runs only after preflight succeeds. `loadConstraintRegistry` loads contracts and binds the CIEnvironment schema; `resolveEnvironmentConstraints` returns effective entries; `validateConstraints` supplies the same checks for schema/render/audit consumers. Run the local preflight again whenever the inputs or installed definitions change.
Capacity family (#4526)
All seven entries default to advisory in `enterprise-cost`; none applies without profile selection. Override individual entries to `blocking` after reviewing inventory and measurements. Built-in named hooks run in schema, render and audit phases through `validateConstraints` and the local preflight. Static inventory checks do not establish the state of a live runner cluster.
| Constraint | Default parameters and check | Cost or latency trade-off |
|---|---|---|
| `capacity.spot-first` | `on_demand_pools: [ops-critical, database]`; all other runner/build pools use spot. `spot_weight` must exceed `zone_weight`, preferring spot across zones. | Interruptions cost reruns; critical on-demand exceptions cost more. |
| `capacity.scale-to-zero` | `min_runners: 0`; every pool explicitly sets `minRunners: 0`. | Idle cost disappears; cold starts add latency. |
| `capacity.pool-caps` | `pool_caps: {pull-requests: 4, merge: 7, bisect: 7, main: 18}`; every declared pool sets `maxRunners` equal to measured `peak_runners`, within its reviewed cap. | Caps queue bursts; larger caps require measurements and spend more. |
| `capacity.pack-for-consolidation` | `minimum_packing_weight: 80`; `packing_weight` exceeds `resource_weight`, allowing quiet nodes to drain. | Denser placement increases contention and correlated failure exposure. |
| `capacity.main-pool` | `main_pool: main`, `main_branch: main`; main jobs select this declared pool with distinct routing labels. | Dedicated capacity fragments utilization; scale-to-zero limits idle cost. |
| `capacity.self-hosted-only` | `allowed_labels: [self-hosted, linux, pull-requests, merge, bisect, main]`; every pool/job uses declared self-hosted labels, with no hosted fallback. | Operators own maintenance, isolation and availability. |
| `capacity.job-timeouts-are-ceilings` | `min_multiple: 3`, `max_multiple: 5`; every job has `timeout_minutes` in that range times measured `median_minutes`. | Generous ceilings delay hang detection; hits require investigation, never automatic increases. |
Declare inventory under `CIEnvironment.spec.runner.pools`, an array of named pools with `labels`, `capacity_type` (`spot` or `on-demand`), `minRunners`, `maxRunners`, `peak_runners`, `spot_weight`, `zone_weight`, `packing_weight` and `resource_weight`. Names must be unique. Weights are integers from 0–100 (spot and packing at least 1). Keep peak and median observations in the existing assessment evidence; these fields are reviewed measurements, not live spend. Build pools belong in this inventory too. An allowed critical pool still needs scale-to-zero, cap, packing and label policy, or explicit per-constraint overrides.
Each CIPipeline job may set `runner_pool` and `runner_labels`. Pool selection falls back to `runner.default_pool`; labels fall back to the selected pool's labels, then `runner.labels`. A selected pool must exist and every routing label must be allowed. Specify `timeout_minutes` (positive integer) and `median_minutes` (positive number) on each job; no timeout is inferred or raised. The unchanged `ci-test`, `ci-cache` and build capabilities keep their own inputs; capacity fields are job metadata, never shell arguments or capability inputs.
Use separate main and pull-request pipeline documents. Every job of a main push pipeline must select the main pool; a pipeline also triggered by pull requests cannot share that pool. Missing push branch filters and wildcard filters are conservatively treated as including main; manual and scheduled pipelines also require the main pool. Non-main pipelines cannot select it. This avoids claiming per-event isolation from a workflow whose jobs have no per-event routing model. Main capacity is not silently downsized: its reviewed measured cap is rendered unchanged (18 in the reference profile), independently from PR capacity (4).
Capacity rendering and limits
The existing GitHub/Gitea Actions templates project each selected pool's labels into `runs-on` and each explicit timeout into `timeout-minutes`. Preserve branch triggers and all existing capability, secret, gate and protection bindings. The GitHub template can additionally emit reviewed ARC scale-set values with `minRunners` and `maxRunners` when the operator binds an ARC installation. Gitea act_runner has no equivalent native scale-set contract here: report not expressible for its runner scaling. A GitLab target has no installed rendering extension in this framework: report not expressible, do not invent output.
Spot/zone affinity, pod packing and scheduler resource weights require an operator-owned Kubernetes runner adapter. Without a reviewed adapter report not expressible for those fields; names/weights in inventory alone do not prove placement. Do not generate autoscaler NodePools. Existing `aiwg:cicd-complete/build-time-budget` gates continue judging observed build elapsed time via `maxBuildSeconds`; timeout ceilings detect hangs and do not replace that performance gate or raise its budget.
Synthetic fixtures under `test/fixtures/cicd/constraints/capacity/` exercise idle runners, absent caps, unapproved on-demand, hosted labels, absent timeouts and main on PR capacity. Both preflight and audit report constraint IDs and subjects.
Composing capacity, pipeline shape and recovery
Selecting `enterprise-cost` activates capacity, pipeline shape and recovery together, in that order. The capacity checker currently requires separate PR and main CIPipeline documents; the pipeline-shape GitHub preview requires combined PR/main triggers. That combined fixture therefore emits advisory capacity findings and is not proof of dedicated pool isolation. Review those findings and any explicit environment overrides before adoption; making `capacity.main-pool` blocking rejects the combined model until a reviewed routing mapping exists. Family-only fixtures isolate unrelated policies explicitly; validation never disables a sibling family automatically.
Pipeline shape (#4527)
All eight entries in this family ship as blocking, with the defaults below. Adopt them by selecting `aiwg:cicd-complete/enterprise-cost`; use environment overrides for an advisory rollout or to turn individual rules off. Parameter schemas reject unknown fields. No policy is applied without profile selection.
| ID | Default parameters | Rationale and trade-off |
|---|---|---|
| `pr.verdict-budget` | `allowed_jobs: [static, contracts]`, `max_job_seconds: 60` | Bound per-push cost with static and repository-contract checks. Heavy test regressions can reach main. The timeout measures running time, excluding runner queue wait. |
| `pr.oversize-moves-to-main` | `issue_label: ci-slow` | Keep over-budget checks in main qualification with a labelled issue. Reduced pre-merge signal must remain tracked, never silently dropped. |
| `pr.cancel-superseded` | `{}` | Group by PR number and cancel obsolete heads. Main batches must finish. |
| `main.single-flight-batches` | `max_in_flight: 1` | One complete main tree qualifies at a time; only the newest pending run remains, covering commits landed meanwhile. This trades FIFO runs for fewer batches and potentially longer feedback latency. |
| `main.publish-qualified-tree` | `{}` | Release publication consumes the successful batch's exact immutable tree and image. A red batch produces no release image. |
| `build.registry-is-cache` | `tag: tree-hash` | Look up content-addressed image tags before building; build only absent tags for changed images. Registry errors must block, never masquerade as an absent tag. |
| `merge.label-gated` | `label: merge-when-green` | An explicit label requests merging once verdicts pass for that exact head, including where native auto-merge is unavailable. Head changes race with verdicts unless the merge adapter rechecks them and supplies an expected head. |
| `gates.laptop-reproducible` | `{}` | Every gate uses the identical local command in CI, such as `nix develop -c node ci/gate.mjs`. Developers need the pinned environment and revision-bound evidence. |
Trade-offs and recovery prerequisite
This shape requires the recovery constraints from #4528. Qualifying after merge deliberately allows regressions onto main. Before production adoption, review main-green merge gating, automated bisect/revert, repair-worker access, migration safety and backpressure with that family. Pipeline-shape validation alone does not establish recovery readiness or authorize enabling this policy. Recovery implementation and provider-specific queue products are outside #4527.
A full-suite pre-merge queue keeps main green but repeats heavy qualification per entry. Full PR tests with path filters still pay for each relevant push. This profile chooses fast PR verdicts and coalesced main qualification instead.
Observed pitfalls:
- Fast verdicts must retain build-time assertions for documentation, generated
artifacts and registry consistency. A static lint alone misses their drift.
- Registry tests should derive expected registrations or enforce shrink-only
baselines; hard-coded counts fail on correct additions.
- A PR already carrying the merge label merges as soon as a pushed head turns
green. Removing the label is the explicit way to withdraw that intent.
GitHub Actions preview and bindings
The existing `cicd-github-actions-workflow` recipe supports this family with one combined workflow and event-guarded jobs. Its group is `${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}`; `cancel-in-progress` is `${{ github.event_name == 'pull_request' }}`. Main pushes have no path filters. GitHub concurrency keeps one active and one newest pending run per group; it does not promise FIFO execution. Never put a commit SHA in the group. Other providers require a reviewed mapping; this checker fails closed for unsupported targets rather than pretending they have the same queue semantics.
Supply the inert preview and the reviewed project binding plan to the existing validator. These inputs extend the provider recipe's `CI_BINDINGS` contract; they are not an execution engine or a new schema family:
node "$AIWG_ROOT/agentic/code/frameworks/cicd-complete/validators/constraints.mjs" \
pipeline.json environment.json --workflow preview.yml \
--shape-bindings ci/bindings.json --phase audit-time
Repeat the same check at render time. Programmatic consumers pass `{workflows: [parsedPreview], shapeBindings: reviewedBindings}` to `validateConstraints` or `renderWithConstraints`. The latter's projection callback must return the exact checked preview; do not generate a different workflow after validation. Family hooks run in all three phases via `check.phase: schema`. They check the rendered contract, including unknown/missing placements, and emit normal per-constraint findings with the selected enforcement. Missing previews produce findings too. Off skips evaluation; invalid parameters still fail.
Binding fields used by this family:
- `provider: github-actions`; `jobs: {jobId: {role: ...}}`, with roles `static`,
`contracts`, `pr-gate`, `qualification`, `main-gate`, `image`, `publish`, `merge`. All rendered jobs need bindings. Source capability IDs and inputs are preserved; only explicit supplemental adapter bindings may be added.
- `capability_command`, `registry_command`, `merge_command`: exact reviewed local
commands. Capability steps retain `CI_CAPABILITY`, `CI_INPUTS`, `CI_BINDINGS`. Reuse `ci-lint`, `ci-test`, `docker-build`, `docker-push` and the existing capability/gate adapter model; never replace a check with echo/success.
- `slow_checks`: reviewed inventory of `{job, command, issue, issue_label}`. Each
command must still run in a qualification job and each issue reference must be nonempty (`#number` or HTTPS URL). An empty array explicitly states there are none. Audit against prior checks and measured durations to detect omissions; a preview cannot prove inventory completeness or that a referenced issue exists.
- `gates: {packId: localCommand}`: every source gate (including rollout gates)
and rendered `CI_GATE` step must use that exact command and full parameters. Reuse `aiwg:cicd-complete/build-time-budget`, passing `maxBuildSeconds: 60` for verdict running time; never include queue wait in its observations.
The main `qualification` job checks out `${{ github.sha }}` with full history, runs the heavy suite and exports `steps.tree.outputs.tree` from `git rev-parse HEAD^{tree}`. Image and publish jobs depend on its success, check out that same SHA and consume `${{ needs.qualification.outputs.tree }}` in `CI_QUALIFIED_TREE`. No `always()` or ignored failures may bypass those guards.
The image job's `registry` step consumes `CI_TREE` and `CI_TAG: tree-hash`. The reviewed adapter computes per-image content trees, compares image inputs to the previous qualified tree, checks registry absence and emits `exists`, `changed`, `image`. Build only when both absent and changed. An unchanged image reuses its existing immutable reference; a merge touching no image builds none. Export `image` from that registry step, then publish only the image job's output. A repository tree is the qualification identity; a per-image tree is the cache identity. The adapter must bind both and reject a digest/tree mismatch.
The merge helper depends on every verdict and its budget gate. `CI_MERGE` JSON contains `label`, `head: ${{ github.event.pull_request.head.sha }}` and `recheck_head_and_verdicts: true`. The reviewed adapter rereads the current label, head and required verdict conclusions, uses a conditional merge with the expected head SHA, and refuses stale/pending/failed heads. It needs an explicitly authorized trusted service identity; PR jobs receive no merge credential. Label and synchronize events reevaluate intent. Untrusted PR code must never control that service.
The fixture under `$AIWG_ROOT/test/fixtures/cicd/pipeline-shape/` is an inert preview and negative mutation set following this recipe. The project-owned `ci/*.mjs` adapters, registry access, issue inventory and trusted merge service are prerequisites, not shipped implementations. Static validation cannot prove adapter behavior, live durations, registry contents, queue execution or forge acceptance. Review those independently before installation; no network calls, workflow dispatches, registry writes or merges occur during validation.
Red-main recovery (#4528)
Recovery is the third `enterprise-cost` family, after capacity and pipeline shape. Selecting `aiwg:cicd-complete/enterprise-cost` opts into these entries together with those families; pipelines without that reference remain unchanged. Safety controls default to `blocking`; backpressure and fix-forward default to `advisory`. Override each entry to `off`, `advisory` or `blocking` explicitly for local adoption.
| Constraint | Default params | Rationale and trade-off |
|---|---|---|
| `recovery.main-green-gate` | `fix_label: fixes-main` | Fail ordinary PR verdicts while main is red; automatically re-run on green. Temporarily blocks unrelated work and makes the fix label privileged. |
| `recovery.bisect-revert` | `max_in_flight: 1` | Freeze a red batch, re-run failures to distinguish flakes, bisect only that range, propose reverts and auto-merge after the original failing checks pass. Serial recovery trades throughput for isolation. |
| `recovery.keep-migrations` | `{}` | Never delete or modify a shipped migration; add a new forward migration. A source revert may need an additional schema repair. |
| `recovery.repair-ships-on-red` | `repair_workers: [bisect, node-repair, drains]` | Ship each repair worker from its own passing tests while main is red. Requires independent evidence and narrow delivery permissions. |
| `recovery.repair-migrates-with-repair` | `{}` | Run each repair build's own pre-deploy migration. Adds migration ownership but removes dependency on the blocked main migrator. |
| `recovery.backpressure-bound` | `alert_threshold: 0.3` | Estimate recovery load and batch size over a complete week. Needs consistent run history; the model is an estimate, not a throughput guarantee. |
| `recovery.fix-forward` | `{}` | Default to a small fix-forward, use a cleaner revert when appropriate, and open an issue for delayed fixes. Accepts temporary post-merge failures with explicit ownership. |
Existing capability and renderer bindings
Recovery implementations remain project-owned. Declare policy on an executable `ci-test` job's optional `inputs.recovery` object. Its `constraint` is the full constraint ID; retain normal `suite`, `workspace` and `command` inputs. These are declarations checked against the selected profile, not proof of execution. `ci-pipeline-audit` must also trace required verdicts, label permissions and re-run subscriptions to actual provider settings and redacted run evidence.
Policy object fields (all flags below must be `true`):
- Main-green: `fix_label`, `required_verdict`, `fail_on_red`, `rerun_on_green`.
- Bisect-revert: `max_in_flight`, `freeze_batch`, `rerun_failures`,
`bisect_frozen_range`, `propose_reverts`, `auto_merge_on_original_checks`, and nonempty `original_checks` containing the original failed check names.
- Keep-migrations: `preserve_shipped`, `forward_fix_new_migration`.
- Fix-forward: `default_response: small-fix-forward`, `revert_when_cleaner`,
`issue_when_not_immediate`.
For each worker, bind a `ci-deploy-handoff` job's optional `inputs.recovery`:
worker: bisect
ships_on_red: true
test_job: bisect-test
build_job: bisect-build
pre_deploy_migration: bisect-migrate
The test job uses `ci-test`, a nonempty command/suite, and `inputs.recovery.worker: bisect`. Its `docker-build` job depends directly on that test. The migration job uses `ci-test` with `suite: pre-deploy-migration`, an idempotent project migration-and-schema-readiness test command, and `inputs.recovery` containing the same `worker` and `build_job`. The migration depends directly on that build; deploy depends directly on the migration. The deploy path must transitively depend on its build. These explicit job dependencies are required even across stages. The pre-deploy suite applies migrations and verifies schema readiness, retaining normal `ci-test` totals, exit status and report outputs. Migration checks inspect every declared red-main repair deploy, including workers beyond the profile's required list.
Reuse `ci-failure-triage`, `ci-flake-hunt`, `ci-release-coordinate` and the CI pipeline incident template. Use `aiwg:dev/ci-flake` for repeated-run evidence and `aiwg:cicd-complete/build-time-budget` for recovery build duration; do not turn a flake re-run into unconditional success. The existing Gitea/GitHub templates preserve `job.inputs` in `CI_INPUTS` and `job.depends_on` as dependencies. Call `renderWithConstraints` before projecting them; schema-phase recovery hooks run at render and audit time. No bisect implementation, merge bot or deployment engine is installed by selecting a profile. Existing delivery authorization and secret protections still apply to the repair path.
Offline audit evidence and assessment inputs
`validators/recovery.mjs` exports `createRecoveryValidators(evidence)`. Pass its result as `validators` to `validateConstraints(..., {phase: 'audit-time', validators})`. Without explicit evidence the built-in hooks report unavailable migration inventories and history. The CLI can check declared controls but cannot establish that missing runtime evidence passed.
Supply `shippedMigrations` and `proposedMigrations` as complete arrays of `{path, digest}` records from the deployed migration ledger and candidate tree. An empty inventory explicitly means none shipped; absent/malformed inventories mean unavailable. Deleting or changing any shipped path/digest is a violation; new paths are allowed. Record the source revision and evidence window in the audit report. A successful render does not verify a migration ledger.
For `ci-assess`, call `assessRecoveryBackpressure(runHistory, alertThreshold)` from `validators/recovery-backpressure.mjs` with a normalized export:
{"window_seconds":604800,"merges":100,"qualification_seconds":[600,1200],"recovery_seconds":[600,1200]}
Use a complete trailing week (or longer declared observation window), count merges in that window, qualification durations in seconds and one recovery duration in seconds per culprit, including flakes in the observed qualification cost. An empty recovery array means an observed week with no culprits; omit it if recovery data is unknown. Incomplete or invalid exports report all four inputs as unavailable. Report source run IDs, window, counts and completeness; never infer zeros from missing logs. The helper does not fetch provider history.
Report `lambda = merges/window_seconds` (merges/second), `T` (mean qualification seconds), `p` (culprits/merges), `r` (mean seconds per culprit), `load = lambdapr`, and `n = lambda*T/(1-load)`. Alert strictly above the selected threshold, default `0.3`. At load >= 1, report `saturated`, alert and leave `n` unavailable rather than reporting a negative or infinite batch. With no recoveries, report measured `p = 0`, `r = 0`. The audit hook emits threshold violations with these inputs; assessment reports them even below the threshold.
Recovery runbook and deadlock rehearsal
Fill the recovery rows in `ci-pipeline-runbook-template` for every selected constraint, recording implementation references, owner, stop conditions and rehearsal evidence. Profile enforcement grants no execution permission.
Worked example: main is red and its migration job has not applied migration 042. The node-repair build carries schema 042 but starts against schema 041, refuses work and cannot repair the node needed to recover main. Waiting for the main migrator deadlocks. Bind `node-repair-test -> node-repair-build -> node-repair-migrate -> node-repair-deploy`; the repair build's own idempotent pre-deploy command applies 042 before worker startup. Rehearse with a fake schema-041 database: the missing migrator fixture must fail preflight; the bound path must migrate before startup and then pass the original failing checks. If a revert is needed, retain shipped 042 unchanged and land 043 as a forward fix. Record both the shipped ledger and candidate inventory, worker test results, migration/build artifact identities and the run that returned main to green.
Agent guide (#4529)
`ci-assess` and `ci-pipeline-audit` measure a selected profile through the existing validators. `ci-architect` proposes new constraints and adopts them only after the operator answers the native question tool. The procedure is `$AIWG_ROOT/docs/frameworks/cicd-complete/agent-guide.md`.