Compare commits

..
Author SHA1 Message Date
James MaesandCodex 04a929aae9 ci: retain Ruby coverage in shared CodeQL selection
Select Ruby for tracked .rb files alongside existing language detection. Covers qctl Java/Ruby/Actions, Ruby-only repositories and untracked-file exclusion.

Validation: red/green regression, seven selector tests, actionlint and two workflow contracts passed; actual qctl branch inventories select the expected languages. Consumer repins and scanner setup changes are outside this PR.

Co-Authored-By: Codex (GPT-6) <noreply@openai.com>
2026-10-29 16:05:19 -05:00
james.maesandCodex 1c389210e6 fix: deploy Voyage through the live shared GitOps updater (#157)
Co-authored-by: Codex <noreply@openai.com>
2026-10-22 13:33:37 -05:00
james.maesandCodex 9438ab0762 fix: pin Voyage CD image and validate release PRs (#155)
Co-authored-by: Codex <noreply@openai.com>
2026-10-22 13:03:14 -05:00
james.maesandCodex 7fed7eee82 fix: avoid CircleCI interpolation in Voyage checkout (#153)
Co-authored-by: Codex <noreply@openai.com>
2026-10-22 12:43:22 -05:00
james.maesandCodex ed880fcb77 fix: correct Voyage CD checkout and release target (#151)
Co-authored-by: Codex <noreply@openai.com>
2026-10-22 12:28:09 -05:00
james.maesandCodex 50fa564006 fix: preserve verified source heads during Node snapshots (#149)
Co-authored-by: Codex <noreply@openai.com>
2026-10-22 05:05:41 -05:00
james.maesandCodex 35e5312fc7 fix: accept CircleCI numeric publication booleans (#148)
Co-authored-by: Codex <noreply@openai.com>
2026-10-22 05:02:01 -05:00
james.maesandCodex 99ac8dec53 perf: avoid repeated analysis after publication verification (#146)
Co-authored-by: Codex <noreply@openai.com>
2026-10-22 04:34:11 -05:00
james.maesandCodex 859eb4badb perf: avoid duplicate analysis in Core dependency assembly (#144)
Co-authored-by: Codex <noreply@openai.com>
2026-10-22 03:27:35 -05:00
james.maesandCodex 357aba57bc fix: check every branch before enabling project cancellation (#142)
Co-authored-by: Codex <noreply@openai.com>
2026-10-22 02:02:23 -05:00
james.maesandCodex fb86d1a4a7 fix: avoid SIGPIPE in CLI capability checks (#140)
Co-authored-by: Codex <noreply@openai.com>
2026-10-22 01:39:24 -05:00
james.maesandCodex e9eb225480 feat: reconcile native CircleCI cost settings (#138)
Co-authored-by: Codex <noreply@openai.com>
2026-10-22 01:28:10 -05:00
james.maesandCodex 09dac40a1e feat: recognize and enforce shared native consumers (#136)
* feat: recognize and enforce shared native consumers

Co-Authored-By: Codex <noreply@openai.com>

* fix: keep qctl required gates appropriate for pull requests

Co-Authored-By: Codex <noreply@openai.com>

---------

Co-authored-by: Codex <noreply@openai.com>
2026-10-22 00:36:08 -05:00
james.maesandCodex 07a8f5cec2 fix: build the template renderer in its own directory (#134)
Co-authored-by: Codex <noreply@openai.com>
2026-10-22 00:13:12 -05:00
james.maesandCodex c4f7b5ba76 feat: verify generated applications through the orb (#132)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 23:57:19 -05:00
james.maesandCodex 3fd8baeda9 feat: validate Homebrew distribution through the orb (#130)
* feat: validate Homebrew distribution through the orb

Co-Authored-By: Codex <noreply@openai.com>

* test: declare Homebrew inputs in fleet fixtures

Co-Authored-By: Codex <noreply@openai.com>

---------

Co-authored-by: Codex <noreply@openai.com>
2026-10-21 23:32:41 -05:00
james.maesandCodex 1334ababf1 feat: validate repository shell automation centrally (#128)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 23:10:56 -05:00
james.maesandCodex 3ca2b71ffa fix: audit catalog as an enforced orb consumer (#127)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 23:04:14 -05:00
james.maesandCodex df9113296e feat: reconcile shared native GitOps consumers (#125)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 22:46:56 -05:00
james.maesandCodex 9b73a4ed5f feat: complete centralized marketing validation (#123)
* feat: complete centralized marketing validation

Co-Authored-By: Codex <noreply@openai.com>

* fix: declare shell fixtures and clean readiness loop lint

Co-Authored-By: Codex <noreply@openai.com>

---------

Co-authored-by: Codex <noreply@openai.com>
2026-10-21 22:23:30 -05:00
james.maesandCodex aa865fefd5 feat: expose Voyage through the shared verification gate (#121)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 21:59:52 -05:00
james.maesandCodex a5d10e8c1c fix: verify marketing PR branches and require concrete Node images (#119)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 21:51:20 -05:00
james.maesandCodex 4f1e5e663d fix: remove fabricated marketing coverage jobs (#117)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 21:35:10 -05:00
james.maesandCodex 898862a095 feat: centralize Node test and artifact pipelines (#115)
* feat: centralize Node test and artifact pipelines

Co-Authored-By: Codex <noreply@openai.com>

* test: supply artifact policy in fleet enrollment fixtures

Co-Authored-By: Codex <noreply@openai.com>

---------

Co-authored-by: Codex <noreply@openai.com>
2026-10-21 21:30:11 -05:00
james.maesandCodex 21403d2287 feat: recognize orb-owned native Next verification (#114)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 21:20:58 -05:00
james.maesandCodex 2675bb7a36 feat: enforce shared branch workflows across five more profiles (#112)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 21:09:13 -05:00
james.maesandCodex 12eccc9e7d feat: preserve combined hotfix and integration test filter (#110)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 20:55:00 -05:00
james.maesandCodex 9e2652d735 fix: pin a compatible GitHub CLI for reconciliation (#108)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 20:38:20 -05:00
james.maesandCodex c4e41dea6b ci: add bounded central enrollment runner (#106)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 20:27:54 -05:00
james.maesandCodex 4562d5c2d2 fix: compare required checks independently of API order (#105)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 20:24:18 -05:00
james.maesandCodex 322a194c05 ci: submit enrollment with GitHub-signed API commits (#104)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 20:18:40 -05:00
james.maes a92d6d13bb Merge pull request #102 from QRun-IO/feat/preserve-restricted-branch-access
feat: enforce CI without changing branch access
2026-10-21 19:55:58 -05:00
james.maesandCodex 9772090684 feat: enforce CI without changing branch access
Co-Authored-By: Codex <noreply@openai.com>
2026-10-21 19:52:42 -05:00
james.maes ab666bb785 Merge pull request #101 from QRun-IO/feat/verify-existing-rulesets
feat: verify existing orb gate rulesets
2026-10-21 19:50:26 -05:00
james.maesandCodex fc39293b9d feat: verify existing orb gate rulesets
Co-Authored-By: Codex <noreply@openai.com>
2026-10-21 19:47:45 -05:00
james.maes e83b8481b9 Merge pull request #100 from QRun-IO/feat/finish-consumer-enrollment
feat: qualify and finish shared enrollment
2026-10-21 19:45:49 -05:00
james.maesandCodex e4ecae6294 feat: qualify and finish shared enrollment
Co-Authored-By: Codex <noreply@openai.com>
2026-10-21 19:40:48 -05:00
james.maes 37b91db07b Merge pull request #99 from QRun-IO/feat/discover-enrollment-targets
feat: discover current consumer enrollment targets
2026-10-21 19:34:22 -05:00
james.maesandCodex c30d821f7e feat: discover current consumer enrollment targets
Co-Authored-By: Codex <noreply@openai.com>
2026-10-21 19:30:56 -05:00
james.maes 6ae688dcf4 Merge pull request #98 from QRun-IO/feat/remote-consumer-enrollment
feat: reconcile signed remote enrollment submissions
2026-10-21 19:30:20 -05:00
james.maesandCodex 78207c16be feat: reconcile signed remote enrollment submissions
Co-Authored-By: Codex <noreply@openai.com>
2026-10-21 19:25:53 -05:00
james.maes efd50aee2f Merge pull request #97 from QRun-IO/feat/batch-consumer-enrollment
feat: enroll consumers with one validated batch
2026-10-21 19:19:12 -05:00
james.maesandCodex 6dd473be25 feat: enroll consumers with one validated batch
Co-Authored-By: Codex <noreply@openai.com>
2026-10-21 19:15:56 -05:00
james.maes 1c8a7c57e5 Merge pull request #95 from QRun-IO/fix/static-analysis-exit-status
fix(ci): propagate Maven static-analysis failures
2026-10-21 19:06:49 -05:00
james.maesandCodex abaebf50ff fix(ci): propagate Maven static-analysis failures
Co-Authored-By: Codex <noreply@openai.com>
2026-10-21 19:02:28 -05:00
james.maes c56e52d4cb Merge pull request #94 from QRun-IO/ci/shared-orb-enforcement
feat(ci): centralize orb branch-check enforcement
2026-10-21 18:58:01 -05:00
james.maesandCodex 09046d45b0 feat(ci): centralize orb branch-check enforcement
Co-Authored-By: Codex <noreply@openai.com>
2026-10-21 18:55:40 -05:00
james.maesandCodex 9e9e6c1fa5 fix(ci): verify frontend maintenance without publishing (#92)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 17:30:16 -05:00
james.maesandCodex 45aaccd2a9 fix(ci): gate core snapshots on all acceptance checks (#90)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 17:14:44 -05:00
james.maesandCodex ab77962b6a fix(audit): discover current organization repositories (#89)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 16:59:04 -05:00
james.maesandCodex d0792d60d6 fix(ci): verify maintenance on nonpublishing branches (#87)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 16:46:05 -05:00
james.maesandCodex 72f5f4d4e7 fix: allow managed orb tracks during QBit onboarding (#85)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 16:26:12 -05:00
james.maesandCodex 00af9aae31 perf: reuse React build before frontend tests (#84)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 15:55:47 -05:00
james.maesandCodex 7e60372948 fix: isolate browser package repositories (#82)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 15:29:28 -05:00
james.maesandCodex 45bab9d960 feat: support managed patch tracks [minor] (#80)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 15:06:44 -05:00
james.maesandCodex f304afb0be fix: isolate Ubuntu bootstrap from image PPAs (#78)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 14:27:11 -05:00
james.maesandCodex f76b9f7a7c fix: refresh only the newly added Temurin repository (#76)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 13:51:50 -05:00
james.maesandCodex fdf62a2f5a fix: align effective Maven versions before publication (#75)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 13:15:09 -05:00
james.maesandCodex 94341ef481 fix(ci): retain verification for schema caller migrations (#73)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 12:57:36 -05:00
james.maesandCodex 2debeada5d feat(ci): centralize opt-in QBit feature tag publication (#72)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 12:52:18 -05:00
james.maesandCodex 6febeff590 fix(audit): verify release and hotfix branch enforcement (#71)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 12:30:59 -05:00
james.maesandCodex 8b58a45f35 ci: include shared RC caller updates in maintenance verification (#70)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 11:59:07 -05:00
james.maesandCodex fbe36d683d ci: verify maintenance changes without publishing applications (#68)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 11:53:20 -05:00
james.maesandCodex bd5ee3bec5 ci: centralize policy-only branches and shared scanner enforcement (#65)
Add the repository-policy profile, validate actual legacy policy trees, normalize packed resource line endings, and scope maintenance requirements to branch source. Preserve canonical scanner enforcement for qqq-all and policy-only main branches.

Validation: 32 audit tests, 7 policy tests, all four target source trees, and Linux packed-generator check pass. Replaces this PR's unrecognized-email signatures using the established verified identity; signature enforcement remains enabled.

Co-authored-by: Codex <noreply@openai.com>
2026-10-21 11:21:15 -05:00
james.maesandCodex d4d6e97df0 fix: retry transient package downloads during CI bootstrap (#66)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 10:56:34 -05:00
james.maesandCodex c288a8864f ci: centralize branch-aware QBit source scanning (#63)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 09:36:07 -05:00
james.maesandCodex 9906c8f120 fix: audit explicitly selected repository branches (#62)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 09:15:33 -05:00
james.maesandCodex 4dcf2c1891 fix: preserve legacy qbit hotfix publication policies (#61)
* fix: preserve legacy qbit hotfix publication policies

Co-Authored-By: Codex <noreply@openai.com>

* fix: regenerate packed profiles with Linux zlib

Co-Authored-By: Codex <noreply@openai.com>

---------

Co-authored-by: Codex <noreply@openai.com>
2026-10-21 09:00:43 -05:00
james.maesandCodex cc30f599e6 fix(ci): provide a stable verification gate across branches (#59)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 03:12:12 -05:00
james.maesandCodex 05a2a5217a fix: audit rc worker pins independently of native workers (#58)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 02:23:51 -05:00
james.maesandCodex 7d73ac90b6 fix: distinguish missing RC refs from GitHub error bodies (#57)
* fix: distinguish missing rc refs from github error bodies

Co-Authored-By: Codex <noreply@openai.com>

* fix: reject empty ref responses across jq versions

Co-Authored-By: Codex <noreply@openai.com>

---------

Co-authored-by: Codex <noreply@openai.com>
2026-10-21 02:15:32 -05:00
james.maesandCodex edc1365ac9 fix: recover verified rc uploads after publisher timeout (#56)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 02:02:14 -05:00
james.maesandCodex 0f33ddadf8 ci: run business E2E on changes and preserve main validation (#55)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 01:19:08 -05:00
james.maesandCodex 5e9bbb54ec ci: add batch version rollout for canonical consumers (#54)
Validate every checkout before updating its orb pin. Preserve publication policy, filters, credentials contexts and forwarded parameters; reject custom callers and mismatched declarations. Cover all 12 profiles, dry runs, no-op repeats, invalid batches and duplicate input with six new tests in the existing contract job. Existing migration and standard tests pass; Linux packed generator check passes.

Co-authored-by: Codex <noreply@openai.com>
2026-10-21 00:45:50 -05:00
james.maesandCodex 5bcec90e33 ci: report the shared database gate on every pull request (#53)
Preserve migration verification, avoid duplicate feature push builds, and cancel superseded pull request runs so the gate can be required safely.

Co-authored-by: Codex <noreply@openai.com>
2026-10-20 22:25:38 -05:00
james.maesandCodex a50b07d927 fix: escape Android heredoc in continued Circle configuration (#51)
Circle accepts the continuation request before reporting an unescaped heredoc as a pipeline configuration error. Escape the template marker and emulate Circle unescaping in executable publisher tests. Validate the actual continued config with CircleCI.

Co-authored-by: Codex <noreply@openai.com>
2026-10-20 22:00:56 -05:00
james.maesandCodex 6318d90e96 feat: centralize lightweight GitOps rendering validation (#50)
Add a read-only native worker and canonical consumer bridge. Verify the pinned Kustomize binary, render every configuration without logging resources, and audit adoption. Behavioral and audit tests pass; all five marketing GitOps configurations render successfully.

Co-authored-by: Codex <noreply@openai.com>
2026-10-20 21:54:25 -05:00
james.maesandCodex a6fea661ff fix: authenticate Android publishing with GitHub package token (#47)
* fix: authenticate Android publishing with GitHub package token

Use the shared GitHub Packages token and verify its identity and registry repository access before Gradle starts. Preserve unit and emulator gates; package write success still requires hosted publication.

Co-Authored-By: Codex <noreply@openai.com>

* fix: keep embedded JSON resources consistent across checkouts

Co-Authored-By: Codex <noreply@openai.com>

---------

Co-authored-by: Codex <noreply@openai.com>
2026-10-20 21:40:01 -05:00
james.maesandCodex 2894bae29a test: retain All release shell behavior in shared owner (#46)
Move the consumer publication regression to the reusable worker; existing test discovery executes it. Verify exact RC1 prerelease/non-latest flags, GA behavior and rejection of other RC versions.

Co-authored-by: Codex <noreply@openai.com>
2026-10-20 21:19:09 -05:00
james.maesandCodex a14e8f9b24 fix: default All releases to shared Circle smoke evidence (#35)
Co-authored-by: Codex <noreply@openai.com>
2026-10-20 21:12:58 -05:00
james.maesandCodex 83611872a3 fix: verify public All smoke evidence without secret export (#44)
Allow unauthenticated Circle API reads for public projects, preserve optional authentication and all fail-closed provenance checks.

Co-authored-by: Codex <noreply@openai.com>
2026-10-20 21:12:00 -05:00
james.maesandCodex 30c4e0e85c fix: use shared Maven credentials for Android publication (#42)
Use the existing organization context and Gradle environment properties. Fail before publishing if either credential is absent and avoid writing secrets to gradle.properties.

Co-authored-by: Codex <noreply@openai.com>
2026-10-20 21:07:21 -05:00
james.maesandCodex f429d9f3c4 fix: build marketing site before browser checks (#40)
Run lint and one production build in every shared marketing workflow before Playwright and Lighthouse. Preserve the delegated delivery contracts.

Co-authored-by: Codex <noreply@openai.com>
2026-10-20 20:56:32 -05:00
71 changed files with 5500 additions and 1877 deletions

No files matched your search

+34 -1
View File
@@ -4,6 +4,9 @@ parameters:
run_rc_finalize_sweep:
type: boolean
default: false
run_enrollment_reconcile:
type: boolean
default: false
orbs:
orb-tools: circleci/orb-tools@12.3
shellcheck: circleci/shellcheck@3.2
@@ -13,6 +16,23 @@ filters: &filters
only: /.*/
jobs:
enrollment-reconcile:
docker:
- image: cimg/python:3.12
resource_class: small
steps:
- checkout
- run:
name: Install reconciliation tools
command: |
bash tools/install_reconcile_gh.sh
python3 -m pip install --disable-pip-version-check PyYAML==6.0.3
- run:
name: Reconcile current QQQ branches
no_output_timeout: 21m
command: python3 tools/run_enrollment.py
- store_artifacts:
path: artifacts/enrollment
rc-finalize-sweep:
docker:
- image: cimg/python:3.12
@@ -28,7 +48,10 @@ jobs:
workflows:
lint-pack:
when:
not: << pipeline.parameters.run_rc_finalize_sweep >>
not:
or:
- << pipeline.parameters.run_rc_finalize_sweep >>
- << pipeline.parameters.run_enrollment_reconcile >>
jobs:
- orb-tools/lint:
filters: *filters
@@ -56,3 +79,13 @@ workflows:
only: main
tags:
ignore: /.*/
reconcile-enrollment:
when: << pipeline.parameters.run_enrollment_reconcile >>
jobs:
- enrollment-reconcile:
context: [qqq-maven-registry-credentials, orb-publishing]
filters:
branches:
only: main
tags:
ignore: /.*/
+14
View File
@@ -47,6 +47,7 @@ jobs:
name: Verify pipeline selection and Maven compatibility contracts
command: |
python3 tests/test_generate_pipeline.py
python3 tests/test_marketing_link_check.py
python3 scripts/pack_pipeline.py --check
bash tests/test_cli_ci_behavior.sh
python3 tests/test_cli_ci_contract.py
@@ -56,11 +57,24 @@ jobs:
python3 tests/test_qbit_feature_profile.py
python3 tests/test_ci_maintenance.py
python3 tests/test_rollout_version.py
python3 tests/test_enforce_orb_checks.py
python3 tests/test_native_next_gates.py
python3 tests/test_native_gitops_gates.py
python3 tests/test_native_specialist_gates.py
python3 tests/test_enroll_consumers.py
python3 tests/test_reconcile_enrollment.py
python3 tests/test_discover_enrollment.py
python3 tests/test_finish_enrollment.py
python3 tests/test_run_enrollment.py
python3 tests/test_install_reconcile_gh.py
python3 tests/test_circle_project_settings.py
python3 tests/test_static_analysis_exit.py
python3 tests/test_validate_standard.py
python3 tests/test_voyage_profile.py
python3 tests/test_next_native.py
python3 tests/test_auxiliary_workflows.py
python3 tests/test_qbit_codeql.py
sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends shellcheck
python3 tests/test_repository_policy.py
python3 tests/test_intellij_plugin.py
python3 tests/test_workflow_lint.py
+2
View File
@@ -31,6 +31,8 @@ jobs:
languages.append('javascript-typescript')
if '.py' in extensions:
languages.append('python')
if '.rb' in extensions:
languages.append('ruby')
if any((name.startswith('.github/workflows/') and PurePosixPath(name).suffix in {'.yml', '.yaml'})
or PurePosixPath(name).name in {'action.yml', 'action.yaml'} for name in files if name):
languages.append('actions')
+6
View File
@@ -61,6 +61,12 @@ test-pipelines: pack
python3 tests/test_qbit_hotfix_profile.py
python3 tests/test_ci_maintenance.py
python3 tests/test_rollout_version.py
python3 tests/test_enforce_orb_checks.py
python3 tests/test_enroll_consumers.py
python3 tests/test_reconcile_enrollment.py
python3 tests/test_discover_enrollment.py
python3 tests/test_finish_enrollment.py
python3 tests/test_static_analysis_exit.py
python3 tests/test_validate_standard.py
python3 tests/test_voyage_profile.py
python3 tests/test_next_native.py
+10
View File
@@ -130,4 +130,14 @@ The organization mode has no fixed repository-count ceiling. Supply
mode preserves its default of 68. Reports identify the inventory source and
credential visibility limit: inaccessible repositories cannot be certified.
This is discovery and audit, not automatic enrollment or branch-rule mutation.
For a qualified batch of canonical orb branches, use the shared
[branch-check enforcement command](branch-enforcement.md). It adds the observed
CircleCI setup/verify gates while preserving other protections. Source enrollment,
scanner transitions and scheduled reconciliation remain separate requirements.
Scheduling and authenticated onboarding still need to be configured centrally.
## Batch enrollment
Use [the shared enrollment command](consumer-enrollment.md) to convert recognized
legacy QBits and update existing canonical consumers in one validated batch.
+248 -238
View File
@@ -1,238 +1,248 @@
# Standardized QQQ pipelines
The orb owns workflow selection and job configuration. A consumer declares a
small manifest; it does not copy pipeline jobs. The initial supported profile is
`qbit`; `core` owns the framework's complete acceptance/release graph. Frontend
and CLI profiles described below retain their own publication contracts. Additional
profiles belong in reviewed `PROFILE_TEMPLATES` renderers in
`src/scripts/generate_pipeline.py`, with profile-specific schema and tests. There
is no arbitrary script or job-YAML passthrough.
Use the same **published** orb version in all three positions below. `0.7.0` is
an illustrative version, not a claim that this change is published. A development
orb version can be used for a controlled canary.
`.circleci/config.yml`:
```yaml
version: 2.1
setup: true
orbs:
qqq-orb: kingsrook/qqq-orb@0.7.0
workflows:
setup:
jobs:
- qqq-orb/generate_pipeline:
orb_version: "0.7.0"
filters:
branches:
ignore: automation/qbit-rc-pending
tags:
only: /.*/
```
`.qqq-ci.yml`:
```yaml
profile: qbit
orb_version: "0.7.0"
default_branch: develop
java_version: "21"
browsers: false
api_checks: false
docs_only: false
publish:
snapshot: true
release_candidate: true
release: true
asciidoc: false
```
Only `profile`, `orb_version` and `default_branch` are required. `default_branch`
must be `develop` or `main`; Java must be the string `17` or `21`. Browsers default
to **true** for compatibility: opt out only after verifying that the consumer has
no browser tests. API checks and docs-only default to false. Publication defaults
to true for snapshots, RCs and tagged releases; AsciiDoc publication defaults to
false. Unknown/duplicate keys, unexpected types, unsupported profiles and a setup
parameter/manifest version mismatch fail before continuation. The canonical-caller
validator also verifies the setup import, filters and profile-specific parameter
declarations; additional jobs, commands, workflows or orbs fail validation. The
parser is pinned to PyYAML 6.0.3 and uses its safe loader.
| Event | Workflow | Job contract |
| --- | --- | --- |
| develop | verify | existing mvn_publish, snapshot |
| release/* | verify | existing mvn_publish, release_candidate |
| vX.Y.Z tag resolving to the checkout | verify | existing mvn_publish, release |
| main, feature/*, hotfix/*, other/unknown branch | verify | existing mvn_test_only |
| Disabled publication or unrecognized/unproven tag | verify | full verification, no publication |
Generated `qbit`, `core`, `frontend-core`, and `frontend-material` pipelines use
the stable workflow name `verify`. All selected jobs, dependencies and filters
remain intact; this adds no executor or duplicate build. Other profiles retain
their existing workflow names and native checks.
When upgrading from legacy workflow names, upgrade the immutable RC worker pin
alongside the orb so finalization recognizes both names. Confirm the CircleCI
app's successful `verify` check on the exact migration commit before replacing
legacy required contexts. Require `setup` and `verify` on managed branches,
preserving other required checks and controls. Human approval is not required;
automated checks authorize the migration.
The pipeline SHA must match the checkout when Circle supplies it. A tagged release
must resolve to that checkout; missing local tags are fetched individually. A main
push does **not** publish a release. Migrating a legacy main-publishing consumer
therefore requires explicit review of its release contract. Existing direct orb
callers remain supported.
The setup filter and generated jobs exclude `automation/qbit-rc-pending`, the
shared RC orchestrator's persistent release lock. Lock updates must not trigger
Maven test or publication work.
The shared jobs keep the `qqq-maven-registry-credentials` context, complete verify,
coverage and configured API checks. Publishing retains version management, signed
artifact deployment, Git operations and release handling. Generated calls disable
the redundant preliminary compile; they do not skip tests or verification. Existing
callers retain the compatibility defaults in the jobs.
## Core profile
QBit alone accepts `release_completion: true` (default false). It enables the
shared Maven RC job's `notify_rc_published` only for RC publication, including
fail-closed verification that the bumped version was pushed before dispatching
the completion event. Enable this on a consumer only after its default branch
contains the shared completion caller. Snapshot and GA jobs never receive this
opt-in; other profiles reject the key.
Use `profile: core` for the QQQ framework. The orb owns the complete baseline
acceptance, broker conformance, cold bootstrap, coverage, diagnostics, static
analysis and publication graph. Core scripts remain in the core source repository.
The independent baseline fixture pins job sets, dependency edges, contexts,
coverage requirements and actual verification commands across all six workflows.
Core additionally supports `publish.feature` and `publish.hotfix` (both true by
default), preserving `publish*` tag and hotfix branch publication. QBit supports
both keys as explicit opt-ins (false by default). QBit feature publishing requires
a `publish*` tag resolving to the checked-out commit; feature branch pushes remain
test-only. Snapshot, RC and GA behavior remains distinct; RC/GA/hotfix
publication still requires the complete source coverage gate. Cold bootstrap and
fresh consumer Maven repositories remain uncached. Shared installer policy replaces
local package preparation; preliminary compilation is disabled before clean
lifecycles and the dependency cache is saved after successful verification.
Lambda XML copies remain in sample coverage evidence. The sample JUnit collector
excludes those two copied reports because their original module directories are
already uploaded, avoiding duplicate test identities without dropping evidence.
External core API triggers require these declarations in the tiny **setup** config:
```yaml
parameters:
mongo_bind_diagnostics:
type: boolean
default: false
next_acceptance_bundle_url:
type: string
default: ""
next_acceptance_bundle_sha256:
type: string
default: ""
next_acceptance_receipt_sha256:
type: string
default: ""
```
Forward each value on `qqq-orb/generate_pipeline`, for example
`mongo_bind_diagnostics: << pipeline.parameters.mongo_bind_diagnostics >>`, and
likewise for the three bundle parameters. Requested values become defaults in the
continued configuration; the continuation POST deliberately omits `parameters` to
avoid CircleCI's setup/continuation/API parameter conflict. Verify both default and
explicit API-triggered parameter values in the hosted canary before migrating
triggering consumers. Other profiles reject non-default core parameters.
## Frontend profiles
`frontend-material` preserves the Maven frontend build/test/package/publication
jobs, Java21/Node20 defaults, registry context, feature-tag, RC, GA and hotfix
contracts. Declare setup pipeline parameter `run_playwright` (boolean, default
false) and forward `run_playwright: << pipeline.parameters.run_playwright >>` on
the generator job. Test/snapshot events select exactly one base or Playwright graph,
so enabling visual tests cannot publish twice. Visual testing retains the pinned
Playwright image, npm ci with legacy peer dependencies and report uploads; only
npm downloads (`~/.npm`) are cached, never node_modules.
`frontend-core` preserves Node24.21, npm trusted publishing and both existing
registry/build-sample contexts. Unlike QBit, its existing main-push **and v-tag**
release contract remains intentional. Both frontend profiles support explicit
numeric-string `node_version` and publication toggles including feature/hotfix.
Material also supports `java_version`. Browser/API/AsciiDoc flags are rejected
rather than silently ignored on these profiles. Existing direct jobs remain usable.
## CLI profile
`cli` owns npm install, generated-client drift, build, unit tests and the real
Prism smoke contract through `cli_verify_publish`. Publication is **disabled by
default**. To enable the existing v-tag publication, declare `publish.release:
true` plus `publish_context: VERIFIED_CONTEXT_NAME`, after verifying that an
existing trusted CircleCI context grants the required GitHub Packages permission.
No context name or credential availability is inferred from the former Actions
GITHUB_TOKEN. A tag must resolve to the current checkout; the job additionally
checks the client version before publishing its three fixed workspaces with the
existing rc dist-tag. Main pushes never publish. CLI docs-only is currently
rejected because generated-client verification remains mandatory.
## Conservative documentation routing
With `docs_only: true`, only feature/hotfix and main changes can take the light
route. Feature/hotfix branches fetch the declared default branch without tags and
compare its merge base with HEAD, covering the whole branch. Main compares its first
parent. Develop, release branches and all tags remain full. Shallow repositories,
missing ancestry, fetch/diff errors, empty diffs and unknown paths remain full.
Only root README.md, CHANGELOG.md, CONTRIBUTING.md and Markdown files below docs/
are eligible. Renames are treated as deletion plus addition, so moving code into
docs cannot hide it. The lightweight job checks whitespace over the proven diff;
manifest validation already ran in setup. It adds no new security scanner and
makes no security-scanning claim. Keep docs-only disabled if those paths are build
inputs or packaged application content.
The light route keeps workflow `verify` and names its job
`qqq-orb/mvn_test_only`. Verify actual CircleCI/GitHub status contexts on the canary
before changing any protection rule; workflow/job identity alone is not proof of
the hosted context name. Current protections must not be removed speculatively.
## Implementation and verification
The setup job checks out source, installs the pinned parser, runs the embedded
Python resource and invokes CircleCI's native continuation API once. JSON output
is valid CircleCI configuration YAML; it is saved at
`/tmp/qqq-generated-config.json`. No external framework or per-consumer generator
installation is required. Readable templates live in src/scripts/templates. scripts/pack_pipeline.py embeds
them as base64 into packed_generate_pipeline.py before orb packing, preventing
CircleCI from interpolating template expressions during setup. The orb includes
the complete generated resource; no runtime source-tree template access is needed.
make pack regenerates it and CI rejects a stale generated resource.
Continuation credentials and response bodies are never printed.
Run `make test-pipelines` with CircleCI CLI, Python3/PyYAML and Bash available.
Tests use offline temporary Git repositories and a bare origin to cover selection,
whole-branch changes, tags, errors, defaults and source/packed parity. The hosted
pipeline-contract-test runs the source suite and shared Maven behavioral tests;
the full local target additionally extracts and executes the actual packed command.
## Android and MCP policy profiles
`android` and `mcp-policy` accept only profile, orb_version and default_branch.
Android retains the audited Android/GCP orb versions and every active unit,
emulator and Maven-publication step. The emulator now runs on main as well as
feature branches so main publication cannot omit its required instrumentation
gate. Dormant Firebase benchmark and release-build definitions referencing absent
app/macrobenchmark modules are not scheduled or copied into the profile.
MCP policy validation remains a small Python container validating all visible YAML
and required pattern fields. Its existing PyYAML dependency is pinned to 6.0.3.
Neither profile introduces Maven/JUnit stand-ins for its actual tests.
`tests/test_mobile_policy_profiles.py` protects Android steps and dependency edges
and executes the policy validator with valid, incomplete and malformed documents.
The generator suite verifies source/packed parity for both profiles.
# Standardized QQQ pipelines
The orb owns workflow selection and job configuration. A consumer declares a
small manifest; it does not copy pipeline jobs. The initial supported profile is
`qbit`; `core` owns the framework's complete acceptance/release graph. Frontend
and CLI profiles described below retain their own publication contracts. Additional
profiles belong in reviewed `PROFILE_TEMPLATES` renderers in
`src/scripts/generate_pipeline.py`, with profile-specific schema and tests. There
is no arbitrary script or job-YAML passthrough.
Use the same **published** orb version in all three positions below. `0.7.0` is
an illustrative version, not a claim that this change is published. A development
orb version can be used for a controlled canary.
`.circleci/config.yml`:
```yaml
version: 2.1
setup: true
orbs:
qqq-orb: kingsrook/qqq-orb@0.7.0
workflows:
setup:
jobs:
- qqq-orb/generate_pipeline:
orb_version: "0.7.0"
filters:
branches:
ignore: automation/qbit-rc-pending
tags:
only: /.*/
```
`.qqq-ci.yml`:
```yaml
profile: qbit
orb_version: "0.7.0"
default_branch: develop
java_version: "21"
browsers: false
api_checks: false
docs_only: false
publish:
snapshot: true
release_candidate: true
release: true
asciidoc: false
```
Only `profile`, `orb_version` and `default_branch` are required. `default_branch`
must be `develop` or `main`; Java must be the string `17` or `21`. Browsers default
to **true** for compatibility: opt out only after verifying that the consumer has
no browser tests. API checks and docs-only default to false. Publication defaults
to true for snapshots, RCs and tagged releases; AsciiDoc publication defaults to
false. Unknown/duplicate keys, unexpected types, unsupported profiles and a setup
parameter/manifest version mismatch fail before continuation. The canonical-caller
validator also verifies the setup import, filters and profile-specific parameter
declarations; additional jobs, commands, workflows or orbs fail validation. The
parser is pinned to PyYAML 6.0.3 and uses its safe loader.
| Event | Workflow | Job contract |
| --- | --- | --- |
| develop | verify | existing mvn_publish, snapshot |
| release/* | verify | existing mvn_publish, release_candidate |
| vX.Y.Z tag resolving to the checkout | verify | existing mvn_publish, release |
| main, feature/*, hotfix/*, other/unknown branch | verify | existing mvn_test_only |
| Disabled publication or unrecognized/unproven tag | verify | full verification, no publication |
Generated `qbit`, `core`, `frontend-core`, and `frontend-material` pipelines use
the stable workflow name `verify`. All selected jobs, dependencies and filters
remain intact; this adds no executor or duplicate build. Other profiles retain
their existing workflow names and native checks.
When upgrading from legacy workflow names, upgrade the immutable RC worker pin
alongside the orb so finalization recognizes both names. Confirm the CircleCI
app's successful `verify` check on the exact migration commit before replacing
legacy required contexts. Require `setup` and `verify` on managed branches,
preserving other required checks and controls. Human approval is not required;
automated checks authorize the migration.
The pipeline SHA must match the checkout when Circle supplies it. A tagged release
must resolve to that checkout; missing local tags are fetched individually. A main
push does **not** publish a release. Migrating a legacy main-publishing consumer
therefore requires explicit review of its release contract. Existing direct orb
callers remain supported.
The setup filter and generated jobs exclude `automation/qbit-rc-pending`, the
shared RC orchestrator's persistent release lock. Lock updates must not trigger
Maven test or publication work.
The shared jobs keep the `qqq-maven-registry-credentials` context, complete verify,
coverage and configured API checks. Publishing retains version management, signed
artifact deployment, Git operations and release handling. Generated calls disable
the redundant preliminary compile; they do not skip tests or verification. Existing
callers retain the compatibility defaults in the jobs.
## Core profile
QBit alone accepts `release_completion: true` (default false). It enables the
shared Maven RC job's `notify_rc_published` only for RC publication, including
fail-closed verification that the bumped version was pushed before dispatching
the completion event. Enable this on a consumer only after its default branch
contains the shared completion caller. Snapshot and GA jobs never receive this
opt-in; other profiles reject the key.
Use `profile: core` for the QQQ framework. The orb owns the complete baseline
acceptance, broker conformance, cold bootstrap, coverage, diagnostics, static
analysis and publication graph. Core scripts remain in the core source repository.
The independent baseline fixture pins job sets, dependency edges, contexts,
coverage requirements and actual verification commands across all six workflows.
Core additionally supports `publish.feature` and `publish.hotfix` (both true by
default), preserving `publish*` tag and hotfix branch publication. QBit supports
both keys as explicit opt-ins (false by default). QBit feature publishing requires
a `publish*` tag resolving to the checked-out commit; feature branch pushes remain
test-only. Snapshot, RC and GA behavior remains distinct; RC/GA/hotfix
publication still requires the complete source coverage gate. Cold bootstrap and
fresh consumer Maven repositories remain uncached. Shared installer policy replaces
local package preparation; preliminary compilation is disabled before clean
lifecycles and the dependency cache is saved after successful verification.
Lambda XML copies remain in sample coverage evidence. The sample JUnit collector
excludes those two copied reports because their original module directories are
already uploaded, avoiding duplicate test identities without dropping evidence.
External core API triggers require these declarations in the tiny **setup** config:
```yaml
parameters:
mongo_bind_diagnostics:
type: boolean
default: false
next_acceptance_bundle_url:
type: string
default: ""
next_acceptance_bundle_sha256:
type: string
default: ""
next_acceptance_receipt_sha256:
type: string
default: ""
```
Forward each value on `qqq-orb/generate_pipeline`, for example
`mongo_bind_diagnostics: << pipeline.parameters.mongo_bind_diagnostics >>`, and
likewise for the three bundle parameters. Requested values become defaults in the
continued configuration; the continuation POST deliberately omits `parameters` to
avoid CircleCI's setup/continuation/API parameter conflict. Verify both default and
explicit API-triggered parameter values in the hosted canary before migrating
triggering consumers. Other profiles reject non-default core parameters.
## Frontend profiles
`frontend-material` preserves the Maven frontend build/test/package/publication
jobs, Java21/Node20 defaults, registry context, feature-tag, RC, GA and hotfix
contracts. Declare setup pipeline parameter `run_playwright` (boolean, default
false) and forward `run_playwright: << pipeline.parameters.run_playwright >>` on
the generator job. Test/snapshot events select exactly one base or Playwright graph,
so enabling visual tests cannot publish twice. Visual testing retains the pinned
Playwright image, npm ci with legacy peer dependencies and report uploads; only
npm downloads (`~/.npm`) are cached, never node_modules.
`frontend-core` preserves Node24.21, npm trusted publishing and both existing
registry/build-sample contexts. Unlike QBit, its existing main-push **and v-tag**
release contract remains intentional. Both frontend profiles support explicit
numeric-string `node_version` and publication toggles including feature/hotfix.
Material also supports `java_version`. Browser/API/AsciiDoc flags are rejected
rather than silently ignored on these profiles. Existing direct jobs remain usable.
## CLI profile
`cli` owns npm install, generated-client drift, build, unit tests and the real
Prism smoke contract through `cli_verify_publish`. Publication is **disabled by
default**. To enable the existing v-tag publication, declare `publish.release:
true` plus `publish_context: VERIFIED_CONTEXT_NAME`, after verifying that an
existing trusted CircleCI context grants the required GitHub Packages permission.
No context name or credential availability is inferred from the former Actions
GITHUB_TOKEN. A tag must resolve to the current checkout; the job additionally
checks the client version before publishing its three fixed workspaces with the
existing rc dist-tag. Main pushes never publish. CLI docs-only is currently
rejected because generated-client verification remains mandatory.
## Conservative documentation routing
With `docs_only: true`, only feature/hotfix and main changes can take the light
route. Feature/hotfix branches fetch the declared default branch without tags and
compare its merge base with HEAD, covering the whole branch. Main compares its first
parent. Develop, release branches and all tags remain full. Shallow repositories,
missing ancestry, fetch/diff errors, empty diffs and unknown paths remain full.
Only root README.md, CHANGELOG.md, CONTRIBUTING.md and Markdown files below docs/
are eligible. Renames are treated as deletion plus addition, so moving code into
docs cannot hide it. The lightweight job checks whitespace over the proven diff;
manifest validation already ran in setup. It adds no new security scanner and
makes no security-scanning claim. Keep docs-only disabled if those paths are build
inputs or packaged application content.
The light route keeps workflow `verify` and names its job
`qqq-orb/mvn_test_only`. Verify actual CircleCI/GitHub status contexts on the canary
before changing any protection rule; workflow/job identity alone is not proof of
the hosted context name. Current protections must not be removed speculatively.
## Implementation and verification
The setup job checks out source, installs the pinned parser, runs the embedded
Python resource and invokes CircleCI's native continuation API once. JSON output
is valid CircleCI configuration YAML; it is saved at
`/tmp/qqq-generated-config.json`. No external framework or per-consumer generator
installation is required. Readable templates live in src/scripts/templates. scripts/pack_pipeline.py embeds
them as base64 into packed_generate_pipeline.py before orb packing, preventing
CircleCI from interpolating template expressions during setup. The orb includes
the complete generated resource; no runtime source-tree template access is needed.
make pack regenerates it and CI rejects a stale generated resource.
Continuation credentials and response bodies are never printed.
Run `make test-pipelines` with CircleCI CLI, Python3/PyYAML and Bash available.
Tests use offline temporary Git repositories and a bare origin to cover selection,
whole-branch changes, tags, errors, defaults and source/packed parity. The hosted
pipeline-contract-test runs the source suite and shared Maven behavioral tests;
the full local target additionally extracts and executes the actual packed command.
## Node snapshot versions
The shared Node publisher calculates develop snapshots as
`MAJOR.MINOR.NEXT_PATCH-SNAPSHOT.CIRCLE_BUILD_NUM`. A positive CircleCI job number
is required, so independent publication jobs receive distinct npm coordinates.
The package version is changed only in the build workspace and published under
the `snapshot` dist-tag. No snapshot version commit is pushed: the branch remains
at the source revision whose required checks ran, avoiding unchecked `[skip ci]`
heads and recursive publication. Stable, RC and hotfix version policies are unchanged.
## Android and MCP policy profiles
`android` and `mcp-policy` accept only profile, orb_version and default_branch.
Android retains the audited Android/GCP orb versions and every active unit,
emulator and Maven-publication step. The emulator now runs on main as well as
feature branches so main publication cannot omit its required instrumentation
gate. Dormant Firebase benchmark and release-build definitions referencing absent
app/macrobenchmark modules are not scheduled or copied into the profile.
MCP policy validation remains a small Python container validating all visible YAML
and required pattern fields. Its existing PyYAML dependency is pinned to 6.0.3.
Neither profile introduces Maven/JUnit stand-ins for its actual tests.
`tests/test_mobile_policy_profiles.py` protects Android steps and dependency edges
and executes the policy validator with valid, incomplete and malformed documents.
The generator suite verifies source/packed parity for both profiles.
+22 -17
View File
@@ -6,17 +6,18 @@ orb version. The canonical QQQ setup produces one final continuation containing
jobs from the pinned `kof22/munitor@0.3.11` orb. It never invokes Munitor's setup
generator or creates another continuation.
The profile is the exact semantic graph rendered by Munitor 0.3.11 from
marketing-website commit `4eb5f63b9fbfac8e5529fcd638324870cea08ae2`, with its
manifest's floating `0.3` pin changed to `0.3.11` for the baseline render.
The checked-in fixture records that real render; the JSON resource contains the
same jobs, parameters, contexts, filters and dependency edges.
The baseline fixture records the original Munitor 0.3.11 render. The shared
profile selects one workflow for the current branch and exposes it as `verify`:
PR checks for feature/hotfix/automation branches, develop, staging, release
candidate, or production for main. Tags and the RC bookkeeping branch do not
run these jobs. Existing deployment dependencies and contexts are preserved.
There are five workflows and 33 job invocations: PR checks (7), develop (7),
staging (7), release candidate (8), and production (4). They preserve Node 22,
Chromium Playwright and Lighthouse, the existing scan and quality jobs, advisory
SAST, and the existing synthetic zero-threshold coverage command. That command
does not measure actual coverage.
The build job installs dependencies once, lints, builds, runs Chromium
Playwright tests, crawls local links and runs Lighthouse. The link crawl waits
at most 60 attempts for the app on port 3005, propagates failures, and stops its
server on exit. Playwright and Lighthouse reports are retained as artifacts,
including on failure. The old synthetic coverage job was removed because it
fabricated 100% rather than measuring coverage; actual tests and scans remain.
Production follows build → image build/Trivy/push/health → independent CD update
and GitHub release. Both final jobs depend on the image job; neither depends on
@@ -26,15 +27,19 @@ existing `github` context; image publication uses `ghcr`. Production-only means
no non-main deployment update, not no non-main artifacts: develop/staging image
publishing and release-candidate GitHub releases remain unchanged.
Keep `.munitor.yml` as declarative worker input when migrating the consumer.
Munitor's `generate_dockerfile` reads it from the attached workspace and requires
`pipeline: node-webapp` and `docker.use_repo_dockerfile: true` to preserve the
repository Dockerfile. The profile does not replace that file or validate all
of its values. Changes to worker input require review alongside the centralized
profile; arbitrary manifest job overrides are not supported. Health remains `/`
on port 3000; the repository Dockerfile remains responsible for the standalone
Consumers need only the QQQ caller and `.qqq-ci.yml`. Before tests, the shared
profile writes minimal `.munitor.yml` worker input into the build workspace:
`pipeline: node-webapp`, Node 22, and `docker.use_repo_dockerfile: true`.
Munitor's Docker worker still requires this file; the orb owns its contents.
This preserves the repository Dockerfile rather than generating a replacement.
Container health remains `/` on port 3000, distinct from the local test server
on port 3005. The repository Dockerfile remains responsible for the standalone
runtime without npm or npx.
The duplicate consumer GitHub test workflow can be removed only after these
central checks qualify. Application test settings and assertions remain in the
application repository; orchestration belongs here.
`MarketingContractTests` checks whole-graph equality and explicit release/test
contracts. The normal generator suite additionally checks source/packed parity.
These are configuration tests, not a claim of hosted delivery, credentials,
+66
View File
@@ -0,0 +1,66 @@
# Shared orb check enforcement
`tools/enforce_orb_checks.py` replaces repository-specific scripts for the shared
CircleCI `setup` and `verify` branch gates. One invocation processes an explicit
batch of current `main` and `develop` branches using existing `gh` authentication.
Create a targets file:
```json
[
{"repository": "QRun-IO/qbit-example", "branch": "main"},
{"repository": "QRun-IO/qbit-example", "branch": "develop"}
]
```
Preview, then apply the same batch:
```sh
python tools/enforce_orb_checks.py --targets targets.json --orb-version 0.8 --output enforcement-plan.json
python tools/enforce_orb_checks.py --targets targets.json --orb-version 0.8 --output enforcement-result.json --apply
```
Every branch must already contain the exact canonical caller for its manifest and
have successful `setup` and `verify` checks from CircleCI app 18001 at its current
commit. Supported profiles are QBit, Core, frontend-core, frontend-material and repository-policy.
The complete batch is inspected before any mutation. Source/head/protection drift,
unavailable APIs and unknown profiles fail closed. Existing repository rulesets are verified as described below.
The tool appends the app-bound checks, enables strict checks and administrator
enforcement, and reads the result back. Existing required checks remain required.
For protected branches it uses the narrow status-check/admin endpoints, preserving
reviews, signatures, linear history, restrictions and other settings. For a
previously unprotected branch it creates protection without adding human reviews.
It never changes scanner configuration, repository visibility, billing, or source.
Output records the planned head and original protection, then verification as each
branch completes. A batch is not transactional: if an API call fails, inspect the
output and rerun; successful protections are retained rather than rolled back.
An already-correct branch needs no mutation.
This command covers the shared orb gate pair only. Continue to run the estate
audit for scanner/native-worker requirements and other policy. Automatic repository
discovery, source enrollment and scheduled reconciliation remain separate work.
GitHub API reference: [protected branches](https://docs.github.com/en/rest/branches/branch-protection).
```sh
python -m unittest discover -s tests -p test_enforce_orb_checks.py -v
```
## Existing rulesets
When effective branch rules come from repository rulesets, the tool can verify
existing enforcement without adding classic protection. Each contributing ruleset
must be active for branches, have no bypass actors and require both setup and
verify from CircleCI app18001. The current branch must also have successful gate
runs. The tool rechecks the branch, effective rules and full ruleset records before
reporting verified. Rule drift or an unbound/missing gate stops verification.
This path writes nothing. It preserves scanner requirements, conditions and the
existing up-to-date-branch policy, including a false strict setting that avoids
unnecessary rebuilds. Reports identify protection_mode=rulesets and the observed
strict value. Unsupported organization-level rulesets, bypass actors and missing
gates remain unresolved rather than being rewritten or ignored.
For classic protection with an empty push allowlist and admin enforcement disabled, the tool leaves the entire classic policy unchanged. After current-head gates pass, it creates a narrowly scoped active repository ruleset requiring app-bound setup and verify with no bypass actors. This enforces CI even for administrators without changing their existing branch access or locking all actors out. The ruleset retains the fleet freshness policy (strict=false); it does not weaken any existing classic policy. A same-named ruleset causes rejection rather than overwrite or duplication. Readback verifies the effective gates and unchanged classic protection; subsequent runs recognize the existing ruleset without writes.
+152
View File
@@ -0,0 +1,152 @@
# Batch consumer enrollment
Use one target file for canonical consumers of every supported Circle profile and
legacy QBits whose jobs and publication filters the shared converter recognizes:
```json
[
{"checkout": "/work/qbit-example", "default_branch": "main"},
{"checkout": "/work/qqq", "default_branch": "develop"}
]
```
The branch values must come from repository inventory. Run on clean isolated
checkouts of the branches being migrated.
```sh
python tools/enroll_consumers.py targets.json --orb-version 0.8
python tools/enroll_consumers.py targets.json --orb-version 0.8 --write
```
The command validates the entire batch before writing. Existing manifests keep
all publication and profile options; only the managed orb version changes.
Recognized legacy QBits receive the canonical caller and inferred publication
policy. An unknown job, filter, profile option, duplicate target, symlink, or
concurrent declaration edit rejects the batch. Repeating a completed enrollment
makes no changes. Filesystem errors during the write phase can leave a partial
batch; rerun after correcting the error. This is not a filesystem transaction.
Only `.circleci/config.yml` and `.qqq-ci.yml` are changed. The tool does not delete
other workflows, infer publication from repository names, or enroll unknown
custom pipelines. Their behavior must first be represented by a central profile.
After committing and qualifying the exact source, apply the shared
[branch enforcement tool](branch-enforcement.md) to supported gate profiles.
This command provides batch source conversion. Use the coordinator below for remote signed submissions. Local conversion alone does not prove fleet deployment or release success.
## Remote signed submissions
Supply observed current branches, without cloning each repository yourself:
```json
[
{"repository": "QRun-IO/qbit-example", "branch": "main"},
{"repository": "QRun-IO/qqq", "branch": "develop"}
]
```
```sh
python tools/reconcile_enrollment.py --targets remote-targets.json --orb-version 0.8 --output plan.json
python tools/reconcile_enrollment.py --targets remote-targets.json --orb-version 0.8 --output result.json --apply
```
Use existing `gh` authentication with repository write access. The coordinator
never installs credentials or changes authentication. Every target is inspected
at an immutable head and validated before any remote mutation. No repository
clone, SSH key or local signing key is required. A moved target stops submission;
refresh the plan instead of overwriting it.
An automation branch derives from the source commit and proposed declarations.
The coordinator creates the branch at the observed base and uses GitHub's
`createCommitOnBranch` API with `expectedHeadOid` for an atomic append. GitHub
signs the commit when supported by the authenticated identity; the coordinator
requires remote signature verification, exact parent, changed paths and
declaration bytes before opening a PR. It never force-updates a branch.
An interrupted branch creation, commit or PR creation can be resumed:
an existing branch still at the planned base receives the missing commit;
matching signed branches and PRs are reused. A mismatched branch is rejected.
Closed existing PRs are reported as existing; they are not silently reopened.
Reports include repository, branch, immutable head and submission URL, without
embedding declaration contents or credentials. Keep the report if a later target
fails; earlier valid submissions remain intact.
API permission, signature or commit-conflict failures stop the run. A timeout
can occur after GitHub accepted a mutation, so inspect remote state or repeat
the same invocation; do not create a different automation branch to retry.
See [GitHub commit API documentation](https://docs.github.com/en/graphql/reference/commits#createcommitonbranch).
This handles remote target lists and signed submissions. Organization discovery is described below. Qualification-aware merging and classic branch enforcement are described below; scheduling and ruleset reconciliation remain separate work. A submitted PR is not a completed migration. Unknown profiles and
native workflows require their own central conversion, not deletion by this tool.
## Organization discovery
The coordinator can select observed current branches directly from GitHub:
```sh
python tools/reconcile_enrollment.py --organization QRun-IO --orb-version 0.8 --output organization-plan.json
python tools/reconcile_enrollment.py --organization QRun-IO --orb-version 0.8 --output organization-result.json --apply
```
Repository and branch inventories are paginated. Only existing main/develop
branches are considered; historical release branches are excluded. Archived
repositories and the orb's own bootstrap repository are reported separately.
Each supported branch receives the same immutable preflight as explicit targets.
Unknown workflows, missing entrypoints, unsupported branch layouts and unavailable
APIs stay `unresolved` in the output. They are never counted as conforming or
silently converted. No-CI and native-only repositories may therefore appear as
unresolved here; use the estate auditor for their separate policy classification.
Discovery finishes before any submission. `--apply` processes qualified plans
and retains unresolved entries for follow-up; one unsupported repository does
not prevent independent valid submissions. An explicit `--targets` batch keeps
its stricter behavior: any preflight failure stops the whole batch. By default neither mode merges PRs or changes branch protections. Use the explicit completion flags below.
## Qualification and enforcement
```sh
python tools/reconcile_enrollment.py --targets remote-targets.json --orb-version 0.8 --output result.json --apply --merge-ready --enforce
```
Both flags require `--apply` and are optional. `--merge-ready` revalidates the
signed submission, exact parent/files/content and current base, requires successful
CircleCI-app `setup` and `verify` checks and every advertised latest check/status,
then requests a normal exact-head squash merge. It never uses admin override or
force pushes. The resulting signed merge must have the qualified source tree.
Pending/failed checks and changed bases are reported without merging. Repeated
runs can advance the same PR once checks complete; there is no polling loop that
holds a CI executor open.
`--enforce` independently checks the actual current target branch, which must
pass its own orb gates before shared classic protection enforcement. Existing
protections and other required checks are preserved. Supported gate profiles are
QBit, Core, frontend-core, frontend-material and repository-policy. Other profiles
remain explicitly unsupported for completion even when source enrollment works.
Existing active repository rulesets with app-bound gates and no bypass actors are verified without writes. Unsupported or incomplete rulesets remain unresolved; none are rewritten or layered with classic protection. API/plan restrictions remain visible.
A merged source update and an enforced branch are separate reported outcomes.
Neither proves artifact publication or deployment. Scheduling and ruleset
reconciliation remain outstanding.
## Central hosted pass
The orb owner's CircleCI config accepts `run_enrollment_reconcile: true` on
`main`. This selects one small Python container instead of the normal orb
build/publication workflow. It uses the existing
`qqq-maven-registry-credentials` context's GitHub token through `gh`.
No consumer-specific runner configuration or local signing key is needed.
`tools/run_enrollment.py` verifies the owner repository and main branch, runs
organization discovery, signed enrollment, qualified merging and enforcement,
then exits. The pass has a 20-minute execution limit. Pending checks are reported
for the next pass rather than polled while a paid executor waits. Incremental
results and execution status are retained under `artifacts/enrollment`, including
when execution fails or times out. A completed pass does not mean every repository
conforms: unresolved and waiting entries remain explicit follow-up work.
Create a single daily CircleCI schedule for the owner project only after a manual
main-branch pass verifies its hosted credentials and results. Set `branch: main`
and `run_enrollment_reconcile: true` in the schedule parameters. Scheduling is
an external project setting; merging this config does not itself enable a schedule.
Keep the existing RC-finalization parameter false for these runs. A timed-out
GitHub request may already have succeeded remotely; the next pass resumes from
the deterministic branch and verified source rather than forcing updates.
+61
View File
@@ -7,3 +7,64 @@ One native job downloads Kustomize 5.7.1 with its pinned official SHA-256 and re
The caller runs on main pushes and pull requests without path filters, so a required check always reports. Superseded PR runs are canceled. Feature pushes do not create duplicate jobs. Remove the old Circle pipeline only after the native job passes on the consumer, then disable obsolete Circle build requests and require the observed native check with no human review.
For marketing-website-cd, the prior Circle job only printed Hello World. Its former production role moved to KofTwentyTwo/cluster-gitops; validation does not re-enable that retired deployment path.
The shared registry includes marketing-website-cd and voyage-cd. Daily enrollment recognizes their canonical main-branch caller without creating Circle configuration. Recognition requires a signed immutable worker pin matching the supported worker, a complete source tree, and no additional Circle or GitHub workflows. Enforcement requires the GitHub Actions app-bound gitops / validate gate and preserves existing branch rules. Unavailable private-repository protections remain an explicit enforcement failure; recognition alone is not enforcement.
### Documentation repositories with shell automation
Use the canonical `repository-policy` manifest with `shell_checks: true` for
repositories containing documentation, YAML/JSON, Mermaid source, and shell tools.
The shared job remains one small executor with no publication or deployment.
It installs ShellCheck only for this opt-in and checks every tracked `.sh` file
with `bash -n` and ShellCheck at warning severity; scripts are never executed.
Mermaid files are treated as UTF-8 documentation, not rendered or syntax-validated.
Application manifests and other executable languages still require a build profile.
### Homebrew distribution taps
The `homebrew-tap` profile takes only `tap` (lowercase owner/name) and `formula`.
One small job in a digest-pinned Homebrew container validates the exact checkout,
reads all OS/architecture variants, fetches their binaries with checksum verification,
then installs and tests the Linux formula. It does not publish or update formulae.
macOS downloads are verified, but this Linux job does not execute macOS binaries.
### Application template acceptance
The `application-template` profile renders the checked-out template through pinned
qctl code and a checksum-verified catalog. It runs transforms but never post-generation
hooks, then performs Maven verify on the generated application with all its tests.
The renderer and Maven dependencies are cached; test reports and the generated JAR
are retained. This is acceptance of a generated consumer, not Maven publication.
Only the standard profile, orb version, and default branch are consumer settings.
The coordinator also recognizes qctl on main/develop and the approved .github,
business-platform, MCP-RAG and IntelliJ callers on main. It verifies each complete
workflow inventory, canonical caller, signed immutable orb pin and matching shared
worker source before recognizing the repository. Native verification gates bind to
the GitHub Actions app; release-only jobs are not merge requirements. No CircleCI
caller is added to these native consumers. qctl requires its shared tests; the native binary job is push-only, and
full platform release builds retain their existing shared-worker policy.
Existing classic branch protections without a required-status-check section gain
an additive shared ruleset. Signing, reviews, history and access restrictions remain
unchanged, and a subsequent reconciliation verifies the effective ruleset.
The same daily pass manages CircleCI's native `autocancel-builds` setting for
canonical `repository-policy`, `homebrew-tap`, `application-template`, and
`marketing` consumers. Marketing must retain `main` as its default branch;
environment deployment remains main-only. CircleCI excludes default-branch,
scheduled and rerun workflows from automatic cancellation. This avoids a custom
cancellation job and does not add executions to consumer pipelines.
The pass uses the existing orb-publishing context on the trusted orb main branch.
It changes only the cancellation flag, checks for source movement before writing,
and verifies preservation of all other flags. Its separate
`result.circle-settings.json` artifact records missing credentials/API access,
unconverted sources and profiles needing cancellation-policy review explicitly.
Publication-heavy profiles are not changed until their non-default release
semantics are reviewed; a successful reconciliation pass does not certify them.
Because cancellation is project-wide, eligibility requires every discovered current main/develop branch to be canonical and use a reviewed profile. An unresolved branch or an unreviewed publishing profile prevents enabling the flag, regardless of branch order. The report lists all observed profiles.
+1 -1
View File
@@ -12,7 +12,7 @@ text = source.read_text(encoding="utf-8")
start = text.index("# BEGIN PROFILE RESOURCES")
end = text.index("# END PROFILE RESOURCES") + len("# END PROFILE RESOURCES")
embedded = ["# Generated by scripts/pack_pipeline.py; edit source/resources, then regenerate.", "import base64", "import zlib"]
for variable, name in (("CORE_TEMPLATE", "core"), ("MATERIAL_TEMPLATE", "frontend-material"), ("VOYAGE_TEMPLATE", "voyage"), ("NEXT_TEMPLATE", "frontend-next"), ("ALL_TEMPLATE", "all"), ("STARTER_TEMPLATE", "app-starter"), ("ANDROID_TEMPLATE", "android"), ("POLICY_TEMPLATE", "mcp-policy"), ("REPOSITORY_POLICY_TEMPLATE", "repository-policy"), ("MARKETING_TEMPLATE", "marketing")):
for variable, name in (("CORE_TEMPLATE", "core"), ("MATERIAL_TEMPLATE", "frontend-material"), ("VOYAGE_TEMPLATE", "voyage"), ("NEXT_TEMPLATE", "frontend-next"), ("ALL_TEMPLATE", "all"), ("STARTER_TEMPLATE", "app-starter"), ("ANDROID_TEMPLATE", "android"), ("POLICY_TEMPLATE", "mcp-policy"), ("REPOSITORY_POLICY_TEMPLATE", "repository-policy"), ("MARKETING_TEMPLATE", "marketing"), ("HOMEBREW_TEMPLATE", "homebrew-tap"), ("APPLICATION_TEMPLATE", "application-template")):
resource = (source.parent / "templates" / (name + ".json")).read_text(encoding="utf-8").encode("utf-8")
payload = base64.b64encode(zlib.compress(resource, level=9)).decode("ascii")
embedded.append(f'{variable} = json.loads(zlib.decompress(base64.b64decode("{payload}")))')
+8
View File
@@ -5,6 +5,12 @@ description: >
- Deploys signed artifacts and waits for confirmed Central release publication
- Saves Maven cache for future builds
parameters:
skip_verified_analysis:
type: boolean
default: false
description: "Skip repeated SpotBugs and PMD only after this job has completed mvn_verify"
steps:
- run:
name: Setup Maven Settings
@@ -17,6 +23,8 @@ steps:
# Central's native publication wait can be silent for its 30-minute limit.
# Let Maven return its real result before CircleCI's inactivity watchdog.
no_output_timeout: 35m
environment:
QQQ_SKIP_VERIFIED_ANALYSIS: << parameters.skip_verified_analysis >>
command: <<include(scripts/mvn_jar_deploy.sh)>>
- save_cache:
paths:
+1 -1
View File
@@ -3,7 +3,7 @@ description: >
- Adds SSH keys for Git operations
- Sets up Git identity for version commits
- Synchronizes NPM version
- Commits version changes if modified (skipped for feature branches)
- Commits version changes if modified (skipped for feature and snapshot builds)
parameters:
branch_type:
+2 -1
View File
@@ -57,7 +57,8 @@ steps:
steps:
- check_middleware_api_versions
- mvn_jar_deploy
- mvn_jar_deploy:
skip_verified_analysis: true
- when:
condition:
+105 -12
View File
@@ -25,6 +25,8 @@ ANDROID_TEMPLATE = json.loads((_TEMPLATE_DIR / "android.json").read_text(encodin
POLICY_TEMPLATE = json.loads((_TEMPLATE_DIR / "mcp-policy.json").read_text(encoding="utf-8"))
REPOSITORY_POLICY_TEMPLATE = json.loads((_TEMPLATE_DIR / "repository-policy.json").read_text(encoding="utf-8"))
MARKETING_TEMPLATE = json.loads((_TEMPLATE_DIR / "marketing.json").read_text(encoding="utf-8"))
HOMEBREW_TEMPLATE = json.loads((_TEMPLATE_DIR / "homebrew-tap.json").read_text(encoding="utf-8"))
APPLICATION_TEMPLATE = json.loads((_TEMPLATE_DIR / "application-template.json").read_text(encoding="utf-8"))
# END PROFILE RESOURCES
@@ -70,16 +72,20 @@ def load_manifest(path, setup_version):
if not isinstance(data, dict):
raise ManifestError("Manifest must be a mapping")
profile = data.get("profile")
if profile not in ("qbit", "core", "frontend-material", "frontend-core", "cli", "voyage", "frontend-next", "all", "app-starter", "android", "mcp-policy", "repository-policy", "marketing"):
if profile not in ("qbit", "core", "frontend-material", "frontend-core", "cli", "voyage", "frontend-next", "all", "app-starter", "android", "mcp-policy", "repository-policy", "marketing", "node-artifact", "homebrew-tap", "application-template"):
raise ManifestError("Unsupported profile")
allowed = ("profile", "orb_version", "default_branch", "docs_only", "publish")
if profile in ("qbit", "core"):
if profile == "homebrew-tap":
allowed = ("profile", "orb_version", "default_branch", "tap", "formula")
elif profile == "node-artifact":
allowed = ("profile", "orb_version", "default_branch", "node_version", "context", "npm_scopes", "artifact_path", "build_branches")
elif profile in ("qbit", "core"):
allowed += ("java_version", "browsers", "api_checks")
if profile == "qbit":
allowed += ("release_completion", "release_on_main", "release_tag_policy", "test_branch_policy")
elif profile == "cli":
allowed += ("publish_context",)
elif profile in ("voyage", "frontend-next", "app-starter", "android", "mcp-policy", "repository-policy", "marketing"):
elif profile in ("voyage", "frontend-next", "app-starter", "android", "mcp-policy", "repository-policy", "marketing", "application-template"):
allowed = ("profile", "orb_version", "default_branch")
elif profile == "all":
allowed = ("profile", "orb_version", "default_branch", "publish", "publish_context")
@@ -87,6 +93,8 @@ def load_manifest(path, setup_version):
allowed += ("node_version",)
if profile == "frontend-material":
allowed += ("java_version",)
if profile == "repository-policy":
allowed += ("shell_checks",)
mapping(data, allowed, "manifest")
version = data.get("orb_version")
if not isinstance(version, str) or not re.fullmatch(r"(?:\d+\.\d+(?:\.\d+)?|dev:[A-Za-z0-9_-]+)", version):
@@ -98,12 +106,38 @@ def load_manifest(path, setup_version):
raise ManifestError("default_branch must be main or develop")
if profile == "marketing" and default_branch != "main":
raise ManifestError("Marketing requires the audited main production branch")
if profile == "homebrew-tap":
tap, formula = data.get("tap"), data.get("formula")
if not isinstance(tap, str) or not re.fullmatch(r"[a-z0-9][a-z0-9-]*/[a-z0-9][a-z0-9-]*", tap):
raise ManifestError("Homebrew requires an explicit lowercase owner/tap")
if not isinstance(formula, str) or not re.fullmatch(r"[a-z0-9][a-z0-9+@._-]*", formula):
raise ManifestError("Homebrew requires a literal formula name")
return {"profile": profile, "orb_version": version, "default_branch": default_branch,
"tap": tap, "formula": formula}
java = data.get("java_version", "21")
if java not in ("17", "21"):
raise ManifestError("java_version must be the string 17 or 21")
node = data.get("node_version", "24.21" if profile == "frontend-core" else "20")
if not isinstance(node, str) or not re.fullmatch(r"\d+(?:\.\d+){0,2}", node):
raise ManifestError("node_version must be an explicit numeric version string")
if profile == "node-artifact":
if "node_version" not in data or not re.fullmatch(r"\d+\.\d+(?:\.\d+)?", node):
raise ManifestError("Node artifact requires an explicit minor or patch image version")
context = data.get("context", "")
scopes = data.get("npm_scopes", [])
artifact = data.get("artifact_path")
branches = data.get("build_branches")
if not isinstance(context, str) or not re.fullmatch(r"[A-Za-z0-9_-]+", context):
raise ManifestError("Node artifact requires an explicit context")
if not isinstance(scopes, list) or any(not isinstance(x, str) or not re.fullmatch(r"@[a-z0-9][a-z0-9-]*", x) for x in scopes) or len(scopes) != len(set(scopes)):
raise ManifestError("Invalid npm registry scopes")
if not isinstance(artifact, str) or not re.fullmatch(r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_.-]+)+", artifact) or any(x in (".", "..") for x in artifact.split("/")):
raise ManifestError("Artifact must be a relative file path")
if not isinstance(branches, list) or not branches or any(not isinstance(x, str) or not re.fullmatch(r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_.-]+)*", x) for x in branches) or len(branches) != len(set(branches)):
raise ManifestError("Build branches must be distinct literal branch names")
return {"profile": profile, "orb_version": version, "default_branch": default_branch,
"node_version": node, "context": context, "npm_scopes": scopes,
"artifact_path": artifact, "build_branches": branches}
publish_keys = ("snapshot", "release_candidate", "release")
if profile == "all":
publish_keys = ("snapshot",)
@@ -130,17 +164,18 @@ def load_manifest(path, setup_version):
raise ManifestError("Unsupported QBit release tag policy")
test_policy = data.get("test_branch_policy", "all")
if test_policy not in ("all", "non-release", "non-release-no-integration", "feature", "non-release-no-main",
"non-release-no-hotfix", "non-release-no-main-hotfix", "feature-no-hotfix"):
"non-release-no-hotfix", "non-release-no-hotfix-integration", "non-release-no-main-hotfix", "feature-no-hotfix"):
raise ManifestError("Unsupported QBit test branch policy")
return {"profile": profile, "orb_version": version, "default_branch": default_branch,
"java_version": java, "node_version": node, "browsers": boolean(data, "browsers", True),
"api_checks": boolean(data, "api_checks", False),
"shell_checks": boolean(data, "shell_checks", False),
"release_completion": boolean(data, "release_completion", False),
"release_on_main": boolean(data, "release_on_main", False),
"release_tag_policy": tag_policy, "test_branch_policy": test_policy,
"docs_only": boolean(data, "docs_only", False),
"publish_context": publish_context,
"publish": {key: boolean(publishing, key, key != "asciidoc" and profile not in ("cli", "all", "repository-policy")
"publish": {key: boolean(publishing, key, key != "asciidoc" and profile not in ("cli", "all", "repository-policy", "application-template")
and not (profile == "qbit" and key in ("hotfix", "feature")))
for key in publish_keys}}
@@ -238,6 +273,7 @@ def qbit_template(config, branch, tag):
"feature": "/(develop|main|release/.*|integration.*)/",
"non-release-no-main": "/(develop|main|release/.*)/",
"non-release-no-hotfix": "/(develop|release/.*|hotfix/.*)/",
"non-release-no-hotfix-integration": "/(develop|release/.*|hotfix/.*|integration.*)/",
"non-release-no-main-hotfix": "/(develop|main|release/.*|hotfix/.*)/",
"feature-no-hotfix": "/(develop|main|release/.*|hotfix/.*|integration.*)/"}
ignored = ignores[config.get("test_branch_policy", "all")]
@@ -406,9 +442,18 @@ def cli_template(config, branch, tag):
def marketing_template(config, branch, tag):
del config, branch, tag
# One final continuation; Munitor supplies jobs, never another setup pipeline.
return copy.deepcopy(MARKETING_TEMPLATE)
del config
# Select the existing branch policy once; automation PRs use normal PR checks.
selected = {"main": "production", "develop": "develop", "staging": "staging"}.get(
branch, "release-candidate" if branch.startswith("release/") else "pr-checks")
result = copy.deepcopy(MARKETING_TEMPLATE)
workflow = result["workflows"][selected]
for job in workflow["jobs"]:
next(iter(job.values()))["filters"] = {
"branches": {"ignore": "/.*/" if tag else "automation/qbit-rc-pending"},
"tags": {"ignore": "/.*/"}}
result["workflows"] = {"verify": workflow}
return result
def android_template(config, branch, tag):
@@ -444,21 +489,69 @@ def next_template(config, branch, tag):
def voyage_template(config, branch, tag):
del branch, tag # This profile's reviewed static filters own its three workflows.
return json.loads(json.dumps(VOYAGE_TEMPLATE).replace("__ORB_VERSION__", config["orb_version"]))
del tag # Existing job filters retain tag exclusion and main-only release actions.
selected = "develop" if branch == "develop" else (
"release" if branch == "main" or branch.startswith("release/") else "pull-request")
result = json.loads(json.dumps(VOYAGE_TEMPLATE).replace("__ORB_VERSION__", config["orb_version"]))
result["workflows"] = {"verify": result["workflows"][selected]}
return result
def repository_policy_template(config, branch, tag):
del branch, tag
result = copy.deepcopy(REPOSITORY_POLICY_TEMPLATE)
if config.get("shell_checks", False):
job = result["jobs"]["validate-policy"]
job["environment"] = {"QQQ_POLICY_SHELL": "true"}
job["steps"].insert(1, {"run": {
"name": "Install static shell validation",
"command": "sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends shellcheck"}})
return result
def homebrew_template(config, branch, tag):
del branch, tag
result = copy.deepcopy(HOMEBREW_TEMPLATE)
result["jobs"]["validate-tap"]["environment"].update({
"QQQ_HOMEBREW_TAP": config["tap"], "QQQ_HOMEBREW_FORMULA": config["formula"]})
return result
def application_template(config, branch, tag):
del config, branch, tag
return copy.deepcopy(REPOSITORY_POLICY_TEMPLATE)
return copy.deepcopy(APPLICATION_TEMPLATE)
PROFILE_TEMPLATES = {"qbit": qbit_template, "core": core_template,
PROFILE_TEMPLATES = {"application-template": application_template, "homebrew-tap": homebrew_template, "qbit": qbit_template, "core": core_template,
"repository-policy": repository_policy_template,
"frontend-material": frontend_template, "frontend-core": frontend_template,
"cli": cli_template, "voyage": voyage_template, "frontend-next": next_template, "all": all_template, "app-starter": starter_template, "android": android_template, "mcp-policy": policy_template, "marketing": marketing_template}
def node_artifact_template(config, branch, tag):
# One checkout/install is shared by tests and an optional artifact build.
lines = ["registry=https://registry.npmjs.org/"]
lines += [scope + ":registry=https://npm.pkg.github.com/" for scope in config["npm_scopes"]]
if config["npm_scopes"]:
lines.append("//npm.pkg.github.com/:_authToken=${NPM_TOKEN}")
npmrc = "printf '%s\\n' " + " ".join("'" + line + "'" for line in lines) + " >> .npmrc"
steps = ["checkout", {"run": {"name": "Configure npm registries", "command": npmrc}},
{"restore_cache": {"keys": ['node-artifact-npm-v1-{{ checksum "package-lock.json" }}', 'node-artifact-npm-v1-']}},
{"run": {"name": "Install locked dependencies", "command": "npm ci --prefer-offline --cache ~/.npm"}},
{"save_cache": {"key": 'node-artifact-npm-v1-{{ checksum "package-lock.json" }}', "paths": ["~/.npm"]}},
{"run": {"name": "Test project", "command": "npm test"}}]
if not tag and branch in config["build_branches"]:
steps += [{"run": {"name": "Build artifact", "command": "npm run build"}},
{"store_artifacts": {"path": config["artifact_path"], "destination": config["artifact_path"].split("/")[-1]}}]
return {"version": 2.1,
"jobs": {"node_artifact": {"docker": [{"image": "cimg/node:" + config["node_version"]}], "steps": steps}},
"workflows": {"verify": {"jobs": [{"node_artifact": {"context": [config["context"]],
"filters": {"branches": {"ignore": "automation/qbit-rc-pending"}, "tags": {"ignore": "/.*/"}}}}]}}}
PROFILE_TEMPLATES["node-artifact"] = node_artifact_template
def runtime_boolean(name):
value = os.environ.get(name, "false").lower()
if value in ("true", "1"):
+8
View File
@@ -22,6 +22,13 @@
set -e
# The shared publish job already ran these checks in its verify lifecycle.
# Standalone command callers retain analysis unless explicitly opted in.
analysis_args=()
if [[ "${QQQ_SKIP_VERIFIED_ANALYSIS:-false}" == "true" || "${QQQ_SKIP_VERIFIED_ANALYSIS:-false}" == "1" ]]; then
analysis_args=(-Dspotbugs.skip=true -Dpmd.skip=true)
fi
##############################################
## Deploy signed artifacts to Maven Central ##
##############################################
@@ -30,6 +37,7 @@ set -e
# Central 0.8.x: this completion flag overrides inherited literal waitUntil=uploaded.
# Do not report a release as successful until Central confirms publication.
mvn -s /tmp/circleci/mvn-settings.xml -P release -B -DskipTests \
"${analysis_args[@]}" \
-Dgpg.keyname="$GPG_KEYNAME" -Dgpg.passphrase="$GPG_PASSPHRASE" \
-DwaitForPublishCompletion=true \
-Dflatten.mode=resolveCiFriendliesOnly -DupdatePomFile=true \
+1 -1
View File
@@ -1,5 +1,5 @@
#!/bin/bash
set -e
set -eo pipefail
echo "Running PMD static analysis..."
+1 -1
View File
@@ -1,5 +1,5 @@
#!/bin/bash
set -e
set -eo pipefail
echo "Running SpotBugs static analysis..."
+1 -1
View File
@@ -64,7 +64,7 @@ echo "Publishing version: $VERSION"
if [[ "$VERSION" =~ -RC\.[0-9]+$ ]]; then
NPM_TAG="rc"
echo "Detected RC version - using tag: $NPM_TAG"
elif [[ "$VERSION" =~ -SNAPSHOT$ ]]; then
elif [[ "$VERSION" =~ -SNAPSHOT(\.[1-9][0-9]*)?$ ]]; then
NPM_TAG="snapshot"
echo "Detected SNAPSHOT version - using tag: $NPM_TAG"
elif [[ "$VERSION" =~ -(alpha|beta) ]]; then
+5 -5
View File
@@ -9,7 +9,7 @@
## It also pushes the changes back to the current branch.
##
## Process:
## 1. Skips for feature branches (ephemeral versions)
## 1. Skips for feature and snapshot builds (ephemeral versions)
## 2. Checks if package.json has been modified
## 3. Extracts the new version from package.json
## 4. Commits the changes with skip ci flag
@@ -22,12 +22,12 @@
set -e
################################################################
## Skip version commit for feature branches ##
## Feature versions are ephemeral and don't need to be ##
## Skip version commit for feature and snapshot builds ##
## These versions are ephemeral and don't need to be ##
## persisted back to the repository ##
################################################################
if [[ "$BRANCH_TYPE" == "feature" ]]; then
echo "Skipping version commit for feature branch (ephemeral versions)"
if [[ "$BRANCH_TYPE" == "feature" || "$BRANCH_TYPE" == "snapshot" ]]; then
echo "Skipping version commit for $BRANCH_TYPE build (ephemeral version)"
exit 0
fi
+109 -16
View File
@@ -16,16 +16,18 @@ import yaml
# Generated by scripts/pack_pipeline.py; edit source/resources, then regenerate.
import base64
import zlib
CORE_TEMPLATE = json.loads(zlib.decompress(base64.b64decode("eNrtPWt3m0iy3+dX9NVk13ZWgN+PJJ5zE9tz4908HWd39kS5Oi1oJMYIMI3s6CTe375V3Q1CCBDIsvyIM19k6K6urndVVzPffyGkccFC7vhe4xlZ19ea+CSgIe2zCJ7Dw+/wBJ71fa/rtzuOZ7Uth3Y9n0eOOXoPI6JhwODvRsf3XUa9RjN+YTGbDtwI3tnU5Uw8vpJvGx77FrWpabIgop7J2p2BZ7msPQjdPNA8Ch2vmwe50agClvfo+tb2XCGHzGROEF0L9C8KfMMPOymSn5+fa/AEB54BBB76/pmhHv7vqr6t7zWSmabf71PPSs3mEQ0jTbBNQ7ZpUUhNlkaQRyzACV/UAwTTY+aZP4gSbEkyXLwPB14KgnrogbAgkh9CBpLDiH/pMYu8xZUJ980zFpG0yDTHZyvMEYBjEz6wfEKDSOvCrEFg0YgR7fyc/PWv468cD/bnukQbitdcbA5GtTyAqUAS7YJ4nHkgyITzBEQyFQb0yc7WFjGifiAIm6JWCuMYrJitVtIYET/2cTDR/GkwjCBktut0e5Hu+l2YO2DPSdRjHkIOQEAimyyxb4EfRuTjx4/tt+/f/d/79unJy4Oj9snnd/t/OW+1vCXSajw5OD45eHPU/tf7k3/8/ub9v9p/f/+qfXzYapDffsPXr15+et0+evfPVqPlMdA2hM/Mnk+WJEMQaxAmkuBDBh69oI5LOy6gZPpe5HgDYGLodB2PuuQtvWAeEYLB9aWWZzstr5Fi4VXy+2oWoXnf4Sy8gPU8dwgEcTj50+8scQL4MNdN5Mh2vkWDkE1IT4eaZ93QHwgBQqoWS1fEeEQ0D4n0PYfEz7QrIOKPH4R9c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Eyg29w7AHaitnYjs5yDRWh1925H9LvgUApq2wyzBliQjOnBiPQPuLSKH0I5O4F1a3e5TN37v/w6QAGpBU8NsHXrS1hDEfRRlN7jEQ3jiAVqcQJDXh2gec6v5NjVIazja01DoX9JuBmkvl4nn+I4H2QG2NeCR+jSerpDNskKwTLaWluUxftE/WLH4RKV6xYwkJMusri4lzRflDRKKTIba/VivRARCs4fB+qLsjJC9D0K+sQ4AHMu/G7YgLI00KyCk3/YS6sq2BLnoFcgWvL0iUm3g5zLk8SD/mOJ/VxOucr0P+WVtKe0Sq709siJsRn4Uw3sMwzHLats1mx6Ko4oq92aq4tSjdxv1bgld+M9Wbk+spcqOe8wHk41yrtpbhdRmWlwzXk7UMYmL93HeXn76+CZPOj/oAEPDQdyJHY8hb2G99RWvWVaVSixagb0ni94pXrLine truncated
MATERIAL_TEMPLATE = json.loads(zlib.decompress(base64.b64decode("eNq1lMtugzAQRfd8heV1TNRKlar8QXdVt02EXDMhDthGfqRBiH/vQAmPvKRU6g7PjH3PXI+pI0IoHEEEb6yjK1JjAENlwatvK7OdH2IYTY3IwWLks4+QIdflpeIZYJoqYWMlhTXObH0sjFqOB64OT/HLa/zM9lypig77m/5rE51WzaKl25uvq2CJB+fdFO/UR0swaWBxyjsPpZvRU7EDkZswFp11ZFHDWEgEx8qJVp/OoZof2Md1qViKYqyuSSfhgiJrWnKRo0OsQB/jvTN6TUnTTLTPt9NZZjNZNaNvt9CDvgTWXHUX9Kad50VBUAV0ClpIcGccFK9NcZ225QhEhCSMFZBxUbESwHaE9CEkxw/3rOyV/uwcVvnd9fswKSTKpKEA92+efgRN3oexIwfpAi+IhQyHyEmjye/A3nP5SMa57cof9LebVW693HIxexsTg+avg1kojfXLc6wUxaXmHrmvbvgLWNtQgmaE4h5bW8X6quUNmctfRdREPykCLqM=")))
VOYAGE_TEMPLATE = json.loads(zlib.decompress(base64.b64decode("eNrtW+tz2zYS/56/AqPJXJKeSUqqHzndqBNbdm1NGzsnObneVDkNREISLBK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87k0NtF+Ez81yZ6ekq3AJvme/OEDpPL/Wcly/xz9BYMn66JmwPhWZY7NhFADAhgFkj9aEtQorKMydRfr5C1vLOIdh8uroYX3y/jn1++vSk2EY3k1CjpQKYNqnvsayKBJhEyrHJu4PioH2qWLNkM+gur5NFJv0JH9CSSGStAbt3PCkmCcxKsyByEHkDBRM4cUn6Fe23AljBt1AISVxNhcqpMAjcuxa4hqQPrUEG3rS+i5MzHW8X5UuorO3qewf/DTp3nXKRlo3BgHE8IVqqMe6Y5iTLgPSUgfVsjqaXOSDVwJAiw7t8gA6GS5ZQ3ebfWUI52dRZcujqF1VefE69m8CjhFWU2y4CN88sXp6CFWtf3xp365uP63imznAp1d2CHK5O3t7da9tHza1iuEdM6LqXv+4wWOGzcXgJTE8MkWnIo5zd4JtFob3jYfxvSFmDTa7M5NnuCSUmx3ilkKxcWB8hr5w653z69PH4v/SabCcM1uHcHhJZel6sRGJhx68w6SAykIB1nwu6qH/f+V/9p+KsYvQ8+jt9FUb/1cRwML5rDyafu/nuvacD+2Hc2nT/snNGl")))
ALL_TEMPLATE = json.loads(zlib.decompress(base64.b64decode("eNq1T7EOgjAU3PmKpjNIdHQyJg4ukmDiYkwDUkxt4UkLEkP4dwsSUojootu7u/fu7lUWQvhOpWKQ4iVazOZ2w4AMlYaVnjXKsszRjCYwZ+lFSQDuduSKEM9fk8PG32+9HSFYn9StRwmSxwJKw0gHsfjhBGnkqAQ47RWtXaGNPHYY9YpZwQ2EIC8X47bbSYOkccRhwUTUhuRU5dhYqvu5rfglZ1xxFHMGSbE91G4SYiYmZUmzgkk6/LPTplsjdPrXD3EhxIcf3sk//sEy1QbVVm09Ad15mhY=")))
STARTER_TEMPLATE = json.loads(zlib.decompress(base64.b64decode("eNp1UMGKwkAMvc9XlDmKtejR0yJ42MsKCl5EQnUzZbbTiZ0ZqiL9d1OpWqt7y3t5eS/JRUSRrNB5TVZOo8loPGwYcjvP8MI1o7IsY2aYkLm2mXdEedKSXwCL5QzW8+Xqe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v7Nm/Hihfjq5rxwL715e74t/dn9s/8DqAZZ8g==")))
class ManifestError(ValueError):
@@ -70,16 +72,20 @@ def load_manifest(path, setup_version):
if not isinstance(data, dict):
raise ManifestError("Manifest must be a mapping")
profile = data.get("profile")
if profile not in ("qbit", "core", "frontend-material", "frontend-core", "cli", "voyage", "frontend-next", "all", "app-starter", "android", "mcp-policy", "repository-policy", "marketing"):
if profile not in ("qbit", "core", "frontend-material", "frontend-core", "cli", "voyage", "frontend-next", "all", "app-starter", "android", "mcp-policy", "repository-policy", "marketing", "node-artifact", "homebrew-tap", "application-template"):
raise ManifestError("Unsupported profile")
allowed = ("profile", "orb_version", "default_branch", "docs_only", "publish")
if profile in ("qbit", "core"):
if profile == "homebrew-tap":
allowed = ("profile", "orb_version", "default_branch", "tap", "formula")
elif profile == "node-artifact":
allowed = ("profile", "orb_version", "default_branch", "node_version", "context", "npm_scopes", "artifact_path", "build_branches")
elif profile in ("qbit", "core"):
allowed += ("java_version", "browsers", "api_checks")
if profile == "qbit":
allowed += ("release_completion", "release_on_main", "release_tag_policy", "test_branch_policy")
elif profile == "cli":
allowed += ("publish_context",)
elif profile in ("voyage", "frontend-next", "app-starter", "android", "mcp-policy", "repository-policy", "marketing"):
elif profile in ("voyage", "frontend-next", "app-starter", "android", "mcp-policy", "repository-policy", "marketing", "application-template"):
allowed = ("profile", "orb_version", "default_branch")
elif profile == "all":
allowed = ("profile", "orb_version", "default_branch", "publish", "publish_context")
@@ -87,6 +93,8 @@ def load_manifest(path, setup_version):
allowed += ("node_version",)
if profile == "frontend-material":
allowed += ("java_version",)
if profile == "repository-policy":
allowed += ("shell_checks",)
mapping(data, allowed, "manifest")
version = data.get("orb_version")
if not isinstance(version, str) or not re.fullmatch(r"(?:\d+\.\d+(?:\.\d+)?|dev:[A-Za-z0-9_-]+)", version):
@@ -98,12 +106,38 @@ def load_manifest(path, setup_version):
raise ManifestError("default_branch must be main or develop")
if profile == "marketing" and default_branch != "main":
raise ManifestError("Marketing requires the audited main production branch")
if profile == "homebrew-tap":
tap, formula = data.get("tap"), data.get("formula")
if not isinstance(tap, str) or not re.fullmatch(r"[a-z0-9][a-z0-9-]*/[a-z0-9][a-z0-9-]*", tap):
raise ManifestError("Homebrew requires an explicit lowercase owner/tap")
if not isinstance(formula, str) or not re.fullmatch(r"[a-z0-9][a-z0-9+@._-]*", formula):
raise ManifestError("Homebrew requires a literal formula name")
return {"profile": profile, "orb_version": version, "default_branch": default_branch,
"tap": tap, "formula": formula}
java = data.get("java_version", "21")
if java not in ("17", "21"):
raise ManifestError("java_version must be the string 17 or 21")
node = data.get("node_version", "24.21" if profile == "frontend-core" else "20")
if not isinstance(node, str) or not re.fullmatch(r"\d+(?:\.\d+){0,2}", node):
raise ManifestError("node_version must be an explicit numeric version string")
if profile == "node-artifact":
if "node_version" not in data or not re.fullmatch(r"\d+\.\d+(?:\.\d+)?", node):
raise ManifestError("Node artifact requires an explicit minor or patch image version")
context = data.get("context", "")
scopes = data.get("npm_scopes", [])
artifact = data.get("artifact_path")
branches = data.get("build_branches")
if not isinstance(context, str) or not re.fullmatch(r"[A-Za-z0-9_-]+", context):
raise ManifestError("Node artifact requires an explicit context")
if not isinstance(scopes, list) or any(not isinstance(x, str) or not re.fullmatch(r"@[a-z0-9][a-z0-9-]*", x) for x in scopes) or len(scopes) != len(set(scopes)):
raise ManifestError("Invalid npm registry scopes")
if not isinstance(artifact, str) or not re.fullmatch(r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_.-]+)+", artifact) or any(x in (".", "..") for x in artifact.split("/")):
raise ManifestError("Artifact must be a relative file path")
if not isinstance(branches, list) or not branches or any(not isinstance(x, str) or not re.fullmatch(r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_.-]+)*", x) for x in branches) or len(branches) != len(set(branches)):
raise ManifestError("Build branches must be distinct literal branch names")
return {"profile": profile, "orb_version": version, "default_branch": default_branch,
"node_version": node, "context": context, "npm_scopes": scopes,
"artifact_path": artifact, "build_branches": branches}
publish_keys = ("snapshot", "release_candidate", "release")
if profile == "all":
publish_keys = ("snapshot",)
@@ -130,17 +164,18 @@ def load_manifest(path, setup_version):
raise ManifestError("Unsupported QBit release tag policy")
test_policy = data.get("test_branch_policy", "all")
if test_policy not in ("all", "non-release", "non-release-no-integration", "feature", "non-release-no-main",
"non-release-no-hotfix", "non-release-no-main-hotfix", "feature-no-hotfix"):
"non-release-no-hotfix", "non-release-no-hotfix-integration", "non-release-no-main-hotfix", "feature-no-hotfix"):
raise ManifestError("Unsupported QBit test branch policy")
return {"profile": profile, "orb_version": version, "default_branch": default_branch,
"java_version": java, "node_version": node, "browsers": boolean(data, "browsers", True),
"api_checks": boolean(data, "api_checks", False),
"shell_checks": boolean(data, "shell_checks", False),
"release_completion": boolean(data, "release_completion", False),
"release_on_main": boolean(data, "release_on_main", False),
"release_tag_policy": tag_policy, "test_branch_policy": test_policy,
"docs_only": boolean(data, "docs_only", False),
"publish_context": publish_context,
"publish": {key: boolean(publishing, key, key != "asciidoc" and profile not in ("cli", "all", "repository-policy")
"publish": {key: boolean(publishing, key, key != "asciidoc" and profile not in ("cli", "all", "repository-policy", "application-template")
and not (profile == "qbit" and key in ("hotfix", "feature")))
for key in publish_keys}}
@@ -238,6 +273,7 @@ def qbit_template(config, branch, tag):
"feature": "/(develop|main|release/.*|integration.*)/",
"non-release-no-main": "/(develop|main|release/.*)/",
"non-release-no-hotfix": "/(develop|release/.*|hotfix/.*)/",
"non-release-no-hotfix-integration": "/(develop|release/.*|hotfix/.*|integration.*)/",
"non-release-no-main-hotfix": "/(develop|main|release/.*|hotfix/.*)/",
"feature-no-hotfix": "/(develop|main|release/.*|hotfix/.*|integration.*)/"}
ignored = ignores[config.get("test_branch_policy", "all")]
@@ -406,9 +442,18 @@ def cli_template(config, branch, tag):
def marketing_template(config, branch, tag):
del config, branch, tag
# One final continuation; Munitor supplies jobs, never another setup pipeline.
return copy.deepcopy(MARKETING_TEMPLATE)
del config
# Select the existing branch policy once; automation PRs use normal PR checks.
selected = {"main": "production", "develop": "develop", "staging": "staging"}.get(
branch, "release-candidate" if branch.startswith("release/") else "pr-checks")
result = copy.deepcopy(MARKETING_TEMPLATE)
workflow = result["workflows"][selected]
for job in workflow["jobs"]:
next(iter(job.values()))["filters"] = {
"branches": {"ignore": "/.*/" if tag else "automation/qbit-rc-pending"},
"tags": {"ignore": "/.*/"}}
result["workflows"] = {"verify": workflow}
return result
def android_template(config, branch, tag):
@@ -444,21 +489,69 @@ def next_template(config, branch, tag):
def voyage_template(config, branch, tag):
del branch, tag # This profile's reviewed static filters own its three workflows.
return json.loads(json.dumps(VOYAGE_TEMPLATE).replace("__ORB_VERSION__", config["orb_version"]))
del tag # Existing job filters retain tag exclusion and main-only release actions.
selected = "develop" if branch == "develop" else (
"release" if branch == "main" or branch.startswith("release/") else "pull-request")
result = json.loads(json.dumps(VOYAGE_TEMPLATE).replace("__ORB_VERSION__", config["orb_version"]))
result["workflows"] = {"verify": result["workflows"][selected]}
return result
def repository_policy_template(config, branch, tag):
del branch, tag
result = copy.deepcopy(REPOSITORY_POLICY_TEMPLATE)
if config.get("shell_checks", False):
job = result["jobs"]["validate-policy"]
job["environment"] = {"QQQ_POLICY_SHELL": "true"}
job["steps"].insert(1, {"run": {
"name": "Install static shell validation",
"command": "sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends shellcheck"}})
return result
def homebrew_template(config, branch, tag):
del branch, tag
result = copy.deepcopy(HOMEBREW_TEMPLATE)
result["jobs"]["validate-tap"]["environment"].update({
"QQQ_HOMEBREW_TAP": config["tap"], "QQQ_HOMEBREW_FORMULA": config["formula"]})
return result
def application_template(config, branch, tag):
del config, branch, tag
return copy.deepcopy(REPOSITORY_POLICY_TEMPLATE)
return copy.deepcopy(APPLICATION_TEMPLATE)
PROFILE_TEMPLATES = {"qbit": qbit_template, "core": core_template,
PROFILE_TEMPLATES = {"application-template": application_template, "homebrew-tap": homebrew_template, "qbit": qbit_template, "core": core_template,
"repository-policy": repository_policy_template,
"frontend-material": frontend_template, "frontend-core": frontend_template,
"cli": cli_template, "voyage": voyage_template, "frontend-next": next_template, "all": all_template, "app-starter": starter_template, "android": android_template, "mcp-policy": policy_template, "marketing": marketing_template}
def node_artifact_template(config, branch, tag):
# One checkout/install is shared by tests and an optional artifact build.
lines = ["registry=https://registry.npmjs.org/"]
lines += [scope + ":registry=https://npm.pkg.github.com/" for scope in config["npm_scopes"]]
if config["npm_scopes"]:
lines.append("//npm.pkg.github.com/:_authToken=${NPM_TOKEN}")
npmrc = "printf '%s\\n' " + " ".join("'" + line + "'" for line in lines) + " >> .npmrc"
steps = ["checkout", {"run": {"name": "Configure npm registries", "command": npmrc}},
{"restore_cache": {"keys": ['node-artifact-npm-v1-{{ checksum "package-lock.json" }}', 'node-artifact-npm-v1-']}},
{"run": {"name": "Install locked dependencies", "command": "npm ci --prefer-offline --cache ~/.npm"}},
{"save_cache": {"key": 'node-artifact-npm-v1-{{ checksum "package-lock.json" }}', "paths": ["~/.npm"]}},
{"run": {"name": "Test project", "command": "npm test"}}]
if not tag and branch in config["build_branches"]:
steps += [{"run": {"name": "Build artifact", "command": "npm run build"}},
{"store_artifacts": {"path": config["artifact_path"], "destination": config["artifact_path"].split("/")[-1]}}]
return {"version": 2.1,
"jobs": {"node_artifact": {"docker": [{"image": "cimg/node:" + config["node_version"]}], "steps": steps}},
"workflows": {"verify": {"jobs": [{"node_artifact": {"context": [config["context"]],
"filters": {"branches": {"ignore": "automation/qbit-rc-pending"}, "tags": {"ignore": "/.*/"}}}}]}}}
PROFILE_TEMPLATES["node-artifact"] = node_artifact_template
def runtime_boolean(name):
value = os.environ.get(name, "false").lower()
if value in ("true", "1"):
+7 -3
View File
@@ -28,13 +28,17 @@ if [[ "$CURRENT_BRANCH" == "main" ]]; then
TARGET_VERSION="$MAJOR_MINOR.0"
echo "Main branch detected - targeting release version: $TARGET_VERSION"
elif [[ "$CURRENT_BRANCH" == "develop" ]]; then
# Develop branch - should be a snapshot version (e.g., 1.0.127-SNAPSHOT)
# Increment patch version for develop
# Snapshot coordinates are unique per CI job without pushing a version commit.
# The source head stays the head whose required checks are being reported.
if [[ ! "${CIRCLE_BUILD_NUM:-}" =~ ^[1-9][0-9]*$ ]]; then
echo "ERROR: Snapshot publication requires a positive CIRCLE_BUILD_NUM" >&2
exit 1
fi
MAJOR_MINOR_PATCH="${NPM_VERSION%-*}"
MAJOR_MINOR="${MAJOR_MINOR_PATCH%.*}"
PATCH="${MAJOR_MINOR_PATCH##*.}"
NEW_PATCH=$((PATCH + 1))
TARGET_VERSION="$MAJOR_MINOR.$NEW_PATCH-SNAPSHOT"
TARGET_VERSION="$MAJOR_MINOR.$NEW_PATCH-SNAPSHOT.$CIRCLE_BUILD_NUM"
echo "Develop branch detected - targeting snapshot version: $TARGET_VERSION"
elif [[ "$CURRENT_BRANCH" == release/* ]]; then
# Release branch - should be a release candidate (e.g., 1.0.0-RC.1, 1.0.0-RC.2, etc.)
@@ -0,0 +1,70 @@
{
"version": 2.1,
"jobs": {
"verify-template": {
"docker": [
{
"image": "cimg/openjdk:21.0"
}
],
"resource_class": "medium",
"steps": [
"checkout",
{
"restore_cache": {
"keys": [
"qqq-template-v1-java21-d84a5783bf09c58e42ba72203247f20bd5779302"
]
}
},
{
"run": {
"name": "Prepare pinned qctl renderer",
"command": "set -euo pipefail\ntool_dir=\"${QQQ_TEMPLATE_TOOL_DIR:-$HOME/.cache/qqq-template-renderer}\"\nmaven_repo=\"${QQQ_TEMPLATE_MAVEN_REPO:-$HOME/.m2/repository}\"\nif [[ ! -d \"$tool_dir/.git\" ]]; then\n git init \"$tool_dir\"\n git -C \"$tool_dir\" remote add origin https://github.com/QRun-IO/qctl.git\n git -C \"$tool_dir\" fetch --depth=1 origin d84a5783bf09c58e42ba72203247f20bd5779302\n git -C \"$tool_dir\" checkout --detach FETCH_HEAD\nfi\ntest \"$(git -C \"$tool_dir\" rev-parse HEAD)\" = d84a5783bf09c58e42ba72203247f20bd5779302\ncd \"$tool_dir\"\n# Build the immutable, already-qualified renderer, not another copy of the consumer.\nif [[ ! -f \"$tool_dir/qctl-qqq/target/qctl-qqq-0.2.1.jar\" || ! -f \"$maven_repo/io/qrun/qctl/qctl-qqq/0.2.1/qctl-qqq-0.2.1.pom\" ]]; then\n mvn -B -ntp -f \"$tool_dir/pom.xml\" -Dmaven.repo.local=\"$maven_repo\" -pl qctl-qqq -am install -DskipTests\nfi\nmvn -B -ntp -f \"$tool_dir/pom.xml\" -Dmaven.repo.local=\"$maven_repo\" -pl qctl-qqq dependency:build-classpath -Dmdep.outputFile=\"$tool_dir/classpath.txt\"\n",
"no_output_timeout": "10m"
}
},
{
"run": {
"name": "Render the exact template checkout without hooks",
"command": "set -euo pipefail\ntool_dir=\"${QQQ_TEMPLATE_TOOL_DIR:-$HOME/.cache/qqq-template-renderer}\"\noutput=\"${QQQ_TEMPLATE_OUTPUT:-$HOME/qqq-template-acceptance}\"\nwork=\"${QQQ_TEMPLATE_WORK:-/tmp/qqq-template-check}\"\nmkdir -p \"$work\"\ncurl --fail --silent --show-error --location --retry 2 --max-time 60 https://raw.githubusercontent.com/QRun-IO/qqq-templates-hub/4d22fc650967eee609107476d5dc3ac5dffeb071/templates.yaml -o \"$work/catalog.yaml\"\necho \"9342ef716f11ffea25a684fba6865e4daf303d968b5fa6a1ddcc6de43a6bb193 $work/catalog.yaml\" | sha256sum --check --status\ncat > \"$work/QqqTemplateCheck.java\" \\<<'JAVA'\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLFactory;\nimport io.qrun.qctl.qqq.template.TemplateEngine;\nimport io.qrun.qctl.qqq.template.TemplateManifest;\nimport io.qrun.qctl.qqq.template.TransformExecutor;\n\npublic class QqqTemplateCheck\n{\n public static void main(String[] args) throws Exception\n {\n if(args.length != 3)\n {\n throw new IllegalArgumentException(\"Expected catalog, checked-out template, fresh output directory\");\n }\n Path output = Path.of(args[2]);\n if(Files.exists(output))\n {\n throw new IllegalArgumentException(\"Output directory must not exist\");\n }\n ObjectMapper mapper = new ObjectMapper(new YAMLFactory());\n JsonNode index = mapper.readTree(Path.of(args[0]).toFile());\n TemplateManifest manifest = null;\n for(JsonNode entry : index.get(\"templates\"))\n {\n if(\"new-qqq-application\".equals(entry.path(\"id\").asText()))\n {\n if(manifest != null) throw new IllegalArgumentException(\"Duplicate template entry\");\n manifest = mapper.treeToValue(entry, TemplateManifest.class);\n }\n }\n if(manifest == null) throw new IllegalArgumentException(\"Template missing from catalog\");\n TemplateEngine engine = new TemplateEngine();\n Map<String, String> variables = new LinkedHashMap<>(Map.of(\n \"projectName\", \"ci-template\", \"groupId\", \"io.qrun.ci\",\n \"artifactId\", \"ci-template\", \"packageName\", \"io.qrun.ci\"));\n variables = engine.evaluateComputed(manifest.computed(), variables);\n Files.createDirectories(output);\n int count = engine.render(Path.of(args[1]), output, variables, manifest);\n if(manifest.transforms() != null)\n {\n new TransformExecutor().execute(output, manifest.transforms(), variables);\n }\n if(count == 0 || !Files.isRegularFile(output.resolve(\"pom.xml\")))\n {\n throw new IllegalStateException(\"Renderer did not create the application\");\n }\n System.out.println(\"Rendered \" + count + \" files from the exact local template; hooks not executed\");\n }\n}\nJAVA\njava -cp \"$(cat \"$tool_dir/classpath.txt\"):$tool_dir/qctl-qqq/target/classes\" \"$work/QqqTemplateCheck.java\" \"$work/catalog.yaml\" \"$PWD\" \"$output\"\n"
}
},
{
"run": {
"name": "Verify generated application and package",
"command": "set -euo pipefail\nmvn -B -ntp -f \"${QQQ_TEMPLATE_OUTPUT:-$HOME/qqq-template-acceptance}/pom.xml\" -Dmaven.repo.local=\"${QQQ_TEMPLATE_MAVEN_REPO:-$HOME/.m2/repository}\" verify\n",
"no_output_timeout": "10m"
}
},
{
"store_test_results": {
"path": "~/qqq-template-acceptance/target/surefire-reports"
}
},
{
"store_artifacts": {
"path": "~/qqq-template-acceptance/target/ci-template.jar",
"destination": "generated-application.jar"
}
},
{
"save_cache": {
"key": "qqq-template-v1-java21-d84a5783bf09c58e42ba72203247f20bd5779302",
"paths": [
"~/.m2/repository",
"~/.cache/qqq-template-renderer"
]
}
}
]
}
},
"workflows": {
"verify": {
"jobs": [
"verify-template"
]
}
}
}
+4 -1
View File
@@ -426,7 +426,10 @@
"uses": "QRun-IO/qqq-orb/.github/workflows/gitops.yml@WORKER_SHA"
}
}
}
},
"additional_repositories": [
"QRun-IO/voyage-cd"
]
},
"qbit-codeql": {
"repository": null,
+3 -3
View File
@@ -238,7 +238,7 @@
{
"run": {
"name": "Build framework dependencies for the sample",
"command": "mvn -B -s /tmp/circleci/mvn-settings.xml -Drevision=0.0.0-sample-acceptance -DskipTests clean install"
"command": "mvn -B -s /tmp/circleci/mvn-settings.xml -Drevision=0.0.0-sample-acceptance -DskipTests -Dspotbugs.skip=true -Dpmd.skip=true clean install"
}
},
{
@@ -308,7 +308,7 @@
{
"run": {
"name": "Build framework dependencies for the sample",
"command": "mvn -B -s /tmp/circleci/mvn-settings.xml -Drevision=0.0.0-sample-multinode -DskipTests clean install"
"command": "mvn -B -s /tmp/circleci/mvn-settings.xml -Drevision=0.0.0-sample-multinode -DskipTests -Dspotbugs.skip=true -Dpmd.skip=true clean install"
}
},
{
@@ -336,7 +336,7 @@
{
"run": {
"name": "Build framework dependencies for the consumers",
"command": "mvn -B -s /tmp/circleci/mvn-settings.xml -Drevision=0.0.0-sample-acceptance -DskipTests clean install"
"command": "mvn -B -s /tmp/circleci/mvn-settings.xml -Drevision=0.0.0-sample-acceptance -DskipTests -Dspotbugs.skip=true -Dpmd.skip=true clean install"
}
},
{
+36
View File
@@ -0,0 +1,36 @@
{
"version": 2.1,
"jobs": {
"validate-tap": {
"docker": [
{
"image": "ghcr.io/homebrew/brew@sha256:0e2563de582c530c92c55420cfa67e5b60bcb541781297ee34c6508ca6e746a3"
}
],
"resource_class": "small",
"working_directory": "/home/linuxbrew/project",
"environment": {
"HOMEBREW_NO_AUTO_UPDATE": "1",
"HOMEBREW_NO_ANALYTICS": "1",
"HOMEBREW_NO_INSTALL_CLEANUP": "1"
},
"steps": [
"checkout",
{
"run": {
"name": "Verify all platform downloads and install the exact tap revision",
"no_output_timeout": "5m",
"command": "set -euo pipefail\nbrew tap \"$QQQ_HOMEBREW_TAP\" \"$PWD\"\ntest \"$(git -C \"$(brew --repository \"$QQQ_HOMEBREW_TAP\")\" rev-parse HEAD)\" = \"$(git rev-parse HEAD)\"\nbrew trust \"$QQQ_HOMEBREW_TAP\"\nbrew readall --syntax --os=all --arch=all \"$QQQ_HOMEBREW_TAP\"\nbrew fetch --all-platforms --build-from-source \"$QQQ_HOMEBREW_TAP/$QQQ_HOMEBREW_FORMULA\"\nbrew install \"$QQQ_HOMEBREW_TAP/$QQQ_HOMEBREW_FORMULA\"\nbrew test \"$QQQ_HOMEBREW_TAP/$QQQ_HOMEBREW_FORMULA\"\n"
}
}
]
}
},
"workflows": {
"verify": {
"jobs": [
"validate-tap"
]
}
}
}
+80 -94
View File
@@ -11,7 +11,7 @@
"name": "build-and-test",
"node_version": "22",
"package_manager": "npm",
"test_commands": "[\"npm run lint\", \"npm run build\", \"npx playwright install chromium --with-deps\", \"npm run test:chromium\", \"npm run lighthouse\"]",
"test_commands": "[\"#!/usr/bin/env bash\\nprintf '%s\\\\n' 'pipeline: node-webapp' 'node_version: 22' 'docker:' ' use_repo_dockerfile: true' > .munitor.yml\", \"npm run lint\", \"npm run build\", \"npx playwright install chromium --with-deps\", \"npm run test:chromium\", \"#!/usr/bin/env bash\\nset -euo pipefail\\nnpm run start > /tmp/qqq-link-server.log 2>&1 &\\nserver_pid=$!\\ntrap 'kill \\\"$server_pid\\\" 2>/dev/null || true; wait \\\"$server_pid\\\" 2>/dev/null || true' EXIT\\nready=false\\nfor _attempt in {1..60}; do\\n if ! kill -0 \\\"$server_pid\\\" 2>/dev/null; then\\n cat /tmp/qqq-link-server.log\\n exit 1\\n fi\\n if curl --fail --silent --output /dev/null --max-time 2 http://localhost:3005/; then\\n ready=true\\n break\\n fi\\n sleep 1\\ndone\\nif [ \\\"$ready\\\" != true ]; then\\n cat /tmp/qqq-link-server.log\\n echo 'Marketing server did not become ready on port 3005' >&2\\n exit 1\\nfi\\nnpm run check-links\", \"npm run lighthouse\"]",
"context": [
"github"
],
@@ -22,7 +22,21 @@
"/hotfix\\/.*/"
]
}
}
},
"post-steps": [
{
"store_artifacts": {
"path": "playwright-report",
"destination": "playwright-report"
}
},
{
"store_artifacts": {
"path": ".lighthouseci",
"destination": "lighthouse-report"
}
}
]
}
},
{
@@ -88,28 +102,6 @@
}
}
},
{
"munitor/node_coverage": {
"name": "coverage",
"node_version": "22",
"package_manager": "npm",
"min_coverage": "0",
"coverage_tool": "jest",
"coverage_summary_path": "coverage/coverage-summary.json",
"coverage_command": "mkdir -p coverage && echo '{\"total\":{\"lines\":{\"pct\":100}}}' > coverage/coverage-summary.json",
"requires": [
"build-and-test"
],
"filters": {
"branches": {
"only": [
"/feature\\/.*/",
"/hotfix\\/.*/"
]
}
}
}
},
{
"munitor/node_security_scan": {
"name": "security-scan",
@@ -137,7 +129,7 @@
"name": "build-and-test",
"node_version": "22",
"package_manager": "npm",
"test_commands": "[\"npm run lint\", \"npm run build\", \"npx playwright install chromium --with-deps\", \"npm run test:chromium\", \"npm run lighthouse\"]",
"test_commands": "[\"#!/usr/bin/env bash\\nprintf '%s\\\\n' 'pipeline: node-webapp' 'node_version: 22' 'docker:' ' use_repo_dockerfile: true' > .munitor.yml\", \"npm run lint\", \"npm run build\", \"npx playwright install chromium --with-deps\", \"npm run test:chromium\", \"#!/usr/bin/env bash\\nset -euo pipefail\\nnpm run start > /tmp/qqq-link-server.log 2>&1 &\\nserver_pid=$!\\ntrap 'kill \\\"$server_pid\\\" 2>/dev/null || true; wait \\\"$server_pid\\\" 2>/dev/null || true' EXIT\\nready=false\\nfor _attempt in {1..60}; do\\n if ! kill -0 \\\"$server_pid\\\" 2>/dev/null; then\\n cat /tmp/qqq-link-server.log\\n exit 1\\n fi\\n if curl --fail --silent --output /dev/null --max-time 2 http://localhost:3005/; then\\n ready=true\\n break\\n fi\\n sleep 1\\ndone\\nif [ \\\"$ready\\\" != true ]; then\\n cat /tmp/qqq-link-server.log\\n echo 'Marketing server did not become ready on port 3005' >&2\\n exit 1\\nfi\\nnpm run check-links\", \"npm run lighthouse\"]",
"context": [
"github"
],
@@ -145,7 +137,21 @@
"branches": {
"only": "develop"
}
}
},
"post-steps": [
{
"store_artifacts": {
"path": "playwright-report",
"destination": "playwright-report"
}
},
{
"store_artifacts": {
"path": ".lighthouseci",
"destination": "lighthouse-report"
}
}
]
}
},
{
@@ -184,25 +190,6 @@
}
}
},
{
"munitor/node_coverage": {
"name": "coverage",
"node_version": "22",
"package_manager": "npm",
"min_coverage": "0",
"coverage_tool": "jest",
"coverage_summary_path": "coverage/coverage-summary.json",
"coverage_command": "mkdir -p coverage && echo '{\"total\":{\"lines\":{\"pct\":100}}}' > coverage/coverage-summary.json",
"requires": [
"build-and-test"
],
"filters": {
"branches": {
"only": "develop"
}
}
}
},
{
"munitor/node_security_scan": {
"name": "security-scan",
@@ -228,7 +215,6 @@
"health_db": "false",
"requires": [
"code-quality",
"coverage",
"secrets-scan",
"sast-scan",
"security-scan"
@@ -252,7 +238,7 @@
"name": "build-and-test",
"node_version": "22",
"package_manager": "npm",
"test_commands": "[\"npm run lint\", \"npm run build\", \"npx playwright install chromium --with-deps\", \"npm run test:chromium\", \"npm run lighthouse\"]",
"test_commands": "[\"#!/usr/bin/env bash\\nprintf '%s\\\\n' 'pipeline: node-webapp' 'node_version: 22' 'docker:' ' use_repo_dockerfile: true' > .munitor.yml\", \"npm run lint\", \"npm run build\", \"npx playwright install chromium --with-deps\", \"npm run test:chromium\", \"#!/usr/bin/env bash\\nset -euo pipefail\\nnpm run start > /tmp/qqq-link-server.log 2>&1 &\\nserver_pid=$!\\ntrap 'kill \\\"$server_pid\\\" 2>/dev/null || true; wait \\\"$server_pid\\\" 2>/dev/null || true' EXIT\\nready=false\\nfor _attempt in {1..60}; do\\n if ! kill -0 \\\"$server_pid\\\" 2>/dev/null; then\\n cat /tmp/qqq-link-server.log\\n exit 1\\n fi\\n if curl --fail --silent --output /dev/null --max-time 2 http://localhost:3005/; then\\n ready=true\\n break\\n fi\\n sleep 1\\ndone\\nif [ \\\"$ready\\\" != true ]; then\\n cat /tmp/qqq-link-server.log\\n echo 'Marketing server did not become ready on port 3005' >&2\\n exit 1\\nfi\\nnpm run check-links\", \"npm run lighthouse\"]",
"context": [
"github"
],
@@ -260,7 +246,21 @@
"branches": {
"only": "staging"
}
}
},
"post-steps": [
{
"store_artifacts": {
"path": "playwright-report",
"destination": "playwright-report"
}
},
{
"store_artifacts": {
"path": ".lighthouseci",
"destination": "lighthouse-report"
}
}
]
}
},
{
@@ -299,25 +299,6 @@
}
}
},
{
"munitor/node_coverage": {
"name": "coverage",
"node_version": "22",
"package_manager": "npm",
"min_coverage": "0",
"coverage_tool": "jest",
"coverage_summary_path": "coverage/coverage-summary.json",
"coverage_command": "mkdir -p coverage && echo '{\"total\":{\"lines\":{\"pct\":100}}}' > coverage/coverage-summary.json",
"requires": [
"build-and-test"
],
"filters": {
"branches": {
"only": "staging"
}
}
}
},
{
"munitor/node_security_scan": {
"name": "security-scan",
@@ -343,7 +324,6 @@
"health_db": "false",
"requires": [
"code-quality",
"coverage",
"secrets-scan",
"sast-scan",
"security-scan"
@@ -367,7 +347,7 @@
"name": "build-and-test",
"node_version": "22",
"package_manager": "npm",
"test_commands": "[\"npm run lint\", \"npm run build\", \"npx playwright install chromium --with-deps\", \"npm run test:chromium\", \"npm run lighthouse\"]",
"test_commands": "[\"#!/usr/bin/env bash\\nprintf '%s\\\\n' 'pipeline: node-webapp' 'node_version: 22' 'docker:' ' use_repo_dockerfile: true' > .munitor.yml\", \"npm run lint\", \"npm run build\", \"npx playwright install chromium --with-deps\", \"npm run test:chromium\", \"#!/usr/bin/env bash\\nset -euo pipefail\\nnpm run start > /tmp/qqq-link-server.log 2>&1 &\\nserver_pid=$!\\ntrap 'kill \\\"$server_pid\\\" 2>/dev/null || true; wait \\\"$server_pid\\\" 2>/dev/null || true' EXIT\\nready=false\\nfor _attempt in {1..60}; do\\n if ! kill -0 \\\"$server_pid\\\" 2>/dev/null; then\\n cat /tmp/qqq-link-server.log\\n exit 1\\n fi\\n if curl --fail --silent --output /dev/null --max-time 2 http://localhost:3005/; then\\n ready=true\\n break\\n fi\\n sleep 1\\ndone\\nif [ \\\"$ready\\\" != true ]; then\\n cat /tmp/qqq-link-server.log\\n echo 'Marketing server did not become ready on port 3005' >&2\\n exit 1\\nfi\\nnpm run check-links\", \"npm run lighthouse\"]",
"context": [
"github"
],
@@ -377,7 +357,21 @@
"/release\\/.*/"
]
}
}
},
"post-steps": [
{
"store_artifacts": {
"path": "playwright-report",
"destination": "playwright-report"
}
},
{
"store_artifacts": {
"path": ".lighthouseci",
"destination": "lighthouse-report"
}
}
]
}
},
{
@@ -422,27 +416,6 @@
}
}
},
{
"munitor/node_coverage": {
"name": "coverage",
"node_version": "22",
"package_manager": "npm",
"min_coverage": "0",
"coverage_tool": "jest",
"coverage_summary_path": "coverage/coverage-summary.json",
"coverage_command": "mkdir -p coverage && echo '{\"total\":{\"lines\":{\"pct\":100}}}' > coverage/coverage-summary.json",
"requires": [
"build-and-test"
],
"filters": {
"branches": {
"only": [
"/release\\/.*/"
]
}
}
}
},
{
"munitor/node_security_scan": {
"name": "security-scan",
@@ -470,7 +443,6 @@
"health_db": "false",
"requires": [
"code-quality",
"coverage",
"secrets-scan",
"sast-scan",
"security-scan"
@@ -514,7 +486,7 @@
"name": "build-and-test",
"node_version": "22",
"package_manager": "npm",
"test_commands": "[\"npm run lint\", \"npm run build\", \"npx playwright install chromium --with-deps\", \"npm run test:chromium\", \"npm run lighthouse\"]",
"test_commands": "[\"#!/usr/bin/env bash\\nprintf '%s\\\\n' 'pipeline: node-webapp' 'node_version: 22' 'docker:' ' use_repo_dockerfile: true' > .munitor.yml\", \"npm run lint\", \"npm run build\", \"npx playwright install chromium --with-deps\", \"npm run test:chromium\", \"#!/usr/bin/env bash\\nset -euo pipefail\\nnpm run start > /tmp/qqq-link-server.log 2>&1 &\\nserver_pid=$!\\ntrap 'kill \\\"$server_pid\\\" 2>/dev/null || true; wait \\\"$server_pid\\\" 2>/dev/null || true' EXIT\\nready=false\\nfor _attempt in {1..60}; do\\n if ! kill -0 \\\"$server_pid\\\" 2>/dev/null; then\\n cat /tmp/qqq-link-server.log\\n exit 1\\n fi\\n if curl --fail --silent --output /dev/null --max-time 2 http://localhost:3005/; then\\n ready=true\\n break\\n fi\\n sleep 1\\ndone\\nif [ \\\"$ready\\\" != true ]; then\\n cat /tmp/qqq-link-server.log\\n echo 'Marketing server did not become ready on port 3005' >&2\\n exit 1\\nfi\\nnpm run check-links\", \"npm run lighthouse\"]",
"context": [
"github"
],
@@ -522,7 +494,21 @@
"branches": {
"only": "main"
}
}
},
"post-steps": [
{
"store_artifacts": {
"path": "playwright-report",
"destination": "playwright-report"
}
},
{
"store_artifacts": {
"path": ".lighthouseci",
"destination": "lighthouse-report"
}
}
]
}
},
{
+1 -1
View File
@@ -19,7 +19,7 @@
{
"run": {
"name": "Validate the application-free branch",
"command": "python3 \\<<'PYTHON'\nimport json\nfrom pathlib import Path\nimport subprocess\nimport xml.etree.ElementTree as ET\nimport yaml\n\npaths = subprocess.check_output(['git', 'ls-files', '-z']).decode('utf-8').split('\\0')\npaths = [Path(name) for name in paths if name]\nif not paths:\n raise SystemExit('No tracked policy files')\nnames = {'LICENSE', 'NOTICE', 'COPYING', 'CODEOWNERS', '.gitignore', '.gitattributes',\n '.editorconfig', 'mvnw', 'mvnw.cmd'}\nsuffixes = {'.md', '.rst', '.txt', '.adoc', '.yml', '.yaml', '.json', '.properties'}\nmanifests = {'pom.xml', 'package.json', 'cargo.toml', 'pyproject.toml', 'go.mod',\n 'build.gradle', 'build.gradle.kts', 'settings.gradle', 'settings.gradle.kts'}\nfor path in paths:\n if path.is_symlink() or path.name.lower() in manifests:\n raise SystemExit(f'Application or symlink requires a build profile: {path}')\n if path.as_posix() == '.mvn/wrapper/maven-wrapper.jar':\n continue\n if path.as_posix() == 'checkstyle/config.xml':\n ET.fromstring(path.read_text(encoding='utf-8'))\n continue\n if path.name not in names and path.suffix.lower() not in suffixes:\n raise SystemExit(f'Unsupported policy file; select a build profile: {path}')\n text = path.read_text(encoding='utf-8')\n if path.suffix.lower() in ('.yml', '.yaml'):\n list(yaml.safe_load_all(text))\n elif path.suffix.lower() == '.json':\n json.loads(text)\nprint(f'Validated {len(paths)} tracked policy/documentation files; no application build or publication')\nPYTHON\n"
"command": "python3 \\<<'PYTHON'\nimport json\nimport os\nfrom pathlib import Path\nimport subprocess\nimport xml.etree.ElementTree as ET\nimport yaml\n\npaths = subprocess.check_output(['git', 'ls-files', '-z']).decode('utf-8').split('\\0')\npaths = [Path(name) for name in paths if name]\nif not paths:\n raise SystemExit('No tracked policy files')\nnames = {'LICENSE', 'NOTICE', 'COPYING', 'CODEOWNERS', '.gitignore', '.gitattributes',\n '.editorconfig', 'mvnw', 'mvnw.cmd'}\nshell_checks = os.environ.get('QQQ_POLICY_SHELL') == 'true'\nsuffixes = {'.md', '.rst', '.txt', '.adoc', '.yml', '.yaml', '.json', '.properties'}\nmanifests = {'pom.xml', 'package.json', 'cargo.toml', 'pyproject.toml', 'go.mod',\n 'build.gradle', 'build.gradle.kts', 'settings.gradle', 'settings.gradle.kts'}\nfor path in paths:\n if path.is_symlink() or path.name.lower() in manifests:\n raise SystemExit(f'Application or symlink requires a build profile: {path}')\n if path.as_posix() == '.mvn/wrapper/maven-wrapper.jar':\n continue\n if path.as_posix() == 'checkstyle/config.xml':\n ET.fromstring(path.read_text(encoding='utf-8'))\n continue\n if shell_checks and path.suffix.lower() == '.sh':\n subprocess.run(['bash', '-n', '--', str(path)], check=True)\n subprocess.run(['shellcheck', '--severity=warning', '--', str(path)], check=True)\n continue\n if shell_checks and path.suffix.lower() == '.mmd':\n path.read_text(encoding='utf-8')\n continue\n if path.name not in names and path.suffix.lower() not in suffixes:\n raise SystemExit(f'Unsupported policy file; select a build profile: {path}')\n text = path.read_text(encoding='utf-8')\n if path.suffix.lower() in ('.yml', '.yaml'):\n list(yaml.safe_load_all(text))\n elif path.suffix.lower() == '.json':\n json.loads(text)\nprint(f'Validated {len(paths)} tracked policy/documentation files; no application build or publication')\nPYTHON\n"
}
}
]
File diff suppressed because it is too large. Load diff
+5
View File
@@ -47,6 +47,9 @@ PROFILE_PARAMETERS = {
"mcp-policy": {},
"repository-policy": {},
"marketing": {},
"node-artifact": {},
"homebrew-tap": {},
"application-template": {},
}
@@ -66,6 +69,8 @@ def canonical_caller(profile, version, explicit_manifest=False, release_tag_poli
"orb_version": version,
"filters": {"branches": {"ignore": "automation/qbit-rc-pending"}, "tags": {"only": "/.*/"}},
}
if profile in ("node-artifact", "homebrew-tap", "application-template"):
options["filters"]["tags"] = {"ignore": "/.*/"}
if profile == "frontend-next":
options["filters"]["branches"] = {"ignore": "/.*/"}
if profile == "qbit" and release_tag_policy is not None:
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -euo pipefail
npm run start > /tmp/qqq-link-server.log 2>&1 &
server_pid=$!
trap 'kill "$server_pid" 2>/dev/null || true; wait "$server_pid" 2>/dev/null || true' EXIT
ready=false
for _attempt in {1..60}; do
if ! kill -0 "$server_pid" 2>/dev/null; then
cat /tmp/qqq-link-server.log
exit 1
fi
if curl --fail --silent --output /dev/null --max-time 2 http://localhost:3005/; then
ready=true
break
fi
sleep 1
done
if [ "$ready" != true ]; then
cat /tmp/qqq-link-server.log
echo 'Marketing server did not become ready on port 3005' >&2
exit 1
fi
npm run check-links
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
printf '%s\n' 'pipeline: node-webapp' 'node_version: 22' 'docker:' ' use_repo_dockerfile: true' > .munitor.yml
+24 -4
View File
@@ -324,13 +324,32 @@ class AuditTests(unittest.TestCase):
self.assertIn('native_maintenance_bridge_drift', [f['code'] for f in report['findings']])
def test_new_circle_profile_mappings_require_actual_configuration(self):
for name, profile in [('qqq-android', 'android'), ('qqq-mcp-rag-standard-policies', 'mcp-policy'), ('marketing-website', 'marketing')]:
for name, profile in [('qqq-android', 'android'), ('qqq-mcp-rag-standard-policies', 'mcp-policy'), ('marketing-website', 'marketing'), ('qqq-templates-hub', 'repository-policy'), ('qqq-meta-manager', 'repository-policy'), ('homebrew-qctl', 'homebrew-tap'), ('new-qqq-application-template', 'application-template')]:
entry = dict(ENTRY, name=name, nameWithOwner='QRun-IO/' + name)
report = audit.audit(entry, Snapshot({}), VERSION, SHA, {})
self.assertEqual(profile, report['profile'])
self.assertIn('missing_manifest', [f['code'] for f in report['findings']])
self.assertIn('missing_canonical_caller', [f['code'] for f in report['findings']])
def test_catalog_requires_canonical_policy_pipeline(self):
self.assertNotIn('QRun-IO/qqq-templates-hub', audit.NO_CI)
entry = dict(ENTRY, name='qqq-templates-hub', nameWithOwner='QRun-IO/qqq-templates-hub')
files = {'.qqq-ci.yml': audit.generator.yaml.safe_dump({
'profile': 'repository-policy', 'orb_version': VERSION, 'default_branch': 'main'}),
'.circleci/config.yml': audit.generator.yaml.safe_dump(
audit.standard.canonical_caller('repository-policy', VERSION)),
'templates.yaml': 'version: 1.0'}
policy = {'managed_branches': ['main'], 'required_checks': {'main': ['setup', 'verify']}}
snapshot = Snapshot(files, ['setup', 'verify'])
snapshot.branch = 'main'
report = audit.audit(entry, snapshot, VERSION, SHA, policy)
self.assertEqual('repository-policy', report['profile'])
self.assertEqual([], report['findings'])
self.assertEqual('pass', report['status'])
files.pop('.circleci/config.yml')
report = audit.audit(entry, snapshot, VERSION, SHA, policy)
self.assertIn('missing_canonical_caller', [f['code'] for f in report['findings']])
def test_intellij_is_native_product_not_no_ci_exception(self):
repository = 'QRun-IO/qqq-app-developer-intellij-plugin'
self.assertNotIn(repository, audit.NO_CI)
@@ -340,7 +359,8 @@ class AuditTests(unittest.TestCase):
self.assertIn('missing_native_maintenance_bridge', [f['code'] for f in report['findings']])
def test_approved_no_ci_is_exact_allowlist_with_evidence_not_check_pass(self):
self.assertEqual(8, len(audit.NO_CI))
self.assertEqual(3, len(audit.NO_CI))
self.assertNotIn("QRun-IO/voyage-cd", audit.NO_CI)
for repository, policy in audit.NO_CI.items():
entry = dict(ENTRY, name=repository.split('/')[-1], nameWithOwner=repository)
files = {path: 'identity fixture' for path in policy['required_paths']}
@@ -362,13 +382,13 @@ class AuditTests(unittest.TestCase):
self.assertIn('profile_not_assigned', [f['code'] for f in report['findings']])
def test_native_specialists_require_bridges_and_report_remaining_workflows(self):
for name, kind in [('qqq-mcp-rag', 'mcp-rag'), ('qqq-business-platform', 'business-db'), ('.github', 'github-workflow-lint'), ('marketing-website-cd', 'gitops')]:
for name, kind in [('qqq-mcp-rag', 'mcp-rag'), ('qqq-business-platform', 'business-db'), ('.github', 'github-workflow-lint'), ('marketing-website-cd', 'gitops'), ('voyage-cd', 'gitops')]:
entry = dict(ENTRY, name=name, nameWithOwner='QRun-IO/' + name)
definition = audit.auxiliary.BRIDGES[kind]
missing = audit.audit(entry, Snapshot({}), VERSION, SHA, {})
self.assertIn('missing_native_maintenance_bridge', [f['code'] for f in missing['findings']])
files = {item['path']: audit.generator.yaml.safe_dump(audit.auxiliary.canonical(key, SHA), sort_keys=False)
for key, item in audit.auxiliary.BRIDGES.items() if item['repository'] == entry['nameWithOwner']}
for key, item in audit.auxiliary.BRIDGES.items() if item['repository'] == entry['nameWithOwner'] or entry['nameWithOwner'] in item.get('additional_repositories', [])}
report = audit.audit(entry, Snapshot(files), VERSION, SHA, {})
self.assertEqual([], report['findings'])
self.assertEqual('unknown', report['status'])
+105
View File
@@ -0,0 +1,105 @@
"""Cost settings preserve source qualification and unrelated project controls."""
from pathlib import Path
import sys
import unittest
from unittest.mock import Mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
import circle_project_settings as settings
class SettingsTests(unittest.TestCase):
def setUp(self):
self.plan = {'repository': 'QRun-IO/marketing-website', 'profile': 'marketing',
'branch': 'main', 'head': 'a' * 40, 'changed': False}
self.before = {'autocancel-builds': False, 'setup-workflows': True,
'build-fork-prs': False, 'drop-all-build-requests': False}
self.source = Mock(side_effect=[{'archived': False, 'default_branch': 'main'},
{'commit': {'sha': self.plan['head']}}])
def test_narrow_update_and_idempotent_readback(self):
request = Mock(side_effect=[{'feature_flags': self.before}, {},
{'feature_flags': {**self.before, 'autocancel-builds': True}}])
result = settings.reconcile(self.plan, self.source, True, request)
self.assertEqual({'state': 'enforced', 'changed': True}, result)
self.assertEqual({'feature_flags': {'autocancel-builds': True}}, request.call_args_list[1].args[1])
request = Mock(return_value={'feature_flags': {**self.before, 'autocancel-builds': True}})
source = Mock(return_value={'archived': False, 'default_branch': 'main'})
self.assertEqual({'state': 'enforced', 'changed': False},
settings.reconcile(self.plan, source, True, request))
self.assertEqual(1, request.call_count)
def test_dry_run_never_writes(self):
request = Mock(return_value={'feature_flags': self.before})
self.assertEqual({'state': 'inspected', 'changed': True},
settings.reconcile(self.plan, self.source, False, request))
request.assert_called_once_with(self.plan['repository'])
def test_unreviewed_profiles_and_unconverted_sources_never_call_api(self):
for change, expected in [({'profile': 'qbit'}, 'not-managed'),
({'profile': 'native-gitops'}, 'not-managed'),
({'changed': True}, 'waiting-source')]:
source, request = Mock(), Mock()
result = settings.reconcile({**self.plan, **change}, source, True, request)
self.assertEqual(expected, result['state'])
source.assert_not_called()
request.assert_not_called()
def test_changed_head_or_unexpected_default_branch_prevents_write(self):
for responses in [
[{'archived': False, 'default_branch': 'main'}, {'commit': {'sha': 'b' * 40}}],
[{'archived': False, 'default_branch': 'develop'}],
[{'archived': True, 'default_branch': 'main'}],
]:
request = Mock(return_value={'feature_flags': self.before})
result = settings.reconcile(self.plan, Mock(side_effect=responses), True, request)
self.assertEqual('unresolved', result['state'])
self.assertTrue(all(len(call.args) == 1 for call in request.call_args_list))
def test_unrelated_setting_drift_and_unavailable_api_are_not_success(self):
request = Mock(side_effect=[{'feature_flags': self.before}, {},
{'feature_flags': {**self.before, 'autocancel-builds': True,
'build-fork-prs': True}}])
self.assertEqual('unresolved', settings.reconcile(self.plan, self.source, True, request)['state'])
source = Mock(return_value={'archived': False, 'default_branch': 'main'})
for response in [Mock(side_effect=ValueError('Central CircleCI credential unavailable')),
Mock(return_value={'feature_flags': {}})]:
self.assertEqual('unresolved', settings.reconcile(self.plan, source, True, response)['state'])
def test_repository_policy_requires_every_current_branch(self):
main = {**self.plan, 'profile': 'repository-policy'}
develop = {**main, 'branch': 'develop', 'profile': 'qbit'}
for plans in ([main, develop], [develop, main]):
source, request = Mock(), Mock()
result = settings.reconcile_repository(plans, [], source, True, request)
self.assertEqual('not-managed', result['state'])
source.assert_not_called()
request.assert_not_called()
for plans, findings in [
([main, {**main, 'branch': 'develop', 'changed': True}], []),
([main], [{'repository': main['repository'], 'branch': 'develop', 'state': 'unresolved'}]),
]:
request = Mock()
self.assertEqual('waiting-source', settings.reconcile_repository(
plans, findings, Mock(), True, request)['state'])
request.assert_not_called()
def test_repository_policy_checks_all_heads_and_writes_once(self):
plans = [self.plan, {**self.plan, 'branch': 'develop', 'head': 'b' * 40}]
def source(path):
if '/branches/' in path:
return {'commit': {'sha': next(p['head'] for p in plans if path.endswith('/' + p['branch']))}}
return {'archived': False, 'default_branch': 'main'}
request = Mock(side_effect=[{'feature_flags': self.before}, {},
{'feature_flags': {**self.before, 'autocancel-builds': True}}])
self.assertEqual({'state': 'enforced', 'changed': True},
settings.reconcile_repository(plans, [], source, True, request))
self.assertEqual(1, sum(len(call.args) == 2 for call in request.call_args_list))
request = Mock()
stale = lambda path: {'commit': {'sha': self.plan['head']}}
self.assertEqual('unresolved', settings.reconcile_repository(plans, [], stale, True, request)['state'])
request.assert_not_called()
if __name__ == '__main__':
unittest.main()
+131
View File
@@ -0,0 +1,131 @@
"""Discovery covers all current branches and never turns an unknown into a target."""
from pathlib import Path
import sys
import unittest
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
import discover_enrollment as discovery
def entry(name, archived=False):
return {'nameWithOwner': 'QRun-IO/' + name, 'isArchived': archived}
class DiscoveryTests(unittest.TestCase):
def policy(self):
return {'QRun-IO/example': {'baseline_sha': 'a' * 40, 'required_paths': ['README.md'],
'forbidden_paths': ['.qqq-ci.yml'], 'forbidden_prefixes': ['.circleci/', '.github/workflows/'],
'rationale': 'Approved documentation-only snapshot'}}
def test_approved_snapshot_is_reported_without_enrollment(self):
def request(path):
if '/branches?' in path:
return [{'name': 'main'}, {'name': 'develop'}]
if '/branches/' in path:
return {'commit': {'sha': ('a' if path.endswith('main') else 'b') * 40}}
return {'truncated': False, 'tree': [{'path': 'README.md', 'type': 'blob'}]}
inspect = mock.Mock(side_effect=lambda target, version: target)
with mock.patch.dict(discovery.audit_estate.NO_CI, self.policy(), clear=True):
plans, findings = discovery.discover('QRun-IO', '0.8', inspect, request, [entry('example')])
self.assertEqual([{'repository': 'QRun-IO/example', 'branch': 'develop'}], plans)
self.assertEqual('approved-no-ci', findings[0]['state'])
self.assertEqual('a' * 40, findings[0]['head'])
inspect.assert_called_once_with(plans[0], '0.8')
def test_no_ci_tree_must_be_complete_and_match_approved_identity(self):
for tree in ({'truncated': True, 'tree': [{'path': 'README.md'}]},
{'truncated': False, 'tree': []},
{'truncated': False, 'tree': [{'path': 'README.md'}, {'path': '.circleci/config.yml'}]}):
def request(path):
if '/branches?' in path:
return [{'name': 'main'}]
if '/branches/' in path:
return {'commit': {'sha': 'a' * 40}}
return tree
inspect = mock.Mock()
with mock.patch.dict(discovery.audit_estate.NO_CI, self.policy(), clear=True):
plans, findings = discovery.discover('QRun-IO', '0.8', inspect, request, [entry('example')])
self.assertEqual([], plans)
self.assertEqual('unresolved', findings[0]['state'])
inspect.assert_not_called()
def test_old_no_ci_label_never_exempts_executable_or_deployment_source(self):
for source in ('base/deployment.yaml', 'template/pom.xml', 'scripts/customize.py', 'Formula/qctl.rb'):
def request(path):
if '/branches?' in path:
return [{'name': 'main'}]
if '/branches/' in path:
return {'commit': {'sha': 'a' * 40}}
return {'truncated': False, 'tree': [{'path': 'README.md', 'type': 'blob'},
{'path': source, 'type': 'blob'}]}
inspect = mock.Mock(side_effect=ValueError('Source needs centralized validation'))
with mock.patch.dict(discovery.audit_estate.NO_CI, self.policy(), clear=True):
plans, findings = discovery.discover('QRun-IO', '0.8', inspect, request, [entry('example')])
self.assertEqual([], plans)
self.assertEqual('unresolved', findings[0]['state'])
inspect.assert_called_once()
def test_changed_no_ci_source_is_never_exempted(self):
def request(path):
if '/branches?' in path:
return [{'name': 'main'}]
return {'commit': {'sha': 'b' * 40}}
inspect = mock.Mock(side_effect=ValueError('Unrecognized executable source'))
with mock.patch.dict(discovery.audit_estate.NO_CI, self.policy(), clear=True):
plans, findings = discovery.discover('QRun-IO', '0.8', inspect, request, [entry('example')])
self.assertEqual([], plans)
self.assertEqual('unresolved', findings[0]['state'])
inspect.assert_called_once()
def test_paginates_branches_and_ignores_historical_releases(self):
requests = []
def request(path):
requests.append(path)
if path.endswith('page=1'):
return [{'name': 'release/' + str(i)} for i in range(99)] + [{'name': 'main'}]
return [{'name': 'develop'}]
inspect = mock.Mock(side_effect=lambda target, version: {**target, 'version': version})
plans, findings = discovery.discover('QRun-IO', '0.8', inspect, request, [entry('example')])
self.assertEqual(['develop', 'main'], [p['branch'] for p in plans])
self.assertEqual(2, len(requests))
self.assertEqual([], findings)
def test_unknown_branch_and_profile_stay_unresolved_while_other_targets_progress(self):
def inspect(target, version):
if target['repository'].endswith('/custom'):
raise ValueError('Unknown orchestration')
return target
def request(path):
return [{'name': 'feature/new'}] if '/new/' in path else [{'name': 'main'}]
plans, findings = discovery.discover('QRun-IO', '0.8', inspect, request,
[entry('custom'), entry('new'), entry('good')])
self.assertEqual([{'repository': 'QRun-IO/good', 'branch': 'main'}], plans)
self.assertEqual(2, len(findings))
self.assertTrue(all(f['state'] == 'unresolved' for f in findings))
def test_archived_and_owner_repositories_are_never_modified(self):
inspect, request = mock.Mock(), mock.Mock()
plans, findings = discovery.discover('QRun-IO', '0.8', inspect, request,
[entry('old', True), entry('qqq-orb')])
self.assertEqual([], plans)
self.assertEqual(['archived', 'owner-bootstrap'], [f['state'] for f in findings])
inspect.assert_not_called()
request.assert_not_called()
def test_api_errors_and_duplicate_branches_never_become_empty_success(self):
for result in (ValueError('GitHub read unavailable'), [{'name': 'main'}, {'name': 'main'}]):
request = mock.Mock(side_effect=result) if isinstance(result, Exception) else mock.Mock(return_value=result)
inspect = mock.Mock()
plans, findings = discovery.discover('QRun-IO', '0.8', inspect, request, [entry('example')])
self.assertEqual([], plans)
self.assertEqual('unresolved', findings[0]['state'])
inspect.assert_not_called()
if __name__ == '__main__':
unittest.main()
+279
View File
@@ -0,0 +1,279 @@
"""Shared enforcement only adds proven gates and preserves unrelated policy."""
import copy
import base64
import importlib.util
from pathlib import Path
import unittest
import yaml
spec = importlib.util.spec_from_file_location('enforcement', Path(__file__).resolve().parents[1] / 'tools/enforce_orb_checks.py')
enforcement = importlib.util.module_from_spec(spec)
spec.loader.exec_module(enforcement)
def runs():
return [{'id': index, 'name': name, 'app': {'id': 18001}, 'conclusion': 'success'}
for index, name in enumerate(('setup', 'verify'), 1)]
class EnforcementTests(unittest.TestCase):
def test_profile_gates_match_shared_branch_workflows(self):
spec = importlib.util.spec_from_file_location('pipeline',
Path(__file__).resolve().parents[1] / 'src/scripts/generate_pipeline.py')
pipeline = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pipeline)
for profile in ('all', 'cli', 'android', 'app-starter', 'mcp-policy'):
desired = enforcement.gates(profile)
for branch in ('main', 'develop', 'feature/change'):
config = {'orb_version': '0.8', 'publish': {'snapshot': False, 'release': False}}
output = pipeline.PROFILE_TEMPLATES[profile](config, branch, '')
self.assertEqual([desired[1]['context']], list(output['workflows']))
successful = [{'id': i, 'name': gate['context'], 'app': {'id': 18001},
'conclusion': 'success'} for i, gate in enumerate(desired)]
before = {'required_status_checks': {'checks': [
*desired, {'context': 'scanner', 'app_id': 15368}]}}
checks = enforcement.required_checks(before, successful, desired)['checks']
self.assertTrue(enforcement.same_checks(before['required_status_checks']['checks'], checks))
self.assertNotIn({'context': 'verify', 'app_id': 18001}, checks)
for bad in (successful[:1], [*successful, dict(successful[1], id=99, conclusion='failure')],
[dict(run, app={'id': 999}) for run in successful]):
with self.subTest(profile=profile), self.assertRaises(ValueError):
enforcement.required_checks(before, bad, desired)
record, effective = self.ruleset_fixture()
record['rules'][0]['parameters']['required_status_checks'] = [
{'context': gate['context'], 'integration_id': gate['app_id']} for gate in desired]
enforcement.verified_rulesets('QRun-IO/example', effective, lambda path: record, desired)
with self.assertRaises(ValueError):
enforcement.verified_rulesets('QRun-IO/example', effective, lambda path: record)
def test_check_comparison_ignores_only_order(self):
checks = [*enforcement.DESIRED, {'context': 'scanner', 'app_id': 15368}]
self.assertTrue(enforcement.same_checks(checks, list(reversed(checks))))
self.assertFalse(enforcement.same_checks(checks, checks[:-1]))
self.assertFalse(enforcement.same_checks(checks, checks + checks[:1]))
self.assertFalse(enforcement.same_checks(checks, [*enforcement.DESIRED, {'context': 'scanner', 'app_id': 999}]))
def test_preserves_security_gate_and_binds_orb_checks(self):
before = {'required_status_checks': {'strict': False, 'contexts': ['security', 'setup'],
'checks': [{'context': 'security', 'app_id': 15368}, {'context': 'setup', 'app_id': -1}]}}
original = copy.deepcopy(before)
result = enforcement.required_checks(before, runs())
self.assertEqual(original, before)
self.assertEqual(result, {'strict': True, 'checks': [{'context': 'security', 'app_id': 15368}, *enforcement.DESIRED]})
def test_wrong_app_failed_latest_and_missing_checks_reject(self):
cases = [[], [runs()[0]], [dict(run, app={'id': 999}) for run in runs()],
runs() + [dict(runs()[1], id=3, conclusion='failure')]]
for candidate in cases:
with self.subTest(candidate=candidate), self.assertRaises(ValueError):
enforcement.required_checks(None, candidate)
with self.assertRaises(ValueError):
enforcement.required_checks({'required_status_checks': {'checks': [{'context': 'verify', 'app_id': 999}]}}, runs())
def test_existing_unrestricted_contexts_are_retained(self):
result = enforcement.required_checks({'required_status_checks': {'contexts': ['legacy-build']}}, runs())
self.assertIn({'context': 'legacy-build', 'app_id': -1}, result['checks'])
def fixture(self, before):
state = {'before': copy.deepcopy(before), 'head': 'a' * 40, 'writes': []}
def request(path, method='GET', payload=None):
if method != 'GET':
state['writes'].append((method, path, payload))
if method == 'PUT':
state['before'] = {**payload, 'enforce_admins': {'enabled': True}}
elif method == 'PATCH':
state['before']['required_status_checks'] = copy.deepcopy(payload)
elif method == 'POST':
state['before']['enforce_admins'] = {'enabled': True}
return None
if '/rules/' in path:
return []
if path.endswith('/protection'):
return copy.deepcopy(state['before'])
return {'commit': {'sha': state['head']}}
plan = {'repository': 'QRun-IO/example', 'branch': 'develop', 'head': 'a' * 40,
'before': copy.deepcopy(before), 'required_status_checks': enforcement.required_checks(before, runs()), 'changed': True}
return plan, request, state
def test_narrow_updates_preserve_reviews_signatures_and_restrictions(self):
before = {'required_status_checks': {'strict': False, 'checks': []}, 'enforce_admins': {'enabled': False},
'required_signatures': {'enabled': True}, 'required_linear_history': {'enabled': True},
'required_pull_request_reviews': {'required_approving_review_count': 2},
'restrictions': {'users': [{'login': 'owner'}]}}
plan, request, state = self.fixture(before)
enforcement.enforce(plan, request)
self.assertEqual(['PATCH', 'POST'], [write[0] for write in state['writes']])
for key in ('required_signatures', 'required_linear_history', 'required_pull_request_reviews', 'restrictions'):
self.assertEqual(before[key], state['before'][key])
def test_new_protection_and_idempotent_noop(self):
plan, request, state = self.fixture(None)
enforcement.enforce(plan, request)
self.assertEqual('PUT', state['writes'][0][0])
self.assertIsNone(state['before']['required_pull_request_reviews'])
plan['before'] = copy.deepcopy(state['before'])
plan['changed'] = False
state['writes'] = []
enforcement.enforce(plan, request)
self.assertEqual([], state['writes'])
def test_github_may_reorder_required_checks_on_readback(self):
before = {'required_status_checks': {'strict': True, 'checks': [
*enforcement.DESIRED, {'context': 'scanner', 'app_id': 15368}]},
'enforce_admins': {'enabled': False}, 'required_signatures': {'enabled': True}}
plan, request, state = self.fixture(before)
def reordered(path, method='GET', payload=None):
value = request(path, method, payload)
if method == 'PATCH':
state['before']['required_status_checks']['checks'].reverse()
return value
enforcement.enforce(plan, reordered)
self.assertTrue(state['before']['enforce_admins']['enabled'])
self.assertEqual(before['required_signatures'], state['before']['required_signatures'])
def test_head_or_protection_drift_never_mutates(self):
for field, value in [('head', 'b' * 40), ('before', {'unexpected': True})]:
plan, request, state = self.fixture(None)
state[field] = value
with self.assertRaises(ValueError):
enforcement.enforce(plan, request)
self.assertEqual([], state['writes'])
def ruleset_fixture(self):
parameters = {'strict_required_status_checks_policy': False,
'required_status_checks': [{'context': c['context'], 'integration_id': c['app_id']}
for c in enforcement.DESIRED] + [{'context': 'scanner', 'integration_id': 15368}]}
record = {'id': 123, 'enforcement': 'active', 'target': 'branch', 'source_type': 'Repository',
'source': 'QRun-IO/example', 'bypass_actors': [],
'rules': [{'type': 'required_status_checks', 'parameters': parameters}]}
effective = [{'type': 'required_status_checks', 'ruleset_source_type': 'Repository',
'ruleset_source': 'QRun-IO/example', 'ruleset_id': 123, 'parameters': copy.deepcopy(parameters)}]
return record, effective
def test_ruleset_verification_preserves_freshness_scanner_and_never_writes(self):
record, effective = self.ruleset_fixture()
original = copy.deepcopy(record)
def request(path, method='GET', payload=None):
self.assertEqual('GET', method)
if path.endswith('/rulesets/123'):
return copy.deepcopy(record)
if '/rules/branches/' in path:
return copy.deepcopy(effective)
if path.endswith('/protection'):
return None
if '/check-runs?' in path:
return {'check_runs': runs()}
if '/contents/' in path:
data = ({'profile': 'qbit', 'orb_version': '0.8', 'default_branch': 'develop'}
if '/.qqq-ci.yml?' in path else enforcement.standard.canonical_caller('qbit', '0.8'))
return {'encoding': 'base64', 'type': 'file', 'content': base64.b64encode(yaml.safe_dump(data).encode()).decode()}
if '/branches/' in path:
return {'commit': {'sha': 'a' * 40}}
return {'archived': False}
plan = enforcement.inspect('QRun-IO/example', 'develop', '0.8', request)
self.assertFalse(plan['changed'])
self.assertFalse(plan['required_status_checks']['strict'])
self.assertEqual('rulesets', plan['protection_mode'])
enforcement.enforce(plan, request)
self.assertEqual(original, record)
record['bypass_actors'] = [{'actor_type': 'RepositoryRole', 'actor_id': 5}]
with self.assertRaises(ValueError):
enforcement.enforce(plan, request)
def test_inactive_bypass_unbound_and_missing_ruleset_gates_reject(self):
record, effective = self.ruleset_fixture()
cases = [dict(record, enforcement='evaluate'), dict(record, bypass_actors=[{'actor_id': 1}]),
dict(record, rules=[])]
unbound = copy.deepcopy(record)
unbound['rules'][0]['parameters']['required_status_checks'][1]['integration_id'] = None
cases.append(unbound)
for candidate in cases:
with self.subTest(candidate=candidate), self.assertRaises(ValueError):
enforcement.verified_rulesets('QRun-IO/example', effective, lambda path: candidate)
def test_unsupported_ruleset_sources_are_not_inferred_as_protected(self):
record, effective = self.ruleset_fixture()
effective[0]['ruleset_source_type'] = 'Organization'
with self.assertRaises(ValueError):
enforcement.verified_rulesets('QRun-IO/example', effective, lambda path: record)
def test_empty_push_allowlist_gains_ruleset_without_changing_access(self):
self.assert_ruleset_preserves_classic({
'restrictions': {'users': [], 'teams': [], 'apps': []},
'enforce_admins': {'enabled': False}, 'required_signatures': {'enabled': True}})
def test_existing_protection_without_status_section_gains_ruleset(self):
for admin in (False, True):
with self.subTest(enforce_admins=admin):
self.assert_ruleset_preserves_classic({
'enforce_admins': {'enabled': admin},
'required_signatures': {'enabled': True},
'required_linear_history': {'enabled': True},
'required_pull_request_reviews': {'required_approving_review_count': 2},
'required_conversation_resolution': {'enabled': True}})
def assert_ruleset_preserves_classic(self, classic):
state = {'ruleset': None, 'writes': []}
def request(path, method='GET', payload=None):
if method != 'GET':
self.assertEqual(('POST', 'repos/QRun-IO/example/rulesets'), (method, path))
state['writes'].append(copy.deepcopy(payload))
state['ruleset'] = {**copy.deepcopy(payload), 'id': 123,
'source_type': 'Repository', 'source': 'QRun-IO/example'}
return state['ruleset']
if '/rulesets?' in path:
return []
if path.endswith('/rulesets/123'):
return copy.deepcopy(state['ruleset'])
if '/rules/branches/' in path:
if state['ruleset'] is None:
return []
return [{**state['ruleset']['rules'][0], 'ruleset_source_type': 'Repository',
'ruleset_source': 'QRun-IO/example', 'ruleset_id': 123}]
if path.endswith('/protection'):
return copy.deepcopy(classic)
if '/check-runs?' in path:
return {'check_runs': runs()}
if '/contents/' in path:
data = ({'profile': 'core', 'orb_version': '0.8', 'default_branch': 'develop'}
if '/.qqq-ci.yml?' in path else enforcement.standard.canonical_caller('core', '0.8'))
return {'encoding': 'base64', 'type': 'file', 'content': base64.b64encode(yaml.safe_dump(data).encode()).decode()}
if '/branches/' in path:
return {'commit': {'sha': 'a' * 40}}
return {'archived': False}
plan = enforcement.inspect('QRun-IO/example', 'main', '0.8', request)
self.assertEqual('create-ruleset', plan['protection_mode'])
enforcement.enforce(plan, request)
self.assertEqual(1, len(state['writes']))
self.assertEqual([], state['writes'][0]['bypass_actors'])
self.assertEqual({'include': ['refs/heads/main'], 'exclude': []}, state['writes'][0]['conditions']['ref_name'])
self.assertEqual(classic, plan['before'])
repeat = enforcement.inspect('QRun-IO/example', 'main', '0.8', request)
self.assertFalse(repeat['changed'])
enforcement.enforce(repeat, request)
self.assertEqual(1, len(state['writes']))
def test_existing_named_ruleset_is_not_overwritten_or_duplicated(self):
before = {'restrictions': {'users': [], 'teams': [], 'apps': []}, 'enforce_admins': {'enabled': False}}
plan, base_request, state = self.fixture(before)
plan['protection_mode'] = 'create-ruleset'
def request(path, method='GET', payload=None):
if '/rulesets?' in path:
return [{'name': 'QQQ automated verification: develop'}]
return base_request(path, method, payload)
with self.assertRaisesRegex(ValueError, 'already exists'):
enforcement.enforce(plan, request)
self.assertEqual([], state['writes'])
if __name__ == '__main__':
unittest.main()
+110
View File
@@ -0,0 +1,110 @@
"""Batch enrollment preserves policy and rejects unsafe or unknown declarations."""
from pathlib import Path
import sys
import tempfile
import unittest
from unittest import mock
import yaml
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
import enroll_consumers as enrollment
class EnrollmentTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
def legacy(self, name):
root = self.root / name
(root / '.circleci').mkdir(parents=True)
config = {'version': 2.1, 'orbs': {'qqq-orb': 'kingsrook/qqq-orb@0.5.0'},
'workflows': {'verify': {'jobs': [{'qqq-orb/mvn_test_only': {}}]}}}
(root / '.circleci/config.yml').write_text(yaml.safe_dump(config), encoding='utf-8')
return {'checkout': str(root), 'default_branch': 'main'}
def canonical(self, profile):
target = self.legacy(profile)
root = Path(target['checkout'])
data = {'profile': profile, 'orb_version': '0.7.4', 'default_branch': 'main'}
if profile == 'node-artifact':
data.update(context='registry', npm_scopes=['@example'], node_version='20.19',
artifact_path='dist/bundle.js', build_branches=['main'])
if profile == 'homebrew-tap':
data.update(tap='qrun-io/qctl', formula='qctl')
(root / '.qqq-ci.yml').write_text(yaml.safe_dump(data), encoding='utf-8')
(root / '.circleci/config.yml').write_text(yaml.safe_dump(
enrollment.rollout.standard.canonical_caller(profile, '0.7.4')), encoding='utf-8')
return target
def test_mixed_fleet_preview_write_and_idempotence(self):
legacy = self.legacy('legacy')
targets = [legacy] + [self.canonical(p) for p in enrollment.rollout.standard.PROFILE_PARAMETERS]
preview = enrollment.enroll(targets, '0.8')
self.assertTrue(all(item['changed'] for item in preview))
self.assertFalse((Path(legacy['checkout']) / '.qqq-ci.yml').exists())
result = enrollment.enroll(targets, '0.8', write=True)
self.assertEqual(1, sum(item['enrollment'] for item in result))
data = yaml.safe_load((Path(legacy['checkout']) / '.qqq-ci.yml').read_text())
self.assertFalse(any(data['publish'].values()))
self.assertEqual('all', data['test_branch_policy'])
self.assertTrue(all(not item['changed'] for item in enrollment.enroll(targets, '0.8', write=True)))
def test_unknown_orchestration_rejects_entire_batch(self):
good, bad = self.legacy('good'), self.legacy('bad')
path = Path(bad['checkout']) / '.circleci/config.yml'
path.write_text(path.read_text() + '\njobs: {custom: {steps: [checkout]}}\n')
original = (Path(good['checkout']) / '.circleci/config.yml').read_bytes()
with self.assertRaises(ValueError):
enrollment.enroll([good, bad], '0.8', write=True)
self.assertEqual(original, (Path(good['checkout']) / '.circleci/config.yml').read_bytes())
self.assertFalse((Path(good['checkout']) / '.qqq-ci.yml').exists())
def test_duplicate_targets_and_wrong_default_reject_before_write(self):
target = self.canonical('core')
for targets in ([target, target], [{**target, 'default_branch': 'develop'}]):
with self.assertRaises(ValueError):
enrollment.enroll(targets, '0.8', write=True)
self.assertEqual('0.7.4', yaml.safe_load((Path(target['checkout']) / '.qqq-ci.yml').read_text())['orb_version'])
def test_invalid_manifest_and_unstable_versions_rejected(self):
target = self.canonical('qbit')
path = Path(target['checkout']) / '.qqq-ci.yml'
path.write_text(path.read_text() + '\nunknown_policy: true\n')
for version in ('0.8', 'dev:snapshot', 'latest', 0.8):
with self.assertRaises(ValueError):
enrollment.enroll([target], version, write=True)
def test_drift_after_preflight_is_not_overwritten(self):
target = self.legacy('drift')
path = Path(target['checkout']) / '.circleci/config.yml'
original_plan = enrollment.plan
def changed_plan(*args):
result = original_plan(*args)
path.write_bytes(b'concurrent edit\n')
return result
with mock.patch.object(enrollment, 'plan', side_effect=changed_plan):
with self.assertRaises(ValueError):
enrollment.enroll([target], '0.8', write=True)
self.assertEqual(b'concurrent edit\n', path.read_bytes())
self.assertFalse((Path(target['checkout']) / '.qqq-ci.yml').exists())
def test_manifest_symlink_is_rejected(self):
target = self.legacy('redirect')
outside = self.root / 'outside.yml'
outside.write_text('untouched\n')
try:
(Path(target['checkout']) / '.qqq-ci.yml').symlink_to(outside)
except OSError as error:
self.skipTest('Symlink creation unavailable: ' + str(error))
with self.assertRaises(ValueError):
enrollment.enroll([target], '0.8', write=True)
self.assertEqual('untouched\n', outside.read_text())
if __name__ == '__main__':
unittest.main()
+103
View File
@@ -0,0 +1,103 @@
"""Automatic completion requires qualified source and preserves normal merge policy."""
import json
from pathlib import Path
import sys
import unittest
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
import finish_enrollment as finish
class FinishTests(unittest.TestCase):
def setUp(self):
self.plan = {'repository': 'QRun-IO/example', 'branch': 'main', 'head': 'a' * 40,
'profile': 'qbit', 'version': '0.8'}
self.result = {'state': 'existing-pr', 'head': 'b' * 40, 'url': 'https://github.com/QRun-IO/example/pull/1'}
self.pr = {'number': 1, 'state': 'OPEN', 'headRefOid': 'b' * 40,
'baseRefOid': 'a' * 40, 'baseRefName': 'main', 'mergeCommit': None}
def checks(self):
return [{'id': i, 'name': name, 'app': {'id': 18001}, 'status': 'completed', 'conclusion': 'success'}
for i, name in enumerate(('setup', 'verify'))]
def test_all_checks_and_statuses_must_pass_and_gates_must_use_circle_app(self):
checks = self.checks()
checks[1]['app']['id'] = 123
checks.append({'id': 3, 'name': 'scanner', 'app': {'id': 15368}, 'status': 'completed', 'conclusion': 'failure'})
with mock.patch.object(finish.remote, 'api', side_effect=[{'check_runs': checks},
{'statuses': [{'context': 'legacy-test', 'state': 'pending'}]}]):
self.assertEqual(['legacy-test', 'scanner', 'verify'], finish.qualification('QRun-IO/example', 'b' * 40))
def test_profile_qualification_requires_its_actual_workflow(self):
for profile in ('all', 'cli', 'android', 'app-starter', 'mcp-policy'):
checks = self.checks()
checks[1]['name'] = finish.enforcement.PROFILE_GATES[profile]
with mock.patch.object(finish.remote, 'api', side_effect=[
{'check_runs': checks}, {'statuses': []}]):
self.assertEqual([], finish.qualification('QRun-IO/example', 'b' * 40, profile))
with mock.patch.object(finish.remote, 'api', side_effect=[
{'check_runs': self.checks()}, {'statuses': []}]):
self.assertEqual([checks[1]['name']], finish.qualification('QRun-IO/example', 'b' * 40, profile))
def test_failed_or_missing_checks_never_merge(self):
with mock.patch.object(finish.remote, 'verify_submission'), mock.patch.object(finish.remote, 'command', return_value=json.dumps(self.pr)) as command, mock.patch.object(finish.remote, 'api', return_value={'commit': {'sha': self.plan['head']}}), mock.patch.object(finish, 'qualification', return_value=['verify']):
self.assertEqual('waiting-checks', finish.merge_ready(self.plan, self.result)['state'])
self.assertEqual(1, command.call_count)
self.assertEqual(['gh', 'pr', 'view'], command.call_args.args[0][:3])
def test_stale_base_never_merges_even_when_checks_were_green(self):
self.pr['baseRefOid'] = 'c' * 40
with mock.patch.object(finish.remote, 'verify_submission'), mock.patch.object(finish.remote, 'command', return_value=json.dumps(self.pr)) as command:
self.assertEqual('stale-base', finish.merge_ready(self.plan, self.result)['state'])
self.assertEqual(1, command.call_count)
def test_success_uses_exact_head_normal_merge_and_verifies_result(self):
calls = []
def command(args):
calls.append(args)
if args[2] == 'merge':
return ''
if len(calls) == 1:
return json.dumps(self.pr)
return json.dumps({'state': 'MERGED', 'mergeCommit': {'oid': 'd' * 40}})
def api(path):
if '/branches/' in path:
return {'commit': {'sha': self.plan['head']}}
return {'commit': {'tree': {'sha': 'e' * 40}, 'verification': {'verified': True}}}
with mock.patch.object(finish.remote, 'verify_submission'), mock.patch.object(finish.remote, 'command', side_effect=command), mock.patch.object(finish.remote, 'api', side_effect=api), mock.patch.object(finish, 'qualification', return_value=[]):
result = finish.merge_ready(self.plan, self.result)
self.assertEqual('merged', result['state'])
self.assertEqual(['gh', 'pr', 'merge', '1', '--repo', 'QRun-IO/example', '--squash', '--match-head-commit', 'b' * 40], calls[1])
def test_enforcement_waits_for_current_head_and_uses_shared_preserving_writer(self):
with mock.patch.object(finish.enforcement, 'inspect', side_effect=ValueError('Current branch has no successful verify')), mock.patch.object(finish.enforcement, 'enforce') as enforce:
self.assertEqual('waiting-enforcement', finish.enforce_current(self.plan)['state'])
enforce.assert_not_called()
current = {'head': 'd' * 40, 'changed': True}
with mock.patch.object(finish.enforcement, 'inspect', return_value=current), mock.patch.object(finish.enforcement, 'enforce') as enforce:
self.assertEqual('enforced', finish.enforce_current(self.plan)['state'])
enforce.assert_called_once_with(current)
def test_unknown_gate_profile_never_merges_or_enforces(self):
self.plan['profile'] = 'unknown-profile'
with mock.patch.object(finish.remote, 'command') as command, mock.patch.object(finish.enforcement, 'inspect') as inspect:
self.assertEqual('unsupported-gates', finish.merge_ready(self.plan, self.result)['state'])
self.assertEqual('unsupported-gates', finish.enforce_current(self.plan)['state'])
command.assert_not_called()
inspect.assert_not_called()
def test_merged_tree_mismatch_is_not_reported_as_success(self):
self.pr.update(state='MERGED', mergeCommit={'oid': 'd' * 40})
with mock.patch.object(finish.remote, 'verify_submission'), mock.patch.object(finish.remote, 'command', return_value=json.dumps(self.pr)), mock.patch.object(finish.remote, 'api', side_effect=[
{'commit': {'tree': {'sha': 'e' * 40}}},
{'commit': {'tree': {'sha': 'f' * 40}, 'verification': {'verified': True}}}]):
with self.assertRaises(ValueError):
finish.merge_ready(self.plan, self.result)
if __name__ == '__main__':
unittest.main()
File diff suppressed because it is too large. Load diff
+28
View File
@@ -0,0 +1,28 @@
"""Capability probes must drain help output while still rejecting missing options."""
from pathlib import Path
import shlex
import subprocess
import unittest
class InstallerTests(unittest.TestCase):
def probe(self, flags):
installer = Path(__file__).resolve().parents[1] / 'tools/install_reconcile_gh.sh'
checks = '\n'.join(line for line in installer.read_text().splitlines()
if line.startswith(('gh api --help', 'gh pr merge --help')))
self.assertEqual(2, len(checks.splitlines()))
producer = ("import signal,sys; signal.signal(signal.SIGPIPE,signal.SIG_DFL); "
f"print({flags!r},flush=True); sys.stdout.write('x'*1048576)")
script = 'set -euo pipefail\ngh() { python3 -c ' + shlex.quote(producer) + '; }\n' + checks
return subprocess.run(['bash', '-c', script], capture_output=True, timeout=10).returncode
def test_large_help_output_does_not_kill_producer(self):
self.assertEqual(0, self.probe('--slurp --match-head-commit'))
def test_missing_required_option_fails(self):
self.assertNotEqual(0, self.probe('--slurp'))
self.assertNotEqual(0, self.probe('--match-head-commit'))
if __name__ == '__main__':
unittest.main()
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Run the generated link-check shell with controlled server/readiness commands."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
class MarketingLinkCheckTests(unittest.TestCase):
def run_check(self, ready, link_status):
template = json.loads((ROOT / 'src/scripts/templates/marketing.json').read_text())
build = template['workflows']['pr-checks']['jobs'][0]['munitor/node_build_and_test']
command = json.loads(build['test_commands'])[5]
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
scripts = {
'npm': '#!/bin/bash\nif [ "$2" = start ]; then echo $$ > "$TEST_ROOT/server.pid"; exec /bin/sleep 30; fi\necho checked > "$TEST_ROOT/checked"\nexit "$LINK_STATUS"\n',
'curl': '#!/bin/bash\nexit "$READY_STATUS"\n',
'sleep': '#!/bin/bash\n/bin/sleep 0.01\n',
}
for name, text in scripts.items():
file = root / name
file.write_text(text)
file.chmod(0o755)
env = {**os.environ, 'PATH': str(root) + ':' + os.environ['PATH'],
'TEST_ROOT': str(root), 'READY_STATUS': str(ready), 'LINK_STATUS': str(link_status)}
result = subprocess.run(['bash', '-c', command], env=env, capture_output=True, timeout=10)
self.assertEqual((root / 'checked').exists(), ready == 0)
pid_file = root / 'server.pid'
if pid_file.exists():
with self.assertRaises(ProcessLookupError):
os.kill(int(pid_file.read_text()), 0)
return result
def test_worker_input_is_generated_before_tests(self):
import yaml
template = json.loads((ROOT / 'src/scripts/templates/marketing.json').read_text())
for workflow in template['workflows'].values():
build = workflow['jobs'][0]['munitor/node_build_and_test']
command = json.loads(build['test_commands'])[0]
with tempfile.TemporaryDirectory() as directory:
subprocess.run(['bash', '-c', command], cwd=directory, check=True)
actual = yaml.safe_load((Path(directory) / '.munitor.yml').read_text())
self.assertEqual(actual, {'pipeline': 'node-webapp', 'node_version': 22,
'docker': {'use_repo_dockerfile': True}})
def test_ready_server_runs_links_and_is_cleaned_up(self):
self.assertEqual(self.run_check(0, 0).returncode, 0)
def test_broken_links_fail_and_server_is_cleaned_up(self):
self.assertEqual(self.run_check(0, 7).returncode, 7)
def test_unready_server_fails_without_running_links(self):
result = self.run_check(1, 0)
self.assertEqual(result.returncode, 1)
self.assertIn(b'did not become ready', result.stderr)
if __name__ == '__main__':
unittest.main()
+3 -1
View File
@@ -43,7 +43,7 @@ class MavenCiContract(unittest.TestCase):
self.assertIs(job["parameters"]["notify_rc_published"]["default"], False)
self.assertIs(read("src/commands/git_operations.yml")["parameters"]["require_pushed_version"]["default"], False)
steps = job["steps"]
deploy = steps.index("mvn_jar_deploy")
deploy = next(i for i, s in enumerate(steps) if isinstance(s, dict) and "mvn_jar_deploy" in s)
pushed = next(i for i, s in enumerate(steps) if "git_operations" in str(s))
dispatch = next(i for i, s in enumerate(steps) if "notify_rc_published.sh" in str(s))
self.assertLess(deploy, pushed)
@@ -57,6 +57,8 @@ class MavenCiContract(unittest.TestCase):
return next(i for i, s in enumerate(steps) if s == name or isinstance(s, dict) and name in s)
self.assertLess(position("mvn_manage_version"), position("mvn_verify"))
self.assertLess(position("mvn_verify"), position("mvn_jar_deploy"))
self.assertEqual(steps[position("mvn_jar_deploy")], {"mvn_jar_deploy": {"skip_verified_analysis": True}})
self.assertIs(read("src/commands/mvn_jar_deploy.yml")["parameters"]["skip_verified_analysis"]["default"], False)
self.assertTrue(any("check_middleware_api_versions" in str(s) for s in steps[position("mvn_verify") + 1:position("mvn_jar_deploy")]))
deploy = (ROOT / "src/scripts/mvn_jar_deploy.sh").read_text()
self.assertIn("-P release", deploy)
+16 -1
View File
@@ -56,13 +56,28 @@ org.codehaus.mojo:flatten-maven-plugin:1.7.3:flatten
deploy
EOF
diff -u "$test_dir/expected-args" "$test_dir/mvn-args"
# The verified publishing job skips only duplicate analysis. Every signing,
# flattening and publication argument must remain identical to the default.
for mode in true 1 false 0; do
PATH="$test_dir/bin:$PATH" TEST_MVN_ARGS="$test_dir/verified-args" \
GPG_KEYNAME=test-key GPG_PASSPHRASE=test-passphrase QQQ_SKIP_VERIFIED_ANALYSIS="$mode" \
bash "$test_dir/deploy.sh" > "$test_dir/verified-output" 2>&1
if [[ "$mode" == true || "$mode" == 1 ]]; then
grep -Fxq -- '-Dspotbugs.skip=true' "$test_dir/verified-args"
grep -Fxq -- '-Dpmd.skip=true' "$test_dir/verified-args"
grep -Fxv -e '-Dspotbugs.skip=true' -e '-Dpmd.skip=true' "$test_dir/verified-args" > "$test_dir/verified-common-args"
diff -u "$test_dir/expected-args" "$test_dir/verified-common-args"
else
diff -u "$test_dir/expected-args" "$test_dir/verified-args"
fi
done
# A Central validation failure or publication timeout must fail this wrapper.
cat > "$test_dir/bin/mvn" <<'EOF'
#!/bin/bash
exit 42
EOF
set +e
PATH="$test_dir/bin:$PATH" GPG_KEYNAME=test-key GPG_PASSPHRASE=test-passphrase \
PATH="$test_dir/bin:$PATH" GPG_KEYNAME=test-key GPG_PASSPHRASE=test-passphrase QQQ_SKIP_VERIFIED_ANALYSIS=true \
bash "$test_dir/deploy.sh" > "$test_dir/failure-output" 2>&1
status=$?
set -e
+112
View File
@@ -0,0 +1,112 @@
"""Native GitOps discovery must prove shared ownership without adding Circle jobs."""
import base64
import copy
from pathlib import Path
import sys
import unittest
from unittest import mock
import yaml
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools'))
import native_gitops_gates as gitops
import reconcile_enrollment as remote
import enforce_orb_checks as enforcement
import finish_enrollment as finish
class GitOpsTests(unittest.TestCase):
def setUp(self):
self.pin, self.head = 'a' * 40, 'b' * 40
self.repo = 'QRun-IO/voyage-cd'
self.caller = gitops.bridge.canonical('gitops', self.pin)
self.signed, self.worker_drift, self.truncated = True, False, False
self.paths = ['.github/workflows/validate.yml', 'base/kustomization.yaml']
self.runs = [{'id': 1, 'name': 'gitops / validate', 'app': {'id': 15368},
'status': 'completed', 'conclusion': 'success'}]
self.before = {'required_status_checks': {'strict': True, 'checks': gitops.gates()},
'enforce_admins': {'enabled': True}}
def request(self, path, method='GET', payload=None):
self.assertEqual(method, 'GET')
if '/contents/' in path:
self.assertNotIn('.circleci/', path)
if '/QRun-IO/qqq-orb/' in path:
raw = (ROOT / '.github/workflows/gitops.yml').read_text() + ('# drift' if self.worker_drift else '')
else:
raw = yaml.safe_dump(self.caller, sort_keys=False)
return {'type': 'file', 'encoding': 'base64', 'content': base64.b64encode(raw.encode()).decode()}
if '/git/trees/' in path:
return {'truncated': self.truncated, 'tree': [{'path': p} for p in self.paths]}
if path.endswith('/commits/' + self.pin):
return {'commit': {'verification': {'verified': self.signed}}}
if '/check-runs?' in path:
return {'check_runs': copy.deepcopy(self.runs)}
if '/status?' in path:
return {'statuses': []}
if path.endswith('/protection'):
return copy.deepcopy(self.before)
if '/rules/branches/' in path:
return []
if '/branches/' in path:
return {'commit': {'sha': self.head}}
return {'archived': False, 'default_branch': 'main'}
def test_discovery_returns_unchanged_native_plan_without_circle_reads_or_writes(self):
for repo in sorted(gitops.REPOSITORIES):
with mock.patch.object(remote, 'api', side_effect=self.request):
plan = remote.inspect({'repository': repo, 'branch': 'main'}, '0.8')
self.assertEqual(plan['profile'], 'native-gitops')
self.assertFalse(plan['changed'])
self.assertEqual(plan['worker_pin'], self.pin)
self.assertEqual(remote.apply(plan), {'state': 'unchanged'})
self.assertEqual(finish.merge_ready(plan, {'state': 'unchanged'}), {'state': 'unchanged'})
def test_enforcement_retains_bound_native_gate(self):
plan = enforcement.inspect(self.repo, 'main', '0.8', self.request)
self.assertFalse(plan['changed'])
self.assertEqual(plan['gates'], gitops.gates())
enforcement.enforce(plan, self.request)
def test_wrong_app_and_failed_gate_reject(self):
for field, value in [('app', {'id': 18001}), ('conclusion', 'failure')]:
original = copy.deepcopy(self.runs)
self.runs[0][field] = value
with self.assertRaises(ValueError):
enforcement.inspect(self.repo, 'main', '0.8', self.request)
self.runs = original
def test_noncanonical_or_unsigned_or_changed_worker_rejects(self):
self.caller['jobs']['gitops']['uses'] = 'other/repo/workflow.yml@' + self.pin
with self.assertRaisesRegex(ValueError, 'canonical'):
gitops.validate(self.repo, self.head, 'main', self.request, yaml.safe_load)
self.caller = gitops.bridge.canonical('gitops', self.pin)
self.signed = False
with self.assertRaisesRegex(ValueError, 'not verified'):
gitops.validate(self.repo, self.head, 'main', self.request, yaml.safe_load)
self.signed, self.worker_drift = True, True
with self.assertRaisesRegex(ValueError, 'supported contract'):
gitops.validate(self.repo, self.head, 'main', self.request, yaml.safe_load)
def test_additional_orchestration_and_incomplete_inventory_reject(self):
for path in ['.circleci/config.yml', '.github/workflows/custom.yaml']:
self.paths.append(path)
with self.assertRaisesRegex(ValueError, 'additional orchestration'):
gitops.validate(self.repo, self.head, 'main', self.request, yaml.safe_load)
self.paths.pop()
self.truncated = True
with self.assertRaisesRegex(ValueError, 'complete source tree'):
gitops.validate(self.repo, self.head, 'main', self.request, yaml.safe_load)
def test_unknown_repository_and_develop_are_not_exempted(self):
for repo, branch in [('QRun-IO/unknown', 'main'), (self.repo, 'develop')]:
with self.assertRaises(ValueError):
gitops.validate(repo, self.head, branch, self.request, yaml.safe_load)
def test_native_pr_qualification(self):
with mock.patch.object(finish.remote, 'api', side_effect=self.request):
self.assertEqual(finish.qualification(self.repo, self.head, 'native-gitops'), [])
self.runs = []
self.assertEqual(finish.qualification(self.repo, self.head, 'native-gitops'), ['gitops / validate'])
if __name__ == '__main__':
unittest.main()
+108
View File
@@ -0,0 +1,108 @@
"""Recognize native ownership without duplicate CI or weaker PR protections."""
import base64
import copy
from pathlib import Path
import sys
import unittest
from unittest import mock
import yaml
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools'))
import enforce_orb_checks as enforcement
import finish_enrollment as finish
class NativeTests(unittest.TestCase):
def setUp(self):
self.pin = 'a' * 40
self.head = 'b' * 40
self.caller = enforcement.native.bridge.canonical_next(self.pin)
self.signed = True
self.worker_drift = False
self.runs = [{'id': i, 'name': gate['context'], 'app': {'id': 15368},
'status': 'completed', 'conclusion': 'success'}
for i, gate in enumerate(enforcement.native.gates())]
self.record = {'id': 1, 'enforcement': 'active', 'target': 'branch',
'source_type': 'Repository', 'source': 'QRun-IO/example', 'bypass_actors': [],
'rules': [{'type': 'required_status_checks', 'parameters': {
'strict_required_status_checks_policy': False,
'required_status_checks': [{'context': g['context'], 'integration_id': g['app_id']}
for g in enforcement.gates('frontend-next')]}}]}
def request(self, path, method='GET', payload=None):
self.assertEqual('GET', method, 'Recognition must not mutate correct protections')
if '/contents/' in path:
if '.github/workflows/ci.yml?' in path:
raw = yaml.safe_dump(self.caller)
elif 'repos/QRun-IO/qqq-orb/' in path:
name = path.split('/contents/')[1].split('?')[0]
raw = (ROOT / name).read_text(encoding='utf-8') + ('# drift' if self.worker_drift else '')
else:
data = ({'profile': 'frontend-next', 'orb_version': '0.8', 'default_branch': 'main'}
if '/.qqq-ci.yml?' in path else enforcement.standard.canonical_caller('frontend-next', '0.8'))
raw = yaml.safe_dump(data)
return {'type': 'file', 'encoding': 'base64', 'content': base64.b64encode(raw.encode()).decode()}
if path.endswith('/commits/' + self.pin):
return {'commit': {'verification': {'verified': self.signed}}}
if '/check-runs?' in path:
return {'check_runs': copy.deepcopy(self.runs)}
if '/status?' in path:
return {'statuses': []}
if '/rulesets/1' in path:
return copy.deepcopy(self.record)
if '/rules/branches/' in path:
return [{'type': 'required_status_checks', 'ruleset_source_type': 'Repository',
'ruleset_source': 'QRun-IO/example', 'ruleset_id': 1}]
if path.endswith('/protection'):
return None
if '/branches/' in path:
return {'commit': {'sha': self.head}}
return {'archived': False}
def test_main_recognition_retains_all_eight_pr_gates_without_image_run(self):
plan = enforcement.inspect('QRun-IO/example', 'main', '0.8', self.request)
self.assertFalse(plan['changed'])
self.assertEqual('rulesets', plan['protection_mode'])
self.assertEqual(enforcement.gates('frontend-next'), plan['required_status_checks']['checks'])
self.assertEqual(8, len(plan['gates']))
enforcement.enforce(plan, self.request)
def test_caller_drift_unsigned_and_changed_workers_fail_closed(self):
self.caller['jobs']['ci']['uses'] = 'untrusted/repo/ci.yml@' + self.pin
with self.assertRaisesRegex(ValueError, 'canonical'):
enforcement.inspect('QRun-IO/example', 'main', '0.8', self.request)
self.caller = enforcement.native.bridge.canonical_next(self.pin)
self.signed = False
with self.assertRaisesRegex(ValueError, 'not verified'):
enforcement.inspect('QRun-IO/example', 'main', '0.8', self.request)
self.signed = True
self.worker_drift = True
with self.assertRaisesRegex(ValueError, 'supported contract'):
enforcement.inspect('QRun-IO/example', 'main', '0.8', self.request)
def test_missing_main_gate_wrong_app_and_missing_pr_protection_reject(self):
self.runs[0]['app']['id'] = 18001
with self.assertRaises(ValueError):
enforcement.inspect('QRun-IO/example', 'main', '0.8', self.request)
self.runs[0]['app']['id'] = 15368
self.record['rules'][0]['parameters']['required_status_checks'].pop()
with self.assertRaisesRegex(ValueError, 'missing app-bound gate'):
enforcement.inspect('QRun-IO/example', 'main', '0.8', self.request)
def test_pr_qualification_requires_both_image_architectures(self):
with mock.patch.object(finish.remote, 'api', side_effect=self.request):
missing = finish.qualification('QRun-IO/example', self.head, 'frontend-next')
self.assertEqual(sorted(enforcement.native.PR_GATES[-2:]), missing)
for i, name in enumerate(enforcement.native.PR_GATES[-2:], 20):
self.runs.append({'id': i, 'name': name, 'app': {'id': 15368},
'status': 'completed', 'conclusion': 'success'})
self.assertEqual([], finish.qualification('QRun-IO/example', self.head, 'frontend-next'))
def test_develop_has_no_native_push_contract(self):
with self.assertRaisesRegex(ValueError, 'main only'):
enforcement.native.validate('QRun-IO/example', self.head, 'develop', self.request, enforcement.standard.load_yaml)
if __name__ == '__main__':
unittest.main()
+149
View File
@@ -0,0 +1,149 @@
"""Native recognition proves central ownership and app-bound verification gates."""
import base64
import copy
from pathlib import Path
import sys
import unittest
from unittest import mock
import yaml
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools'))
import native_specialist_gates as native
import reconcile_enrollment as remote
import enforce_orb_checks as enforcement
import finish_enrollment as finish
class NativeTests(unittest.TestCase):
def fixture(self, repo):
self.repo, self.pin, self.head = repo, 'a' * 40, 'b' * 40
self.profile, self.branches, kinds, _ = native.DEFINITIONS[repo]
self.callers = dict(native.caller(kind, self.pin) for kind in kinds)
self.paths = list(self.callers)
self.signed, self.drift, self.truncated = True, False, False
self.mode = '100644'
self.runs = [{'id': i, 'name': gate['context'], 'app': {'id': gate['app_id']},
'status': 'completed', 'conclusion': 'success'}
for i, gate in enumerate(native.gates(self.profile))]
self.before = {'required_status_checks': {'strict': True, 'checks': native.gates(self.profile)},
'enforce_admins': {'enabled': True}}
def request(self, path, method='GET', payload=None):
self.assertEqual('GET', method)
if '/contents/' in path:
self.assertNotIn('.circleci/', path)
file = path.split('/contents/')[1].split('?')[0]
if path.startswith('repos/QRun-IO/qqq-orb/'):
raw = (ROOT / file).read_text() + ('# changed' if self.drift else '')
else:
raw = yaml.safe_dump(self.callers[file], sort_keys=False)
return {'type': 'file', 'encoding': 'base64', 'content': base64.b64encode(raw.encode()).decode()}
if '/git/trees/' in path:
return {'truncated': self.truncated, 'tree': [{'path': p, 'type': 'blob', 'mode': self.mode} for p in self.paths]}
if path.endswith('/commits/' + self.pin):
return {'commit': {'verification': {'verified': self.signed}}}
if '/check-runs?' in path:
return {'check_runs': copy.deepcopy(self.runs)}
if '/status?' in path:
return {'statuses': []}
if path.endswith('/protection'):
return copy.deepcopy(self.before)
if '/rules/branches/' in path:
return []
if '/branches/' in path:
return {'commit': {'sha': self.head}}
return {'archived': False, 'default_branch': 'main'}
def test_all_approved_callers_discover_enforce_and_qualify_without_mutation(self):
for repo in native.DEFINITIONS:
self.fixture(repo)
for branch in self.branches:
with self.subTest(repo=repo, branch=branch), mock.patch.object(remote, 'api', side_effect=self.request):
plan = remote.inspect({'repository': repo, 'branch': branch}, '0.8')
self.assertEqual(self.profile, plan['profile'])
self.assertFalse(plan['changed'])
self.assertEqual(set(self.callers), set(plan['worker_pins']))
self.assertEqual({'state': 'unchanged'}, remote.apply(plan))
self.assertEqual({'state': 'unchanged'}, finish.merge_ready(plan, {'state': 'unchanged'}))
self.assertEqual([], finish.qualification(repo, self.head, self.profile))
protected = enforcement.inspect(repo, branch, '0.8', self.request)
self.assertFalse(protected['changed'])
enforcement.enforce(protected, self.request)
def test_failed_missing_wrong_app_and_newer_failed_gate_reject(self):
for repo in native.DEFINITIONS:
self.fixture(repo)
good = copy.deepcopy(self.runs)
for bad in [[], good[1:], [dict(x, app={'id': 18001}) for x in good],
good + [dict(good[0], id=99, conclusion='failure')]]:
self.runs = bad
with self.subTest(repo=repo), self.assertRaises(ValueError):
enforcement.inspect(repo, 'main', '0.8', self.request)
def test_custom_caller_unsigned_or_changed_worker_rejects(self):
for repo in native.DEFINITIONS:
for defect in ('caller', 'unsigned', 'worker', 'mutable'):
self.fixture(repo)
if defect == 'caller':
next(iter(self.callers.values()))['extra'] = True
elif defect == 'unsigned':
self.signed = False
elif defect == 'worker':
self.drift = True
else:
jobs = next(iter(self.callers.values()))['jobs']
job = next(iter(jobs.values()))
job['uses'] = job['uses'].replace(self.pin, 'main')
with self.subTest(repo=repo, defect=defect), self.assertRaises(ValueError):
native.validate(repo, self.head, 'main', self.request)
def test_complete_workflow_inventory_required(self):
self.fixture('QRun-IO/qqq-business-platform')
for path in ('.circleci/config.yml', '.github/workflows/custom.yml', '.github/workflows/extra.yaml'):
self.paths.append(path)
with self.assertRaisesRegex(ValueError, 'additional orchestration'):
native.validate(self.repo, self.head, 'main', self.request)
self.paths.pop()
self.truncated = True
with self.assertRaisesRegex(ValueError, 'complete source tree'):
native.validate(self.repo, self.head, 'main', self.request)
def test_symlinked_or_missing_caller_rejects(self):
self.fixture('QRun-IO/qctl')
self.mode = '120000'
with self.assertRaisesRegex(ValueError, 'regular source file'):
native.validate(self.repo, self.head, 'main', self.request)
self.paths = []
with self.assertRaisesRegex(ValueError, 'regular source file'):
native.validate(self.repo, self.head, 'main', self.request)
def test_unknown_repo_and_unapproved_branch_reject(self):
self.fixture('QRun-IO/qqq-mcp-rag')
for repo, branch in [('QRun-IO/unknown', 'main'), (self.repo, 'develop'), ('QRun-IO/qctl', 'release/old')]:
with self.assertRaises(ValueError):
native.validate(repo, self.head, branch, self.request)
def test_qctl_pr_gate_excludes_push_only_native_binary_job(self):
worker = native.load_workflow((ROOT / '.github/workflows/qctl-native.yml').read_text())
self.assertNotIn('if', worker['jobs']['test'])
self.assertEqual("github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.full_native)",
worker['jobs']['build-native']['if'])
self.assertEqual([{'context': 'native / test', 'app_id': 15368}], native.gates('qctl'))
def test_github_yaml_events_and_duplicate_keys(self):
self.assertEqual({'on': {'push': None}, 'enabled': True},
native.load_workflow('on:\n push:\nenabled: true\n'))
for raw in ('on: {}\non: {}\n', 'jobs: {build: {}, build: {}}\n', '1: value\n'):
with self.subTest(raw=raw), self.assertRaises(ValueError):
native.load_workflow(raw)
def test_native_enforcement_preserves_other_required_checks(self):
self.fixture('QRun-IO/qctl')
self.before['required_status_checks']['checks'].append({'context': 'security', 'app_id': 15368})
plan = enforcement.inspect(self.repo, 'main', '0.8', self.request)
self.assertIn({'context': 'security', 'app_id': 15368}, plan['required_status_checks']['checks'])
if __name__ == '__main__':
unittest.main()
+34
View File
@@ -76,6 +76,7 @@ sys.exit(subprocess.run([os.environ['TEST_REAL_NODE'], *sys.argv[1:]], input=sou
def test_tags_and_legacy_authentication(self):
for trusted in [True, False]:
for version, tag in [('1.0.0-RC.1', 'rc'), ('1.0.0-SNAPSHOT', 'snapshot'),
('1.0.0-SNAPSHOT.101', 'snapshot'),
('1.0.0-alpha.1', 'next'), ('1.0.0-beta.1', 'next'), ('1.0.0', 'latest')]:
with self.subTest(trusted=trusted, version=version):
result, args, oidc = self.run_publish(version, trusted)
@@ -133,5 +134,38 @@ sys.exit(subprocess.run([os.environ['TEST_REAL_NODE'], *sys.argv[1:]], input=sou
self.assertNotIn('Successfully published', result.stdout)
class SnapshotVersionTests(unittest.TestCase):
def test_snapshot_jobs_keep_source_head_and_publish_distinct_versions(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
def git(*args):
return subprocess.check_output(['git', *args], cwd=root, text=True).strip()
git('init', '-q', '-b', 'develop')
source = '{"name": "snapshot-test", "version": "0.40.27-SNAPSHOT"}\n'
package = root / 'package.json'
package.write_text(source)
git('add', 'package.json')
git('-c', 'user.name=Test', '-c', 'user.email=test@example.invalid',
'-c', 'commit.gpgsign=false', 'commit', '-qm', 'initial source')
head = git('rev-parse', 'HEAD')
for number in ('101', '102'):
package.write_text(source)
env = dict(os.environ, CIRCLE_BUILD_NUM=number, BRANCH_TYPE='snapshot')
subprocess.run(['bash', str(SCRIPT.parent / 'sync-npm-version.sh')],
cwd=root, env=env, check=True, capture_output=True)
self.assertEqual(json.loads(package.read_text())['version'], '0.40.28-SNAPSHOT.' + number)
subprocess.run(['bash', str(SCRIPT.parent / 'node_version_commit.sh')],
cwd=root, env=env, check=True, capture_output=True)
self.assertEqual(git('rev-parse', 'HEAD'), head)
self.assertEqual(git('diff', '--cached', '--name-only'), '')
for number in ('', '0', '01', '-1', 'abc'):
package.write_text(source)
result = subprocess.run(['bash', str(SCRIPT.parent / 'sync-npm-version.sh')],
cwd=root, env=dict(os.environ, CIRCLE_BUILD_NUM=number),
capture_output=True)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(package.read_text(), source)
if __name__ == '__main__':
unittest.main()
+13 -1
View File
@@ -44,8 +44,20 @@ class BranchLanguages(unittest.TestCase):
self.assertEqual(0, result.returncode, result.stderr)
self.assertIn('build-mode=autobuild\n', output)
def test_java_cli_preserves_homebrew_ruby_coverage(self):
result, output = self.select(['src/Main.java', 'packaging/homebrew/qctl.rb', '.github/workflows/build.yml'])
self.assertEqual(0, result.returncode, result.stderr)
self.assertIn('languages=java-kotlin,ruby,actions\n', output)
self.assertIn('build-mode=none\n', output)
def test_ruby_only_source_is_supported(self):
result, output = self.select(['Formula/qctl.rb'])
self.assertEqual(0, result.returncode, result.stderr)
self.assertIn('languages=ruby\n', output)
self.assertIn('build-mode=none\n', output)
def test_untracked_files_do_not_select_languages(self):
result, output = self.select(['src/Example.java'], ['web/generated.js', '.github/workflows/untracked.yml'])
result, output = self.select(['src/Example.java'], ['web/generated.js', 'generated/formula.rb', '.github/workflows/untracked.yml'])
self.assertEqual(0, result.returncode, result.stderr)
self.assertIn('languages=java-kotlin\n', output)
+185
View File
@@ -0,0 +1,185 @@
"""Remote enrollment keeps immutable source checks and resumes signed submissions."""
import base64
from pathlib import Path
import sys
import unittest
from unittest import mock
import yaml
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
import reconcile_enrollment as remote
class ReconcileTests(unittest.TestCase):
def setUp(self):
self.head = 'a' * 40
self.new = 'b' * 40
self.repo = 'QRun-IO/example'
self.target = {'repository': self.repo, 'branch': 'main'}
self.manifest = {'profile': 'qbit', 'orb_version': '0.7.4', 'default_branch': 'main',
'publish': {'snapshot': False, 'release_candidate': False, 'release': False}}
self.sources = {
'.qqq-ci.yml': yaml.safe_dump(self.manifest).encode(),
'.circleci/config.yml': yaml.safe_dump(remote.enroll_consumers.rollout.standard.canonical_caller('qbit', '0.7.4')).encode()}
def request(self, path, missing=False):
if path == 'repos/' + self.repo:
return {'archived': False, 'default_branch': 'main'}
if path.endswith('/branches/main'):
return {'commit': {'sha': self.head}}
if '/contents/' in path:
self.assertTrue(path.endswith('?ref=' + self.head))
name = path.split('/contents/')[1].split('?')[0]
raw = self.sources.get(name)
return None if raw is None else {'type': 'file', 'encoding': 'base64', 'content': base64.b64encode(raw).decode()}
raise AssertionError(path)
def plan(self):
with mock.patch.object(remote, 'api', side_effect=self.request):
return remote.inspect(self.target, '0.8')
def test_immutable_plan_is_deterministic_and_preserves_policy(self):
first, second = self.plan(), self.plan()
self.assertEqual(first['automation_branch'], second['automation_branch'])
self.assertEqual(self.sources, first['originals'])
self.assertEqual({**self.manifest, 'orb_version': '0.8'},
yaml.safe_load(first['replacements']['.qqq-ci.yml']))
self.assertTrue(first['changed'])
def test_missing_manifest_uses_legacy_converter(self):
self.sources.pop('.qqq-ci.yml')
self.sources['.circleci/config.yml'] = yaml.safe_dump({'version': 2.1,
'orbs': {'qqq-orb': 'kingsrook/qqq-orb@0.5.0'},
'workflows': {'verify': {'jobs': [{'qqq-orb/mvn_test_only': {}}]}}}).encode()
plan = self.plan()
self.assertIsNone(plan['originals']['.qqq-ci.yml'])
self.assertFalse(any(yaml.safe_load(plan['replacements']['.qqq-ci.yml'])['publish'].values()))
def submission_api(self, plan, path, missing=False):
if '/branches/main' in path:
return {'commit': {'sha': self.head}}
if '/git/ref/' in path:
return {'object': {'sha': self.new}}
if '/commits/' in path:
return {'commit': {'verification': {'verified': True}},
'parents': [{'sha': self.head}], 'files': [{'filename': p} for p in remote.PATHS]}
if '/contents/' in path:
self.assertTrue(path.endswith('?ref=' + self.new))
name = path.split('/contents/')[1].split('?')[0]
return {'type': 'file', 'encoding': 'base64', 'content': base64.b64encode(plan['replacements'][name]).decode()}
if '/pulls?' in path:
return [{'head': {'sha': self.new}, 'html_url': 'https://github.com/QRun-IO/example/pull/1'}]
raise AssertionError(path)
def test_matching_existing_submission_uses_no_git_or_pr_mutations(self):
plan = self.plan()
with mock.patch.object(remote, 'api', side_effect=lambda *a, **k: self.submission_api(plan, *a, **k)), mock.patch.object(remote, 'command') as command:
result = remote.apply(plan)
self.assertEqual('existing-pr', result['state'])
command.assert_not_called()
def test_unsigned_existing_branch_is_rejected_without_mutation(self):
plan = self.plan()
def request(path, missing=False):
value = self.submission_api(plan, path, missing)
if '/commits/' in path:
value['commit']['verification']['verified'] = False
return value
with mock.patch.object(remote, 'api', side_effect=request), mock.patch.object(remote, 'command') as command:
with self.assertRaises(ValueError):
remote.apply(plan)
command.assert_not_called()
def test_source_drift_prevents_submission(self):
plan = self.plan()
with mock.patch.object(remote, 'api', return_value={'commit': {'sha': 'c' * 40}}), mock.patch.object(remote, 'command') as command:
with self.assertRaises(ValueError):
remote.apply(plan)
command.assert_not_called()
def test_interrupted_push_creates_only_missing_pr(self):
plan = self.plan()
seen = []
def request(path, missing=False):
return [] if '/pulls?' in path else self.submission_api(plan, path, missing)
def command(args, cwd=None):
seen.append(args[:3])
self.assertEqual(['gh', 'pr', 'create'], args[:3])
self.assertIn(self.head, Path(args[args.index('--body-file') + 1]).read_text())
return 'https://github.com/QRun-IO/example/pull/2'
with mock.patch.object(remote, 'api', side_effect=request), mock.patch.object(remote, 'command', side_effect=command):
result = remote.apply(plan)
self.assertEqual('submitted', result['state'])
self.assertEqual([['gh', 'pr', 'create']], seen)
def test_new_api_submission_is_atomic_and_exact(self):
plan = self.plan()
mutations = []
def request(path, missing=False):
if '/git/ref/' in path:
return None
return self.submission_api(plan, path, missing)
def mutate(path, payload):
mutations.append((path, payload))
return {'data': {'createCommitOnBranch': {'commit': {'oid': self.new}}}}
with mock.patch.object(remote, 'api', side_effect=request), mock.patch.object(remote, 'mutation', side_effect=mutate), mock.patch.object(remote, 'command') as command:
self.assertEqual('existing-pr', remote.apply(plan)['state'])
command.assert_not_called()
self.assertEqual(('repos/' + self.repo + '/git/refs', {'ref': 'refs/heads/' + plan['automation_branch'], 'sha': self.head}), mutations[0])
commit = mutations[1][1]['variables']['input']
self.assertEqual(self.head, commit['expectedHeadOid'])
self.assertEqual({'repositoryNameWithOwner': self.repo, 'branchName': plan['automation_branch']}, commit['branch'])
self.assertEqual(plan['replacements'], {item['path']: base64.b64decode(item['contents']) for item in commit['fileChanges']['additions']})
def test_base_only_branch_resumes_without_creating_another_ref(self):
plan = self.plan()
result = {'data': {'createCommitOnBranch': {'commit': {'oid': self.new}}}}
with mock.patch.object(remote, 'api', return_value={'commit': {'sha': self.head}}), mock.patch.object(remote, 'mutation', return_value=result) as mutation:
self.assertEqual(self.new, remote.signed_api_commit(plan, {'object': {'sha': self.head}}))
self.assertEqual(1, mutation.call_count)
self.assertEqual('graphql', mutation.call_args.args[0])
def test_existing_completed_branch_is_not_mutated(self):
with mock.patch.object(remote, 'mutation') as mutation:
self.assertEqual(self.new, remote.signed_api_commit(self.plan(), {'object': {'sha': self.new}}))
mutation.assert_not_called()
def test_target_drift_prevents_commit_on_base_only_branch(self):
plan = self.plan()
with mock.patch.object(remote, 'api', return_value={'commit': {'sha': 'c' * 40}}), mock.patch.object(remote, 'mutation') as mutation:
with self.assertRaises(ValueError):
remote.signed_api_commit(plan, {'object': {'sha': self.head}})
mutation.assert_not_called()
def test_graphql_errors_fail_closed(self):
response = mock.Mock(returncode=0, stdout='{"errors": [{"message": "conflict"}]}')
with mock.patch.object(remote.subprocess, 'run', return_value=response):
with self.assertRaises(ValueError):
remote.mutation('graphql', {})
def test_unsigned_api_commit_cannot_create_pr(self):
plan = self.plan()
def request(path, missing=False):
if '/git/ref/' in path:
return {'object': {'sha': self.head}}
value = self.submission_api(plan, path, missing)
if '/commits/' in path:
value['commit']['verification']['verified'] = False
return value
with mock.patch.object(remote, 'api', side_effect=request), mock.patch.object(remote, 'mutation', return_value={'data': {'createCommitOnBranch': {'commit': {'oid': self.new}}}}), mock.patch.object(remote, 'command') as command:
with self.assertRaises(ValueError):
remote.apply(plan)
command.assert_not_called()
if __name__ == '__main__':
unittest.main()
+32 -2
View File
@@ -1,6 +1,7 @@
"""Execute the policy job against real git indexes, including application promotion."""
import importlib.util
import json
import os
import shutil
from pathlib import Path
import subprocess
@@ -35,7 +36,7 @@ class RepositoryPolicyTests(unittest.TestCase):
subprocess.run([sys.executable, str(root / 'scripts/pack_pipeline.py'), '--check'], check=True)
self.assertEqual(packed, (root / 'src/scripts/packed_generate_pipeline.py').read_bytes())
def execute(self, files, untracked=None):
def execute(self, files, untracked=None, shell_checks=False):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
subprocess.run(['git', 'init', '-q'], cwd=root, check=True)
@@ -46,7 +47,8 @@ class RepositoryPolicyTests(unittest.TestCase):
subprocess.run(['git', 'add', '.'], cwd=root, check=True)
for name, content in (untracked or {}).items():
(root / name).write_text(content, encoding='utf-8')
return subprocess.run([sys.executable, '-c', SCRIPT], cwd=root, capture_output=True, text=True)
env = dict(os.environ, QQQ_POLICY_SHELL='true' if shell_checks else 'false')
return subprocess.run([sys.executable, '-c', SCRIPT], cwd=root, env=env, capture_output=True, text=True)
def test_placeholder_with_wrappers_and_workflows(self):
result = self.execute({'LICENSE': 'Apache-2.0', 'docs/DESIGN.md': '# Planned application',
@@ -74,6 +76,34 @@ class RepositoryPolicyTests(unittest.TestCase):
def test_only_tracked_files_are_policy_inputs(self):
self.assertEqual(0, self.execute({'README.md': '# Docs'}, {'main.py': 'temporary tool'}).returncode)
def test_shell_validation_is_opt_in_and_never_executes_scripts(self):
files = {'automation/safe.sh': '#!/bin/bash\nexit 42\n', 'diagram.mmd': 'flowchart LR\n A-->B\n'}
self.assertNotEqual(0, self.execute(files).returncode)
result = self.execute(files, shell_checks=True)
self.assertEqual(0, result.returncode, result.stderr)
def test_shell_validation_rejects_syntax_warnings_and_application_sources(self):
for name, content in [('broken.sh', '#!/bin/bash\nif then\n'),
('unsafe.sh', '#!/bin/bash\necho $unquoted\n'),
('main.py', 'print(42)'), ('package.json', '{}')]:
with self.subTest(name=name):
self.assertNotEqual(0, self.execute({name: content}, shell_checks=True).returncode)
def test_shell_option_is_strict_and_keeps_single_small_nonpublishing_job(self):
manifest = {'profile': 'repository-policy', 'orb_version': '0.8',
'default_branch': 'main', 'shell_checks': True}
with patch.object(Path, 'read_text', return_value=yaml.safe_dump(manifest)):
config = pipeline.load_manifest('unused', '0.8')
result = pipeline.repository_policy_template(config, 'main', '')
self.assertFalse(any(config['publish'].values()))
self.assertEqual({'validate-policy'}, set(result['jobs']))
self.assertEqual('small', result['jobs']['validate-policy']['resource_class'])
self.assertEqual({'QQQ_POLICY_SHELL': 'true'}, result['jobs']['validate-policy']['environment'])
for overrides in ({'shell_checks': 'true'}, {'profile': 'qbit'}):
with patch.object(Path, 'read_text', return_value=yaml.safe_dump(dict(manifest, **overrides))):
with self.assertRaises(pipeline.ManifestError):
pipeline.load_manifest('unused', '0.8')
def test_manifest_cannot_enable_publication(self):
manifest = {'profile': 'repository-policy', 'orb_version': '0.7.14', 'default_branch': 'develop'}
with patch.object(Path, 'read_text', return_value=yaml.safe_dump(manifest)):
+5
View File
@@ -20,6 +20,11 @@ class RolloutTests(unittest.TestCase):
def checkout(self, name, profile='qbit', explicit=False, **policy):
root = self.root / name
(root / '.circleci').mkdir(parents=True)
if profile == 'node-artifact':
policy = {'context': 'registry', 'npm_scopes': ['@example'], 'node_version': '20.19',
'artifact_path': 'dist/bundle.js', 'build_branches': ['main'], **policy}
if profile == 'homebrew-tap':
policy = {'tap': 'qrun-io/qctl', 'formula': 'qctl', **policy}
manifest = {'profile': profile, 'orb_version': '0.7.4', 'default_branch': 'develop', **policy}
caller = rollout.standard.canonical_caller(profile, '0.7.4', explicit_manifest=explicit,
release_tag_policy=manifest.get('release_tag_policy'))
+49
View File
@@ -0,0 +1,49 @@
"""Central execution rejects untrusted branches and preserves partial evidence."""
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import Mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
import run_enrollment
class RunnerTests(unittest.TestCase):
def environment(self):
return {'CIRCLE_PROJECT_USERNAME': 'QRun-IO', 'CIRCLE_PROJECT_REPONAME': 'qqq-orb',
'CIRCLE_BRANCH': 'main', 'GITHUB_TOKEN': 'test-only-secret'}
def test_wrong_owner_branch_repo_tag_or_missing_auth_cannot_execute(self):
for change in ({'CIRCLE_PROJECT_USERNAME': 'other'}, {'CIRCLE_PROJECT_REPONAME': 'other'},
{'CIRCLE_BRANCH': 'develop'}, {'CIRCLE_TAG': 'v1.0.0'}, {'GITHUB_TOKEN': ''}):
execute = Mock()
with self.subTest(change=change), self.assertRaises(ValueError):
run_enrollment.run({**self.environment(), **change}, execute)
execute.assert_not_called()
def test_timeout_retains_partial_report_without_secrets(self):
with tempfile.TemporaryDirectory() as directory:
def execute(args, **kwargs):
output = Path(args[args.index('--output') + 1])
output.write_text('[{"state":"unresolved"}]')
self.assertEqual(1200, kwargs['timeout'])
self.assertIn('--circle-settings', args)
self.assertEqual('test-only-secret', kwargs['env']['GH_TOKEN'])
raise subprocess.TimeoutExpired(args, 1200)
self.assertEqual(124, run_enrollment.run(self.environment(), execute, directory))
output = Path(directory) / 'artifacts/enrollment'
self.assertEqual([{'state': 'unresolved'}], json.loads((output / 'result.json').read_text()))
self.assertEqual('timed-out', json.loads((output / 'run.json').read_text())['state'])
self.assertNotIn('test-only-secret', (output / 'run.json').read_text())
def test_failed_pass_propagates_nonzero_exit(self):
with tempfile.TemporaryDirectory() as directory:
self.assertEqual(2, run_enrollment.run(self.environment(), Mock(return_value=Mock(returncode=2)), directory))
self.assertEqual('failed', json.loads((Path(directory) / 'artifacts/enrollment/run.json').read_text())['state'])
if __name__ == '__main__':
unittest.main()
+33
View File
@@ -3,6 +3,7 @@ import importlib.util
import json
from pathlib import Path
import re
import tempfile
import unittest
from unittest import mock
@@ -15,6 +16,38 @@ spec.loader.exec_module(migration)
class MigrationTests(unittest.TestCase):
def test_hotfix_and_integration_exclusion_preserves_main_tests_and_publications(self):
pattern = "/(develop|release/.*|hotfix/.*|integration.*)/"
config = self.config(filters={"branches": {"ignore": pattern}, "tags": {"only": []}})
for kind, branch in (("snapshot", "develop"), ("release_candidate", r"/release\/.*/"), ("hotfix", r"/hotfix\/.*/")):
config["workflows"][kind] = {"jobs": [{"qqq-orb/mvn_publish": {
"branch_type": kind, "filters": {"branches": {"only": [branch]}}}}]}
config["workflows"]["release"] = {"jobs": [{"qqq-orb/mvn_publish": {
"branch_type": "release", "filters": {"branches": {"ignore": "/.*/"},
"tags": {"only": [r"/^v\d+\.\d+\.\d+$/"]}}}}]}
manifest = migration.infer_manifest(config, "0.8", "develop")
self.assertEqual("non-release-no-hotfix-integration", manifest["test_branch_policy"])
self.assertFalse(manifest["release_on_main"])
self.assertEqual("stable", manifest["release_tag_policy"])
self.assertTrue(all(manifest["publish"][kind] for kind in ("snapshot", "release_candidate", "release", "hotfix")))
spec = importlib.util.spec_from_file_location("filter_pipeline", Path(__file__).resolve().parents[1] / "src/scripts/generate_pipeline.py")
pipeline = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pipeline)
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "manifest.yml"
path.write_text(yaml.safe_dump(manifest), encoding="utf-8")
loaded = pipeline.load_manifest(path, "0.8")
with mock.patch.object(pipeline, "proven_ci_maintenance", return_value=False), mock.patch.object(pipeline, "proven_docs_only", return_value=False), mock.patch.object(pipeline, "git", return_value=b"qualified-head\n"):
for branch, tag, kind in (("main", "", None), ("feature/test", "", None),
("integration-test", "", None), ("develop", "", "snapshot"),
("release/1.0", "", "release_candidate"), ("hotfix/1.0.1", "", "hotfix"),
("", "v1.0.0", "release")):
result = pipeline.qbit_template(loaded, branch, tag)
options = next(iter(next(iter(result["workflows"].values()))["jobs"][0].values()))
self.assertEqual(kind, options.get("branch_type"))
if kind is None:
self.assertEqual(["automation/qbit-rc-pending", pattern], options["filters"]["branches"]["ignore"])
def test_630_original_filter_intersections_equal_generated_publications(self):
spec = importlib.util.spec_from_file_location(
"publication_pipeline", Path(__file__).resolve().parents[1] / "src/scripts/generate_pipeline.py")
+51
View File
@@ -0,0 +1,51 @@
"""Maven failures must survive tee without overriding project analysis policy."""
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
SCRIPTS = [('mvn_spotbugs.sh', 'SPOTBUGS_FAIL_ON_ERROR', 'spotbugs.failOnError'),
('mvn_pmd.sh', 'PMD_FAIL_ON_VIOLATION', 'pmd.failOnViolation')]
class StaticAnalysisExitTests(unittest.TestCase):
def invoke(self, script, variable, setting, status):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
binary = root / 'mvn'
binary.write_text('#!/bin/sh\nprintf "%s\\n" "$@" > "$ARGUMENT_FILE"\necho analysis-output\nexit "$FAKE_MAVEN_EXIT"\n')
binary.chmod(0o755)
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
ARGUMENT_FILE=str(root / 'arguments'), FAKE_MAVEN_EXIT=str(status))
env.pop(variable, None)
if setting is not None:
env[variable] = setting
result = subprocess.run(['bash', str(ROOT / 'src/scripts' / script)], cwd=root,
env=env, text=True, capture_output=True, timeout=15)
return result, (root / 'arguments').read_text().splitlines()
def test_maven_failure_is_never_hidden_by_successful_tee(self):
for script, variable, _ in SCRIPTS:
for setting in ('true', 'false'):
with self.subTest(script=script, setting=setting):
result, _ = self.invoke(script, variable, setting, 17)
self.assertEqual(17, result.returncode)
self.assertIn('analysis-output', result.stdout)
def test_success_preserves_explicit_flag_and_project_defaults(self):
for script, variable, property_name in SCRIPTS:
for setting in ('true', 'false', None):
with self.subTest(script=script, setting=setting):
result, arguments = self.invoke(script, variable, setting, 0)
self.assertEqual(0, result.returncode, result.stderr)
if setting == 'true':
self.assertIn('-D' + property_name + '=true', arguments)
else:
self.assertFalse(any(arg.startswith('-D' + property_name + '=') for arg in arguments))
self.assertIn('-DskipTests', arguments)
if __name__ == '__main__':
unittest.main()
+45
View File
@@ -0,0 +1,45 @@
"""Voyage delegates live GitOps updates to the existing shared updater."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
TEMPLATE = json.loads((Path(__file__).resolve().parents[1] / "src/scripts/templates/voyage.json").read_text())
class VoyageGitOps(unittest.TestCase):
def test_live_target_uses_shared_updater_only_after_main_image_publication(self):
self.assertNotIn('update-cd-repo', TEMPLATE['jobs'])
self.assertEqual(TEMPLATE['orbs']['munitor'], 'kof22/munitor@0.3.11')
invocations = [(workflow, entry['munitor/update_cd_repo'])
for workflow, body in TEMPLATE['workflows'].items() for entry in body['jobs']
if 'munitor/update_cd_repo' in entry]
self.assertEqual(len(invocations), 1)
workflow, options = invocations[0]
self.assertEqual(workflow, 'release')
self.assertEqual(options['cd_repo'], 'KofTwentyTwo/cluster-gitops')
self.assertEqual(options['cd_path'], 'tenants/voyage/kustomization.yaml')
self.assertEqual(options['cd_image_name'], 'ghcr.io/qrun-io/voyage')
self.assertEqual(options['cd_format'], 'kustomize')
self.assertEqual(options['requires'], ['docker-build'])
self.assertEqual(options['context'], ['github'])
self.assertEqual(options['filters'], {'branches': {'only': 'main'}})
def test_updater_receives_published_commit_tag_and_rejects_invalid_revision(self):
options = next(entry['munitor/update_cd_repo'] for entry in TEMPLATE['workflows']['release']['jobs']
if 'munitor/update_cd_repo' in entry)
command = options['pre-steps'][0]['run']['command']
with tempfile.TemporaryDirectory() as directory:
env_file = Path(directory) / 'bash-env'
for revision in ('a' * 40, '', 'main', 'a' * 39):
env_file.write_text('')
env = {**os.environ, 'BASH_ENV': str(env_file), 'CIRCLE_SHA1': revision}
result = subprocess.run(['bash', '-c', command], env=env, capture_output=True)
if revision == 'a' * 40:
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(env_file.read_text(), "export PROJECT_VERSION='aaaaaaa'\n")
else:
self.assertNotEqual(result.returncode, 0)
self.assertEqual(env_file.read_text(), '')
+131 -130
View File
@@ -1,130 +1,131 @@
"""Voyage's authoritative CI contracts, extracted from source 9f598cc105ef."""
import json
import os
import subprocess
import tempfile
from pathlib import Path
import re
import unittest
TEMPLATE = json.loads((Path(__file__).resolve().parents[1] / "src/scripts/templates/voyage.json").read_text())
def matches(pattern, branch):
if isinstance(pattern, list):
return any(matches(p, branch) for p in pattern)
if pattern.startswith("/") and pattern.endswith("/"):
return re.fullmatch(pattern[1:-1], branch) is not None
return pattern == branch
def selected(branch):
found = []
for workflow, body in TEMPLATE["workflows"].items():
for invocation in body["jobs"]:
name, options = next(iter(invocation.items()))
filters = options.get("filters", {}).get("branches", {})
if "only" in filters and not matches(filters["only"], branch):
continue
if "ignore" in filters and matches(filters["ignore"], branch):
continue
found.append((workflow, name, options))
return found
class VoyageContract(unittest.TestCase):
def test_each_supported_branch_has_one_validation_owner(self):
for branch, workflow in (("feature/example", "pull-request"), ("hotfix/example", "pull-request"), ("develop", "develop"), ("main", "release"), ("release/1.0", "release")):
with self.subTest(branch=branch):
jobs = selected(branch)
self.assertEqual({w for w, _, _ in jobs}, {workflow})
self.assertEqual([n for _, n, _ in jobs].count("build-and-test"), 1)
self.assertEqual(selected("release-please--branches--main"), [])
def test_verify_owns_tests_quality_and_coverage_without_skips(self):
jobs = TEMPLATE["jobs"]
self.assertNotIn("coverage", jobs)
self.assertNotIn("code-quality", jobs)
steps = jobs["build-and-test"]["steps"]
commands = [s["run"]["command"] for s in steps if isinstance(s, dict) and "run" in s]
self.assertEqual(commands, ["mvn clean verify -B -T4 --update-snapshots --no-transfer-progress"])
full = json.dumps(jobs)
self.assertNotIn("mvn test", full)
self.assertNotIn("jacoco.skip", full)
self.assertNotIn("skipTests", full)
self.assertLess(steps.index("qqq-orb/mvn_cache_restore"), steps.index("qqq-orb/mvn_cache_save"))
def test_unit_integration_and_coverage_evidence_retained(self):
steps = TEMPLATE["jobs"]["build-and-test"]["steps"]
results = [s["store_test_results"]["path"] for s in steps if isinstance(s, dict) and "store_test_results" in s]
self.assertEqual(results, ["target/surefire-reports", "target/failsafe-reports"])
paths = next(s["persist_to_workspace"]["paths"] for s in steps if isinstance(s, dict) and "persist_to_workspace" in s)
for path in ("target/site", "target/jacoco.exec", "target/voyage.jar", "target/classes", "target/test-classes"):
self.assertIn(path, paths)
sonar = json.dumps(TEMPLATE["jobs"]["sonar-scan"])
self.assertIn("target/site/jacoco/jacoco.xml", sonar)
self.assertIn("attach_workspace", sonar)
def test_all_workflow_dependencies_exist_and_preserve_release_boundaries(self):
for workflow, body in TEMPLATE["workflows"].items():
names = {next(iter(entry)) for entry in body["jobs"]}
for entry in body["jobs"]:
name, options = next(iter(entry.items()))
self.assertIn(name, TEMPLATE["jobs"])
self.assertTrue(set(options.get("requires", [])).issubset(names))
for branch in ("feature/example", "release/1.0", "develop"):
self.assertNotIn("update-cd-repo", [n for _, n, _ in selected(branch)])
self.assertNotIn("release-please", [n for _, n, _ in selected(branch)])
main = {n: o for _, n, o in selected("main")}
self.assertEqual(main["update-cd-repo"]["requires"], ["docker-build"])
self.assertEqual(main["release-please"]["requires"], ["docker-build"])
self.assertEqual(main["docker-build"]["requires"], ["build-and-test", "secrets-scan", "sast-scan", "security-scan"])
def test_dependency_scan_propagates_findings_and_operational_errors(self):
command = next(s["run"]["command"] for s in TEMPLATE["jobs"]["security-scan"]["steps"]
if isinstance(s, dict) and "run" in s)
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "bin").mkdir()
docker = root / "bin/docker"
docker.write_text('#!/bin/sh\nexit "$SCANNER_RESULT"\n')
docker.chmod(0o755)
(root / "target").mkdir()
(root / "target/voyage.jar").write_bytes(b"artifact")
env = {**os.environ, "HOME": directory, "PATH": str(root / "bin") + os.pathsep + os.environ["PATH"],
"CIRCLE_BRANCH": "develop"}
for code in (0, 1, 2):
result = subprocess.run(["bash", "-c", command], cwd=root,
env={**env, "SCANNER_RESULT": str(code)}, capture_output=True)
self.assertEqual(result.returncode, code)
(root / "target/voyage.jar").unlink()
result = subprocess.run(["bash", "-c", command], cwd=root,
env={**env, "SCANNER_RESULT": "0"}, capture_output=True)
self.assertNotEqual(result.returncode, 0)
def test_security_policies_and_destinations_preserved(self):
jobs = TEMPLATE["jobs"]
self.assertIn('--exit-code 1', json.dumps(jobs["docker-build"]))
self.assertIn('--severity CRITICAL,HIGH', json.dumps(jobs["docker-build"]))
self.assertIn('ghcr.io/qrun-io/voyage', json.dumps(jobs["docker-build"]))
self.assertIn('overlays/production/kustomization.yaml', json.dumps(jobs["update-cd-repo"]))
owasp = '\n'.join(s["run"]["command"] for s in jobs["security-scan"]["steps"] if isinstance(s, dict) and "run" in s)
self.assertIn('--severity HIGH,CRITICAL --exit-code 1', owasp)
self.assertIn('target/voyage.jar:/scan/voyage.jar:ro', owasp)
self.assertIn('aquasec/trivy:0.76.0@sha256:', owasp)
self.assertNotIn('--ignore-unfixed', owasp)
self.assertNotIn('NVD_API_KEY', owasp)
self.assertNotIn('mvn ', owasp)
self.assertIn('set -euo pipefail', owasp)
self.assertEqual(jobs["security-scan"]["resource_class"], "medium")
for workflow in TEMPLATE["workflows"].values():
for invocation in workflow["jobs"]:
if "security-scan" in invocation:
self.assertNotIn("context", invocation["security-scan"])
self.assertIn('./gitleaks detect', json.dumps(jobs["secrets-scan"]))
self.assertIn('|| true', json.dumps(jobs["sast-scan"]))
self.assertIn('makeAggregateBom', json.dumps(jobs["sbom"]))
if __name__ == "__main__":
unittest.main()
"""Voyage's authoritative CI contracts, extracted from source 9f598cc105ef."""
import json
import os
import subprocess
import tempfile
from pathlib import Path
import re
import unittest
TEMPLATE = json.loads((Path(__file__).resolve().parents[1] / "src/scripts/templates/voyage.json").read_text())
def matches(pattern, branch):
if isinstance(pattern, list):
return any(matches(p, branch) for p in pattern)
if pattern.startswith("/") and pattern.endswith("/"):
return re.fullmatch(pattern[1:-1], branch) is not None
return pattern == branch
def selected(branch):
found = []
for workflow, body in TEMPLATE["workflows"].items():
for invocation in body["jobs"]:
name, options = next(iter(invocation.items()))
filters = options.get("filters", {}).get("branches", {})
if "only" in filters and not matches(filters["only"], branch):
continue
if "ignore" in filters and matches(filters["ignore"], branch):
continue
found.append((workflow, options.get("name", name), options))
return found
class VoyageContract(unittest.TestCase):
def test_each_supported_branch_has_one_validation_owner(self):
for branch, workflow in (("feature/example", "pull-request"), ("hotfix/example", "pull-request"), ("develop", "develop"), ("main", "release"), ("release/1.0", "release")):
with self.subTest(branch=branch):
jobs = selected(branch)
self.assertEqual({w for w, _, _ in jobs}, {workflow})
self.assertEqual([n for _, n, _ in jobs].count("build-and-test"), 1)
self.assertEqual({n for _, n, _ in selected("release-please--branches--main")},
{"build-and-test", "secrets-scan", "sast-scan", "security-scan"})
def test_verify_owns_tests_quality_and_coverage_without_skips(self):
jobs = TEMPLATE["jobs"]
self.assertNotIn("coverage", jobs)
self.assertNotIn("code-quality", jobs)
steps = jobs["build-and-test"]["steps"]
commands = [s["run"]["command"] for s in steps if isinstance(s, dict) and "run" in s]
self.assertEqual(commands, ["mvn clean verify -B -T4 --update-snapshots --no-transfer-progress"])
full = json.dumps(jobs)
self.assertNotIn("mvn test", full)
self.assertNotIn("jacoco.skip", full)
self.assertNotIn("skipTests", full)
self.assertLess(steps.index("qqq-orb/mvn_cache_restore"), steps.index("qqq-orb/mvn_cache_save"))
def test_unit_integration_and_coverage_evidence_retained(self):
steps = TEMPLATE["jobs"]["build-and-test"]["steps"]
results = [s["store_test_results"]["path"] for s in steps if isinstance(s, dict) and "store_test_results" in s]
self.assertEqual(results, ["target/surefire-reports", "target/failsafe-reports"])
paths = next(s["persist_to_workspace"]["paths"] for s in steps if isinstance(s, dict) and "persist_to_workspace" in s)
for path in ("target/site", "target/jacoco.exec", "target/voyage.jar", "target/classes", "target/test-classes"):
self.assertIn(path, paths)
sonar = json.dumps(TEMPLATE["jobs"]["sonar-scan"])
self.assertIn("target/site/jacoco/jacoco.xml", sonar)
self.assertIn("attach_workspace", sonar)
def test_all_workflow_dependencies_exist_and_preserve_release_boundaries(self):
for workflow, body in TEMPLATE["workflows"].items():
names = {next(iter(entry.values())).get("name", next(iter(entry))) for entry in body["jobs"]}
for entry in body["jobs"]:
name, options = next(iter(entry.items()))
self.assertTrue(name in TEMPLATE["jobs"] or name == "munitor/update_cd_repo")
self.assertTrue(set(options.get("requires", [])).issubset(names))
for branch in ("feature/example", "release/1.0", "develop"):
self.assertNotIn("update-cd-repo", [n for _, n, _ in selected(branch)])
self.assertNotIn("release-please", [n for _, n, _ in selected(branch)])
main = {n: o for _, n, o in selected("main")}
self.assertEqual(main["update-cd-repo"]["requires"], ["docker-build"])
self.assertEqual(main["release-please"]["requires"], ["docker-build"])
self.assertEqual(main["docker-build"]["requires"], ["build-and-test", "secrets-scan", "sast-scan", "security-scan"])
def test_dependency_scan_propagates_findings_and_operational_errors(self):
command = next(s["run"]["command"] for s in TEMPLATE["jobs"]["security-scan"]["steps"]
if isinstance(s, dict) and "run" in s)
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "bin").mkdir()
docker = root / "bin/docker"
docker.write_text('#!/bin/sh\nexit "$SCANNER_RESULT"\n')
docker.chmod(0o755)
(root / "target").mkdir()
(root / "target/voyage.jar").write_bytes(b"artifact")
env = {**os.environ, "HOME": directory, "PATH": str(root / "bin") + os.pathsep + os.environ["PATH"],
"CIRCLE_BRANCH": "develop"}
for code in (0, 1, 2):
result = subprocess.run(["bash", "-c", command], cwd=root,
env={**env, "SCANNER_RESULT": str(code)}, capture_output=True)
self.assertEqual(result.returncode, code)
(root / "target/voyage.jar").unlink()
result = subprocess.run(["bash", "-c", command], cwd=root,
env={**env, "SCANNER_RESULT": "0"}, capture_output=True)
self.assertNotEqual(result.returncode, 0)
def test_security_policies_and_destinations_preserved(self):
jobs = TEMPLATE["jobs"]
self.assertIn('--exit-code 1', json.dumps(jobs["docker-build"]))
self.assertIn('--severity CRITICAL,HIGH', json.dumps(jobs["docker-build"]))
self.assertIn('ghcr.io/qrun-io/voyage', json.dumps(jobs["docker-build"]))
self.assertNotIn('update-cd-repo', jobs)
owasp = '\n'.join(s["run"]["command"] for s in jobs["security-scan"]["steps"] if isinstance(s, dict) and "run" in s)
self.assertIn('--severity HIGH,CRITICAL --exit-code 1', owasp)
self.assertIn('target/voyage.jar:/scan/voyage.jar:ro', owasp)
self.assertIn('aquasec/trivy:0.76.0@sha256:', owasp)
self.assertNotIn('--ignore-unfixed', owasp)
self.assertNotIn('NVD_API_KEY', owasp)
self.assertNotIn('mvn ', owasp)
self.assertIn('set -euo pipefail', owasp)
self.assertEqual(jobs["security-scan"]["resource_class"], "medium")
for workflow in TEMPLATE["workflows"].values():
for invocation in workflow["jobs"]:
if "security-scan" in invocation:
self.assertNotIn("context", invocation["security-scan"])
self.assertIn('./gitleaks detect', json.dumps(jobs["secrets-scan"]))
self.assertIn('|| true', json.dumps(jobs["sast-scan"]))
self.assertIn('makeAggregateBom', json.dumps(jobs["sbom"]))
if __name__ == "__main__":
unittest.main()
+42
View File
@@ -0,0 +1,42 @@
"""Execute Voyage release commands; CD implementation belongs to Munitor."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
TEMPLATE = json.loads((ROOT / "src/scripts/templates/voyage.json").read_text())
COMMAND = next(step["run"]["command"] for step in TEMPLATE["jobs"]["release-please"]["steps"]
if isinstance(step, dict) and "run" in step)
class VoyageRelease(unittest.TestCase):
def run_release(self, fail=False):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
npx = root / "npx"
npx.write_text('''#!/usr/bin/env python3
import json, os, sys
with open(os.environ['EVENTS'], 'a') as output:
output.write(json.dumps(sys.argv[1:])+'\\n')
assert '--target-branch=main' in sys.argv
if os.environ['FAILURE']=='true' and 'github-release' in sys.argv: sys.exit(25)
''')
npx.chmod(0o755)
events = root / "events.jsonl"
env = {**os.environ, "PATH": str(root) + os.pathsep + os.environ["PATH"],
"EVENTS": str(events), "FAILURE": str(fail).lower(), "GITHUB_TOKEN": "fixture-token"}
result = subprocess.run(["bash", "-c", COMMAND], cwd=root, env=env, capture_output=True, text=True)
return result, [json.loads(line) for line in events.read_text().splitlines()]
def test_release_targets_main_for_both_commands(self):
result, rows = self.run_release()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual([args[1] for args in rows], ['github-release', 'release-pr'])
def test_release_failure_is_not_hidden_by_second_command(self):
result, rows = self.run_release(fail=True)
self.assertEqual(result.returncode, 25, result.stderr)
self.assertEqual(len(rows), 1)
+3 -2
View File
@@ -46,7 +46,7 @@ PROFILES = {'qqq': 'core', 'qqq-frontend-material-dashboard': 'frontend-material
'qqq-android': 'android', 'qqq-mcp-rag-standard-policies': 'mcp-policy',
'marketing-website': 'marketing', 'qqq-mcp-rag': 'native-mcp',
'qqq-business-platform': 'native-business', '.github': 'native-workflow-lint',
'qqq-orb': 'owner-bootstrap', 'marketing-website-cd': 'native-gitops'}
'new-qqq-application-template': 'application-template', 'homebrew-qctl': 'homebrew-tap', 'qqq-meta-manager': 'repository-policy', 'qqq-templates-hub': 'repository-policy', 'qqq-orb': 'owner-bootstrap', 'marketing-website-cd': 'native-gitops', 'voyage-cd': 'native-gitops'}
NO_CI = json.loads((ROOT / 'tools/no-ci-policy.json').read_text(encoding='utf-8'))
@@ -270,7 +270,8 @@ def audit(entry, snapshot, version, worker_sha, policy):
if profile not in ('qbit', 'repository-policy', 'all') or 'codeql_worker_sha' not in policy:
continue
bridge_sha = policy['codeql_worker_sha']
elif definition['repository'] != entry['nameWithOwner']:
elif (definition['repository'] != entry['nameWithOwner']
and entry['nameWithOwner'] not in definition.get('additional_repositories', [])):
continue
path = definition['path']
raw = snapshot.read(path)
+78
View File
@@ -0,0 +1,78 @@
"""Manage native cost controls only for profiles with reviewed cancellation semantics."""
import json
import os
import re
from urllib.error import URLError
from urllib.request import Request, urlopen
AUTOCANCEL_PROFILES = {'repository-policy', 'homebrew-tap', 'application-template', 'marketing'}
def request(repository, payload=None):
"""Use existing central credentials; never expose authentication or error bodies."""
if not re.fullmatch(r'QRun-IO/[A-Za-z0-9_.-]+', repository):
raise ValueError('Only QRun-IO projects can be managed')
token = os.environ.get('CIRCLE_TOKEN')
if not token:
raise ValueError('Central CircleCI credential unavailable')
headers = {'Circle-Token': token, 'Accept': 'application/json'}
if payload is not None:
headers['Content-Type'] = 'application/json'
operation = Request('https://circleci.com/api/v1.1/project/github/' + repository + '/settings',
headers=headers, method='GET' if payload is None else 'PUT',
data=None if payload is None else json.dumps(payload).encode())
try:
with urlopen(operation, timeout=30) as response:
return json.load(response)
except (URLError, ValueError):
raise ValueError('CircleCI project settings unavailable') from None
def reconcile(plan, source_request, apply=False, settings_request=request):
"""Require a current canonical source and preserve every unrelated project flag."""
if plan['profile'] not in AUTOCANCEL_PROFILES:
return {'state': 'not-managed', 'reason': 'Profile cancellation policy not reviewed'}
if plan['changed']:
return {'state': 'waiting-source', 'reason': 'Canonical enrollment must land first'}
repo = plan['repository']
try:
info = source_request(f'repos/{repo}')
if info['archived'] or (plan['profile'] == 'marketing' and info['default_branch'] != 'main'):
raise ValueError('Repository default branch or archive state differs from policy')
before = settings_request(repo)['feature_flags']
if not isinstance(before, dict) or type(before.get('autocancel-builds')) is not bool:
raise ValueError('CircleCI cancellation flag is missing or invalid')
changed = not before['autocancel-builds']
if apply and changed:
if source_request(f'repos/{repo}/branches/{plan["branch"]}')['commit']['sha'] != plan['head']:
raise ValueError('Source changed after enrollment inspection')
settings_request(repo, {'feature_flags': {'autocancel-builds': True}})
after = settings_request(repo)['feature_flags']
if after != {**before, 'autocancel-builds': True}:
raise ValueError('CircleCI settings readback differs from the narrow update')
return {'state': 'enforced' if apply else 'inspected', 'changed': changed}
except (ValueError, KeyError, TypeError) as error:
return {'state': 'unresolved', 'reason': str(error)}
def reconcile_repository(plans, findings, source_request, apply=False, settings_request=request):
"""A project-wide flag requires agreement across all discovered current branches."""
repo = plans[0]['repository']
if any(plan['repository'] != repo for plan in plans):
raise ValueError('Expected one repository')
if any(row['repository'] == repo and row.get('state') == 'unresolved' for row in findings):
return {'state': 'waiting-source', 'reason': 'A current branch is unresolved'}
if any(plan['profile'] not in AUTOCANCEL_PROFILES for plan in plans):
return {'state': 'not-managed', 'reason': 'A current branch has an unreviewed cancellation policy'}
if any(plan['changed'] for plan in plans):
return {'state': 'waiting-source', 'reason': 'All current branches must have canonical enrollment'}
try:
for plan in plans:
if source_request(f'repos/{repo}/branches/{plan["branch"]}')['commit']['sha'] != plan['head']:
raise ValueError('Source changed after enrollment inspection')
except (ValueError, KeyError, TypeError) as error:
return {'state': 'unresolved', 'reason': str(error)}
# Preserve the marketing default-branch guard even in mixed eligible profiles.
plan = next((p for p in plans if p['profile'] == 'marketing'), plans[0])
return reconcile(plan, source_request, apply, settings_request)
+74
View File
@@ -0,0 +1,74 @@
"""Discover current enrollment targets without assuming unknown repositories conform."""
import audit_estate
def approved_no_ci(target, request):
"""Recognize only unchanged documentation; executable/data sources still need inspection."""
repo = target['repository']
policy = audit_estate.NO_CI.get(repo)
if policy is None:
return None
head = request(f'repos/{repo}/branches/{target["branch"]}')['commit']['sha']
if head != policy['baseline_sha']:
return None
tree = request(f'repos/{repo}/git/trees/{head}?recursive=1')
if tree.get('truncated') is not False or not isinstance(tree.get('tree'), list):
raise ValueError('Approved no-CI snapshot requires a complete source tree')
paths = {item['path'] for item in tree['tree']}
if not set(policy['required_paths']) <= paths:
raise ValueError('Approved no-CI identity paths are missing')
if any(path in policy['forbidden_paths'] or any(path.startswith(prefix)
for prefix in policy['forbidden_prefixes']) for path in paths):
raise ValueError('Approved no-CI snapshot contains unexpected CI configuration')
documents = {'LICENSE', 'NOTICE', '.gitignore', '.gitattributes', '.gitkeep'}
for item in tree['tree']:
if item.get('type') == 'tree':
continue
if item.get('type') != 'blob' or not (item['path'].endswith(('.md', '.txt')) or item['path'] in documents):
return None
return {**target, 'head': head, 'state': 'approved-no-ci',
'source_kind': 'documentation-only', 'reason': policy['rationale']}
def discover(organization, version, inspect, request, inventory=None):
"""Inspect every active main/develop branch; retain unsupported results explicitly."""
entries = audit_estate.discover_inventory(organization) if inventory is None else inventory
plans, findings = [], []
for entry in entries:
repo = entry['nameWithOwner']
if entry['isArchived']:
findings.append({'repository': repo, 'state': 'archived'})
continue
if repo.lower() == (organization + '/qqq-orb').lower():
findings.append({'repository': repo, 'state': 'owner-bootstrap',
'reason': 'Orb publisher is not its own consumer'})
continue
try:
branches, page = [], 1
while True:
batch = request(f'repos/{repo}/branches?per_page=100&page={page}')
if not isinstance(batch, list) or any(not isinstance(b, dict) or not isinstance(b.get('name'), str) for b in batch):
raise ValueError('Invalid branch inventory')
branches.extend(b['name'] for b in batch)
if len(batch) < 100:
break
page += 1
if len(set(branches)) != len(branches):
raise ValueError('Duplicate branch inventory')
selected = sorted(set(branches) & {'main', 'develop'})
if not selected:
raise ValueError('No current main/develop branch; explicit profile decision required')
except (ValueError, OSError) as error:
findings.append({'repository': repo, 'state': 'unresolved', 'reason': str(error)})
continue
for branch in selected:
target = {'repository': repo, 'branch': branch}
try:
no_ci = approved_no_ci(target, request)
if no_ci is not None:
findings.append(no_ci)
else:
plans.append(inspect(target, version))
except (ValueError, OSError) as error:
findings.append({**target, 'state': 'unresolved', 'reason': str(error)})
return plans, findings
+265
View File
@@ -0,0 +1,265 @@
#!/usr/bin/env python3
"""Batch-enforce observed orb checks; dry-run unless --apply. Never changes source."""
import argparse
import base64
import importlib.util
import json
from pathlib import Path
import re
import subprocess
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('standard', ROOT / 'src/scripts/validate_standard.py')
standard = importlib.util.module_from_spec(spec)
spec.loader.exec_module(standard)
DESIRED = [{'context': name, 'app_id': 18001} for name in ('setup', 'verify')]
PROFILE_GATES = {profile: 'verify' for profile in (
'qbit', 'core', 'frontend-core', 'frontend-material', 'repository-policy', 'node-artifact', 'homebrew-tap', 'application-template', 'marketing', 'voyage')}
PROFILE_GATES.update({'all': 'verify-and-smoke', 'cli': 'test_only',
'app-starter': 'test_only', 'android': 'test-and-build',
'mcp-policy': 'validate'})
PROFILES = set(PROFILE_GATES) | {'frontend-next', 'native-gitops'}
_native_spec = importlib.util.spec_from_file_location('native_next_gates', ROOT / 'tools/native_next_gates.py')
native = importlib.util.module_from_spec(_native_spec)
_native_spec.loader.exec_module(native)
_gitops_spec = importlib.util.spec_from_file_location('native_gitops_gates', ROOT / 'tools/native_gitops_gates.py')
gitops = importlib.util.module_from_spec(_gitops_spec)
_gitops_spec.loader.exec_module(gitops)
_specialist_spec = importlib.util.spec_from_file_location('native_specialist_gates', ROOT / 'tools/native_specialist_gates.py')
specialists = importlib.util.module_from_spec(_specialist_spec)
_specialist_spec.loader.exec_module(specialists)
PROFILES |= specialists.PROFILES
def gates(profile):
if profile in specialists.PROFILES:
return specialists.gates(profile)
if profile == 'native-gitops':
return gitops.gates()
if profile == 'frontend-next':
return native.gates(pull_request=True)
return [{'context': name, 'app_id': 18001}
for name in ('setup', PROFILE_GATES[profile])]
def same_checks(left, right):
"""GitHub may reorder checks; retain exact bindings and duplicate counts."""
return sorted(json.dumps(check, sort_keys=True) for check in left) == sorted(
json.dumps(check, sort_keys=True) for check in right)
def api(path, method='GET', payload=None):
"""Use existing gh authentication; never expose response bodies on failure."""
args = ['gh', 'api', '--method', method, path]
if payload is not None:
args += ['--input', '-']
result = subprocess.run(args, input=None if payload is None else json.dumps(payload),
text=True, encoding='utf-8', capture_output=True, timeout=60)
if result.returncode:
try:
error = json.loads(result.stdout)
except ValueError:
error = {}
if method == 'GET' and path.endswith('/protection') and error.get('status') == '404' and error.get('message') == 'Branch not protected':
return None
raise ValueError('GitHub operation unavailable: ' + method + ' ' + path.split('?')[0])
return json.loads(result.stdout) if result.stdout.strip() else None
def required_checks(before, runs, desired_gates=DESIRED, observed_gates=None):
"""Require successful event-appropriate gates and preserve every PR requirement."""
for desired in (desired_gates if observed_gates is None else observed_gates):
matches = [run for run in runs if run['name'] == desired['context'] and run['app']['id'] == desired['app_id']]
if not matches or max(matches, key=lambda run: run['id'])['conclusion'] != 'success':
raise ValueError('Current branch head has no successful app-bound gate: ' + desired['context'])
prior = (before or {}).get('required_status_checks') or {}
checks = [dict(check) for check in prior.get('checks', [])]
represented = {check['context'] for check in checks}
checks += [{'context': name, 'app_id': -1} for name in prior.get('contexts', []) if name not in represented]
for desired in desired_gates:
matches = [check for check in checks if check['context'] == desired['context']]
if any(check.get('app_id') not in (None, -1, desired['app_id']) for check in matches):
raise ValueError('Existing gate uses a different app: ' + desired['context'])
checks = [check for check in checks if check['context'] != desired['context']]
checks.append(dict(desired))
return {'strict': True, 'checks': checks}
def verified_rulesets(repo, effective, request=api, desired_gates=DESIRED):
"""Recognize active repository rulesets with bound gates and no bypass actors."""
selected = [rule for rule in effective if rule['type'] == 'required_status_checks']
if not selected or any(rule.get('ruleset_source_type') != 'Repository'
or rule.get('ruleset_source') != repo for rule in selected):
raise ValueError('Required rulesets need unsupported source reconciliation')
records = []
for identifier in sorted({rule['ruleset_id'] for rule in selected}):
record = request(f'repos/{repo}/rulesets/{identifier}')
if (record.get('enforcement') != 'active' or record.get('target') != 'branch'
or record.get('source_type') != 'Repository' or record.get('source') != repo
or record.get('bypass_actors') != []):
raise ValueError('Ruleset must be active with no bypass actors')
records.append(record)
requirements = [rule['parameters'] for record in records for rule in record['rules']
if rule['type'] == 'required_status_checks']
for desired in desired_gates:
if not any(check['context'] == desired['context'] and check.get('integration_id') == desired['app_id']
for parameters in requirements for check in parameters['required_status_checks']):
raise ValueError('Ruleset is missing app-bound gate: ' + desired['context'])
# Retain the existing freshness policy: recognition does not add rebuilds or
# weaken any existing scanner, merge, or bypass requirement.
return records, any(parameters.get('strict_required_status_checks_policy', False) for parameters in requirements)
def inspect(repo, branch, version, request=api):
"""Read immutable canonical source, latest check runs, and current protections."""
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', repo) or branch not in ('main', 'develop'):
raise ValueError('Targets must name an exact repository and main/develop branch')
root = 'repos/' + repo
info = request(root)
if info['archived']:
raise ValueError('Archived repository')
prefix = root + '/branches/' + branch
head = request(prefix)['commit']['sha']
if repo in specialists.DEFINITIONS:
profile, _ = specialists.validate(repo, head, branch, request)
elif repo in gitops.REPOSITORIES:
gitops.validate(repo, head, branch, request, standard.load_yaml)
profile = 'native-gitops'
else:
source = []
for path in ('.circleci/config.yml', '.qqq-ci.yml'):
item = request(root + '/contents/' + quote(path, safe='/') + '?ref=' + head)
if item.get('encoding') != 'base64' or item.get('type') != 'file':
raise ValueError('Canonical declarations must be regular files')
source.append(base64.b64decode(item['content'], validate=False).decode('utf-8'))
standard.validate(*source, version)
profile = standard.load_yaml(source[1])['profile']
if profile not in PROFILES:
raise ValueError('Profile has no supported shared branch gates')
desired_gates = gates(profile)
observed_gates = desired_gates
if profile == 'frontend-next':
native.validate(repo, head, branch, request, standard.load_yaml)
observed_gates = native.gates()
rules = request(root + '/rules/branches/' + branch)
rulesets, ruleset_strict = verified_rulesets(repo, rules, request, desired_gates) if rules else ([], False)
before = request(prefix + '/protection')
restrictions = (before or {}).get('restrictions')
missing_status_section = before is not None and before.get('required_status_checks') is None
empty_push_allowlist = (restrictions is not None
and not any(restrictions.get(kind) for kind in ('users', 'teams', 'apps'))
and not (before or {}).get('enforce_admins', {}).get('enabled'))
# GitHub cannot PATCH a missing status-check subresource. An additive ruleset
# preserves the existing signing, review, history and access policies.
use_ruleset = not rulesets and (missing_status_section or empty_push_allowlist)
runs = []
page = 1
while True:
batch = request(root + '/commits/' + head + '/check-runs?filter=latest&per_page=100&page=' + str(page))['check_runs']
runs += batch
if len(batch) < 100:
break
page += 1
desired = required_checks(before, runs, desired_gates, observed_gates)
if use_ruleset:
return {'repository': repo, 'branch': branch, 'head': head, 'before': before, 'gates': desired_gates,
'required_status_checks': {'strict': False, 'checks': desired_gates},
'changed': True, 'protection_mode': 'create-ruleset'}
if rulesets:
desired['strict'] = ruleset_strict or bool(((before or {}).get('required_status_checks') or {}).get('strict'))
return {'repository': repo, 'branch': branch, 'head': head, 'before': before, 'gates': desired_gates,
'required_status_checks': desired, 'changed': False, 'protection_mode': 'rulesets',
'effective_rules': rules, 'rulesets': rulesets}
current = (before or {}).get('required_status_checks') or {}
ready = (current.get('strict') is True and same_checks(current.get('checks', []), desired['checks'])
and (before or {}).get('enforce_admins', {}).get('enabled') is True)
return {'repository': repo, 'branch': branch, 'head': head, 'before': before, 'gates': desired_gates,
'required_status_checks': desired, 'changed': not ready}
def enforce(plan, request=api):
"""Recheck drift, use narrow updates, and verify preservation of other settings."""
desired_gates = plan.get('gates', DESIRED)
root = 'repos/' + plan['repository']
prefix = root + '/branches/' + plan['branch']
if request(prefix)['commit']['sha'] != plan['head'] or request(prefix + '/protection') != plan['before']:
raise ValueError('Branch or protection changed after preflight')
rules = request(root + '/rules/branches/' + plan['branch'])
if plan.get('protection_mode') == 'rulesets':
if rules != plan['effective_rules'] or verified_rulesets(plan['repository'], rules, request, desired_gates)[0] != plan['rulesets']:
raise ValueError('Ruleset changed after preflight')
return
if rules:
raise ValueError('Ruleset changed after preflight')
if plan.get('protection_mode') == 'create-ruleset':
name = 'QQQ automated verification: ' + plan['branch']
page = 1
while True:
existing = request(root + '/rulesets?per_page=100&page=' + str(page))
if any(record['name'] == name for record in existing):
raise ValueError('Named ruleset already exists; reconcile its scope explicitly')
if len(existing) < 100:
break
page += 1
request(root + '/rulesets', 'POST', {
'name': name, 'target': 'branch', 'enforcement': 'active', 'bypass_actors': [],
'conditions': {'ref_name': {'include': ['refs/heads/' + plan['branch']], 'exclude': []}},
'rules': [{'type': 'required_status_checks', 'parameters': {
'strict_required_status_checks_policy': False, 'do_not_enforce_on_create': False,
'required_status_checks': [{'context': gate['context'], 'integration_id': gate['app_id']}
for gate in desired_gates]}}]})
effective = request(root + '/rules/branches/' + plan['branch'])
verified_rulesets(plan['repository'], effective, request, desired_gates)
if request(prefix + '/protection') != plan['before']:
raise ValueError('Classic access policy changed during ruleset creation')
return
if not plan['changed']:
return
before = plan['before']
if before is None:
request(prefix + '/protection', 'PUT', {
'required_status_checks': plan['required_status_checks'], 'enforce_admins': True,
'required_pull_request_reviews': None, 'restrictions': None})
else:
request(prefix + '/protection/required_status_checks', 'PATCH', plan['required_status_checks'])
if not before['enforce_admins']['enabled']:
request(prefix + '/protection/enforce_admins', 'POST')
after = request(prefix + '/protection')
actual = after['required_status_checks']
if not actual['strict'] or not same_checks(actual['checks'], plan['required_status_checks']['checks']) or not after['enforce_admins']['enabled']:
raise ValueError('Protection readback did not match requested gates')
if before:
for key, value in before.items():
if key not in ('required_status_checks', 'enforce_admins') and after.get(key) != value:
raise ValueError('Unrelated protection changed: ' + key)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--targets', type=Path, required=True, help='JSON list of {repository, branch}')
parser.add_argument('--orb-version', required=True)
parser.add_argument('--apply', action='store_true')
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
targets = json.loads(args.targets.read_text(encoding='utf-8'))
if not isinstance(targets, list) or not targets:
raise ValueError('A nonempty explicit target list is required')
if len({(row['repository'], row['branch']) for row in targets}) != len(targets):
raise ValueError('Duplicate branch target')
# Resolve the entire batch before any mutations. Failures never trigger rollback
# that would remove successful protections; rerunning converges idempotently.
plans = [inspect(row['repository'], row['branch'], args.orb_version) for row in targets]
args.output.write_text(json.dumps({'state': 'planned', 'plans': plans}, indent=2), encoding='utf-8')
if args.apply:
for plan in plans:
enforce(plan)
plan['verified'] = True
args.output.write_text(json.dumps({'state': 'applying', 'plans': plans}, indent=2), encoding='utf-8')
args.output.write_text(json.dumps({'state': 'verified', 'plans': plans}, indent=2), encoding='utf-8')
print(json.dumps({'targets': len(plans), 'changed': sum(plan['changed'] for plan in plans), 'applied': args.apply}))
if __name__ == '__main__':
main()
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Enroll a batch of audited consumers; preview by default, write with --write.
Existing canonical profiles retain their manifests. Legacy QBits use the shared
policy inference. Unknown orchestration is rejected before any checkout changes.
"""
import argparse
import json
from pathlib import Path
import re
import tempfile
import yaml
import rollout_version as rollout
import standardize_qbit as qbit
def declaration(root, relative):
"""Reject redirected declarations, including symlinked parent directories."""
path = root / relative
current = path
while current != root:
if current.is_symlink():
raise ValueError('CI declarations must not use symlinks')
current = current.parent
if not path.resolve().is_relative_to(root):
raise ValueError('CI declarations must remain inside the checkout')
return path
def plan(target, version):
"""Preserve explicit publication policy and validate generated declarations."""
if not isinstance(target, dict) or set(target) != {'checkout', 'default_branch'}:
raise ValueError('Each target requires checkout and observed default_branch')
if target['default_branch'] not in ('main', 'develop'):
raise ValueError('Unsupported default branch')
root = Path(target['checkout']).resolve(strict=True)
config = declaration(root, '.circleci/config.yml')
manifest = declaration(root, '.qqq-ci.yml')
if manifest.exists():
data = rollout.standard.load_yaml(manifest.read_text(encoding='utf-8'))
if not isinstance(data, dict) or data.get('default_branch') != target['default_branch']:
raise ValueError('Observed default branch differs from manifest')
return {**rollout.plan(root, version), 'enrollment': False}
original = config.read_bytes()
data = qbit.infer_manifest(rollout.standard.load_yaml(original.decode('utf-8')),
version, target['default_branch'])
caller = rollout.standard.canonical_caller(data['profile'], version,
release_tag_policy=data['release_tag_policy'], publish_feature=data['publish'].get('feature', False))
config_raw = yaml.safe_dump(caller, sort_keys=False)
manifest_raw = yaml.safe_dump(data, sort_keys=False)
rollout.standard.validate(config_raw, manifest_raw, version)
with tempfile.TemporaryDirectory() as directory:
temporary_manifest = Path(directory) / 'manifest.yml'
temporary_manifest.write_text(manifest_raw, encoding='utf-8')
rollout.pipeline.load_manifest(temporary_manifest, version)
return {'checkout': str(root), 'profile': data['profile'], 'from': None,
'to': version, 'enrollment': True,
'files': [(config, original, config_raw.encode('utf-8')),
(manifest, None, manifest_raw.encode('utf-8'))]}
def enroll(targets, version, write=False):
"""Validate the whole batch before writing; repeat applications are no-ops."""
if not isinstance(version, str) or not re.fullmatch(r'\d+\.\d+(?:\.\d+)?', version):
raise ValueError('Enrollment requires a stable minor track or exact patch')
if not isinstance(targets, list) or not targets:
raise ValueError('A nonempty target list is required')
plans = [plan(target, version) for target in targets]
if len({item['checkout'] for item in plans}) != len(plans):
raise ValueError('Each checkout may appear only once')
if write:
for item in plans:
for path, original, replacement in item['files']:
declaration(Path(item['checkout']), path.relative_to(item['checkout']))
current = path.read_bytes() if path.exists() else None
if current != original:
raise ValueError('Declaration changed after preflight')
for item in plans:
for path, original, replacement in item['files']:
if replacement != original:
path.write_bytes(replacement)
return [{**{key: value for key, value in item.items() if key != 'files'},
'changed': any(old != new for _, old, new in item['files']),
'written': write} for item in plans]
def main():
"""Read one fleet target file and emit an auditable result."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('targets', type=Path)
parser.add_argument('--orb-version', required=True)
parser.add_argument('--write', action='store_true')
args = parser.parse_args()
print(json.dumps(enroll(json.loads(args.targets.read_text(encoding='utf-8')),
args.orb_version, args.write), indent=2))
if __name__ == '__main__':
main()
+85
View File
@@ -0,0 +1,85 @@
"""Qualify signed enrollment PRs and enforce only successful current branch heads."""
import json
import enforce_orb_checks as enforcement
import reconcile_enrollment as remote
def qualification(repo, head, profile='qbit'):
"""Require profile-specific app-bound gates and every advertised latest check/status."""
checks, page = [], 1
while True:
batch = remote.api(f'repos/{repo}/commits/{head}/check-runs?filter=latest&per_page=100&page={page}')['check_runs']
checks.extend(batch)
if len(batch) < 100:
break
page += 1
reasons = []
for gate in enforcement.gates(profile):
name = gate['context']
found = [check for check in checks if check['name'] == name and check['app']['id'] == gate['app_id']]
if not found or max(found, key=lambda check: check['id'])['conclusion'] != 'success':
reasons.append(name)
for check in checks:
if check['status'] != 'completed' or check['conclusion'] not in ('success', 'neutral', 'skipped'):
reasons.append(check['name'])
page = 1
while True:
batch = remote.api(f'repos/{repo}/commits/{head}/status?per_page=100&page={page}')['statuses']
reasons.extend(status['context'] for status in batch if status['state'] != 'success')
if len(batch) < 100:
break
page += 1
return sorted(set(reasons))
def merge_ready(plan, result):
"""Normal exact-head squash merge only; no administrative or force bypass."""
if plan['profile'] not in enforcement.PROFILES:
return {'state': 'unsupported-gates', 'profile': plan['profile']}
if result['state'] == 'unchanged':
return {'state': 'unchanged'}
repo, head = plan['repository'], result['head']
remote.verify_submission(plan, head)
pr = json.loads(remote.command(['gh', 'pr', 'view', result['url'], '--repo', repo,
'--json', 'number,state,headRefOid,baseRefOid,baseRefName,mergeCommit']))
if pr['headRefOid'] != head or pr['baseRefName'] != plan['branch']:
raise ValueError('PR differs from enrollment target')
if pr['state'] == 'CLOSED':
return {'state': 'closed', 'url': result['url']}
if pr['state'] != 'MERGED':
if pr['baseRefOid'] != plan['head'] or remote.api(f'repos/{repo}/branches/{plan["branch"]}')['commit']['sha'] != plan['head']:
return {'state': 'stale-base', 'url': result['url']}
if plan['profile'] in enforcement.specialists.PROFILES:
enforcement.specialists.validate(repo, head, plan['branch'], remote.api)
if plan['profile'] == 'native-gitops':
enforcement.gitops.validate(repo, head, plan['branch'], remote.api, enforcement.standard.load_yaml)
if plan['profile'] == 'frontend-next':
enforcement.native.validate(repo, head, plan['branch'], remote.api, enforcement.standard.load_yaml)
pending = qualification(repo, head, plan['profile'])
if pending:
return {'state': 'waiting-checks', 'checks': pending, 'url': result['url']}
remote.command(['gh', 'pr', 'merge', str(pr['number']), '--repo', repo, '--squash', '--match-head-commit', head])
pr = json.loads(remote.command(['gh', 'pr', 'view', result['url'], '--repo', repo,
'--json', 'state,mergeCommit']))
if pr['state'] != 'MERGED':
raise ValueError('PR merge was not confirmed')
merged = pr['mergeCommit']['oid']
expected = remote.api(f'repos/{repo}/commits/{head}')['commit']['tree']['sha']
actual = remote.api(f'repos/{repo}/commits/{merged}')['commit']
if not actual['verification']['verified'] or actual['tree']['sha'] != expected:
raise ValueError('Merged signature or source tree differs from qualified source')
return {'state': 'merged', 'url': result['url'], 'head': head, 'merge': merged}
def enforce_current(plan):
"""Use shared narrow enforcement after the actual branch head passes its gates."""
if plan['profile'] not in enforcement.PROFILES:
return {'state': 'unsupported-gates', 'profile': plan['profile']}
try:
current = enforcement.inspect(plan['repository'], plan['branch'], plan['version'])
except ValueError as error:
return {'state': 'waiting-enforcement', 'reason': str(error)}
enforcement.enforce(current)
return {'state': 'enforced', 'head': current['head'], 'changed': current['changed'],
'protection_mode': current.get('protection_mode', 'classic')}
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
# Ubuntu Jammy ships gh 2.4, which lacks API --slurp and modern merge guards.
# Pin the official amd64 release and its GitHub release asset SHA-256.
version=2.103.0
checksum=fdd768eb70f6409f80fcfa9f3a1c0adf0fc98d827ab3ce0bed2ac22762c5d786
archive=$(mktemp)
binary=$(mktemp)
trap 'rm -f "$archive" "$binary"' EXIT
curl --fail --silent --show-error --location --retry 3 \
"https://github.com/cli/cli/releases/download/v${version}/gh_${version}_linux_amd64.tar.gz" -o "$archive"
printf '%s %s\n' "$checksum" "$archive" | sha256sum --check --status
tar -xOzf "$archive" "gh_${version}_linux_amd64/bin/gh" > "$binary"
sudo install -m 0755 "$binary" /usr/local/bin/gh
gh --version
# Drain help output: grep -q can SIGPIPE gh under pipefail.
gh api --help | grep -- --slurp >/dev/null
gh pr merge --help | grep -- --match-head-commit >/dev/null
+51
View File
@@ -0,0 +1,51 @@
"""Recognize approved GitOps repositories through their shared immutable worker."""
import base64
import importlib.util
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('gitops_bridge', ROOT / 'src/scripts/generate_auxiliary_workflow.py')
bridge = importlib.util.module_from_spec(spec)
spec.loader.exec_module(bridge)
DEFINITION = bridge.BRIDGES['gitops']
REPOSITORIES = {DEFINITION['repository'], *DEFINITION.get('additional_repositories', [])}
def gates():
return [{'context': 'gitops / validate', 'app_id': 15368}]
def validate(repo, head, branch, request, load_yaml):
if repo not in REPOSITORIES or branch != 'main':
raise ValueError('GitOps recognition requires an approved repository on main only')
def content(owner, path, ref):
item = request(f'repos/{owner}/contents/{path}?ref={ref}')
if item.get('type') != 'file' or item.get('encoding') != 'base64':
raise ValueError('GitOps workflow must be a regular file')
return base64.b64decode(item['content']).decode('utf-8').replace('\r\n', '\n')
path = DEFINITION['path']
caller = load_yaml(content(repo, path, head))
try:
pin = caller['jobs']['gitops']['uses'].rsplit('@', 1)[1]
expected = bridge.canonical('gitops', pin)
except (KeyError, TypeError, IndexError, ValueError, AttributeError):
raise ValueError('GitOps caller has no immutable shared worker pin') from None
if caller != expected:
raise ValueError('GitOps caller differs from the canonical shared bridge')
tree = request(f'repos/{repo}/git/trees/{head}?recursive=1')
if tree.get('truncated') is not False or not isinstance(tree.get('tree'), list):
raise ValueError('GitOps recognition requires the complete source tree')
for entry in tree['tree']:
name = entry['path']
if name == '.circleci/config.yml' or (name.startswith('.github/workflows/')
and name.endswith(('.yml', '.yaml')) and name != path):
raise ValueError('GitOps repository has additional orchestration: ' + name)
commit = request('repos/QRun-IO/qqq-orb/commits/' + pin)
if not commit['commit']['verification']['verified']:
raise ValueError('GitOps worker commit is not verified')
worker = '.github/workflows/gitops.yml'
if content('QRun-IO/qqq-orb', worker, pin) != (ROOT / worker).read_text(encoding='utf-8'):
raise ValueError('Pinned GitOps worker differs from the supported contract')
return pin
+51
View File
@@ -0,0 +1,51 @@
"""Validate the canonical native bridge and its immutable shared worker contract."""
import base64
import importlib.util
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('next_bridge', ROOT / 'src/scripts/generate_next_workflow.py')
bridge = importlib.util.module_from_spec(spec)
spec.loader.exec_module(bridge)
MAIN_GATES = [
'ci / Typecheck, lint, unit tests and coverage',
'ci / Mocked e2e (Playwright, chromium)',
'ci / Collaboration e2e (MSW; chromium, firefox, webkit, mobile, tablet)',
'ci / Bundle budget (static export)', 'ci / Storybook build',
'acceptance / acceptance gate',
]
PR_GATES = MAIN_GATES + ['dashboard-image / build (amd64, ubuntu-24.04)',
'dashboard-image / build (arm64, ubuntu-24.04-arm)']
def gates(pull_request=False):
return [{'context': name, 'app_id': 15368} for name in (PR_GATES if pull_request else MAIN_GATES)]
def validate(repo, head, branch, request, load_yaml):
"""Only main has a push trigger; require exact caller and reviewed worker bytes."""
if branch != 'main':
raise ValueError('Next native branch verification supports main only')
def content(owner, path, ref):
item = request(f'repos/{owner}/contents/{path}?ref={ref}')
if item.get('type') != 'file' or item.get('encoding') != 'base64':
raise ValueError('Native workflow must be a regular file')
return base64.b64decode(item['content']).decode('utf-8').replace('\r\n', '\n')
caller = load_yaml(content(repo, '.github/workflows/ci.yml', head))
try:
pin = caller['jobs']['ci']['uses'].rsplit('@', 1)[1]
expected = bridge.canonical_next(pin)
except (KeyError, TypeError, IndexError, ValueError):
raise ValueError('Native caller has no valid immutable worker pin') from None
if caller != expected:
raise ValueError('Native caller differs from the canonical shared bridge')
commit = request('repos/QRun-IO/qqq-orb/commits/' + pin)
if not commit['commit']['verification']['verified']:
raise ValueError('Shared native worker commit is not verified')
for name in ('next-ci.yml', 'next-acceptance.yml', 'next-dashboard-image.yml'):
path = '.github/workflows/' + name
if content('QRun-IO/qqq-orb', path, pin) != (ROOT / path).read_text(encoding='utf-8'):
raise ValueError('Pinned native worker differs from the supported contract: ' + name)
return pin
+115
View File
@@ -0,0 +1,115 @@
"""Recognize reviewed native consumers and their shared immutable orb workers."""
import base64
import importlib.util
import re
from pathlib import Path
import yaml
ROOT = Path(__file__).resolve().parents[1]
def module(name):
spec = importlib.util.spec_from_file_location(name, ROOT / 'src/scripts' / (name + '.py'))
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
auxiliary = module('generate_auxiliary_workflow')
qctl = module('generate_qctl_workflow')
standard = module('validate_standard')
class WorkflowLoader(standard.UniqueLoader):
# GitHub uses YAML 1.2: unquoted "on" is an event key, not a boolean.
yaml_implicit_resolvers = {
key: [(tag, pattern) for tag, pattern in values if tag != 'tag:yaml.org,2002:bool']
for key, values in standard.UniqueLoader.yaml_implicit_resolvers.items()
}
WorkflowLoader.add_implicit_resolver('tag:yaml.org,2002:bool', re.compile(r'^(true|false)$', re.I), list('tTfF'))
def load_workflow(raw):
try:
return yaml.load(raw, Loader=WorkflowLoader)
except yaml.YAMLError as error:
raise ValueError('Invalid native workflow YAML') from error
# Only observed, mandatory verification gates; release-only jobs are not PR gates.
DEFINITIONS = {
'QRun-IO/qctl': ('qctl', ('main', 'develop'), ('qctl',),
('native / test',)),
'QRun-IO/.github': ('native-workflow-lint', ('main',), ('github-workflow-lint',),
('actionlint / actionlint',)),
'QRun-IO/qqq-business-platform': ('native-business', ('main',), ('business-db', 'business-e2e'),
('validate / empty-database-migration', 'validate / Deployment gate / E2E passed')),
'QRun-IO/qqq-mcp-rag': ('native-mcp', ('main',), ('mcp-rag',),
('validate / Build and Test',)),
'QRun-IO/qqq-app-developer-intellij-plugin': ('intellij-plugin', ('main',), ('intellij-plugin',),
('plugin / build',)),
}
PROFILES = {definition[0] for definition in DEFINITIONS.values()}
def gates(profile):
names = next(definition[3] for definition in DEFINITIONS.values() if definition[0] == profile)
return [{'context': name, 'app_id': 15368} for name in names]
def caller(kind, pin):
if kind == 'qctl':
return '.github/workflows/build.yml', load_workflow(qctl.generate(pin))
return auxiliary.BRIDGES[kind]['path'], auxiliary.canonical(kind, pin)
def validate(repo, head, branch, request):
if repo not in DEFINITIONS or branch not in DEFINITIONS[repo][1]:
raise ValueError('Native recognition requires an approved repository and branch')
profile, _, kinds, _ = DEFINITIONS[repo]
def content(owner, path, ref):
item = request(f'repos/{owner}/contents/{path}?ref={ref}')
if item.get('type') != 'file' or item.get('encoding') != 'base64':
raise ValueError('Native workflow must be a regular file')
return base64.b64decode(item['content']).decode('utf-8').replace('\r\n', '\n')
paths, pins, verified = set(), {}, set()
for kind in kinds:
path, _ = caller(kind, '0' * 40)
actual = load_workflow(content(repo, path, head))
try:
pin = next(iter(actual['jobs'].values()))['uses'].rsplit('@', 1)[1]
_, expected = caller(kind, pin)
except (KeyError, TypeError, IndexError, ValueError, AttributeError, StopIteration):
raise ValueError('Native caller has no immutable orb pin') from None
if actual != expected:
raise ValueError('Native caller differs from the canonical shared bridge')
if pin not in verified:
commit = request('repos/QRun-IO/qqq-orb/commits/' + pin)
if not commit['commit']['verification']['verified']:
raise ValueError('Native worker commit is not verified')
verified.add(pin)
for job in expected['jobs'].values():
worker = job['uses'].split('@')[0].removeprefix('QRun-IO/qqq-orb/')
if content('QRun-IO/qqq-orb', worker, pin) != (ROOT / worker).read_text(encoding='utf-8'):
raise ValueError('Pinned native worker differs from the supported contract')
paths.add(path)
pins[path] = pin
tree = request(f'repos/{repo}/git/trees/{head}?recursive=1')
if tree.get('truncated') is not False or not isinstance(tree.get('tree'), list):
raise ValueError('Native recognition requires the complete source tree')
entries = {entry['path']: entry for entry in tree['tree']}
for path in paths:
entry = entries.get(path, {})
if entry.get('type') != 'blob' or entry.get('mode') not in ('100644', '100755'):
raise ValueError('Native caller is missing or is not a regular source file')
for entry in tree['tree']:
path = entry['path']
if path == '.circleci/config.yml' or (path.startswith('.github/workflows/')
and path.endswith(('.yml', '.yaml')) and path not in paths):
raise ValueError('Native repository has additional orchestration: ' + path)
return profile, pins
-80
View File
@@ -1,68 +1,4 @@
{
"QRun-IO/new-qqq-application-template": {
"baseline_sha": "730a836a666535a361927d83f15720e91eb71541",
"required_paths": [
"README.md"
],
"forbidden_prefixes": [
".circleci/",
".github/workflows/"
],
"forbidden_paths": [
".qqq-ci.yml",
"Jenkinsfile",
".gitlab-ci.yml"
],
"rationale": "Template source; core generated-consumer acceptance owns validation."
},
"QRun-IO/voyage-cd": {
"baseline_sha": "f8734e2d30b59af4909bd0a4c39fa6c9d6981d61",
"required_paths": [
"README.md"
],
"forbidden_prefixes": [
".circleci/",
".github/workflows/"
],
"forbidden_paths": [
".qqq-ci.yml",
"Jenkinsfile",
".gitlab-ci.yml"
],
"rationale": "GitOps deployment declarations; audited repository has no CI."
},
"QRun-IO/qqq-templates-hub": {
"baseline_sha": "bd591168c7200ce40a3535f2052b8327056e82e0",
"required_paths": [
"templates.yaml"
],
"forbidden_prefixes": [
".circleci/",
".github/workflows/"
],
"forbidden_paths": [
".qqq-ci.yml",
"Jenkinsfile",
".gitlab-ci.yml"
],
"rationale": "Template catalog, no standalone CI in approved snapshot."
},
"QRun-IO/qqq-meta-manager": {
"baseline_sha": "da17eb306bf1587cbf98a1555499e9b27f4caa50",
"required_paths": [
"README.md"
],
"forbidden_prefixes": [
".circleci/",
".github/workflows/"
],
"forbidden_paths": [
".qqq-ci.yml",
"Jenkinsfile",
".gitlab-ci.yml"
],
"rationale": "Metadata and automation knowledge repository; no registered CI entrypoint."
},
"QRun-IO/qqq-maven-registry": {
"baseline_sha": "134576e4e701984635105f97c8f52aa1e27205b2",
"required_paths": [
@@ -95,22 +31,6 @@
],
"rationale": "Component placeholder documentation with no executable CI."
},
"QRun-IO/homebrew-qctl": {
"baseline_sha": "8dc185d2172c9cbf14dd5b7f83caf350430a632b",
"required_paths": [
"README.md"
],
"forbidden_prefixes": [
".circleci/",
".github/workflows/"
],
"forbidden_paths": [
".qqq-ci.yml",
"Jenkinsfile",
".gitlab-ci.yml"
],
"rationale": "Distribution tap; qctl publication owns formula updates, no local CI."
},
"QRun-IO/.github-private": {
"baseline_sha": "3eb51cfc419398b2d4f1f6e5ebdeb17f3469ef8a",
"required_paths": [
+240
View File
@@ -0,0 +1,240 @@
#!/usr/bin/env python3
"""Plan remote enrollment and submit signed, repeatable PRs with --apply."""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
import enroll_consumers
import native_gitops_gates as gitops
import native_specialist_gates as specialists
import yaml
PATHS = ('.circleci/config.yml', '.qqq-ci.yml')
def command(args, cwd=None):
"""Use existing credentials and signing configuration without interactive prompts."""
env = dict(os.environ, GIT_TERMINAL_PROMPT='0')
result = subprocess.run(args, cwd=cwd, env=env, capture_output=True,
text=True, encoding='utf-8', timeout=120)
if result.returncode:
raise ValueError('Command failed: ' + args[0])
return result.stdout.strip()
def api(path, missing=False):
"""Only an explicit 404 is treated as absence; other API failures stop work."""
result = subprocess.run(['gh', 'api', path], capture_output=True,
text=True, encoding='utf-8', timeout=60)
try:
data = json.loads(result.stdout)
except ValueError:
raise ValueError('Invalid GitHub response') from None
if result.returncode:
if missing and str(data.get('status')) == '404':
return None
raise ValueError('GitHub read unavailable: ' + path.split('?')[0])
return data
def content(repo, path, head):
"""Read a regular declaration at an immutable commit, never at a moving branch."""
item = api(f'repos/{repo}/contents/{path}?ref={head}', missing=True)
if item is None:
return None
if item.get('type') != 'file' or item.get('encoding') != 'base64':
raise ValueError('Declaration is not a regular file')
return base64.b64decode(item['content'])
def mutation(path, payload):
"""Use the existing gh identity; never print credentials or response bodies."""
result = subprocess.run(['gh', 'api', path, '--method', 'POST', '--input', '-'],
input=json.dumps(payload), capture_output=True,
text=True, encoding='utf-8', timeout=60)
if result.returncode:
raise ValueError('GitHub mutation failed; inspect remote state before retrying')
try:
data = json.loads(result.stdout)
except ValueError:
raise ValueError('Invalid GitHub mutation response') from None
if not isinstance(data, dict) or data.get('errors'):
raise ValueError('GitHub mutation did not succeed')
return data
def signed_api_commit(plan, ref):
"""Resume a base-only branch; append atomically without local Git/SSH keys."""
repo, branch, base = plan['repository'], plan['automation_branch'], plan['head']
if ref is None:
mutation(f'repos/{repo}/git/refs', {'ref': 'refs/heads/' + branch, 'sha': base})
elif ref['object']['sha'] != base:
return ref['object']['sha']
if api(f'repos/{repo}/branches/{plan["branch"]}')['commit']['sha'] != base:
raise ValueError('Target branch moved before submission')
additions = [{'path': path, 'contents': base64.b64encode(plan['replacements'][path]).decode('ascii')}
for path in PATHS if plan['originals'][path] != plan['replacements'][path]]
result = mutation('graphql', {
'query': 'mutation($input: CreateCommitOnBranchInput!) { createCommitOnBranch(input: $input) { commit { oid } } }',
'variables': {'input': {
'branch': {'repositoryNameWithOwner': repo, 'branchName': branch},
'expectedHeadOid': base,
'message': {'headline': 'ci: enroll in the shared QQQ orb',
'body': 'Co-Authored-By: Codex <noreply@openai.com>'},
'fileChanges': {'additions': additions}}}})
try:
head = result['data']['createCommitOnBranch']['commit']['oid']
except (KeyError, TypeError):
raise ValueError('GitHub commit response is incomplete') from None
if not isinstance(head, str) or not re.fullmatch(r'[0-9a-f]{40}', head):
raise ValueError('GitHub commit response has no valid SHA')
return head
def inspect(target, version):
"""Resolve observed repository identity and reuse the shared enrollment planner."""
if not isinstance(target, dict) or set(target) != {'repository', 'branch'}:
raise ValueError('Each target requires repository and branch')
repo, branch = target['repository'], target['branch']
if not isinstance(repo, str) or not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', repo):
raise ValueError('Invalid repository')
if branch not in ('main', 'develop'):
raise ValueError('Enrollment targets current main/develop only')
info = api('repos/' + repo)
if info['archived']:
raise ValueError('Archived repository')
head = api(f'repos/{repo}/branches/{branch}')['commit']['sha']
if repo in specialists.DEFINITIONS:
profile, pins = specialists.validate(repo, head, branch, api)
return {**target, 'head': head, 'profile': profile, 'version': version,
'changed': False, 'worker_pins': pins}
if repo in gitops.REPOSITORIES:
pin = gitops.validate(repo, head, branch, api, yaml.safe_load)
return {**target, 'head': head, 'profile': 'native-gitops', 'version': version,
'changed': False, 'worker_pin': pin}
originals = {path: content(repo, path, head) for path in PATHS}
if originals[PATHS[0]] is None:
raise ValueError('No recognized CircleCI entrypoint')
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / '.circleci').mkdir()
for path, data in originals.items():
if data is not None:
(root / path).write_bytes(data)
plan = enroll_consumers.plan({'checkout': str(root), 'default_branch': info['default_branch']}, version)
replacements = {str(path.relative_to(root)).replace('\\', '/'): new for path, _, new in plan['files']}
digest = hashlib.sha256(head.encode() + b''.join(replacements[path] for path in PATHS)).hexdigest()[:20]
return {**target, 'head': head, 'originals': originals, 'replacements': replacements,
'profile': plan['profile'], 'version': version,
'changed': any(originals[path] != replacements[path] for path in PATHS),
'automation_branch': f'automation/qqq-enroll-{branch}-{digest}'}
def verify_submission(plan, head):
"""Accept only a signed, one-parent commit with exactly the planned changes."""
repo = plan['repository']
commit = api(f'repos/{repo}/commits/{head}')
expected = {path for path in PATHS if plan['originals'][path] != plan['replacements'][path]}
if (not commit['commit']['verification']['verified']
or [parent['sha'] for parent in commit['parents']] != [plan['head']]
or {item['filename'] for item in commit['files']} != expected):
raise ValueError('Existing automation branch differs from the signed plan')
for path in PATHS:
if content(repo, path, head) != plan['replacements'][path]:
raise ValueError('Submitted declaration differs from plan')
def apply(plan):
"""Never force push; reuse matching submissions after interrupted executions."""
if not plan['changed']:
return {'state': 'unchanged'}
repo, branch = plan['repository'], plan['automation_branch']
if api(f'repos/{repo}/branches/{plan["branch"]}')['commit']['sha'] != plan['head']:
raise ValueError('Target branch changed after preflight')
ref = api(f'repos/{repo}/git/ref/heads/{branch}', missing=True)
head = signed_api_commit(plan, ref)
verify_submission(plan, head)
pulls = api(f'repos/{repo}/pulls?state=all&head={repo.split("/")[0]}:{branch}&base={plan["branch"]}')
if pulls:
if len(pulls) != 1 or pulls[0]['head']['sha'] != head:
raise ValueError('Ambiguous existing enrollment PR')
return {'state': 'existing-pr', 'head': head, 'url': pulls[0]['html_url']}
body = ('Uses the shared orb enrollment converter and preserves existing publication policy. '
'Only the canonical caller and manifest change. Exact-head hosted checks must pass '
'before merge; branch enforcement follows successful qualification.\n\n'
'Source base: ' + plan['head'])
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'body.md'
path.write_text(body, encoding='utf-8')
url = command(['gh', 'pr', 'create', '--repo', repo, '--base', plan['branch'], '--head', branch,
'--title', 'ci: enroll in the shared QQQ orb', '--body-file', str(path)])
return {'state': 'submitted', 'head': head, 'url': url}
def main():
"""Preflight every explicit target before mutations and save resumable results."""
parser = argparse.ArgumentParser(description=__doc__)
source = parser.add_mutually_exclusive_group(required=True)
source.add_argument('--targets', type=Path)
source.add_argument('--organization')
parser.add_argument('--orb-version', required=True)
parser.add_argument('--apply', action='store_true')
parser.add_argument('--merge-ready', action='store_true')
parser.add_argument('--enforce', action='store_true')
parser.add_argument('--circle-settings', action='store_true')
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
if (args.merge_ready or args.enforce) and not args.apply:
parser.error('--merge-ready and --enforce require --apply')
if not re.fullmatch(r'\d+\.\d+(?:\.\d+)?', args.orb_version):
raise ValueError('A stable minor track or exact patch is required')
findings = []
if args.organization:
from discover_enrollment import discover
plans, findings = discover(args.organization, args.orb_version, inspect, api)
else:
targets = json.loads(args.targets.read_text(encoding='utf-8'))
if not isinstance(targets, list) or not targets:
raise ValueError('A nonempty target list is required')
plans = [inspect(target, args.orb_version) for target in targets]
if len({(p['repository'].lower(), p['branch']) for p in plans}) != len(plans):
raise ValueError('Duplicate target')
rows = [{key: value for key, value in p.items() if key not in ('originals', 'replacements')} for p in plans]
report = findings + rows
args.output.write_text(json.dumps(report, indent=2), encoding='utf-8')
if args.apply:
for plan, row in zip(plans, rows):
row['result'] = apply(plan)
args.output.write_text(json.dumps(report, indent=2), encoding='utf-8')
if args.merge_ready or args.enforce:
import finish_enrollment
if args.merge_ready:
row['qualification'] = finish_enrollment.merge_ready(plan, row['result'])
args.output.write_text(json.dumps(report, indent=2), encoding='utf-8')
if args.enforce:
row['enforcement'] = finish_enrollment.enforce_current(plan)
args.output.write_text(json.dumps(report, indent=2), encoding='utf-8')
if args.circle_settings:
import circle_project_settings
settings = []
for repo in sorted({plan['repository'] for plan in plans}):
branches = [plan for plan in plans if plan['repository'] == repo]
settings.append({'repository': repo,
'profiles': sorted({plan['profile'] for plan in branches}),
**circle_project_settings.reconcile_repository(
branches, findings, api, apply=args.apply)})
args.output.with_suffix('.circle-settings.json').write_text(
json.dumps(settings, indent=2), encoding='utf-8')
print(json.dumps({'targets': len(plans), 'changed': sum(p['changed'] for p in plans),
'unresolved': sum(row['state'] == 'unresolved' for row in findings),
'applied': args.apply}))
if __name__ == '__main__':
main()
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""One bounded central reconciliation pass; no executor polling for PR checks."""
import json
import os
from pathlib import Path
import subprocess
import sys
def run(environment=None, execute=subprocess.run, root=None):
env = dict(os.environ if environment is None else environment)
if (env.get('CIRCLE_PROJECT_USERNAME') != 'QRun-IO'
or env.get('CIRCLE_PROJECT_REPONAME') != 'qqq-orb'
or env.get('CIRCLE_BRANCH') != 'main' or env.get('CIRCLE_TAG')):
raise ValueError('Reconciliation requires the orb main branch')
token = env.get('GH_TOKEN') or env.get('GITHUB_TOKEN')
if not token:
raise ValueError('Existing GitHub authentication is required')
env['GH_TOKEN'] = token
root = Path(root) if root else Path(__file__).resolve().parents[1]
output = root / 'artifacts/enrollment'
output.mkdir(parents=True, exist_ok=True)
args = [sys.executable, str(root / 'tools/reconcile_enrollment.py'),
'--organization', 'QRun-IO', '--orb-version', '0.8',
'--output', str(output / 'result.json'), '--apply', '--merge-ready', '--enforce',
'--circle-settings']
try:
result = execute(args, cwd=root, env=env, timeout=1200, check=False)
code = result.returncode
state = 'completed' if code == 0 else 'failed'
except subprocess.TimeoutExpired:
code, state = 124, 'timed-out'
(output / 'run.json').write_text(json.dumps({'state': state, 'exit_code': code,
'report_available': (output / 'result.json').exists(),
'note': 'Completion of a pass does not prove all repositories conform; inspect unresolved and waiting entries.'}, indent=2), encoding='utf-8')
return code
if __name__ == '__main__':
sys.exit(run())
+1
View File
@@ -91,6 +91,7 @@ def test_filters(filters):
"/(develop|main|release/.*|integration.*)/": "feature",
"/(develop|main|release/.*)/": "non-release-no-main",
"/(develop|release/.*|hotfix/.*)/": "non-release-no-hotfix",
"/(develop|release/.*|hotfix/.*|integration.*)/": "non-release-no-hotfix-integration",
"/(develop|main|release/.*|hotfix/.*)/": "non-release-no-main-hotfix",
"/(develop|main|release/.*|hotfix/.*|integration.*)/": "feature-no-hotfix",
}.get(pattern.replace(r"\/", "/"))