infra-ci-cd-turborepo-ci
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTurborepo CI Patterns
Turborepo CI 模式
Quick Guide: Usefor PR builds (auto-detects CI environment, falls back to full suite on shallow clones). Enable Remote Cache with--affected+TURBO_TOKENenv vars. DeclareTURBO_TEAMfor every cacheable task or cached results will be incomplete. Useoutputsandenvin turbo.json to include environment variables in cache hashes -- missing entries cause cross-environment cache collisions. PinglobalEnvversion in CI. Useturboto conditionally skip entire CI steps.turbo query affected
<critical_requirements>
快速指南: PR构建时使用参数(自动检测CI环境,在浅克隆时自动回退到全量任务集)。通过--affected+TURBO_TOKEN环境变量启用Remote Cache。为所有可缓存任务声明TURBO_TEAM,否则缓存结果会不完整。在turbo.json中使用outputs和env将环境变量纳入缓存哈希——缺失条目会导致跨环境缓存冲突。在CI中固定globalEnv版本。使用turbo有条件地跳过整个CI步骤。turbo query affected
<critical_requirements>
CRITICAL: Before Using This Skill
关键要求:使用本技能前须知
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,, named constants)import type
(You MUST declare for every cacheable task in turbo.json -- missing outputs means cached results restore without build artifacts)
outputs(You MUST list environment variables that affect task output in (task-level) or (all tasks) -- omitting them causes cross-environment cache hits with wrong values)
envglobalEnv(You MUST use for PR builds -- running the full task graph on PRs wastes CI time on unchanged packages)
--affected(You MUST pin the CLI version in CI -- can introduce breaking changes mid-pipeline)
turbolatest</critical_requirements>
Detailed Resources:
- examples/core.md - turbo.json task config, outputs, env, caching control, filter syntax
- examples/remote-cache.md - Remote Cache setup, self-hosted options, signature verification
- examples/affected-detection.md - --affected flag, turbo query affected, conditional CI steps
- examples/docker.md - turbo prune --docker, multi-stage Dockerfile, layer caching
- reference.md - Decision frameworks, CLI flags, turbo.json quick reference
Auto-detection: Turborepo CI, turbo.json, turbo run, turbo prune, --affected, --filter, TURBO_TOKEN, TURBO_TEAM, Remote Cache, turbo query affected, outputs, dependsOn, globalEnv, envMode, concurrency, turbo login, turbo link, cache artifacts, monorepo CI
When to use:
- Configuring CI pipelines for a Turborepo monorepo
- Setting up Remote Cache for shared build artifacts across CI and local
- Using to run only changed-package tasks on PRs
--affected - Optimizing Docker builds with
turbo prune --docker - Debugging cache misses with or
--summarize--dry - Skipping CI steps conditionally with
turbo query affected
When NOT to use:
- General Turborepo workspace setup (package structure, task graph design) -- that belongs in a monorepo/workspace skill
- CI provider-specific workflow syntax (use your CI provider's skill)
- Application build configuration (bundler, compiler settings)
Key patterns covered:
- turbo.json task configuration (,
outputs,env,dependsOn,cache)inputs - Remote Cache authentication and setup (,
TURBO_TOKEN, signature verification)TURBO_TEAM - Affected detection (,
--affected,--filter=...[origin/main])turbo query affected - Docker optimization with and multi-stage builds
turbo prune --docker - Cache debugging (,
--summarize,--dry)--force - Environment variable modes (vs
strict) andloosepassThroughEnv - Concurrency control and output log filtering
<philosophy>
所有代码必须遵循CLAUDE.md中的项目约定(短横线命名、命名导出、导入顺序、、命名常量)import type
(必须在turbo.json中为所有可缓存任务声明——缺失outputs会导致缓存结果恢复时没有构建产物)
outputs(必须将影响任务输出的环境变量列在(任务级别)或(所有任务)中——遗漏会导致跨环境缓存命中并返回错误值)
envglobalEnv(PR构建必须使用——对PR运行完整任务图会在未变更的包上浪费CI时间)
--affected(必须在CI中固定 CLI版本——使用可能会在流水线运行中引入破坏性变更)
turbolatest</critical_requirements>
详细资源:
- examples/core.md - turbo.json任务配置、outputs、env、缓存控制、过滤语法
- examples/remote-cache.md - Remote Cache设置、自托管选项、签名验证
- examples/affected-detection.md - --affected参数、turbo query affected、条件CI步骤
- examples/docker.md - turbo prune --docker、多阶段Dockerfile、层缓存
- reference.md - 决策框架、CLI参数、turbo.json快速参考
自动检测项: Turborepo CI、turbo.json、turbo run、turbo prune、--affected、--filter、TURBO_TOKEN、TURBO_TEAM、Remote Cache、turbo query affected、outputs、dependsOn、globalEnv、envMode、concurrency、turbo login、turbo link、缓存产物、monorepo CI
适用场景:
- 为Turborepo monorepo配置CI流水线
- 设置Remote Cache以在CI和本地之间共享构建产物
- 使用仅在PR上运行变更包的任务
--affected - 通过优化Docker构建
turbo prune --docker - 使用或
--summarize调试缓存未命中问题--dry - 通过有条件地跳过CI步骤
turbo query affected
不适用场景:
- 通用Turborepo工作区设置(包结构、任务图设计)——这属于monorepo/工作区技能范畴
- CI提供商特定的工作流语法(使用对应CI提供商的技能)
- 应用构建配置(打包器、编译器设置)
涵盖的核心模式:
- turbo.json任务配置(、
outputs、env、dependsOn、cache)inputs - Remote Cache认证与设置(、
TURBO_TOKEN、签名验证)TURBO_TEAM - 变更检测(、
--affected、--filter=...[origin/main])turbo query affected - 使用和多阶段构建优化Docker
turbo prune --docker - 缓存调试(、
--summarize、--dry)--force - 环境变量模式(vs
strict)和loosepassThroughEnv - 并发控制与输出日志过滤
<philosophy>
Philosophy
设计理念
Turborepo's CI value comes from two things: caching (never redo work whose inputs haven't changed) and affected detection (never start work that can't have changed). The combination turns a 15-minute full monorepo build into a sub-minute cache restore for unchanged packages.
Core CI principles:
- Cache correctness over speed: A wrong cache hit is worse than a cache miss. Declare all and all
outputsvariables that affect task results.env - Affected detection for PRs, full suite for main: PRs get fast feedback via . Main branch runs the full task graph to catch integration issues.
--affected - Remote Cache for team-wide sharing: Local cache is per-machine. Remote Cache shares artifacts across CI runners and developer machines, eliminating redundant work organization-wide.
- Pin versions in CI: Turborepo follows semver, but in CI means non-reproducible builds. Pin to the major version at minimum.
latest
When to use Turborepo in CI:
- Monorepo with 2+ packages where cross-package caching saves meaningful time
- Teams where multiple developers and CI runners rebuild the same packages
- Projects where Docker builds benefit from pruned lockfiles
When NOT to use:
- Single-package repos (no cross-package caching benefit)
- Repos where every PR touches every package (affected detection provides no speedup)
<patterns>
Turborepo在CI中的价值来自两点:缓存(从不重复执行输入未变更的工作)和变更检测(从不启动不可能发生变更的工作)。两者结合可将15分钟的全量monorepo构建缩短为仅需数十秒的缓存恢复(针对未变更包)。
核心CI原则:
- 缓存正确性优先于速度:错误的缓存命中比缓存未命中更糟糕。声明所有和所有影响任务结果的
outputs变量。env - PR用变更检测,主分支用全量任务:PR通过获得快速反馈。主分支运行完整任务图以捕获集成问题。
--affected - Remote Cache用于团队共享:本地缓存是单机器的。Remote Cache在CI运行器和开发机器之间共享产物,消除整个团队的重复工作。
- CI中固定版本:Turborepo遵循语义化版本,但CI中使用会导致不可复现的构建。至少固定主版本号。
latest
何时在CI中使用Turborepo:
- 包含2个以上包的monorepo,跨包缓存能节省大量时间
- 团队中有多名开发者和多个CI运行器重复构建相同包
- Docker构建可从修剪后的锁文件中受益的项目
何时不使用:
- 单包仓库(无跨包缓存收益)
- 每个PR都会修改所有包的仓库(变更检测无法提升速度)
<patterns>
Core Patterns
核心模式
Pattern 1: Task Configuration in turbo.json
模式1:turbo.json中的任务配置
Every task that produces files must declare . Every task affected by environment variables must declare . Missing either causes cache correctness issues.
outputsenvjsonc
{
"$schema": "https://turborepo.dev/schema.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", "build/**"],
"env": ["NODE_ENV", "API_URL"],
},
"test": {
"dependsOn": ["^build"],
"outputs": ["coverage/**"],
"env": ["DATABASE_URL"],
},
"lint": {
"dependsOn": [],
"cache": true,
},
"type-check": {
"dependsOn": ["^build"],
"cache": true,
},
},
}Key decisions:
- means "run build in all dependencies first" -- the
dependsOn: ["^build"]prefix means upstream packages^ - defines what gets cached and restored -- omit it and cached runs produce empty results
outputs - includes variables in the cache hash -- change the value, bust the cache
env - disables caching for tasks like
cache: falseor deployment scriptsdev
See examples/core.md for complete task config with , , , and package-level overrides.
inputspassThroughEnvoutputLogs每个生成文件的任务都必须声明。每个受环境变量影响的任务都必须声明。缺失任何一项都会导致缓存正确性问题。
outputsenvjsonc
{
"$schema": "https://turborepo.dev/schema.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", "build/**"],
"env": ["NODE_ENV", "API_URL"],
},
"test": {
"dependsOn": ["^build"],
"outputs": ["coverage/**"],
"env": ["DATABASE_URL"],
},
"lint": {
"dependsOn": [],
"cache": true,
},
"type-check": {
"dependsOn": ["^build"],
"cache": true,
},
},
}关键决策:
- 表示“先运行所有依赖包中的build任务”——
dependsOn: ["^build"]前缀表示上游包^ - 定义了哪些内容会被缓存和恢复——省略它会导致缓存运行返回空结果
outputs - 将变量纳入缓存哈希——变量值变更会使缓存失效
env - 禁用对
cache: false或部署脚本等任务的缓存dev
查看examples/core.md了解包含、、和包级别覆盖的完整任务配置。
inputspassThroughEnvoutputLogsPattern 2: Remote Cache Setup
模式2:Remote Cache设置
Remote Cache shares build artifacts across CI runners and developer machines. Two environment variables enable it.
bash
undefinedRemote Cache在CI运行器和开发机器之间共享构建产物。两个环境变量即可启用它。
bash
undefinedRequired for Remote Cache in CI
CI中启用Remote Cache所需的变量
TURBO_TOKEN=<bearer-token> # Auth token (Vercel or self-hosted)
TURBO_TEAM=<team-slug> # Team/account identifier
**Vercel Remote Cache:** Free, automatic on Vercel deployments. For other CI providers, set `TURBO_TOKEN` and `TURBO_TEAM` as CI secrets.
**Self-hosted:** Use `TURBO_API` to point to a custom Remote Cache server implementing the Turborepo Remote Cache API. Community options: `ducktors/turborepo-remote-cache`, `brunojppb/turbo-cache-server`.
**Signature verification** (recommended for shared caches):
```jsonc
{
"remoteCache": {
"signature": true,
},
}Set with an HMAC-SHA256 secret. Failed verification is treated as a cache miss.
TURBO_REMOTE_CACHE_SIGNATURE_KEYSee examples/remote-cache.md for complete setup including self-hosted config and cache permission tuning.
TURBO_TOKEN=<bearer-token> # 认证令牌(Vercel或自托管)
TURBO_TEAM=<team-slug> # 团队/账户标识符
**Vercel Remote Cache:** 免费,在Vercel部署时自动配置。对于其他CI提供商,将`TURBO_TOKEN`和`TURBO_TEAM`设置为CI密钥。
**自托管:** 使用`TURBO_API`指向实现Turborepo Remote Cache API的自定义Remote Cache服务器。社区选项:`ducktors/turborepo-remote-cache`、`brunojppb/turbo-cache-server`。
**签名验证**(共享缓存推荐使用):
```jsonc
{
"remoteCache": {
"signature": true,
},
}设置为HMAC-SHA256密钥。验证失败会被视为缓存未命中。
TURBO_REMOTE_CACHE_SIGNATURE_KEY查看examples/remote-cache.md了解包含自托管配置和缓存权限调整的完整设置。
Pattern 3: Affected Detection for PR Builds
模式3:PR构建的变更检测
--affectedGITHUB_BASE_REFbash
undefined--affectedGITHUB_BASE_REFbash
undefinedPR builds: only changed packages
PR构建:仅运行变更包的任务
turbo run build test lint --affected
turbo run build test lint --affected
Manual comparison base
手动指定比较基准
turbo run test --filter=...[origin/main]
**Gotcha:** Shallow clones break affected detection because git diff needs history. `--affected` gracefully falls back to running all tasks, but `--filter=...[origin/main]` may fail silently. Ensure sufficient clone depth in CI.
**Advanced: Conditional CI steps** with `turbo query affected`:
```bashturbo run test --filter=...[origin/main]
**注意事项:** 浅克隆会破坏变更检测,因为git diff需要历史记录。`--affected`会优雅地回退到运行所有任务,但`--filter=...[origin/main]`可能会静默失败。确保CI中有足够的克隆深度。
**进阶:使用`turbo query affected`实现条件CI步骤**:
```bashCheck if a specific package is affected before running expensive steps
在运行昂贵步骤前检查特定包是否有变更
AFFECTED=$(turbo query affected --packages web
| jq '.data.affectedPackages.length') if [ "$AFFECTED" -gt 0 ]; then
| jq '.data.affectedPackages.length') if [ "$AFFECTED" -gt 0 ]; then
Run expensive deployment steps
fi
See [examples/affected-detection.md](examples/affected-detection.md) for PR vs main branch patterns and `turbo query affected` examples.
---AFFECTED=$(turbo query affected --packages web
| jq '.data.affectedPackages.length') if [ "$AFFECTED" -gt 0 ]; then
| jq '.data.affectedPackages.length') if [ "$AFFECTED" -gt 0 ]; then
运行昂贵的部署步骤
fi
查看[examples/affected-detection.md](examples/affected-detection.md)了解PR与主分支模式以及`turbo query affected`示例。
---Pattern 4: Docker Optimization with turbo prune
模式4:使用turbo prune优化Docker
turbo prune--dockerdockerfile
undefinedturbo prune--dockerdockerfile
undefinedStage 1: Install dependencies (cached unless lockfile changes)
阶段1:安装依赖(仅在锁文件变更时重新缓存)
FROM node:20-alpine AS deps
WORKDIR /app
COPY out/json/ .
RUN npm install --frozen-lockfile
FROM node:20-alpine AS deps
WORKDIR /app
COPY out/json/ .
RUN npm install --frozen-lockfile
Stage 2: Build (cached unless source changes)
阶段2:构建(仅在源代码变更时重新缓存)
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app .
COPY out/full/ .
RUN npx turbo run build --filter=web
**Key benefit:** Changes to source code in one package don't invalidate the dependency install layer for other packages. Without pruning, any lockfile change (even in unrelated packages) busts the Docker cache for all images.
See [examples/docker.md](examples/docker.md) for complete multi-stage Dockerfile with `turbo prune --docker`.
---FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app .
COPY out/full/ .
RUN npx turbo run build --filter=web
**核心优势:** 单个包的源代码变更不会使其他包的依赖安装层失效。如果不进行修剪,锁文件的任何变更(即使是无关包的)都会使所有镜像的Docker缓存失效。
查看[examples/docker.md](examples/docker.md)了解包含`turbo prune --docker`的完整多阶段Dockerfile。
---Pattern 5: Cache Debugging
模式5:缓存调试
When tasks produce unexpected results after cache hits, use these tools to diagnose.
bash
undefined当任务在缓存命中后产生意外结果时,使用以下工具进行诊断。
bash
undefinedSee what would run without executing (dry run)
查看会运行哪些任务但不实际执行(空运行)
turbo run build --dry
turbo run build --dry
Generate detailed run summary with hashes and timing
生成包含哈希和计时的详细运行摘要
turbo run build --summarize
turbo run build --summarize
Output in .turbo/runs/<id>.json
输出到.turbo/runs/<id>.json
Force re-execution, ignoring cache
强制重新执行,忽略缓存
turbo run build --force
turbo run build --force
Control cache sources (disable remote, keep local)
控制缓存源(禁用远程缓存,保留本地缓存)
turbo run build --cache=local:rw,remote:off
**Common cache miss causes:**
- Changed environment variable not listed in `env` or `globalEnv`
- Modified file not captured by default inputs (use `inputs` key to customize)
- Different `turbo` version between CI and local (different hashing algorithm)
- Missing `outputs` declaration (task runs but restores nothing from cache)
See [examples/core.md](examples/core.md) for `--summarize` output analysis and cache troubleshooting.
---turbo run build --cache=local:rw,remote:off
**常见缓存未命中原因:**
- 变更的环境变量未列在`env`或`globalEnv`中
- 修改的文件未被默认输入捕获(使用`inputs`键自定义)
- CI与本地使用的`turbo`版本不同(哈希算法不同)
- 缺失`outputs`声明(任务运行但从缓存中恢复不到任何内容)
查看[examples/core.md](examples/core.md)了解`--summarize`输出分析和缓存故障排除。
---Pattern 6: Environment Variable Strategy
模式6:环境变量策略
Turborepo's env mode (default in v2) only makes variables listed in , , or available to tasks. This prevents accidental cache collisions but requires explicit configuration.
strictenvglobalEnvpassThroughEnvjsonc
{
"globalEnv": ["CI", "NODE_ENV"],
"tasks": {
"build": {
"env": ["API_URL", "SENTRY_DSN"],
"passThroughEnv": ["npm_config_registry"],
},
},
}Decision: vs vs :
envglobalEnvpassThroughEnv| Key | Affects hash? | Available to task? | Scope |
|---|---|---|---|
| Yes | Yes | Single task |
| Yes (all tasks) | Yes | All tasks |
| No | Yes | Single task |
| No | Yes | All tasks |
When to use : Variables needed at runtime but that don't affect build output (e.g., , ). Changing them should not bust the cache.
passThroughEnvnpm_config_registryHTTP_PROXYSee examples/core.md for strict vs loose mode examples and environment variable debugging.
</patterns>
<performance>
Turborepo的环境模式(v2默认)仅允许、或中列出的变量对任务可用。这可以防止意外的缓存冲突,但需要显式配置。
strictenvglobalEnvpassThroughEnvjsonc
{
"globalEnv": ["CI", "NODE_ENV"],
"tasks": {
"build": {
"env": ["API_URL", "SENTRY_DSN"],
"passThroughEnv": ["npm_config_registry"],
},
},
}决策: vs vs :
envglobalEnvpassThroughEnv| 键 | 影响哈希? | 对任务可用? | 范围 |
|---|---|---|---|
| 是 | 是 | 单个任务 |
| 是(所有任务) | 是 | 所有任务 |
| 否 | 是 | 单个任务 |
| 否 | 是 | 所有任务 |
何时使用: 运行时需要但不影响构建输出的变量(如、)。变更这些变量不应使缓存失效。
passThroughEnvnpm_config_registryHTTP_PROXY查看examples/core.md了解严格模式与宽松模式示例以及环境变量调试。
</patterns>
<performance>
Performance Optimization
性能优化
Goal: PR builds < 3 minutes with affected detection + Remote Cache
Cache hit rate optimization:
- Declare all and
outputsvariables to prevent false missesenv - Use to compare hashes between runs and identify unexpected invalidations
--summarize - Keep minimal -- variables there bust cache for ALL tasks
globalEnv - Use task-level for variables that only affect specific tasks
env
Concurrency tuning:
bash
undefined目标:通过变更检测 + Remote Cache使PR构建时间<3分钟
缓存命中率优化:
- 声明所有和
outputs变量以防止虚假未命中env - 使用比较不同运行之间的哈希,识别意外的缓存失效
--summarize - 尽量减少——其中的变量会使所有任务的缓存失效
globalEnv - 对仅影响特定任务的变量使用任务级别的
env
并发调优:
bash
undefinedDefault concurrency is 10 parallel tasks
默认并发数为10个并行任务
turbo run build test lint --concurrency=20
turbo run build test lint --concurrency=20
Use percentage of available CPUs
使用可用CPU的百分比
turbo run build --concurrency=50%
turbo run build --concurrency=50%
Serial execution (debugging)
串行执行(调试用)
turbo run build --concurrency=1
**Output log filtering for CI readability:**
```jsonc
{
"tasks": {
"build": {
"outputLogs": "new-only",
},
"lint": {
"outputLogs": "errors-only",
},
},
}Options: (default), , , , .
fullhash-onlynew-onlyerrors-onlynoneMonitoring targets:
- PR build: < 3 min (with affected + Remote Cache)
- Main build: < 10 min (full suite)
- Cache hit rate: > 80% on Remote Cache
- Docker build: < 5 min with pruned lockfile
<decision_framework>
turbo run build --concurrency=1
**CI可读性的输出日志过滤:**
```jsonc
{
"tasks": {
"build": {
"outputLogs": "new-only",
},
"lint": {
"outputLogs": "errors-only",
},
},
}选项:(默认)、、、、。
fullhash-onlynew-onlyerrors-onlynone监控指标:
- PR构建: <3分钟(使用变更检测 + Remote Cache)
- 主分支构建: <10分钟(全量任务)
- 缓存命中率: Remote Cache命中率>80%
- Docker构建: 使用修剪后的锁文件时<5分钟
<decision_framework>
Decision Framework
决策框架
When to use --affected vs --filter?
何时使用--affected vs --filter?
Running a PR build?
|-- YES --> Use --affected (auto-detects CI env, graceful shallow clone fallback)
+-- NO --> Need specific package selection?
|-- YES --> Use --filter (explicit package/directory/git targeting)
+-- NO --> Run full task graph (main branch, release builds)是否运行PR构建?
|-- 是 --> 使用--affected(自动检测CI环境,浅克隆时优雅回退)
+-- 否 --> 是否需要特定包选择?
|-- 是 --> 使用--filter(显式指定包/目录/git目标)
+-- 否 --> 运行完整任务图(主分支、发布构建)When to enable Remote Cache?
何时启用Remote Cache?
Team > 1 person OR using CI?
|-- YES --> Enable Remote Cache (shared artifacts save significant time)
| |-- Using Vercel for hosting?
| | |-- YES --> Free, auto-configured on Vercel deployments
| | +-- NO --> Set TURBO_TOKEN + TURBO_TEAM as CI secrets
| +-- Need artifact signing?
| |-- YES --> Enable signature verification in turbo.json
| +-- NO --> Default (unsigned) is fine for trusted environments
+-- NO --> Local cache sufficient (solo developer, single machine)团队人数>1或使用CI?
|-- 是 --> 启用Remote Cache(共享产物节省大量时间)
| |-- 是否使用Vercel托管?
| | |-- 是 --> 免费,在Vercel部署时自动配置
| | +-- 否 --> 将TURBO_TOKEN + TURBO_TEAM设置为CI密钥
| +-- 是否需要产物签名?
| |-- 是 --> 在turbo.json中启用签名验证
| +-- 否 --> 默认(未签名)在可信环境中足够
+-- 否 --> 本地缓存足够(单人开发、单机器)env vs globalEnv vs passThroughEnv?
env vs globalEnv vs passThroughEnv?
Does the variable affect task output (build artifacts, test results)?
|-- YES --> Does it affect ALL tasks or just one?
| |-- ALL tasks --> globalEnv (changes bust cache for everything)
| +-- One task --> env on that specific task
+-- NO --> Does the task need it at runtime?
|-- YES --> passThroughEnv (available but not in hash)
+-- NO --> Don't list it (strict mode blocks it)变量是否影响任务输出(构建产物、测试结果)?
|-- 是 --> 它影响所有任务还是仅一个?
| |-- 所有任务 --> globalEnv(变更会使所有任务的缓存失效)
| +-- 单个任务 --> 在该特定任务上使用env
+-- 否 --> 任务运行时是否需要它?
|-- 是 --> passThroughEnv(可用但不纳入哈希)
+-- 否 --> 不要列出它(严格模式会阻止它)When to use turbo prune --docker?
何时使用turbo prune --docker?
Building Docker images from monorepo?
|-- YES --> Does your Dockerfile install from root lockfile?
| |-- YES --> Use turbo prune --docker (pruned lockfile = better layer caching)
| +-- NO --> Standard turbo prune (no --docker flag needed)
+-- NO --> Not applicable</decision_framework>
<red_flags>
是否从monorepo构建Docker镜像?
|-- 是 --> Dockerfile是否从根锁文件安装依赖?
| |-- 是 --> 使用turbo prune --docker(修剪后的锁文件=更好的层缓存)
| +-- 否 --> 使用标准turbo prune(不需要--docker参数)
+-- 否 --> 不适用</decision_framework>
<red_flags>
RED FLAGS
警示信号
High Priority:
- Missing on cacheable tasks -- cached runs restore nothing, tasks appear to succeed but produce no artifacts
outputs - Missing for environment-dependent tasks -- build with
envhits cache fromAPI_URL=staging, serving wrong configAPI_URL=production - Using turbo version in CI -- non-reproducible builds, potential breaking changes mid-pipeline
latest - Shallow clones without fallback -- fails when git history is insufficient;
--filter=...[origin/main]handles this gracefully by falling back to full suite--affected
Medium Priority:
- All environment variables in -- every change busts cache for ALL tasks; use task-level
globalEnvfor task-specific variablesenv - No on PR builds -- full task graph on PRs wastes CI time rebuilding unchanged packages
--affected - Missing signature verification on shared Remote Cache -- unsigned artifacts can be tampered with in shared environments
- Not using explicitly in CI -- bare
turbo runmay conflict with future CLI subcommandsturbo build
Common Mistakes:
- Forgetting for tasks that consume upstream package outputs (test/lint fail because dependency not built)
dependsOn: ["^build"] - Using env mode and wondering why cache hits serve wrong environment config
loose - Not including for files like
globalDependenciesor.envthat affect all packagestsconfig.base.json - Setting on tasks that should be cached (e.g., test, lint) because of past debugging and forgetting to re-enable
cache: false
Gotchas & Edge Cases:
- auto-detects GitHub Actions via
--affected-- other CI providers may need manualGITHUB_BASE_REFinstead--filter - returns JSON -- parse with
turbo query affectedfor conditional CI stepsjq - globs are relative to the package directory, not the repo root
outputs - in
$TURBO_DEFAULT$restores the default input behavior when you only want to add inputs, not replace theminputs - Remote Cache requires
signature: true-- missing key means cache reads fail silently (treated as misses)TURBO_REMOTE_CACHE_SIGNATURE_KEY - output goes to
--summarize-- useful for diffing hashes between two runs to find what changed.turbo/runs/ - Circular package dependencies are allowed since v2.9 (validated at task graph level, not package graph level)
- flag is deprecated -- use
--parallelin turbo.json for long-running tasks insteadpersistent: true - is deprecated -- use
turbo-ignoreinstead for conditional CI stepsturbo query affected - default is 30s,
remoteCache.timeoutis 60s -- increase for large monorepo artifactsuploadTimeout
</red_flags>
<critical_reminders>
高优先级:
- 可缓存任务缺失——缓存运行恢复不到任何内容,任务看似成功但无产物
outputs - 依赖环境的任务缺失——使用
env构建时命中API_URL=staging的缓存,返回错误配置API_URL=production - CI中使用版本的turbo——不可复现的构建,流水线运行中可能引入破坏性变更
latest - 浅克隆无回退机制——当git历史不足时会失败;
--filter=...[origin/main]会优雅回退到全量任务--affected
中优先级:
- 所有环境变量都放在中——任何变更都会使所有任务的缓存失效;对任务特定变量使用任务级别的
globalEnvenv - PR构建未使用——PR上运行完整任务图会浪费CI时间重新构建未变更的包
--affected - 共享Remote Cache缺失签名验证——未签名的产物在共享环境中可能被篡改
- CI中未显式使用——直接使用
turbo run可能与未来的CLI子命令冲突turbo build
常见错误:
- 忘记为依赖上游包输出的任务设置(测试/ lint失败,因为依赖未构建)
dependsOn: ["^build"] - 使用环境模式,却疑惑为什么缓存命中返回错误的环境配置
loose - 未将影响所有包的文件(如或
.env)加入tsconfig.base.jsonglobalDependencies - 因过去的调试需求将应缓存的任务(如test、lint)设置为,之后忘记重新启用
cache: false
注意事项与边缘情况:
- 通过
--affected自动检测GitHub Actions——其他CI提供商可能需要手动使用GITHUB_BASE_REF--filter - 返回JSON——使用
turbo query affected解析以实现条件CI步骤jq - 通配符相对于包目录,而非仓库根目录
outputs - 当仅想添加输入而非替换默认输入时,在中使用
inputs恢复默认输入行为$TURBO_DEFAULT$ - Remote Cache的需要
signature: true——缺失密钥会导致缓存读取静默失败(视为未命中)TURBO_REMOTE_CACHE_SIGNATURE_KEY - 输出到
--summarize——用于比较两次运行的哈希以找出变更点.turbo/runs/ - 自v2.9起允许循环包依赖(在任务图级别验证,而非包图级别)
- 参数已废弃——对长时间运行的任务使用turbo.json中的
--parallel替代persistent: true - 已废弃——使用
turbo-ignore替代以实现条件CI步骤turbo query affected - 默认值为30秒,
remoteCache.timeout为60秒——大型monorepo产物可增加该值uploadTimeout
</red_flags>
<critical_reminders>
CRITICAL REMINDERS
关键提醒
All code must follow project conventions in CLAUDE.md
(You MUST declare for every cacheable task in turbo.json -- missing outputs means cached results restore without build artifacts)
outputs(You MUST list environment variables that affect task output in (task-level) or (all tasks) -- omitting them causes cross-environment cache hits with wrong values)
envglobalEnv(You MUST use for PR builds -- running the full task graph on PRs wastes CI time on unchanged packages)
--affected(You MUST pin the CLI version in CI -- can introduce breaking changes mid-pipeline)
turbolatestFailure to follow these rules will cause incorrect cache hits (wrong build artifacts served), slow CI (full rebuilds on every PR), and non-reproducible pipelines.
</critical_reminders>
所有代码必须遵循CLAUDE.md中的项目约定
(必须在turbo.json中为所有可缓存任务声明——缺失outputs会导致缓存结果恢复时没有构建产物)
outputs(必须将影响任务输出的环境变量列在(任务级别)或(所有任务)中——遗漏会导致跨环境缓存命中并返回错误值)
envglobalEnv(PR构建必须使用——对PR运行完整任务图会在未变更的包上浪费CI时间)
--affected(必须在CI中固定 CLI版本——使用可能会在流水线运行中引入破坏性变更)
turbolatest不遵循这些规则会导致错误的缓存命中(返回错误的构建产物)、缓慢的CI(每个PR都全量重建)以及不可复现的流水线。
</critical_reminders>