Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

step-02-generate-pipeline.md 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. ---
  2. name: 'step-02-generate-pipeline'
  3. description: 'Generate CI pipeline configuration with adaptive orchestration (agent-team, subagent, or sequential)'
  4. nextStepFile: '{skill-root}/steps-c/step-03-configure-quality-gates.md'
  5. knowledgeIndex: './resources/tea-index.csv'
  6. outputFile: '{test_artifacts}/ci-pipeline-progress.md'
  7. ---
  8. # Step 2: Generate CI Pipeline
  9. ## STEP GOAL
  10. Create platform-specific CI configuration with test execution, sharding, burn-in, and artifacts.
  11. ## MANDATORY EXECUTION RULES
  12. - 📖 Read the entire step file before acting
  13. - ✅ Speak in `{communication_language}`
  14. - ✅ Resolve execution mode from explicit user request first, then config
  15. - ✅ Apply fallback rules deterministically when requested mode is unsupported
  16. ---
  17. ## EXECUTION PROTOCOLS:
  18. - 🎯 Follow the MANDATORY SEQUENCE exactly
  19. - 💾 Record outputs before proceeding
  20. - 📖 Load the next step only when instructed
  21. ## CONTEXT BOUNDARIES:
  22. - Available context: config, loaded artifacts, and knowledge fragments
  23. - Focus: this step's goal only
  24. - Limits: do not execute future steps
  25. - Dependencies: prior steps' outputs (if any)
  26. ## MANDATORY SEQUENCE
  27. **CRITICAL:** Follow this sequence exactly. Do not skip, reorder, or improvise.
  28. ## 0. Resolve Execution Mode (User Override First)
  29. ```javascript
  30. const orchestrationContext = {
  31. config: {
  32. execution_mode: config.tea_execution_mode || 'auto', // "auto" | "subagent" | "agent-team" | "sequential"
  33. capability_probe: config.tea_capability_probe !== false, // true by default
  34. },
  35. timestamp: new Date().toISOString().replace(/[:.]/g, '-'),
  36. };
  37. const normalizeUserExecutionMode = (mode) => {
  38. if (typeof mode !== 'string') return null;
  39. const normalized = mode.trim().toLowerCase().replace(/[-_]/g, ' ').replace(/\s+/g, ' ');
  40. if (normalized === 'auto') return 'auto';
  41. if (normalized === 'sequential') return 'sequential';
  42. if (normalized === 'subagent' || normalized === 'sub agent' || normalized === 'subagents' || normalized === 'sub agents') {
  43. return 'subagent';
  44. }
  45. if (normalized === 'agent team' || normalized === 'agent teams' || normalized === 'agentteam') {
  46. return 'agent-team';
  47. }
  48. return null;
  49. };
  50. const normalizeConfigExecutionMode = (mode) => {
  51. if (mode === 'subagent') return 'subagent';
  52. if (mode === 'auto' || mode === 'sequential' || mode === 'subagent' || mode === 'agent-team') {
  53. return mode;
  54. }
  55. return null;
  56. };
  57. // Explicit user instruction in the active run takes priority over config.
  58. const explicitModeFromUser = normalizeUserExecutionMode(runtime.getExplicitExecutionModeHint?.() || null);
  59. const requestedMode = explicitModeFromUser || normalizeConfigExecutionMode(orchestrationContext.config.execution_mode) || 'auto';
  60. const probeEnabled = orchestrationContext.config.capability_probe;
  61. const supports = { subagent: false, agentTeam: false };
  62. if (probeEnabled) {
  63. supports.subagent = runtime.canLaunchSubagents?.() === true;
  64. supports.agentTeam = runtime.canLaunchAgentTeams?.() === true;
  65. }
  66. let resolvedMode = requestedMode;
  67. if (requestedMode === 'auto') {
  68. if (supports.agentTeam) resolvedMode = 'agent-team';
  69. else if (supports.subagent) resolvedMode = 'subagent';
  70. else resolvedMode = 'sequential';
  71. } else if (probeEnabled && requestedMode === 'agent-team' && !supports.agentTeam) {
  72. resolvedMode = supports.subagent ? 'subagent' : 'sequential';
  73. } else if (probeEnabled && requestedMode === 'subagent' && !supports.subagent) {
  74. resolvedMode = 'sequential';
  75. }
  76. ```
  77. Resolution precedence:
  78. 1. Explicit user request in this run (`agent team` => `agent-team`; `subagent` => `subagent`; `sequential`; `auto`)
  79. 2. `tea_execution_mode` from config
  80. 3. Runtime capability fallback (when probing enabled)
  81. ## 1. Resolve Output Path and Select Template
  82. Determine the pipeline output file path based on the detected `ci_platform`:
  83. | CI Platform | Output Path | Template File |
  84. | ---------------- | ------------------------------------------- | ----------------------------------------------- |
  85. | `github-actions` | `{project-root}/.github/workflows/test.yml` | `./github-actions-template.yaml` |
  86. | `gitlab-ci` | `{project-root}/.gitlab-ci.yml` | `./gitlab-ci-template.yaml` |
  87. | `jenkins` | `{project-root}/Jenkinsfile` | `./jenkins-pipeline-template.groovy` |
  88. | `azure-devops` | `{project-root}/azure-pipelines.yml` | `./azure-pipelines-template.yaml` |
  89. | `harness` | `{project-root}/.harness/pipeline.yaml` | `./harness-pipeline-template.yaml` |
  90. | `circle-ci` | `{project-root}/.circleci/config.yml` | _(no template; generate from first principles)_ |
  91. Use templates from `./` when available. Adapt the template to the project's `test_stack_type` and `test_framework`.
  92. ---
  93. ## Security: Script Injection Prevention
  94. > **CRITICAL:** Treat `${{ inputs.* }}` and the entire `${{ github.event.* }}` namespace as unsafe by default. ALWAYS route them through `env:` intermediaries and reference as double-quoted `"$ENV_VAR"` in `run:` blocks. NEVER interpolate them directly.
  95. When the generated pipeline is extended into reusable workflows (`on: workflow_call`), manual dispatch (`on: workflow_dispatch`), or composite actions, these values become user-controllable and can inject arbitrary shell commands.
  96. **Two rules for generated `run:` blocks:**
  97. 1. **No direct interpolation** — pass unsafe contexts through `env:`, reference as `"$ENV_VAR"`
  98. 2. **Inputs must be DATA, not COMMANDS** — never accept command-shaped inputs (e.g., `inputs.install-command`) that get executed as shell code. Even through `env:`, running `$CMD` where CMD comes from an input is still command injection. Use fixed commands and pass inputs only as arguments.
  99. ```yaml
  100. # ✅ SAFE — input is DATA interpolated into a fixed command
  101. - name: Run tests
  102. env:
  103. TEST_GREP: ${{ inputs.test-grep }}
  104. run: |
  105. # Security: inputs passed through env: to prevent script injection
  106. npx playwright test --grep "$TEST_GREP"
  107. # ❌ NEVER — direct GitHub expression injection
  108. - name: Run tests
  109. run: |
  110. npx playwright test --grep "${{ inputs.test-grep }}"
  111. # ❌ NEVER — executing input-derived env var as a command
  112. - name: Install
  113. env:
  114. CMD: ${{ inputs.install-command }}
  115. run: $CMD
  116. ```
  117. Include a `# Security: inputs passed through env: to prevent script injection` comment in generated YAML wherever this pattern is applied.
  118. **Safe contexts** (do NOT need `env:` intermediaries): `${{ steps.*.outputs.* }}`, `${{ matrix.* }}`, `${{ runner.os }}`, `${{ github.sha }}`, `${{ github.ref }}`, `${{ secrets.* }}`, `${{ env.* }}`.
  119. ---
  120. ## 2. Pipeline Stages
  121. Include stages:
  122. - lint
  123. - test (parallel shards)
  124. - contract-test (if `tea_use_pactjs_utils` enabled)
  125. - burn-in (flaky detection)
  126. - report (aggregate + publish)
  127. ---
  128. ## 3. Test Execution
  129. - Parallel sharding enabled
  130. - CI retries configured
  131. - Capture artifacts (HTML report, JUnit XML, traces/videos on failure)
  132. - Cache dependencies (language-appropriate: node_modules, .venv, .m2, go module cache, NuGet, bundler)
  133. Write the selected pipeline configuration to the resolved output path from step 1. Adjust test commands based on `test_stack_type` and `test_framework`:
  134. - **Frontend/Fullstack**: Include browser install, E2E/component test commands, Playwright/Cypress artifacts
  135. - **Backend (Node.js)**: Use `npm test` or framework-specific commands (`vitest`, `jest`), skip browser install
  136. - **Backend (Python)**: Use `pytest` with coverage (`pytest --cov`), install via `pip install -r requirements.txt` or `poetry install`
  137. - **Backend (Java/Kotlin)**: Use `mvn test` or `gradle test`, cache `.m2/repository` or `.gradle/caches`
  138. - **Backend (Go)**: Use `go test ./...` with coverage (`-coverprofile`), cache Go modules
  139. - **Backend (C#/.NET)**: Use `dotnet test` with coverage, restore NuGet packages
  140. - **Backend (Ruby)**: Use `bundle exec rspec` with coverage, cache `vendor/bundle`
  141. ### Contract Testing Pipeline (if `tea_use_pactjs_utils` enabled)
  142. **If `tea_use_pactjs_utils` is enabled**, use `{knowledgeIndex}` to load:
  143. - `pact-consumer-framework-setup.md` — determinism gate, `jq -S` publish normalization, 1:1 local/CI parity, full consumer CI workflow template
  144. - `pactjs-utils-consumer-helpers.md` — one-interaction-per-`it()` determinism rule
  145. - `pactjs-utils-provider-verifier.md` — `buildVerifierOptions`, broker config, breaking change patterns, **vitest `pool: 'forks'` + `singleFork: true`** (same rule applies to consumer AND provider configs)
  146. - `pactjs-utils-request-filter.md` — `createRequestFilter` auth injection patterns for CI pipeline auth setup
  147. - `pact-broker-webhooks.md` — PactFlow → GitHub webhook auth (dedicated machine user, classic PAT with `repo` scope, PactFlow-stored secret), rotation runbook, and staleness monitoring options (the webhook is what makes `can-i-deploy` succeed end-to-end)
  148. When `tea_use_pactjs_utils` is enabled, add a `contract-test` stage after `test`:
  149. **Required env block** (add to the generated pipeline):
  150. ```yaml
  151. env:
  152. PACT_BROKER_BASE_URL: ${{ secrets.PACT_BROKER_BASE_URL }}
  153. PACT_BROKER_TOKEN: ${{ secrets.PACT_BROKER_TOKEN }}
  154. GITHUB_SHA: ${{ github.sha }} # auto-set by GitHub Actions
  155. GITHUB_BRANCH: ${{ github.head_ref || github.ref_name }} # NOT auto-set — must be defined explicitly
  156. ```
  157. > **Note:** `GITHUB_SHA` is auto-set by GitHub Actions, but `GITHUB_BRANCH` is **not** — it must be derived from `github.head_ref` (for PRs) or `github.ref_name` (for pushes). The pactjs-utils library reads both from `process.env`.
  158. 1. **Consumer test (determinism gate) + publish**: Run consumer contract tests as a determinism gate, then publish pacts to broker — each step calls the same `npm run` script a developer runs locally (1:1 parity)
  159. - `npm run test:pact:consumer` — **this is the determinism gate**: runs `scripts/check-pact-determinism.sh` which invokes the inner `test:pact:consumer:run` N times (default 3) and fails if generated pact JSON is not byte-stable across runs. Never fold this into the publish step — keep it as its own visible CI step so failures are attributable to generation vs publish.
  160. - `npm run publish:pact` — publishes to the broker; internally normalizes interactions via `jq -S '.interactions |= sort_by(...)'` as defense-in-depth against any ordering drift that slips past the gate.
  161. - Ensure `jq` is available on the runner. It is preinstalled on GitHub `ubuntu-latest`; for other runner images or self-hosted runners, add an explicit install step (e.g., `apt-get install -y jq` or `brew install jq`) before any contract-test or publish command.
  162. - Only publish on PR and main branch pushes.
  163. 2. **Provider verification**: Run provider verification against published pacts
  164. - `npm run test:pact:provider:remote:contract`
  165. - `buildVerifierOptions` auto-reads `PACT_BROKER_BASE_URL`, `PACT_BROKER_TOKEN`, `GITHUB_SHA`, `GITHUB_BRANCH`
  166. - Provider Vitest config (`vitest.config.contract.ts`) **must** use `pool: 'forks'` + `poolOptions.forks.singleFork: true` (see `pactjs-utils-provider-verifier.md` Example 7) — required for message providers and any multi-file provider contract suite to keep Pact Rust FFI state coherent. The SAME config is required on the consumer side (`vitest.config.pact.ts`) alongside `fileParallelism: false` — see `pact-consumer-framework-setup.md` Example 2.
  167. - Verification results published to broker when `CI=true`
  168. 3. **Can-I-Deploy gate**: Block deployment if contracts are incompatible
  169. - `npm run can:i:deploy:provider`
  170. - Ensure the script adds `--retry-while-unknown 6 --retry-interval 10` for async verification
  171. 4. **Webhook job**: Add `repository_dispatch` trigger for `contract_requiring_verification_published` event
  172. - Provider verification runs when consumers publish new pacts
  173. - Ensures compatibility is checked on both consumer and provider changes
  174. - Webhook authentication uses a dedicated GitHub machine user + classic PAT (`repo` scope, no expiration) stored as a PactFlow secret. See `pact-broker-webhooks.md` for the full pattern, rotation runbook, and staleness monitoring. A silently-expired PAT is the most common non-code cause of `can-i-deploy` timeouts with `There is no verified pact between ...`.
  175. 5. **Breaking change handling**: When `PACT_BREAKING_CHANGE=true` env var is set:
  176. - Provider test passes `includeMainAndDeployed: false` to `buildVerifierOptions` — verifies only matching branch
  177. - Coordinate with consumer team before removing the flag
  178. 6. **Record deployment**: After successful deployment, record version in broker
  179. - `npm run record:provider:deployment --env=production`
  180. 7. **Staleness monitoring (recommended)**: Scheduled CI job (e.g., daily) that asserts recent verification results exist for each critical consumer/provider pair — surfaces silent webhook failures before they block a release. See `pact-broker-webhooks.md` Example 4.
  181. Required CI secrets: `PACT_BROKER_BASE_URL`, `PACT_BROKER_TOKEN`
  182. **If `tea_pact_mcp` is `"mcp"`:** Reference the SmartBear MCP `Can I Deploy` and `Matrix` tools for pipeline guidance in `pact-mcp.md`.
  183. ---
  184. ### 4. Save Progress
  185. **Save this step's accumulated work to `{outputFile}`.**
  186. - **If `{outputFile}` does not exist** (first save), create it with YAML frontmatter:
  187. ```yaml
  188. ---
  189. stepsCompleted: ['step-02-generate-pipeline']
  190. lastStep: 'step-02-generate-pipeline'
  191. lastSaved: '{date}'
  192. ---
  193. ```
  194. Then write this step's output below the frontmatter.
  195. - **If `{outputFile}` already exists**, update:
  196. - Add `'step-02-generate-pipeline'` to `stepsCompleted` array (only if not already present)
  197. - Set `lastStep: 'step-02-generate-pipeline'`
  198. - Set `lastSaved: '{date}'`
  199. - Append this step's output to the appropriate section of the document.
  200. ### 5. Orchestration Notes for This Step
  201. For this step, treat these work units as parallelizable when `resolvedMode` is `agent-team` or `subagent`:
  202. - Worker A: resolve platform path/template and produce base pipeline skeleton (section 1)
  203. - Worker B: construct stage definitions and test execution blocks (sections 2-3)
  204. - Worker C: contract-testing block (only when `tea_use_pactjs_utils` is true)
  205. If `resolvedMode` is `sequential`, execute sections 1→4 in order.
  206. Load next step: `{nextStepFile}`
  207. ## 🚨 SYSTEM SUCCESS/FAILURE METRICS:
  208. ### ✅ SUCCESS:
  209. - Step completed in full with required outputs
  210. ### ❌ SYSTEM FAILURE:
  211. - Skipped sequence steps or missing outputs
  212. **Master Rule:** Skipping steps is FORBIDDEN.