Compare commits
276 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fe695b334e | |||
| 7f7bba633d | |||
| 1a15ea183a | |||
| 8c0600225a | |||
| 832355081b | |||
| 1081c320ab | |||
| bdeeb036fb | |||
| 4b1bf5f7ba | |||
| f935d9a7bf | |||
| dd325d790a | |||
| ed786fb12c | |||
| cc5eeefde9 | |||
| cf53d15ae5 | |||
| 7351e21150 | |||
| c5ab66152a | |||
| 1805301941 | |||
| e8633e0299 | |||
| 6bcaa46864 | |||
| d545472da8 | |||
| 025db33a75 | |||
| 731db47fd7 | |||
| 4b6aea9f5e | |||
| 0568059fb8 | |||
| 3e5df300ab | |||
| 221ed882fa | |||
| df8a2c43f4 | |||
| 391d23c65e | |||
| 092cea6073 | |||
| de2dc7ca13 | |||
| 5236e02308 | |||
| 8e1d873edc | |||
| 4ca3ee97c3 | |||
| e6ad74afed | |||
| 79f41e54af | |||
| 4f9be499b4 | |||
| 42b534366d | |||
| 7528cc51fa | |||
| bbb1baa631 | |||
| 91b350efa8 | |||
| 50ca951540 | |||
| 18bfb0bc4a | |||
| 3b0fb81570 | |||
| bdbc14902e | |||
| dc6716828b | |||
| 8de74d0984 | |||
| b89c3084e7 | |||
| bdf6d257b7 | |||
| 678cd321f5 | |||
| a0e34557f9 | |||
| 5c7c9dd5fa | |||
| 4f31277f4f | |||
| c16377af25 | |||
| 130cec466f | |||
| 65b94a1293 | |||
| 896a3f31ad | |||
| ea81b52442 | |||
| edc9cc5af8 | |||
| 2fa93afe2b | |||
| ee22084d1a | |||
| ca2fc0fa85 | |||
| 0c14bcbe55 | |||
| 08d899a2d2 | |||
| 0d4160e968 | |||
| 8c15428f43 | |||
| 59b12edcb6 | |||
| dd3b79ebf4 | |||
| d64e41dd99 | |||
| f5769f0bfb | |||
| 292a21319d | |||
| c5e1bedca2 | |||
| c0540c8846 | |||
| ece9b5bf4a | |||
| 51420790c3 | |||
| c407de6e2b | |||
| 950265fc8c | |||
| 28fea0db0c | |||
| b5c3663126 | |||
| a757f40d83 | |||
| 7a4e052533 | |||
| 9a57042cbe | |||
| 754b01a066 | |||
| 5a1735b041 | |||
| a0ff232ad7 | |||
| 17f2f1bdc6 | |||
| e48f2f3a8c | |||
| 7785eae516 | |||
| 28c5d95964 | |||
| 0e53c3f3d5 | |||
| 6bf8c4693f | |||
| 8e3cff657b | |||
| 15d508e814 | |||
| 6570674abf | |||
| 2d71d9ac65 | |||
| f43d2028ff | |||
| 6c9f0cb46d | |||
| bd13929de8 | |||
| f5a7ea1606 | |||
| 9c42292ed8 | |||
| ec0f51ed75 | |||
| 5ae53ecae8 | |||
| 5066511576 | |||
| 0b6961b0d7 | |||
| 089e111fcc | |||
| 93fddd14de | |||
| f1873b27a8 | |||
| 81c157d063 | |||
| 1f5520ebb1 | |||
| 0aef1ef26f | |||
| 693f75149a | |||
| 5e4dd04b66 | |||
| 8280910e48 | |||
| 37a69f0c9d | |||
| 359c7fbf4e | |||
| 0d2882e1c0 | |||
| 541498f58a | |||
| b85ac155cf | |||
| 5f42ccc3e9 | |||
| 8fdfc523a8 | |||
| a44a27b29a | |||
| 0cac182b73 | |||
| b69ff4ceb9 | |||
| 4337d2e928 | |||
| a0be6adcf8 | |||
| dffdfa694c | |||
| a40ff52db0 | |||
| bd41ce5692 | |||
| 1f09a5d1a5 | |||
| 0b99f560d4 | |||
| 866d5b1e9b | |||
| d4ad62f522 | |||
| 3aff575002 | |||
| 7df9d96dac | |||
| 05fb208fda | |||
| 33f031be04 | |||
| 0e11f95163 | |||
| 2b07ac22c2 | |||
| efa364f73d | |||
| 82265ff157 | |||
| 015ff1a45b | |||
| cdb4bb2acc | |||
| 3c7f94e3d5 | |||
| ef55f97df3 | |||
| 5880551c6a | |||
| fb6c2982e6 | |||
| 81944b02c5 | |||
| c1cc626e52 | |||
| 6f3d38ad3c | |||
| d0e4a92738 | |||
| 2ea6961e0d | |||
| 1195565b96 | |||
| 7478cbb59d | |||
| 79d878f240 | |||
| b198606bef | |||
| 1cb6c0b14c | |||
| 3f6bdc7ff7 | |||
| cc4ec68bce | |||
| 01d2f64b90 | |||
| 39d8a9a6ac | |||
| 4f02c6b56e | |||
| 3f77cd5927 | |||
| 89aa25e5d0 | |||
| cdd735dc63 | |||
| f59c15a410 | |||
| 94319c7531 | |||
| 35bc17e4fe | |||
| d65dcfa806 | |||
| e35dcd2050 | |||
| 251121530d | |||
| ec110b7bff | |||
| bd627f1096 | |||
| e3eedf9e94 | |||
| eb678bfa59 | |||
| dc8839365f | |||
| 3f05214013 | |||
| 86de174d86 | |||
| d9f2ed0d44 | |||
| c331bf949c | |||
| 3d62c8b5c1 | |||
| 9c3a9d7e13 | |||
| e189dcc101 | |||
| 4f4b9dc048 | |||
| fdabc14892 | |||
| da3b00f961 | |||
| 8d5b316fdd | |||
| b53fd7c7f5 | |||
| 5a424fa8df | |||
| cf043b7e20 | |||
| 7276e4cff7 | |||
| f9258c9d82 | |||
| 8b245f1b0a | |||
| a092ed06c4 | |||
| de67da4bc6 | |||
| f89ccb091f | |||
| 2bd8ef3f72 | |||
| 0e8893faea | |||
| f9ab939c74 | |||
| 7a446e4979 | |||
| 0f33fa6c40 | |||
| e108dac1bb | |||
| 3fcd2008ef | |||
| 75f36edb8f | |||
| 3672e1a3ea | |||
| bc9b3229c6 | |||
| a15881db1a | |||
| 1dd4262336 | |||
| 687357c82e | |||
| 3d1e544812 | |||
| 9bb69383b8 | |||
| 1831ace87e | |||
| 478afc7046 | |||
| 1299d044eb | |||
| 273a474047 | |||
| f016664557 | |||
| 81bb7d3d17 | |||
| 587659cb03 | |||
| 05de3ff450 | |||
| 8fee466a1f | |||
| d6572f3de4 | |||
| 367986dea1 | |||
| 6ae0fd1217 | |||
| 1b12e1fc6f | |||
| fc8072930a | |||
| b6ed6cbca8 | |||
| 162fca17c4 | |||
| e57848cea7 | |||
| 5f51a4b268 | |||
| 2039a5e119 | |||
| 411e2e2453 | |||
| f4bb7d734f | |||
| e586896470 | |||
| d2335186ac | |||
| 2d7e24ce68 | |||
| 6bb82c0c2e | |||
| 0137ea2dc9 | |||
| 6754cde03a | |||
| 4202f2c760 | |||
| 323554b335 | |||
| 643a6be8be | |||
| 6092966ce4 | |||
| 25442271ab | |||
| e343bd27d8 | |||
| 07a68baab9 | |||
| 7e12359221 | |||
| 21d1555d78 | |||
| 1b12b392b7 | |||
| fe0757c981 | |||
| 88098cc5f7 | |||
| acb4d3cb3d | |||
| 95300a20cc | |||
| 45f2ae303a | |||
| 4816c5514a | |||
| 42b1f144da | |||
| d6b01597e4 | |||
| 60e0fcde01 | |||
| e1bb85254c | |||
| 85deb8bc66 | |||
| 574d841837 | |||
| 6bf261d9d0 | |||
| 0777cb87cf | |||
| 6cde9c075e | |||
| f23d48512e | |||
| 246d4fd636 | |||
| 0bb9d67f0b | |||
| df99ad50c7 | |||
| 6be0a7eb56 | |||
| 2d87134710 | |||
| c69dd7f146 | |||
| 2045c829a3 | |||
| 64f2be4605 | |||
| 8b7dc6c8bf | |||
| 6cca28c798 | |||
| 4e7e9468fe | |||
| 7f68286bad | |||
| 42a8a44b26 | |||
| 0fe39b2931 | |||
| fb93570d09 |
@@ -30,5 +30,16 @@
|
||||
"enableAllProjectMcpServers": true,
|
||||
"env": {
|
||||
"BASH_MAX_TIMEOUT_MS": "1800000"
|
||||
},
|
||||
"extraKnownMarketplaces": {
|
||||
"nx-claude-plugins": {
|
||||
"source": {
|
||||
"source": "github",
|
||||
"repo": "nrwl/nx-ai-agents-config"
|
||||
}
|
||||
}
|
||||
},
|
||||
"enabledPlugins": {
|
||||
"nx@nx-claude-plugins": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
---
|
||||
name: ci-watcher
|
||||
description: Polls Nx Cloud CI pipeline and self-healing status. Returns structured state when actionable. Spawned by /nx-cloud-ci-monitor command to monitor CI Attempt status.
|
||||
model: fast
|
||||
---
|
||||
|
||||
# CI Watcher Subagent
|
||||
|
||||
You are a CI monitoring subagent responsible for polling Nx Cloud CI Attempt status and self-healing state. You report status back to the main agent - you do NOT make apply/reject decisions.
|
||||
|
||||
## Your Responsibilities
|
||||
|
||||
1. Poll CI status using the `ci_information` MCP tool
|
||||
2. Implement exponential backoff between polls
|
||||
3. Return structured state when an actionable condition is reached
|
||||
4. Track iteration count and elapsed time
|
||||
5. Output status updates based on verbosity level
|
||||
|
||||
## Input Parameters (from Main Agent)
|
||||
|
||||
The main agent may provide these optional parameters in the prompt:
|
||||
|
||||
| Parameter | Description |
|
||||
| ------------------- | -------------------------------------------------------- |
|
||||
| `branch` | Branch to monitor (auto-detected if not provided) |
|
||||
| `expectedCommitSha` | Commit SHA that should trigger a new CI Attempt |
|
||||
| `previousCipeUrl` | CI Attempt URL before the action (to detect change) |
|
||||
| `subagentTimeout` | Polling timeout in minutes (default: 60) |
|
||||
| `verbosity` | Output level: minimal, medium, verbose (default: medium) |
|
||||
|
||||
When `expectedCommitSha` or `previousCipeUrl` is provided, you must detect whether a new CI Attempt has spawned.
|
||||
|
||||
## MCP Tool Reference
|
||||
|
||||
### `ci_information`
|
||||
|
||||
**Input:**
|
||||
|
||||
```json
|
||||
{
|
||||
"branch": "string (optional, defaults to current git branch)",
|
||||
"select": "string (optional, comma-separated field names)",
|
||||
"pageToken": "number (optional, 0-based pagination for long strings)"
|
||||
}
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```json
|
||||
{
|
||||
"cipeStatus": "NOT_STARTED | IN_PROGRESS | SUCCEEDED | FAILED | CANCELED | TIMED_OUT",
|
||||
"cipeUrl": "string",
|
||||
"branch": "string",
|
||||
"commitSha": "string | null",
|
||||
"failedTaskIds": "string[]",
|
||||
"verifiedTaskIds": "string[]",
|
||||
"selfHealingEnabled": "boolean",
|
||||
"selfHealingStatus": "NOT_STARTED | IN_PROGRESS | COMPLETED | FAILED | NOT_EXECUTABLE | null",
|
||||
"verificationStatus": "NOT_STARTED | IN_PROGRESS | COMPLETED | FAILED | NOT_EXECUTABLE | null",
|
||||
"userAction": "NONE | APPLIED | REJECTED | APPLIED_LOCALLY | APPLIED_AUTOMATICALLY | null",
|
||||
"failureClassification": "string | null",
|
||||
"taskOutputSummary": "string | null",
|
||||
"suggestedFixReasoning": "string | null",
|
||||
"suggestedFixDescription": "string | null",
|
||||
"suggestedFix": "string | null",
|
||||
"shortLink": "string | null",
|
||||
"couldAutoApplyTasks": "boolean | null",
|
||||
"confidence": "number | null",
|
||||
"confidenceReasoning": "string | null"
|
||||
}
|
||||
```
|
||||
|
||||
**Select Parameter:**
|
||||
|
||||
| Usage | Returns |
|
||||
| --------------- | ----------------------------------------------------------- |
|
||||
| No `select` | Formatted overview (truncated, not recommended for polling) |
|
||||
| Single field | Raw value with pagination for long strings |
|
||||
| Multiple fields | Object with requested field values |
|
||||
|
||||
**Field Sets for Efficient Polling:**
|
||||
|
||||
```yaml
|
||||
WAIT_FIELDS:
|
||||
'cipeUrl,commitSha,cipeStatus'
|
||||
# Minimal fields for detecting new CI Attempt
|
||||
|
||||
LIGHT_FIELDS:
|
||||
'cipeStatus,cipeUrl,branch,commitSha,selfHealingStatus,verificationStatus,userAction,failedTaskIds,verifiedTaskIds,selfHealingEnabled,failureClassification,couldAutoApplyTasks,shortLink,confidence,confidenceReasoning'
|
||||
# Status fields for determining actionable state
|
||||
|
||||
HEAVY_FIELDS:
|
||||
'taskOutputSummary,suggestedFix,suggestedFixReasoning,suggestedFixDescription'
|
||||
# Large content fields - fetch only when returning to main agent
|
||||
```
|
||||
|
||||
## Initial Wait
|
||||
|
||||
Before first poll, wait based on context:
|
||||
|
||||
- **Fresh start (no expected CIPE):** Wait 60 seconds to allow CI to start
|
||||
- **Expecting new CIPE:** Wait 30 seconds (action already triggered)
|
||||
|
||||
**IMPORTANT:** Always run sleep in foreground, NOT as background command.
|
||||
|
||||
```bash
|
||||
sleep 60 # or 30 if expecting new CIPE (FOREGROUND, not background)
|
||||
```
|
||||
|
||||
## Two-Phase Operation
|
||||
|
||||
The subagent operates in one of two modes depending on input:
|
||||
|
||||
### Mode 1: Fresh Start (no `expectedCommitSha` or `previousCipeUrl`)
|
||||
|
||||
Normal polling - process whatever CIPE is returned by `ci_information`.
|
||||
|
||||
### Mode 2: Wait-for-New-CIPE (when `expectedCommitSha` or `previousCipeUrl` provided)
|
||||
|
||||
**CRITICAL**: When expecting a new CIPE, the subagent must **completely ignore** the old/stale CIPE. Do NOT process its status, do NOT return actionable states based on it.
|
||||
|
||||
#### Phase A: Wait Mode
|
||||
|
||||
1. Start a **new-CIPE timeout** timer (default: 30 minutes)
|
||||
2. On each poll of `ci_information`:
|
||||
- Check if CIPE is NEW:
|
||||
- `cipeUrl` differs from `previousCipeUrl` → **new CIPE detected**
|
||||
- `commitSha` matches `expectedCommitSha` → **correct CIPE detected**
|
||||
- If still OLD CIPE: **ignore all status fields**, just wait and poll again
|
||||
- Do NOT return `fix_available`, `ci_success`, etc. based on old CIPE!
|
||||
3. Output wait status (see below)
|
||||
4. If timeout (30 min) reached → return `no_new_cipe`
|
||||
|
||||
#### Phase B: Normal Polling (after new CIPE detected)
|
||||
|
||||
Once new CIPE is detected:
|
||||
|
||||
1. Clear the new-CIPE timeout
|
||||
2. Switch to normal polling mode
|
||||
3. Process the NEW CIPE's status normally
|
||||
4. Return when actionable state reached
|
||||
|
||||
### Wait Mode Output
|
||||
|
||||
While in wait mode, output clearly that you're waiting (not processing):
|
||||
|
||||
```
|
||||
[CI Monitor] ═══════════════════════════════════════════════════════
|
||||
[CI Monitor] WAIT MODE - Expecting new CI Attempt
|
||||
[CI Monitor] Expected SHA: <expectedCommitSha>
|
||||
[CI Monitor] Previous CI Attempt: <previousCipeUrl>
|
||||
[CI Monitor] ═══════════════════════════════════════════════════════
|
||||
|
||||
[CI Monitor] Polling... (elapsed: 0m 30s)
|
||||
[CI Monitor] Still seeing previous CI Attempt (ignoring): <oldCipeUrl>
|
||||
|
||||
[CI Monitor] Polling... (elapsed: 1m 30s)
|
||||
[CI Monitor] Still seeing previous CI Attempt (ignoring): <oldCipeUrl>
|
||||
|
||||
[CI Monitor] Polling... (elapsed: 2m 30s)
|
||||
[CI Monitor] ✓ New CI Attempt detected! URL: <newCipeUrl>, SHA: <newCommitSha>
|
||||
[CI Monitor] Switching to normal polling mode...
|
||||
```
|
||||
|
||||
### Why This Matters (Context Preservation)
|
||||
|
||||
**The problem**: Stale CIPE data can be very large:
|
||||
|
||||
- `taskOutputSummary`: potentially thousands of characters of build/test output
|
||||
- `suggestedFix`: entire patch files
|
||||
- `suggestedFixReasoning`: detailed explanation
|
||||
|
||||
If subagent returns stale CIPE data to main agent, it **pollutes main agent's context** with useless information (we already processed that CIPE). This wastes valuable context window.
|
||||
|
||||
**Without wait mode:**
|
||||
|
||||
1. Poll `ci_information` → get old CIPE with huge data
|
||||
2. Return to main agent with all that stale data
|
||||
3. Main agent's context gets polluted with useless info
|
||||
4. Main agent has to process/ignore it anyway
|
||||
|
||||
**With wait mode:**
|
||||
|
||||
1. Poll `ci_information` → get old CIPE → **ignore it, don't return**
|
||||
2. Keep waiting internally (stale data stays in subagent)
|
||||
3. New CIPE appears → switch to normal mode
|
||||
4. Return to main agent with only the NEW, relevant CIPE data
|
||||
|
||||
## Polling Loop
|
||||
|
||||
### Subagent State Management
|
||||
|
||||
Maintain internal accumulated state across polls:
|
||||
|
||||
```
|
||||
accumulated_state = {}
|
||||
```
|
||||
|
||||
### Call `ci_information` MCP Tool
|
||||
|
||||
**Wait Mode (expecting new CI Attempt):**
|
||||
|
||||
```
|
||||
ci_information({
|
||||
branch: "<branch_name>",
|
||||
select: "cipeUrl,commitSha,cipeStatus"
|
||||
})
|
||||
```
|
||||
|
||||
Only fetch minimal fields needed to detect CI Attempt change. Do NOT fetch heavy fields - stale data wastes context.
|
||||
|
||||
**Normal Mode (processing CI Attempt):**
|
||||
|
||||
```
|
||||
ci_information({
|
||||
branch: "<branch_name>",
|
||||
select: "cipeStatus,cipeUrl,branch,commitSha,selfHealingStatus,verificationStatus,userAction,failedTaskIds,verifiedTaskIds,selfHealingEnabled,failureClassification,couldAutoApplyTasks,shortLink,confidence,confidenceReasoning"
|
||||
})
|
||||
```
|
||||
|
||||
Merge response into `accumulated_state` after each poll.
|
||||
|
||||
### Analyze Response
|
||||
|
||||
**If in Wait Mode** (expecting new CIPE):
|
||||
|
||||
1. Check if CIPE is new (see Two-Phase Operation above)
|
||||
2. If old CIPE → **ignore status**, output wait message, poll again
|
||||
3. If new CIPE → switch to normal mode, continue below
|
||||
|
||||
**If in Normal Mode**:
|
||||
Based on the response, decide whether to **keep polling** or **return to main agent**.
|
||||
|
||||
### Keep Polling When
|
||||
|
||||
Continue polling (with backoff) if ANY of these conditions are true:
|
||||
|
||||
| Condition | Reason |
|
||||
| --------------------------------------- | ---------------------------------------- |
|
||||
| `cipeStatus == 'IN_PROGRESS'` | CI still running |
|
||||
| `cipeStatus == 'NOT_STARTED'` | CI hasn't started yet |
|
||||
| `selfHealingStatus == 'IN_PROGRESS'` | Self-healing agent working |
|
||||
| `selfHealingStatus == 'NOT_STARTED'` | Self-healing not started yet |
|
||||
| `failureClassification == 'FLAKY_TASK'` | Auto-rerun in progress |
|
||||
| `userAction == 'APPLIED_AUTOMATICALLY'` | New CI Attempt spawning after auto-apply |
|
||||
|
||||
When `couldAutoApplyTasks == true`:
|
||||
|
||||
- `verificationStatus` = `NOT_STARTED`, `IN_PROGRESS` → keep polling (verification still in progress)
|
||||
- `verificationStatus` = `COMPLETED` → return `fix_auto_applying` (auto-apply will happen, main agent spawns wait mode subagent)
|
||||
- `verificationStatus` = `FAILED`, `NOT_EXECUTABLE` → return `fix_available` (auto-apply won't happen, needs manual action)
|
||||
|
||||
### Exponential Backoff
|
||||
|
||||
Between polls, wait with exponential backoff:
|
||||
|
||||
| Poll Attempt | Wait Time |
|
||||
| ------------ | ----------------- |
|
||||
| 1st | 60 seconds |
|
||||
| 2nd | 90 seconds |
|
||||
| 3rd+ | 120 seconds (cap) |
|
||||
|
||||
Reset to 60 seconds when state changes significantly.
|
||||
|
||||
**IMPORTANT:** Run sleep in foreground (NOT as background command). Background sleep causes "What should Claude do?" prompts when completed.
|
||||
|
||||
```bash
|
||||
# Example backoff - run in FOREGROUND
|
||||
sleep 60 # First wait
|
||||
sleep 90 # Second wait
|
||||
sleep 120 # Third and subsequent waits (capped)
|
||||
```
|
||||
|
||||
### Fetch Heavy Fields on Actionable State
|
||||
|
||||
Before returning to main agent, fetch heavy fields if the status requires them:
|
||||
|
||||
| Status | Heavy Fields Needed |
|
||||
| ------------------- | ------------------------------------------------------------------------------ |
|
||||
| `ci_success` | None |
|
||||
| `fix_auto_applying` | None |
|
||||
| `fix_available` | `taskOutputSummary,suggestedFix,suggestedFixReasoning,suggestedFixDescription` |
|
||||
| `fix_failed` | `taskOutputSummary` |
|
||||
| `no_fix` | `taskOutputSummary` |
|
||||
| `environment_issue` | None |
|
||||
| `no_new_cipe` | None |
|
||||
| `polling_timeout` | None |
|
||||
| `cipe_canceled` | None |
|
||||
| `cipe_timed_out` | None |
|
||||
|
||||
```
|
||||
# Example: fetching heavy fields for fix_available
|
||||
ci_information({
|
||||
branch: "<branch_name>",
|
||||
select: "taskOutputSummary,suggestedFix,suggestedFixReasoning,suggestedFixDescription"
|
||||
})
|
||||
```
|
||||
|
||||
Merge response into `accumulated_state`, then return merged state to main agent.
|
||||
|
||||
**Pagination:** Heavy string fields return first page only. If `hasMore` indicated, include in return format so main agent knows more content available.
|
||||
|
||||
### Return to Main Agent When
|
||||
|
||||
Return immediately with structured state if ANY of these conditions are true:
|
||||
|
||||
| Status | Condition |
|
||||
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci_success` | `cipeStatus == 'SUCCEEDED'` |
|
||||
| `fix_auto_applying` | `selfHealingStatus == 'COMPLETED'` AND `couldAutoApplyTasks == true` AND `verificationStatus == 'COMPLETED'` |
|
||||
| `fix_available` | `selfHealingStatus == 'COMPLETED'` AND `suggestedFix != null` AND (`couldAutoApplyTasks != true` OR `verificationStatus` in (`FAILED`, `NOT_EXECUTABLE`)) |
|
||||
| `fix_failed` | `selfHealingStatus == 'FAILED'` |
|
||||
| `environment_issue` | `failureClassification == 'ENVIRONMENT_STATE'` |
|
||||
| `no_fix` | `cipeStatus == 'FAILED'` AND (`selfHealingEnabled == false` OR `selfHealingStatus == 'NOT_EXECUTABLE'`) |
|
||||
| `no_new_cipe` | `expectedCommitSha` or `previousCipeUrl` provided, but no new CI Attempt detected after 30 min |
|
||||
| `polling_timeout` | Subagent has been polling for > configured timeout (default 60 min) |
|
||||
| `cipe_canceled` | `cipeStatus == 'CANCELED'` |
|
||||
| `cipe_timed_out` | `cipeStatus == 'TIMED_OUT'` |
|
||||
|
||||
## Subagent Timeout
|
||||
|
||||
Track elapsed time. If you have been polling for more than **60 minutes** (configurable via main agent), return with `status: polling_timeout`.
|
||||
|
||||
## Return Format
|
||||
|
||||
When returning to the main agent, provide a structured response with accumulated state:
|
||||
|
||||
```
|
||||
## CI Monitor Result
|
||||
|
||||
**Status:** <status>
|
||||
**Iterations:** <count>
|
||||
**Elapsed:** <minutes>m <seconds>s
|
||||
|
||||
### CI Attempt Details
|
||||
- **Status:** <cipeStatus>
|
||||
- **URL:** <cipeUrl>
|
||||
- **Branch:** <branch>
|
||||
- **Commit:** <commitSha>
|
||||
- **Failed Tasks:** <failedTaskIds>
|
||||
- **Verified Tasks:** <verifiedTaskIds>
|
||||
|
||||
### Self-Healing Details
|
||||
- **Enabled:** <selfHealingEnabled>
|
||||
- **Status:** <selfHealingStatus>
|
||||
- **Verification:** <verificationStatus>
|
||||
- **User Action:** <userAction>
|
||||
- **Classification:** <failureClassification>
|
||||
- **Confidence:** <confidence>
|
||||
- **Confidence Reasoning:** <confidenceReasoning>
|
||||
|
||||
### Fix Information (if available)
|
||||
- **Short Link:** <shortLink>
|
||||
- **Description:** <suggestedFixDescription>
|
||||
- **Reasoning:** <suggestedFixReasoning>
|
||||
|
||||
### Task Output Summary (first page)
|
||||
<taskOutputSummary>
|
||||
[MORE_CONTENT_AVAILABLE: taskOutputSummary, pageToken: 1]
|
||||
|
||||
### Suggested Fix (first page)
|
||||
<suggestedFix>
|
||||
[MORE_CONTENT_AVAILABLE: suggestedFix, pageToken: 1]
|
||||
```
|
||||
|
||||
### Pagination Indicators
|
||||
|
||||
When a heavy field has more content available, append indicator:
|
||||
|
||||
```
|
||||
[MORE_CONTENT_AVAILABLE: <fieldName>, pageToken: <nextPage>]
|
||||
```
|
||||
|
||||
Main agent can fetch additional pages if needed using:
|
||||
|
||||
```
|
||||
ci_information({ select: "<fieldName>", pageToken: <nextPage> })
|
||||
```
|
||||
|
||||
Fields that may have pagination:
|
||||
|
||||
- `taskOutputSummary` (reverse pagination - page 0 = most recent)
|
||||
- `suggestedFix` (forward pagination - page 0 = start)
|
||||
- `suggestedFixReasoning`
|
||||
|
||||
### Return Format for `no_new_cipe`
|
||||
|
||||
When returning with `status: no_new_cipe`, include additional context:
|
||||
|
||||
```
|
||||
## CI Monitor Result
|
||||
|
||||
**Status:** no_new_cipe
|
||||
**Iterations:** <count>
|
||||
**Elapsed:** <minutes>m <seconds>s
|
||||
|
||||
### Expected CI Attempt Not Found
|
||||
- **Expected Commit SHA:** <expectedCommitSha>
|
||||
- **Previous CI Attempt URL:** <previousCipeUrl>
|
||||
- **Last Seen CI Attempt URL:** <cipeUrl>
|
||||
- **Last Seen Commit SHA:** <commitSha>
|
||||
- **New CI Attempt Timeout:** 30 minutes (exceeded)
|
||||
|
||||
### Likely Cause
|
||||
CI workflow failed before Nx tasks could run (e.g., install step, checkout, auth).
|
||||
Check your CI provider logs for the commit <expectedCommitSha>.
|
||||
|
||||
### Last Known CI Attempt State
|
||||
- **Status:** <cipeStatus>
|
||||
- **Branch:** <branch>
|
||||
```
|
||||
|
||||
## Status Reporting (Verbosity-Controlled)
|
||||
|
||||
Output is controlled by the `verbosity` parameter from the main agent:
|
||||
|
||||
| Level | What to Output |
|
||||
| --------- | ----------------------------------------------------------------- |
|
||||
| `minimal` | No intermediate output. Only return final result when actionable. |
|
||||
| `medium` | Output only on significant state changes (not every poll). |
|
||||
| `verbose` | Output detailed phase information after every poll. |
|
||||
|
||||
### Minimal Verbosity
|
||||
|
||||
No output during polling. Poll silently and return when done.
|
||||
|
||||
### Medium Verbosity (Default)
|
||||
|
||||
Output **only when state changes significantly** to save context tokens:
|
||||
|
||||
- `cipeStatus` changes (e.g., IN_PROGRESS → FAILED)
|
||||
- `selfHealingStatus` changes (e.g., IN_PROGRESS → COMPLETED)
|
||||
- New CI Attempt detected (in wait mode)
|
||||
|
||||
Format: single line, no decorators:
|
||||
|
||||
```
|
||||
[CI Monitor] CI: FAILED | Self-Healing: IN_PROGRESS | Elapsed: 4m
|
||||
```
|
||||
|
||||
### Verbose Verbosity
|
||||
|
||||
Output detailed phase box after every poll:
|
||||
|
||||
```
|
||||
[CI Monitor] ─────────────────────────────────────────────────────
|
||||
[CI Monitor] Iteration <N> | Elapsed: <X>m <Y>s
|
||||
[CI Monitor]
|
||||
[CI Monitor] CI Status: <cipeStatus>
|
||||
[CI Monitor] Self-Healing: <selfHealingStatus>
|
||||
[CI Monitor] Verification: <verificationStatus>
|
||||
[CI Monitor] Classification: <failureClassification>
|
||||
[CI Monitor]
|
||||
[CI Monitor] → <human-readable phase description>
|
||||
[CI Monitor] ─────────────────────────────────────────────────────
|
||||
```
|
||||
|
||||
### Phase Descriptions (for verbose output)
|
||||
|
||||
| Status Combo | Description |
|
||||
| ----------------------------------------------------------------------------------------- | ------------------------------------------- |
|
||||
| `cipeStatus: IN_PROGRESS` | "CI running..." |
|
||||
| `cipeStatus: NOT_STARTED` | "Waiting for CI to start..." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: NOT_STARTED` | "CI failed. Self-healing starting..." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: IN_PROGRESS` | "CI failed. Self-healing generating fix..." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: COMPLETED` + `verificationStatus: IN_PROGRESS` | "Fix generated! Verification running..." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: COMPLETED` + `verificationStatus: COMPLETED` | "Fix ready! Verified successfully." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: COMPLETED` + `verificationStatus: FAILED` | "Fix generated but verification failed." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: FAILED` | "Self-healing could not generate a fix." |
|
||||
| `cipeStatus: SUCCEEDED` | "CI passed!" |
|
||||
|
||||
## Important Notes
|
||||
|
||||
- You do NOT make apply/reject decisions - that's the main agent's job
|
||||
- You do NOT perform git operations
|
||||
- You only poll and report state
|
||||
- Respect the `verbosity` parameter for output (default: medium)
|
||||
- If `ci_information` returns an error, wait and retry (count as failed poll)
|
||||
- Track consecutive failures - if 5 consecutive failures, return with `status: error`
|
||||
- When expecting new CI Attempt, track the 30-minute new-CI-Attempt timeout separately from the main polling timeout
|
||||
@@ -0,0 +1,428 @@
|
||||
# CI Monitor Command
|
||||
|
||||
You are the orchestrator for monitoring Nx Cloud CI pipeline executions and handling self-healing fixes. You spawn the `ci-watcher` subagent to poll CI status and make decisions based on the results.
|
||||
|
||||
## Context
|
||||
|
||||
- **Current Branch:** !`git branch --show-current`
|
||||
- **Current Commit:** !`git rev-parse --short HEAD`
|
||||
- **Remote Status:** !`git status -sb | head -1`
|
||||
|
||||
## User Instructions
|
||||
|
||||
**Important:** If user provides specific instructions, respect them over default behaviors described below.
|
||||
|
||||
## Configuration Defaults
|
||||
|
||||
| Setting | Default | Description |
|
||||
| ------------------------- | ------------- | ------------------------------------------------------------------- |
|
||||
| `--max-cycles` | 10 | Maximum CIPE cycles before timeout |
|
||||
| `--timeout` | 120 | Maximum duration in minutes |
|
||||
| `--verbosity` | medium | Output level: minimal, medium, verbose |
|
||||
| `--branch` | (auto-detect) | Branch to monitor |
|
||||
| `--subagent-timeout` | 60 | Subagent polling timeout in minutes |
|
||||
| `--fresh` | false | Ignore previous context, start fresh |
|
||||
| `--auto-fix-workflow` | false | Attempt common fixes for pre-CIPE failures (e.g., lockfile updates) |
|
||||
| `--new-cipe-timeout` | 10 | Minutes to wait for new CIPE after action |
|
||||
| `--local-verify-attempts` | 3 | Max local verification + enhance cycles before pushing to CI |
|
||||
|
||||
## Nx Cloud Connection Check
|
||||
|
||||
**CRITICAL**: Before starting the monitoring loop, verify the workspace is connected to Nx Cloud.
|
||||
|
||||
### Step 0: Verify Nx Cloud Connection
|
||||
|
||||
1. **Check `nx.json`** at workspace root for `nxCloudId` or `nxCloudAccessToken`
|
||||
2. **If `nx.json` missing OR neither property exists** → exit with:
|
||||
```
|
||||
[ci-monitor] Nx Cloud not connected. Unlock 70% faster CI and auto-fix broken PRs with https://nx.dev/nx-cloud
|
||||
```
|
||||
3. **If connected** → continue to main loop
|
||||
|
||||
## Session Context Behavior
|
||||
|
||||
**Important:** Within a Claude Code session, conversation context persists. If you Ctrl+C to interrupt the monitor and re-run `/ci-monitor`, Claude remembers the previous state and may continue from where it left off.
|
||||
|
||||
- **To continue monitoring:** Just re-run `/ci-monitor` (context is preserved)
|
||||
- **To start fresh:** Use `/ci-monitor --fresh` to ignore previous context
|
||||
- **For a completely clean slate:** Exit Claude Code and restart `claude`
|
||||
|
||||
## Default Behaviors by Status
|
||||
|
||||
The subagent returns with one of the following statuses. This table defines the **default behavior** for each status. User instructions can override any of these.
|
||||
|
||||
| Status | Default Behavior |
|
||||
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci_success` | Exit with success. Log "CI passed successfully!" |
|
||||
| `fix_auto_applying` | Fix will be auto-applied by self-healing. Do NOT call MCP. Record `last_cipe_url`, spawn new subagent in wait mode to poll for new CIPE. |
|
||||
| `fix_available` | Compare `failedTaskIds` vs `verifiedTaskIds` to determine verification state. See **Fix Available Decision Logic** section below. |
|
||||
| `fix_failed` | Self-healing failed to generate fix. Attempt local fix based on `taskOutputSummary`. If successful → commit, push, loop. If not → exit with failure. |
|
||||
| `environment_issue` | Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`. New CIPE spawns automatically. Loop to poll for new CIPE. |
|
||||
| `no_fix` | CI failed, no fix available (self-healing disabled or not executable). Attempt local fix if possible. Otherwise exit with failure. |
|
||||
| `no_new_cipe` | Expected CIPE never spawned (CI workflow likely failed before Nx tasks). Report to user, attempt common fixes if configured, or exit with guidance. |
|
||||
| `polling_timeout` | Subagent polling timeout reached. Exit with timeout. |
|
||||
| `cipe_canceled` | CIPE was canceled. Exit with canceled status. |
|
||||
| `cipe_timed_out` | CIPE timed out. Exit with timeout status. |
|
||||
| `error` | Increment `no_progress_count`. If >= 3 → exit with circuit breaker. Otherwise wait 60s and loop. |
|
||||
|
||||
### Fix Available Decision Logic
|
||||
|
||||
When subagent returns `fix_available`, main agent compares `failedTaskIds` vs `verifiedTaskIds`:
|
||||
|
||||
#### Step 1: Categorize Tasks
|
||||
|
||||
1. **Verified tasks** = tasks in both `failedTaskIds` AND `verifiedTaskIds`
|
||||
2. **Unverified tasks** = tasks in `failedTaskIds` but NOT in `verifiedTaskIds`
|
||||
3. **E2E tasks** = unverified tasks where target contains "e2e" (task format: `<project>:<target>` or `<project>:<target>:<config>`)
|
||||
4. **Verifiable tasks** = unverified tasks that are NOT e2e
|
||||
|
||||
#### Step 2: Determine Path
|
||||
|
||||
| Condition | Path |
|
||||
| --------------------------------------- | ---------------------------------------- |
|
||||
| No unverified tasks (all verified) | Apply via MCP |
|
||||
| Unverified tasks exist, but ALL are e2e | Apply via MCP (treat as verified enough) |
|
||||
| Verifiable tasks exist | Local verification flow |
|
||||
|
||||
#### Step 3a: Apply via MCP (fully/e2e-only verified)
|
||||
|
||||
- Call `update_self_healing_fix({ shortLink, action: "APPLY" })`
|
||||
- Record `last_cipe_url`, spawn subagent in wait mode
|
||||
|
||||
#### Step 3b: Local Verification Flow
|
||||
|
||||
When verifiable (non-e2e) unverified tasks exist:
|
||||
|
||||
1. **Detect package manager:**
|
||||
- `pnpm-lock.yaml` exists → `pnpm nx`
|
||||
- `yarn.lock` exists → `yarn nx`
|
||||
- Otherwise → `npx nx`
|
||||
|
||||
2. **Run verifiable tasks in parallel:**
|
||||
- Spawn `general` subagents to run each task concurrently
|
||||
- Each subagent runs: `<pm> nx run <taskId>`
|
||||
- Collect pass/fail results from all subagents
|
||||
|
||||
3. **Evaluate results:**
|
||||
|
||||
| Result | Action |
|
||||
| ------------------------- | ---------------------------- |
|
||||
| ALL verifiable tasks pass | Apply via MCP |
|
||||
| ANY verifiable task fails | Apply-locally + enhance flow |
|
||||
|
||||
4. **Apply-locally + enhance flow:**
|
||||
- Run `nx apply-locally <shortLink>`
|
||||
- Enhance the code to fix failing tasks
|
||||
- Run failing tasks again to verify fix
|
||||
- If still failing → increment `local_verify_count`, loop back to enhance
|
||||
- If passing → commit and push, record `expected_commit_sha`, spawn subagent in wait mode
|
||||
|
||||
5. **Track attempts** (wraps step 4):
|
||||
- Increment `local_verify_count` after each enhance cycle
|
||||
- If `local_verify_count >= local_verify_attempts` (default: 3):
|
||||
- Get code in commit-able state
|
||||
- Commit and push with message indicating local verification failed
|
||||
- Report to user:
|
||||
```
|
||||
[ci-monitor] Local verification failed after <N> attempts. Pushed to CI for final validation. Failed: <taskIds>
|
||||
```
|
||||
- Record `expected_commit_sha`, spawn subagent in wait mode (let CI be final judge)
|
||||
|
||||
#### Commit Message Format
|
||||
|
||||
```bash
|
||||
git commit -m "fix(<projects>): <brief description>
|
||||
|
||||
Failed tasks: <taskId1>, <taskId2>
|
||||
Local verification: passed|enhanced|failed-pushing-to-ci"
|
||||
```
|
||||
|
||||
### Unverified Fix Flow (No Verification Attempted)
|
||||
|
||||
When `verificationStatus` is `FAILED`, `NOT_EXECUTABLE`, or fix has `couldAutoApplyTasks != true` with no verification:
|
||||
|
||||
- Analyze fix content (`suggestedFix`, `suggestedFixReasoning`, `taskOutputSummary`)
|
||||
- If fix looks correct → apply via MCP
|
||||
- If fix needs enhancement → use Apply Locally + Enhance Flow above
|
||||
- If fix is wrong → reject via MCP, fix from scratch, commit, push
|
||||
|
||||
### Auto-Apply Eligibility
|
||||
|
||||
The `couldAutoApplyTasks` field indicates whether the fix is eligible for automatic application:
|
||||
|
||||
- **`true`**: Fix is eligible for auto-apply. Subagent keeps polling while verification is in progress. Returns `fix_auto_applying` when verified, or `fix_available` if verification fails.
|
||||
- **`false`** or **`null`**: Fix requires manual action (apply via MCP, apply locally, or reject)
|
||||
|
||||
**Key point**: When subagent returns `fix_auto_applying`, do NOT call MCP to apply - self-healing handles it. Just spawn a new subagent in wait mode.
|
||||
|
||||
### Apply vs Reject vs Apply Locally
|
||||
|
||||
- **Apply via MCP**: Calls `update_self_healing_fix({ shortLink, action: "APPLY" })`. Self-healing agent applies the fix in CI and a new CIPE spawns automatically. No local git operations needed.
|
||||
- **Apply Locally**: Runs `nx apply-locally <shortLink>`. Applies the patch to your local working directory and sets state to `APPLIED_LOCALLY`. Use this when you want to enhance the fix before pushing.
|
||||
- **Reject via MCP**: Calls `update_self_healing_fix({ shortLink, action: "REJECT" })`. Marks fix as rejected. Use only when the fix is completely wrong and you'll fix from scratch.
|
||||
|
||||
### Apply Locally + Enhance Flow
|
||||
|
||||
When the fix needs enhancement (use `nx apply-locally`, NOT reject):
|
||||
|
||||
1. Apply the patch locally: `nx apply-locally <shortLink>` (this also updates state to `APPLIED_LOCALLY`)
|
||||
2. Make additional changes as needed
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Reject + Fix From Scratch Flow
|
||||
|
||||
When the fix is completely wrong:
|
||||
|
||||
1. Call MCP to reject: `update_self_healing_fix({ shortLink, action: "REJECT" })`
|
||||
2. Fix the issue from scratch locally
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Environment Issue Handling
|
||||
|
||||
When `failureClassification == 'ENVIRONMENT_STATE'`:
|
||||
|
||||
1. Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`
|
||||
2. New CIPE spawns automatically (no local git operations needed)
|
||||
3. Loop to poll for new CIPE with `previousCipeUrl` set
|
||||
|
||||
### No-New-CIPE Handling
|
||||
|
||||
When `status == 'no_new_cipe'`:
|
||||
|
||||
This means the expected CIPE was never created - CI likely failed before Nx tasks could run.
|
||||
|
||||
1. **Report to user:**
|
||||
|
||||
```
|
||||
[ci-monitor] No CI attempt for <sha> after 10 min. Check CI provider for pre-Nx failures (install, checkout, auth). Last CI attempt: <previousCipeUrl>
|
||||
```
|
||||
|
||||
2. **If user configured auto-fix attempts** (e.g., `--auto-fix-workflow`):
|
||||
- Detect package manager: check for `pnpm-lock.yaml`, `yarn.lock`, `package-lock.json`
|
||||
- Run install to update lockfile:
|
||||
```bash
|
||||
pnpm install # or npm install / yarn install
|
||||
```
|
||||
- If lockfile changed:
|
||||
```bash
|
||||
git add pnpm-lock.yaml # or appropriate lockfile
|
||||
git commit -m "chore: update lockfile"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
- Record new commit SHA, loop to poll with `expectedCommitSha`
|
||||
|
||||
3. **Otherwise:** Exit with `no_new_cipe` status, providing guidance for user to investigate
|
||||
|
||||
## Exit Conditions
|
||||
|
||||
Exit the monitoring loop when ANY of these conditions are met:
|
||||
|
||||
| Condition | Exit Type |
|
||||
| ------------------------------------------- | ---------------- |
|
||||
| CI passes (`cipeStatus == 'SUCCEEDED'`) | Success |
|
||||
| Max CIPE cycles reached | Timeout |
|
||||
| Max duration reached | Timeout |
|
||||
| 3 consecutive no-progress iterations | Circuit breaker |
|
||||
| No fix available and local fix not possible | Failure |
|
||||
| No new CIPE and auto-fix not configured | Pre-CIPE failure |
|
||||
| User cancels | Cancelled |
|
||||
|
||||
## Main Loop
|
||||
|
||||
### Step 1: Initialize Tracking
|
||||
|
||||
```
|
||||
cycle_count = 0
|
||||
start_time = now()
|
||||
no_progress_count = 0
|
||||
local_verify_count = 0
|
||||
last_state = null
|
||||
last_cipe_url = null
|
||||
expected_commit_sha = null
|
||||
```
|
||||
|
||||
### Step 2: Spawn Subagent
|
||||
|
||||
Spawn the `ci-watcher` subagent to poll CI status:
|
||||
|
||||
**Fresh start (first spawn, no expected CIPE):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>."
|
||||
)
|
||||
```
|
||||
|
||||
**After action that triggers new CIPE (wait mode):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>.
|
||||
|
||||
WAIT MODE: A new CIPE should spawn. Ignore old CIPE until new one appears.
|
||||
Expected commit SHA: <expected_commit_sha>
|
||||
Previous CIPE URL: <last_cipe_url>"
|
||||
)
|
||||
```
|
||||
|
||||
### Step 3: Handle Subagent Response
|
||||
|
||||
When subagent returns:
|
||||
|
||||
1. Check the returned status
|
||||
2. Look up default behavior in the table above
|
||||
3. Check if user instructions override the default
|
||||
4. Execute the appropriate action
|
||||
5. **If action expects new CIPE**, update tracking (see Step 3a)
|
||||
6. If action results in looping, go to Step 2
|
||||
|
||||
### Step 3a: Track State for New-CIPE Detection
|
||||
|
||||
After actions that should trigger a new CIPE, record state before looping:
|
||||
|
||||
| Action | What to Track | Subagent Mode |
|
||||
| ----------------------------- | --------------------------------------------- | ------------- |
|
||||
| Fix auto-applying | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply via MCP | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply locally + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Reject + fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Fix failed + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| No fix + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Environment rerun | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| No-new-CIPE + auto-fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
|
||||
**CRITICAL**: When passing `expectedCommitSha` or `last_cipe_url` to the subagent, it enters **wait mode**:
|
||||
|
||||
- Subagent will **completely ignore** the old/stale CIPE
|
||||
- Subagent will only wait for new CIPE to appear
|
||||
- Subagent will NOT return to main agent with stale CIPE data
|
||||
- Once new CIPE detected, subagent switches to normal polling
|
||||
|
||||
**Why wait mode matters for context preservation**: Stale CIPE data can be very large (task output summaries, suggested fix patches, reasoning). If subagent returns this to main agent, it pollutes main agent's context with useless data since we already processed that CIPE. Wait mode keeps stale data in the subagent, never sending it to main agent.
|
||||
|
||||
### Step 4: Progress Tracking
|
||||
|
||||
After each action:
|
||||
|
||||
- If state changed significantly → reset `no_progress_count = 0`
|
||||
- If state unchanged → `no_progress_count++`
|
||||
- On new CI attempt detected → reset `local_verify_count = 0`
|
||||
|
||||
## Status Reporting
|
||||
|
||||
Based on verbosity level:
|
||||
|
||||
| Level | What to Report |
|
||||
| --------- | -------------------------------------------------------------------------- |
|
||||
| `minimal` | Only final result (success/failure/timeout) |
|
||||
| `medium` | State changes + periodic updates ("Cycle N \| Elapsed: Xm \| Status: ...") |
|
||||
| `verbose` | All of medium + full subagent responses, git outputs, MCP responses |
|
||||
|
||||
## User Instruction Examples
|
||||
|
||||
Users can override default behaviors:
|
||||
|
||||
| Instruction | Effect |
|
||||
| ------------------------------------------------ | --------------------------------------------- |
|
||||
| "never auto-apply" | Always prompt before applying any fix |
|
||||
| "always ask before git push" | Prompt before each push |
|
||||
| "reject any fix for e2e tasks" | Auto-reject if `failedTaskIds` contains e2e |
|
||||
| "apply all fixes regardless of verification" | Skip verification check, apply everything |
|
||||
| "if confidence < 70, reject" | Check confidence field before applying |
|
||||
| "run 'nx affected -t typecheck' before applying" | Add local verification step |
|
||||
| "auto-fix workflow failures" | Attempt lockfile updates on pre-CIPE failures |
|
||||
| "wait 45 min for new CIPE" | Override new-CIPE timeout (default: 10 min) |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Action |
|
||||
| ------------------------ | ------------------------------------------------------------------------------------- |
|
||||
| Git rebase conflict | Report to user, exit |
|
||||
| `nx apply-locally` fails | Report to user, attempt manual patch or exit |
|
||||
| MCP tool error | Retry once, if fails report to user |
|
||||
| Subagent spawn failure | Retry once, if fails exit with error |
|
||||
| No new CIPE detected | If `--auto-fix-workflow`, try lockfile update; otherwise report to user with guidance |
|
||||
| Lockfile auto-fix fails | Report to user, exit with guidance to check CI logs |
|
||||
|
||||
## Example Session
|
||||
|
||||
### Example 1: Normal Flow with Self-Healing (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-auth'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, verbosity=medium
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: IN_PROGRESS | Self-Healing: NOT_STARTED | Elapsed: 1m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: IN_PROGRESS | Elapsed: 3m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 5m
|
||||
|
||||
[ci-monitor] Fix available! Verification: COMPLETED
|
||||
[ci-monitor] Applying fix via MCP...
|
||||
[ci-monitor] Fix applied in CI. Waiting for new CI attempt...
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 8m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 2
|
||||
- Total time: 12m 34s
|
||||
- Fixes applied: 1
|
||||
- Result: SUCCESS
|
||||
```
|
||||
|
||||
### Example 2: Pre-CI Failure (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-products'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, auto-fix-workflow=true
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 2m
|
||||
|
||||
[ci-monitor] Applying fix locally, enhancing, and pushing...
|
||||
[ci-monitor] Committed: abc1234
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] Waiting for new CI attempt... (expected SHA: abc1234)
|
||||
[CI Monitor] ⚠️ CI attempt timeout (10 min). Returning no_new_cipe.
|
||||
|
||||
[ci-monitor] Status: no_new_cipe
|
||||
[ci-monitor] --auto-fix-workflow enabled. Attempting lockfile update...
|
||||
[ci-monitor] Lockfile updated. Committed: def5678
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 18m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 3
|
||||
- Total time: 22m 15s
|
||||
- Fixes applied: 1 (self-healing) + 1 (lockfile)
|
||||
- Result: SUCCESS
|
||||
```
|
||||
@@ -0,0 +1,437 @@
|
||||
---
|
||||
name: ci-monitor
|
||||
description: Monitor Nx Cloud CI pipeline and handle self-healing fixes automatically. Checks for Nx Cloud connection before starting.
|
||||
---
|
||||
|
||||
# CI Monitor Command
|
||||
|
||||
You are the orchestrator for monitoring Nx Cloud CI pipeline executions and handling self-healing fixes. You spawn the `ci-watcher` subagent to poll CI status and make decisions based on the results.
|
||||
|
||||
## Context
|
||||
|
||||
- **Current Branch:** !`git branch --show-current`
|
||||
- **Current Commit:** !`git rev-parse --short HEAD`
|
||||
- **Remote Status:** !`git status -sb | head -1`
|
||||
|
||||
## User Instructions
|
||||
|
||||
$ARGUMENTS
|
||||
|
||||
**Important:** If user provides specific instructions, respect them over default behaviors described below.
|
||||
|
||||
## Configuration Defaults
|
||||
|
||||
| Setting | Default | Description |
|
||||
| ------------------------- | ------------- | ------------------------------------------------------------------- |
|
||||
| `--max-cycles` | 10 | Maximum CIPE cycles before timeout |
|
||||
| `--timeout` | 120 | Maximum duration in minutes |
|
||||
| `--verbosity` | medium | Output level: minimal, medium, verbose |
|
||||
| `--branch` | (auto-detect) | Branch to monitor |
|
||||
| `--subagent-timeout` | 60 | Subagent polling timeout in minutes |
|
||||
| `--fresh` | false | Ignore previous context, start fresh |
|
||||
| `--auto-fix-workflow` | false | Attempt common fixes for pre-CIPE failures (e.g., lockfile updates) |
|
||||
| `--new-cipe-timeout` | 10 | Minutes to wait for new CIPE after action |
|
||||
| `--local-verify-attempts` | 3 | Max local verification + enhance cycles before pushing to CI |
|
||||
|
||||
Parse any overrides from `$ARGUMENTS` and merge with defaults.
|
||||
|
||||
## Nx Cloud Connection Check
|
||||
|
||||
**CRITICAL**: Before starting the monitoring loop, verify the workspace is connected to Nx Cloud.
|
||||
|
||||
### Step 0: Verify Nx Cloud Connection
|
||||
|
||||
1. **Check `nx.json`** at workspace root for `nxCloudId` or `nxCloudAccessToken`
|
||||
2. **If `nx.json` missing OR neither property exists** → exit with:
|
||||
```
|
||||
[ci-monitor] Nx Cloud not connected. Unlock 70% faster CI and auto-fix broken PRs with https://nx.dev/nx-cloud
|
||||
```
|
||||
3. **If connected** → continue to main loop
|
||||
|
||||
## Session Context Behavior
|
||||
|
||||
**Important:** Within a Claude Code session, conversation context persists. If you Ctrl+C to interrupt the monitor and re-run `/ci-monitor`, Claude remembers the previous state and may continue from where it left off.
|
||||
|
||||
- **To continue monitoring:** Just re-run `/ci-monitor` (context is preserved)
|
||||
- **To start fresh:** Use `/ci-monitor --fresh` to ignore previous context
|
||||
- **For a completely clean slate:** Exit Claude Code and restart `claude`
|
||||
|
||||
## Default Behaviors by Status
|
||||
|
||||
The subagent returns with one of the following statuses. This table defines the **default behavior** for each status. User instructions can override any of these.
|
||||
|
||||
| Status | Default Behavior |
|
||||
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci_success` | Exit with success. Log "CI passed successfully!" |
|
||||
| `fix_auto_applying` | Fix will be auto-applied by self-healing. Do NOT call MCP. Record `last_cipe_url`, spawn new subagent in wait mode to poll for new CIPE. |
|
||||
| `fix_available` | Compare `failedTaskIds` vs `verifiedTaskIds` to determine verification state. See **Fix Available Decision Logic** section below. |
|
||||
| `fix_failed` | Self-healing failed to generate fix. Attempt local fix based on `taskOutputSummary`. If successful → commit, push, loop. If not → exit with failure. |
|
||||
| `environment_issue` | Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`. New CIPE spawns automatically. Loop to poll for new CIPE. |
|
||||
| `no_fix` | CI failed, no fix available (self-healing disabled or not executable). Attempt local fix if possible. Otherwise exit with failure. |
|
||||
| `no_new_cipe` | Expected CIPE never spawned (CI workflow likely failed before Nx tasks). Report to user, attempt common fixes if configured, or exit with guidance. |
|
||||
| `polling_timeout` | Subagent polling timeout reached. Exit with timeout. |
|
||||
| `cipe_canceled` | CIPE was canceled. Exit with canceled status. |
|
||||
| `cipe_timed_out` | CIPE timed out. Exit with timeout status. |
|
||||
| `error` | Increment `no_progress_count`. If >= 3 → exit with circuit breaker. Otherwise wait 60s and loop. |
|
||||
|
||||
### Fix Available Decision Logic
|
||||
|
||||
When subagent returns `fix_available`, main agent compares `failedTaskIds` vs `verifiedTaskIds`:
|
||||
|
||||
#### Step 1: Categorize Tasks
|
||||
|
||||
1. **Verified tasks** = tasks in both `failedTaskIds` AND `verifiedTaskIds`
|
||||
2. **Unverified tasks** = tasks in `failedTaskIds` but NOT in `verifiedTaskIds`
|
||||
3. **E2E tasks** = unverified tasks where target contains "e2e" (task format: `<project>:<target>` or `<project>:<target>:<config>`)
|
||||
4. **Verifiable tasks** = unverified tasks that are NOT e2e
|
||||
|
||||
#### Step 2: Determine Path
|
||||
|
||||
| Condition | Path |
|
||||
| --------------------------------------- | ---------------------------------------- |
|
||||
| No unverified tasks (all verified) | Apply via MCP |
|
||||
| Unverified tasks exist, but ALL are e2e | Apply via MCP (treat as verified enough) |
|
||||
| Verifiable tasks exist | Local verification flow |
|
||||
|
||||
#### Step 3a: Apply via MCP (fully/e2e-only verified)
|
||||
|
||||
- Call `update_self_healing_fix({ shortLink, action: "APPLY" })`
|
||||
- Record `last_cipe_url`, spawn subagent in wait mode
|
||||
|
||||
#### Step 3b: Local Verification Flow
|
||||
|
||||
When verifiable (non-e2e) unverified tasks exist:
|
||||
|
||||
1. **Detect package manager:**
|
||||
- `pnpm-lock.yaml` exists → `pnpm nx`
|
||||
- `yarn.lock` exists → `yarn nx`
|
||||
- Otherwise → `npx nx`
|
||||
|
||||
2. **Run verifiable tasks in parallel:**
|
||||
- Spawn `general` subagents to run each task concurrently
|
||||
- Each subagent runs: `<pm> nx run <taskId>`
|
||||
- Collect pass/fail results from all subagents
|
||||
|
||||
3. **Evaluate results:**
|
||||
|
||||
| Result | Action |
|
||||
| ------------------------- | ---------------------------- |
|
||||
| ALL verifiable tasks pass | Apply via MCP |
|
||||
| ANY verifiable task fails | Apply-locally + enhance flow |
|
||||
|
||||
4. **Apply-locally + enhance flow:**
|
||||
- Run `nx apply-locally <shortLink>`
|
||||
- Enhance the code to fix failing tasks
|
||||
- Run failing tasks again to verify fix
|
||||
- If still failing → increment `local_verify_count`, loop back to enhance
|
||||
- If passing → commit and push, record `expected_commit_sha`, spawn subagent in wait mode
|
||||
|
||||
5. **Track attempts** (wraps step 4):
|
||||
- Increment `local_verify_count` after each enhance cycle
|
||||
- If `local_verify_count >= local_verify_attempts` (default: 3):
|
||||
- Get code in commit-able state
|
||||
- Commit and push with message indicating local verification failed
|
||||
- Report to user:
|
||||
```
|
||||
[ci-monitor] Local verification failed after <N> attempts. Pushed to CI for final validation. Failed: <taskIds>
|
||||
```
|
||||
- Record `expected_commit_sha`, spawn subagent in wait mode (let CI be final judge)
|
||||
|
||||
#### Commit Message Format
|
||||
|
||||
```bash
|
||||
git commit -m "fix(<projects>): <brief description>
|
||||
|
||||
Failed tasks: <taskId1>, <taskId2>
|
||||
Local verification: passed|enhanced|failed-pushing-to-ci"
|
||||
```
|
||||
|
||||
### Unverified Fix Flow (No Verification Attempted)
|
||||
|
||||
When `verificationStatus` is `FAILED`, `NOT_EXECUTABLE`, or fix has `couldAutoApplyTasks != true` with no verification:
|
||||
|
||||
- Analyze fix content (`suggestedFix`, `suggestedFixReasoning`, `taskOutputSummary`)
|
||||
- If fix looks correct → apply via MCP
|
||||
- If fix needs enhancement → use Apply Locally + Enhance Flow above
|
||||
- If fix is wrong → reject via MCP, fix from scratch, commit, push
|
||||
|
||||
### Auto-Apply Eligibility
|
||||
|
||||
The `couldAutoApplyTasks` field indicates whether the fix is eligible for automatic application:
|
||||
|
||||
- **`true`**: Fix is eligible for auto-apply. Subagent keeps polling while verification is in progress. Returns `fix_auto_applying` when verified, or `fix_available` if verification fails.
|
||||
- **`false`** or **`null`**: Fix requires manual action (apply via MCP, apply locally, or reject)
|
||||
|
||||
**Key point**: When subagent returns `fix_auto_applying`, do NOT call MCP to apply - self-healing handles it. Just spawn a new subagent in wait mode.
|
||||
|
||||
### Apply vs Reject vs Apply Locally
|
||||
|
||||
- **Apply via MCP**: Calls `update_self_healing_fix({ shortLink, action: "APPLY" })`. Self-healing agent applies the fix in CI and a new CIPE spawns automatically. No local git operations needed.
|
||||
- **Apply Locally**: Runs `nx apply-locally <shortLink>`. Applies the patch to your local working directory and sets state to `APPLIED_LOCALLY`. Use this when you want to enhance the fix before pushing.
|
||||
- **Reject via MCP**: Calls `update_self_healing_fix({ shortLink, action: "REJECT" })`. Marks fix as rejected. Use only when the fix is completely wrong and you'll fix from scratch.
|
||||
|
||||
### Apply Locally + Enhance Flow
|
||||
|
||||
When the fix needs enhancement (use `nx apply-locally`, NOT reject):
|
||||
|
||||
1. Apply the patch locally: `nx apply-locally <shortLink>` (this also updates state to `APPLIED_LOCALLY`)
|
||||
2. Make additional changes as needed
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Reject + Fix From Scratch Flow
|
||||
|
||||
When the fix is completely wrong:
|
||||
|
||||
1. Call MCP to reject: `update_self_healing_fix({ shortLink, action: "REJECT" })`
|
||||
2. Fix the issue from scratch locally
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Environment Issue Handling
|
||||
|
||||
When `failureClassification == 'ENVIRONMENT_STATE'`:
|
||||
|
||||
1. Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`
|
||||
2. New CIPE spawns automatically (no local git operations needed)
|
||||
3. Loop to poll for new CIPE with `previousCipeUrl` set
|
||||
|
||||
### No-New-CIPE Handling
|
||||
|
||||
When `status == 'no_new_cipe'`:
|
||||
|
||||
This means the expected CIPE was never created - CI likely failed before Nx tasks could run.
|
||||
|
||||
1. **Report to user:**
|
||||
|
||||
```
|
||||
[ci-monitor] No CI attempt for <sha> after 10 min. Check CI provider for pre-Nx failures (install, checkout, auth). Last CI attempt: <previousCipeUrl>
|
||||
```
|
||||
|
||||
2. **If user configured auto-fix attempts** (e.g., `--auto-fix-workflow`):
|
||||
- Detect package manager: check for `pnpm-lock.yaml`, `yarn.lock`, `package-lock.json`
|
||||
- Run install to update lockfile:
|
||||
```bash
|
||||
pnpm install # or npm install / yarn install
|
||||
```
|
||||
- If lockfile changed:
|
||||
```bash
|
||||
git add pnpm-lock.yaml # or appropriate lockfile
|
||||
git commit -m "chore: update lockfile"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
- Record new commit SHA, loop to poll with `expectedCommitSha`
|
||||
|
||||
3. **Otherwise:** Exit with `no_new_cipe` status, providing guidance for user to investigate
|
||||
|
||||
## Exit Conditions
|
||||
|
||||
Exit the monitoring loop when ANY of these conditions are met:
|
||||
|
||||
| Condition | Exit Type |
|
||||
| ------------------------------------------- | ---------------- |
|
||||
| CI passes (`cipeStatus == 'SUCCEEDED'`) | Success |
|
||||
| Max CIPE cycles reached | Timeout |
|
||||
| Max duration reached | Timeout |
|
||||
| 3 consecutive no-progress iterations | Circuit breaker |
|
||||
| No fix available and local fix not possible | Failure |
|
||||
| No new CIPE and auto-fix not configured | Pre-CIPE failure |
|
||||
| User cancels | Cancelled |
|
||||
|
||||
## Main Loop
|
||||
|
||||
### Step 1: Initialize Tracking
|
||||
|
||||
```
|
||||
cycle_count = 0
|
||||
start_time = now()
|
||||
no_progress_count = 0
|
||||
local_verify_count = 0
|
||||
last_state = null
|
||||
last_cipe_url = null
|
||||
expected_commit_sha = null
|
||||
```
|
||||
|
||||
### Step 2: Spawn Subagent
|
||||
|
||||
Spawn the `ci-watcher` subagent to poll CI status:
|
||||
|
||||
**Fresh start (first spawn, no expected CIPE):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>."
|
||||
)
|
||||
```
|
||||
|
||||
**After action that triggers new CIPE (wait mode):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>.
|
||||
|
||||
WAIT MODE: A new CIPE should spawn. Ignore old CIPE until new one appears.
|
||||
Expected commit SHA: <expected_commit_sha>
|
||||
Previous CIPE URL: <last_cipe_url>"
|
||||
)
|
||||
```
|
||||
|
||||
### Step 3: Handle Subagent Response
|
||||
|
||||
When subagent returns:
|
||||
|
||||
1. Check the returned status
|
||||
2. Look up default behavior in the table above
|
||||
3. Check if user instructions override the default
|
||||
4. Execute the appropriate action
|
||||
5. **If action expects new CIPE**, update tracking (see Step 3a)
|
||||
6. If action results in looping, go to Step 2
|
||||
|
||||
### Step 3a: Track State for New-CIPE Detection
|
||||
|
||||
After actions that should trigger a new CIPE, record state before looping:
|
||||
|
||||
| Action | What to Track | Subagent Mode |
|
||||
| ----------------------------- | --------------------------------------------- | ------------- |
|
||||
| Fix auto-applying | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply via MCP | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply locally + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Reject + fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Fix failed + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| No fix + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Environment rerun | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| No-new-CIPE + auto-fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
|
||||
**CRITICAL**: When passing `expectedCommitSha` or `last_cipe_url` to the subagent, it enters **wait mode**:
|
||||
|
||||
- Subagent will **completely ignore** the old/stale CIPE
|
||||
- Subagent will only wait for new CIPE to appear
|
||||
- Subagent will NOT return to main agent with stale CIPE data
|
||||
- Once new CIPE detected, subagent switches to normal polling
|
||||
|
||||
**Why wait mode matters for context preservation**: Stale CIPE data can be very large (task output summaries, suggested fix patches, reasoning). If subagent returns this to main agent, it pollutes main agent's context with useless data since we already processed that CIPE. Wait mode keeps stale data in the subagent, never sending it to main agent.
|
||||
|
||||
### Step 4: Progress Tracking
|
||||
|
||||
After each action:
|
||||
|
||||
- If state changed significantly → reset `no_progress_count = 0`
|
||||
- If state unchanged → `no_progress_count++`
|
||||
- On new CI attempt detected → reset `local_verify_count = 0`
|
||||
|
||||
## Status Reporting
|
||||
|
||||
Based on verbosity level:
|
||||
|
||||
| Level | What to Report |
|
||||
| --------- | -------------------------------------------------------------------------- |
|
||||
| `minimal` | Only final result (success/failure/timeout) |
|
||||
| `medium` | State changes + periodic updates ("Cycle N \| Elapsed: Xm \| Status: ...") |
|
||||
| `verbose` | All of medium + full subagent responses, git outputs, MCP responses |
|
||||
|
||||
## User Instruction Examples
|
||||
|
||||
Users can override default behaviors:
|
||||
|
||||
| Instruction | Effect |
|
||||
| ------------------------------------------------ | --------------------------------------------- |
|
||||
| "never auto-apply" | Always prompt before applying any fix |
|
||||
| "always ask before git push" | Prompt before each push |
|
||||
| "reject any fix for e2e tasks" | Auto-reject if `failedTaskIds` contains e2e |
|
||||
| "apply all fixes regardless of verification" | Skip verification check, apply everything |
|
||||
| "if confidence < 70, reject" | Check confidence field before applying |
|
||||
| "run 'nx affected -t typecheck' before applying" | Add local verification step |
|
||||
| "auto-fix workflow failures" | Attempt lockfile updates on pre-CIPE failures |
|
||||
| "wait 45 min for new CIPE" | Override new-CIPE timeout (default: 10 min) |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Action |
|
||||
| ------------------------ | ------------------------------------------------------------------------------------- |
|
||||
| Git rebase conflict | Report to user, exit |
|
||||
| `nx apply-locally` fails | Report to user, attempt manual patch or exit |
|
||||
| MCP tool error | Retry once, if fails report to user |
|
||||
| Subagent spawn failure | Retry once, if fails exit with error |
|
||||
| No new CIPE detected | If `--auto-fix-workflow`, try lockfile update; otherwise report to user with guidance |
|
||||
| Lockfile auto-fix fails | Report to user, exit with guidance to check CI logs |
|
||||
|
||||
## Example Session
|
||||
|
||||
### Example 1: Normal Flow with Self-Healing (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-auth'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, verbosity=medium
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: IN_PROGRESS | Self-Healing: NOT_STARTED | Elapsed: 1m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: IN_PROGRESS | Elapsed: 3m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 5m
|
||||
|
||||
[ci-monitor] Fix available! Verification: COMPLETED
|
||||
[ci-monitor] Applying fix via MCP...
|
||||
[ci-monitor] Fix applied in CI. Waiting for new CI attempt...
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 8m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 2
|
||||
- Total time: 12m 34s
|
||||
- Fixes applied: 1
|
||||
- Result: SUCCESS
|
||||
```
|
||||
|
||||
### Example 2: Pre-CI Failure (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-products'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, auto-fix-workflow=true
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 2m
|
||||
|
||||
[ci-monitor] Applying fix locally, enhancing, and pushing...
|
||||
[ci-monitor] Committed: abc1234
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] Waiting for new CI attempt... (expected SHA: abc1234)
|
||||
[CI Monitor] ⚠️ CI attempt timeout (10 min). Returning no_new_cipe.
|
||||
|
||||
[ci-monitor] Status: no_new_cipe
|
||||
[ci-monitor] --auto-fix-workflow enabled. Attempting lockfile update...
|
||||
[ci-monitor] Lockfile updated. Committed: def5678
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 18m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 3
|
||||
- Total time: 22m 15s
|
||||
- Fixes applied: 1 (self-healing) + 1 (lockfile)
|
||||
- Result: SUCCESS
|
||||
```
|
||||
@@ -0,0 +1,228 @@
|
||||
---
|
||||
name: nx-generate
|
||||
description: Generate code using nx generators. USE WHEN scaffolding code or transforming existing code - for example creating libraries or applications, or anything else that is boilerplate code or automates repetitive tasks. ALWAYS use this first when generating code with Nx instead of calling MCP tools or running nx generate immediately.
|
||||
---
|
||||
|
||||
# Run Nx Generator
|
||||
|
||||
Nx generators are powerful tools that scaffold projects, make automated code migrations or automate repetitive tasks in a monorepo. They ensure consistency across the codebase and reduce boilerplate work.
|
||||
|
||||
This skill applies when the user wants to:
|
||||
|
||||
- Create new projects like libraries or applications
|
||||
- Scaffold features or boilerplate code
|
||||
- Run workspace-specific or custom generators
|
||||
- Do anything else that an nx generator exists for
|
||||
|
||||
## Generator Discovery Flow
|
||||
|
||||
### Step 1: List Available Generators
|
||||
|
||||
Use the Nx CLI to discover available generators:
|
||||
|
||||
- List all generators for a plugin: `npx nx list @nx/react`
|
||||
- View available plugins: `npx nx list`
|
||||
|
||||
This includes:
|
||||
|
||||
- Plugin generators (e.g., `@nx/react:library`, `@nx/js:library`)
|
||||
- Local workspace generators (defined in the repo's own plugins)
|
||||
|
||||
### Step 2: Match Generator to User Request
|
||||
|
||||
Based on the user's request, identify which generator(s) could fulfill their needs. Consider:
|
||||
|
||||
- What artifact type they want to create (library, application, etc.)
|
||||
- Which framework or technology stack is relevant
|
||||
- Whether they mentioned specific generator names
|
||||
|
||||
**IMPORTANT**: When both a local workspace generator and an external plugin generator could satisfy the request, **always prefer the local workspace generator**. Local generators are customized for the specific repo's patterns and conventions.
|
||||
|
||||
It's possible that the user request is something that no Nx generator exists for whatsoever. In this case, you can stop using this skill and try to help the user another way. HOWEVER, the burden of proof for this is high. Before aborting, carefully consider each and every generator that's available. Look into details for any that could be related in any way before making this decision.
|
||||
|
||||
## Pre-Execution Checklist
|
||||
|
||||
Before running any generator, complete these steps:
|
||||
|
||||
### 1. Fetch Generator Schema
|
||||
|
||||
Use the `--help` flag to understand all available options:
|
||||
|
||||
```bash
|
||||
npx nx g @nx/react:library --help
|
||||
```
|
||||
|
||||
Pay attention to:
|
||||
|
||||
- Required options that must be provided
|
||||
- Optional options that may be relevant to the user's request
|
||||
- Default values that might need to be overridden
|
||||
|
||||
### 2. Read Generator Source Code
|
||||
|
||||
Understanding what the generator actually does helps you:
|
||||
|
||||
- Know what files will be created/modified
|
||||
- Understand any side effects (updating configs, installing deps, etc.)
|
||||
- Identify options that might not be obvious from the schema
|
||||
|
||||
To find generator source code:
|
||||
|
||||
- For plugin generators: Use `node -e "console.log(require.resolve('@nx/<plugin>/generators.json'));"` to find the generators.json, then locate the source from there
|
||||
- If that fails, read directly from `node_modules/<plugin>/generators.json`
|
||||
- For local generators: They are typically in `tools/generators/` or a local plugin directory. You can search the repo for the generator name to find it.
|
||||
|
||||
### 2.5 Reevaluate if the generator is right
|
||||
|
||||
Once you have built up an understanding of what the selected generator does, reconsider: Is this the right generator to service the user request?
|
||||
If not, it's okay to go back to the Generator Discovery Flow and select a different generator before proceeding. If you do, make sure to go through the entire pre-execution checklist once more.
|
||||
|
||||
### 3. Understand Repo Context
|
||||
|
||||
Before generating, examine the target area of the codebase:
|
||||
|
||||
- Look at similar existing artifacts (other libraries, applications, etc.)
|
||||
- Identify patterns and conventions used in the repo
|
||||
- Note naming conventions, file structures, and configuration patterns
|
||||
- Try to match these patterns when configuring the generator
|
||||
|
||||
For example, if similar libraries are using a specific test runner, build tool or linter, try to match that if possible.
|
||||
If projects or other artifacts are organized with a specific naming convention, try to match it.
|
||||
|
||||
### 4. Validate Required Options
|
||||
|
||||
Ensure all required options have values:
|
||||
|
||||
- Map the user's request to generator options
|
||||
- Infer values from context where possible
|
||||
- Ask the user for any critical missing information
|
||||
|
||||
## Execution
|
||||
|
||||
Keep in mind that you might have to prefix things with npx/pnpx/yarn if the user doesn't have nx installed globally.
|
||||
Many generators will behave differently based on where they are executed. For example, first-party nx library generators use the cwd to determine the directory that the library should be placed in. This is highly important.
|
||||
|
||||
### Consider Dry-Run (Optional)
|
||||
|
||||
Running with `--dry-run` first is strongly encouraged but not mandatory. Use your judgment:
|
||||
|
||||
- For complex generators or unfamiliar territory: do a dry-run first
|
||||
- For simple, well-understood generators: may proceed directly
|
||||
- Dry-run shows file names and created/deleted/modified markers, but not content
|
||||
- There are cases where a generator does not support dry-run (for example if it had to install an npm package) - in that case --dry-run might fail. Don't be discouraged but simply move on to running the generator for real and iterating from there.
|
||||
|
||||
### Running the Generator
|
||||
|
||||
Execute the generator with:
|
||||
|
||||
```bash
|
||||
nx generate <generator-name> <options> --no-interactive
|
||||
```
|
||||
|
||||
**CRITICAL**: Always include `--no-interactive` to prevent prompts that would hang the execution.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
nx generate @nx/react:library --name=my-utils --no-interactive
|
||||
```
|
||||
|
||||
### Handling Generator Failures
|
||||
|
||||
If the generator fails:
|
||||
|
||||
1. **Diagnose the error** - Read the error message carefully
|
||||
2. **Identify the cause** - Missing options, invalid values, conflicts, etc.
|
||||
3. **Attempt automatic fix** - Adjust options or resolve conflicts
|
||||
4. **Retry** - Run the generator again with corrected options
|
||||
|
||||
Common failure reasons:
|
||||
|
||||
- Missing required options
|
||||
- Invalid option values
|
||||
- Conflicting with existing files
|
||||
- Missing dependencies
|
||||
- Generator doesn't support certain flag combinations
|
||||
|
||||
## Post-Generation
|
||||
|
||||
### 1. Modify Generated Code (If Needed)
|
||||
|
||||
Generators provide a starting point, but the output may need adjustment to match the user's specific requirements:
|
||||
|
||||
- Add or modify functionality as requested
|
||||
- Adjust imports, exports, or configurations
|
||||
- Integrate with existing code patterns in the repo
|
||||
|
||||
### 2. Format Code
|
||||
|
||||
Run formatting on all generated/modified files:
|
||||
|
||||
```bash
|
||||
nx format --fix
|
||||
```
|
||||
|
||||
Languages other than javascript/typescript might need other formatting invocations too.
|
||||
|
||||
### 3. Run Verification
|
||||
|
||||
Verify that the generated code works correctly. What this looks like will vary depending on the type of generator and the targets available.
|
||||
If the generator created a new project, run its targets directly
|
||||
Use your best judgement to determine what needs to be verified.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
nx lint <new-project>
|
||||
nx test <new-project>
|
||||
nx build <new-project>
|
||||
```
|
||||
|
||||
### 4. Handle Verification Failures
|
||||
|
||||
When verification fails:
|
||||
|
||||
**If scope is manageable** (a few lint errors, minor type issues):
|
||||
|
||||
- Fix the issues
|
||||
- Re-run verification to confirm
|
||||
|
||||
**If issues are extensive** (many errors, complex problems):
|
||||
|
||||
- Attempt simple, obvious fixes first
|
||||
- If still failing, escalate to the user with:
|
||||
- Description of what was generated
|
||||
- What verification is failing
|
||||
- What you've attempted to fix
|
||||
- Remaining issues that need user input
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Generator Failures
|
||||
|
||||
- Check the error message for specific causes
|
||||
- Verify all required options are provided
|
||||
- Check for conflicts with existing files
|
||||
- Ensure the generator name and options are correct
|
||||
|
||||
### Missing Options
|
||||
|
||||
- Consult the generator schema for required fields
|
||||
- Infer values from context when reasonable
|
||||
- Ask the user for values that cannot be inferred
|
||||
|
||||
## Key Principles
|
||||
|
||||
1. **Local generators first** - Always prefer workspace/local generators over external plugin generators when both could work
|
||||
|
||||
2. **Understand before running** - Read both the schema AND the source code to fully understand what will happen
|
||||
|
||||
3. **No prompts** - Always use `--no-interactive` to prevent hanging
|
||||
|
||||
4. **Generators are starting points** - Modify the output as needed to fully satisfy the user's requirements
|
||||
|
||||
5. **Verify changes work** - Don't just generate; ensure the code builds, lints, and tests pass
|
||||
|
||||
6. **Be proactive about fixes** - Don't just report errors; attempt to resolve them automatically when possible
|
||||
|
||||
7. **Match repo patterns** - Study existing similar code in the repo and match its conventions
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
name: nx-plugins
|
||||
description: Find and add Nx plugins. USE WHEN user wants to discover available plugins, install a new plugin, or add support for a specific framework or technology to the workspace.
|
||||
---
|
||||
|
||||
## Finding and Installing new plugins
|
||||
|
||||
- List plugins: `pnpm nx list`
|
||||
- Install plugins `pnpm nx add <plugin>`. Example: `pnpm nx add @nx/react`.
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
name: nx-run-tasks
|
||||
description: Helps with running tasks in an Nx workspace. USE WHEN the user wants to execute build, test, lint, serve, or run any other tasks defined in the workspace.
|
||||
---
|
||||
|
||||
You can run tasks with Nx in the following way.
|
||||
|
||||
Keep in mind that you might have to prefix things with npx/pnpx/yarn if the user doesn't have nx installed globally. Look at the package.json or lockfile to determine which package manager is in use.
|
||||
|
||||
For more details on any command, run it with `--help` (e.g. `nx run-many --help`, `nx affected --help`).
|
||||
|
||||
## Understand which tasks can be run
|
||||
|
||||
You can check those via `nx show project <projectname> --json`, for example `nx show project myapp --json`. It contains a `targets` section which has information about targets that can be run. You can also just look at the `package.json` scripts or `project.json` targets, but you might miss out on inferred tasks by Nx plugins.
|
||||
|
||||
## Run a single task
|
||||
|
||||
```
|
||||
nx run <project>:<task>
|
||||
```
|
||||
|
||||
where `project` is the project name defined in `package.json` or `project.json` (if present).
|
||||
|
||||
## Run multiple tasks
|
||||
|
||||
```
|
||||
nx run-many -t build test lint typecheck
|
||||
```
|
||||
|
||||
You can pass a `-p` flag to filter to specific projects, otherwise it runs on all projects. You can also use `--exclude` to exclude projects, and `--parallel` to control the number of parallel processes (default is 3).
|
||||
|
||||
Examples:
|
||||
|
||||
- `nx run-many -t test -p proj1 proj2` — test specific projects
|
||||
- `nx run-many -t test --projects=*-app --exclude=excluded-app` — test projects matching a pattern
|
||||
- `nx run-many -t test --projects=tag:api-*` — test projects by tag
|
||||
|
||||
## Run tasks for affected projects
|
||||
|
||||
Use `nx affected` to only run tasks on projects that have been changed and projects that depend on changed projects. This is especially useful in CI and for large workspaces.
|
||||
|
||||
```
|
||||
nx affected -t build test lint
|
||||
```
|
||||
|
||||
By default it compares against the base branch. You can customize this:
|
||||
|
||||
- `nx affected -t test --base=main --head=HEAD` — compare against a specific base and head
|
||||
- `nx affected -t test --files=libs/mylib/src/index.ts` — specify changed files directly
|
||||
|
||||
## Useful flags
|
||||
|
||||
These flags work with `run`, `run-many`, and `affected`:
|
||||
|
||||
- `--skipNxCache` — rerun tasks even when results are cached
|
||||
- `--verbose` — print additional information such as stack traces
|
||||
- `--nxBail` — stop execution after the first failed task
|
||||
- `--configuration=<name>` — use a specific configuration (e.g. `production`)
|
||||
@@ -0,0 +1,186 @@
|
||||
---
|
||||
name: nx-workspace
|
||||
description: "Explore and understand Nx workspaces. USE WHEN answering any questions about the nx workspace, the projects in it or tasks to run. EXAMPLES: 'What projects are in this workspace?', 'How is project X configured?', 'What targets can I run?', 'What's affected by my changes?', 'Which projects depend on library Y?', or any questions about Nx workspace structure, project configuration, or available tasks."
|
||||
---
|
||||
|
||||
# Nx Workspace Exploration
|
||||
|
||||
This skill provides read-only exploration of Nx workspaces. Use it to understand workspace structure, project configuration, available targets, and dependencies.
|
||||
|
||||
Keep in mind that you might have to prefix commands with `npx`/`pnpx`/`yarn` if nx isn't installed globally. Check the lockfile to determine the package manager in use.
|
||||
|
||||
## Listing Projects
|
||||
|
||||
Use `nx show projects` to list projects in the workspace.
|
||||
|
||||
```bash
|
||||
# List all projects
|
||||
nx show projects
|
||||
|
||||
# Filter by pattern (glob)
|
||||
nx show projects --projects "apps/*"
|
||||
nx show projects --projects "shared-*"
|
||||
|
||||
# Filter by project type
|
||||
nx show projects --type app
|
||||
nx show projects --type lib
|
||||
nx show projects --type e2e
|
||||
|
||||
# Filter by target (projects that have a specific target)
|
||||
nx show projects --withTarget build
|
||||
nx show projects --withTarget e2e
|
||||
|
||||
# Find affected projects (changed since base branch)
|
||||
nx show projects --affected
|
||||
nx show projects --affected --base=main
|
||||
nx show projects --affected --type app
|
||||
|
||||
# Combine filters
|
||||
nx show projects --type lib --withTarget test
|
||||
nx show projects --affected --exclude="*-e2e"
|
||||
|
||||
# Output as JSON
|
||||
nx show projects --json
|
||||
```
|
||||
|
||||
## Project Configuration
|
||||
|
||||
Use `nx show project <name> --json` to get the full resolved configuration for a project.
|
||||
|
||||
**Important**: Do NOT read `project.json` directly - it only contains partial configuration. The `nx show project` command returns the full resolved config including inferred targets from plugins.
|
||||
|
||||
You can read the full project schema at `node_modules/nx/schemas/project-schema.json` to understand nx project configuration options.
|
||||
|
||||
```bash
|
||||
# Get full project configuration
|
||||
nx show project my-app --json
|
||||
|
||||
# Extract specific parts from the JSON
|
||||
nx show project my-app --json | jq '.targets'
|
||||
nx show project my-app --json | jq '.targets.build'
|
||||
nx show project my-app --json | jq '.targets | keys'
|
||||
|
||||
|
||||
# Check project metadata
|
||||
nx show project my-app --json | jq '{name, root, sourceRoot, projectType, tags}'
|
||||
```
|
||||
|
||||
## Target Information
|
||||
|
||||
Targets define what tasks can be run on a project.
|
||||
|
||||
```bash
|
||||
# List all targets for a project
|
||||
nx show project my-app --json | jq '.targets | keys'
|
||||
|
||||
# Get full target configuration
|
||||
nx show project my-app --json | jq '.targets.build'
|
||||
|
||||
# Check target executor/command
|
||||
nx show project my-app --json | jq '.targets.build.executor'
|
||||
nx show project my-app --json | jq '.targets.build.command'
|
||||
|
||||
# View target options
|
||||
nx show project my-app --json | jq '.targets.build.options'
|
||||
|
||||
# Check target inputs/outputs (for caching)
|
||||
nx show project my-app --json | jq '.targets.build.inputs'
|
||||
nx show project my-app --json | jq '.targets.build.outputs'
|
||||
|
||||
# Find projects with a specific target
|
||||
nx show projects --withTarget serve
|
||||
nx show projects --withTarget e2e
|
||||
```
|
||||
|
||||
## Workspace Configuration
|
||||
|
||||
Read `nx.json` directly for workspace-level configuration.
|
||||
You can read the full project schema at `node_modules/nx/schemas/nx-schema.json` to understand nx project configuration options.
|
||||
|
||||
```bash
|
||||
# Read the full nx.json
|
||||
cat nx.json
|
||||
|
||||
# Or use jq for specific sections
|
||||
cat nx.json | jq '.targetDefaults'
|
||||
cat nx.json | jq '.namedInputs'
|
||||
cat nx.json | jq '.plugins'
|
||||
cat nx.json | jq '.generators'
|
||||
```
|
||||
|
||||
Key nx.json sections:
|
||||
|
||||
- `targetDefaults` - Default configuration applied to all targets of a given name
|
||||
- `namedInputs` - Reusable input definitions for caching
|
||||
- `plugins` - Nx plugins and their configuration
|
||||
- ...and much more, read the schema or nx.json for details
|
||||
|
||||
## Affected Projects
|
||||
|
||||
Find projects affected by changes in the current branch.
|
||||
|
||||
```bash
|
||||
# Affected since base branch (auto-detected)
|
||||
nx show projects --affected
|
||||
|
||||
# Affected with explicit base
|
||||
nx show projects --affected --base=main
|
||||
nx show projects --affected --base=origin/main
|
||||
|
||||
# Affected between two commits
|
||||
nx show projects --affected --base=abc123 --head=def456
|
||||
|
||||
# Affected apps only
|
||||
nx show projects --affected --type app
|
||||
|
||||
# Affected excluding e2e projects
|
||||
nx show projects --affected --exclude="*-e2e"
|
||||
|
||||
# Affected by uncommitted changes
|
||||
nx show projects --affected --uncommitted
|
||||
|
||||
# Affected by untracked files
|
||||
nx show projects --affected --untracked
|
||||
```
|
||||
|
||||
## Common Exploration Patterns
|
||||
|
||||
### "What's in this workspace?"
|
||||
|
||||
```bash
|
||||
nx show projects
|
||||
nx show projects --type app
|
||||
nx show projects --type lib
|
||||
```
|
||||
|
||||
### "How do I build/test/lint project X?"
|
||||
|
||||
```bash
|
||||
nx show project X --json | jq '.targets | keys'
|
||||
nx show project X --json | jq '.targets.build'
|
||||
```
|
||||
|
||||
### "What depends on library Y?"
|
||||
|
||||
```bash
|
||||
# Find projects that may depend on Y by searching for imports
|
||||
# (Nx doesn't have a direct "dependents" command via CLI)
|
||||
grep -r "from '@myorg/Y'" --include="*.ts" --include="*.tsx" apps/ libs/
|
||||
```
|
||||
|
||||
### "What configuration options are available?"
|
||||
|
||||
```bash
|
||||
cat node_modules/nx/schemas/nx-schema.json | jq '.properties | keys'
|
||||
cat node_modules/nx/schemas/project-schema.json | jq '.properties | keys'
|
||||
```
|
||||
|
||||
### "Why is project X affected?"
|
||||
|
||||
```bash
|
||||
# Check what files changed
|
||||
git diff --name-only main
|
||||
|
||||
# See which project owns those files
|
||||
nx show project X --json | jq '.root'
|
||||
```
|
||||
@@ -0,0 +1,438 @@
|
||||
description = "Monitor Nx Cloud CI pipeline and handle self-healing fixes automatically. Checks for Nx Cloud connection before starting."
|
||||
prompt = """
|
||||
# CI Monitor Command
|
||||
|
||||
You are the orchestrator for monitoring Nx Cloud CI pipeline executions and handling self-healing fixes. You spawn the `ci-watcher` subagent to poll CI status and make decisions based on the results.
|
||||
|
||||
## Context
|
||||
|
||||
- **Current Branch:** !`git branch --show-current`
|
||||
- **Current Commit:** !`git rev-parse --short HEAD`
|
||||
- **Remote Status:** !`git status -sb | head -1`
|
||||
|
||||
## User Instructions
|
||||
|
||||
{{args}}
|
||||
|
||||
**Important:** If user provides specific instructions, respect them over default behaviors described below.
|
||||
|
||||
## Configuration Defaults
|
||||
|
||||
| Setting | Default | Description |
|
||||
| ------------------------- | ------------- | ------------------------------------------------------------------- |
|
||||
| `--max-cycles` | 10 | Maximum CIPE cycles before timeout |
|
||||
| `--timeout` | 120 | Maximum duration in minutes |
|
||||
| `--verbosity` | medium | Output level: minimal, medium, verbose |
|
||||
| `--branch` | (auto-detect) | Branch to monitor |
|
||||
| `--subagent-timeout` | 60 | Subagent polling timeout in minutes |
|
||||
| `--fresh` | false | Ignore previous context, start fresh |
|
||||
| `--auto-fix-workflow` | false | Attempt common fixes for pre-CIPE failures (e.g., lockfile updates) |
|
||||
| `--new-cipe-timeout` | 10 | Minutes to wait for new CIPE after action |
|
||||
| `--local-verify-attempts` | 3 | Max local verification + enhance cycles before pushing to CI |
|
||||
|
||||
Parse any overrides from `{{args}}` and merge with defaults.
|
||||
|
||||
## Nx Cloud Connection Check
|
||||
|
||||
**CRITICAL**: Before starting the monitoring loop, verify the workspace is connected to Nx Cloud.
|
||||
|
||||
### Step 0: Verify Nx Cloud Connection
|
||||
|
||||
1. **Check `nx.json`** at workspace root for `nxCloudId` or `nxCloudAccessToken`
|
||||
2. **If `nx.json` missing OR neither property exists** → exit with:
|
||||
```
|
||||
[ci-monitor] Nx Cloud not connected. Unlock 70% faster CI and auto-fix broken PRs with https://nx.dev/nx-cloud
|
||||
```
|
||||
3. **If connected** → continue to main loop
|
||||
|
||||
## Session Context Behavior
|
||||
|
||||
**Important:** Within a Claude Code session, conversation context persists. If you Ctrl+C to interrupt the monitor and re-run `/ci-monitor`, Claude remembers the previous state and may continue from where it left off.
|
||||
|
||||
- **To continue monitoring:** Just re-run `/ci-monitor` (context is preserved)
|
||||
- **To start fresh:** Use `/ci-monitor --fresh` to ignore previous context
|
||||
- **For a completely clean slate:** Exit Claude Code and restart `claude`
|
||||
|
||||
## Default Behaviors by Status
|
||||
|
||||
The subagent returns with one of the following statuses. This table defines the **default behavior** for each status. User instructions can override any of these.
|
||||
|
||||
| Status | Default Behavior |
|
||||
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci_success` | Exit with success. Log "CI passed successfully!" |
|
||||
| `fix_auto_applying` | Fix will be auto-applied by self-healing. Do NOT call MCP. Record `last_cipe_url`, spawn new subagent in wait mode to poll for new CIPE. |
|
||||
| `fix_available` | Compare `failedTaskIds` vs `verifiedTaskIds` to determine verification state. See **Fix Available Decision Logic** section below. |
|
||||
| `fix_failed` | Self-healing failed to generate fix. Attempt local fix based on `taskOutputSummary`. If successful → commit, push, loop. If not → exit with failure. |
|
||||
| `environment_issue` | Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`. New CIPE spawns automatically. Loop to poll for new CIPE. |
|
||||
| `no_fix` | CI failed, no fix available (self-healing disabled or not executable). Attempt local fix if possible. Otherwise exit with failure. |
|
||||
| `no_new_cipe` | Expected CIPE never spawned (CI workflow likely failed before Nx tasks). Report to user, attempt common fixes if configured, or exit with guidance. |
|
||||
| `polling_timeout` | Subagent polling timeout reached. Exit with timeout. |
|
||||
| `cipe_canceled` | CIPE was canceled. Exit with canceled status. |
|
||||
| `cipe_timed_out` | CIPE timed out. Exit with timeout status. |
|
||||
| `error` | Increment `no_progress_count`. If >= 3 → exit with circuit breaker. Otherwise wait 60s and loop. |
|
||||
|
||||
### Fix Available Decision Logic
|
||||
|
||||
When subagent returns `fix_available`, main agent compares `failedTaskIds` vs `verifiedTaskIds`:
|
||||
|
||||
#### Step 1: Categorize Tasks
|
||||
|
||||
1. **Verified tasks** = tasks in both `failedTaskIds` AND `verifiedTaskIds`
|
||||
2. **Unverified tasks** = tasks in `failedTaskIds` but NOT in `verifiedTaskIds`
|
||||
3. **E2E tasks** = unverified tasks where target contains "e2e" (task format: `<project>:<target>` or `<project>:<target>:<config>`)
|
||||
4. **Verifiable tasks** = unverified tasks that are NOT e2e
|
||||
|
||||
#### Step 2: Determine Path
|
||||
|
||||
| Condition | Path |
|
||||
| --------------------------------------- | ---------------------------------------- |
|
||||
| No unverified tasks (all verified) | Apply via MCP |
|
||||
| Unverified tasks exist, but ALL are e2e | Apply via MCP (treat as verified enough) |
|
||||
| Verifiable tasks exist | Local verification flow |
|
||||
|
||||
#### Step 3a: Apply via MCP (fully/e2e-only verified)
|
||||
|
||||
- Call `update_self_healing_fix({ shortLink, action: "APPLY" })`
|
||||
- Record `last_cipe_url`, spawn subagent in wait mode
|
||||
|
||||
#### Step 3b: Local Verification Flow
|
||||
|
||||
When verifiable (non-e2e) unverified tasks exist:
|
||||
|
||||
1. **Detect package manager:**
|
||||
|
||||
- `pnpm-lock.yaml` exists → `pnpm nx`
|
||||
- `yarn.lock` exists → `yarn nx`
|
||||
- Otherwise → `npx nx`
|
||||
|
||||
2. **Run verifiable tasks in parallel:**
|
||||
|
||||
- Spawn `general` subagents to run each task concurrently
|
||||
- Each subagent runs: `<pm> nx run <taskId>`
|
||||
- Collect pass/fail results from all subagents
|
||||
|
||||
3. **Evaluate results:**
|
||||
|
||||
| Result | Action |
|
||||
| ------------------------- | ---------------------------- |
|
||||
| ALL verifiable tasks pass | Apply via MCP |
|
||||
| ANY verifiable task fails | Apply-locally + enhance flow |
|
||||
|
||||
4. **Apply-locally + enhance flow:**
|
||||
|
||||
- Run `nx apply-locally <shortLink>`
|
||||
- Enhance the code to fix failing tasks
|
||||
- Run failing tasks again to verify fix
|
||||
- If still failing → increment `local_verify_count`, loop back to enhance
|
||||
- If passing → commit and push, record `expected_commit_sha`, spawn subagent in wait mode
|
||||
|
||||
5. **Track attempts** (wraps step 4):
|
||||
- Increment `local_verify_count` after each enhance cycle
|
||||
- If `local_verify_count >= local_verify_attempts` (default: 3):
|
||||
- Get code in commit-able state
|
||||
- Commit and push with message indicating local verification failed
|
||||
- Report to user:
|
||||
```
|
||||
[ci-monitor] Local verification failed after <N> attempts. Pushed to CI for final validation. Failed: <taskIds>
|
||||
```
|
||||
- Record `expected_commit_sha`, spawn subagent in wait mode (let CI be final judge)
|
||||
|
||||
#### Commit Message Format
|
||||
|
||||
```bash
|
||||
git commit -m "fix(<projects>): <brief description>
|
||||
|
||||
Failed tasks: <taskId1>, <taskId2>
|
||||
Local verification: passed|enhanced|failed-pushing-to-ci"
|
||||
```
|
||||
|
||||
### Unverified Fix Flow (No Verification Attempted)
|
||||
|
||||
When `verificationStatus` is `FAILED`, `NOT_EXECUTABLE`, or fix has `couldAutoApplyTasks != true` with no verification:
|
||||
|
||||
- Analyze fix content (`suggestedFix`, `suggestedFixReasoning`, `taskOutputSummary`)
|
||||
- If fix looks correct → apply via MCP
|
||||
- If fix needs enhancement → use Apply Locally + Enhance Flow above
|
||||
- If fix is wrong → reject via MCP, fix from scratch, commit, push
|
||||
|
||||
### Auto-Apply Eligibility
|
||||
|
||||
The `couldAutoApplyTasks` field indicates whether the fix is eligible for automatic application:
|
||||
|
||||
- **`true`**: Fix is eligible for auto-apply. Subagent keeps polling while verification is in progress. Returns `fix_auto_applying` when verified, or `fix_available` if verification fails.
|
||||
- **`false`** or **`null`**: Fix requires manual action (apply via MCP, apply locally, or reject)
|
||||
|
||||
**Key point**: When subagent returns `fix_auto_applying`, do NOT call MCP to apply - self-healing handles it. Just spawn a new subagent in wait mode.
|
||||
|
||||
### Apply vs Reject vs Apply Locally
|
||||
|
||||
- **Apply via MCP**: Calls `update_self_healing_fix({ shortLink, action: "APPLY" })`. Self-healing agent applies the fix in CI and a new CIPE spawns automatically. No local git operations needed.
|
||||
- **Apply Locally**: Runs `nx apply-locally <shortLink>`. Applies the patch to your local working directory and sets state to `APPLIED_LOCALLY`. Use this when you want to enhance the fix before pushing.
|
||||
- **Reject via MCP**: Calls `update_self_healing_fix({ shortLink, action: "REJECT" })`. Marks fix as rejected. Use only when the fix is completely wrong and you'll fix from scratch.
|
||||
|
||||
### Apply Locally + Enhance Flow
|
||||
|
||||
When the fix needs enhancement (use `nx apply-locally`, NOT reject):
|
||||
|
||||
1. Apply the patch locally: `nx apply-locally <shortLink>` (this also updates state to `APPLIED_LOCALLY`)
|
||||
2. Make additional changes as needed
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Reject + Fix From Scratch Flow
|
||||
|
||||
When the fix is completely wrong:
|
||||
|
||||
1. Call MCP to reject: `update_self_healing_fix({ shortLink, action: "REJECT" })`
|
||||
2. Fix the issue from scratch locally
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Environment Issue Handling
|
||||
|
||||
When `failureClassification == 'ENVIRONMENT_STATE'`:
|
||||
|
||||
1. Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`
|
||||
2. New CIPE spawns automatically (no local git operations needed)
|
||||
3. Loop to poll for new CIPE with `previousCipeUrl` set
|
||||
|
||||
### No-New-CIPE Handling
|
||||
|
||||
When `status == 'no_new_cipe'`:
|
||||
|
||||
This means the expected CIPE was never created - CI likely failed before Nx tasks could run.
|
||||
|
||||
1. **Report to user:**
|
||||
|
||||
```
|
||||
[ci-monitor] No CI attempt for <sha> after 10 min. Check CI provider for pre-Nx failures (install, checkout, auth). Last CI attempt: <previousCipeUrl>
|
||||
```
|
||||
|
||||
2. **If user configured auto-fix attempts** (e.g., `--auto-fix-workflow`):
|
||||
|
||||
- Detect package manager: check for `pnpm-lock.yaml`, `yarn.lock`, `package-lock.json`
|
||||
- Run install to update lockfile:
|
||||
```bash
|
||||
pnpm install # or npm install / yarn install
|
||||
```
|
||||
- If lockfile changed:
|
||||
```bash
|
||||
git add pnpm-lock.yaml # or appropriate lockfile
|
||||
git commit -m "chore: update lockfile"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
- Record new commit SHA, loop to poll with `expectedCommitSha`
|
||||
|
||||
3. **Otherwise:** Exit with `no_new_cipe` status, providing guidance for user to investigate
|
||||
|
||||
## Exit Conditions
|
||||
|
||||
Exit the monitoring loop when ANY of these conditions are met:
|
||||
|
||||
| Condition | Exit Type |
|
||||
| ------------------------------------------- | ---------------- |
|
||||
| CI passes (`cipeStatus == 'SUCCEEDED'`) | Success |
|
||||
| Max CIPE cycles reached | Timeout |
|
||||
| Max duration reached | Timeout |
|
||||
| 3 consecutive no-progress iterations | Circuit breaker |
|
||||
| No fix available and local fix not possible | Failure |
|
||||
| No new CIPE and auto-fix not configured | Pre-CIPE failure |
|
||||
| User cancels | Cancelled |
|
||||
|
||||
## Main Loop
|
||||
|
||||
### Step 1: Initialize Tracking
|
||||
|
||||
```
|
||||
cycle_count = 0
|
||||
start_time = now()
|
||||
no_progress_count = 0
|
||||
local_verify_count = 0
|
||||
last_state = null
|
||||
last_cipe_url = null
|
||||
expected_commit_sha = null
|
||||
```
|
||||
|
||||
### Step 2: Spawn Subagent
|
||||
|
||||
Spawn the `ci-watcher` subagent to poll CI status:
|
||||
|
||||
**Fresh start (first spawn, no expected CIPE):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>."
|
||||
)
|
||||
```
|
||||
|
||||
**After action that triggers new CIPE (wait mode):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>.
|
||||
|
||||
WAIT MODE: A new CIPE should spawn. Ignore old CIPE until new one appears.
|
||||
Expected commit SHA: <expected_commit_sha>
|
||||
Previous CIPE URL: <last_cipe_url>"
|
||||
)
|
||||
```
|
||||
|
||||
### Step 3: Handle Subagent Response
|
||||
|
||||
When subagent returns:
|
||||
|
||||
1. Check the returned status
|
||||
2. Look up default behavior in the table above
|
||||
3. Check if user instructions override the default
|
||||
4. Execute the appropriate action
|
||||
5. **If action expects new CIPE**, update tracking (see Step 3a)
|
||||
6. If action results in looping, go to Step 2
|
||||
|
||||
### Step 3a: Track State for New-CIPE Detection
|
||||
|
||||
After actions that should trigger a new CIPE, record state before looping:
|
||||
|
||||
| Action | What to Track | Subagent Mode |
|
||||
| ----------------------------- | --------------------------------------------- | ------------- |
|
||||
| Fix auto-applying | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply via MCP | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply locally + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Reject + fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Fix failed + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| No fix + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Environment rerun | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| No-new-CIPE + auto-fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
|
||||
**CRITICAL**: When passing `expectedCommitSha` or `last_cipe_url` to the subagent, it enters **wait mode**:
|
||||
|
||||
- Subagent will **completely ignore** the old/stale CIPE
|
||||
- Subagent will only wait for new CIPE to appear
|
||||
- Subagent will NOT return to main agent with stale CIPE data
|
||||
- Once new CIPE detected, subagent switches to normal polling
|
||||
|
||||
**Why wait mode matters for context preservation**: Stale CIPE data can be very large (task output summaries, suggested fix patches, reasoning). If subagent returns this to main agent, it pollutes main agent's context with useless data since we already processed that CIPE. Wait mode keeps stale data in the subagent, never sending it to main agent.
|
||||
|
||||
### Step 4: Progress Tracking
|
||||
|
||||
After each action:
|
||||
|
||||
- If state changed significantly → reset `no_progress_count = 0`
|
||||
- If state unchanged → `no_progress_count++`
|
||||
- On new CI attempt detected → reset `local_verify_count = 0`
|
||||
|
||||
## Status Reporting
|
||||
|
||||
Based on verbosity level:
|
||||
|
||||
| Level | What to Report |
|
||||
| --------- | -------------------------------------------------------------------------- |
|
||||
| `minimal` | Only final result (success/failure/timeout) |
|
||||
| `medium` | State changes + periodic updates ("Cycle N \\| Elapsed: Xm \\| Status: ...") |
|
||||
| `verbose` | All of medium + full subagent responses, git outputs, MCP responses |
|
||||
|
||||
## User Instruction Examples
|
||||
|
||||
Users can override default behaviors:
|
||||
|
||||
| Instruction | Effect |
|
||||
| ------------------------------------------------ | --------------------------------------------- |
|
||||
| "never auto-apply" | Always prompt before applying any fix |
|
||||
| "always ask before git push" | Prompt before each push |
|
||||
| "reject any fix for e2e tasks" | Auto-reject if `failedTaskIds` contains e2e |
|
||||
| "apply all fixes regardless of verification" | Skip verification check, apply everything |
|
||||
| "if confidence < 70, reject" | Check confidence field before applying |
|
||||
| "run 'nx affected -t typecheck' before applying" | Add local verification step |
|
||||
| "auto-fix workflow failures" | Attempt lockfile updates on pre-CIPE failures |
|
||||
| "wait 45 min for new CIPE" | Override new-CIPE timeout (default: 10 min) |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Action |
|
||||
| ------------------------ | ------------------------------------------------------------------------------------- |
|
||||
| Git rebase conflict | Report to user, exit |
|
||||
| `nx apply-locally` fails | Report to user, attempt manual patch or exit |
|
||||
| MCP tool error | Retry once, if fails report to user |
|
||||
| Subagent spawn failure | Retry once, if fails exit with error |
|
||||
| No new CIPE detected | If `--auto-fix-workflow`, try lockfile update; otherwise report to user with guidance |
|
||||
| Lockfile auto-fix fails | Report to user, exit with guidance to check CI logs |
|
||||
|
||||
## Example Session
|
||||
|
||||
### Example 1: Normal Flow with Self-Healing (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-auth'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, verbosity=medium
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: IN_PROGRESS | Self-Healing: NOT_STARTED | Elapsed: 1m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: IN_PROGRESS | Elapsed: 3m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 5m
|
||||
|
||||
[ci-monitor] Fix available! Verification: COMPLETED
|
||||
[ci-monitor] Applying fix via MCP...
|
||||
[ci-monitor] Fix applied in CI. Waiting for new CI attempt...
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 8m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 2
|
||||
- Total time: 12m 34s
|
||||
- Fixes applied: 1
|
||||
- Result: SUCCESS
|
||||
```
|
||||
|
||||
### Example 2: Pre-CI Failure (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-products'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, auto-fix-workflow=true
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 2m
|
||||
|
||||
[ci-monitor] Applying fix locally, enhancing, and pushing...
|
||||
[ci-monitor] Committed: abc1234
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] Waiting for new CI attempt... (expected SHA: abc1234)
|
||||
[CI Monitor] ⚠️ CI attempt timeout (10 min). Returning no_new_cipe.
|
||||
|
||||
[ci-monitor] Status: no_new_cipe
|
||||
[ci-monitor] --auto-fix-workflow enabled. Attempting lockfile update...
|
||||
[ci-monitor] Lockfile updated. Committed: def5678
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 18m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 3
|
||||
- Total time: 22m 15s
|
||||
- Fixes applied: 1 (self-healing) + 1 (lockfile)
|
||||
- Result: SUCCESS
|
||||
```"""
|
||||
@@ -0,0 +1,437 @@
|
||||
---
|
||||
name: ci-monitor
|
||||
description: Monitor Nx Cloud CI pipeline and handle self-healing fixes automatically. Checks for Nx Cloud connection before starting.
|
||||
---
|
||||
|
||||
# CI Monitor Command
|
||||
|
||||
You are the orchestrator for monitoring Nx Cloud CI pipeline executions and handling self-healing fixes. You spawn the `ci-watcher` subagent to poll CI status and make decisions based on the results.
|
||||
|
||||
## Context
|
||||
|
||||
- **Current Branch:** !`git branch --show-current`
|
||||
- **Current Commit:** !`git rev-parse --short HEAD`
|
||||
- **Remote Status:** !`git status -sb | head -1`
|
||||
|
||||
## User Instructions
|
||||
|
||||
$ARGUMENTS
|
||||
|
||||
**Important:** If user provides specific instructions, respect them over default behaviors described below.
|
||||
|
||||
## Configuration Defaults
|
||||
|
||||
| Setting | Default | Description |
|
||||
| ------------------------- | ------------- | ------------------------------------------------------------------- |
|
||||
| `--max-cycles` | 10 | Maximum CIPE cycles before timeout |
|
||||
| `--timeout` | 120 | Maximum duration in minutes |
|
||||
| `--verbosity` | medium | Output level: minimal, medium, verbose |
|
||||
| `--branch` | (auto-detect) | Branch to monitor |
|
||||
| `--subagent-timeout` | 60 | Subagent polling timeout in minutes |
|
||||
| `--fresh` | false | Ignore previous context, start fresh |
|
||||
| `--auto-fix-workflow` | false | Attempt common fixes for pre-CIPE failures (e.g., lockfile updates) |
|
||||
| `--new-cipe-timeout` | 10 | Minutes to wait for new CIPE after action |
|
||||
| `--local-verify-attempts` | 3 | Max local verification + enhance cycles before pushing to CI |
|
||||
|
||||
Parse any overrides from `$ARGUMENTS` and merge with defaults.
|
||||
|
||||
## Nx Cloud Connection Check
|
||||
|
||||
**CRITICAL**: Before starting the monitoring loop, verify the workspace is connected to Nx Cloud.
|
||||
|
||||
### Step 0: Verify Nx Cloud Connection
|
||||
|
||||
1. **Check `nx.json`** at workspace root for `nxCloudId` or `nxCloudAccessToken`
|
||||
2. **If `nx.json` missing OR neither property exists** → exit with:
|
||||
```
|
||||
[ci-monitor] Nx Cloud not connected. Unlock 70% faster CI and auto-fix broken PRs with https://nx.dev/nx-cloud
|
||||
```
|
||||
3. **If connected** → continue to main loop
|
||||
|
||||
## Session Context Behavior
|
||||
|
||||
**Important:** Within a Claude Code session, conversation context persists. If you Ctrl+C to interrupt the monitor and re-run `/ci-monitor`, Claude remembers the previous state and may continue from where it left off.
|
||||
|
||||
- **To continue monitoring:** Just re-run `/ci-monitor` (context is preserved)
|
||||
- **To start fresh:** Use `/ci-monitor --fresh` to ignore previous context
|
||||
- **For a completely clean slate:** Exit Claude Code and restart `claude`
|
||||
|
||||
## Default Behaviors by Status
|
||||
|
||||
The subagent returns with one of the following statuses. This table defines the **default behavior** for each status. User instructions can override any of these.
|
||||
|
||||
| Status | Default Behavior |
|
||||
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci_success` | Exit with success. Log "CI passed successfully!" |
|
||||
| `fix_auto_applying` | Fix will be auto-applied by self-healing. Do NOT call MCP. Record `last_cipe_url`, spawn new subagent in wait mode to poll for new CIPE. |
|
||||
| `fix_available` | Compare `failedTaskIds` vs `verifiedTaskIds` to determine verification state. See **Fix Available Decision Logic** section below. |
|
||||
| `fix_failed` | Self-healing failed to generate fix. Attempt local fix based on `taskOutputSummary`. If successful → commit, push, loop. If not → exit with failure. |
|
||||
| `environment_issue` | Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`. New CIPE spawns automatically. Loop to poll for new CIPE. |
|
||||
| `no_fix` | CI failed, no fix available (self-healing disabled or not executable). Attempt local fix if possible. Otherwise exit with failure. |
|
||||
| `no_new_cipe` | Expected CIPE never spawned (CI workflow likely failed before Nx tasks). Report to user, attempt common fixes if configured, or exit with guidance. |
|
||||
| `polling_timeout` | Subagent polling timeout reached. Exit with timeout. |
|
||||
| `cipe_canceled` | CIPE was canceled. Exit with canceled status. |
|
||||
| `cipe_timed_out` | CIPE timed out. Exit with timeout status. |
|
||||
| `error` | Increment `no_progress_count`. If >= 3 → exit with circuit breaker. Otherwise wait 60s and loop. |
|
||||
|
||||
### Fix Available Decision Logic
|
||||
|
||||
When subagent returns `fix_available`, main agent compares `failedTaskIds` vs `verifiedTaskIds`:
|
||||
|
||||
#### Step 1: Categorize Tasks
|
||||
|
||||
1. **Verified tasks** = tasks in both `failedTaskIds` AND `verifiedTaskIds`
|
||||
2. **Unverified tasks** = tasks in `failedTaskIds` but NOT in `verifiedTaskIds`
|
||||
3. **E2E tasks** = unverified tasks where target contains "e2e" (task format: `<project>:<target>` or `<project>:<target>:<config>`)
|
||||
4. **Verifiable tasks** = unverified tasks that are NOT e2e
|
||||
|
||||
#### Step 2: Determine Path
|
||||
|
||||
| Condition | Path |
|
||||
| --------------------------------------- | ---------------------------------------- |
|
||||
| No unverified tasks (all verified) | Apply via MCP |
|
||||
| Unverified tasks exist, but ALL are e2e | Apply via MCP (treat as verified enough) |
|
||||
| Verifiable tasks exist | Local verification flow |
|
||||
|
||||
#### Step 3a: Apply via MCP (fully/e2e-only verified)
|
||||
|
||||
- Call `update_self_healing_fix({ shortLink, action: "APPLY" })`
|
||||
- Record `last_cipe_url`, spawn subagent in wait mode
|
||||
|
||||
#### Step 3b: Local Verification Flow
|
||||
|
||||
When verifiable (non-e2e) unverified tasks exist:
|
||||
|
||||
1. **Detect package manager:**
|
||||
- `pnpm-lock.yaml` exists → `pnpm nx`
|
||||
- `yarn.lock` exists → `yarn nx`
|
||||
- Otherwise → `npx nx`
|
||||
|
||||
2. **Run verifiable tasks in parallel:**
|
||||
- Spawn `general` subagents to run each task concurrently
|
||||
- Each subagent runs: `<pm> nx run <taskId>`
|
||||
- Collect pass/fail results from all subagents
|
||||
|
||||
3. **Evaluate results:**
|
||||
|
||||
| Result | Action |
|
||||
| ------------------------- | ---------------------------- |
|
||||
| ALL verifiable tasks pass | Apply via MCP |
|
||||
| ANY verifiable task fails | Apply-locally + enhance flow |
|
||||
|
||||
4. **Apply-locally + enhance flow:**
|
||||
- Run `nx apply-locally <shortLink>`
|
||||
- Enhance the code to fix failing tasks
|
||||
- Run failing tasks again to verify fix
|
||||
- If still failing → increment `local_verify_count`, loop back to enhance
|
||||
- If passing → commit and push, record `expected_commit_sha`, spawn subagent in wait mode
|
||||
|
||||
5. **Track attempts** (wraps step 4):
|
||||
- Increment `local_verify_count` after each enhance cycle
|
||||
- If `local_verify_count >= local_verify_attempts` (default: 3):
|
||||
- Get code in commit-able state
|
||||
- Commit and push with message indicating local verification failed
|
||||
- Report to user:
|
||||
```
|
||||
[ci-monitor] Local verification failed after <N> attempts. Pushed to CI for final validation. Failed: <taskIds>
|
||||
```
|
||||
- Record `expected_commit_sha`, spawn subagent in wait mode (let CI be final judge)
|
||||
|
||||
#### Commit Message Format
|
||||
|
||||
```bash
|
||||
git commit -m "fix(<projects>): <brief description>
|
||||
|
||||
Failed tasks: <taskId1>, <taskId2>
|
||||
Local verification: passed|enhanced|failed-pushing-to-ci"
|
||||
```
|
||||
|
||||
### Unverified Fix Flow (No Verification Attempted)
|
||||
|
||||
When `verificationStatus` is `FAILED`, `NOT_EXECUTABLE`, or fix has `couldAutoApplyTasks != true` with no verification:
|
||||
|
||||
- Analyze fix content (`suggestedFix`, `suggestedFixReasoning`, `taskOutputSummary`)
|
||||
- If fix looks correct → apply via MCP
|
||||
- If fix needs enhancement → use Apply Locally + Enhance Flow above
|
||||
- If fix is wrong → reject via MCP, fix from scratch, commit, push
|
||||
|
||||
### Auto-Apply Eligibility
|
||||
|
||||
The `couldAutoApplyTasks` field indicates whether the fix is eligible for automatic application:
|
||||
|
||||
- **`true`**: Fix is eligible for auto-apply. Subagent keeps polling while verification is in progress. Returns `fix_auto_applying` when verified, or `fix_available` if verification fails.
|
||||
- **`false`** or **`null`**: Fix requires manual action (apply via MCP, apply locally, or reject)
|
||||
|
||||
**Key point**: When subagent returns `fix_auto_applying`, do NOT call MCP to apply - self-healing handles it. Just spawn a new subagent in wait mode.
|
||||
|
||||
### Apply vs Reject vs Apply Locally
|
||||
|
||||
- **Apply via MCP**: Calls `update_self_healing_fix({ shortLink, action: "APPLY" })`. Self-healing agent applies the fix in CI and a new CIPE spawns automatically. No local git operations needed.
|
||||
- **Apply Locally**: Runs `nx apply-locally <shortLink>`. Applies the patch to your local working directory and sets state to `APPLIED_LOCALLY`. Use this when you want to enhance the fix before pushing.
|
||||
- **Reject via MCP**: Calls `update_self_healing_fix({ shortLink, action: "REJECT" })`. Marks fix as rejected. Use only when the fix is completely wrong and you'll fix from scratch.
|
||||
|
||||
### Apply Locally + Enhance Flow
|
||||
|
||||
When the fix needs enhancement (use `nx apply-locally`, NOT reject):
|
||||
|
||||
1. Apply the patch locally: `nx apply-locally <shortLink>` (this also updates state to `APPLIED_LOCALLY`)
|
||||
2. Make additional changes as needed
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Reject + Fix From Scratch Flow
|
||||
|
||||
When the fix is completely wrong:
|
||||
|
||||
1. Call MCP to reject: `update_self_healing_fix({ shortLink, action: "REJECT" })`
|
||||
2. Fix the issue from scratch locally
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Environment Issue Handling
|
||||
|
||||
When `failureClassification == 'ENVIRONMENT_STATE'`:
|
||||
|
||||
1. Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`
|
||||
2. New CIPE spawns automatically (no local git operations needed)
|
||||
3. Loop to poll for new CIPE with `previousCipeUrl` set
|
||||
|
||||
### No-New-CIPE Handling
|
||||
|
||||
When `status == 'no_new_cipe'`:
|
||||
|
||||
This means the expected CIPE was never created - CI likely failed before Nx tasks could run.
|
||||
|
||||
1. **Report to user:**
|
||||
|
||||
```
|
||||
[ci-monitor] No CI attempt for <sha> after 10 min. Check CI provider for pre-Nx failures (install, checkout, auth). Last CI attempt: <previousCipeUrl>
|
||||
```
|
||||
|
||||
2. **If user configured auto-fix attempts** (e.g., `--auto-fix-workflow`):
|
||||
- Detect package manager: check for `pnpm-lock.yaml`, `yarn.lock`, `package-lock.json`
|
||||
- Run install to update lockfile:
|
||||
```bash
|
||||
pnpm install # or npm install / yarn install
|
||||
```
|
||||
- If lockfile changed:
|
||||
```bash
|
||||
git add pnpm-lock.yaml # or appropriate lockfile
|
||||
git commit -m "chore: update lockfile"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
- Record new commit SHA, loop to poll with `expectedCommitSha`
|
||||
|
||||
3. **Otherwise:** Exit with `no_new_cipe` status, providing guidance for user to investigate
|
||||
|
||||
## Exit Conditions
|
||||
|
||||
Exit the monitoring loop when ANY of these conditions are met:
|
||||
|
||||
| Condition | Exit Type |
|
||||
| ------------------------------------------- | ---------------- |
|
||||
| CI passes (`cipeStatus == 'SUCCEEDED'`) | Success |
|
||||
| Max CIPE cycles reached | Timeout |
|
||||
| Max duration reached | Timeout |
|
||||
| 3 consecutive no-progress iterations | Circuit breaker |
|
||||
| No fix available and local fix not possible | Failure |
|
||||
| No new CIPE and auto-fix not configured | Pre-CIPE failure |
|
||||
| User cancels | Cancelled |
|
||||
|
||||
## Main Loop
|
||||
|
||||
### Step 1: Initialize Tracking
|
||||
|
||||
```
|
||||
cycle_count = 0
|
||||
start_time = now()
|
||||
no_progress_count = 0
|
||||
local_verify_count = 0
|
||||
last_state = null
|
||||
last_cipe_url = null
|
||||
expected_commit_sha = null
|
||||
```
|
||||
|
||||
### Step 2: Spawn Subagent
|
||||
|
||||
Spawn the `ci-watcher` subagent to poll CI status:
|
||||
|
||||
**Fresh start (first spawn, no expected CIPE):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>."
|
||||
)
|
||||
```
|
||||
|
||||
**After action that triggers new CIPE (wait mode):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>.
|
||||
|
||||
WAIT MODE: A new CIPE should spawn. Ignore old CIPE until new one appears.
|
||||
Expected commit SHA: <expected_commit_sha>
|
||||
Previous CIPE URL: <last_cipe_url>"
|
||||
)
|
||||
```
|
||||
|
||||
### Step 3: Handle Subagent Response
|
||||
|
||||
When subagent returns:
|
||||
|
||||
1. Check the returned status
|
||||
2. Look up default behavior in the table above
|
||||
3. Check if user instructions override the default
|
||||
4. Execute the appropriate action
|
||||
5. **If action expects new CIPE**, update tracking (see Step 3a)
|
||||
6. If action results in looping, go to Step 2
|
||||
|
||||
### Step 3a: Track State for New-CIPE Detection
|
||||
|
||||
After actions that should trigger a new CIPE, record state before looping:
|
||||
|
||||
| Action | What to Track | Subagent Mode |
|
||||
| ----------------------------- | --------------------------------------------- | ------------- |
|
||||
| Fix auto-applying | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply via MCP | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply locally + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Reject + fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Fix failed + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| No fix + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Environment rerun | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| No-new-CIPE + auto-fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
|
||||
**CRITICAL**: When passing `expectedCommitSha` or `last_cipe_url` to the subagent, it enters **wait mode**:
|
||||
|
||||
- Subagent will **completely ignore** the old/stale CIPE
|
||||
- Subagent will only wait for new CIPE to appear
|
||||
- Subagent will NOT return to main agent with stale CIPE data
|
||||
- Once new CIPE detected, subagent switches to normal polling
|
||||
|
||||
**Why wait mode matters for context preservation**: Stale CIPE data can be very large (task output summaries, suggested fix patches, reasoning). If subagent returns this to main agent, it pollutes main agent's context with useless data since we already processed that CIPE. Wait mode keeps stale data in the subagent, never sending it to main agent.
|
||||
|
||||
### Step 4: Progress Tracking
|
||||
|
||||
After each action:
|
||||
|
||||
- If state changed significantly → reset `no_progress_count = 0`
|
||||
- If state unchanged → `no_progress_count++`
|
||||
- On new CI attempt detected → reset `local_verify_count = 0`
|
||||
|
||||
## Status Reporting
|
||||
|
||||
Based on verbosity level:
|
||||
|
||||
| Level | What to Report |
|
||||
| --------- | -------------------------------------------------------------------------- |
|
||||
| `minimal` | Only final result (success/failure/timeout) |
|
||||
| `medium` | State changes + periodic updates ("Cycle N \| Elapsed: Xm \| Status: ...") |
|
||||
| `verbose` | All of medium + full subagent responses, git outputs, MCP responses |
|
||||
|
||||
## User Instruction Examples
|
||||
|
||||
Users can override default behaviors:
|
||||
|
||||
| Instruction | Effect |
|
||||
| ------------------------------------------------ | --------------------------------------------- |
|
||||
| "never auto-apply" | Always prompt before applying any fix |
|
||||
| "always ask before git push" | Prompt before each push |
|
||||
| "reject any fix for e2e tasks" | Auto-reject if `failedTaskIds` contains e2e |
|
||||
| "apply all fixes regardless of verification" | Skip verification check, apply everything |
|
||||
| "if confidence < 70, reject" | Check confidence field before applying |
|
||||
| "run 'nx affected -t typecheck' before applying" | Add local verification step |
|
||||
| "auto-fix workflow failures" | Attempt lockfile updates on pre-CIPE failures |
|
||||
| "wait 45 min for new CIPE" | Override new-CIPE timeout (default: 10 min) |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Action |
|
||||
| ------------------------ | ------------------------------------------------------------------------------------- |
|
||||
| Git rebase conflict | Report to user, exit |
|
||||
| `nx apply-locally` fails | Report to user, attempt manual patch or exit |
|
||||
| MCP tool error | Retry once, if fails report to user |
|
||||
| Subagent spawn failure | Retry once, if fails exit with error |
|
||||
| No new CIPE detected | If `--auto-fix-workflow`, try lockfile update; otherwise report to user with guidance |
|
||||
| Lockfile auto-fix fails | Report to user, exit with guidance to check CI logs |
|
||||
|
||||
## Example Session
|
||||
|
||||
### Example 1: Normal Flow with Self-Healing (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-auth'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, verbosity=medium
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: IN_PROGRESS | Self-Healing: NOT_STARTED | Elapsed: 1m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: IN_PROGRESS | Elapsed: 3m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 5m
|
||||
|
||||
[ci-monitor] Fix available! Verification: COMPLETED
|
||||
[ci-monitor] Applying fix via MCP...
|
||||
[ci-monitor] Fix applied in CI. Waiting for new CI attempt...
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 8m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 2
|
||||
- Total time: 12m 34s
|
||||
- Fixes applied: 1
|
||||
- Result: SUCCESS
|
||||
```
|
||||
|
||||
### Example 2: Pre-CI Failure (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-products'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, auto-fix-workflow=true
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 2m
|
||||
|
||||
[ci-monitor] Applying fix locally, enhancing, and pushing...
|
||||
[ci-monitor] Committed: abc1234
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] Waiting for new CI attempt... (expected SHA: abc1234)
|
||||
[CI Monitor] ⚠️ CI attempt timeout (10 min). Returning no_new_cipe.
|
||||
|
||||
[ci-monitor] Status: no_new_cipe
|
||||
[ci-monitor] --auto-fix-workflow enabled. Attempting lockfile update...
|
||||
[ci-monitor] Lockfile updated. Committed: def5678
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 18m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 3
|
||||
- Total time: 22m 15s
|
||||
- Fixes applied: 1 (self-healing) + 1 (lockfile)
|
||||
- Result: SUCCESS
|
||||
```
|
||||
@@ -0,0 +1,228 @@
|
||||
---
|
||||
name: nx-generate
|
||||
description: Generate code using nx generators. USE WHEN scaffolding code or transforming existing code - for example creating libraries or applications, or anything else that is boilerplate code or automates repetitive tasks. ALWAYS use this first when generating code with Nx instead of calling MCP tools or running nx generate immediately.
|
||||
---
|
||||
|
||||
# Run Nx Generator
|
||||
|
||||
Nx generators are powerful tools that scaffold projects, make automated code migrations or automate repetitive tasks in a monorepo. They ensure consistency across the codebase and reduce boilerplate work.
|
||||
|
||||
This skill applies when the user wants to:
|
||||
|
||||
- Create new projects like libraries or applications
|
||||
- Scaffold features or boilerplate code
|
||||
- Run workspace-specific or custom generators
|
||||
- Do anything else that an nx generator exists for
|
||||
|
||||
## Generator Discovery Flow
|
||||
|
||||
### Step 1: List Available Generators
|
||||
|
||||
Use the Nx CLI to discover available generators:
|
||||
|
||||
- List all generators for a plugin: `npx nx list @nx/react`
|
||||
- View available plugins: `npx nx list`
|
||||
|
||||
This includes:
|
||||
|
||||
- Plugin generators (e.g., `@nx/react:library`, `@nx/js:library`)
|
||||
- Local workspace generators (defined in the repo's own plugins)
|
||||
|
||||
### Step 2: Match Generator to User Request
|
||||
|
||||
Based on the user's request, identify which generator(s) could fulfill their needs. Consider:
|
||||
|
||||
- What artifact type they want to create (library, application, etc.)
|
||||
- Which framework or technology stack is relevant
|
||||
- Whether they mentioned specific generator names
|
||||
|
||||
**IMPORTANT**: When both a local workspace generator and an external plugin generator could satisfy the request, **always prefer the local workspace generator**. Local generators are customized for the specific repo's patterns and conventions.
|
||||
|
||||
It's possible that the user request is something that no Nx generator exists for whatsoever. In this case, you can stop using this skill and try to help the user another way. HOWEVER, the burden of proof for this is high. Before aborting, carefully consider each and every generator that's available. Look into details for any that could be related in any way before making this decision.
|
||||
|
||||
## Pre-Execution Checklist
|
||||
|
||||
Before running any generator, complete these steps:
|
||||
|
||||
### 1. Fetch Generator Schema
|
||||
|
||||
Use the `--help` flag to understand all available options:
|
||||
|
||||
```bash
|
||||
npx nx g @nx/react:library --help
|
||||
```
|
||||
|
||||
Pay attention to:
|
||||
|
||||
- Required options that must be provided
|
||||
- Optional options that may be relevant to the user's request
|
||||
- Default values that might need to be overridden
|
||||
|
||||
### 2. Read Generator Source Code
|
||||
|
||||
Understanding what the generator actually does helps you:
|
||||
|
||||
- Know what files will be created/modified
|
||||
- Understand any side effects (updating configs, installing deps, etc.)
|
||||
- Identify options that might not be obvious from the schema
|
||||
|
||||
To find generator source code:
|
||||
|
||||
- For plugin generators: Use `node -e "console.log(require.resolve('@nx/<plugin>/generators.json'));"` to find the generators.json, then locate the source from there
|
||||
- If that fails, read directly from `node_modules/<plugin>/generators.json`
|
||||
- For local generators: They are typically in `tools/generators/` or a local plugin directory. You can search the repo for the generator name to find it.
|
||||
|
||||
### 2.5 Reevaluate if the generator is right
|
||||
|
||||
Once you have built up an understanding of what the selected generator does, reconsider: Is this the right generator to service the user request?
|
||||
If not, it's okay to go back to the Generator Discovery Flow and select a different generator before proceeding. If you do, make sure to go through the entire pre-execution checklist once more.
|
||||
|
||||
### 3. Understand Repo Context
|
||||
|
||||
Before generating, examine the target area of the codebase:
|
||||
|
||||
- Look at similar existing artifacts (other libraries, applications, etc.)
|
||||
- Identify patterns and conventions used in the repo
|
||||
- Note naming conventions, file structures, and configuration patterns
|
||||
- Try to match these patterns when configuring the generator
|
||||
|
||||
For example, if similar libraries are using a specific test runner, build tool or linter, try to match that if possible.
|
||||
If projects or other artifacts are organized with a specific naming convention, try to match it.
|
||||
|
||||
### 4. Validate Required Options
|
||||
|
||||
Ensure all required options have values:
|
||||
|
||||
- Map the user's request to generator options
|
||||
- Infer values from context where possible
|
||||
- Ask the user for any critical missing information
|
||||
|
||||
## Execution
|
||||
|
||||
Keep in mind that you might have to prefix things with npx/pnpx/yarn if the user doesn't have nx installed globally.
|
||||
Many generators will behave differently based on where they are executed. For example, first-party nx library generators use the cwd to determine the directory that the library should be placed in. This is highly important.
|
||||
|
||||
### Consider Dry-Run (Optional)
|
||||
|
||||
Running with `--dry-run` first is strongly encouraged but not mandatory. Use your judgment:
|
||||
|
||||
- For complex generators or unfamiliar territory: do a dry-run first
|
||||
- For simple, well-understood generators: may proceed directly
|
||||
- Dry-run shows file names and created/deleted/modified markers, but not content
|
||||
- There are cases where a generator does not support dry-run (for example if it had to install an npm package) - in that case --dry-run might fail. Don't be discouraged but simply move on to running the generator for real and iterating from there.
|
||||
|
||||
### Running the Generator
|
||||
|
||||
Execute the generator with:
|
||||
|
||||
```bash
|
||||
nx generate <generator-name> <options> --no-interactive
|
||||
```
|
||||
|
||||
**CRITICAL**: Always include `--no-interactive` to prevent prompts that would hang the execution.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
nx generate @nx/react:library --name=my-utils --no-interactive
|
||||
```
|
||||
|
||||
### Handling Generator Failures
|
||||
|
||||
If the generator fails:
|
||||
|
||||
1. **Diagnose the error** - Read the error message carefully
|
||||
2. **Identify the cause** - Missing options, invalid values, conflicts, etc.
|
||||
3. **Attempt automatic fix** - Adjust options or resolve conflicts
|
||||
4. **Retry** - Run the generator again with corrected options
|
||||
|
||||
Common failure reasons:
|
||||
|
||||
- Missing required options
|
||||
- Invalid option values
|
||||
- Conflicting with existing files
|
||||
- Missing dependencies
|
||||
- Generator doesn't support certain flag combinations
|
||||
|
||||
## Post-Generation
|
||||
|
||||
### 1. Modify Generated Code (If Needed)
|
||||
|
||||
Generators provide a starting point, but the output may need adjustment to match the user's specific requirements:
|
||||
|
||||
- Add or modify functionality as requested
|
||||
- Adjust imports, exports, or configurations
|
||||
- Integrate with existing code patterns in the repo
|
||||
|
||||
### 2. Format Code
|
||||
|
||||
Run formatting on all generated/modified files:
|
||||
|
||||
```bash
|
||||
nx format --fix
|
||||
```
|
||||
|
||||
Languages other than javascript/typescript might need other formatting invocations too.
|
||||
|
||||
### 3. Run Verification
|
||||
|
||||
Verify that the generated code works correctly. What this looks like will vary depending on the type of generator and the targets available.
|
||||
If the generator created a new project, run its targets directly
|
||||
Use your best judgement to determine what needs to be verified.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
nx lint <new-project>
|
||||
nx test <new-project>
|
||||
nx build <new-project>
|
||||
```
|
||||
|
||||
### 4. Handle Verification Failures
|
||||
|
||||
When verification fails:
|
||||
|
||||
**If scope is manageable** (a few lint errors, minor type issues):
|
||||
|
||||
- Fix the issues
|
||||
- Re-run verification to confirm
|
||||
|
||||
**If issues are extensive** (many errors, complex problems):
|
||||
|
||||
- Attempt simple, obvious fixes first
|
||||
- If still failing, escalate to the user with:
|
||||
- Description of what was generated
|
||||
- What verification is failing
|
||||
- What you've attempted to fix
|
||||
- Remaining issues that need user input
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Generator Failures
|
||||
|
||||
- Check the error message for specific causes
|
||||
- Verify all required options are provided
|
||||
- Check for conflicts with existing files
|
||||
- Ensure the generator name and options are correct
|
||||
|
||||
### Missing Options
|
||||
|
||||
- Consult the generator schema for required fields
|
||||
- Infer values from context when reasonable
|
||||
- Ask the user for values that cannot be inferred
|
||||
|
||||
## Key Principles
|
||||
|
||||
1. **Local generators first** - Always prefer workspace/local generators over external plugin generators when both could work
|
||||
|
||||
2. **Understand before running** - Read both the schema AND the source code to fully understand what will happen
|
||||
|
||||
3. **No prompts** - Always use `--no-interactive` to prevent hanging
|
||||
|
||||
4. **Generators are starting points** - Modify the output as needed to fully satisfy the user's requirements
|
||||
|
||||
5. **Verify changes work** - Don't just generate; ensure the code builds, lints, and tests pass
|
||||
|
||||
6. **Be proactive about fixes** - Don't just report errors; attempt to resolve them automatically when possible
|
||||
|
||||
7. **Match repo patterns** - Study existing similar code in the repo and match its conventions
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
name: nx-plugins
|
||||
description: Find and add Nx plugins. USE WHEN user wants to discover available plugins, install a new plugin, or add support for a specific framework or technology to the workspace.
|
||||
---
|
||||
|
||||
## Finding and Installing new plugins
|
||||
|
||||
- List plugins: `pnpm nx list`
|
||||
- Install plugins `pnpm nx add <plugin>`. Example: `pnpm nx add @nx/react`.
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
name: nx-run-tasks
|
||||
description: Helps with running tasks in an Nx workspace. USE WHEN the user wants to execute build, test, lint, serve, or run any other tasks defined in the workspace.
|
||||
---
|
||||
|
||||
You can run tasks with Nx in the following way.
|
||||
|
||||
Keep in mind that you might have to prefix things with npx/pnpx/yarn if the user doesn't have nx installed globally. Look at the package.json or lockfile to determine which package manager is in use.
|
||||
|
||||
For more details on any command, run it with `--help` (e.g. `nx run-many --help`, `nx affected --help`).
|
||||
|
||||
## Understand which tasks can be run
|
||||
|
||||
You can check those via `nx show project <projectname> --json`, for example `nx show project myapp --json`. It contains a `targets` section which has information about targets that can be run. You can also just look at the `package.json` scripts or `project.json` targets, but you might miss out on inferred tasks by Nx plugins.
|
||||
|
||||
## Run a single task
|
||||
|
||||
```
|
||||
nx run <project>:<task>
|
||||
```
|
||||
|
||||
where `project` is the project name defined in `package.json` or `project.json` (if present).
|
||||
|
||||
## Run multiple tasks
|
||||
|
||||
```
|
||||
nx run-many -t build test lint typecheck
|
||||
```
|
||||
|
||||
You can pass a `-p` flag to filter to specific projects, otherwise it runs on all projects. You can also use `--exclude` to exclude projects, and `--parallel` to control the number of parallel processes (default is 3).
|
||||
|
||||
Examples:
|
||||
|
||||
- `nx run-many -t test -p proj1 proj2` — test specific projects
|
||||
- `nx run-many -t test --projects=*-app --exclude=excluded-app` — test projects matching a pattern
|
||||
- `nx run-many -t test --projects=tag:api-*` — test projects by tag
|
||||
|
||||
## Run tasks for affected projects
|
||||
|
||||
Use `nx affected` to only run tasks on projects that have been changed and projects that depend on changed projects. This is especially useful in CI and for large workspaces.
|
||||
|
||||
```
|
||||
nx affected -t build test lint
|
||||
```
|
||||
|
||||
By default it compares against the base branch. You can customize this:
|
||||
|
||||
- `nx affected -t test --base=main --head=HEAD` — compare against a specific base and head
|
||||
- `nx affected -t test --files=libs/mylib/src/index.ts` — specify changed files directly
|
||||
|
||||
## Useful flags
|
||||
|
||||
These flags work with `run`, `run-many`, and `affected`:
|
||||
|
||||
- `--skipNxCache` — rerun tasks even when results are cached
|
||||
- `--verbose` — print additional information such as stack traces
|
||||
- `--nxBail` — stop execution after the first failed task
|
||||
- `--configuration=<name>` — use a specific configuration (e.g. `production`)
|
||||
@@ -0,0 +1,186 @@
|
||||
---
|
||||
name: nx-workspace
|
||||
description: "Explore and understand Nx workspaces. USE WHEN answering any questions about the nx workspace, the projects in it or tasks to run. EXAMPLES: 'What projects are in this workspace?', 'How is project X configured?', 'What targets can I run?', 'What's affected by my changes?', 'Which projects depend on library Y?', or any questions about Nx workspace structure, project configuration, or available tasks."
|
||||
---
|
||||
|
||||
# Nx Workspace Exploration
|
||||
|
||||
This skill provides read-only exploration of Nx workspaces. Use it to understand workspace structure, project configuration, available targets, and dependencies.
|
||||
|
||||
Keep in mind that you might have to prefix commands with `npx`/`pnpx`/`yarn` if nx isn't installed globally. Check the lockfile to determine the package manager in use.
|
||||
|
||||
## Listing Projects
|
||||
|
||||
Use `nx show projects` to list projects in the workspace.
|
||||
|
||||
```bash
|
||||
# List all projects
|
||||
nx show projects
|
||||
|
||||
# Filter by pattern (glob)
|
||||
nx show projects --projects "apps/*"
|
||||
nx show projects --projects "shared-*"
|
||||
|
||||
# Filter by project type
|
||||
nx show projects --type app
|
||||
nx show projects --type lib
|
||||
nx show projects --type e2e
|
||||
|
||||
# Filter by target (projects that have a specific target)
|
||||
nx show projects --withTarget build
|
||||
nx show projects --withTarget e2e
|
||||
|
||||
# Find affected projects (changed since base branch)
|
||||
nx show projects --affected
|
||||
nx show projects --affected --base=main
|
||||
nx show projects --affected --type app
|
||||
|
||||
# Combine filters
|
||||
nx show projects --type lib --withTarget test
|
||||
nx show projects --affected --exclude="*-e2e"
|
||||
|
||||
# Output as JSON
|
||||
nx show projects --json
|
||||
```
|
||||
|
||||
## Project Configuration
|
||||
|
||||
Use `nx show project <name> --json` to get the full resolved configuration for a project.
|
||||
|
||||
**Important**: Do NOT read `project.json` directly - it only contains partial configuration. The `nx show project` command returns the full resolved config including inferred targets from plugins.
|
||||
|
||||
You can read the full project schema at `node_modules/nx/schemas/project-schema.json` to understand nx project configuration options.
|
||||
|
||||
```bash
|
||||
# Get full project configuration
|
||||
nx show project my-app --json
|
||||
|
||||
# Extract specific parts from the JSON
|
||||
nx show project my-app --json | jq '.targets'
|
||||
nx show project my-app --json | jq '.targets.build'
|
||||
nx show project my-app --json | jq '.targets | keys'
|
||||
|
||||
|
||||
# Check project metadata
|
||||
nx show project my-app --json | jq '{name, root, sourceRoot, projectType, tags}'
|
||||
```
|
||||
|
||||
## Target Information
|
||||
|
||||
Targets define what tasks can be run on a project.
|
||||
|
||||
```bash
|
||||
# List all targets for a project
|
||||
nx show project my-app --json | jq '.targets | keys'
|
||||
|
||||
# Get full target configuration
|
||||
nx show project my-app --json | jq '.targets.build'
|
||||
|
||||
# Check target executor/command
|
||||
nx show project my-app --json | jq '.targets.build.executor'
|
||||
nx show project my-app --json | jq '.targets.build.command'
|
||||
|
||||
# View target options
|
||||
nx show project my-app --json | jq '.targets.build.options'
|
||||
|
||||
# Check target inputs/outputs (for caching)
|
||||
nx show project my-app --json | jq '.targets.build.inputs'
|
||||
nx show project my-app --json | jq '.targets.build.outputs'
|
||||
|
||||
# Find projects with a specific target
|
||||
nx show projects --withTarget serve
|
||||
nx show projects --withTarget e2e
|
||||
```
|
||||
|
||||
## Workspace Configuration
|
||||
|
||||
Read `nx.json` directly for workspace-level configuration.
|
||||
You can read the full project schema at `node_modules/nx/schemas/nx-schema.json` to understand nx project configuration options.
|
||||
|
||||
```bash
|
||||
# Read the full nx.json
|
||||
cat nx.json
|
||||
|
||||
# Or use jq for specific sections
|
||||
cat nx.json | jq '.targetDefaults'
|
||||
cat nx.json | jq '.namedInputs'
|
||||
cat nx.json | jq '.plugins'
|
||||
cat nx.json | jq '.generators'
|
||||
```
|
||||
|
||||
Key nx.json sections:
|
||||
|
||||
- `targetDefaults` - Default configuration applied to all targets of a given name
|
||||
- `namedInputs` - Reusable input definitions for caching
|
||||
- `plugins` - Nx plugins and their configuration
|
||||
- ...and much more, read the schema or nx.json for details
|
||||
|
||||
## Affected Projects
|
||||
|
||||
Find projects affected by changes in the current branch.
|
||||
|
||||
```bash
|
||||
# Affected since base branch (auto-detected)
|
||||
nx show projects --affected
|
||||
|
||||
# Affected with explicit base
|
||||
nx show projects --affected --base=main
|
||||
nx show projects --affected --base=origin/main
|
||||
|
||||
# Affected between two commits
|
||||
nx show projects --affected --base=abc123 --head=def456
|
||||
|
||||
# Affected apps only
|
||||
nx show projects --affected --type app
|
||||
|
||||
# Affected excluding e2e projects
|
||||
nx show projects --affected --exclude="*-e2e"
|
||||
|
||||
# Affected by uncommitted changes
|
||||
nx show projects --affected --uncommitted
|
||||
|
||||
# Affected by untracked files
|
||||
nx show projects --affected --untracked
|
||||
```
|
||||
|
||||
## Common Exploration Patterns
|
||||
|
||||
### "What's in this workspace?"
|
||||
|
||||
```bash
|
||||
nx show projects
|
||||
nx show projects --type app
|
||||
nx show projects --type lib
|
||||
```
|
||||
|
||||
### "How do I build/test/lint project X?"
|
||||
|
||||
```bash
|
||||
nx show project X --json | jq '.targets | keys'
|
||||
nx show project X --json | jq '.targets.build'
|
||||
```
|
||||
|
||||
### "What depends on library Y?"
|
||||
|
||||
```bash
|
||||
# Find projects that may depend on Y by searching for imports
|
||||
# (Nx doesn't have a direct "dependents" command via CLI)
|
||||
grep -r "from '@myorg/Y'" --include="*.ts" --include="*.tsx" apps/ libs/
|
||||
```
|
||||
|
||||
### "What configuration options are available?"
|
||||
|
||||
```bash
|
||||
cat node_modules/nx/schemas/nx-schema.json | jq '.properties | keys'
|
||||
cat node_modules/nx/schemas/project-schema.json | jq '.properties | keys'
|
||||
```
|
||||
|
||||
### "Why is project X affected?"
|
||||
|
||||
```bash
|
||||
# Check what files changed
|
||||
git diff --name-only main
|
||||
|
||||
# See which project owns those files
|
||||
nx show project X --json | jq '.root'
|
||||
```
|
||||
@@ -0,0 +1,478 @@
|
||||
---
|
||||
description: Polls Nx Cloud CI pipeline and self-healing status. Returns structured state when actionable. Spawned by /nx-cloud-ci-monitor command to monitor CI Attempt status.
|
||||
---
|
||||
|
||||
# CI Watcher Subagent
|
||||
|
||||
You are a CI monitoring subagent responsible for polling Nx Cloud CI Attempt status and self-healing state. You report status back to the main agent - you do NOT make apply/reject decisions.
|
||||
|
||||
## Your Responsibilities
|
||||
|
||||
1. Poll CI status using the `ci_information` MCP tool
|
||||
2. Implement exponential backoff between polls
|
||||
3. Return structured state when an actionable condition is reached
|
||||
4. Track iteration count and elapsed time
|
||||
5. Output status updates based on verbosity level
|
||||
|
||||
## Input Parameters (from Main Agent)
|
||||
|
||||
The main agent may provide these optional parameters in the prompt:
|
||||
|
||||
| Parameter | Description |
|
||||
| ------------------- | -------------------------------------------------------- |
|
||||
| `branch` | Branch to monitor (auto-detected if not provided) |
|
||||
| `expectedCommitSha` | Commit SHA that should trigger a new CI Attempt |
|
||||
| `previousCipeUrl` | CI Attempt URL before the action (to detect change) |
|
||||
| `subagentTimeout` | Polling timeout in minutes (default: 60) |
|
||||
| `verbosity` | Output level: minimal, medium, verbose (default: medium) |
|
||||
|
||||
When `expectedCommitSha` or `previousCipeUrl` is provided, you must detect whether a new CI Attempt has spawned.
|
||||
|
||||
## MCP Tool Reference
|
||||
|
||||
### `ci_information`
|
||||
|
||||
**Input:**
|
||||
|
||||
```json
|
||||
{
|
||||
"branch": "string (optional, defaults to current git branch)",
|
||||
"select": "string (optional, comma-separated field names)",
|
||||
"pageToken": "number (optional, 0-based pagination for long strings)"
|
||||
}
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```json
|
||||
{
|
||||
"cipeStatus": "NOT_STARTED | IN_PROGRESS | SUCCEEDED | FAILED | CANCELED | TIMED_OUT",
|
||||
"cipeUrl": "string",
|
||||
"branch": "string",
|
||||
"commitSha": "string | null",
|
||||
"failedTaskIds": "string[]",
|
||||
"verifiedTaskIds": "string[]",
|
||||
"selfHealingEnabled": "boolean",
|
||||
"selfHealingStatus": "NOT_STARTED | IN_PROGRESS | COMPLETED | FAILED | NOT_EXECUTABLE | null",
|
||||
"verificationStatus": "NOT_STARTED | IN_PROGRESS | COMPLETED | FAILED | NOT_EXECUTABLE | null",
|
||||
"userAction": "NONE | APPLIED | REJECTED | APPLIED_LOCALLY | APPLIED_AUTOMATICALLY | null",
|
||||
"failureClassification": "string | null",
|
||||
"taskOutputSummary": "string | null",
|
||||
"suggestedFixReasoning": "string | null",
|
||||
"suggestedFixDescription": "string | null",
|
||||
"suggestedFix": "string | null",
|
||||
"shortLink": "string | null",
|
||||
"couldAutoApplyTasks": "boolean | null",
|
||||
"confidence": "number | null",
|
||||
"confidenceReasoning": "string | null"
|
||||
}
|
||||
```
|
||||
|
||||
**Select Parameter:**
|
||||
|
||||
| Usage | Returns |
|
||||
| --------------- | ----------------------------------------------------------- |
|
||||
| No `select` | Formatted overview (truncated, not recommended for polling) |
|
||||
| Single field | Raw value with pagination for long strings |
|
||||
| Multiple fields | Object with requested field values |
|
||||
|
||||
**Field Sets for Efficient Polling:**
|
||||
|
||||
```yaml
|
||||
WAIT_FIELDS:
|
||||
'cipeUrl,commitSha,cipeStatus'
|
||||
# Minimal fields for detecting new CI Attempt
|
||||
|
||||
LIGHT_FIELDS:
|
||||
'cipeStatus,cipeUrl,branch,commitSha,selfHealingStatus,verificationStatus,userAction,failedTaskIds,verifiedTaskIds,selfHealingEnabled,failureClassification,couldAutoApplyTasks,shortLink,confidence,confidenceReasoning'
|
||||
# Status fields for determining actionable state
|
||||
|
||||
HEAVY_FIELDS:
|
||||
'taskOutputSummary,suggestedFix,suggestedFixReasoning,suggestedFixDescription'
|
||||
# Large content fields - fetch only when returning to main agent
|
||||
```
|
||||
|
||||
## Initial Wait
|
||||
|
||||
Before first poll, wait based on context:
|
||||
|
||||
- **Fresh start (no expected CIPE):** Wait 60 seconds to allow CI to start
|
||||
- **Expecting new CIPE:** Wait 30 seconds (action already triggered)
|
||||
|
||||
**IMPORTANT:** Always run sleep in foreground, NOT as background command.
|
||||
|
||||
```bash
|
||||
sleep 60 # or 30 if expecting new CIPE (FOREGROUND, not background)
|
||||
```
|
||||
|
||||
## Two-Phase Operation
|
||||
|
||||
The subagent operates in one of two modes depending on input:
|
||||
|
||||
### Mode 1: Fresh Start (no `expectedCommitSha` or `previousCipeUrl`)
|
||||
|
||||
Normal polling - process whatever CIPE is returned by `ci_information`.
|
||||
|
||||
### Mode 2: Wait-for-New-CIPE (when `expectedCommitSha` or `previousCipeUrl` provided)
|
||||
|
||||
**CRITICAL**: When expecting a new CIPE, the subagent must **completely ignore** the old/stale CIPE. Do NOT process its status, do NOT return actionable states based on it.
|
||||
|
||||
#### Phase A: Wait Mode
|
||||
|
||||
1. Start a **new-CIPE timeout** timer (default: 30 minutes)
|
||||
2. On each poll of `ci_information`:
|
||||
- Check if CIPE is NEW:
|
||||
- `cipeUrl` differs from `previousCipeUrl` → **new CIPE detected**
|
||||
- `commitSha` matches `expectedCommitSha` → **correct CIPE detected**
|
||||
- If still OLD CIPE: **ignore all status fields**, just wait and poll again
|
||||
- Do NOT return `fix_available`, `ci_success`, etc. based on old CIPE!
|
||||
3. Output wait status (see below)
|
||||
4. If timeout (30 min) reached → return `no_new_cipe`
|
||||
|
||||
#### Phase B: Normal Polling (after new CIPE detected)
|
||||
|
||||
Once new CIPE is detected:
|
||||
|
||||
1. Clear the new-CIPE timeout
|
||||
2. Switch to normal polling mode
|
||||
3. Process the NEW CIPE's status normally
|
||||
4. Return when actionable state reached
|
||||
|
||||
### Wait Mode Output
|
||||
|
||||
While in wait mode, output clearly that you're waiting (not processing):
|
||||
|
||||
```
|
||||
[CI Monitor] ═══════════════════════════════════════════════════════
|
||||
[CI Monitor] WAIT MODE - Expecting new CI Attempt
|
||||
[CI Monitor] Expected SHA: <expectedCommitSha>
|
||||
[CI Monitor] Previous CI Attempt: <previousCipeUrl>
|
||||
[CI Monitor] ═══════════════════════════════════════════════════════
|
||||
|
||||
[CI Monitor] Polling... (elapsed: 0m 30s)
|
||||
[CI Monitor] Still seeing previous CI Attempt (ignoring): <oldCipeUrl>
|
||||
|
||||
[CI Monitor] Polling... (elapsed: 1m 30s)
|
||||
[CI Monitor] Still seeing previous CI Attempt (ignoring): <oldCipeUrl>
|
||||
|
||||
[CI Monitor] Polling... (elapsed: 2m 30s)
|
||||
[CI Monitor] ✓ New CI Attempt detected! URL: <newCipeUrl>, SHA: <newCommitSha>
|
||||
[CI Monitor] Switching to normal polling mode...
|
||||
```
|
||||
|
||||
### Why This Matters (Context Preservation)
|
||||
|
||||
**The problem**: Stale CIPE data can be very large:
|
||||
|
||||
- `taskOutputSummary`: potentially thousands of characters of build/test output
|
||||
- `suggestedFix`: entire patch files
|
||||
- `suggestedFixReasoning`: detailed explanation
|
||||
|
||||
If subagent returns stale CIPE data to main agent, it **pollutes main agent's context** with useless information (we already processed that CIPE). This wastes valuable context window.
|
||||
|
||||
**Without wait mode:**
|
||||
|
||||
1. Poll `ci_information` → get old CIPE with huge data
|
||||
2. Return to main agent with all that stale data
|
||||
3. Main agent's context gets polluted with useless info
|
||||
4. Main agent has to process/ignore it anyway
|
||||
|
||||
**With wait mode:**
|
||||
|
||||
1. Poll `ci_information` → get old CIPE → **ignore it, don't return**
|
||||
2. Keep waiting internally (stale data stays in subagent)
|
||||
3. New CIPE appears → switch to normal mode
|
||||
4. Return to main agent with only the NEW, relevant CIPE data
|
||||
|
||||
## Polling Loop
|
||||
|
||||
### Subagent State Management
|
||||
|
||||
Maintain internal accumulated state across polls:
|
||||
|
||||
```
|
||||
accumulated_state = {}
|
||||
```
|
||||
|
||||
### Call `ci_information` MCP Tool
|
||||
|
||||
**Wait Mode (expecting new CI Attempt):**
|
||||
|
||||
```
|
||||
ci_information({
|
||||
branch: "<branch_name>",
|
||||
select: "cipeUrl,commitSha,cipeStatus"
|
||||
})
|
||||
```
|
||||
|
||||
Only fetch minimal fields needed to detect CI Attempt change. Do NOT fetch heavy fields - stale data wastes context.
|
||||
|
||||
**Normal Mode (processing CI Attempt):**
|
||||
|
||||
```
|
||||
ci_information({
|
||||
branch: "<branch_name>",
|
||||
select: "cipeStatus,cipeUrl,branch,commitSha,selfHealingStatus,verificationStatus,userAction,failedTaskIds,verifiedTaskIds,selfHealingEnabled,failureClassification,couldAutoApplyTasks,shortLink,confidence,confidenceReasoning"
|
||||
})
|
||||
```
|
||||
|
||||
Merge response into `accumulated_state` after each poll.
|
||||
|
||||
### Analyze Response
|
||||
|
||||
**If in Wait Mode** (expecting new CIPE):
|
||||
|
||||
1. Check if CIPE is new (see Two-Phase Operation above)
|
||||
2. If old CIPE → **ignore status**, output wait message, poll again
|
||||
3. If new CIPE → switch to normal mode, continue below
|
||||
|
||||
**If in Normal Mode**:
|
||||
Based on the response, decide whether to **keep polling** or **return to main agent**.
|
||||
|
||||
### Keep Polling When
|
||||
|
||||
Continue polling (with backoff) if ANY of these conditions are true:
|
||||
|
||||
| Condition | Reason |
|
||||
| --------------------------------------- | ---------------------------------------- |
|
||||
| `cipeStatus == 'IN_PROGRESS'` | CI still running |
|
||||
| `cipeStatus == 'NOT_STARTED'` | CI hasn't started yet |
|
||||
| `selfHealingStatus == 'IN_PROGRESS'` | Self-healing agent working |
|
||||
| `selfHealingStatus == 'NOT_STARTED'` | Self-healing not started yet |
|
||||
| `failureClassification == 'FLAKY_TASK'` | Auto-rerun in progress |
|
||||
| `userAction == 'APPLIED_AUTOMATICALLY'` | New CI Attempt spawning after auto-apply |
|
||||
|
||||
When `couldAutoApplyTasks == true`:
|
||||
|
||||
- `verificationStatus` = `NOT_STARTED`, `IN_PROGRESS` → keep polling (verification still in progress)
|
||||
- `verificationStatus` = `COMPLETED` → return `fix_auto_applying` (auto-apply will happen, main agent spawns wait mode subagent)
|
||||
- `verificationStatus` = `FAILED`, `NOT_EXECUTABLE` → return `fix_available` (auto-apply won't happen, needs manual action)
|
||||
|
||||
### Exponential Backoff
|
||||
|
||||
Between polls, wait with exponential backoff:
|
||||
|
||||
| Poll Attempt | Wait Time |
|
||||
| ------------ | ----------------- |
|
||||
| 1st | 60 seconds |
|
||||
| 2nd | 90 seconds |
|
||||
| 3rd+ | 120 seconds (cap) |
|
||||
|
||||
Reset to 60 seconds when state changes significantly.
|
||||
|
||||
**IMPORTANT:** Run sleep in foreground (NOT as background command). Background sleep causes "What should Claude do?" prompts when completed.
|
||||
|
||||
```bash
|
||||
# Example backoff - run in FOREGROUND
|
||||
sleep 60 # First wait
|
||||
sleep 90 # Second wait
|
||||
sleep 120 # Third and subsequent waits (capped)
|
||||
```
|
||||
|
||||
### Fetch Heavy Fields on Actionable State
|
||||
|
||||
Before returning to main agent, fetch heavy fields if the status requires them:
|
||||
|
||||
| Status | Heavy Fields Needed |
|
||||
| ------------------- | ------------------------------------------------------------------------------ |
|
||||
| `ci_success` | None |
|
||||
| `fix_auto_applying` | None |
|
||||
| `fix_available` | `taskOutputSummary,suggestedFix,suggestedFixReasoning,suggestedFixDescription` |
|
||||
| `fix_failed` | `taskOutputSummary` |
|
||||
| `no_fix` | `taskOutputSummary` |
|
||||
| `environment_issue` | None |
|
||||
| `no_new_cipe` | None |
|
||||
| `polling_timeout` | None |
|
||||
| `cipe_canceled` | None |
|
||||
| `cipe_timed_out` | None |
|
||||
|
||||
```
|
||||
# Example: fetching heavy fields for fix_available
|
||||
ci_information({
|
||||
branch: "<branch_name>",
|
||||
select: "taskOutputSummary,suggestedFix,suggestedFixReasoning,suggestedFixDescription"
|
||||
})
|
||||
```
|
||||
|
||||
Merge response into `accumulated_state`, then return merged state to main agent.
|
||||
|
||||
**Pagination:** Heavy string fields return first page only. If `hasMore` indicated, include in return format so main agent knows more content available.
|
||||
|
||||
### Return to Main Agent When
|
||||
|
||||
Return immediately with structured state if ANY of these conditions are true:
|
||||
|
||||
| Status | Condition |
|
||||
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci_success` | `cipeStatus == 'SUCCEEDED'` |
|
||||
| `fix_auto_applying` | `selfHealingStatus == 'COMPLETED'` AND `couldAutoApplyTasks == true` AND `verificationStatus == 'COMPLETED'` |
|
||||
| `fix_available` | `selfHealingStatus == 'COMPLETED'` AND `suggestedFix != null` AND (`couldAutoApplyTasks != true` OR `verificationStatus` in (`FAILED`, `NOT_EXECUTABLE`)) |
|
||||
| `fix_failed` | `selfHealingStatus == 'FAILED'` |
|
||||
| `environment_issue` | `failureClassification == 'ENVIRONMENT_STATE'` |
|
||||
| `no_fix` | `cipeStatus == 'FAILED'` AND (`selfHealingEnabled == false` OR `selfHealingStatus == 'NOT_EXECUTABLE'`) |
|
||||
| `no_new_cipe` | `expectedCommitSha` or `previousCipeUrl` provided, but no new CI Attempt detected after 30 min |
|
||||
| `polling_timeout` | Subagent has been polling for > configured timeout (default 60 min) |
|
||||
| `cipe_canceled` | `cipeStatus == 'CANCELED'` |
|
||||
| `cipe_timed_out` | `cipeStatus == 'TIMED_OUT'` |
|
||||
|
||||
## Subagent Timeout
|
||||
|
||||
Track elapsed time. If you have been polling for more than **60 minutes** (configurable via main agent), return with `status: polling_timeout`.
|
||||
|
||||
## Return Format
|
||||
|
||||
When returning to the main agent, provide a structured response with accumulated state:
|
||||
|
||||
```
|
||||
## CI Monitor Result
|
||||
|
||||
**Status:** <status>
|
||||
**Iterations:** <count>
|
||||
**Elapsed:** <minutes>m <seconds>s
|
||||
|
||||
### CI Attempt Details
|
||||
- **Status:** <cipeStatus>
|
||||
- **URL:** <cipeUrl>
|
||||
- **Branch:** <branch>
|
||||
- **Commit:** <commitSha>
|
||||
- **Failed Tasks:** <failedTaskIds>
|
||||
- **Verified Tasks:** <verifiedTaskIds>
|
||||
|
||||
### Self-Healing Details
|
||||
- **Enabled:** <selfHealingEnabled>
|
||||
- **Status:** <selfHealingStatus>
|
||||
- **Verification:** <verificationStatus>
|
||||
- **User Action:** <userAction>
|
||||
- **Classification:** <failureClassification>
|
||||
- **Confidence:** <confidence>
|
||||
- **Confidence Reasoning:** <confidenceReasoning>
|
||||
|
||||
### Fix Information (if available)
|
||||
- **Short Link:** <shortLink>
|
||||
- **Description:** <suggestedFixDescription>
|
||||
- **Reasoning:** <suggestedFixReasoning>
|
||||
|
||||
### Task Output Summary (first page)
|
||||
<taskOutputSummary>
|
||||
[MORE_CONTENT_AVAILABLE: taskOutputSummary, pageToken: 1]
|
||||
|
||||
### Suggested Fix (first page)
|
||||
<suggestedFix>
|
||||
[MORE_CONTENT_AVAILABLE: suggestedFix, pageToken: 1]
|
||||
```
|
||||
|
||||
### Pagination Indicators
|
||||
|
||||
When a heavy field has more content available, append indicator:
|
||||
|
||||
```
|
||||
[MORE_CONTENT_AVAILABLE: <fieldName>, pageToken: <nextPage>]
|
||||
```
|
||||
|
||||
Main agent can fetch additional pages if needed using:
|
||||
|
||||
```
|
||||
ci_information({ select: "<fieldName>", pageToken: <nextPage> })
|
||||
```
|
||||
|
||||
Fields that may have pagination:
|
||||
|
||||
- `taskOutputSummary` (reverse pagination - page 0 = most recent)
|
||||
- `suggestedFix` (forward pagination - page 0 = start)
|
||||
- `suggestedFixReasoning`
|
||||
|
||||
### Return Format for `no_new_cipe`
|
||||
|
||||
When returning with `status: no_new_cipe`, include additional context:
|
||||
|
||||
```
|
||||
## CI Monitor Result
|
||||
|
||||
**Status:** no_new_cipe
|
||||
**Iterations:** <count>
|
||||
**Elapsed:** <minutes>m <seconds>s
|
||||
|
||||
### Expected CI Attempt Not Found
|
||||
- **Expected Commit SHA:** <expectedCommitSha>
|
||||
- **Previous CI Attempt URL:** <previousCipeUrl>
|
||||
- **Last Seen CI Attempt URL:** <cipeUrl>
|
||||
- **Last Seen Commit SHA:** <commitSha>
|
||||
- **New CI Attempt Timeout:** 30 minutes (exceeded)
|
||||
|
||||
### Likely Cause
|
||||
CI workflow failed before Nx tasks could run (e.g., install step, checkout, auth).
|
||||
Check your CI provider logs for the commit <expectedCommitSha>.
|
||||
|
||||
### Last Known CI Attempt State
|
||||
- **Status:** <cipeStatus>
|
||||
- **Branch:** <branch>
|
||||
```
|
||||
|
||||
## Status Reporting (Verbosity-Controlled)
|
||||
|
||||
Output is controlled by the `verbosity` parameter from the main agent:
|
||||
|
||||
| Level | What to Output |
|
||||
| --------- | ----------------------------------------------------------------- |
|
||||
| `minimal` | No intermediate output. Only return final result when actionable. |
|
||||
| `medium` | Output only on significant state changes (not every poll). |
|
||||
| `verbose` | Output detailed phase information after every poll. |
|
||||
|
||||
### Minimal Verbosity
|
||||
|
||||
No output during polling. Poll silently and return when done.
|
||||
|
||||
### Medium Verbosity (Default)
|
||||
|
||||
Output **only when state changes significantly** to save context tokens:
|
||||
|
||||
- `cipeStatus` changes (e.g., IN_PROGRESS → FAILED)
|
||||
- `selfHealingStatus` changes (e.g., IN_PROGRESS → COMPLETED)
|
||||
- New CI Attempt detected (in wait mode)
|
||||
|
||||
Format: single line, no decorators:
|
||||
|
||||
```
|
||||
[CI Monitor] CI: FAILED | Self-Healing: IN_PROGRESS | Elapsed: 4m
|
||||
```
|
||||
|
||||
### Verbose Verbosity
|
||||
|
||||
Output detailed phase box after every poll:
|
||||
|
||||
```
|
||||
[CI Monitor] ─────────────────────────────────────────────────────
|
||||
[CI Monitor] Iteration <N> | Elapsed: <X>m <Y>s
|
||||
[CI Monitor]
|
||||
[CI Monitor] CI Status: <cipeStatus>
|
||||
[CI Monitor] Self-Healing: <selfHealingStatus>
|
||||
[CI Monitor] Verification: <verificationStatus>
|
||||
[CI Monitor] Classification: <failureClassification>
|
||||
[CI Monitor]
|
||||
[CI Monitor] → <human-readable phase description>
|
||||
[CI Monitor] ─────────────────────────────────────────────────────
|
||||
```
|
||||
|
||||
### Phase Descriptions (for verbose output)
|
||||
|
||||
| Status Combo | Description |
|
||||
| ----------------------------------------------------------------------------------------- | ------------------------------------------- |
|
||||
| `cipeStatus: IN_PROGRESS` | "CI running..." |
|
||||
| `cipeStatus: NOT_STARTED` | "Waiting for CI to start..." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: NOT_STARTED` | "CI failed. Self-healing starting..." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: IN_PROGRESS` | "CI failed. Self-healing generating fix..." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: COMPLETED` + `verificationStatus: IN_PROGRESS` | "Fix generated! Verification running..." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: COMPLETED` + `verificationStatus: COMPLETED` | "Fix ready! Verified successfully." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: COMPLETED` + `verificationStatus: FAILED` | "Fix generated but verification failed." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: FAILED` | "Self-healing could not generate a fix." |
|
||||
| `cipeStatus: SUCCEEDED` | "CI passed!" |
|
||||
|
||||
## Important Notes
|
||||
|
||||
- You do NOT make apply/reject decisions - that's the main agent's job
|
||||
- You do NOT perform git operations
|
||||
- You only poll and report state
|
||||
- Respect the `verbosity` parameter for output (default: medium)
|
||||
- If `ci_information` returns an error, wait and retry (count as failed poll)
|
||||
- Track consecutive failures - if 5 consecutive failures, return with `status: error`
|
||||
- When expecting new CI Attempt, track the 30-minute new-CI-Attempt timeout separately from the main polling timeout
|
||||
@@ -0,0 +1,18 @@
|
||||
# This configuration is here to prevent false positive alerts for __fixtures__.
|
||||
# We are intentionally disabling the PR opening feature.
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: 'npm'
|
||||
directory: '/'
|
||||
schedule:
|
||||
interval: 'weekly'
|
||||
open-pull-requests-limit: 0
|
||||
exclude-paths:
|
||||
- '**/__fixtures__/**'
|
||||
|
||||
- package-ecosystem: 'github-actions'
|
||||
directory: '/'
|
||||
schedule:
|
||||
interval: 'weekly'
|
||||
open-pull-requests-limit: 0
|
||||
@@ -0,0 +1,437 @@
|
||||
---
|
||||
description: Monitor Nx Cloud CI pipeline and handle self-healing fixes automatically. Checks for Nx Cloud connection before starting.
|
||||
argument-hint: '[instructions] [--max-cycles N] [--timeout MINUTES] [--verbosity minimal|medium|verbose] [--branch BRANCH] [--fresh] [--auto-fix-workflow] [--new-cipe-timeout MINUTES]'
|
||||
---
|
||||
|
||||
# CI Monitor Command
|
||||
|
||||
You are the orchestrator for monitoring Nx Cloud CI pipeline executions and handling self-healing fixes. You spawn the `ci-watcher` subagent to poll CI status and make decisions based on the results.
|
||||
|
||||
## Context
|
||||
|
||||
- **Current Branch:** !`git branch --show-current`
|
||||
- **Current Commit:** !`git rev-parse --short HEAD`
|
||||
- **Remote Status:** !`git status -sb | head -1`
|
||||
|
||||
## User Instructions
|
||||
|
||||
${input:args}
|
||||
|
||||
**Important:** If user provides specific instructions, respect them over default behaviors described below.
|
||||
|
||||
## Configuration Defaults
|
||||
|
||||
| Setting | Default | Description |
|
||||
| ------------------------- | ------------- | ------------------------------------------------------------------- |
|
||||
| `--max-cycles` | 10 | Maximum CIPE cycles before timeout |
|
||||
| `--timeout` | 120 | Maximum duration in minutes |
|
||||
| `--verbosity` | medium | Output level: minimal, medium, verbose |
|
||||
| `--branch` | (auto-detect) | Branch to monitor |
|
||||
| `--subagent-timeout` | 60 | Subagent polling timeout in minutes |
|
||||
| `--fresh` | false | Ignore previous context, start fresh |
|
||||
| `--auto-fix-workflow` | false | Attempt common fixes for pre-CIPE failures (e.g., lockfile updates) |
|
||||
| `--new-cipe-timeout` | 10 | Minutes to wait for new CIPE after action |
|
||||
| `--local-verify-attempts` | 3 | Max local verification + enhance cycles before pushing to CI |
|
||||
|
||||
Parse any overrides from `${input:args}` and merge with defaults.
|
||||
|
||||
## Nx Cloud Connection Check
|
||||
|
||||
**CRITICAL**: Before starting the monitoring loop, verify the workspace is connected to Nx Cloud.
|
||||
|
||||
### Step 0: Verify Nx Cloud Connection
|
||||
|
||||
1. **Check `nx.json`** at workspace root for `nxCloudId` or `nxCloudAccessToken`
|
||||
2. **If `nx.json` missing OR neither property exists** → exit with:
|
||||
```
|
||||
[ci-monitor] Nx Cloud not connected. Unlock 70% faster CI and auto-fix broken PRs with https://nx.dev/nx-cloud
|
||||
```
|
||||
3. **If connected** → continue to main loop
|
||||
|
||||
## Session Context Behavior
|
||||
|
||||
**Important:** Within a Claude Code session, conversation context persists. If you Ctrl+C to interrupt the monitor and re-run `/ci-monitor`, Claude remembers the previous state and may continue from where it left off.
|
||||
|
||||
- **To continue monitoring:** Just re-run `/ci-monitor` (context is preserved)
|
||||
- **To start fresh:** Use `/ci-monitor --fresh` to ignore previous context
|
||||
- **For a completely clean slate:** Exit Claude Code and restart `claude`
|
||||
|
||||
## Default Behaviors by Status
|
||||
|
||||
The subagent returns with one of the following statuses. This table defines the **default behavior** for each status. User instructions can override any of these.
|
||||
|
||||
| Status | Default Behavior |
|
||||
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci_success` | Exit with success. Log "CI passed successfully!" |
|
||||
| `fix_auto_applying` | Fix will be auto-applied by self-healing. Do NOT call MCP. Record `last_cipe_url`, spawn new subagent in wait mode to poll for new CIPE. |
|
||||
| `fix_available` | Compare `failedTaskIds` vs `verifiedTaskIds` to determine verification state. See **Fix Available Decision Logic** section below. |
|
||||
| `fix_failed` | Self-healing failed to generate fix. Attempt local fix based on `taskOutputSummary`. If successful → commit, push, loop. If not → exit with failure. |
|
||||
| `environment_issue` | Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`. New CIPE spawns automatically. Loop to poll for new CIPE. |
|
||||
| `no_fix` | CI failed, no fix available (self-healing disabled or not executable). Attempt local fix if possible. Otherwise exit with failure. |
|
||||
| `no_new_cipe` | Expected CIPE never spawned (CI workflow likely failed before Nx tasks). Report to user, attempt common fixes if configured, or exit with guidance. |
|
||||
| `polling_timeout` | Subagent polling timeout reached. Exit with timeout. |
|
||||
| `cipe_canceled` | CIPE was canceled. Exit with canceled status. |
|
||||
| `cipe_timed_out` | CIPE timed out. Exit with timeout status. |
|
||||
| `error` | Increment `no_progress_count`. If >= 3 → exit with circuit breaker. Otherwise wait 60s and loop. |
|
||||
|
||||
### Fix Available Decision Logic
|
||||
|
||||
When subagent returns `fix_available`, main agent compares `failedTaskIds` vs `verifiedTaskIds`:
|
||||
|
||||
#### Step 1: Categorize Tasks
|
||||
|
||||
1. **Verified tasks** = tasks in both `failedTaskIds` AND `verifiedTaskIds`
|
||||
2. **Unverified tasks** = tasks in `failedTaskIds` but NOT in `verifiedTaskIds`
|
||||
3. **E2E tasks** = unverified tasks where target contains "e2e" (task format: `<project>:<target>` or `<project>:<target>:<config>`)
|
||||
4. **Verifiable tasks** = unverified tasks that are NOT e2e
|
||||
|
||||
#### Step 2: Determine Path
|
||||
|
||||
| Condition | Path |
|
||||
| --------------------------------------- | ---------------------------------------- |
|
||||
| No unverified tasks (all verified) | Apply via MCP |
|
||||
| Unverified tasks exist, but ALL are e2e | Apply via MCP (treat as verified enough) |
|
||||
| Verifiable tasks exist | Local verification flow |
|
||||
|
||||
#### Step 3a: Apply via MCP (fully/e2e-only verified)
|
||||
|
||||
- Call `update_self_healing_fix({ shortLink, action: "APPLY" })`
|
||||
- Record `last_cipe_url`, spawn subagent in wait mode
|
||||
|
||||
#### Step 3b: Local Verification Flow
|
||||
|
||||
When verifiable (non-e2e) unverified tasks exist:
|
||||
|
||||
1. **Detect package manager:**
|
||||
- `pnpm-lock.yaml` exists → `pnpm nx`
|
||||
- `yarn.lock` exists → `yarn nx`
|
||||
- Otherwise → `npx nx`
|
||||
|
||||
2. **Run verifiable tasks in parallel:**
|
||||
- Spawn `general` subagents to run each task concurrently
|
||||
- Each subagent runs: `<pm> nx run <taskId>`
|
||||
- Collect pass/fail results from all subagents
|
||||
|
||||
3. **Evaluate results:**
|
||||
|
||||
| Result | Action |
|
||||
| ------------------------- | ---------------------------- |
|
||||
| ALL verifiable tasks pass | Apply via MCP |
|
||||
| ANY verifiable task fails | Apply-locally + enhance flow |
|
||||
|
||||
4. **Apply-locally + enhance flow:**
|
||||
- Run `nx apply-locally <shortLink>`
|
||||
- Enhance the code to fix failing tasks
|
||||
- Run failing tasks again to verify fix
|
||||
- If still failing → increment `local_verify_count`, loop back to enhance
|
||||
- If passing → commit and push, record `expected_commit_sha`, spawn subagent in wait mode
|
||||
|
||||
5. **Track attempts** (wraps step 4):
|
||||
- Increment `local_verify_count` after each enhance cycle
|
||||
- If `local_verify_count >= local_verify_attempts` (default: 3):
|
||||
- Get code in commit-able state
|
||||
- Commit and push with message indicating local verification failed
|
||||
- Report to user:
|
||||
```
|
||||
[ci-monitor] Local verification failed after <N> attempts. Pushed to CI for final validation. Failed: <taskIds>
|
||||
```
|
||||
- Record `expected_commit_sha`, spawn subagent in wait mode (let CI be final judge)
|
||||
|
||||
#### Commit Message Format
|
||||
|
||||
```bash
|
||||
git commit -m "fix(<projects>): <brief description>
|
||||
|
||||
Failed tasks: <taskId1>, <taskId2>
|
||||
Local verification: passed|enhanced|failed-pushing-to-ci"
|
||||
```
|
||||
|
||||
### Unverified Fix Flow (No Verification Attempted)
|
||||
|
||||
When `verificationStatus` is `FAILED`, `NOT_EXECUTABLE`, or fix has `couldAutoApplyTasks != true` with no verification:
|
||||
|
||||
- Analyze fix content (`suggestedFix`, `suggestedFixReasoning`, `taskOutputSummary`)
|
||||
- If fix looks correct → apply via MCP
|
||||
- If fix needs enhancement → use Apply Locally + Enhance Flow above
|
||||
- If fix is wrong → reject via MCP, fix from scratch, commit, push
|
||||
|
||||
### Auto-Apply Eligibility
|
||||
|
||||
The `couldAutoApplyTasks` field indicates whether the fix is eligible for automatic application:
|
||||
|
||||
- **`true`**: Fix is eligible for auto-apply. Subagent keeps polling while verification is in progress. Returns `fix_auto_applying` when verified, or `fix_available` if verification fails.
|
||||
- **`false`** or **`null`**: Fix requires manual action (apply via MCP, apply locally, or reject)
|
||||
|
||||
**Key point**: When subagent returns `fix_auto_applying`, do NOT call MCP to apply - self-healing handles it. Just spawn a new subagent in wait mode.
|
||||
|
||||
### Apply vs Reject vs Apply Locally
|
||||
|
||||
- **Apply via MCP**: Calls `update_self_healing_fix({ shortLink, action: "APPLY" })`. Self-healing agent applies the fix in CI and a new CIPE spawns automatically. No local git operations needed.
|
||||
- **Apply Locally**: Runs `nx apply-locally <shortLink>`. Applies the patch to your local working directory and sets state to `APPLIED_LOCALLY`. Use this when you want to enhance the fix before pushing.
|
||||
- **Reject via MCP**: Calls `update_self_healing_fix({ shortLink, action: "REJECT" })`. Marks fix as rejected. Use only when the fix is completely wrong and you'll fix from scratch.
|
||||
|
||||
### Apply Locally + Enhance Flow
|
||||
|
||||
When the fix needs enhancement (use `nx apply-locally`, NOT reject):
|
||||
|
||||
1. Apply the patch locally: `nx apply-locally <shortLink>` (this also updates state to `APPLIED_LOCALLY`)
|
||||
2. Make additional changes as needed
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Reject + Fix From Scratch Flow
|
||||
|
||||
When the fix is completely wrong:
|
||||
|
||||
1. Call MCP to reject: `update_self_healing_fix({ shortLink, action: "REJECT" })`
|
||||
2. Fix the issue from scratch locally
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Environment Issue Handling
|
||||
|
||||
When `failureClassification == 'ENVIRONMENT_STATE'`:
|
||||
|
||||
1. Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`
|
||||
2. New CIPE spawns automatically (no local git operations needed)
|
||||
3. Loop to poll for new CIPE with `previousCipeUrl` set
|
||||
|
||||
### No-New-CIPE Handling
|
||||
|
||||
When `status == 'no_new_cipe'`:
|
||||
|
||||
This means the expected CIPE was never created - CI likely failed before Nx tasks could run.
|
||||
|
||||
1. **Report to user:**
|
||||
|
||||
```
|
||||
[ci-monitor] No CI attempt for <sha> after 10 min. Check CI provider for pre-Nx failures (install, checkout, auth). Last CI attempt: <previousCipeUrl>
|
||||
```
|
||||
|
||||
2. **If user configured auto-fix attempts** (e.g., `--auto-fix-workflow`):
|
||||
- Detect package manager: check for `pnpm-lock.yaml`, `yarn.lock`, `package-lock.json`
|
||||
- Run install to update lockfile:
|
||||
```bash
|
||||
pnpm install # or npm install / yarn install
|
||||
```
|
||||
- If lockfile changed:
|
||||
```bash
|
||||
git add pnpm-lock.yaml # or appropriate lockfile
|
||||
git commit -m "chore: update lockfile"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
- Record new commit SHA, loop to poll with `expectedCommitSha`
|
||||
|
||||
3. **Otherwise:** Exit with `no_new_cipe` status, providing guidance for user to investigate
|
||||
|
||||
## Exit Conditions
|
||||
|
||||
Exit the monitoring loop when ANY of these conditions are met:
|
||||
|
||||
| Condition | Exit Type |
|
||||
| ------------------------------------------- | ---------------- |
|
||||
| CI passes (`cipeStatus == 'SUCCEEDED'`) | Success |
|
||||
| Max CIPE cycles reached | Timeout |
|
||||
| Max duration reached | Timeout |
|
||||
| 3 consecutive no-progress iterations | Circuit breaker |
|
||||
| No fix available and local fix not possible | Failure |
|
||||
| No new CIPE and auto-fix not configured | Pre-CIPE failure |
|
||||
| User cancels | Cancelled |
|
||||
|
||||
## Main Loop
|
||||
|
||||
### Step 1: Initialize Tracking
|
||||
|
||||
```
|
||||
cycle_count = 0
|
||||
start_time = now()
|
||||
no_progress_count = 0
|
||||
local_verify_count = 0
|
||||
last_state = null
|
||||
last_cipe_url = null
|
||||
expected_commit_sha = null
|
||||
```
|
||||
|
||||
### Step 2: Spawn Subagent
|
||||
|
||||
Spawn the `ci-watcher` subagent to poll CI status:
|
||||
|
||||
**Fresh start (first spawn, no expected CIPE):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>."
|
||||
)
|
||||
```
|
||||
|
||||
**After action that triggers new CIPE (wait mode):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>.
|
||||
|
||||
WAIT MODE: A new CIPE should spawn. Ignore old CIPE until new one appears.
|
||||
Expected commit SHA: <expected_commit_sha>
|
||||
Previous CIPE URL: <last_cipe_url>"
|
||||
)
|
||||
```
|
||||
|
||||
### Step 3: Handle Subagent Response
|
||||
|
||||
When subagent returns:
|
||||
|
||||
1. Check the returned status
|
||||
2. Look up default behavior in the table above
|
||||
3. Check if user instructions override the default
|
||||
4. Execute the appropriate action
|
||||
5. **If action expects new CIPE**, update tracking (see Step 3a)
|
||||
6. If action results in looping, go to Step 2
|
||||
|
||||
### Step 3a: Track State for New-CIPE Detection
|
||||
|
||||
After actions that should trigger a new CIPE, record state before looping:
|
||||
|
||||
| Action | What to Track | Subagent Mode |
|
||||
| ----------------------------- | --------------------------------------------- | ------------- |
|
||||
| Fix auto-applying | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply via MCP | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply locally + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Reject + fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Fix failed + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| No fix + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Environment rerun | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| No-new-CIPE + auto-fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
|
||||
**CRITICAL**: When passing `expectedCommitSha` or `last_cipe_url` to the subagent, it enters **wait mode**:
|
||||
|
||||
- Subagent will **completely ignore** the old/stale CIPE
|
||||
- Subagent will only wait for new CIPE to appear
|
||||
- Subagent will NOT return to main agent with stale CIPE data
|
||||
- Once new CIPE detected, subagent switches to normal polling
|
||||
|
||||
**Why wait mode matters for context preservation**: Stale CIPE data can be very large (task output summaries, suggested fix patches, reasoning). If subagent returns this to main agent, it pollutes main agent's context with useless data since we already processed that CIPE. Wait mode keeps stale data in the subagent, never sending it to main agent.
|
||||
|
||||
### Step 4: Progress Tracking
|
||||
|
||||
After each action:
|
||||
|
||||
- If state changed significantly → reset `no_progress_count = 0`
|
||||
- If state unchanged → `no_progress_count++`
|
||||
- On new CI attempt detected → reset `local_verify_count = 0`
|
||||
|
||||
## Status Reporting
|
||||
|
||||
Based on verbosity level:
|
||||
|
||||
| Level | What to Report |
|
||||
| --------- | -------------------------------------------------------------------------- |
|
||||
| `minimal` | Only final result (success/failure/timeout) |
|
||||
| `medium` | State changes + periodic updates ("Cycle N \| Elapsed: Xm \| Status: ...") |
|
||||
| `verbose` | All of medium + full subagent responses, git outputs, MCP responses |
|
||||
|
||||
## User Instruction Examples
|
||||
|
||||
Users can override default behaviors:
|
||||
|
||||
| Instruction | Effect |
|
||||
| ------------------------------------------------ | --------------------------------------------- |
|
||||
| "never auto-apply" | Always prompt before applying any fix |
|
||||
| "always ask before git push" | Prompt before each push |
|
||||
| "reject any fix for e2e tasks" | Auto-reject if `failedTaskIds` contains e2e |
|
||||
| "apply all fixes regardless of verification" | Skip verification check, apply everything |
|
||||
| "if confidence < 70, reject" | Check confidence field before applying |
|
||||
| "run 'nx affected -t typecheck' before applying" | Add local verification step |
|
||||
| "auto-fix workflow failures" | Attempt lockfile updates on pre-CIPE failures |
|
||||
| "wait 45 min for new CIPE" | Override new-CIPE timeout (default: 10 min) |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Action |
|
||||
| ------------------------ | ------------------------------------------------------------------------------------- |
|
||||
| Git rebase conflict | Report to user, exit |
|
||||
| `nx apply-locally` fails | Report to user, attempt manual patch or exit |
|
||||
| MCP tool error | Retry once, if fails report to user |
|
||||
| Subagent spawn failure | Retry once, if fails exit with error |
|
||||
| No new CIPE detected | If `--auto-fix-workflow`, try lockfile update; otherwise report to user with guidance |
|
||||
| Lockfile auto-fix fails | Report to user, exit with guidance to check CI logs |
|
||||
|
||||
## Example Session
|
||||
|
||||
### Example 1: Normal Flow with Self-Healing (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-auth'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, verbosity=medium
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: IN_PROGRESS | Self-Healing: NOT_STARTED | Elapsed: 1m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: IN_PROGRESS | Elapsed: 3m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 5m
|
||||
|
||||
[ci-monitor] Fix available! Verification: COMPLETED
|
||||
[ci-monitor] Applying fix via MCP...
|
||||
[ci-monitor] Fix applied in CI. Waiting for new CI attempt...
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 8m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 2
|
||||
- Total time: 12m 34s
|
||||
- Fixes applied: 1
|
||||
- Result: SUCCESS
|
||||
```
|
||||
|
||||
### Example 2: Pre-CI Failure (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-products'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, auto-fix-workflow=true
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 2m
|
||||
|
||||
[ci-monitor] Applying fix locally, enhancing, and pushing...
|
||||
[ci-monitor] Committed: abc1234
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] Waiting for new CI attempt... (expected SHA: abc1234)
|
||||
[CI Monitor] ⚠️ CI attempt timeout (10 min). Returning no_new_cipe.
|
||||
|
||||
[ci-monitor] Status: no_new_cipe
|
||||
[ci-monitor] --auto-fix-workflow enabled. Attempting lockfile update...
|
||||
[ci-monitor] Lockfile updated. Committed: def5678
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 18m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 3
|
||||
- Total time: 22m 15s
|
||||
- Fixes applied: 1 (self-healing) + 1 (lockfile)
|
||||
- Result: SUCCESS
|
||||
```
|
||||
@@ -0,0 +1,437 @@
|
||||
---
|
||||
name: ci-monitor
|
||||
description: Monitor Nx Cloud CI pipeline and handle self-healing fixes automatically. Checks for Nx Cloud connection before starting.
|
||||
---
|
||||
|
||||
# CI Monitor Command
|
||||
|
||||
You are the orchestrator for monitoring Nx Cloud CI pipeline executions and handling self-healing fixes. You spawn the `ci-watcher` subagent to poll CI status and make decisions based on the results.
|
||||
|
||||
## Context
|
||||
|
||||
- **Current Branch:** !`git branch --show-current`
|
||||
- **Current Commit:** !`git rev-parse --short HEAD`
|
||||
- **Remote Status:** !`git status -sb | head -1`
|
||||
|
||||
## User Instructions
|
||||
|
||||
$ARGUMENTS
|
||||
|
||||
**Important:** If user provides specific instructions, respect them over default behaviors described below.
|
||||
|
||||
## Configuration Defaults
|
||||
|
||||
| Setting | Default | Description |
|
||||
| ------------------------- | ------------- | ------------------------------------------------------------------- |
|
||||
| `--max-cycles` | 10 | Maximum CIPE cycles before timeout |
|
||||
| `--timeout` | 120 | Maximum duration in minutes |
|
||||
| `--verbosity` | medium | Output level: minimal, medium, verbose |
|
||||
| `--branch` | (auto-detect) | Branch to monitor |
|
||||
| `--subagent-timeout` | 60 | Subagent polling timeout in minutes |
|
||||
| `--fresh` | false | Ignore previous context, start fresh |
|
||||
| `--auto-fix-workflow` | false | Attempt common fixes for pre-CIPE failures (e.g., lockfile updates) |
|
||||
| `--new-cipe-timeout` | 10 | Minutes to wait for new CIPE after action |
|
||||
| `--local-verify-attempts` | 3 | Max local verification + enhance cycles before pushing to CI |
|
||||
|
||||
Parse any overrides from `$ARGUMENTS` and merge with defaults.
|
||||
|
||||
## Nx Cloud Connection Check
|
||||
|
||||
**CRITICAL**: Before starting the monitoring loop, verify the workspace is connected to Nx Cloud.
|
||||
|
||||
### Step 0: Verify Nx Cloud Connection
|
||||
|
||||
1. **Check `nx.json`** at workspace root for `nxCloudId` or `nxCloudAccessToken`
|
||||
2. **If `nx.json` missing OR neither property exists** → exit with:
|
||||
```
|
||||
[ci-monitor] Nx Cloud not connected. Unlock 70% faster CI and auto-fix broken PRs with https://nx.dev/nx-cloud
|
||||
```
|
||||
3. **If connected** → continue to main loop
|
||||
|
||||
## Session Context Behavior
|
||||
|
||||
**Important:** Within a Claude Code session, conversation context persists. If you Ctrl+C to interrupt the monitor and re-run `/ci-monitor`, Claude remembers the previous state and may continue from where it left off.
|
||||
|
||||
- **To continue monitoring:** Just re-run `/ci-monitor` (context is preserved)
|
||||
- **To start fresh:** Use `/ci-monitor --fresh` to ignore previous context
|
||||
- **For a completely clean slate:** Exit Claude Code and restart `claude`
|
||||
|
||||
## Default Behaviors by Status
|
||||
|
||||
The subagent returns with one of the following statuses. This table defines the **default behavior** for each status. User instructions can override any of these.
|
||||
|
||||
| Status | Default Behavior |
|
||||
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci_success` | Exit with success. Log "CI passed successfully!" |
|
||||
| `fix_auto_applying` | Fix will be auto-applied by self-healing. Do NOT call MCP. Record `last_cipe_url`, spawn new subagent in wait mode to poll for new CIPE. |
|
||||
| `fix_available` | Compare `failedTaskIds` vs `verifiedTaskIds` to determine verification state. See **Fix Available Decision Logic** section below. |
|
||||
| `fix_failed` | Self-healing failed to generate fix. Attempt local fix based on `taskOutputSummary`. If successful → commit, push, loop. If not → exit with failure. |
|
||||
| `environment_issue` | Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`. New CIPE spawns automatically. Loop to poll for new CIPE. |
|
||||
| `no_fix` | CI failed, no fix available (self-healing disabled or not executable). Attempt local fix if possible. Otherwise exit with failure. |
|
||||
| `no_new_cipe` | Expected CIPE never spawned (CI workflow likely failed before Nx tasks). Report to user, attempt common fixes if configured, or exit with guidance. |
|
||||
| `polling_timeout` | Subagent polling timeout reached. Exit with timeout. |
|
||||
| `cipe_canceled` | CIPE was canceled. Exit with canceled status. |
|
||||
| `cipe_timed_out` | CIPE timed out. Exit with timeout status. |
|
||||
| `error` | Increment `no_progress_count`. If >= 3 → exit with circuit breaker. Otherwise wait 60s and loop. |
|
||||
|
||||
### Fix Available Decision Logic
|
||||
|
||||
When subagent returns `fix_available`, main agent compares `failedTaskIds` vs `verifiedTaskIds`:
|
||||
|
||||
#### Step 1: Categorize Tasks
|
||||
|
||||
1. **Verified tasks** = tasks in both `failedTaskIds` AND `verifiedTaskIds`
|
||||
2. **Unverified tasks** = tasks in `failedTaskIds` but NOT in `verifiedTaskIds`
|
||||
3. **E2E tasks** = unverified tasks where target contains "e2e" (task format: `<project>:<target>` or `<project>:<target>:<config>`)
|
||||
4. **Verifiable tasks** = unverified tasks that are NOT e2e
|
||||
|
||||
#### Step 2: Determine Path
|
||||
|
||||
| Condition | Path |
|
||||
| --------------------------------------- | ---------------------------------------- |
|
||||
| No unverified tasks (all verified) | Apply via MCP |
|
||||
| Unverified tasks exist, but ALL are e2e | Apply via MCP (treat as verified enough) |
|
||||
| Verifiable tasks exist | Local verification flow |
|
||||
|
||||
#### Step 3a: Apply via MCP (fully/e2e-only verified)
|
||||
|
||||
- Call `update_self_healing_fix({ shortLink, action: "APPLY" })`
|
||||
- Record `last_cipe_url`, spawn subagent in wait mode
|
||||
|
||||
#### Step 3b: Local Verification Flow
|
||||
|
||||
When verifiable (non-e2e) unverified tasks exist:
|
||||
|
||||
1. **Detect package manager:**
|
||||
- `pnpm-lock.yaml` exists → `pnpm nx`
|
||||
- `yarn.lock` exists → `yarn nx`
|
||||
- Otherwise → `npx nx`
|
||||
|
||||
2. **Run verifiable tasks in parallel:**
|
||||
- Spawn `general` subagents to run each task concurrently
|
||||
- Each subagent runs: `<pm> nx run <taskId>`
|
||||
- Collect pass/fail results from all subagents
|
||||
|
||||
3. **Evaluate results:**
|
||||
|
||||
| Result | Action |
|
||||
| ------------------------- | ---------------------------- |
|
||||
| ALL verifiable tasks pass | Apply via MCP |
|
||||
| ANY verifiable task fails | Apply-locally + enhance flow |
|
||||
|
||||
4. **Apply-locally + enhance flow:**
|
||||
- Run `nx apply-locally <shortLink>`
|
||||
- Enhance the code to fix failing tasks
|
||||
- Run failing tasks again to verify fix
|
||||
- If still failing → increment `local_verify_count`, loop back to enhance
|
||||
- If passing → commit and push, record `expected_commit_sha`, spawn subagent in wait mode
|
||||
|
||||
5. **Track attempts** (wraps step 4):
|
||||
- Increment `local_verify_count` after each enhance cycle
|
||||
- If `local_verify_count >= local_verify_attempts` (default: 3):
|
||||
- Get code in commit-able state
|
||||
- Commit and push with message indicating local verification failed
|
||||
- Report to user:
|
||||
```
|
||||
[ci-monitor] Local verification failed after <N> attempts. Pushed to CI for final validation. Failed: <taskIds>
|
||||
```
|
||||
- Record `expected_commit_sha`, spawn subagent in wait mode (let CI be final judge)
|
||||
|
||||
#### Commit Message Format
|
||||
|
||||
```bash
|
||||
git commit -m "fix(<projects>): <brief description>
|
||||
|
||||
Failed tasks: <taskId1>, <taskId2>
|
||||
Local verification: passed|enhanced|failed-pushing-to-ci"
|
||||
```
|
||||
|
||||
### Unverified Fix Flow (No Verification Attempted)
|
||||
|
||||
When `verificationStatus` is `FAILED`, `NOT_EXECUTABLE`, or fix has `couldAutoApplyTasks != true` with no verification:
|
||||
|
||||
- Analyze fix content (`suggestedFix`, `suggestedFixReasoning`, `taskOutputSummary`)
|
||||
- If fix looks correct → apply via MCP
|
||||
- If fix needs enhancement → use Apply Locally + Enhance Flow above
|
||||
- If fix is wrong → reject via MCP, fix from scratch, commit, push
|
||||
|
||||
### Auto-Apply Eligibility
|
||||
|
||||
The `couldAutoApplyTasks` field indicates whether the fix is eligible for automatic application:
|
||||
|
||||
- **`true`**: Fix is eligible for auto-apply. Subagent keeps polling while verification is in progress. Returns `fix_auto_applying` when verified, or `fix_available` if verification fails.
|
||||
- **`false`** or **`null`**: Fix requires manual action (apply via MCP, apply locally, or reject)
|
||||
|
||||
**Key point**: When subagent returns `fix_auto_applying`, do NOT call MCP to apply - self-healing handles it. Just spawn a new subagent in wait mode.
|
||||
|
||||
### Apply vs Reject vs Apply Locally
|
||||
|
||||
- **Apply via MCP**: Calls `update_self_healing_fix({ shortLink, action: "APPLY" })`. Self-healing agent applies the fix in CI and a new CIPE spawns automatically. No local git operations needed.
|
||||
- **Apply Locally**: Runs `nx apply-locally <shortLink>`. Applies the patch to your local working directory and sets state to `APPLIED_LOCALLY`. Use this when you want to enhance the fix before pushing.
|
||||
- **Reject via MCP**: Calls `update_self_healing_fix({ shortLink, action: "REJECT" })`. Marks fix as rejected. Use only when the fix is completely wrong and you'll fix from scratch.
|
||||
|
||||
### Apply Locally + Enhance Flow
|
||||
|
||||
When the fix needs enhancement (use `nx apply-locally`, NOT reject):
|
||||
|
||||
1. Apply the patch locally: `nx apply-locally <shortLink>` (this also updates state to `APPLIED_LOCALLY`)
|
||||
2. Make additional changes as needed
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Reject + Fix From Scratch Flow
|
||||
|
||||
When the fix is completely wrong:
|
||||
|
||||
1. Call MCP to reject: `update_self_healing_fix({ shortLink, action: "REJECT" })`
|
||||
2. Fix the issue from scratch locally
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Environment Issue Handling
|
||||
|
||||
When `failureClassification == 'ENVIRONMENT_STATE'`:
|
||||
|
||||
1. Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`
|
||||
2. New CIPE spawns automatically (no local git operations needed)
|
||||
3. Loop to poll for new CIPE with `previousCipeUrl` set
|
||||
|
||||
### No-New-CIPE Handling
|
||||
|
||||
When `status == 'no_new_cipe'`:
|
||||
|
||||
This means the expected CIPE was never created - CI likely failed before Nx tasks could run.
|
||||
|
||||
1. **Report to user:**
|
||||
|
||||
```
|
||||
[ci-monitor] No CI attempt for <sha> after 10 min. Check CI provider for pre-Nx failures (install, checkout, auth). Last CI attempt: <previousCipeUrl>
|
||||
```
|
||||
|
||||
2. **If user configured auto-fix attempts** (e.g., `--auto-fix-workflow`):
|
||||
- Detect package manager: check for `pnpm-lock.yaml`, `yarn.lock`, `package-lock.json`
|
||||
- Run install to update lockfile:
|
||||
```bash
|
||||
pnpm install # or npm install / yarn install
|
||||
```
|
||||
- If lockfile changed:
|
||||
```bash
|
||||
git add pnpm-lock.yaml # or appropriate lockfile
|
||||
git commit -m "chore: update lockfile"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
- Record new commit SHA, loop to poll with `expectedCommitSha`
|
||||
|
||||
3. **Otherwise:** Exit with `no_new_cipe` status, providing guidance for user to investigate
|
||||
|
||||
## Exit Conditions
|
||||
|
||||
Exit the monitoring loop when ANY of these conditions are met:
|
||||
|
||||
| Condition | Exit Type |
|
||||
| ------------------------------------------- | ---------------- |
|
||||
| CI passes (`cipeStatus == 'SUCCEEDED'`) | Success |
|
||||
| Max CIPE cycles reached | Timeout |
|
||||
| Max duration reached | Timeout |
|
||||
| 3 consecutive no-progress iterations | Circuit breaker |
|
||||
| No fix available and local fix not possible | Failure |
|
||||
| No new CIPE and auto-fix not configured | Pre-CIPE failure |
|
||||
| User cancels | Cancelled |
|
||||
|
||||
## Main Loop
|
||||
|
||||
### Step 1: Initialize Tracking
|
||||
|
||||
```
|
||||
cycle_count = 0
|
||||
start_time = now()
|
||||
no_progress_count = 0
|
||||
local_verify_count = 0
|
||||
last_state = null
|
||||
last_cipe_url = null
|
||||
expected_commit_sha = null
|
||||
```
|
||||
|
||||
### Step 2: Spawn Subagent
|
||||
|
||||
Spawn the `ci-watcher` subagent to poll CI status:
|
||||
|
||||
**Fresh start (first spawn, no expected CIPE):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>."
|
||||
)
|
||||
```
|
||||
|
||||
**After action that triggers new CIPE (wait mode):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>.
|
||||
|
||||
WAIT MODE: A new CIPE should spawn. Ignore old CIPE until new one appears.
|
||||
Expected commit SHA: <expected_commit_sha>
|
||||
Previous CIPE URL: <last_cipe_url>"
|
||||
)
|
||||
```
|
||||
|
||||
### Step 3: Handle Subagent Response
|
||||
|
||||
When subagent returns:
|
||||
|
||||
1. Check the returned status
|
||||
2. Look up default behavior in the table above
|
||||
3. Check if user instructions override the default
|
||||
4. Execute the appropriate action
|
||||
5. **If action expects new CIPE**, update tracking (see Step 3a)
|
||||
6. If action results in looping, go to Step 2
|
||||
|
||||
### Step 3a: Track State for New-CIPE Detection
|
||||
|
||||
After actions that should trigger a new CIPE, record state before looping:
|
||||
|
||||
| Action | What to Track | Subagent Mode |
|
||||
| ----------------------------- | --------------------------------------------- | ------------- |
|
||||
| Fix auto-applying | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply via MCP | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply locally + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Reject + fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Fix failed + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| No fix + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Environment rerun | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| No-new-CIPE + auto-fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
|
||||
**CRITICAL**: When passing `expectedCommitSha` or `last_cipe_url` to the subagent, it enters **wait mode**:
|
||||
|
||||
- Subagent will **completely ignore** the old/stale CIPE
|
||||
- Subagent will only wait for new CIPE to appear
|
||||
- Subagent will NOT return to main agent with stale CIPE data
|
||||
- Once new CIPE detected, subagent switches to normal polling
|
||||
|
||||
**Why wait mode matters for context preservation**: Stale CIPE data can be very large (task output summaries, suggested fix patches, reasoning). If subagent returns this to main agent, it pollutes main agent's context with useless data since we already processed that CIPE. Wait mode keeps stale data in the subagent, never sending it to main agent.
|
||||
|
||||
### Step 4: Progress Tracking
|
||||
|
||||
After each action:
|
||||
|
||||
- If state changed significantly → reset `no_progress_count = 0`
|
||||
- If state unchanged → `no_progress_count++`
|
||||
- On new CI attempt detected → reset `local_verify_count = 0`
|
||||
|
||||
## Status Reporting
|
||||
|
||||
Based on verbosity level:
|
||||
|
||||
| Level | What to Report |
|
||||
| --------- | -------------------------------------------------------------------------- |
|
||||
| `minimal` | Only final result (success/failure/timeout) |
|
||||
| `medium` | State changes + periodic updates ("Cycle N \| Elapsed: Xm \| Status: ...") |
|
||||
| `verbose` | All of medium + full subagent responses, git outputs, MCP responses |
|
||||
|
||||
## User Instruction Examples
|
||||
|
||||
Users can override default behaviors:
|
||||
|
||||
| Instruction | Effect |
|
||||
| ------------------------------------------------ | --------------------------------------------- |
|
||||
| "never auto-apply" | Always prompt before applying any fix |
|
||||
| "always ask before git push" | Prompt before each push |
|
||||
| "reject any fix for e2e tasks" | Auto-reject if `failedTaskIds` contains e2e |
|
||||
| "apply all fixes regardless of verification" | Skip verification check, apply everything |
|
||||
| "if confidence < 70, reject" | Check confidence field before applying |
|
||||
| "run 'nx affected -t typecheck' before applying" | Add local verification step |
|
||||
| "auto-fix workflow failures" | Attempt lockfile updates on pre-CIPE failures |
|
||||
| "wait 45 min for new CIPE" | Override new-CIPE timeout (default: 10 min) |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Action |
|
||||
| ------------------------ | ------------------------------------------------------------------------------------- |
|
||||
| Git rebase conflict | Report to user, exit |
|
||||
| `nx apply-locally` fails | Report to user, attempt manual patch or exit |
|
||||
| MCP tool error | Retry once, if fails report to user |
|
||||
| Subagent spawn failure | Retry once, if fails exit with error |
|
||||
| No new CIPE detected | If `--auto-fix-workflow`, try lockfile update; otherwise report to user with guidance |
|
||||
| Lockfile auto-fix fails | Report to user, exit with guidance to check CI logs |
|
||||
|
||||
## Example Session
|
||||
|
||||
### Example 1: Normal Flow with Self-Healing (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-auth'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, verbosity=medium
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: IN_PROGRESS | Self-Healing: NOT_STARTED | Elapsed: 1m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: IN_PROGRESS | Elapsed: 3m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 5m
|
||||
|
||||
[ci-monitor] Fix available! Verification: COMPLETED
|
||||
[ci-monitor] Applying fix via MCP...
|
||||
[ci-monitor] Fix applied in CI. Waiting for new CI attempt...
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 8m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 2
|
||||
- Total time: 12m 34s
|
||||
- Fixes applied: 1
|
||||
- Result: SUCCESS
|
||||
```
|
||||
|
||||
### Example 2: Pre-CI Failure (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-products'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, auto-fix-workflow=true
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 2m
|
||||
|
||||
[ci-monitor] Applying fix locally, enhancing, and pushing...
|
||||
[ci-monitor] Committed: abc1234
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] Waiting for new CI attempt... (expected SHA: abc1234)
|
||||
[CI Monitor] ⚠️ CI attempt timeout (10 min). Returning no_new_cipe.
|
||||
|
||||
[ci-monitor] Status: no_new_cipe
|
||||
[ci-monitor] --auto-fix-workflow enabled. Attempting lockfile update...
|
||||
[ci-monitor] Lockfile updated. Committed: def5678
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 18m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 3
|
||||
- Total time: 22m 15s
|
||||
- Fixes applied: 1 (self-healing) + 1 (lockfile)
|
||||
- Result: SUCCESS
|
||||
```
|
||||
@@ -0,0 +1,228 @@
|
||||
---
|
||||
name: nx-generate
|
||||
description: Generate code using nx generators. USE WHEN scaffolding code or transforming existing code - for example creating libraries or applications, or anything else that is boilerplate code or automates repetitive tasks. ALWAYS use this first when generating code with Nx instead of calling MCP tools or running nx generate immediately.
|
||||
---
|
||||
|
||||
# Run Nx Generator
|
||||
|
||||
Nx generators are powerful tools that scaffold projects, make automated code migrations or automate repetitive tasks in a monorepo. They ensure consistency across the codebase and reduce boilerplate work.
|
||||
|
||||
This skill applies when the user wants to:
|
||||
|
||||
- Create new projects like libraries or applications
|
||||
- Scaffold features or boilerplate code
|
||||
- Run workspace-specific or custom generators
|
||||
- Do anything else that an nx generator exists for
|
||||
|
||||
## Generator Discovery Flow
|
||||
|
||||
### Step 1: List Available Generators
|
||||
|
||||
Use the Nx CLI to discover available generators:
|
||||
|
||||
- List all generators for a plugin: `npx nx list @nx/react`
|
||||
- View available plugins: `npx nx list`
|
||||
|
||||
This includes:
|
||||
|
||||
- Plugin generators (e.g., `@nx/react:library`, `@nx/js:library`)
|
||||
- Local workspace generators (defined in the repo's own plugins)
|
||||
|
||||
### Step 2: Match Generator to User Request
|
||||
|
||||
Based on the user's request, identify which generator(s) could fulfill their needs. Consider:
|
||||
|
||||
- What artifact type they want to create (library, application, etc.)
|
||||
- Which framework or technology stack is relevant
|
||||
- Whether they mentioned specific generator names
|
||||
|
||||
**IMPORTANT**: When both a local workspace generator and an external plugin generator could satisfy the request, **always prefer the local workspace generator**. Local generators are customized for the specific repo's patterns and conventions.
|
||||
|
||||
It's possible that the user request is something that no Nx generator exists for whatsoever. In this case, you can stop using this skill and try to help the user another way. HOWEVER, the burden of proof for this is high. Before aborting, carefully consider each and every generator that's available. Look into details for any that could be related in any way before making this decision.
|
||||
|
||||
## Pre-Execution Checklist
|
||||
|
||||
Before running any generator, complete these steps:
|
||||
|
||||
### 1. Fetch Generator Schema
|
||||
|
||||
Use the `--help` flag to understand all available options:
|
||||
|
||||
```bash
|
||||
npx nx g @nx/react:library --help
|
||||
```
|
||||
|
||||
Pay attention to:
|
||||
|
||||
- Required options that must be provided
|
||||
- Optional options that may be relevant to the user's request
|
||||
- Default values that might need to be overridden
|
||||
|
||||
### 2. Read Generator Source Code
|
||||
|
||||
Understanding what the generator actually does helps you:
|
||||
|
||||
- Know what files will be created/modified
|
||||
- Understand any side effects (updating configs, installing deps, etc.)
|
||||
- Identify options that might not be obvious from the schema
|
||||
|
||||
To find generator source code:
|
||||
|
||||
- For plugin generators: Use `node -e "console.log(require.resolve('@nx/<plugin>/generators.json'));"` to find the generators.json, then locate the source from there
|
||||
- If that fails, read directly from `node_modules/<plugin>/generators.json`
|
||||
- For local generators: They are typically in `tools/generators/` or a local plugin directory. You can search the repo for the generator name to find it.
|
||||
|
||||
### 2.5 Reevaluate if the generator is right
|
||||
|
||||
Once you have built up an understanding of what the selected generator does, reconsider: Is this the right generator to service the user request?
|
||||
If not, it's okay to go back to the Generator Discovery Flow and select a different generator before proceeding. If you do, make sure to go through the entire pre-execution checklist once more.
|
||||
|
||||
### 3. Understand Repo Context
|
||||
|
||||
Before generating, examine the target area of the codebase:
|
||||
|
||||
- Look at similar existing artifacts (other libraries, applications, etc.)
|
||||
- Identify patterns and conventions used in the repo
|
||||
- Note naming conventions, file structures, and configuration patterns
|
||||
- Try to match these patterns when configuring the generator
|
||||
|
||||
For example, if similar libraries are using a specific test runner, build tool or linter, try to match that if possible.
|
||||
If projects or other artifacts are organized with a specific naming convention, try to match it.
|
||||
|
||||
### 4. Validate Required Options
|
||||
|
||||
Ensure all required options have values:
|
||||
|
||||
- Map the user's request to generator options
|
||||
- Infer values from context where possible
|
||||
- Ask the user for any critical missing information
|
||||
|
||||
## Execution
|
||||
|
||||
Keep in mind that you might have to prefix things with npx/pnpx/yarn if the user doesn't have nx installed globally.
|
||||
Many generators will behave differently based on where they are executed. For example, first-party nx library generators use the cwd to determine the directory that the library should be placed in. This is highly important.
|
||||
|
||||
### Consider Dry-Run (Optional)
|
||||
|
||||
Running with `--dry-run` first is strongly encouraged but not mandatory. Use your judgment:
|
||||
|
||||
- For complex generators or unfamiliar territory: do a dry-run first
|
||||
- For simple, well-understood generators: may proceed directly
|
||||
- Dry-run shows file names and created/deleted/modified markers, but not content
|
||||
- There are cases where a generator does not support dry-run (for example if it had to install an npm package) - in that case --dry-run might fail. Don't be discouraged but simply move on to running the generator for real and iterating from there.
|
||||
|
||||
### Running the Generator
|
||||
|
||||
Execute the generator with:
|
||||
|
||||
```bash
|
||||
nx generate <generator-name> <options> --no-interactive
|
||||
```
|
||||
|
||||
**CRITICAL**: Always include `--no-interactive` to prevent prompts that would hang the execution.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
nx generate @nx/react:library --name=my-utils --no-interactive
|
||||
```
|
||||
|
||||
### Handling Generator Failures
|
||||
|
||||
If the generator fails:
|
||||
|
||||
1. **Diagnose the error** - Read the error message carefully
|
||||
2. **Identify the cause** - Missing options, invalid values, conflicts, etc.
|
||||
3. **Attempt automatic fix** - Adjust options or resolve conflicts
|
||||
4. **Retry** - Run the generator again with corrected options
|
||||
|
||||
Common failure reasons:
|
||||
|
||||
- Missing required options
|
||||
- Invalid option values
|
||||
- Conflicting with existing files
|
||||
- Missing dependencies
|
||||
- Generator doesn't support certain flag combinations
|
||||
|
||||
## Post-Generation
|
||||
|
||||
### 1. Modify Generated Code (If Needed)
|
||||
|
||||
Generators provide a starting point, but the output may need adjustment to match the user's specific requirements:
|
||||
|
||||
- Add or modify functionality as requested
|
||||
- Adjust imports, exports, or configurations
|
||||
- Integrate with existing code patterns in the repo
|
||||
|
||||
### 2. Format Code
|
||||
|
||||
Run formatting on all generated/modified files:
|
||||
|
||||
```bash
|
||||
nx format --fix
|
||||
```
|
||||
|
||||
Languages other than javascript/typescript might need other formatting invocations too.
|
||||
|
||||
### 3. Run Verification
|
||||
|
||||
Verify that the generated code works correctly. What this looks like will vary depending on the type of generator and the targets available.
|
||||
If the generator created a new project, run its targets directly
|
||||
Use your best judgement to determine what needs to be verified.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
nx lint <new-project>
|
||||
nx test <new-project>
|
||||
nx build <new-project>
|
||||
```
|
||||
|
||||
### 4. Handle Verification Failures
|
||||
|
||||
When verification fails:
|
||||
|
||||
**If scope is manageable** (a few lint errors, minor type issues):
|
||||
|
||||
- Fix the issues
|
||||
- Re-run verification to confirm
|
||||
|
||||
**If issues are extensive** (many errors, complex problems):
|
||||
|
||||
- Attempt simple, obvious fixes first
|
||||
- If still failing, escalate to the user with:
|
||||
- Description of what was generated
|
||||
- What verification is failing
|
||||
- What you've attempted to fix
|
||||
- Remaining issues that need user input
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Generator Failures
|
||||
|
||||
- Check the error message for specific causes
|
||||
- Verify all required options are provided
|
||||
- Check for conflicts with existing files
|
||||
- Ensure the generator name and options are correct
|
||||
|
||||
### Missing Options
|
||||
|
||||
- Consult the generator schema for required fields
|
||||
- Infer values from context when reasonable
|
||||
- Ask the user for values that cannot be inferred
|
||||
|
||||
## Key Principles
|
||||
|
||||
1. **Local generators first** - Always prefer workspace/local generators over external plugin generators when both could work
|
||||
|
||||
2. **Understand before running** - Read both the schema AND the source code to fully understand what will happen
|
||||
|
||||
3. **No prompts** - Always use `--no-interactive` to prevent hanging
|
||||
|
||||
4. **Generators are starting points** - Modify the output as needed to fully satisfy the user's requirements
|
||||
|
||||
5. **Verify changes work** - Don't just generate; ensure the code builds, lints, and tests pass
|
||||
|
||||
6. **Be proactive about fixes** - Don't just report errors; attempt to resolve them automatically when possible
|
||||
|
||||
7. **Match repo patterns** - Study existing similar code in the repo and match its conventions
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
name: nx-plugins
|
||||
description: Find and add Nx plugins. USE WHEN user wants to discover available plugins, install a new plugin, or add support for a specific framework or technology to the workspace.
|
||||
---
|
||||
|
||||
## Finding and Installing new plugins
|
||||
|
||||
- List plugins: `pnpm nx list`
|
||||
- Install plugins `pnpm nx add <plugin>`. Example: `pnpm nx add @nx/react`.
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
name: nx-run-tasks
|
||||
description: Helps with running tasks in an Nx workspace. USE WHEN the user wants to execute build, test, lint, serve, or run any other tasks defined in the workspace.
|
||||
---
|
||||
|
||||
You can run tasks with Nx in the following way.
|
||||
|
||||
Keep in mind that you might have to prefix things with npx/pnpx/yarn if the user doesn't have nx installed globally. Look at the package.json or lockfile to determine which package manager is in use.
|
||||
|
||||
For more details on any command, run it with `--help` (e.g. `nx run-many --help`, `nx affected --help`).
|
||||
|
||||
## Understand which tasks can be run
|
||||
|
||||
You can check those via `nx show project <projectname> --json`, for example `nx show project myapp --json`. It contains a `targets` section which has information about targets that can be run. You can also just look at the `package.json` scripts or `project.json` targets, but you might miss out on inferred tasks by Nx plugins.
|
||||
|
||||
## Run a single task
|
||||
|
||||
```
|
||||
nx run <project>:<task>
|
||||
```
|
||||
|
||||
where `project` is the project name defined in `package.json` or `project.json` (if present).
|
||||
|
||||
## Run multiple tasks
|
||||
|
||||
```
|
||||
nx run-many -t build test lint typecheck
|
||||
```
|
||||
|
||||
You can pass a `-p` flag to filter to specific projects, otherwise it runs on all projects. You can also use `--exclude` to exclude projects, and `--parallel` to control the number of parallel processes (default is 3).
|
||||
|
||||
Examples:
|
||||
|
||||
- `nx run-many -t test -p proj1 proj2` — test specific projects
|
||||
- `nx run-many -t test --projects=*-app --exclude=excluded-app` — test projects matching a pattern
|
||||
- `nx run-many -t test --projects=tag:api-*` — test projects by tag
|
||||
|
||||
## Run tasks for affected projects
|
||||
|
||||
Use `nx affected` to only run tasks on projects that have been changed and projects that depend on changed projects. This is especially useful in CI and for large workspaces.
|
||||
|
||||
```
|
||||
nx affected -t build test lint
|
||||
```
|
||||
|
||||
By default it compares against the base branch. You can customize this:
|
||||
|
||||
- `nx affected -t test --base=main --head=HEAD` — compare against a specific base and head
|
||||
- `nx affected -t test --files=libs/mylib/src/index.ts` — specify changed files directly
|
||||
|
||||
## Useful flags
|
||||
|
||||
These flags work with `run`, `run-many`, and `affected`:
|
||||
|
||||
- `--skipNxCache` — rerun tasks even when results are cached
|
||||
- `--verbose` — print additional information such as stack traces
|
||||
- `--nxBail` — stop execution after the first failed task
|
||||
- `--configuration=<name>` — use a specific configuration (e.g. `production`)
|
||||
@@ -0,0 +1,186 @@
|
||||
---
|
||||
name: nx-workspace
|
||||
description: "Explore and understand Nx workspaces. USE WHEN answering any questions about the nx workspace, the projects in it or tasks to run. EXAMPLES: 'What projects are in this workspace?', 'How is project X configured?', 'What targets can I run?', 'What's affected by my changes?', 'Which projects depend on library Y?', or any questions about Nx workspace structure, project configuration, or available tasks."
|
||||
---
|
||||
|
||||
# Nx Workspace Exploration
|
||||
|
||||
This skill provides read-only exploration of Nx workspaces. Use it to understand workspace structure, project configuration, available targets, and dependencies.
|
||||
|
||||
Keep in mind that you might have to prefix commands with `npx`/`pnpx`/`yarn` if nx isn't installed globally. Check the lockfile to determine the package manager in use.
|
||||
|
||||
## Listing Projects
|
||||
|
||||
Use `nx show projects` to list projects in the workspace.
|
||||
|
||||
```bash
|
||||
# List all projects
|
||||
nx show projects
|
||||
|
||||
# Filter by pattern (glob)
|
||||
nx show projects --projects "apps/*"
|
||||
nx show projects --projects "shared-*"
|
||||
|
||||
# Filter by project type
|
||||
nx show projects --type app
|
||||
nx show projects --type lib
|
||||
nx show projects --type e2e
|
||||
|
||||
# Filter by target (projects that have a specific target)
|
||||
nx show projects --withTarget build
|
||||
nx show projects --withTarget e2e
|
||||
|
||||
# Find affected projects (changed since base branch)
|
||||
nx show projects --affected
|
||||
nx show projects --affected --base=main
|
||||
nx show projects --affected --type app
|
||||
|
||||
# Combine filters
|
||||
nx show projects --type lib --withTarget test
|
||||
nx show projects --affected --exclude="*-e2e"
|
||||
|
||||
# Output as JSON
|
||||
nx show projects --json
|
||||
```
|
||||
|
||||
## Project Configuration
|
||||
|
||||
Use `nx show project <name> --json` to get the full resolved configuration for a project.
|
||||
|
||||
**Important**: Do NOT read `project.json` directly - it only contains partial configuration. The `nx show project` command returns the full resolved config including inferred targets from plugins.
|
||||
|
||||
You can read the full project schema at `node_modules/nx/schemas/project-schema.json` to understand nx project configuration options.
|
||||
|
||||
```bash
|
||||
# Get full project configuration
|
||||
nx show project my-app --json
|
||||
|
||||
# Extract specific parts from the JSON
|
||||
nx show project my-app --json | jq '.targets'
|
||||
nx show project my-app --json | jq '.targets.build'
|
||||
nx show project my-app --json | jq '.targets | keys'
|
||||
|
||||
|
||||
# Check project metadata
|
||||
nx show project my-app --json | jq '{name, root, sourceRoot, projectType, tags}'
|
||||
```
|
||||
|
||||
## Target Information
|
||||
|
||||
Targets define what tasks can be run on a project.
|
||||
|
||||
```bash
|
||||
# List all targets for a project
|
||||
nx show project my-app --json | jq '.targets | keys'
|
||||
|
||||
# Get full target configuration
|
||||
nx show project my-app --json | jq '.targets.build'
|
||||
|
||||
# Check target executor/command
|
||||
nx show project my-app --json | jq '.targets.build.executor'
|
||||
nx show project my-app --json | jq '.targets.build.command'
|
||||
|
||||
# View target options
|
||||
nx show project my-app --json | jq '.targets.build.options'
|
||||
|
||||
# Check target inputs/outputs (for caching)
|
||||
nx show project my-app --json | jq '.targets.build.inputs'
|
||||
nx show project my-app --json | jq '.targets.build.outputs'
|
||||
|
||||
# Find projects with a specific target
|
||||
nx show projects --withTarget serve
|
||||
nx show projects --withTarget e2e
|
||||
```
|
||||
|
||||
## Workspace Configuration
|
||||
|
||||
Read `nx.json` directly for workspace-level configuration.
|
||||
You can read the full project schema at `node_modules/nx/schemas/nx-schema.json` to understand nx project configuration options.
|
||||
|
||||
```bash
|
||||
# Read the full nx.json
|
||||
cat nx.json
|
||||
|
||||
# Or use jq for specific sections
|
||||
cat nx.json | jq '.targetDefaults'
|
||||
cat nx.json | jq '.namedInputs'
|
||||
cat nx.json | jq '.plugins'
|
||||
cat nx.json | jq '.generators'
|
||||
```
|
||||
|
||||
Key nx.json sections:
|
||||
|
||||
- `targetDefaults` - Default configuration applied to all targets of a given name
|
||||
- `namedInputs` - Reusable input definitions for caching
|
||||
- `plugins` - Nx plugins and their configuration
|
||||
- ...and much more, read the schema or nx.json for details
|
||||
|
||||
## Affected Projects
|
||||
|
||||
Find projects affected by changes in the current branch.
|
||||
|
||||
```bash
|
||||
# Affected since base branch (auto-detected)
|
||||
nx show projects --affected
|
||||
|
||||
# Affected with explicit base
|
||||
nx show projects --affected --base=main
|
||||
nx show projects --affected --base=origin/main
|
||||
|
||||
# Affected between two commits
|
||||
nx show projects --affected --base=abc123 --head=def456
|
||||
|
||||
# Affected apps only
|
||||
nx show projects --affected --type app
|
||||
|
||||
# Affected excluding e2e projects
|
||||
nx show projects --affected --exclude="*-e2e"
|
||||
|
||||
# Affected by uncommitted changes
|
||||
nx show projects --affected --uncommitted
|
||||
|
||||
# Affected by untracked files
|
||||
nx show projects --affected --untracked
|
||||
```
|
||||
|
||||
## Common Exploration Patterns
|
||||
|
||||
### "What's in this workspace?"
|
||||
|
||||
```bash
|
||||
nx show projects
|
||||
nx show projects --type app
|
||||
nx show projects --type lib
|
||||
```
|
||||
|
||||
### "How do I build/test/lint project X?"
|
||||
|
||||
```bash
|
||||
nx show project X --json | jq '.targets | keys'
|
||||
nx show project X --json | jq '.targets.build'
|
||||
```
|
||||
|
||||
### "What depends on library Y?"
|
||||
|
||||
```bash
|
||||
# Find projects that may depend on Y by searching for imports
|
||||
# (Nx doesn't have a direct "dependents" command via CLI)
|
||||
grep -r "from '@myorg/Y'" --include="*.ts" --include="*.tsx" apps/ libs/
|
||||
```
|
||||
|
||||
### "What configuration options are available?"
|
||||
|
||||
```bash
|
||||
cat node_modules/nx/schemas/nx-schema.json | jq '.properties | keys'
|
||||
cat node_modules/nx/schemas/project-schema.json | jq '.properties | keys'
|
||||
```
|
||||
|
||||
### "Why is project X affected?"
|
||||
|
||||
```bash
|
||||
# Check what files changed
|
||||
git diff --name-only main
|
||||
|
||||
# See which project owns those files
|
||||
nx show project X --json | jq '.root'
|
||||
```
|
||||
@@ -0,0 +1,92 @@
|
||||
name: Banner Content Monitor
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '*/15 * * * *'
|
||||
workflow_dispatch: # Allow manual trigger
|
||||
|
||||
permissions: {}
|
||||
|
||||
env:
|
||||
BANNER_URL: ${{ vars.BANNER_URL }}
|
||||
|
||||
jobs:
|
||||
check-and-deploy:
|
||||
if: ${{ github.repository_owner == 'nrwl' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Fetch banner content and compute hash
|
||||
id: banner
|
||||
run: |
|
||||
if [ -z "$BANNER_URL" ]; then
|
||||
echo "BANNER_URL is not set"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Fetch content and compute hash
|
||||
CONTENT_HASH=$(curl -sf "$BANNER_URL" | sha256sum | cut -d' ' -f1)
|
||||
|
||||
if [ -z "$CONTENT_HASH" ]; then
|
||||
echo "Failed to fetch banner content"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "current_hash=$CONTENT_HASH" >> $GITHUB_OUTPUT
|
||||
echo "Current banner hash: $CONTENT_HASH"
|
||||
|
||||
- name: Restore cached hash
|
||||
id: cache
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: .banner-hash
|
||||
key: banner-content-hash-
|
||||
restore-keys: |
|
||||
banner-content-hash-
|
||||
|
||||
- name: Compare hashes
|
||||
id: compare
|
||||
run: |
|
||||
CURRENT_HASH="${{ steps.banner.outputs.current_hash }}"
|
||||
|
||||
if [ -f .banner-hash ]; then
|
||||
CACHED_HASH=$(cat .banner-hash)
|
||||
echo "Cached hash: $CACHED_HASH"
|
||||
else
|
||||
CACHED_HASH=""
|
||||
echo "No cached hash found"
|
||||
fi
|
||||
|
||||
if [ "$CURRENT_HASH" != "$CACHED_HASH" ]; then
|
||||
echo "changed=true" >> $GITHUB_OUTPUT
|
||||
echo "Banner content has changed!"
|
||||
else
|
||||
echo "changed=false" >> $GITHUB_OUTPUT
|
||||
echo "Banner content unchanged"
|
||||
fi
|
||||
|
||||
- name: Trigger Netlify deploys
|
||||
if: steps.compare.outputs.changed == 'true'
|
||||
env:
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
run: |
|
||||
npm install -g netlify-cli
|
||||
|
||||
echo "Triggering nx-docs deploy..."
|
||||
netlify deploy --trigger --prod -s nx-docs
|
||||
|
||||
echo "Triggering nx-dev deploy..."
|
||||
netlify deploy --trigger --prod -s nx-dev
|
||||
|
||||
echo "Both deploys triggered successfully"
|
||||
|
||||
- name: Save new hash to cache
|
||||
if: steps.compare.outputs.changed == 'true'
|
||||
run: |
|
||||
echo "${{ steps.banner.outputs.current_hash }}" > .banner-hash
|
||||
|
||||
- name: Update cache
|
||||
if: steps.compare.outputs.changed == 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: .banner-hash
|
||||
key: banner-content-hash-${{ github.run_id }}
|
||||
@@ -18,6 +18,7 @@ jobs:
|
||||
main-linux:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
NX_BATCH_MODE: 'false'
|
||||
NX_E2E_CI_CACHE_KEY: e2e-github-linux
|
||||
NX_DAEMON: 'true'
|
||||
NX_PERF_LOGGING: 'false'
|
||||
@@ -29,6 +30,9 @@ jobs:
|
||||
NX_ALLOW_NON_CACHEABLE_DTE: 'true'
|
||||
NX_CLOUD_USE_NEW_TASK_APIS: 'true'
|
||||
NX_CLOUD_USE_NEW_STREAM_OUTPUT: 'true'
|
||||
NX_CLOUD_EXPERIMENTAL_POLLING: 'true'
|
||||
NX_CLOUD_CONTINUOUS_ASSIGNMENT: 'true'
|
||||
NX_CLOUD_VERBOSE_LOGGING: 'true'
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -47,7 +51,7 @@ jobs:
|
||||
main-branch-name: 'master'
|
||||
|
||||
- name: Start CI Run
|
||||
run: npx nx-cloud@next start-ci-run --auto-apply-fixes="*format:check*,*sync:check*,*conformance:check*,*format-native*,*lint-native*,*lint*,*astro-docs:validate-links*" --distribute-on="./.nx/workflows/dynamic-changesets.yaml" --stop-agents-after="e2e"
|
||||
run: npx nx-cloud@next start-ci-run --distribute-on="./.nx/workflows/dynamic-changesets.yaml" --stop-agents-after="e2e"
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
uses: pnpm/action-setup@7088e561eb65bb68695d245aa206f005ef30921d # v4.1.0
|
||||
id: pnpm-install
|
||||
with:
|
||||
version: 10.11.1
|
||||
version: 10.28.2
|
||||
run_install: false
|
||||
|
||||
- name: Get pnpm store directory
|
||||
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
|
||||
- uses: pnpm/action-setup@7088e561eb65bb68695d245aa206f005ef30921d # v4.1.0
|
||||
with:
|
||||
version: 10.11.1
|
||||
version: 10.28.2
|
||||
|
||||
- name: Use Node.js ${{ matrix.node_version }}
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
|
||||
@@ -75,7 +75,7 @@ const matrixData: MatrixData = {
|
||||
os_name: 'Linux',
|
||||
os_timeout: 60,
|
||||
package_managers: ['npm', 'pnpm', 'yarn'],
|
||||
node_versions: ['20.19.0', '22.12.0', '24.0.0'],
|
||||
node_versions: ['20.19.0', '22.13.0', '24.0.0'],
|
||||
excluded: ['e2e-detox', 'e2e-react-native', 'e2e-expo']
|
||||
},
|
||||
// Docker is not supported on ARM-based macOS runners (no nested virtualization)
|
||||
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
|
||||
- uses: pnpm/action-setup@7088e561eb65bb68695d245aa206f005ef30921d # v4.1.0
|
||||
with:
|
||||
version: 10.11.1 # Aligned with root package.json (pnpm/action-setup will helpfully error if out of sync)
|
||||
version: 10.28.2 # Aligned with root package.json (pnpm/action-setup will helpfully error if out of sync)
|
||||
|
||||
- name: Run a security audit
|
||||
run: pnpm dlx audit-ci --critical --report-type summary
|
||||
|
||||
@@ -22,7 +22,7 @@ env:
|
||||
NX_RUN_GROUP: ${{ github.run_id }}-${{ github.run_attempt }}
|
||||
CYPRESS_INSTALL_BINARY: 0
|
||||
NODE_VERSION: 22.16.0
|
||||
PNPM_VERSION: 10.11.1 # Aligned with root package.json (pnpm/action-setup will helpfully error if out of sync)
|
||||
PNPM_VERSION: 10.28.2 # Aligned with root package.json (pnpm/action-setup will helpfully error if out of sync)
|
||||
|
||||
jobs:
|
||||
# We first need to determine the version we are releasing, and if we need a custom repo or ref to use for the git checkout in subsequent steps.
|
||||
@@ -354,12 +354,24 @@ jobs:
|
||||
architecture: x86
|
||||
|
||||
- name: Build in docker
|
||||
uses: addnab/docker-run-action@4f65fabd2431ebc8d299f8e5a018d79a769ae185 # v3
|
||||
if: ${{ matrix.settings.docker }}
|
||||
with:
|
||||
image: ${{ matrix.settings.docker }}
|
||||
options: --user 0:0 -v ${{ github.workspace }}/.cargo-cache/git/db:/usr/local/cargo/git/db -v ${{ github.workspace }}/.cargo/registry/cache:/usr/local/cargo/registry/cache -v ${{ github.workspace }}/.cargo/registry/index:/usr/local/cargo/registry/index -v ${{ github.workspace }}:/build -w /build
|
||||
run: ${{ matrix.settings.build }}
|
||||
shell: bash
|
||||
env:
|
||||
BUILD_SCRIPT: ${{ matrix.settings.build }}
|
||||
run: |
|
||||
SCRIPT_FILE=$(mktemp)
|
||||
echo "$BUILD_SCRIPT" > "$SCRIPT_FILE"
|
||||
docker run --rm \
|
||||
--user 0:0 \
|
||||
-e PNPM_VERSION \
|
||||
-v ${{ github.workspace }}/.cargo-cache/git/db:/usr/local/cargo/git/db \
|
||||
-v ${{ github.workspace }}/.cargo/registry/cache:/usr/local/cargo/registry/cache \
|
||||
-v ${{ github.workspace }}/.cargo/registry/index:/usr/local/cargo/registry/index \
|
||||
-v ${{ github.workspace }}:/build \
|
||||
-v "$SCRIPT_FILE:/build-script.sh" \
|
||||
-w /build \
|
||||
${{ matrix.settings.docker }} \
|
||||
bash /build-script.sh
|
||||
|
||||
- name: Build
|
||||
run: ${{ matrix.settings.build }}
|
||||
@@ -406,7 +418,7 @@ jobs:
|
||||
env
|
||||
whoami
|
||||
sudo pkg install -y -f node libnghttp2 www/npm git openjdk17
|
||||
sudo npm install --location=global --ignore-scripts pnpm@10.11.1
|
||||
sudo npm install --location=global --ignore-scripts pnpm@10.28.2
|
||||
# Set up Java 17
|
||||
export JAVA_HOME=/usr/local/openjdk17
|
||||
export PATH="$JAVA_HOME/bin:$PATH"
|
||||
@@ -472,11 +484,27 @@ jobs:
|
||||
rm -rf ~/.rustup/toolchains/*/share || true
|
||||
# Remove other development tool caches
|
||||
rm -rf ~/.cache/* || true
|
||||
|
||||
# Remove unnecessary workspace directories
|
||||
rm -rf docs astro-docs nx-dev || true
|
||||
|
||||
echo "Checking disk space after cleanup"
|
||||
df -h
|
||||
|
||||
echo "Building FreeBSD bindings"
|
||||
pnpm nx run-many --verbose --outputStyle stream --target=build-native -- --target=x86_64-unknown-freebsd
|
||||
BUILD_EXIT=0
|
||||
pnpm nx run-many --verbose --outputStyle stream --target=build-native -- --target=x86_64-unknown-freebsd || BUILD_EXIT=$?
|
||||
|
||||
echo "=== Disk usage after build ==="
|
||||
df -h
|
||||
|
||||
if [ "$BUILD_EXIT" -ne 0 ]; then
|
||||
echo "Build failed with exit code $BUILD_EXIT"
|
||||
exit $BUILD_EXIT
|
||||
fi
|
||||
|
||||
echo "Build succeeded"
|
||||
|
||||
echo "Cleaning up"
|
||||
pnpm nx reset
|
||||
rm -rf node_modules
|
||||
|
||||
@@ -25,7 +25,11 @@ jest.debug.config.js
|
||||
/nx-dev/nx-dev/public/documentation
|
||||
/nx-dev/nx-dev/public/tutorials
|
||||
/nx-dev/nx-dev/public/images/open-graph
|
||||
**/tests/temp-db
|
||||
|
||||
# Banner JSON files are generated during static builds
|
||||
/nx-dev/nx-dev/lib/banner.json
|
||||
/astro-docs/src/content/banner.json
|
||||
**/tests/temp-db*
|
||||
|
||||
# Issues scraper creates these files, stored by github's cache
|
||||
/scripts/issues-scraper/cached
|
||||
@@ -67,7 +71,7 @@ dependency-reduced-pom.xml
|
||||
*.wasm
|
||||
/wasi-sdk*
|
||||
|
||||
vite.config.*.timestamp*
|
||||
*.config.timestamp*
|
||||
|
||||
storybook-static
|
||||
|
||||
@@ -133,3 +137,4 @@ test-results
|
||||
# .NET build output
|
||||
/packages/dotnet/analyzer/bin
|
||||
/packages/dotnet/analyzer/obj
|
||||
/*.deb
|
||||
|
||||
@@ -1,8 +1,23 @@
|
||||
distribute-on:
|
||||
default: auto linux-large, 3 linux-extra-large
|
||||
extra-small-changeset: 6 linux-large, 3 linux-extra-large
|
||||
small-changeset: 6 linux-large, 4 linux-extra-large
|
||||
medium-changeset: 6 linux-large, 5 linux-extra-large
|
||||
large-changeset: 6 linux-large, 6 linux-extra-large
|
||||
extra-large-changeset: 8 linux-large, 8 linux-extra-large
|
||||
assignment-rules:
|
||||
- projects:
|
||||
- e2e-gradle
|
||||
- e2e-next
|
||||
- e2e-plugin
|
||||
targets:
|
||||
- e2e-ci**
|
||||
run-on:
|
||||
- agent: linux-extra-large
|
||||
parallelism: 2
|
||||
- projects:
|
||||
- e2e-angular
|
||||
- e2e-node
|
||||
- e2e-react
|
||||
targets:
|
||||
- e2e-ci**
|
||||
run-on:
|
||||
@@ -25,15 +40,14 @@ assignment-rules:
|
||||
|
||||
- projects:
|
||||
- e2e-release
|
||||
- e2e-angular
|
||||
- e2e-react
|
||||
- e2e-next
|
||||
- e2e-nuxt
|
||||
- e2e-web
|
||||
- e2e-eslint
|
||||
- e2e-remix
|
||||
- e2e-cypress
|
||||
- e2e-docker
|
||||
- e2e-js
|
||||
- e2e-nx
|
||||
- e2e-nx-init
|
||||
- e2e-dotnet
|
||||
- e2e-workspace-create
|
||||
@@ -44,7 +58,7 @@ assignment-rules:
|
||||
- agent: linux-large
|
||||
parallelism: 1
|
||||
- agent: linux-extra-large
|
||||
parallelism: 1
|
||||
parallelism: 2
|
||||
|
||||
# All other e2e tests can run in parallel
|
||||
- targets:
|
||||
@@ -80,6 +94,15 @@ assignment-rules:
|
||||
- agent: linux-extra-large
|
||||
parallelism: 6
|
||||
|
||||
# TODO(altan): remove when scheduling issue resolved
|
||||
- projects:
|
||||
- nx-dev
|
||||
targets:
|
||||
- prebuild-banner
|
||||
run-on:
|
||||
- agent: linux-extra-large
|
||||
parallelism: 6
|
||||
|
||||
- targets:
|
||||
- "*"
|
||||
run-on:
|
||||
|
||||
@@ -3,3 +3,10 @@ nx-dev/**/jest.config.js
|
||||
_files
|
||||
_solution
|
||||
nx-dev/tutorial/**/templates
|
||||
|
||||
# Generated by napi-rs (outputs of build-native)
|
||||
packages/nx/src/native/index.d.ts
|
||||
packages/nx/src/native/native-bindings.js
|
||||
|
||||
# Workaround for ignore-files crate bug with prefix matching
|
||||
**/target/
|
||||
|
||||
@@ -0,0 +1,479 @@
|
||||
---
|
||||
description: Polls Nx Cloud CI pipeline and self-healing status. Returns structured state when actionable. Spawned by /nx-cloud-ci-monitor command to monitor CI Attempt status.
|
||||
mode: subagent
|
||||
---
|
||||
|
||||
# CI Watcher Subagent
|
||||
|
||||
You are a CI monitoring subagent responsible for polling Nx Cloud CI Attempt status and self-healing state. You report status back to the main agent - you do NOT make apply/reject decisions.
|
||||
|
||||
## Your Responsibilities
|
||||
|
||||
1. Poll CI status using the `ci_information` MCP tool
|
||||
2. Implement exponential backoff between polls
|
||||
3. Return structured state when an actionable condition is reached
|
||||
4. Track iteration count and elapsed time
|
||||
5. Output status updates based on verbosity level
|
||||
|
||||
## Input Parameters (from Main Agent)
|
||||
|
||||
The main agent may provide these optional parameters in the prompt:
|
||||
|
||||
| Parameter | Description |
|
||||
| ------------------- | -------------------------------------------------------- |
|
||||
| `branch` | Branch to monitor (auto-detected if not provided) |
|
||||
| `expectedCommitSha` | Commit SHA that should trigger a new CI Attempt |
|
||||
| `previousCipeUrl` | CI Attempt URL before the action (to detect change) |
|
||||
| `subagentTimeout` | Polling timeout in minutes (default: 60) |
|
||||
| `verbosity` | Output level: minimal, medium, verbose (default: medium) |
|
||||
|
||||
When `expectedCommitSha` or `previousCipeUrl` is provided, you must detect whether a new CI Attempt has spawned.
|
||||
|
||||
## MCP Tool Reference
|
||||
|
||||
### `ci_information`
|
||||
|
||||
**Input:**
|
||||
|
||||
```json
|
||||
{
|
||||
"branch": "string (optional, defaults to current git branch)",
|
||||
"select": "string (optional, comma-separated field names)",
|
||||
"pageToken": "number (optional, 0-based pagination for long strings)"
|
||||
}
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```json
|
||||
{
|
||||
"cipeStatus": "NOT_STARTED | IN_PROGRESS | SUCCEEDED | FAILED | CANCELED | TIMED_OUT",
|
||||
"cipeUrl": "string",
|
||||
"branch": "string",
|
||||
"commitSha": "string | null",
|
||||
"failedTaskIds": "string[]",
|
||||
"verifiedTaskIds": "string[]",
|
||||
"selfHealingEnabled": "boolean",
|
||||
"selfHealingStatus": "NOT_STARTED | IN_PROGRESS | COMPLETED | FAILED | NOT_EXECUTABLE | null",
|
||||
"verificationStatus": "NOT_STARTED | IN_PROGRESS | COMPLETED | FAILED | NOT_EXECUTABLE | null",
|
||||
"userAction": "NONE | APPLIED | REJECTED | APPLIED_LOCALLY | APPLIED_AUTOMATICALLY | null",
|
||||
"failureClassification": "string | null",
|
||||
"taskOutputSummary": "string | null",
|
||||
"suggestedFixReasoning": "string | null",
|
||||
"suggestedFixDescription": "string | null",
|
||||
"suggestedFix": "string | null",
|
||||
"shortLink": "string | null",
|
||||
"couldAutoApplyTasks": "boolean | null",
|
||||
"confidence": "number | null",
|
||||
"confidenceReasoning": "string | null"
|
||||
}
|
||||
```
|
||||
|
||||
**Select Parameter:**
|
||||
|
||||
| Usage | Returns |
|
||||
| --------------- | ----------------------------------------------------------- |
|
||||
| No `select` | Formatted overview (truncated, not recommended for polling) |
|
||||
| Single field | Raw value with pagination for long strings |
|
||||
| Multiple fields | Object with requested field values |
|
||||
|
||||
**Field Sets for Efficient Polling:**
|
||||
|
||||
```yaml
|
||||
WAIT_FIELDS:
|
||||
'cipeUrl,commitSha,cipeStatus'
|
||||
# Minimal fields for detecting new CI Attempt
|
||||
|
||||
LIGHT_FIELDS:
|
||||
'cipeStatus,cipeUrl,branch,commitSha,selfHealingStatus,verificationStatus,userAction,failedTaskIds,verifiedTaskIds,selfHealingEnabled,failureClassification,couldAutoApplyTasks,shortLink,confidence,confidenceReasoning'
|
||||
# Status fields for determining actionable state
|
||||
|
||||
HEAVY_FIELDS:
|
||||
'taskOutputSummary,suggestedFix,suggestedFixReasoning,suggestedFixDescription'
|
||||
# Large content fields - fetch only when returning to main agent
|
||||
```
|
||||
|
||||
## Initial Wait
|
||||
|
||||
Before first poll, wait based on context:
|
||||
|
||||
- **Fresh start (no expected CIPE):** Wait 60 seconds to allow CI to start
|
||||
- **Expecting new CIPE:** Wait 30 seconds (action already triggered)
|
||||
|
||||
**IMPORTANT:** Always run sleep in foreground, NOT as background command.
|
||||
|
||||
```bash
|
||||
sleep 60 # or 30 if expecting new CIPE (FOREGROUND, not background)
|
||||
```
|
||||
|
||||
## Two-Phase Operation
|
||||
|
||||
The subagent operates in one of two modes depending on input:
|
||||
|
||||
### Mode 1: Fresh Start (no `expectedCommitSha` or `previousCipeUrl`)
|
||||
|
||||
Normal polling - process whatever CIPE is returned by `ci_information`.
|
||||
|
||||
### Mode 2: Wait-for-New-CIPE (when `expectedCommitSha` or `previousCipeUrl` provided)
|
||||
|
||||
**CRITICAL**: When expecting a new CIPE, the subagent must **completely ignore** the old/stale CIPE. Do NOT process its status, do NOT return actionable states based on it.
|
||||
|
||||
#### Phase A: Wait Mode
|
||||
|
||||
1. Start a **new-CIPE timeout** timer (default: 30 minutes)
|
||||
2. On each poll of `ci_information`:
|
||||
- Check if CIPE is NEW:
|
||||
- `cipeUrl` differs from `previousCipeUrl` → **new CIPE detected**
|
||||
- `commitSha` matches `expectedCommitSha` → **correct CIPE detected**
|
||||
- If still OLD CIPE: **ignore all status fields**, just wait and poll again
|
||||
- Do NOT return `fix_available`, `ci_success`, etc. based on old CIPE!
|
||||
3. Output wait status (see below)
|
||||
4. If timeout (30 min) reached → return `no_new_cipe`
|
||||
|
||||
#### Phase B: Normal Polling (after new CIPE detected)
|
||||
|
||||
Once new CIPE is detected:
|
||||
|
||||
1. Clear the new-CIPE timeout
|
||||
2. Switch to normal polling mode
|
||||
3. Process the NEW CIPE's status normally
|
||||
4. Return when actionable state reached
|
||||
|
||||
### Wait Mode Output
|
||||
|
||||
While in wait mode, output clearly that you're waiting (not processing):
|
||||
|
||||
```
|
||||
[CI Monitor] ═══════════════════════════════════════════════════════
|
||||
[CI Monitor] WAIT MODE - Expecting new CI Attempt
|
||||
[CI Monitor] Expected SHA: <expectedCommitSha>
|
||||
[CI Monitor] Previous CI Attempt: <previousCipeUrl>
|
||||
[CI Monitor] ═══════════════════════════════════════════════════════
|
||||
|
||||
[CI Monitor] Polling... (elapsed: 0m 30s)
|
||||
[CI Monitor] Still seeing previous CI Attempt (ignoring): <oldCipeUrl>
|
||||
|
||||
[CI Monitor] Polling... (elapsed: 1m 30s)
|
||||
[CI Monitor] Still seeing previous CI Attempt (ignoring): <oldCipeUrl>
|
||||
|
||||
[CI Monitor] Polling... (elapsed: 2m 30s)
|
||||
[CI Monitor] ✓ New CI Attempt detected! URL: <newCipeUrl>, SHA: <newCommitSha>
|
||||
[CI Monitor] Switching to normal polling mode...
|
||||
```
|
||||
|
||||
### Why This Matters (Context Preservation)
|
||||
|
||||
**The problem**: Stale CIPE data can be very large:
|
||||
|
||||
- `taskOutputSummary`: potentially thousands of characters of build/test output
|
||||
- `suggestedFix`: entire patch files
|
||||
- `suggestedFixReasoning`: detailed explanation
|
||||
|
||||
If subagent returns stale CIPE data to main agent, it **pollutes main agent's context** with useless information (we already processed that CIPE). This wastes valuable context window.
|
||||
|
||||
**Without wait mode:**
|
||||
|
||||
1. Poll `ci_information` → get old CIPE with huge data
|
||||
2. Return to main agent with all that stale data
|
||||
3. Main agent's context gets polluted with useless info
|
||||
4. Main agent has to process/ignore it anyway
|
||||
|
||||
**With wait mode:**
|
||||
|
||||
1. Poll `ci_information` → get old CIPE → **ignore it, don't return**
|
||||
2. Keep waiting internally (stale data stays in subagent)
|
||||
3. New CIPE appears → switch to normal mode
|
||||
4. Return to main agent with only the NEW, relevant CIPE data
|
||||
|
||||
## Polling Loop
|
||||
|
||||
### Subagent State Management
|
||||
|
||||
Maintain internal accumulated state across polls:
|
||||
|
||||
```
|
||||
accumulated_state = {}
|
||||
```
|
||||
|
||||
### Call `ci_information` MCP Tool
|
||||
|
||||
**Wait Mode (expecting new CI Attempt):**
|
||||
|
||||
```
|
||||
ci_information({
|
||||
branch: "<branch_name>",
|
||||
select: "cipeUrl,commitSha,cipeStatus"
|
||||
})
|
||||
```
|
||||
|
||||
Only fetch minimal fields needed to detect CI Attempt change. Do NOT fetch heavy fields - stale data wastes context.
|
||||
|
||||
**Normal Mode (processing CI Attempt):**
|
||||
|
||||
```
|
||||
ci_information({
|
||||
branch: "<branch_name>",
|
||||
select: "cipeStatus,cipeUrl,branch,commitSha,selfHealingStatus,verificationStatus,userAction,failedTaskIds,verifiedTaskIds,selfHealingEnabled,failureClassification,couldAutoApplyTasks,shortLink,confidence,confidenceReasoning"
|
||||
})
|
||||
```
|
||||
|
||||
Merge response into `accumulated_state` after each poll.
|
||||
|
||||
### Analyze Response
|
||||
|
||||
**If in Wait Mode** (expecting new CIPE):
|
||||
|
||||
1. Check if CIPE is new (see Two-Phase Operation above)
|
||||
2. If old CIPE → **ignore status**, output wait message, poll again
|
||||
3. If new CIPE → switch to normal mode, continue below
|
||||
|
||||
**If in Normal Mode**:
|
||||
Based on the response, decide whether to **keep polling** or **return to main agent**.
|
||||
|
||||
### Keep Polling When
|
||||
|
||||
Continue polling (with backoff) if ANY of these conditions are true:
|
||||
|
||||
| Condition | Reason |
|
||||
| --------------------------------------- | ---------------------------------------- |
|
||||
| `cipeStatus == 'IN_PROGRESS'` | CI still running |
|
||||
| `cipeStatus == 'NOT_STARTED'` | CI hasn't started yet |
|
||||
| `selfHealingStatus == 'IN_PROGRESS'` | Self-healing agent working |
|
||||
| `selfHealingStatus == 'NOT_STARTED'` | Self-healing not started yet |
|
||||
| `failureClassification == 'FLAKY_TASK'` | Auto-rerun in progress |
|
||||
| `userAction == 'APPLIED_AUTOMATICALLY'` | New CI Attempt spawning after auto-apply |
|
||||
|
||||
When `couldAutoApplyTasks == true`:
|
||||
|
||||
- `verificationStatus` = `NOT_STARTED`, `IN_PROGRESS` → keep polling (verification still in progress)
|
||||
- `verificationStatus` = `COMPLETED` → return `fix_auto_applying` (auto-apply will happen, main agent spawns wait mode subagent)
|
||||
- `verificationStatus` = `FAILED`, `NOT_EXECUTABLE` → return `fix_available` (auto-apply won't happen, needs manual action)
|
||||
|
||||
### Exponential Backoff
|
||||
|
||||
Between polls, wait with exponential backoff:
|
||||
|
||||
| Poll Attempt | Wait Time |
|
||||
| ------------ | ----------------- |
|
||||
| 1st | 60 seconds |
|
||||
| 2nd | 90 seconds |
|
||||
| 3rd+ | 120 seconds (cap) |
|
||||
|
||||
Reset to 60 seconds when state changes significantly.
|
||||
|
||||
**IMPORTANT:** Run sleep in foreground (NOT as background command). Background sleep causes "What should Claude do?" prompts when completed.
|
||||
|
||||
```bash
|
||||
# Example backoff - run in FOREGROUND
|
||||
sleep 60 # First wait
|
||||
sleep 90 # Second wait
|
||||
sleep 120 # Third and subsequent waits (capped)
|
||||
```
|
||||
|
||||
### Fetch Heavy Fields on Actionable State
|
||||
|
||||
Before returning to main agent, fetch heavy fields if the status requires them:
|
||||
|
||||
| Status | Heavy Fields Needed |
|
||||
| ------------------- | ------------------------------------------------------------------------------ |
|
||||
| `ci_success` | None |
|
||||
| `fix_auto_applying` | None |
|
||||
| `fix_available` | `taskOutputSummary,suggestedFix,suggestedFixReasoning,suggestedFixDescription` |
|
||||
| `fix_failed` | `taskOutputSummary` |
|
||||
| `no_fix` | `taskOutputSummary` |
|
||||
| `environment_issue` | None |
|
||||
| `no_new_cipe` | None |
|
||||
| `polling_timeout` | None |
|
||||
| `cipe_canceled` | None |
|
||||
| `cipe_timed_out` | None |
|
||||
|
||||
```
|
||||
# Example: fetching heavy fields for fix_available
|
||||
ci_information({
|
||||
branch: "<branch_name>",
|
||||
select: "taskOutputSummary,suggestedFix,suggestedFixReasoning,suggestedFixDescription"
|
||||
})
|
||||
```
|
||||
|
||||
Merge response into `accumulated_state`, then return merged state to main agent.
|
||||
|
||||
**Pagination:** Heavy string fields return first page only. If `hasMore` indicated, include in return format so main agent knows more content available.
|
||||
|
||||
### Return to Main Agent When
|
||||
|
||||
Return immediately with structured state if ANY of these conditions are true:
|
||||
|
||||
| Status | Condition |
|
||||
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci_success` | `cipeStatus == 'SUCCEEDED'` |
|
||||
| `fix_auto_applying` | `selfHealingStatus == 'COMPLETED'` AND `couldAutoApplyTasks == true` AND `verificationStatus == 'COMPLETED'` |
|
||||
| `fix_available` | `selfHealingStatus == 'COMPLETED'` AND `suggestedFix != null` AND (`couldAutoApplyTasks != true` OR `verificationStatus` in (`FAILED`, `NOT_EXECUTABLE`)) |
|
||||
| `fix_failed` | `selfHealingStatus == 'FAILED'` |
|
||||
| `environment_issue` | `failureClassification == 'ENVIRONMENT_STATE'` |
|
||||
| `no_fix` | `cipeStatus == 'FAILED'` AND (`selfHealingEnabled == false` OR `selfHealingStatus == 'NOT_EXECUTABLE'`) |
|
||||
| `no_new_cipe` | `expectedCommitSha` or `previousCipeUrl` provided, but no new CI Attempt detected after 30 min |
|
||||
| `polling_timeout` | Subagent has been polling for > configured timeout (default 60 min) |
|
||||
| `cipe_canceled` | `cipeStatus == 'CANCELED'` |
|
||||
| `cipe_timed_out` | `cipeStatus == 'TIMED_OUT'` |
|
||||
|
||||
## Subagent Timeout
|
||||
|
||||
Track elapsed time. If you have been polling for more than **60 minutes** (configurable via main agent), return with `status: polling_timeout`.
|
||||
|
||||
## Return Format
|
||||
|
||||
When returning to the main agent, provide a structured response with accumulated state:
|
||||
|
||||
```
|
||||
## CI Monitor Result
|
||||
|
||||
**Status:** <status>
|
||||
**Iterations:** <count>
|
||||
**Elapsed:** <minutes>m <seconds>s
|
||||
|
||||
### CI Attempt Details
|
||||
- **Status:** <cipeStatus>
|
||||
- **URL:** <cipeUrl>
|
||||
- **Branch:** <branch>
|
||||
- **Commit:** <commitSha>
|
||||
- **Failed Tasks:** <failedTaskIds>
|
||||
- **Verified Tasks:** <verifiedTaskIds>
|
||||
|
||||
### Self-Healing Details
|
||||
- **Enabled:** <selfHealingEnabled>
|
||||
- **Status:** <selfHealingStatus>
|
||||
- **Verification:** <verificationStatus>
|
||||
- **User Action:** <userAction>
|
||||
- **Classification:** <failureClassification>
|
||||
- **Confidence:** <confidence>
|
||||
- **Confidence Reasoning:** <confidenceReasoning>
|
||||
|
||||
### Fix Information (if available)
|
||||
- **Short Link:** <shortLink>
|
||||
- **Description:** <suggestedFixDescription>
|
||||
- **Reasoning:** <suggestedFixReasoning>
|
||||
|
||||
### Task Output Summary (first page)
|
||||
<taskOutputSummary>
|
||||
[MORE_CONTENT_AVAILABLE: taskOutputSummary, pageToken: 1]
|
||||
|
||||
### Suggested Fix (first page)
|
||||
<suggestedFix>
|
||||
[MORE_CONTENT_AVAILABLE: suggestedFix, pageToken: 1]
|
||||
```
|
||||
|
||||
### Pagination Indicators
|
||||
|
||||
When a heavy field has more content available, append indicator:
|
||||
|
||||
```
|
||||
[MORE_CONTENT_AVAILABLE: <fieldName>, pageToken: <nextPage>]
|
||||
```
|
||||
|
||||
Main agent can fetch additional pages if needed using:
|
||||
|
||||
```
|
||||
ci_information({ select: "<fieldName>", pageToken: <nextPage> })
|
||||
```
|
||||
|
||||
Fields that may have pagination:
|
||||
|
||||
- `taskOutputSummary` (reverse pagination - page 0 = most recent)
|
||||
- `suggestedFix` (forward pagination - page 0 = start)
|
||||
- `suggestedFixReasoning`
|
||||
|
||||
### Return Format for `no_new_cipe`
|
||||
|
||||
When returning with `status: no_new_cipe`, include additional context:
|
||||
|
||||
```
|
||||
## CI Monitor Result
|
||||
|
||||
**Status:** no_new_cipe
|
||||
**Iterations:** <count>
|
||||
**Elapsed:** <minutes>m <seconds>s
|
||||
|
||||
### Expected CI Attempt Not Found
|
||||
- **Expected Commit SHA:** <expectedCommitSha>
|
||||
- **Previous CI Attempt URL:** <previousCipeUrl>
|
||||
- **Last Seen CI Attempt URL:** <cipeUrl>
|
||||
- **Last Seen Commit SHA:** <commitSha>
|
||||
- **New CI Attempt Timeout:** 30 minutes (exceeded)
|
||||
|
||||
### Likely Cause
|
||||
CI workflow failed before Nx tasks could run (e.g., install step, checkout, auth).
|
||||
Check your CI provider logs for the commit <expectedCommitSha>.
|
||||
|
||||
### Last Known CI Attempt State
|
||||
- **Status:** <cipeStatus>
|
||||
- **Branch:** <branch>
|
||||
```
|
||||
|
||||
## Status Reporting (Verbosity-Controlled)
|
||||
|
||||
Output is controlled by the `verbosity` parameter from the main agent:
|
||||
|
||||
| Level | What to Output |
|
||||
| --------- | ----------------------------------------------------------------- |
|
||||
| `minimal` | No intermediate output. Only return final result when actionable. |
|
||||
| `medium` | Output only on significant state changes (not every poll). |
|
||||
| `verbose` | Output detailed phase information after every poll. |
|
||||
|
||||
### Minimal Verbosity
|
||||
|
||||
No output during polling. Poll silently and return when done.
|
||||
|
||||
### Medium Verbosity (Default)
|
||||
|
||||
Output **only when state changes significantly** to save context tokens:
|
||||
|
||||
- `cipeStatus` changes (e.g., IN_PROGRESS → FAILED)
|
||||
- `selfHealingStatus` changes (e.g., IN_PROGRESS → COMPLETED)
|
||||
- New CI Attempt detected (in wait mode)
|
||||
|
||||
Format: single line, no decorators:
|
||||
|
||||
```
|
||||
[CI Monitor] CI: FAILED | Self-Healing: IN_PROGRESS | Elapsed: 4m
|
||||
```
|
||||
|
||||
### Verbose Verbosity
|
||||
|
||||
Output detailed phase box after every poll:
|
||||
|
||||
```
|
||||
[CI Monitor] ─────────────────────────────────────────────────────
|
||||
[CI Monitor] Iteration <N> | Elapsed: <X>m <Y>s
|
||||
[CI Monitor]
|
||||
[CI Monitor] CI Status: <cipeStatus>
|
||||
[CI Monitor] Self-Healing: <selfHealingStatus>
|
||||
[CI Monitor] Verification: <verificationStatus>
|
||||
[CI Monitor] Classification: <failureClassification>
|
||||
[CI Monitor]
|
||||
[CI Monitor] → <human-readable phase description>
|
||||
[CI Monitor] ─────────────────────────────────────────────────────
|
||||
```
|
||||
|
||||
### Phase Descriptions (for verbose output)
|
||||
|
||||
| Status Combo | Description |
|
||||
| ----------------------------------------------------------------------------------------- | ------------------------------------------- |
|
||||
| `cipeStatus: IN_PROGRESS` | "CI running..." |
|
||||
| `cipeStatus: NOT_STARTED` | "Waiting for CI to start..." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: NOT_STARTED` | "CI failed. Self-healing starting..." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: IN_PROGRESS` | "CI failed. Self-healing generating fix..." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: COMPLETED` + `verificationStatus: IN_PROGRESS` | "Fix generated! Verification running..." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: COMPLETED` + `verificationStatus: COMPLETED` | "Fix ready! Verified successfully." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: COMPLETED` + `verificationStatus: FAILED` | "Fix generated but verification failed." |
|
||||
| `cipeStatus: FAILED` + `selfHealingStatus: FAILED` | "Self-healing could not generate a fix." |
|
||||
| `cipeStatus: SUCCEEDED` | "CI passed!" |
|
||||
|
||||
## Important Notes
|
||||
|
||||
- You do NOT make apply/reject decisions - that's the main agent's job
|
||||
- You do NOT perform git operations
|
||||
- You only poll and report state
|
||||
- Respect the `verbosity` parameter for output (default: medium)
|
||||
- If `ci_information` returns an error, wait and retry (count as failed poll)
|
||||
- Track consecutive failures - if 5 consecutive failures, return with `status: error`
|
||||
- When expecting new CI Attempt, track the 30-minute new-CI-Attempt timeout separately from the main polling timeout
|
||||
@@ -0,0 +1,437 @@
|
||||
---
|
||||
description: Monitor Nx Cloud CI pipeline and handle self-healing fixes automatically. Checks for Nx Cloud connection before starting.
|
||||
argument-hint: '[instructions] [--max-cycles N] [--timeout MINUTES] [--verbosity minimal|medium|verbose] [--branch BRANCH] [--fresh] [--auto-fix-workflow] [--new-cipe-timeout MINUTES]'
|
||||
---
|
||||
|
||||
# CI Monitor Command
|
||||
|
||||
You are the orchestrator for monitoring Nx Cloud CI pipeline executions and handling self-healing fixes. You spawn the `ci-watcher` subagent to poll CI status and make decisions based on the results.
|
||||
|
||||
## Context
|
||||
|
||||
- **Current Branch:** !`git branch --show-current`
|
||||
- **Current Commit:** !`git rev-parse --short HEAD`
|
||||
- **Remote Status:** !`git status -sb | head -1`
|
||||
|
||||
## User Instructions
|
||||
|
||||
$ARGUMENTS
|
||||
|
||||
**Important:** If user provides specific instructions, respect them over default behaviors described below.
|
||||
|
||||
## Configuration Defaults
|
||||
|
||||
| Setting | Default | Description |
|
||||
| ------------------------- | ------------- | ------------------------------------------------------------------- |
|
||||
| `--max-cycles` | 10 | Maximum CIPE cycles before timeout |
|
||||
| `--timeout` | 120 | Maximum duration in minutes |
|
||||
| `--verbosity` | medium | Output level: minimal, medium, verbose |
|
||||
| `--branch` | (auto-detect) | Branch to monitor |
|
||||
| `--subagent-timeout` | 60 | Subagent polling timeout in minutes |
|
||||
| `--fresh` | false | Ignore previous context, start fresh |
|
||||
| `--auto-fix-workflow` | false | Attempt common fixes for pre-CIPE failures (e.g., lockfile updates) |
|
||||
| `--new-cipe-timeout` | 10 | Minutes to wait for new CIPE after action |
|
||||
| `--local-verify-attempts` | 3 | Max local verification + enhance cycles before pushing to CI |
|
||||
|
||||
Parse any overrides from `$ARGUMENTS` and merge with defaults.
|
||||
|
||||
## Nx Cloud Connection Check
|
||||
|
||||
**CRITICAL**: Before starting the monitoring loop, verify the workspace is connected to Nx Cloud.
|
||||
|
||||
### Step 0: Verify Nx Cloud Connection
|
||||
|
||||
1. **Check `nx.json`** at workspace root for `nxCloudId` or `nxCloudAccessToken`
|
||||
2. **If `nx.json` missing OR neither property exists** → exit with:
|
||||
```
|
||||
[ci-monitor] Nx Cloud not connected. Unlock 70% faster CI and auto-fix broken PRs with https://nx.dev/nx-cloud
|
||||
```
|
||||
3. **If connected** → continue to main loop
|
||||
|
||||
## Session Context Behavior
|
||||
|
||||
**Important:** Within a Claude Code session, conversation context persists. If you Ctrl+C to interrupt the monitor and re-run `/ci-monitor`, Claude remembers the previous state and may continue from where it left off.
|
||||
|
||||
- **To continue monitoring:** Just re-run `/ci-monitor` (context is preserved)
|
||||
- **To start fresh:** Use `/ci-monitor --fresh` to ignore previous context
|
||||
- **For a completely clean slate:** Exit Claude Code and restart `claude`
|
||||
|
||||
## Default Behaviors by Status
|
||||
|
||||
The subagent returns with one of the following statuses. This table defines the **default behavior** for each status. User instructions can override any of these.
|
||||
|
||||
| Status | Default Behavior |
|
||||
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci_success` | Exit with success. Log "CI passed successfully!" |
|
||||
| `fix_auto_applying` | Fix will be auto-applied by self-healing. Do NOT call MCP. Record `last_cipe_url`, spawn new subagent in wait mode to poll for new CIPE. |
|
||||
| `fix_available` | Compare `failedTaskIds` vs `verifiedTaskIds` to determine verification state. See **Fix Available Decision Logic** section below. |
|
||||
| `fix_failed` | Self-healing failed to generate fix. Attempt local fix based on `taskOutputSummary`. If successful → commit, push, loop. If not → exit with failure. |
|
||||
| `environment_issue` | Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`. New CIPE spawns automatically. Loop to poll for new CIPE. |
|
||||
| `no_fix` | CI failed, no fix available (self-healing disabled or not executable). Attempt local fix if possible. Otherwise exit with failure. |
|
||||
| `no_new_cipe` | Expected CIPE never spawned (CI workflow likely failed before Nx tasks). Report to user, attempt common fixes if configured, or exit with guidance. |
|
||||
| `polling_timeout` | Subagent polling timeout reached. Exit with timeout. |
|
||||
| `cipe_canceled` | CIPE was canceled. Exit with canceled status. |
|
||||
| `cipe_timed_out` | CIPE timed out. Exit with timeout status. |
|
||||
| `error` | Increment `no_progress_count`. If >= 3 → exit with circuit breaker. Otherwise wait 60s and loop. |
|
||||
|
||||
### Fix Available Decision Logic
|
||||
|
||||
When subagent returns `fix_available`, main agent compares `failedTaskIds` vs `verifiedTaskIds`:
|
||||
|
||||
#### Step 1: Categorize Tasks
|
||||
|
||||
1. **Verified tasks** = tasks in both `failedTaskIds` AND `verifiedTaskIds`
|
||||
2. **Unverified tasks** = tasks in `failedTaskIds` but NOT in `verifiedTaskIds`
|
||||
3. **E2E tasks** = unverified tasks where target contains "e2e" (task format: `<project>:<target>` or `<project>:<target>:<config>`)
|
||||
4. **Verifiable tasks** = unverified tasks that are NOT e2e
|
||||
|
||||
#### Step 2: Determine Path
|
||||
|
||||
| Condition | Path |
|
||||
| --------------------------------------- | ---------------------------------------- |
|
||||
| No unverified tasks (all verified) | Apply via MCP |
|
||||
| Unverified tasks exist, but ALL are e2e | Apply via MCP (treat as verified enough) |
|
||||
| Verifiable tasks exist | Local verification flow |
|
||||
|
||||
#### Step 3a: Apply via MCP (fully/e2e-only verified)
|
||||
|
||||
- Call `update_self_healing_fix({ shortLink, action: "APPLY" })`
|
||||
- Record `last_cipe_url`, spawn subagent in wait mode
|
||||
|
||||
#### Step 3b: Local Verification Flow
|
||||
|
||||
When verifiable (non-e2e) unverified tasks exist:
|
||||
|
||||
1. **Detect package manager:**
|
||||
- `pnpm-lock.yaml` exists → `pnpm nx`
|
||||
- `yarn.lock` exists → `yarn nx`
|
||||
- Otherwise → `npx nx`
|
||||
|
||||
2. **Run verifiable tasks in parallel:**
|
||||
- Spawn `general` subagents to run each task concurrently
|
||||
- Each subagent runs: `<pm> nx run <taskId>`
|
||||
- Collect pass/fail results from all subagents
|
||||
|
||||
3. **Evaluate results:**
|
||||
|
||||
| Result | Action |
|
||||
| ------------------------- | ---------------------------- |
|
||||
| ALL verifiable tasks pass | Apply via MCP |
|
||||
| ANY verifiable task fails | Apply-locally + enhance flow |
|
||||
|
||||
4. **Apply-locally + enhance flow:**
|
||||
- Run `nx apply-locally <shortLink>`
|
||||
- Enhance the code to fix failing tasks
|
||||
- Run failing tasks again to verify fix
|
||||
- If still failing → increment `local_verify_count`, loop back to enhance
|
||||
- If passing → commit and push, record `expected_commit_sha`, spawn subagent in wait mode
|
||||
|
||||
5. **Track attempts** (wraps step 4):
|
||||
- Increment `local_verify_count` after each enhance cycle
|
||||
- If `local_verify_count >= local_verify_attempts` (default: 3):
|
||||
- Get code in commit-able state
|
||||
- Commit and push with message indicating local verification failed
|
||||
- Report to user:
|
||||
```
|
||||
[ci-monitor] Local verification failed after <N> attempts. Pushed to CI for final validation. Failed: <taskIds>
|
||||
```
|
||||
- Record `expected_commit_sha`, spawn subagent in wait mode (let CI be final judge)
|
||||
|
||||
#### Commit Message Format
|
||||
|
||||
```bash
|
||||
git commit -m "fix(<projects>): <brief description>
|
||||
|
||||
Failed tasks: <taskId1>, <taskId2>
|
||||
Local verification: passed|enhanced|failed-pushing-to-ci"
|
||||
```
|
||||
|
||||
### Unverified Fix Flow (No Verification Attempted)
|
||||
|
||||
When `verificationStatus` is `FAILED`, `NOT_EXECUTABLE`, or fix has `couldAutoApplyTasks != true` with no verification:
|
||||
|
||||
- Analyze fix content (`suggestedFix`, `suggestedFixReasoning`, `taskOutputSummary`)
|
||||
- If fix looks correct → apply via MCP
|
||||
- If fix needs enhancement → use Apply Locally + Enhance Flow above
|
||||
- If fix is wrong → reject via MCP, fix from scratch, commit, push
|
||||
|
||||
### Auto-Apply Eligibility
|
||||
|
||||
The `couldAutoApplyTasks` field indicates whether the fix is eligible for automatic application:
|
||||
|
||||
- **`true`**: Fix is eligible for auto-apply. Subagent keeps polling while verification is in progress. Returns `fix_auto_applying` when verified, or `fix_available` if verification fails.
|
||||
- **`false`** or **`null`**: Fix requires manual action (apply via MCP, apply locally, or reject)
|
||||
|
||||
**Key point**: When subagent returns `fix_auto_applying`, do NOT call MCP to apply - self-healing handles it. Just spawn a new subagent in wait mode.
|
||||
|
||||
### Apply vs Reject vs Apply Locally
|
||||
|
||||
- **Apply via MCP**: Calls `update_self_healing_fix({ shortLink, action: "APPLY" })`. Self-healing agent applies the fix in CI and a new CIPE spawns automatically. No local git operations needed.
|
||||
- **Apply Locally**: Runs `nx apply-locally <shortLink>`. Applies the patch to your local working directory and sets state to `APPLIED_LOCALLY`. Use this when you want to enhance the fix before pushing.
|
||||
- **Reject via MCP**: Calls `update_self_healing_fix({ shortLink, action: "REJECT" })`. Marks fix as rejected. Use only when the fix is completely wrong and you'll fix from scratch.
|
||||
|
||||
### Apply Locally + Enhance Flow
|
||||
|
||||
When the fix needs enhancement (use `nx apply-locally`, NOT reject):
|
||||
|
||||
1. Apply the patch locally: `nx apply-locally <shortLink>` (this also updates state to `APPLIED_LOCALLY`)
|
||||
2. Make additional changes as needed
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Reject + Fix From Scratch Flow
|
||||
|
||||
When the fix is completely wrong:
|
||||
|
||||
1. Call MCP to reject: `update_self_healing_fix({ shortLink, action: "REJECT" })`
|
||||
2. Fix the issue from scratch locally
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Environment Issue Handling
|
||||
|
||||
When `failureClassification == 'ENVIRONMENT_STATE'`:
|
||||
|
||||
1. Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`
|
||||
2. New CIPE spawns automatically (no local git operations needed)
|
||||
3. Loop to poll for new CIPE with `previousCipeUrl` set
|
||||
|
||||
### No-New-CIPE Handling
|
||||
|
||||
When `status == 'no_new_cipe'`:
|
||||
|
||||
This means the expected CIPE was never created - CI likely failed before Nx tasks could run.
|
||||
|
||||
1. **Report to user:**
|
||||
|
||||
```
|
||||
[ci-monitor] No CI attempt for <sha> after 10 min. Check CI provider for pre-Nx failures (install, checkout, auth). Last CI attempt: <previousCipeUrl>
|
||||
```
|
||||
|
||||
2. **If user configured auto-fix attempts** (e.g., `--auto-fix-workflow`):
|
||||
- Detect package manager: check for `pnpm-lock.yaml`, `yarn.lock`, `package-lock.json`
|
||||
- Run install to update lockfile:
|
||||
```bash
|
||||
pnpm install # or npm install / yarn install
|
||||
```
|
||||
- If lockfile changed:
|
||||
```bash
|
||||
git add pnpm-lock.yaml # or appropriate lockfile
|
||||
git commit -m "chore: update lockfile"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
- Record new commit SHA, loop to poll with `expectedCommitSha`
|
||||
|
||||
3. **Otherwise:** Exit with `no_new_cipe` status, providing guidance for user to investigate
|
||||
|
||||
## Exit Conditions
|
||||
|
||||
Exit the monitoring loop when ANY of these conditions are met:
|
||||
|
||||
| Condition | Exit Type |
|
||||
| ------------------------------------------- | ---------------- |
|
||||
| CI passes (`cipeStatus == 'SUCCEEDED'`) | Success |
|
||||
| Max CIPE cycles reached | Timeout |
|
||||
| Max duration reached | Timeout |
|
||||
| 3 consecutive no-progress iterations | Circuit breaker |
|
||||
| No fix available and local fix not possible | Failure |
|
||||
| No new CIPE and auto-fix not configured | Pre-CIPE failure |
|
||||
| User cancels | Cancelled |
|
||||
|
||||
## Main Loop
|
||||
|
||||
### Step 1: Initialize Tracking
|
||||
|
||||
```
|
||||
cycle_count = 0
|
||||
start_time = now()
|
||||
no_progress_count = 0
|
||||
local_verify_count = 0
|
||||
last_state = null
|
||||
last_cipe_url = null
|
||||
expected_commit_sha = null
|
||||
```
|
||||
|
||||
### Step 2: Spawn Subagent
|
||||
|
||||
Spawn the `ci-watcher` subagent to poll CI status:
|
||||
|
||||
**Fresh start (first spawn, no expected CIPE):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>."
|
||||
)
|
||||
```
|
||||
|
||||
**After action that triggers new CIPE (wait mode):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>.
|
||||
|
||||
WAIT MODE: A new CIPE should spawn. Ignore old CIPE until new one appears.
|
||||
Expected commit SHA: <expected_commit_sha>
|
||||
Previous CIPE URL: <last_cipe_url>"
|
||||
)
|
||||
```
|
||||
|
||||
### Step 3: Handle Subagent Response
|
||||
|
||||
When subagent returns:
|
||||
|
||||
1. Check the returned status
|
||||
2. Look up default behavior in the table above
|
||||
3. Check if user instructions override the default
|
||||
4. Execute the appropriate action
|
||||
5. **If action expects new CIPE**, update tracking (see Step 3a)
|
||||
6. If action results in looping, go to Step 2
|
||||
|
||||
### Step 3a: Track State for New-CIPE Detection
|
||||
|
||||
After actions that should trigger a new CIPE, record state before looping:
|
||||
|
||||
| Action | What to Track | Subagent Mode |
|
||||
| ----------------------------- | --------------------------------------------- | ------------- |
|
||||
| Fix auto-applying | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply via MCP | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply locally + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Reject + fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Fix failed + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| No fix + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Environment rerun | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| No-new-CIPE + auto-fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
|
||||
**CRITICAL**: When passing `expectedCommitSha` or `last_cipe_url` to the subagent, it enters **wait mode**:
|
||||
|
||||
- Subagent will **completely ignore** the old/stale CIPE
|
||||
- Subagent will only wait for new CIPE to appear
|
||||
- Subagent will NOT return to main agent with stale CIPE data
|
||||
- Once new CIPE detected, subagent switches to normal polling
|
||||
|
||||
**Why wait mode matters for context preservation**: Stale CIPE data can be very large (task output summaries, suggested fix patches, reasoning). If subagent returns this to main agent, it pollutes main agent's context with useless data since we already processed that CIPE. Wait mode keeps stale data in the subagent, never sending it to main agent.
|
||||
|
||||
### Step 4: Progress Tracking
|
||||
|
||||
After each action:
|
||||
|
||||
- If state changed significantly → reset `no_progress_count = 0`
|
||||
- If state unchanged → `no_progress_count++`
|
||||
- On new CI attempt detected → reset `local_verify_count = 0`
|
||||
|
||||
## Status Reporting
|
||||
|
||||
Based on verbosity level:
|
||||
|
||||
| Level | What to Report |
|
||||
| --------- | -------------------------------------------------------------------------- |
|
||||
| `minimal` | Only final result (success/failure/timeout) |
|
||||
| `medium` | State changes + periodic updates ("Cycle N \| Elapsed: Xm \| Status: ...") |
|
||||
| `verbose` | All of medium + full subagent responses, git outputs, MCP responses |
|
||||
|
||||
## User Instruction Examples
|
||||
|
||||
Users can override default behaviors:
|
||||
|
||||
| Instruction | Effect |
|
||||
| ------------------------------------------------ | --------------------------------------------- |
|
||||
| "never auto-apply" | Always prompt before applying any fix |
|
||||
| "always ask before git push" | Prompt before each push |
|
||||
| "reject any fix for e2e tasks" | Auto-reject if `failedTaskIds` contains e2e |
|
||||
| "apply all fixes regardless of verification" | Skip verification check, apply everything |
|
||||
| "if confidence < 70, reject" | Check confidence field before applying |
|
||||
| "run 'nx affected -t typecheck' before applying" | Add local verification step |
|
||||
| "auto-fix workflow failures" | Attempt lockfile updates on pre-CIPE failures |
|
||||
| "wait 45 min for new CIPE" | Override new-CIPE timeout (default: 10 min) |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Action |
|
||||
| ------------------------ | ------------------------------------------------------------------------------------- |
|
||||
| Git rebase conflict | Report to user, exit |
|
||||
| `nx apply-locally` fails | Report to user, attempt manual patch or exit |
|
||||
| MCP tool error | Retry once, if fails report to user |
|
||||
| Subagent spawn failure | Retry once, if fails exit with error |
|
||||
| No new CIPE detected | If `--auto-fix-workflow`, try lockfile update; otherwise report to user with guidance |
|
||||
| Lockfile auto-fix fails | Report to user, exit with guidance to check CI logs |
|
||||
|
||||
## Example Session
|
||||
|
||||
### Example 1: Normal Flow with Self-Healing (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-auth'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, verbosity=medium
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: IN_PROGRESS | Self-Healing: NOT_STARTED | Elapsed: 1m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: IN_PROGRESS | Elapsed: 3m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 5m
|
||||
|
||||
[ci-monitor] Fix available! Verification: COMPLETED
|
||||
[ci-monitor] Applying fix via MCP...
|
||||
[ci-monitor] Fix applied in CI. Waiting for new CI attempt...
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 8m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 2
|
||||
- Total time: 12m 34s
|
||||
- Fixes applied: 1
|
||||
- Result: SUCCESS
|
||||
```
|
||||
|
||||
### Example 2: Pre-CI Failure (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-products'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, auto-fix-workflow=true
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 2m
|
||||
|
||||
[ci-monitor] Applying fix locally, enhancing, and pushing...
|
||||
[ci-monitor] Committed: abc1234
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] Waiting for new CI attempt... (expected SHA: abc1234)
|
||||
[CI Monitor] ⚠️ CI attempt timeout (10 min). Returning no_new_cipe.
|
||||
|
||||
[ci-monitor] Status: no_new_cipe
|
||||
[ci-monitor] --auto-fix-workflow enabled. Attempting lockfile update...
|
||||
[ci-monitor] Lockfile updated. Committed: def5678
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 18m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 3
|
||||
- Total time: 22m 15s
|
||||
- Fixes applied: 1 (self-healing) + 1 (lockfile)
|
||||
- Result: SUCCESS
|
||||
```
|
||||
@@ -0,0 +1,437 @@
|
||||
---
|
||||
name: ci-monitor
|
||||
description: Monitor Nx Cloud CI pipeline and handle self-healing fixes automatically. Checks for Nx Cloud connection before starting.
|
||||
---
|
||||
|
||||
# CI Monitor Command
|
||||
|
||||
You are the orchestrator for monitoring Nx Cloud CI pipeline executions and handling self-healing fixes. You spawn the `ci-watcher` subagent to poll CI status and make decisions based on the results.
|
||||
|
||||
## Context
|
||||
|
||||
- **Current Branch:** !`git branch --show-current`
|
||||
- **Current Commit:** !`git rev-parse --short HEAD`
|
||||
- **Remote Status:** !`git status -sb | head -1`
|
||||
|
||||
## User Instructions
|
||||
|
||||
$ARGUMENTS
|
||||
|
||||
**Important:** If user provides specific instructions, respect them over default behaviors described below.
|
||||
|
||||
## Configuration Defaults
|
||||
|
||||
| Setting | Default | Description |
|
||||
| ------------------------- | ------------- | ------------------------------------------------------------------- |
|
||||
| `--max-cycles` | 10 | Maximum CIPE cycles before timeout |
|
||||
| `--timeout` | 120 | Maximum duration in minutes |
|
||||
| `--verbosity` | medium | Output level: minimal, medium, verbose |
|
||||
| `--branch` | (auto-detect) | Branch to monitor |
|
||||
| `--subagent-timeout` | 60 | Subagent polling timeout in minutes |
|
||||
| `--fresh` | false | Ignore previous context, start fresh |
|
||||
| `--auto-fix-workflow` | false | Attempt common fixes for pre-CIPE failures (e.g., lockfile updates) |
|
||||
| `--new-cipe-timeout` | 10 | Minutes to wait for new CIPE after action |
|
||||
| `--local-verify-attempts` | 3 | Max local verification + enhance cycles before pushing to CI |
|
||||
|
||||
Parse any overrides from `$ARGUMENTS` and merge with defaults.
|
||||
|
||||
## Nx Cloud Connection Check
|
||||
|
||||
**CRITICAL**: Before starting the monitoring loop, verify the workspace is connected to Nx Cloud.
|
||||
|
||||
### Step 0: Verify Nx Cloud Connection
|
||||
|
||||
1. **Check `nx.json`** at workspace root for `nxCloudId` or `nxCloudAccessToken`
|
||||
2. **If `nx.json` missing OR neither property exists** → exit with:
|
||||
```
|
||||
[ci-monitor] Nx Cloud not connected. Unlock 70% faster CI and auto-fix broken PRs with https://nx.dev/nx-cloud
|
||||
```
|
||||
3. **If connected** → continue to main loop
|
||||
|
||||
## Session Context Behavior
|
||||
|
||||
**Important:** Within a Claude Code session, conversation context persists. If you Ctrl+C to interrupt the monitor and re-run `/ci-monitor`, Claude remembers the previous state and may continue from where it left off.
|
||||
|
||||
- **To continue monitoring:** Just re-run `/ci-monitor` (context is preserved)
|
||||
- **To start fresh:** Use `/ci-monitor --fresh` to ignore previous context
|
||||
- **For a completely clean slate:** Exit Claude Code and restart `claude`
|
||||
|
||||
## Default Behaviors by Status
|
||||
|
||||
The subagent returns with one of the following statuses. This table defines the **default behavior** for each status. User instructions can override any of these.
|
||||
|
||||
| Status | Default Behavior |
|
||||
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci_success` | Exit with success. Log "CI passed successfully!" |
|
||||
| `fix_auto_applying` | Fix will be auto-applied by self-healing. Do NOT call MCP. Record `last_cipe_url`, spawn new subagent in wait mode to poll for new CIPE. |
|
||||
| `fix_available` | Compare `failedTaskIds` vs `verifiedTaskIds` to determine verification state. See **Fix Available Decision Logic** section below. |
|
||||
| `fix_failed` | Self-healing failed to generate fix. Attempt local fix based on `taskOutputSummary`. If successful → commit, push, loop. If not → exit with failure. |
|
||||
| `environment_issue` | Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`. New CIPE spawns automatically. Loop to poll for new CIPE. |
|
||||
| `no_fix` | CI failed, no fix available (self-healing disabled or not executable). Attempt local fix if possible. Otherwise exit with failure. |
|
||||
| `no_new_cipe` | Expected CIPE never spawned (CI workflow likely failed before Nx tasks). Report to user, attempt common fixes if configured, or exit with guidance. |
|
||||
| `polling_timeout` | Subagent polling timeout reached. Exit with timeout. |
|
||||
| `cipe_canceled` | CIPE was canceled. Exit with canceled status. |
|
||||
| `cipe_timed_out` | CIPE timed out. Exit with timeout status. |
|
||||
| `error` | Increment `no_progress_count`. If >= 3 → exit with circuit breaker. Otherwise wait 60s and loop. |
|
||||
|
||||
### Fix Available Decision Logic
|
||||
|
||||
When subagent returns `fix_available`, main agent compares `failedTaskIds` vs `verifiedTaskIds`:
|
||||
|
||||
#### Step 1: Categorize Tasks
|
||||
|
||||
1. **Verified tasks** = tasks in both `failedTaskIds` AND `verifiedTaskIds`
|
||||
2. **Unverified tasks** = tasks in `failedTaskIds` but NOT in `verifiedTaskIds`
|
||||
3. **E2E tasks** = unverified tasks where target contains "e2e" (task format: `<project>:<target>` or `<project>:<target>:<config>`)
|
||||
4. **Verifiable tasks** = unverified tasks that are NOT e2e
|
||||
|
||||
#### Step 2: Determine Path
|
||||
|
||||
| Condition | Path |
|
||||
| --------------------------------------- | ---------------------------------------- |
|
||||
| No unverified tasks (all verified) | Apply via MCP |
|
||||
| Unverified tasks exist, but ALL are e2e | Apply via MCP (treat as verified enough) |
|
||||
| Verifiable tasks exist | Local verification flow |
|
||||
|
||||
#### Step 3a: Apply via MCP (fully/e2e-only verified)
|
||||
|
||||
- Call `update_self_healing_fix({ shortLink, action: "APPLY" })`
|
||||
- Record `last_cipe_url`, spawn subagent in wait mode
|
||||
|
||||
#### Step 3b: Local Verification Flow
|
||||
|
||||
When verifiable (non-e2e) unverified tasks exist:
|
||||
|
||||
1. **Detect package manager:**
|
||||
- `pnpm-lock.yaml` exists → `pnpm nx`
|
||||
- `yarn.lock` exists → `yarn nx`
|
||||
- Otherwise → `npx nx`
|
||||
|
||||
2. **Run verifiable tasks in parallel:**
|
||||
- Spawn `general` subagents to run each task concurrently
|
||||
- Each subagent runs: `<pm> nx run <taskId>`
|
||||
- Collect pass/fail results from all subagents
|
||||
|
||||
3. **Evaluate results:**
|
||||
|
||||
| Result | Action |
|
||||
| ------------------------- | ---------------------------- |
|
||||
| ALL verifiable tasks pass | Apply via MCP |
|
||||
| ANY verifiable task fails | Apply-locally + enhance flow |
|
||||
|
||||
4. **Apply-locally + enhance flow:**
|
||||
- Run `nx apply-locally <shortLink>`
|
||||
- Enhance the code to fix failing tasks
|
||||
- Run failing tasks again to verify fix
|
||||
- If still failing → increment `local_verify_count`, loop back to enhance
|
||||
- If passing → commit and push, record `expected_commit_sha`, spawn subagent in wait mode
|
||||
|
||||
5. **Track attempts** (wraps step 4):
|
||||
- Increment `local_verify_count` after each enhance cycle
|
||||
- If `local_verify_count >= local_verify_attempts` (default: 3):
|
||||
- Get code in commit-able state
|
||||
- Commit and push with message indicating local verification failed
|
||||
- Report to user:
|
||||
```
|
||||
[ci-monitor] Local verification failed after <N> attempts. Pushed to CI for final validation. Failed: <taskIds>
|
||||
```
|
||||
- Record `expected_commit_sha`, spawn subagent in wait mode (let CI be final judge)
|
||||
|
||||
#### Commit Message Format
|
||||
|
||||
```bash
|
||||
git commit -m "fix(<projects>): <brief description>
|
||||
|
||||
Failed tasks: <taskId1>, <taskId2>
|
||||
Local verification: passed|enhanced|failed-pushing-to-ci"
|
||||
```
|
||||
|
||||
### Unverified Fix Flow (No Verification Attempted)
|
||||
|
||||
When `verificationStatus` is `FAILED`, `NOT_EXECUTABLE`, or fix has `couldAutoApplyTasks != true` with no verification:
|
||||
|
||||
- Analyze fix content (`suggestedFix`, `suggestedFixReasoning`, `taskOutputSummary`)
|
||||
- If fix looks correct → apply via MCP
|
||||
- If fix needs enhancement → use Apply Locally + Enhance Flow above
|
||||
- If fix is wrong → reject via MCP, fix from scratch, commit, push
|
||||
|
||||
### Auto-Apply Eligibility
|
||||
|
||||
The `couldAutoApplyTasks` field indicates whether the fix is eligible for automatic application:
|
||||
|
||||
- **`true`**: Fix is eligible for auto-apply. Subagent keeps polling while verification is in progress. Returns `fix_auto_applying` when verified, or `fix_available` if verification fails.
|
||||
- **`false`** or **`null`**: Fix requires manual action (apply via MCP, apply locally, or reject)
|
||||
|
||||
**Key point**: When subagent returns `fix_auto_applying`, do NOT call MCP to apply - self-healing handles it. Just spawn a new subagent in wait mode.
|
||||
|
||||
### Apply vs Reject vs Apply Locally
|
||||
|
||||
- **Apply via MCP**: Calls `update_self_healing_fix({ shortLink, action: "APPLY" })`. Self-healing agent applies the fix in CI and a new CIPE spawns automatically. No local git operations needed.
|
||||
- **Apply Locally**: Runs `nx apply-locally <shortLink>`. Applies the patch to your local working directory and sets state to `APPLIED_LOCALLY`. Use this when you want to enhance the fix before pushing.
|
||||
- **Reject via MCP**: Calls `update_self_healing_fix({ shortLink, action: "REJECT" })`. Marks fix as rejected. Use only when the fix is completely wrong and you'll fix from scratch.
|
||||
|
||||
### Apply Locally + Enhance Flow
|
||||
|
||||
When the fix needs enhancement (use `nx apply-locally`, NOT reject):
|
||||
|
||||
1. Apply the patch locally: `nx apply-locally <shortLink>` (this also updates state to `APPLIED_LOCALLY`)
|
||||
2. Make additional changes as needed
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Reject + Fix From Scratch Flow
|
||||
|
||||
When the fix is completely wrong:
|
||||
|
||||
1. Call MCP to reject: `update_self_healing_fix({ shortLink, action: "REJECT" })`
|
||||
2. Fix the issue from scratch locally
|
||||
3. Commit and push:
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix: resolve <failedTaskIds>"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
4. Loop to poll for new CIPE
|
||||
|
||||
### Environment Issue Handling
|
||||
|
||||
When `failureClassification == 'ENVIRONMENT_STATE'`:
|
||||
|
||||
1. Call MCP to request rerun: `update_self_healing_fix({ shortLink, action: "RERUN_ENVIRONMENT_STATE" })`
|
||||
2. New CIPE spawns automatically (no local git operations needed)
|
||||
3. Loop to poll for new CIPE with `previousCipeUrl` set
|
||||
|
||||
### No-New-CIPE Handling
|
||||
|
||||
When `status == 'no_new_cipe'`:
|
||||
|
||||
This means the expected CIPE was never created - CI likely failed before Nx tasks could run.
|
||||
|
||||
1. **Report to user:**
|
||||
|
||||
```
|
||||
[ci-monitor] No CI attempt for <sha> after 10 min. Check CI provider for pre-Nx failures (install, checkout, auth). Last CI attempt: <previousCipeUrl>
|
||||
```
|
||||
|
||||
2. **If user configured auto-fix attempts** (e.g., `--auto-fix-workflow`):
|
||||
- Detect package manager: check for `pnpm-lock.yaml`, `yarn.lock`, `package-lock.json`
|
||||
- Run install to update lockfile:
|
||||
```bash
|
||||
pnpm install # or npm install / yarn install
|
||||
```
|
||||
- If lockfile changed:
|
||||
```bash
|
||||
git add pnpm-lock.yaml # or appropriate lockfile
|
||||
git commit -m "chore: update lockfile"
|
||||
git push origin $(git branch --show-current)
|
||||
```
|
||||
- Record new commit SHA, loop to poll with `expectedCommitSha`
|
||||
|
||||
3. **Otherwise:** Exit with `no_new_cipe` status, providing guidance for user to investigate
|
||||
|
||||
## Exit Conditions
|
||||
|
||||
Exit the monitoring loop when ANY of these conditions are met:
|
||||
|
||||
| Condition | Exit Type |
|
||||
| ------------------------------------------- | ---------------- |
|
||||
| CI passes (`cipeStatus == 'SUCCEEDED'`) | Success |
|
||||
| Max CIPE cycles reached | Timeout |
|
||||
| Max duration reached | Timeout |
|
||||
| 3 consecutive no-progress iterations | Circuit breaker |
|
||||
| No fix available and local fix not possible | Failure |
|
||||
| No new CIPE and auto-fix not configured | Pre-CIPE failure |
|
||||
| User cancels | Cancelled |
|
||||
|
||||
## Main Loop
|
||||
|
||||
### Step 1: Initialize Tracking
|
||||
|
||||
```
|
||||
cycle_count = 0
|
||||
start_time = now()
|
||||
no_progress_count = 0
|
||||
local_verify_count = 0
|
||||
last_state = null
|
||||
last_cipe_url = null
|
||||
expected_commit_sha = null
|
||||
```
|
||||
|
||||
### Step 2: Spawn Subagent
|
||||
|
||||
Spawn the `ci-watcher` subagent to poll CI status:
|
||||
|
||||
**Fresh start (first spawn, no expected CIPE):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>."
|
||||
)
|
||||
```
|
||||
|
||||
**After action that triggers new CIPE (wait mode):**
|
||||
|
||||
```
|
||||
Task(
|
||||
agent: "ci-watcher",
|
||||
prompt: "Monitor CI for branch '<branch>'.
|
||||
Subagent timeout: <subagent-timeout> minutes.
|
||||
New-CIPE timeout: <new-cipe-timeout> minutes.
|
||||
Verbosity: <verbosity>.
|
||||
|
||||
WAIT MODE: A new CIPE should spawn. Ignore old CIPE until new one appears.
|
||||
Expected commit SHA: <expected_commit_sha>
|
||||
Previous CIPE URL: <last_cipe_url>"
|
||||
)
|
||||
```
|
||||
|
||||
### Step 3: Handle Subagent Response
|
||||
|
||||
When subagent returns:
|
||||
|
||||
1. Check the returned status
|
||||
2. Look up default behavior in the table above
|
||||
3. Check if user instructions override the default
|
||||
4. Execute the appropriate action
|
||||
5. **If action expects new CIPE**, update tracking (see Step 3a)
|
||||
6. If action results in looping, go to Step 2
|
||||
|
||||
### Step 3a: Track State for New-CIPE Detection
|
||||
|
||||
After actions that should trigger a new CIPE, record state before looping:
|
||||
|
||||
| Action | What to Track | Subagent Mode |
|
||||
| ----------------------------- | --------------------------------------------- | ------------- |
|
||||
| Fix auto-applying | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply via MCP | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| Apply locally + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Reject + fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Fix failed + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| No fix + local fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
| Environment rerun | `last_cipe_url = current cipeUrl` | Wait mode |
|
||||
| No-new-CIPE + auto-fix + push | `expected_commit_sha = $(git rev-parse HEAD)` | Wait mode |
|
||||
|
||||
**CRITICAL**: When passing `expectedCommitSha` or `last_cipe_url` to the subagent, it enters **wait mode**:
|
||||
|
||||
- Subagent will **completely ignore** the old/stale CIPE
|
||||
- Subagent will only wait for new CIPE to appear
|
||||
- Subagent will NOT return to main agent with stale CIPE data
|
||||
- Once new CIPE detected, subagent switches to normal polling
|
||||
|
||||
**Why wait mode matters for context preservation**: Stale CIPE data can be very large (task output summaries, suggested fix patches, reasoning). If subagent returns this to main agent, it pollutes main agent's context with useless data since we already processed that CIPE. Wait mode keeps stale data in the subagent, never sending it to main agent.
|
||||
|
||||
### Step 4: Progress Tracking
|
||||
|
||||
After each action:
|
||||
|
||||
- If state changed significantly → reset `no_progress_count = 0`
|
||||
- If state unchanged → `no_progress_count++`
|
||||
- On new CI attempt detected → reset `local_verify_count = 0`
|
||||
|
||||
## Status Reporting
|
||||
|
||||
Based on verbosity level:
|
||||
|
||||
| Level | What to Report |
|
||||
| --------- | -------------------------------------------------------------------------- |
|
||||
| `minimal` | Only final result (success/failure/timeout) |
|
||||
| `medium` | State changes + periodic updates ("Cycle N \| Elapsed: Xm \| Status: ...") |
|
||||
| `verbose` | All of medium + full subagent responses, git outputs, MCP responses |
|
||||
|
||||
## User Instruction Examples
|
||||
|
||||
Users can override default behaviors:
|
||||
|
||||
| Instruction | Effect |
|
||||
| ------------------------------------------------ | --------------------------------------------- |
|
||||
| "never auto-apply" | Always prompt before applying any fix |
|
||||
| "always ask before git push" | Prompt before each push |
|
||||
| "reject any fix for e2e tasks" | Auto-reject if `failedTaskIds` contains e2e |
|
||||
| "apply all fixes regardless of verification" | Skip verification check, apply everything |
|
||||
| "if confidence < 70, reject" | Check confidence field before applying |
|
||||
| "run 'nx affected -t typecheck' before applying" | Add local verification step |
|
||||
| "auto-fix workflow failures" | Attempt lockfile updates on pre-CIPE failures |
|
||||
| "wait 45 min for new CIPE" | Override new-CIPE timeout (default: 10 min) |
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Action |
|
||||
| ------------------------ | ------------------------------------------------------------------------------------- |
|
||||
| Git rebase conflict | Report to user, exit |
|
||||
| `nx apply-locally` fails | Report to user, attempt manual patch or exit |
|
||||
| MCP tool error | Retry once, if fails report to user |
|
||||
| Subagent spawn failure | Retry once, if fails exit with error |
|
||||
| No new CIPE detected | If `--auto-fix-workflow`, try lockfile update; otherwise report to user with guidance |
|
||||
| Lockfile auto-fix fails | Report to user, exit with guidance to check CI logs |
|
||||
|
||||
## Example Session
|
||||
|
||||
### Example 1: Normal Flow with Self-Healing (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-auth'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, verbosity=medium
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: IN_PROGRESS | Self-Healing: NOT_STARTED | Elapsed: 1m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: IN_PROGRESS | Elapsed: 3m
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 5m
|
||||
|
||||
[ci-monitor] Fix available! Verification: COMPLETED
|
||||
[ci-monitor] Applying fix via MCP...
|
||||
[ci-monitor] Fix applied in CI. Waiting for new CI attempt...
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 8m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 2
|
||||
- Total time: 12m 34s
|
||||
- Fixes applied: 1
|
||||
- Result: SUCCESS
|
||||
```
|
||||
|
||||
### Example 2: Pre-CI Failure (medium verbosity)
|
||||
|
||||
```
|
||||
[ci-monitor] Starting CI monitor for branch 'feature/add-products'
|
||||
[ci-monitor] Config: max-cycles=5, timeout=120m, auto-fix-workflow=true
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] CI attempt: FAILED | Self-Healing: COMPLETED | Elapsed: 2m
|
||||
|
||||
[ci-monitor] Applying fix locally, enhancing, and pushing...
|
||||
[ci-monitor] Committed: abc1234
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] Waiting for new CI attempt... (expected SHA: abc1234)
|
||||
[CI Monitor] ⚠️ CI attempt timeout (10 min). Returning no_new_cipe.
|
||||
|
||||
[ci-monitor] Status: no_new_cipe
|
||||
[ci-monitor] --auto-fix-workflow enabled. Attempting lockfile update...
|
||||
[ci-monitor] Lockfile updated. Committed: def5678
|
||||
|
||||
[ci-monitor] Spawning subagent to poll CI status...
|
||||
[CI Monitor] New CI attempt detected!
|
||||
[CI Monitor] CI attempt: SUCCEEDED | Elapsed: 18m
|
||||
|
||||
[ci-monitor] CI passed successfully!
|
||||
|
||||
[ci-monitor] Summary:
|
||||
- Total cycles: 3
|
||||
- Total time: 22m 15s
|
||||
- Fixes applied: 1 (self-healing) + 1 (lockfile)
|
||||
- Result: SUCCESS
|
||||
```
|
||||
@@ -0,0 +1,228 @@
|
||||
---
|
||||
name: nx-generate
|
||||
description: Generate code using nx generators. USE WHEN scaffolding code or transforming existing code - for example creating libraries or applications, or anything else that is boilerplate code or automates repetitive tasks. ALWAYS use this first when generating code with Nx instead of calling MCP tools or running nx generate immediately.
|
||||
---
|
||||
|
||||
# Run Nx Generator
|
||||
|
||||
Nx generators are powerful tools that scaffold projects, make automated code migrations or automate repetitive tasks in a monorepo. They ensure consistency across the codebase and reduce boilerplate work.
|
||||
|
||||
This skill applies when the user wants to:
|
||||
|
||||
- Create new projects like libraries or applications
|
||||
- Scaffold features or boilerplate code
|
||||
- Run workspace-specific or custom generators
|
||||
- Do anything else that an nx generator exists for
|
||||
|
||||
## Generator Discovery Flow
|
||||
|
||||
### Step 1: List Available Generators
|
||||
|
||||
Use the Nx CLI to discover available generators:
|
||||
|
||||
- List all generators for a plugin: `npx nx list @nx/react`
|
||||
- View available plugins: `npx nx list`
|
||||
|
||||
This includes:
|
||||
|
||||
- Plugin generators (e.g., `@nx/react:library`, `@nx/js:library`)
|
||||
- Local workspace generators (defined in the repo's own plugins)
|
||||
|
||||
### Step 2: Match Generator to User Request
|
||||
|
||||
Based on the user's request, identify which generator(s) could fulfill their needs. Consider:
|
||||
|
||||
- What artifact type they want to create (library, application, etc.)
|
||||
- Which framework or technology stack is relevant
|
||||
- Whether they mentioned specific generator names
|
||||
|
||||
**IMPORTANT**: When both a local workspace generator and an external plugin generator could satisfy the request, **always prefer the local workspace generator**. Local generators are customized for the specific repo's patterns and conventions.
|
||||
|
||||
It's possible that the user request is something that no Nx generator exists for whatsoever. In this case, you can stop using this skill and try to help the user another way. HOWEVER, the burden of proof for this is high. Before aborting, carefully consider each and every generator that's available. Look into details for any that could be related in any way before making this decision.
|
||||
|
||||
## Pre-Execution Checklist
|
||||
|
||||
Before running any generator, complete these steps:
|
||||
|
||||
### 1. Fetch Generator Schema
|
||||
|
||||
Use the `--help` flag to understand all available options:
|
||||
|
||||
```bash
|
||||
npx nx g @nx/react:library --help
|
||||
```
|
||||
|
||||
Pay attention to:
|
||||
|
||||
- Required options that must be provided
|
||||
- Optional options that may be relevant to the user's request
|
||||
- Default values that might need to be overridden
|
||||
|
||||
### 2. Read Generator Source Code
|
||||
|
||||
Understanding what the generator actually does helps you:
|
||||
|
||||
- Know what files will be created/modified
|
||||
- Understand any side effects (updating configs, installing deps, etc.)
|
||||
- Identify options that might not be obvious from the schema
|
||||
|
||||
To find generator source code:
|
||||
|
||||
- For plugin generators: Use `node -e "console.log(require.resolve('@nx/<plugin>/generators.json'));"` to find the generators.json, then locate the source from there
|
||||
- If that fails, read directly from `node_modules/<plugin>/generators.json`
|
||||
- For local generators: They are typically in `tools/generators/` or a local plugin directory. You can search the repo for the generator name to find it.
|
||||
|
||||
### 2.5 Reevaluate if the generator is right
|
||||
|
||||
Once you have built up an understanding of what the selected generator does, reconsider: Is this the right generator to service the user request?
|
||||
If not, it's okay to go back to the Generator Discovery Flow and select a different generator before proceeding. If you do, make sure to go through the entire pre-execution checklist once more.
|
||||
|
||||
### 3. Understand Repo Context
|
||||
|
||||
Before generating, examine the target area of the codebase:
|
||||
|
||||
- Look at similar existing artifacts (other libraries, applications, etc.)
|
||||
- Identify patterns and conventions used in the repo
|
||||
- Note naming conventions, file structures, and configuration patterns
|
||||
- Try to match these patterns when configuring the generator
|
||||
|
||||
For example, if similar libraries are using a specific test runner, build tool or linter, try to match that if possible.
|
||||
If projects or other artifacts are organized with a specific naming convention, try to match it.
|
||||
|
||||
### 4. Validate Required Options
|
||||
|
||||
Ensure all required options have values:
|
||||
|
||||
- Map the user's request to generator options
|
||||
- Infer values from context where possible
|
||||
- Ask the user for any critical missing information
|
||||
|
||||
## Execution
|
||||
|
||||
Keep in mind that you might have to prefix things with npx/pnpx/yarn if the user doesn't have nx installed globally.
|
||||
Many generators will behave differently based on where they are executed. For example, first-party nx library generators use the cwd to determine the directory that the library should be placed in. This is highly important.
|
||||
|
||||
### Consider Dry-Run (Optional)
|
||||
|
||||
Running with `--dry-run` first is strongly encouraged but not mandatory. Use your judgment:
|
||||
|
||||
- For complex generators or unfamiliar territory: do a dry-run first
|
||||
- For simple, well-understood generators: may proceed directly
|
||||
- Dry-run shows file names and created/deleted/modified markers, but not content
|
||||
- There are cases where a generator does not support dry-run (for example if it had to install an npm package) - in that case --dry-run might fail. Don't be discouraged but simply move on to running the generator for real and iterating from there.
|
||||
|
||||
### Running the Generator
|
||||
|
||||
Execute the generator with:
|
||||
|
||||
```bash
|
||||
nx generate <generator-name> <options> --no-interactive
|
||||
```
|
||||
|
||||
**CRITICAL**: Always include `--no-interactive` to prevent prompts that would hang the execution.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
nx generate @nx/react:library --name=my-utils --no-interactive
|
||||
```
|
||||
|
||||
### Handling Generator Failures
|
||||
|
||||
If the generator fails:
|
||||
|
||||
1. **Diagnose the error** - Read the error message carefully
|
||||
2. **Identify the cause** - Missing options, invalid values, conflicts, etc.
|
||||
3. **Attempt automatic fix** - Adjust options or resolve conflicts
|
||||
4. **Retry** - Run the generator again with corrected options
|
||||
|
||||
Common failure reasons:
|
||||
|
||||
- Missing required options
|
||||
- Invalid option values
|
||||
- Conflicting with existing files
|
||||
- Missing dependencies
|
||||
- Generator doesn't support certain flag combinations
|
||||
|
||||
## Post-Generation
|
||||
|
||||
### 1. Modify Generated Code (If Needed)
|
||||
|
||||
Generators provide a starting point, but the output may need adjustment to match the user's specific requirements:
|
||||
|
||||
- Add or modify functionality as requested
|
||||
- Adjust imports, exports, or configurations
|
||||
- Integrate with existing code patterns in the repo
|
||||
|
||||
### 2. Format Code
|
||||
|
||||
Run formatting on all generated/modified files:
|
||||
|
||||
```bash
|
||||
nx format --fix
|
||||
```
|
||||
|
||||
Languages other than javascript/typescript might need other formatting invocations too.
|
||||
|
||||
### 3. Run Verification
|
||||
|
||||
Verify that the generated code works correctly. What this looks like will vary depending on the type of generator and the targets available.
|
||||
If the generator created a new project, run its targets directly
|
||||
Use your best judgement to determine what needs to be verified.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
nx lint <new-project>
|
||||
nx test <new-project>
|
||||
nx build <new-project>
|
||||
```
|
||||
|
||||
### 4. Handle Verification Failures
|
||||
|
||||
When verification fails:
|
||||
|
||||
**If scope is manageable** (a few lint errors, minor type issues):
|
||||
|
||||
- Fix the issues
|
||||
- Re-run verification to confirm
|
||||
|
||||
**If issues are extensive** (many errors, complex problems):
|
||||
|
||||
- Attempt simple, obvious fixes first
|
||||
- If still failing, escalate to the user with:
|
||||
- Description of what was generated
|
||||
- What verification is failing
|
||||
- What you've attempted to fix
|
||||
- Remaining issues that need user input
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Generator Failures
|
||||
|
||||
- Check the error message for specific causes
|
||||
- Verify all required options are provided
|
||||
- Check for conflicts with existing files
|
||||
- Ensure the generator name and options are correct
|
||||
|
||||
### Missing Options
|
||||
|
||||
- Consult the generator schema for required fields
|
||||
- Infer values from context when reasonable
|
||||
- Ask the user for values that cannot be inferred
|
||||
|
||||
## Key Principles
|
||||
|
||||
1. **Local generators first** - Always prefer workspace/local generators over external plugin generators when both could work
|
||||
|
||||
2. **Understand before running** - Read both the schema AND the source code to fully understand what will happen
|
||||
|
||||
3. **No prompts** - Always use `--no-interactive` to prevent hanging
|
||||
|
||||
4. **Generators are starting points** - Modify the output as needed to fully satisfy the user's requirements
|
||||
|
||||
5. **Verify changes work** - Don't just generate; ensure the code builds, lints, and tests pass
|
||||
|
||||
6. **Be proactive about fixes** - Don't just report errors; attempt to resolve them automatically when possible
|
||||
|
||||
7. **Match repo patterns** - Study existing similar code in the repo and match its conventions
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
name: nx-plugins
|
||||
description: Find and add Nx plugins. USE WHEN user wants to discover available plugins, install a new plugin, or add support for a specific framework or technology to the workspace.
|
||||
---
|
||||
|
||||
## Finding and Installing new plugins
|
||||
|
||||
- List plugins: `pnpm nx list`
|
||||
- Install plugins `pnpm nx add <plugin>`. Example: `pnpm nx add @nx/react`.
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
name: nx-run-tasks
|
||||
description: Helps with running tasks in an Nx workspace. USE WHEN the user wants to execute build, test, lint, serve, or run any other tasks defined in the workspace.
|
||||
---
|
||||
|
||||
You can run tasks with Nx in the following way.
|
||||
|
||||
Keep in mind that you might have to prefix things with npx/pnpx/yarn if the user doesn't have nx installed globally. Look at the package.json or lockfile to determine which package manager is in use.
|
||||
|
||||
For more details on any command, run it with `--help` (e.g. `nx run-many --help`, `nx affected --help`).
|
||||
|
||||
## Understand which tasks can be run
|
||||
|
||||
You can check those via `nx show project <projectname> --json`, for example `nx show project myapp --json`. It contains a `targets` section which has information about targets that can be run. You can also just look at the `package.json` scripts or `project.json` targets, but you might miss out on inferred tasks by Nx plugins.
|
||||
|
||||
## Run a single task
|
||||
|
||||
```
|
||||
nx run <project>:<task>
|
||||
```
|
||||
|
||||
where `project` is the project name defined in `package.json` or `project.json` (if present).
|
||||
|
||||
## Run multiple tasks
|
||||
|
||||
```
|
||||
nx run-many -t build test lint typecheck
|
||||
```
|
||||
|
||||
You can pass a `-p` flag to filter to specific projects, otherwise it runs on all projects. You can also use `--exclude` to exclude projects, and `--parallel` to control the number of parallel processes (default is 3).
|
||||
|
||||
Examples:
|
||||
|
||||
- `nx run-many -t test -p proj1 proj2` — test specific projects
|
||||
- `nx run-many -t test --projects=*-app --exclude=excluded-app` — test projects matching a pattern
|
||||
- `nx run-many -t test --projects=tag:api-*` — test projects by tag
|
||||
|
||||
## Run tasks for affected projects
|
||||
|
||||
Use `nx affected` to only run tasks on projects that have been changed and projects that depend on changed projects. This is especially useful in CI and for large workspaces.
|
||||
|
||||
```
|
||||
nx affected -t build test lint
|
||||
```
|
||||
|
||||
By default it compares against the base branch. You can customize this:
|
||||
|
||||
- `nx affected -t test --base=main --head=HEAD` — compare against a specific base and head
|
||||
- `nx affected -t test --files=libs/mylib/src/index.ts` — specify changed files directly
|
||||
|
||||
## Useful flags
|
||||
|
||||
These flags work with `run`, `run-many`, and `affected`:
|
||||
|
||||
- `--skipNxCache` — rerun tasks even when results are cached
|
||||
- `--verbose` — print additional information such as stack traces
|
||||
- `--nxBail` — stop execution after the first failed task
|
||||
- `--configuration=<name>` — use a specific configuration (e.g. `production`)
|
||||
@@ -0,0 +1,186 @@
|
||||
---
|
||||
name: nx-workspace
|
||||
description: "Explore and understand Nx workspaces. USE WHEN answering any questions about the nx workspace, the projects in it or tasks to run. EXAMPLES: 'What projects are in this workspace?', 'How is project X configured?', 'What targets can I run?', 'What's affected by my changes?', 'Which projects depend on library Y?', or any questions about Nx workspace structure, project configuration, or available tasks."
|
||||
---
|
||||
|
||||
# Nx Workspace Exploration
|
||||
|
||||
This skill provides read-only exploration of Nx workspaces. Use it to understand workspace structure, project configuration, available targets, and dependencies.
|
||||
|
||||
Keep in mind that you might have to prefix commands with `npx`/`pnpx`/`yarn` if nx isn't installed globally. Check the lockfile to determine the package manager in use.
|
||||
|
||||
## Listing Projects
|
||||
|
||||
Use `nx show projects` to list projects in the workspace.
|
||||
|
||||
```bash
|
||||
# List all projects
|
||||
nx show projects
|
||||
|
||||
# Filter by pattern (glob)
|
||||
nx show projects --projects "apps/*"
|
||||
nx show projects --projects "shared-*"
|
||||
|
||||
# Filter by project type
|
||||
nx show projects --type app
|
||||
nx show projects --type lib
|
||||
nx show projects --type e2e
|
||||
|
||||
# Filter by target (projects that have a specific target)
|
||||
nx show projects --withTarget build
|
||||
nx show projects --withTarget e2e
|
||||
|
||||
# Find affected projects (changed since base branch)
|
||||
nx show projects --affected
|
||||
nx show projects --affected --base=main
|
||||
nx show projects --affected --type app
|
||||
|
||||
# Combine filters
|
||||
nx show projects --type lib --withTarget test
|
||||
nx show projects --affected --exclude="*-e2e"
|
||||
|
||||
# Output as JSON
|
||||
nx show projects --json
|
||||
```
|
||||
|
||||
## Project Configuration
|
||||
|
||||
Use `nx show project <name> --json` to get the full resolved configuration for a project.
|
||||
|
||||
**Important**: Do NOT read `project.json` directly - it only contains partial configuration. The `nx show project` command returns the full resolved config including inferred targets from plugins.
|
||||
|
||||
You can read the full project schema at `node_modules/nx/schemas/project-schema.json` to understand nx project configuration options.
|
||||
|
||||
```bash
|
||||
# Get full project configuration
|
||||
nx show project my-app --json
|
||||
|
||||
# Extract specific parts from the JSON
|
||||
nx show project my-app --json | jq '.targets'
|
||||
nx show project my-app --json | jq '.targets.build'
|
||||
nx show project my-app --json | jq '.targets | keys'
|
||||
|
||||
|
||||
# Check project metadata
|
||||
nx show project my-app --json | jq '{name, root, sourceRoot, projectType, tags}'
|
||||
```
|
||||
|
||||
## Target Information
|
||||
|
||||
Targets define what tasks can be run on a project.
|
||||
|
||||
```bash
|
||||
# List all targets for a project
|
||||
nx show project my-app --json | jq '.targets | keys'
|
||||
|
||||
# Get full target configuration
|
||||
nx show project my-app --json | jq '.targets.build'
|
||||
|
||||
# Check target executor/command
|
||||
nx show project my-app --json | jq '.targets.build.executor'
|
||||
nx show project my-app --json | jq '.targets.build.command'
|
||||
|
||||
# View target options
|
||||
nx show project my-app --json | jq '.targets.build.options'
|
||||
|
||||
# Check target inputs/outputs (for caching)
|
||||
nx show project my-app --json | jq '.targets.build.inputs'
|
||||
nx show project my-app --json | jq '.targets.build.outputs'
|
||||
|
||||
# Find projects with a specific target
|
||||
nx show projects --withTarget serve
|
||||
nx show projects --withTarget e2e
|
||||
```
|
||||
|
||||
## Workspace Configuration
|
||||
|
||||
Read `nx.json` directly for workspace-level configuration.
|
||||
You can read the full project schema at `node_modules/nx/schemas/nx-schema.json` to understand nx project configuration options.
|
||||
|
||||
```bash
|
||||
# Read the full nx.json
|
||||
cat nx.json
|
||||
|
||||
# Or use jq for specific sections
|
||||
cat nx.json | jq '.targetDefaults'
|
||||
cat nx.json | jq '.namedInputs'
|
||||
cat nx.json | jq '.plugins'
|
||||
cat nx.json | jq '.generators'
|
||||
```
|
||||
|
||||
Key nx.json sections:
|
||||
|
||||
- `targetDefaults` - Default configuration applied to all targets of a given name
|
||||
- `namedInputs` - Reusable input definitions for caching
|
||||
- `plugins` - Nx plugins and their configuration
|
||||
- ...and much more, read the schema or nx.json for details
|
||||
|
||||
## Affected Projects
|
||||
|
||||
Find projects affected by changes in the current branch.
|
||||
|
||||
```bash
|
||||
# Affected since base branch (auto-detected)
|
||||
nx show projects --affected
|
||||
|
||||
# Affected with explicit base
|
||||
nx show projects --affected --base=main
|
||||
nx show projects --affected --base=origin/main
|
||||
|
||||
# Affected between two commits
|
||||
nx show projects --affected --base=abc123 --head=def456
|
||||
|
||||
# Affected apps only
|
||||
nx show projects --affected --type app
|
||||
|
||||
# Affected excluding e2e projects
|
||||
nx show projects --affected --exclude="*-e2e"
|
||||
|
||||
# Affected by uncommitted changes
|
||||
nx show projects --affected --uncommitted
|
||||
|
||||
# Affected by untracked files
|
||||
nx show projects --affected --untracked
|
||||
```
|
||||
|
||||
## Common Exploration Patterns
|
||||
|
||||
### "What's in this workspace?"
|
||||
|
||||
```bash
|
||||
nx show projects
|
||||
nx show projects --type app
|
||||
nx show projects --type lib
|
||||
```
|
||||
|
||||
### "How do I build/test/lint project X?"
|
||||
|
||||
```bash
|
||||
nx show project X --json | jq '.targets | keys'
|
||||
nx show project X --json | jq '.targets.build'
|
||||
```
|
||||
|
||||
### "What depends on library Y?"
|
||||
|
||||
```bash
|
||||
# Find projects that may depend on Y by searching for imports
|
||||
# (Nx doesn't have a direct "dependents" command via CLI)
|
||||
grep -r "from '@myorg/Y'" --include="*.ts" --include="*.tsx" apps/ libs/
|
||||
```
|
||||
|
||||
### "What configuration options are available?"
|
||||
|
||||
```bash
|
||||
cat node_modules/nx/schemas/nx-schema.json | jq '.properties | keys'
|
||||
cat node_modules/nx/schemas/project-schema.json | jq '.properties | keys'
|
||||
```
|
||||
|
||||
### "Why is project X affected?"
|
||||
|
||||
```bash
|
||||
# Check what files changed
|
||||
git diff --name-only main
|
||||
|
||||
# See which project owns those files
|
||||
nx show project X --json | jq '.root'
|
||||
```
|
||||
@@ -206,18 +206,8 @@ Fixes #ISSUE_NUMBER
|
||||
|
||||
- When running tasks (for example build, lint, test, e2e, etc.), always prefer running the task through `nx` (i.e. `nx run`, `nx run-many`, `nx affected`) instead of using the underlying tooling directly
|
||||
- You have access to the Nx MCP server and its tools, use them to help the user
|
||||
- When answering questions about the repository, use the `nx_workspace` tool first to gain an understanding of the workspace architecture where applicable.
|
||||
- When working in individual projects, use the `nx_project_details` mcp tool to analyze and understand the specific project structure and dependencies
|
||||
- For questions around nx configuration, best practices or if you're unsure, use the `nx_docs` tool to get relevant, up-to-date docs. Always use this instead of assuming things about nx configuration
|
||||
- If the user needs help with an Nx configuration or project graph error, use the `nx_workspace` tool to get any errors
|
||||
|
||||
# CI Error Guidelines
|
||||
|
||||
If the user wants help with fixing an error in their CI pipeline, use the following flow:
|
||||
|
||||
- Retrieve the list of current CI Pipeline Executions (CIPEs) using the `nx_cloud_cipe_details` tool
|
||||
- If there are any errors, use the `nx_cloud_fix_cipe_failure` tool to retrieve the logs for a specific task
|
||||
- Use the task logs to see what's wrong and help the user fix their problem. Use the appropriate tools if necessary
|
||||
- Make sure that the problem is fixed by running the task that you passed into the `nx_cloud_fix_cipe_failure` tool
|
||||
- For understanding the workspace structure, projects, or available tasks, use the `/nx-workspace` skill which provides guidance on exploring Nx workspaces
|
||||
- For questions around nx configuration, best practices or if you're unsure, use the `nx_docs` MCP tool to get relevant, up-to-date docs. Always use this instead of assuming things about nx configuration
|
||||
- For Nx plugin best practices, check `node_modules/@nx/<plugin>/PLUGIN.md`. Not all plugins have this file - proceed without it if unavailable.
|
||||
|
||||
<!-- nx configuration end-->
|
||||
|
||||
@@ -206,18 +206,8 @@ Fixes #ISSUE_NUMBER
|
||||
|
||||
- When running tasks (for example build, lint, test, e2e, etc.), always prefer running the task through `nx` (i.e. `nx run`, `nx run-many`, `nx affected`) instead of using the underlying tooling directly
|
||||
- You have access to the Nx MCP server and its tools, use them to help the user
|
||||
- When answering questions about the repository, use the `nx_workspace` tool first to gain an understanding of the workspace architecture where applicable.
|
||||
- When working in individual projects, use the `nx_project_details` mcp tool to analyze and understand the specific project structure and dependencies
|
||||
- For questions around nx configuration, best practices or if you're unsure, use the `nx_docs` tool to get relevant, up-to-date docs. Always use this instead of assuming things about nx configuration
|
||||
- If the user needs help with an Nx configuration or project graph error, use the `nx_workspace` tool to get any errors
|
||||
|
||||
# CI Error Guidelines
|
||||
|
||||
If the user wants help with fixing an error in their CI pipeline, use the following flow:
|
||||
|
||||
- Retrieve the list of current CI Pipeline Executions (CIPEs) using the `nx_cloud_cipe_details` tool
|
||||
- If there are any errors, use the `nx_cloud_fix_cipe_failure` tool to retrieve the logs for a specific task
|
||||
- Use the task logs to see what's wrong and help the user fix their problem. Use the appropriate tools if necessary
|
||||
- Make sure that the problem is fixed by running the task that you passed into the `nx_cloud_fix_cipe_failure` tool
|
||||
- For understanding the workspace structure, projects, or available tasks, use the `/nx-workspace` skill which provides guidance on exploring Nx workspaces
|
||||
- For questions around nx configuration, best practices or if you're unsure, use the `nx_docs` MCP tool to get relevant, up-to-date docs. Always use this instead of assuming things about nx configuration
|
||||
- For Nx plugin best practices, check `node_modules/@nx/<plugin>/PLUGIN.md`. Not all plugins have this file - proceed without it if unavailable.
|
||||
|
||||
<!-- nx configuration end-->
|
||||
|
||||
@@ -2,19 +2,10 @@
|
||||
|
||||
We would love for you to contribute to Nx! Read this document to see how to do it.
|
||||
|
||||
## How to Get Started Video
|
||||
|
||||
Watch this 5-minute video:
|
||||
|
||||
<a href="https://www.youtube.com/watch?v=8LCA_4qxc08" target="_blank" rel="noreferrer">
|
||||
<p style="text-align: center;"><img src="./images/how-to-contribute.png" width="600" alt="Nx - How to contribute"></p>
|
||||
</a>
|
||||
|
||||
## Got a Question?
|
||||
|
||||
We are trying to keep GitHub issues for bug reports and feature requests. Using the `nrwl` tag
|
||||
on [Stack Overflow](https://stackoverflow.com/questions/tagged/nrwl) is a much better place to ask general questions
|
||||
about how to use Nx.
|
||||
We are trying to keep GitHub issues for bug reports and feature requests.
|
||||
You can join our [Discord](https://go.nx.dev/community) for general questions and seeking help from others.
|
||||
|
||||
## Found an Issue?
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2017-2025 Narwhal Technologies Inc.
|
||||
Copyright (c) 2017-2026 Narwhal Technologies Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<p style="text-align: center;">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./images/nx-dark.svg">
|
||||
<img alt="Nx - Smart Repos · Fast Builds" src="./images/nx-light.svg" width="100%">
|
||||
<img alt="Nx - Smart Monorepos · Fast Builds" src="./images/nx-light.svg" width="100%">
|
||||
</picture>
|
||||
</p>
|
||||
|
||||
@@ -19,9 +19,7 @@
|
||||
|
||||
<hr>
|
||||
|
||||
# Smart Repos · Fast Builds
|
||||
|
||||
Get to green PRs in half the time. Nx optimizes your builds, scales your CI, and fixes failed PRs. Built for developers and AI agents.
|
||||
# The Monorepo Platform that amplifies both developers and AI agents. Nx optimizes your builds, scales your CI, and fixes failed PRs automatically. Ship in half the time.
|
||||
|
||||
Create a new Nx workspace with
|
||||
|
||||
@@ -58,7 +56,7 @@ Learn more in the [Nx CI docs »](https://nx.dev/ci/getting-started/intro?u
|
||||
- [Our Twitter/X](https://x.com/nxdevtools)
|
||||
|
||||
<p style="text-align: center;"><a href="https://www.youtube.com/@nxdevtools/videos" target="_blank" rel="noreferrer"><img src="./images/nx-courses-and-videos.svg"
|
||||
width="100%" alt="Nx - Smart Repos · Fast Builds"></a></p>
|
||||
width="100%" alt="Nx - Smart Monorepos · Fast Builds"></a></p>
|
||||
|
||||
## Want to help?
|
||||
|
||||
|
||||
@@ -13,3 +13,15 @@ Instead, please report them to the Security Team at security@nrwl.io.
|
||||
You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message.
|
||||
|
||||
Nx follows the principle of Coordinated Vulnerability Disclosure.
|
||||
|
||||
## What Should Be Reported
|
||||
|
||||
The security email is for **demonstrable, verified vulnerabilities within the Nx codebase itself**.
|
||||
|
||||
**Please do not use the security email for:**
|
||||
|
||||
- Reports about outdated dependencies (e.g., "package X has a newer version available")
|
||||
- Reports about dependencies with known CVEs that do not directly affect Nx functionality
|
||||
- General vulnerability scanner output
|
||||
|
||||
If you have a concern about an outdated dependency that you believe impacts Nx users, please open a [GitHub issue](https://github.com/nrwl/nx/issues/new/choose) instead.
|
||||
|
||||
@@ -22,6 +22,48 @@ This documentation site leverages Astro's static site generation capabilities wi
|
||||
- Dynamic API documentation generation from Nx packages and CLI commands
|
||||
- Community plugin registry
|
||||
|
||||
## Information Architecture Principles
|
||||
|
||||
When creating or reorganizing documentation, follow these 5 principles to determine where content belongs.
|
||||
|
||||
### 1. Progressive Disclosure (The "Journey" Rule)
|
||||
|
||||
- **Concept:** Don't overwhelm the user. Reveal complexity only as they advance in their journey.
|
||||
- **The Test:** _Is this for the First 30 Minutes (Getting Started), the First 30 Days (Features), or Forever (Reference)?_
|
||||
|
||||
### 2. Category Homogeneity (The "Scan" Rule)
|
||||
|
||||
- **Concept:** Items in a list must be of the same "type" (noun, verb, or concept) to reduce cognitive load.
|
||||
- **The Test:** _Does this list mix Concepts (Mental Model), Tasks (Update Nx), and Products (React)? If yes, split it._
|
||||
|
||||
### 3. Type-Based Navigation (The "Intent" Rule)
|
||||
|
||||
- **Concept:** Separate **Learning** (Narrative/Guides) from **Looking Up** (Reference/API).
|
||||
- **The Test:** _Is the user here to learn a workflow (Guide) or look up a flag syntax (Reference)?_
|
||||
|
||||
### 4. The Pen & Paper Test (The "Theory" Rule)
|
||||
|
||||
- **Concept:** Distinguish Architecture from Features to keep "Core Concepts" pure.
|
||||
- **The Test:** _Can I explain this using only a pen and paper?_
|
||||
- **Yes:** It goes in **How Nx Works** (Architecture).
|
||||
- **No (I need a terminal):** It goes in **Platform Features** (Feature).
|
||||
|
||||
### 5. Universal vs. Specific (The "Placement" Rule)
|
||||
|
||||
- **Concept:** Distinguish Platform features from Ecosystem tools to prevent "Features" from becoming a junk drawer.
|
||||
- **The Test:** _Does this feature apply to EVERY user (e.g., Caching, Agents)?_
|
||||
- **Yes:** **Platform Features**.
|
||||
- **No (Only React users):** **Technologies**.
|
||||
|
||||
### Sidebar Structure
|
||||
|
||||
The sidebar has 4 top-level sections that follow the user journey:
|
||||
|
||||
1. **Getting Started** - Essential setup, tutorials, and core concepts (How Nx Works, Platform Features)
|
||||
2. **Technologies** - Framework and tool-specific guides (React, Angular, Node, build tools, test tools)
|
||||
3. **Knowledge Base** - Recipes, troubleshooting, and topic-specific guides
|
||||
4. **Reference** - Exhaustive facts, no narrative (CLI commands, configuration, API docs)
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
|
||||
@@ -6,14 +6,17 @@ import react from '@astrojs/react';
|
||||
import markdoc from '@astrojs/markdoc';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
import { sidebar } from './sidebar.mts';
|
||||
import rehypeTableOptionLinks from './src/plugins/utils/rehype-table-option-links.ts';
|
||||
import { resolveNxDevUrl } from './src/utils/resolve-nx-dev-url.ts';
|
||||
|
||||
// Always resolve NX_DEV_URL so downstream consumers (Footer, Header) pick it up.
|
||||
// For deploy previews this overrides any site-level env var to point to the matching preview.
|
||||
process.env.NX_DEV_URL = resolveNxDevUrl();
|
||||
|
||||
const BASE = '/docs';
|
||||
|
||||
// This is exposed as window.__CONFIG
|
||||
const PUBLIC_CONFIG = {
|
||||
cookiebotDisabled: process.env.COOKIEBOT_DISABLED === 'true',
|
||||
cookiebotId: process.env.COOKIEBOT_ID ?? null,
|
||||
gaMeasurementId: 'UA-88380372-10',
|
||||
gtmMeasurementId: 'GTM-KW8423B6',
|
||||
isProd: process.env.NODE_ENV === 'production',
|
||||
};
|
||||
@@ -33,6 +36,9 @@ export default defineConfig({
|
||||
},
|
||||
},
|
||||
},
|
||||
markdown: {
|
||||
rehypePlugins: [rehypeTableOptionLinks],
|
||||
},
|
||||
trailingSlash: 'never',
|
||||
// This adapter doesn't support local previews, so only load it on Netlify.
|
||||
adapter: process.env['NETLIFY'] ? netlify() : undefined,
|
||||
@@ -56,22 +62,6 @@ export default defineConfig({
|
||||
tag: 'script',
|
||||
content: `window.__CONFIG = ${JSON.stringify(PUBLIC_CONFIG)};`,
|
||||
},
|
||||
...(process.env.COOKIEBOT_ID &&
|
||||
process.env.COOKIEBOT_DISABLED !== 'true'
|
||||
? [
|
||||
{
|
||||
/** @type {"script"} */
|
||||
tag: 'script',
|
||||
attrs: {
|
||||
id: 'Cookiebot',
|
||||
src: 'https://consent.cookiebot.com/uc.js',
|
||||
'data-cbid': process.env.COOKIEBOT_ID,
|
||||
'data-blockingmode': 'auto',
|
||||
type: 'text/javascript',
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
tag: 'script',
|
||||
attrs: {
|
||||
@@ -87,17 +77,13 @@ export default defineConfig({
|
||||
// since the sidebar doesn't auto generate w/ dynamic routes from src/pages/reference
|
||||
// only the src/content/docs/reference files
|
||||
'./src/plugins/sidebar-reference-updater.middleware.ts',
|
||||
'./src/plugins/sidebar-icons.middleware.ts',
|
||||
'./src/plugins/og.middleware.ts',
|
||||
'./src/plugins/github-stars.middleware.ts',
|
||||
'./src/plugins/raw-content.middleware.ts',
|
||||
'./src/plugins/canonical.middleware.ts',
|
||||
],
|
||||
markdown: {
|
||||
// this breaks the renderMarkdown function in the plugin loader due to starlight path normalization
|
||||
// as to _why_ it has to normalize a path?
|
||||
// idk just working around the issue for now but we'll want to have linked headers so will need to fix
|
||||
headingLinks: false,
|
||||
headingLinks: true,
|
||||
},
|
||||
social: [
|
||||
{ icon: 'github', label: 'GitHub', href: 'https://github.com/nrwl/nx' },
|
||||
|
||||
@@ -11,7 +11,7 @@ test('links in descriptions of properties should correctly link to the same page
|
||||
|
||||
await page
|
||||
.getByTestId('main-pane')
|
||||
.getByRole('link', { name: 'nxCloudAccessToken' })
|
||||
.getByRole('link', { name: 'nxCloudAccessToken', exact: true })
|
||||
.click();
|
||||
|
||||
await expect(
|
||||
|
||||
@@ -4,9 +4,15 @@ import {
|
||||
Markdoc,
|
||||
} from '@astrojs/markdoc/config';
|
||||
import starlightMarkdoc from '@astrojs/starlight-markdoc';
|
||||
import { transformOptionsTable } from './src/utils/markdoc-table-option-links';
|
||||
|
||||
export default defineMarkdocConfig({
|
||||
extends: [starlightMarkdoc()],
|
||||
nodes: {
|
||||
table: {
|
||||
transform: transformOptionsTable,
|
||||
},
|
||||
},
|
||||
tags: {
|
||||
call_to_action: {
|
||||
render: component('./src/components/markdoc/CallToAction.astro'),
|
||||
@@ -238,6 +244,15 @@ export default defineMarkdocConfig({
|
||||
},
|
||||
},
|
||||
},
|
||||
sidebar_group_cards: {
|
||||
render: component('./src/components/markdoc/SidebarGroupCards.astro'),
|
||||
attributes: {
|
||||
group: {
|
||||
type: 'String',
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
metrics: {
|
||||
render: component('./src/components/markdoc/Metrics.astro'),
|
||||
attributes: {
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
# Disable gradle and maven plugins on Netlify
|
||||
# (Netlify only supports Java 8 but these plugins require Java 17)
|
||||
[build.environment]
|
||||
NX_GRADLE_DISABLE = "true"
|
||||
NX_MAVEN_DISABLE = "true"
|
||||
|
||||
# Edge functions are auto-discovered from netlify/edge-functions/
|
||||
# Path configuration is in each function's inline `config` export
|
||||
|
||||
# Permanent redirects (301 by default)
|
||||
|
||||
# Storybook docs consolidation
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { Context } from 'https://edge.netlify.com';
|
||||
|
||||
/**
|
||||
* Content negotiation for LLM-friendly docs access.
|
||||
* See: https://llmstxt.org/
|
||||
*/
|
||||
export default async function handler(
|
||||
request: Request,
|
||||
context: Context
|
||||
): Promise<Response | URL> {
|
||||
const url = new URL(request.url);
|
||||
const pathname = url.pathname;
|
||||
|
||||
const acceptHeader = request.headers.get('accept') || '';
|
||||
|
||||
// Serve markdown for LLM tools that explicitly request it
|
||||
// Or if there are no accept headers passed (e.g. Cursor)
|
||||
if (!acceptHeader || acceptHeader.includes('text/markdown')) {
|
||||
const mdPath = pathname.replace(/\/?$/, '.md');
|
||||
return new URL(mdPath, request.url);
|
||||
}
|
||||
|
||||
const response = await context.next();
|
||||
|
||||
const contentType = response.headers.get('content-type') || '';
|
||||
if (!contentType.includes('text/html')) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const mdPath = pathname.replace(/\/?$/, '.md');
|
||||
|
||||
const linkHeader = [
|
||||
`<${mdPath}>; rel="alternate"; type="text/markdown"`,
|
||||
`</docs/llms.txt>; rel="alternate"; type="text/markdown"; title="LLM Index"`,
|
||||
`</docs/llms-full.txt>; rel="alternate"; type="text/markdown"; title="Full Documentation"`,
|
||||
].join(', ');
|
||||
|
||||
// Netlify responses are immutable
|
||||
const newHeaders = new Headers(response.headers);
|
||||
newHeaders.set('Link', linkHeader);
|
||||
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: newHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
export const config = {
|
||||
path: ['/docs/*'],
|
||||
excludedPath: [
|
||||
'/docs/*.md',
|
||||
'/docs/*.js',
|
||||
'/docs/*.txt',
|
||||
'/docs/images/*',
|
||||
// _astro and other asset paths
|
||||
'/docs/_*',
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { Context } from 'https://edge.netlify.com';
|
||||
|
||||
// Configuration - set these in Netlify environment variables
|
||||
const GA_MEASUREMENT_ID =
|
||||
Netlify.env.get('GA_MEASUREMENT_ID') || 'G-XXXXXXXXXX';
|
||||
const GA_API_SECRET = Netlify.env.get('GA_API_SECRET') || '';
|
||||
|
||||
function getClientId(request: Request): string {
|
||||
// Try to extract existing GA client ID from cookie
|
||||
const cookies = request.headers.get('cookie') || '';
|
||||
const gaMatch = cookies.match(/_ga=GA\d+\.\d+\.(\d+\.\d+)/);
|
||||
if (gaMatch) {
|
||||
return gaMatch[1];
|
||||
}
|
||||
|
||||
// Generate a new client ID for this request
|
||||
// For non-browser clients (AI tools), this creates a session-based ID
|
||||
const timestamp = Date.now();
|
||||
const random = Math.floor(Math.random() * 1000000000);
|
||||
return `${random}.${timestamp}`;
|
||||
}
|
||||
|
||||
async function sendToGA4(
|
||||
request: Request,
|
||||
context: Context,
|
||||
pathname: string
|
||||
): Promise<void> {
|
||||
if (!GA_API_SECRET) {
|
||||
console.warn('GA_API_SECRET not configured, skipping analytics');
|
||||
return;
|
||||
}
|
||||
|
||||
const clientId = getClientId(request);
|
||||
const userAgent = request.headers.get('user-agent') || 'unknown';
|
||||
|
||||
// Anthropic: ClaudeBot (training), Claude-User (user fetch), Claude-SearchBot (search index),
|
||||
// Claude-Web (web crawler), anthropic-ai (legacy training)
|
||||
// OpenAI: GPTBot (training), ChatGPT-User (user browsing), OAI-SearchBot (search index)
|
||||
// Perplexity: PerplexityBot (search index), Perplexity-User (user fetch)
|
||||
// Google: Google-Extended (AI/Gemini training)
|
||||
// Other: Bytespider (ByteDance training)
|
||||
const isAITool =
|
||||
/ClaudeBot|Claude-User|Claude-SearchBot|Claude-Web|anthropic-ai|GPTBot|ChatGPT-User|OAI-SearchBot|PerplexityBot|Perplexity-User|Google-Extended|Bytespider/i.test(
|
||||
userAgent
|
||||
);
|
||||
// Generic bots (SEO crawlers, social previews, etc.)
|
||||
const isGenericBot =
|
||||
/Googlebot|Amazonbot|CCBot|BingBot|YandexBot|DuckDuckBot|Applebot|crawler|spider|slurp|facebook|twitter|linkedin|slack|discord|telegram/i.test(
|
||||
userAgent
|
||||
);
|
||||
|
||||
const payload = {
|
||||
client_id: clientId,
|
||||
events: [
|
||||
{
|
||||
name: 'server_page_view',
|
||||
params: {
|
||||
page_location: request.url,
|
||||
page_title: pathname,
|
||||
page_path: pathname,
|
||||
// Custom parameters for filtering
|
||||
content_type: pathname.endsWith('.txt')
|
||||
? 'text/plain'
|
||||
: 'text/markdown',
|
||||
file_extension: pathname.substring(pathname.lastIndexOf('.')),
|
||||
user_agent: userAgent,
|
||||
is_ai_tool: isAITool ? 'true' : 'false',
|
||||
is_bot: isGenericBot ? 'true' : 'false',
|
||||
country: context.geo?.country?.code || 'unknown',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
console.log(`Tracked asset path: ${pathname}`);
|
||||
|
||||
const endpoint = `https://www.google-analytics.com/mp/collect?measurement_id=${GA_MEASUREMENT_ID}&api_secret=${GA_API_SECRET}`;
|
||||
|
||||
try {
|
||||
await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
} catch (error) {
|
||||
// Log but don't fail the request
|
||||
console.error('Failed to send to GA4:', error);
|
||||
}
|
||||
}
|
||||
|
||||
export default async function handler(
|
||||
request: Request,
|
||||
context: Context
|
||||
): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
const pathname = url.pathname;
|
||||
|
||||
// Send analytics in background (non-blocking)
|
||||
context.waitUntil(sendToGA4(request, context, pathname));
|
||||
|
||||
// Continue to serve the actual file
|
||||
const response = await context.next();
|
||||
|
||||
// Netlify Edge Function responses are immutable, so create a new Response
|
||||
const newHeaders = new Headers(response.headers);
|
||||
newHeaders.set('x-nx-edge-function', 'track-asset-requests');
|
||||
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: newHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
export const config = {
|
||||
path: ['/**/*.txt', '/**/*.md'],
|
||||
// Something is adding .png.md and .svg.md to get image paths, exclude those.
|
||||
excludedPath: ['/docs/og/*', '/docs/*.svg.md', '/docs/*.png.md'],
|
||||
};
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { Context } from 'https://edge.netlify.com';
|
||||
|
||||
const GA_MEASUREMENT_ID =
|
||||
Netlify.env.get('GA_MEASUREMENT_ID') || 'G-XXXXXXXXXX';
|
||||
const GA_API_SECRET = Netlify.env.get('GA_API_SECRET') || '';
|
||||
|
||||
function getClientId(request: Request): string {
|
||||
const cookies = request.headers.get('cookie') || '';
|
||||
const gaMatch = cookies.match(/_ga=GA\d+\.\d+\.(\d+\.\d+)/);
|
||||
if (gaMatch) return gaMatch[1];
|
||||
|
||||
const timestamp = Date.now();
|
||||
const random = Math.floor(Math.random() * 1000000000);
|
||||
return `${random}.${timestamp}`;
|
||||
}
|
||||
|
||||
async function sendToGA4(
|
||||
request: Request,
|
||||
context: Context,
|
||||
pathname: string
|
||||
): Promise<void> {
|
||||
if (!GA_API_SECRET) {
|
||||
console.warn('GA_API_SECRET not configured, skipping analytics');
|
||||
return;
|
||||
}
|
||||
|
||||
const clientId = getClientId(request);
|
||||
const userAgent = request.headers.get('user-agent') || 'unknown';
|
||||
// Anthropic: ClaudeBot (training), Claude-User (user fetch), Claude-SearchBot (search index),
|
||||
// Claude-Web (web crawler), anthropic-ai (legacy training)
|
||||
// OpenAI: GPTBot (training), ChatGPT-User (user browsing), OAI-SearchBot (search index)
|
||||
// Perplexity: PerplexityBot (search index), Perplexity-User (user fetch)
|
||||
// Google: Google-Extended (AI/Gemini training)
|
||||
// Other: Bytespider (ByteDance training)
|
||||
const isAITool =
|
||||
/ClaudeBot|Claude-User|Claude-SearchBot|Claude-Web|anthropic-ai|GPTBot|ChatGPT-User|OAI-SearchBot|PerplexityBot|Perplexity-User|Google-Extended|Bytespider/i.test(
|
||||
userAgent
|
||||
);
|
||||
// Generic bots (SEO crawlers, social previews, etc.)
|
||||
const isGenericBot =
|
||||
/Googlebot|Amazonbot|CCBot|BingBot|YandexBot|DuckDuckBot|Applebot|crawler|spider|slurp|facebook|twitter|linkedin|slack|discord|telegram/i.test(
|
||||
userAgent
|
||||
);
|
||||
|
||||
const payload = {
|
||||
client_id: clientId,
|
||||
events: [
|
||||
{
|
||||
name: 'server_page_view',
|
||||
params: {
|
||||
page_location: request.url,
|
||||
page_title: pathname,
|
||||
page_path: pathname,
|
||||
content_type: 'text/html',
|
||||
file_extension: '.html',
|
||||
user_agent: userAgent,
|
||||
is_ai_tool: isAITool ? 'true' : 'false',
|
||||
is_bot: isGenericBot ? 'true' : 'false',
|
||||
country: context.geo?.country?.code || 'unknown',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
console.log(`Tracked HTML page: ${pathname}`);
|
||||
|
||||
const endpoint = `https://www.google-analytics.com/mp/collect?measurement_id=${GA_MEASUREMENT_ID}&api_secret=${GA_API_SECRET}`;
|
||||
|
||||
try {
|
||||
await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to send to GA4:', error);
|
||||
}
|
||||
}
|
||||
|
||||
export default async function handler(
|
||||
request: Request,
|
||||
context: Context
|
||||
): Promise<Response> {
|
||||
const pathname = new URL(request.url).pathname;
|
||||
|
||||
// Always track - filtering is done at config level via `accept: ['text/html']`
|
||||
context.waitUntil(sendToGA4(request, context, pathname));
|
||||
|
||||
const response = await context.next();
|
||||
const newHeaders = new Headers(response.headers);
|
||||
newHeaders.set('x-nx-edge-function', 'track-page-requests');
|
||||
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: newHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
export const config = {
|
||||
path: ['/docs/*'],
|
||||
// Only track requests from clients that want HTML (browsers)
|
||||
// This filters out curl, AI agents, and other non-browser clients
|
||||
accept: ['text/html'],
|
||||
excludedPath: [
|
||||
// Text/code files (handled by track-asset-requests or not tracked)
|
||||
'/docs/*.md',
|
||||
'/docs/*.js',
|
||||
'/docs/*.txt',
|
||||
// Images
|
||||
'/docs/*.svg',
|
||||
'/docs/*.png',
|
||||
'/docs/*.jpg',
|
||||
'/docs/*.jpeg',
|
||||
'/docs/*.gif',
|
||||
'/docs/*.webp',
|
||||
'/docs/*.ico',
|
||||
'/docs/images/*',
|
||||
'/docs/og/*',
|
||||
// Fonts
|
||||
'/docs/fonts/*',
|
||||
'/docs/*.woff',
|
||||
'/docs/*.woff2',
|
||||
// Search index (pagefind)
|
||||
'/docs/pagefind/*',
|
||||
// Astro build assets
|
||||
'/docs/_*',
|
||||
],
|
||||
};
|
||||
@@ -16,6 +16,7 @@
|
||||
"@nx/nx-dev-ui-icons": "workspace:*",
|
||||
"@nx/nx-dev-ui-markdoc": "workspace:*",
|
||||
"@tailwindcss/vite": "^4.1.11",
|
||||
"@types/hast": "^3.0.4",
|
||||
"astro": "^5.10.1",
|
||||
"astro-og-canvas": "^0.7.0",
|
||||
"canvaskit-wasm": "^0.40.0",
|
||||
|
||||
@@ -38,31 +38,9 @@
|
||||
const config = window.__CONFIG || {};
|
||||
if (!config.isProd) return;
|
||||
|
||||
const isCookiebotDisabled = config.cookiebotDisabled ?? false;
|
||||
const gaMeasurementId = config.gaMeasurementId ?? 'UA-88380372-10';
|
||||
const gtmMeasurementId = config.gtmMeasurementId ?? 'GTM-KW8423B6';
|
||||
|
||||
// Initialize global objects
|
||||
window.Cookiebot = window.Cookiebot || {};
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
window.gtag =
|
||||
window.gtag ||
|
||||
function () {
|
||||
window.dataLayer.push(arguments);
|
||||
};
|
||||
|
||||
const loadGoogleAnalytics = () => {
|
||||
const script = document.createElement('script');
|
||||
script.src = `https://www.googletagmanager.com/gtag/js?id=${gaMeasurementId}`;
|
||||
script.async = true;
|
||||
document.head.appendChild(script);
|
||||
|
||||
// Initialize gtag
|
||||
window.gtag('js', new Date());
|
||||
window.gtag('config', gaMeasurementId, {
|
||||
page_path: window.location.pathname,
|
||||
});
|
||||
};
|
||||
|
||||
const loadGTM = () => {
|
||||
if (!gtmMeasurementId) return;
|
||||
@@ -79,70 +57,82 @@
|
||||
})(window, document, 'script', 'dataLayer', gtmMeasurementId);
|
||||
};
|
||||
|
||||
const loadHubSpot = () => {
|
||||
const hsScript = document.createElement('script');
|
||||
hsScript.src = 'https://js.hs-scripts.com/2757427.js';
|
||||
hsScript.async = true;
|
||||
hsScript.defer = true;
|
||||
document.head.appendChild(hsScript);
|
||||
|
||||
// Load HubSpot Forms
|
||||
const hsFormsScript = document.createElement('script');
|
||||
hsFormsScript.src = '//js.hsforms.net/forms/v2.js';
|
||||
hsFormsScript.async = true;
|
||||
hsFormsScript.defer = true;
|
||||
document.head.appendChild(hsFormsScript);
|
||||
// GA4 events are dispatched via GTM dataLayer.
|
||||
const pushGtmEvent = (eventName, payload) => {
|
||||
window.dataLayer.push({ event: eventName, ...payload });
|
||||
};
|
||||
|
||||
const loadApollo = () => {
|
||||
const n = Math.random().toString(36).substring(7);
|
||||
const script = document.createElement('script');
|
||||
script.src = `https://assets.apollo.io/micro/website-tracker/tracker.iife.js?nocache=${n}`;
|
||||
script.async = true;
|
||||
script.defer = true;
|
||||
script.onload = function () {
|
||||
if (window.trackingFunctions?.onLoad) {
|
||||
window.trackingFunctions.onLoad({
|
||||
appId: '65e1db2f1976f30300fd8b26',
|
||||
// Scroll depth tracking
|
||||
const SCROLL_THRESHOLDS = [10, 25, 50, 75, 90];
|
||||
let firedThresholds = new Set();
|
||||
let scrollTrackingEnabled = false;
|
||||
let scrollRafId = null;
|
||||
|
||||
function getScrollPercentage() {
|
||||
const scrollTop = window.scrollY || document.documentElement.scrollTop;
|
||||
const scrollHeight = document.documentElement.scrollHeight;
|
||||
const clientHeight = window.innerHeight;
|
||||
return (scrollTop + clientHeight) / scrollHeight;
|
||||
}
|
||||
|
||||
function handleScrollTracking() {
|
||||
if (!scrollTrackingEnabled) return;
|
||||
|
||||
const scrollPercentage = getScrollPercentage() * 100;
|
||||
|
||||
// Fire events for all thresholds we've passed but haven't fired yet
|
||||
for (const threshold of SCROLL_THRESHOLDS) {
|
||||
if (scrollPercentage >= threshold && !firedThresholds.has(threshold)) {
|
||||
firedThresholds.add(threshold);
|
||||
sendSearchEvent(`scroll_${threshold}`, {
|
||||
event_category: 'scroll',
|
||||
event_label: window.location.pathname,
|
||||
});
|
||||
}
|
||||
};
|
||||
document.head.appendChild(script);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const loadHotjar = () => {
|
||||
(function (h, o, t, j, a, r) {
|
||||
h.hj =
|
||||
h.hj ||
|
||||
function () {
|
||||
(h.hj.q = h.hj.q || []).push(arguments);
|
||||
};
|
||||
h._hjSettings = { hjid: 2774127, hjsv: 6 };
|
||||
a = o.getElementsByTagName('head')[0];
|
||||
r = o.createElement('script');
|
||||
r.async = 1;
|
||||
r.src = t + h._hjSettings.hjid + j + h._hjSettings.hjsv;
|
||||
a.appendChild(r);
|
||||
})(window, document, 'https://static.hotjar.com/c/hotjar-', '.js?sv=');
|
||||
};
|
||||
function throttledScrollHandler() {
|
||||
if (scrollRafId !== null) return;
|
||||
|
||||
const loadTwitterPixel = () => {
|
||||
!(function (e, t, n, s, u, a) {
|
||||
e.twq ||
|
||||
((s = e.twq =
|
||||
function () {
|
||||
s.exe ? s.exe.apply(s, arguments) : s.queue.push(arguments);
|
||||
}),
|
||||
(s.version = '1.1'),
|
||||
(s.queue = []),
|
||||
(u = t.createElement(n)),
|
||||
(u.async = !0),
|
||||
(u.src = 'https://static.ads-twitter.com/uwt.js'),
|
||||
(a = t.getElementsByTagName(n)[0]),
|
||||
a.parentNode.insertBefore(u, a));
|
||||
})(window, document, 'script');
|
||||
window.twq('config', 'obtp4');
|
||||
};
|
||||
scrollRafId = requestAnimationFrame(() => {
|
||||
handleScrollTracking();
|
||||
scrollRafId = null;
|
||||
});
|
||||
}
|
||||
|
||||
function attachScrollListener() {
|
||||
window.addEventListener('scroll', throttledScrollHandler, {
|
||||
passive: true,
|
||||
});
|
||||
}
|
||||
|
||||
function setupScrollTracking() {
|
||||
// Reset scroll depth on navigation (for SPA-like behavior via View Transitions)
|
||||
firedThresholds = new Set();
|
||||
scrollTrackingEnabled = false;
|
||||
|
||||
// Delay tracking start to avoid false triggers during navigation
|
||||
setTimeout(() => {
|
||||
scrollTrackingEnabled = true;
|
||||
// Immediately check current scroll position to capture thresholds
|
||||
// that may have been passed during the delay
|
||||
handleScrollTracking();
|
||||
}, 500);
|
||||
|
||||
attachScrollListener();
|
||||
|
||||
// Handle Astro View Transitions - reset on navigation
|
||||
document.addEventListener('astro:after-swap', () => {
|
||||
firedThresholds = new Set();
|
||||
scrollTrackingEnabled = false;
|
||||
setTimeout(() => {
|
||||
scrollTrackingEnabled = true;
|
||||
// Immediately check current scroll position after navigation
|
||||
handleScrollTracking();
|
||||
}, 500);
|
||||
});
|
||||
}
|
||||
|
||||
const SEARCH_DEBOUNCE_MS = 1000;
|
||||
let searchDebounceTimer;
|
||||
@@ -151,8 +141,7 @@
|
||||
let inputHandler = null;
|
||||
|
||||
function sendSearchEvent(eventType, data) {
|
||||
if (typeof window.gtag !== 'undefined')
|
||||
window.gtag('event', eventType, data);
|
||||
pushGtmEvent(eventType, data);
|
||||
}
|
||||
|
||||
function trackSearchQuery(query) {
|
||||
@@ -203,31 +192,11 @@
|
||||
});
|
||||
}
|
||||
|
||||
const checkAndLoadScripts = () => {
|
||||
if (isCookiebotDisabled) {
|
||||
loadGoogleAnalytics();
|
||||
loadGTM();
|
||||
loadHubSpot();
|
||||
setupSearchTracking();
|
||||
} else if (window.Cookiebot && window.Cookiebot.consent) {
|
||||
// Statistics cookies (Google Analytics, GTM, Search Tracking)
|
||||
if (window.Cookiebot.consent.statistics) {
|
||||
loadGoogleAnalytics();
|
||||
loadGTM();
|
||||
setupSearchTracking();
|
||||
}
|
||||
|
||||
// Marketing cookies (HubSpot, Apollo, Hotjar, Twitter)
|
||||
if (window.Cookiebot.consent.marketing) {
|
||||
loadHubSpot();
|
||||
loadApollo();
|
||||
loadHotjar();
|
||||
loadTwitterPixel();
|
||||
}
|
||||
} else {
|
||||
// Wait for Cookiebot to load
|
||||
setTimeout(checkAndLoadScripts, 100);
|
||||
}
|
||||
const initializeAnalytics = () => {
|
||||
if (!gtmMeasurementId) return;
|
||||
loadGTM();
|
||||
setupSearchTracking();
|
||||
setupScrollTracking();
|
||||
};
|
||||
|
||||
// Add GTM noscript iframe to body
|
||||
@@ -244,11 +213,8 @@
|
||||
document.body.insertBefore(noscript, document.body.firstChild);
|
||||
};
|
||||
|
||||
// Listen for user consent to cookies
|
||||
window.addEventListener('CookiebotOnAccept', checkAndLoadScripts);
|
||||
|
||||
// Initial check
|
||||
checkAndLoadScripts();
|
||||
initializeAnalytics();
|
||||
|
||||
// Add GTM noscript on DOM ready
|
||||
if (document.readyState === 'loading') {
|
||||
|
||||
|
Before Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 46 KiB |
|
Before Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 88 KiB |
|
Before Width: | Height: | Size: 155 KiB |
|
After Width: | Height: | Size: 409 KiB |
|
After Width: | Height: | Size: 188 KiB |
|
After Width: | Height: | Size: 188 KiB |
|
After Width: | Height: | Size: 297 KiB |
@@ -2,70 +2,119 @@
|
||||
import { Icon } from '@astrojs/starlight/components';
|
||||
import { getCollection } from 'astro:content';
|
||||
|
||||
const { pathname } = Astro.url;
|
||||
|
||||
const cleanedPath = pathname.split('?')[0];
|
||||
|
||||
const allDocs = await getCollection('docs');
|
||||
|
||||
const pathSegments = cleanedPath.split('/').filter(Boolean);
|
||||
|
||||
type Crumb = {
|
||||
id: string;
|
||||
name: string;
|
||||
href: string;
|
||||
label: string;
|
||||
href?: string;
|
||||
current: boolean;
|
||||
};
|
||||
|
||||
function slugify(label: string): string {
|
||||
return label
|
||||
.replace(/\.NET/g, 'dotnet')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9_]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
}
|
||||
|
||||
function findDocByPath (path: string) {
|
||||
path = path.replace(/^docs\//, '');
|
||||
return allDocs.find(d => d.id === `${path}`)
|
||||
?? allDocs.find(d => d.id === `${path}/index`);
|
||||
// --- Primary: Sidebar-based breadcrumbs ---
|
||||
const sidebar = Astro.locals.starlightRoute.sidebar;
|
||||
|
||||
function findBreadcrumbPath(
|
||||
entries: typeof sidebar,
|
||||
path: Crumb[] = [],
|
||||
slugSegments: string[] = []
|
||||
): Crumb[] | null {
|
||||
for (const entry of entries) {
|
||||
if (entry.type === 'link' && entry.isCurrent) {
|
||||
return [...path, { label: entry.label, href: entry.href, current: true }];
|
||||
}
|
||||
if (entry.type === 'group') {
|
||||
const currentSlugs = [...slugSegments, slugify(entry.label)];
|
||||
const groupHref = `/docs/${currentSlugs.join('/')}`;
|
||||
const result = findBreadcrumbPath(
|
||||
entry.entries,
|
||||
[
|
||||
...path,
|
||||
{ label: entry.label, href: groupHref, current: false },
|
||||
],
|
||||
currentSlugs
|
||||
);
|
||||
if (result) return result;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function createNameFromSegment(segment: string): string {
|
||||
let crumbs: Crumb[] = findBreadcrumbPath(sidebar) ?? [];
|
||||
|
||||
// --- Fallback: URL-path-based breadcrumbs ---
|
||||
if (crumbs.length === 0) {
|
||||
const { pathname } = Astro.url;
|
||||
const cleanedPath = pathname.split('?')[0];
|
||||
const allDocs = await getCollection('docs');
|
||||
const pathSegments = cleanedPath.split('/').filter(Boolean);
|
||||
|
||||
function findDocByPath(path: string) {
|
||||
path = path.replace(/^docs\//, '');
|
||||
return (
|
||||
allDocs.find((d) => d.id === `${path}`) ??
|
||||
allDocs.find((d) => d.id === `${path}/index`)
|
||||
);
|
||||
}
|
||||
|
||||
function createNameFromSegment(segment: string): string {
|
||||
segment = segment.split('#')[0];
|
||||
return segment
|
||||
.split('-')
|
||||
.map(s => s.charAt(0).toUpperCase() + s.slice(1))
|
||||
.join(' ');
|
||||
.split('-')
|
||||
.map((s) => s.charAt(0).toUpperCase() + s.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
crumbs = pathSegments
|
||||
.map((segment, index) => {
|
||||
const docPath = pathSegments.slice(0, index + 1).join('/');
|
||||
const doc = findDocByPath(docPath);
|
||||
const label =
|
||||
doc?.data?.sidebar?.label ||
|
||||
doc?.data?.title ||
|
||||
createNameFromSegment(segment);
|
||||
// If `base` is set in config, don't include it in breadcrumbs
|
||||
if (index === 0 && import.meta.env.BASE_URL) return null;
|
||||
return {
|
||||
label,
|
||||
href: `/${docPath}`,
|
||||
current: index === pathSegments.length - 1,
|
||||
};
|
||||
})
|
||||
.filter(Boolean) as Crumb[];
|
||||
}
|
||||
|
||||
const crumbs: Crumb[] = pathSegments.map((segment, index) => {
|
||||
const docPath = pathSegments.slice(0, index + 1).join('/');
|
||||
const doc = findDocByPath(docPath);
|
||||
const name = doc?.data?.sidebar?.label || doc?.data?.title || createNameFromSegment(segment);
|
||||
// If `base` is set in config, don't include it in breadcrumbs
|
||||
if (index === 0 && import.meta.env.BASE_URL) return null;
|
||||
return {
|
||||
id: segment,
|
||||
name,
|
||||
href: `/${docPath}`,
|
||||
current: index === pathSegments.length - 1,
|
||||
};
|
||||
}).filter(Boolean);
|
||||
---
|
||||
|
||||
|
||||
<nav class="not-content flex mb-4" aria-label="Breadcrumb">
|
||||
<ol role="list" class="flex m-0 p-0 flex-wrap items-center space-x-2 text-sm">
|
||||
{crumbs.map((crumb, index) => (
|
||||
<li class="flex items-center">
|
||||
{index > 0 && (
|
||||
<Icon name="right-caret" class="w-5 h-5 ml-2 mr-2"/>
|
||||
)}
|
||||
<a
|
||||
href={crumb.href}
|
||||
class={`no-underline text-sm${
|
||||
crumb.current
|
||||
? ' text-slate-900 dark:text-slate-100 font-semibold'
|
||||
: ' text-slate-500 dark:text-slate-400 font-medium hover:text-slate-700 dark:hover:text-slate-200'
|
||||
} transition-colors`}
|
||||
aria-current={crumb.current ? 'page' : undefined}
|
||||
>
|
||||
{crumb.name}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
{
|
||||
crumbs.map((crumb, index) => (
|
||||
<li class="flex items-center">
|
||||
{index > 0 && <Icon name="right-caret" class="w-5 h-5 ml-2 mr-2" />}
|
||||
{crumb.href ? (
|
||||
<a
|
||||
href={crumb.href}
|
||||
class={`no-underline text-sm${
|
||||
crumb.current
|
||||
? ' text-slate-900 dark:text-slate-100 font-semibold'
|
||||
: ' text-slate-500 dark:text-slate-400 font-medium hover:text-slate-700 dark:hover:text-slate-200'
|
||||
} transition-colors`}
|
||||
aria-current={crumb.current ? 'page' : undefined}
|
||||
>
|
||||
{crumb.label}
|
||||
</a>
|
||||
) : (
|
||||
<span class="text-sm text-slate-500 dark:text-slate-400 font-medium">
|
||||
{crumb.label}
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
))
|
||||
}
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
@@ -447,13 +447,6 @@ const currentVersion = versions.find((v) => v.current);
|
||||
</div>
|
||||
|
||||
<div class="h-6 w-px bg-slate-200 mx-1 dark:bg-slate-700"></div>
|
||||
<a
|
||||
id="header-ai-link"
|
||||
href={`${nxDevUrl}/ai`}
|
||||
class="px-3 py-2 text-sm font-medium text-slate-600 hover:text-blue-500 rounded-md transition-colors whitespace-nowrap no-underline dark:text-slate-200 dark:hover:text-sky-500"
|
||||
>
|
||||
AI
|
||||
</a>
|
||||
<a
|
||||
id="header-nx-cloud-link"
|
||||
href={`${nxDevUrl}/nx-cloud`}
|
||||
@@ -516,7 +509,7 @@ const currentVersion = versions.find((v) => v.current);
|
||||
</div>
|
||||
|
||||
<script>
|
||||
import { sendCustomEvent } from '@nx/nx-dev-feature-analytics';
|
||||
import { sendCustomEventViaGtm } from '@nx/nx-dev-feature-analytics';
|
||||
|
||||
function setupAnalyticsTracking() {
|
||||
const docsHomeLink = document.getElementById('header-docs-home-link');
|
||||
@@ -528,7 +521,7 @@ const currentVersion = versions.find((v) => v.current);
|
||||
const tryNxCloudBtn = document.getElementById('header-try-nx-cloud-btn');
|
||||
|
||||
docsHomeLink?.addEventListener('click', () => {
|
||||
sendCustomEvent(
|
||||
sendCustomEventViaGtm(
|
||||
'documentation-click',
|
||||
'header-navigation',
|
||||
'documentation-header'
|
||||
@@ -536,7 +529,7 @@ const currentVersion = versions.find((v) => v.current);
|
||||
});
|
||||
|
||||
aiLink?.addEventListener('click', () => {
|
||||
sendCustomEvent(
|
||||
sendCustomEventViaGtm(
|
||||
'ai-click',
|
||||
'header-navigation',
|
||||
'documentation-header'
|
||||
@@ -544,7 +537,7 @@ const currentVersion = versions.find((v) => v.current);
|
||||
});
|
||||
|
||||
nxCloudLink?.addEventListener('click', () => {
|
||||
sendCustomEvent(
|
||||
sendCustomEventViaGtm(
|
||||
'nx-cloud-click',
|
||||
'header-navigation',
|
||||
'documentation-header'
|
||||
@@ -552,7 +545,7 @@ const currentVersion = versions.find((v) => v.current);
|
||||
});
|
||||
|
||||
pricingLink?.addEventListener('click', () => {
|
||||
sendCustomEvent(
|
||||
sendCustomEventViaGtm(
|
||||
'pricing-click',
|
||||
'header-navigation',
|
||||
'documentation-header'
|
||||
@@ -560,7 +553,7 @@ const currentVersion = versions.find((v) => v.current);
|
||||
});
|
||||
|
||||
enterpriseLink?.addEventListener('click', () => {
|
||||
sendCustomEvent(
|
||||
sendCustomEventViaGtm(
|
||||
'enterprise-click',
|
||||
'header-navigation',
|
||||
'documentation-header'
|
||||
@@ -568,11 +561,19 @@ const currentVersion = versions.find((v) => v.current);
|
||||
});
|
||||
|
||||
contactBtn?.addEventListener('click', () => {
|
||||
sendCustomEvent('contact-click', 'header-cta', 'documentation-header');
|
||||
sendCustomEventViaGtm(
|
||||
'contact-click',
|
||||
'header-cta',
|
||||
'documentation-header'
|
||||
);
|
||||
});
|
||||
|
||||
tryNxCloudBtn?.addEventListener('click', () => {
|
||||
sendCustomEvent('login-click', 'header-cta', 'documentation-header');
|
||||
sendCustomEventViaGtm(
|
||||
'login-click',
|
||||
'header-cta',
|
||||
'documentation-header'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -13,13 +13,10 @@ const githubStarsCount = Astro.locals.githubStarsCount ?? 0;
|
||||
const bannerCollection = await getCollection('banner');
|
||||
const bannerConfig = bannerCollection[0]?.data;
|
||||
|
||||
// Check if banner is active
|
||||
// Check if banner is active based on activeUntil date
|
||||
function isBannerActive(config: typeof bannerConfig): boolean {
|
||||
if (!config?.enabled) return false;
|
||||
if (config.activeUntil) {
|
||||
return new Date() < new Date(config.activeUntil);
|
||||
}
|
||||
return true;
|
||||
if (!config?.activeUntil) return false;
|
||||
return new Date() < new Date(config.activeUntil);
|
||||
}
|
||||
|
||||
const showBanner = isBannerActive(bannerConfig);
|
||||
@@ -41,7 +38,7 @@ const bannerId = bannerConfig ? `${bannerConfig.title}-${bannerConfig.activeUnti
|
||||
<GitHubStarWidget starsCount={githubStarsCount} client:load />
|
||||
<div class="flex flex-col mx-2 gap-2">
|
||||
<a
|
||||
href="https://nx.dev/contact"
|
||||
href={`${import.meta.env.SITE || 'https://nx.dev'}/contact`}
|
||||
class="w-full inline-flex items-center justify-center px-4 py-2 text-sm font-medium rounded-md transition no-underline border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-700 shadow-sm"
|
||||
title="Contact Us"
|
||||
>
|
||||
@@ -114,7 +111,7 @@ const bannerId = bannerConfig ? `${bannerConfig.title}-${bannerConfig.activeUnti
|
||||
inset-block: var(--sl-nav-height) 0;
|
||||
inset-inline-start: 0;
|
||||
width: 100%;
|
||||
background-color: var(--sl-color-black);
|
||||
background-color: var(--sl-color-bg-sidebar);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,24 +2,81 @@
|
||||
import MobileMenuFooter from '@astrojs/starlight/components/MobileMenuFooter.astro'
|
||||
import SidebarPersister from '@astrojs/starlight/components/SidebarPersister.astro'
|
||||
import SidebarSublist from './SidebarSublist.astro'
|
||||
import { GitHubStarWidget } from '@nx/nx-dev-ui-common/src/lib/github-star-widget';
|
||||
import TabbedSidebar from './sidebar-tabs/TabbedSidebar.astro'
|
||||
import SidebarTab from './sidebar-tabs/SidebarTab.astro'
|
||||
import SidebarTabPanel from './sidebar-tabs/SidebarTabPanel.astro'
|
||||
import type { SidebarEntry } from './SidebarSublist.astro'
|
||||
import { sidebarTabs } from '../../../sidebar.mts'
|
||||
|
||||
const { sidebar } = Astro.locals.starlightRoute
|
||||
const githubStarsCount = Astro.locals.githubStarsCount ?? 0;
|
||||
|
||||
// Check if any entry in a tree has isCurrent
|
||||
function hasCurrentPage(entries: SidebarEntry[]): boolean {
|
||||
return entries.some((entry) => {
|
||||
if (entry.type === 'link') return entry.isCurrent
|
||||
return hasCurrentPage(entry.entries)
|
||||
})
|
||||
}
|
||||
|
||||
// For each tab, resolve its groups from the sidebar using the tab's group labels
|
||||
const tabs = sidebarTabs.map((config) => {
|
||||
const groupLabels = config.groups.map((g) =>
|
||||
typeof g === 'string' ? g : g.label
|
||||
)
|
||||
const groups = sidebar.filter(
|
||||
(entry: SidebarEntry) => entry.type === 'group' && groupLabels.includes(entry.label)
|
||||
)
|
||||
// Single-group tabs: unwrap the top-level group to avoid redundant heading
|
||||
const isSingleGroup = groups.length === 1 && groups[0].type === 'group'
|
||||
const entries: SidebarEntry[] = isSingleGroup ? (groups[0] as any).entries : groups
|
||||
const active = hasCurrentPage(groups)
|
||||
return { ...config, entries, active }
|
||||
})
|
||||
|
||||
// Exactly one tab should be active; if none matched, leave it for the client to decide
|
||||
const anyActive = tabs.some((t) => t.active)
|
||||
---
|
||||
|
||||
<div class="sidebar-wrapper" data-testid="sidebar-wrapper">
|
||||
<SidebarPersister>
|
||||
<SidebarSublist sublist={sidebar}/>
|
||||
<TabbedSidebar>
|
||||
{tabs.map((tab) => (
|
||||
<SidebarTab
|
||||
slot="tabs"
|
||||
id={tab.id}
|
||||
icon={tab.icon}
|
||||
label={tab.label}
|
||||
active={anyActive ? tab.active : false}
|
||||
/>
|
||||
))}
|
||||
{tabs.map((tab) => (
|
||||
<SidebarTabPanel
|
||||
slot="panels"
|
||||
id={`${tab.id}-panel`}
|
||||
tabId={tab.id}
|
||||
active={anyActive ? tab.active : false}
|
||||
>
|
||||
<SidebarSublist sublist={tab.entries} />
|
||||
</SidebarTabPanel>
|
||||
))}
|
||||
</TabbedSidebar>
|
||||
</SidebarPersister>
|
||||
<div class="md:sl-hidden">
|
||||
<MobileMenuFooter/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Enable sidebar expand/collapse animations after first paint so that
|
||||
// groups that are already open on page load don't animate from closed.
|
||||
requestAnimationFrame(() => {
|
||||
document.querySelector('.sidebar-wrapper')?.classList.add('sidebar-animate');
|
||||
});
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.sidebar-wrapper :global(a) {
|
||||
color: var(--sl-color-gray-4);
|
||||
color: var(--sl-color-gray-3);
|
||||
}
|
||||
|
||||
.sidebar-wrapper :global(a[aria-current=page]) {
|
||||
@@ -35,11 +92,15 @@ const githubStarsCount = Astro.locals.githubStarsCount ?? 0;
|
||||
}
|
||||
|
||||
.sidebar-wrapper :global(details summary .group-label) {
|
||||
font-size: var(--text-lg);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
font-size: var(--text-base);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
.sidebar-wrapper :global(ul ul summary) {
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
.sidebar-wrapper :global(details[open] summary .group-label) {
|
||||
color: var(--sl-color-gray-2);
|
||||
color: var(--sl-color-text-accent);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -3,43 +3,43 @@
|
||||
* This is a modified version of the SidebarSublist component from Starlight with support for icons.
|
||||
* https://github.com/withastro/starlight/blob/46524ac/packages/starlight/components/SidebarSublist.astro -->
|
||||
*/
|
||||
import { Badge, Icon } from '@astrojs/starlight/components'
|
||||
import { Badge, Icon } from '@astrojs/starlight/components';
|
||||
|
||||
export interface SidebarLink {
|
||||
type: 'link'
|
||||
label: string
|
||||
href: string
|
||||
isCurrent: boolean
|
||||
badge: any
|
||||
attrs: any
|
||||
type: 'link';
|
||||
label: string;
|
||||
href: string;
|
||||
isCurrent: boolean;
|
||||
badge: any;
|
||||
attrs: any;
|
||||
}
|
||||
|
||||
export interface SidebarGroup {
|
||||
type: 'group'
|
||||
label: string
|
||||
entries: (SidebarLink | SidebarGroup)[]
|
||||
collapsed: boolean
|
||||
badge: any
|
||||
attrs?: any
|
||||
type: 'group';
|
||||
label: string;
|
||||
entries: (SidebarLink | SidebarGroup)[];
|
||||
collapsed: boolean;
|
||||
badge: any;
|
||||
attrs?: any;
|
||||
}
|
||||
|
||||
export type SidebarEntry = SidebarLink | SidebarGroup
|
||||
export type SidebarEntry = SidebarLink | SidebarGroup;
|
||||
|
||||
interface Props {
|
||||
sublist: SidebarEntry[]
|
||||
sublist: SidebarEntry[];
|
||||
|
||||
nested?: boolean
|
||||
nested?: boolean;
|
||||
}
|
||||
|
||||
const { sublist, nested } = Astro.props
|
||||
const { sublist, nested } = Astro.props;
|
||||
|
||||
// Copied from https://github.com/withastro/starlight/blob/46524ac/packages/starlight/utils/navigation.ts#L447
|
||||
function flattenSidebar(entries: SidebarEntry[]): SidebarEntry[] {
|
||||
return entries.reduce<SidebarEntry[]>((acc, entry) => {
|
||||
if (entry.type === 'group') acc.push(...flattenSidebar(entry.entries))
|
||||
else acc.push(entry)
|
||||
return acc
|
||||
}, [])
|
||||
if (entry.type === 'group') acc.push(...flattenSidebar(entry.entries));
|
||||
else acc.push(entry);
|
||||
return acc;
|
||||
}, []);
|
||||
}
|
||||
|
||||
function getIconPath(iconName: string | undefined): string | null {
|
||||
@@ -53,7 +53,7 @@ function getIconPath(iconName: string | undefined): string | null {
|
||||
sublist.map((entry) => {
|
||||
const icon = getIconPath(entry.attrs?.['data-icon']);
|
||||
return (
|
||||
<li class={icon ? 'p-0 border-none' : ''}>
|
||||
<li class={icon ? 'border-none p-0' : ''}>
|
||||
{entry.type === 'link' ? (
|
||||
<a
|
||||
href={entry.href}
|
||||
@@ -66,35 +66,47 @@ function getIconPath(iconName: string | undefined): string | null {
|
||||
aria-hidden="true"
|
||||
src={icon}
|
||||
alt=""
|
||||
class="sidebar-icon w-4 h-4 dark:invert"
|
||||
class="sidebar-icon h-4 w-4 dark:invert"
|
||||
/>
|
||||
)}
|
||||
<span>{entry.label}</span>
|
||||
{entry.badge &&
|
||||
<Badge variant={entry.badge.variant} class={entry.badge.class}
|
||||
text={entry.badge.text}/>}
|
||||
{entry.badge && (
|
||||
<Badge
|
||||
variant={entry.badge.variant}
|
||||
class={entry.badge.class}
|
||||
text={entry.badge.text}
|
||||
/>
|
||||
)}
|
||||
</a>
|
||||
) : (
|
||||
<details
|
||||
open={flattenSidebar(entry.entries).some((i: any) => i.isCurrent) || !entry.collapsed}>
|
||||
<summary class={icon ? 'pl-0 py-2' : ''}>
|
||||
open={
|
||||
flattenSidebar(entry.entries).some((i: any) => i.isCurrent) ||
|
||||
!entry.collapsed
|
||||
}
|
||||
>
|
||||
<summary class={icon ? 'py-2 pl-0' : ''}>
|
||||
<div class="group-label">
|
||||
{icon && (
|
||||
<img
|
||||
aria-hidden="true"
|
||||
src={icon}
|
||||
alt=""
|
||||
class="sidebar-icon w-4 h-4 dark:invert"
|
||||
class="sidebar-icon h-4 w-4 dark:invert"
|
||||
/>
|
||||
)}
|
||||
<span class="large">{entry.label}</span>
|
||||
{entry.badge && (
|
||||
<Badge variant={entry.badge.variant} class={entry.badge.class} text={entry.badge.text}/>
|
||||
<Badge
|
||||
variant={entry.badge.variant}
|
||||
class={entry.badge.class}
|
||||
text={entry.badge.text}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<Icon name="right-caret" class="caret" size="1.25rem"/>
|
||||
<Icon name="right-caret" class="caret" size="1.25rem" />
|
||||
</summary>
|
||||
<Astro.self sublist={entry.entries} nested/>
|
||||
<Astro.self sublist={entry.entries} nested />
|
||||
</details>
|
||||
)}
|
||||
</li>
|
||||
@@ -107,7 +119,7 @@ function getIconPath(iconName: string | undefined): string | null {
|
||||
<style>
|
||||
@layer starlight.core {
|
||||
ul {
|
||||
--sl-sidebar-item-padding-inline: 0.5rem;
|
||||
--sl-sidebar-item-padding-inline: 0.375rem;
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
}
|
||||
@@ -128,8 +140,18 @@ function getIconPath(iconName: string | undefined): string | null {
|
||||
color: var(--sl-color-white);
|
||||
}
|
||||
|
||||
a.large {
|
||||
font-size: inherit;
|
||||
font-weight: inherit;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.top-level {
|
||||
padding-top: 0.75rem;
|
||||
}
|
||||
|
||||
.top-level > li + li {
|
||||
margin-top: 0.75rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
summary {
|
||||
@@ -140,6 +162,17 @@ function getIconPath(iconName: string | undefined): string | null {
|
||||
line-height: 1.4;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
font-weight: 600;
|
||||
color: var(--sl-color-white);
|
||||
border-radius: 0.25rem;
|
||||
}
|
||||
|
||||
summary:hover {
|
||||
background-color: color-mix(
|
||||
in srgb,
|
||||
var(--sl-color-gray-5) 40%,
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
summary::marker,
|
||||
@@ -148,8 +181,16 @@ function getIconPath(iconName: string | undefined): string | null {
|
||||
}
|
||||
|
||||
.caret {
|
||||
transition: transform 0.2s ease-in-out;
|
||||
transition:
|
||||
transform 0.2s ease-in-out,
|
||||
color 0.15s ease;
|
||||
flex-shrink: 0;
|
||||
color: var(--sl-color-gray-4);
|
||||
}
|
||||
|
||||
.caret:hover,
|
||||
summary:hover .caret {
|
||||
color: var(--sl-color-gray-2);
|
||||
}
|
||||
|
||||
:global([dir='rtl']) .caret {
|
||||
@@ -158,6 +199,11 @@ function getIconPath(iconName: string | undefined): string | null {
|
||||
|
||||
[open] > summary .caret {
|
||||
transform: rotateZ(90deg);
|
||||
color: var(--sl-color-text-accent);
|
||||
}
|
||||
|
||||
[open] > summary {
|
||||
color: var(--sl-color-text-accent);
|
||||
}
|
||||
|
||||
a {
|
||||
@@ -165,7 +211,7 @@ function getIconPath(iconName: string | undefined): string | null {
|
||||
border-radius: 0.25rem;
|
||||
text-decoration: none;
|
||||
color: var(--sl-color-gray-2);
|
||||
padding: 0.3em var(--sl-sidebar-item-padding-inline);
|
||||
padding: 0.2em var(--sl-sidebar-item-padding-inline);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
@@ -187,9 +233,60 @@ function getIconPath(iconName: string | undefined): string | null {
|
||||
margin-inline-end: 0.25em;
|
||||
}
|
||||
|
||||
/*
|
||||
* Deep nesting adjustments (3+ levels).
|
||||
* Uses :is() to target any li that is at least 3 levels deep,
|
||||
* then tightens spacing progressively via custom properties.
|
||||
*/
|
||||
ul ul ul {
|
||||
--_nest-indent: 0.25rem;
|
||||
--_nest-link-block: 0.15em;
|
||||
}
|
||||
|
||||
ul ul ul ul {
|
||||
--_nest-indent: 0.2rem;
|
||||
}
|
||||
|
||||
ul ul ul li {
|
||||
margin-inline-start: var(--_nest-indent);
|
||||
padding-inline-start: var(--_nest-indent);
|
||||
}
|
||||
|
||||
ul ul ul a {
|
||||
padding-block: var(--_nest-link-block);
|
||||
}
|
||||
|
||||
/* Smooth expand/collapse — progressive enhancement (Chrome 129+, Firefox 131+, Safari 17.5+).
|
||||
Gated behind .sidebar-animate (added by JS after first paint) to prevent
|
||||
already-open groups from animating on page load. */
|
||||
details {
|
||||
interpolate-size: allow-keywords;
|
||||
}
|
||||
|
||||
:global(.sidebar-animate) details > ul {
|
||||
overflow: hidden;
|
||||
height: 0;
|
||||
opacity: 0;
|
||||
transition:
|
||||
height 0.2s ease,
|
||||
opacity 0.15s ease;
|
||||
}
|
||||
|
||||
:global(.sidebar-animate) details[open] > ul {
|
||||
height: auto;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@starting-style {
|
||||
:global(.sidebar-animate) details[open] > ul {
|
||||
height: 0;
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 50rem) {
|
||||
.top-level > li + li {
|
||||
margin-top: 0.5rem;
|
||||
margin-top: 0.375rem;
|
||||
}
|
||||
|
||||
.large {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
import { Icon } from '@astrojs/starlight/components'
|
||||
|
||||
interface Props {
|
||||
id: string
|
||||
icon?: string
|
||||
label: string
|
||||
active?: boolean
|
||||
}
|
||||
|
||||
const { id, icon, label, active = false } = Astro.props
|
||||
const panelId = `${id}-panel`
|
||||
---
|
||||
|
||||
<button
|
||||
role="tab"
|
||||
id={id}
|
||||
aria-selected={active ? 'true' : 'false'}
|
||||
aria-controls={panelId}
|
||||
data-active={active ? 'true' : undefined}
|
||||
tabindex={active ? 0 : -1}
|
||||
>
|
||||
{icon && <Icon name={icon} size="1rem" />}
|
||||
{label}
|
||||
</button>
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
interface Props {
|
||||
id: string
|
||||
tabId: string
|
||||
active?: boolean
|
||||
}
|
||||
|
||||
const { id, tabId, active = false } = Astro.props
|
||||
---
|
||||
|
||||
<div
|
||||
role="tabpanel"
|
||||
id={id}
|
||||
aria-labelledby={tabId}
|
||||
hidden={!active}
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
// TabbedSidebar: A custom element that shows/hides tab panels in the sidebar.
|
||||
// All panels are rendered at build time; JS toggles visibility.
|
||||
---
|
||||
|
||||
<nx-tabbed-sidebar>
|
||||
<div class="nx-tab-bar-sticky">
|
||||
<div class="nx-tab-bar" role="tablist" aria-label="Sidebar sections" aria-orientation="vertical">
|
||||
<slot name="tabs" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="nx-tab-panels">
|
||||
<slot name="panels" />
|
||||
</div>
|
||||
</nx-tabbed-sidebar>
|
||||
|
||||
<script>
|
||||
class NxTabbedSidebar extends HTMLElement {
|
||||
private tabs: HTMLButtonElement[] = [];
|
||||
private panels: HTMLElement[] = [];
|
||||
|
||||
connectedCallback() {
|
||||
this.tabs = Array.from(this.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
this.panels = Array.from(this.querySelectorAll<HTMLElement>('[role="tabpanel"]'));
|
||||
|
||||
if (this.tabs.length === 0) return;
|
||||
|
||||
// Determine initial active tab
|
||||
const activeIndex = this.getInitialTabIndex();
|
||||
this.switchTab(activeIndex, false);
|
||||
|
||||
// Event listeners
|
||||
this.addEventListener('click', this.handleClick);
|
||||
this.addEventListener('keydown', this.handleKeydown);
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
this.removeEventListener('click', this.handleClick);
|
||||
this.removeEventListener('keydown', this.handleKeydown);
|
||||
}
|
||||
|
||||
private getInitialTabIndex(): number {
|
||||
// 1. Tab with data-active="true" (set server-side from isCurrent check)
|
||||
const serverActive = this.tabs.findIndex(
|
||||
(tab) => tab.getAttribute('data-active') === 'true'
|
||||
);
|
||||
if (serverActive !== -1) return serverActive;
|
||||
|
||||
// 2. sessionStorage fallback
|
||||
const stored = sessionStorage.getItem('nx-sidebar-tab');
|
||||
if (stored !== null) {
|
||||
const storedIndex = this.tabs.findIndex((tab) => tab.id === stored);
|
||||
if (storedIndex !== -1) return storedIndex;
|
||||
}
|
||||
|
||||
// 3. Default to first tab
|
||||
return 0;
|
||||
}
|
||||
|
||||
private switchTab(index: number, store = true) {
|
||||
this.tabs.forEach((tab, i) => {
|
||||
const selected = i === index;
|
||||
tab.setAttribute('aria-selected', String(selected));
|
||||
tab.tabIndex = selected ? 0 : -1;
|
||||
});
|
||||
|
||||
this.panels.forEach((panel, i) => {
|
||||
panel.hidden = i !== index;
|
||||
});
|
||||
|
||||
if (store && this.tabs[index]) {
|
||||
sessionStorage.setItem('nx-sidebar-tab', this.tabs[index].id);
|
||||
}
|
||||
}
|
||||
|
||||
private handleClick = (e: Event) => {
|
||||
const tab = (e.target as HTMLElement).closest<HTMLButtonElement>('[role="tab"]');
|
||||
if (!tab) return;
|
||||
const index = this.tabs.indexOf(tab);
|
||||
if (index !== -1) {
|
||||
this.switchTab(index);
|
||||
tab.focus();
|
||||
}
|
||||
};
|
||||
|
||||
private handleKeydown = (e: KeyboardEvent) => {
|
||||
const tab = (e.target as HTMLElement).closest<HTMLButtonElement>('[role="tab"]');
|
||||
if (!tab) return;
|
||||
|
||||
const currentIndex = this.tabs.indexOf(tab);
|
||||
let nextIndex: number | null = null;
|
||||
|
||||
switch (e.key) {
|
||||
case 'ArrowDown':
|
||||
nextIndex = (currentIndex + 1) % this.tabs.length;
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
nextIndex = (currentIndex - 1 + this.tabs.length) % this.tabs.length;
|
||||
break;
|
||||
case 'Home':
|
||||
nextIndex = 0;
|
||||
break;
|
||||
case 'End':
|
||||
nextIndex = this.tabs.length - 1;
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
this.switchTab(nextIndex);
|
||||
this.tabs[nextIndex].focus();
|
||||
};
|
||||
}
|
||||
|
||||
customElements.define('nx-tabbed-sidebar', NxTabbedSidebar);
|
||||
</script>
|
||||
@@ -0,0 +1,108 @@
|
||||
---
|
||||
import { getCollection } from 'astro:content';
|
||||
import Cards from './Cards.astro';
|
||||
import LinkCard from './LinkCard.astro';
|
||||
|
||||
export interface Props {
|
||||
group: string;
|
||||
}
|
||||
|
||||
const { group } = Astro.props;
|
||||
const groupSegments = group.split('/');
|
||||
|
||||
// Use the Starlight resolved sidebar from Astro locals
|
||||
const sidebar = Astro.locals.starlightRoute.sidebar;
|
||||
type SidebarEntry = (typeof sidebar)[number];
|
||||
|
||||
function findGroup(
|
||||
entries: SidebarEntry[],
|
||||
segments: string[],
|
||||
depth: number = 0
|
||||
): SidebarEntry | null {
|
||||
for (const entry of entries) {
|
||||
if (entry.type === 'group' && entry.label === segments[depth]) {
|
||||
if (depth === segments.length - 1) {
|
||||
return entry;
|
||||
}
|
||||
return findGroup(entry.entries, segments, depth + 1);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
interface LinkItem {
|
||||
label: string;
|
||||
href: string;
|
||||
}
|
||||
|
||||
function slugify(label: string): string {
|
||||
return label
|
||||
.replace(/\.NET/g, 'dotnet')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9_]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
}
|
||||
|
||||
// Build base URL path from the group prop segments
|
||||
const baseSlug = groupSegments.map((s) => slugify(s)).join('/');
|
||||
|
||||
function collectTopLevelItems(entries: SidebarEntry[]): LinkItem[] {
|
||||
const items: LinkItem[] = [];
|
||||
for (const entry of entries) {
|
||||
if (entry.type === 'link') {
|
||||
items.push({ label: entry.label, href: entry.href });
|
||||
}
|
||||
if (entry.type === 'group') {
|
||||
const groupSlug = slugify(entry.label);
|
||||
items.push({
|
||||
label: entry.label,
|
||||
href: `/docs/${baseSlug}/${groupSlug}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
const matchedGroup = findGroup(sidebar, groupSegments);
|
||||
const linkItems =
|
||||
matchedGroup && matchedGroup.type === 'group'
|
||||
? collectTopLevelItems(matchedGroup.entries)
|
||||
: [];
|
||||
|
||||
// Look up each page in the docs collection for descriptions
|
||||
const allDocs = await getCollection('docs');
|
||||
|
||||
const processedPages = linkItems.map((item) => {
|
||||
const docPath = item.href.replace(/^\/docs\//, '');
|
||||
const doc = allDocs.find(
|
||||
(d) =>
|
||||
d.id === docPath ||
|
||||
d.id === `${docPath}.mdoc` ||
|
||||
d.id === `${docPath}/index` ||
|
||||
d.id === `${docPath}/index.mdoc`
|
||||
);
|
||||
|
||||
return {
|
||||
title: item.label,
|
||||
description: doc?.data?.description || '',
|
||||
href: item.href,
|
||||
};
|
||||
});
|
||||
---
|
||||
|
||||
{
|
||||
processedPages.length > 0 ? (
|
||||
<Cards>
|
||||
{processedPages.map((page) => (
|
||||
<LinkCard
|
||||
title={page.title}
|
||||
description={page.description}
|
||||
href={page.href}
|
||||
type="documentation"
|
||||
/>
|
||||
))}
|
||||
</Cards>
|
||||
) : (
|
||||
<p>No pages found in this section.</p>
|
||||
)
|
||||
}
|
||||
@@ -106,14 +106,14 @@ const banner = defineCollection({
|
||||
loader: file('src/content/banner.json'),
|
||||
schema: z.object({
|
||||
id: z.string(),
|
||||
slug: z.string(),
|
||||
title: z.string(),
|
||||
description: z.string(),
|
||||
primaryCtaUrl: z.string(),
|
||||
primaryCtaText: z.string(),
|
||||
secondaryCtaUrl: z.string().optional(),
|
||||
secondaryCtaText: z.string().optional(),
|
||||
enabled: z.boolean(),
|
||||
activeUntil: z.string().optional(),
|
||||
activeUntil: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": "banner",
|
||||
"activeUntil": "2025-12-26T00:00:00.000Z",
|
||||
"description": "This is the first banner's description.",
|
||||
"enabled": false,
|
||||
"primaryCtaText": "Hello from today",
|
||||
"primaryCtaUrl": "https://nx.dev",
|
||||
"title": "This is the first banner's title HEHEHEHEHE",
|
||||
"secondaryCtaText": "",
|
||||
"secondaryCtaUrl": "",
|
||||
"_generated": "2025-12-11T20:41:11.810Z"
|
||||
}
|
||||
]
|
||||
@@ -1,284 +0,0 @@
|
||||
---
|
||||
title: Common Task Configurations
|
||||
description: Learn about standard task naming conventions in Nx projects, including build, serve, test, and lint tasks, for consistent project configuration.
|
||||
keywords: [build, serve, test, lint]
|
||||
sidebar:
|
||||
order: 1
|
||||
label: Common Tasks
|
||||
filter: 'type:Concepts'
|
||||
weight: 5.0
|
||||
---
|
||||
|
||||
The tasks that are [inferred by plugins](/docs/concepts/inferred-tasks) or that you define in your [project configuration](/docs/reference/project-configuration) can have any name that you want, but it is helpful for developers if you keep your task naming convention consistent across the projects in your repository. This way, if a developer moves from one project to another, they already know how to launch tasks for the new project. Here are some common task names that you can define for your projects.
|
||||
|
||||
## `build`
|
||||
|
||||
This task should produce the compiled output of this project. Typically, you'll want to have `build` tasks depend on the `build` tasks of project dependencies across the whole repository. You can set this default in the `nx.json` file like this:
|
||||
|
||||
```json title="nx.json"
|
||||
{
|
||||
"targetDefaults": {
|
||||
"build": {
|
||||
"dependsOn": ["^build"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The task might use the [@nx/vite](/docs/technologies/build-tools/vite/introduction), [@nx/webpack](/docs/technologies/build-tools/webpack/introduction) or [@nx/rspack](/docs/technologies/build-tools/rspack/introduction) plugins. Or you could have the task launch your own custom script.
|
||||
|
||||
{% tabs %}
|
||||
{% tabitem label="Vite" %}
|
||||
|
||||
Set up an [inferred](/docs/concepts/inferred-tasks) `build` task for every project that has a Vite configuration file with this configuration in `nx.json`:
|
||||
|
||||
```json title="nx.json"
|
||||
{
|
||||
"plugins": [
|
||||
{
|
||||
"plugin": "@nx/vite/plugin",
|
||||
"options": {
|
||||
"buildTargetName": "build"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
You can also [override the inferred task configuration](/docs/concepts/inferred-tasks#overriding-inferred-task-configuration) as needed.
|
||||
|
||||
{% /tabitem %}
|
||||
{% tabitem label="Webpack" %}
|
||||
|
||||
Set up an [inferred](/docs/concepts/inferred-tasks) `build` task for every project that has a Webpack configuration file with this configuration in `nx.json`:
|
||||
|
||||
```json title="nx.json"
|
||||
{
|
||||
"plugins": [
|
||||
{
|
||||
"plugin": "@nx/webpack/plugin",
|
||||
"options": {
|
||||
"buildTargetName": "build"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
You can also [override the inferred task configuration](/docs/concepts/inferred-tasks#overriding-inferred-task-configuration) as needed.
|
||||
|
||||
{% /tabitem %}
|
||||
{% tabitem label="rspack" %}
|
||||
|
||||
Set up an [inferred](/docs/concepts/inferred-tasks) `build` task for every project that has an rspack configuration file with this configuration in `nx.json`:
|
||||
|
||||
```json title="nx.json"
|
||||
{
|
||||
"plugins": [
|
||||
{
|
||||
"plugin": "@nx/rspack/plugin",
|
||||
"options": {
|
||||
"buildTargetName": "build"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
You can also [override the inferred task configuration](/docs/concepts/inferred-tasks#overriding-inferred-task-configuration) as needed.
|
||||
|
||||
{% /tabitem %}
|
||||
{% tabitem label="Custom Script" %}
|
||||
|
||||
You can define your own `build` task in your project configuration. Here is an example that uses `ts-node` to run a node script.
|
||||
|
||||
```json title="packages/my-project/package.json"
|
||||
{
|
||||
"scripts": {
|
||||
"build": "ts-node build-script.ts"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
{% /tabs %}
|
||||
|
||||
## `serve`
|
||||
|
||||
This task should run your project in a developer preview mode. The task might use the [@nx/vite](/docs/technologies/build-tools/vite/introduction), [@nx/webpack](/docs/technologies/build-tools/webpack/introduction) or [@nx/rspack](/docs/technologies/build-tools/rspack/introduction) plugins. Or you could have the task launch your own custom script.
|
||||
|
||||
{% tabs %}
|
||||
{% tabitem label="Vite" %}
|
||||
|
||||
Set up an [inferred](/docs/concepts/inferred-tasks) `serve` task for every project that has a Vite configuration file with this configuration in `nx.json`:
|
||||
|
||||
```json title="nx.json"
|
||||
{
|
||||
"plugins": [
|
||||
{
|
||||
"plugin": "@nx/vite/plugin",
|
||||
"options": {
|
||||
"serveTargetName": "serve"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
You can also [override the inferred task configuration](/docs/concepts/inferred-tasks#overriding-inferred-task-configuration) as needed.
|
||||
|
||||
{% /tabitem %}
|
||||
{% tabitem label="Webpack" %}
|
||||
|
||||
Set up an [inferred](/docs/concepts/inferred-tasks) `serve` task for every project that has a Webpack configuration file with this configuration in `nx.json`:
|
||||
|
||||
```json title="nx.json"
|
||||
{
|
||||
"plugins": [
|
||||
{
|
||||
"plugin": "@nx/webpack/plugin",
|
||||
"options": {
|
||||
"serveTargetName": "serve"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
You can also [override the inferred task configuration](/docs/concepts/inferred-tasks#overriding-inferred-task-configuration) as needed.
|
||||
|
||||
{% /tabitem %}
|
||||
{% tabitem label="rspack" %}
|
||||
|
||||
Set up an [inferred](/docs/concepts/inferred-tasks) `serve` task for every project that has an rspack configuration file with this configuration in `nx.json`:
|
||||
|
||||
```json title="nx.json"
|
||||
{
|
||||
"plugins": [
|
||||
{
|
||||
"plugin": "@nx/rspack/plugin",
|
||||
"options": {
|
||||
"serveTargetName": "serve"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
You can also [override the inferred task configuration](/docs/concepts/inferred-tasks#overriding-inferred-task-configuration) as needed.
|
||||
|
||||
{% /tabitem %}
|
||||
{% tabitem label="Custom Script" %}
|
||||
|
||||
You can define your own `serve` task in your project configuration. Here is an example that uses `ts-node` to run the entry point of your project.
|
||||
|
||||
```json title="packages/my-project/package.json"
|
||||
{
|
||||
"scripts": {
|
||||
"serve": "ts-node main.ts"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
{% /tabs %}
|
||||
|
||||
## `test`
|
||||
|
||||
This task typically runs unit tests for a project. The task might use the [@nx/vite](/docs/technologies/build-tools/vite/introduction) or [@nx/jest](/docs/technologies/test-tools/jest/introduction) plugins. Or you could have the task launch your own custom script.
|
||||
|
||||
{% tabs %}
|
||||
{% tabitem label="Vitest" %}
|
||||
|
||||
Set up an [inferred](/docs/concepts/inferred-tasks) `test` task for every project that has a Vitest configuration file with this configuration in `nx.json`:
|
||||
|
||||
```json title="nx.json"
|
||||
{
|
||||
"plugins": [
|
||||
{
|
||||
"plugin": "@nx/vite/plugin",
|
||||
"options": {
|
||||
"testTargetName": "test"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
You can also [override the inferred task configuration](/docs/concepts/inferred-tasks#overriding-inferred-task-configuration) as needed.
|
||||
|
||||
{% /tabitem %}
|
||||
{% tabitem label="Jest" %}
|
||||
|
||||
Set up an [inferred](/docs/concepts/inferred-tasks) `test` task for every project that has a Jest configuration file with this configuration in `nx.json`:
|
||||
|
||||
```json title="nx.json"
|
||||
{
|
||||
"plugins": [
|
||||
{
|
||||
"plugin": "@nx/jest/plugin",
|
||||
"options": {
|
||||
"targetName": "test"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
You can also [override the inferred task configuration](/docs/concepts/inferred-tasks#overriding-inferred-task-configuration) as needed.
|
||||
|
||||
{% /tabitem %}
|
||||
{% tabitem label="Custom Script" %}
|
||||
|
||||
You can define your own `test` task in your project configuration. Here is an example that runs the `ava` test tool.
|
||||
|
||||
```json title="packages/my-project/package.json"
|
||||
{
|
||||
"scripts": {
|
||||
"test": "ava"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
{% /tabs %}
|
||||
|
||||
## `lint`
|
||||
|
||||
This task should run lint rules for a project. The task might use the [@nx/eslint](/docs/technologies/eslint/introduction) plugin or run your own custom script.
|
||||
|
||||
{% tabs %}
|
||||
{% tabitem label="ESLint" %}
|
||||
|
||||
Set up an [inferred](/docs/concepts/inferred-tasks) `lint` task for every project that has an ESLint configuration file with this configuration in `nx.json`:
|
||||
|
||||
```json title="nx.json"
|
||||
{
|
||||
"plugins": [
|
||||
{
|
||||
"plugin": "@nx/eslint/plugin",
|
||||
"options": {
|
||||
"targetName": "lint"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
You can also [override the inferred task configuration](/docs/concepts/inferred-tasks#overriding-inferred-task-configuration) as needed.
|
||||
|
||||
{% /tabitem %}
|
||||
{% tabitem label="Custom Script" %}
|
||||
|
||||
You can define your own `lint` task in your project configuration. Here is an example that runs the `sonarts` lint tool.
|
||||
|
||||
```json title="packages/my-project/package.json"
|
||||
{
|
||||
"scripts": {
|
||||
"lint": "sonarts"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
{% /tabs %}
|
||||
@@ -55,7 +55,7 @@ The configuration for package manager workspaces varies based on which package m
|
||||
|
||||
Defining the `workspaces` property in the root `package.json` file lets npm know to look for other `package.json` files in the specified folders. With this configuration in place, all the dependencies for the individual projects will be installed in the root `node_modules` folder when `npm install` is run in the root folder. Also, the projects themselves will be linked in the root `node_modules` folder to be accessed as if they were npm packages.
|
||||
|
||||
If you want to reference a local library project with its own `build` task, you should include the library in the `devDependencies` of the application's `package.json` with `*` specified as the library's version. `*` tells npm to use whatever version of the project is available.
|
||||
If you want to reference a local library project with its own `build` task, you should include the library in the `devDependencies` of the application/library's `package.json` with `*` specified as the library's version. `*` tells npm to use whatever version of the project is available.
|
||||
|
||||
```json title="/apps/my-app/package.json"
|
||||
{
|
||||
@@ -76,7 +76,7 @@ If you want to reference a local library project with its own `build` task, you
|
||||
|
||||
Defining the `workspaces` property in the root `package.json` file lets yarn know to look for other `package.json` files in the specified folders. With this configuration in place, all the dependencies for the individual projects will be installed in the root `node_modules` folder when `yarn` is run in the root folder. Also, the projects themselves will be linked in the root `node_modules` folder to be accessed as if they were npm packages.
|
||||
|
||||
If you want to reference a local library project with its own `build` task, you should include the library in the `devDependencies` of the application's `package.json` with `workspace:*` specified as the library's version. [`workspace:*` tells yarn that the project is in the same repository](https://yarnpkg.com/features/workspaces) and not an npm package. You want to specify local projects as `devDependencies` instead of `dependencies` so that the library is not included twice in the production bundle of the application.
|
||||
If you want to reference a local library project with its own `build` task, you should include the library in the `devDependencies` of the application/library's `package.json` with `workspace:*` specified as the library's version. [`workspace:*` tells yarn that the project is in the same repository](https://yarnpkg.com/features/workspaces) and not an npm package. You want to specify local projects as `devDependencies` instead of `dependencies` so that the library is not included twice in the production bundle of the application.
|
||||
|
||||
```json title="/apps/my-app/package.json"
|
||||
{
|
||||
@@ -97,7 +97,7 @@ If you want to reference a local library project with its own `build` task, you
|
||||
|
||||
Defining the `workspaces` property in the root `package.json` file lets bun know to look for other `package.json` files in the specified folders. With this configuration in place, all the dependencies for the individual projects will be installed in the root `node_modules` folder when `bun install` is run in the root folder. Also, the projects themselves will be linked in the root `node_modules` folder to be accessed as if they were npm packages.
|
||||
|
||||
If you want to reference a local library project with its own `build` task, you should include the library in the `devDependencies` of the application's `package.json` with `workspace:*` specified as the library's version. [`workspace:*` tells bun that the project is in the same repository](https://bun.sh/docs/install/workspaces) and not an npm package. You want to specify local projects as `devDependencies` instead of `dependencies` so that the library is not included twice in the production bundle of the application.
|
||||
If you want to reference a local library project with its own `build` task, you should include the library in the `devDependencies` of the application/library's `package.json` with `workspace:*` specified as the library's version. [`workspace:*` tells bun that the project is in the same repository](https://bun.sh/docs/install/workspaces) and not an npm package. You want to specify local projects as `devDependencies` instead of `dependencies` so that the library is not included twice in the production bundle of the application.
|
||||
|
||||
```json title="/apps/my-app/package.json"
|
||||
{
|
||||
|
||||
@@ -68,18 +68,80 @@ The following permissions are required for Nx Cloud to work:
|
||||
|
||||
Repository permissions:
|
||||
|
||||
- `Administration: Read & Write`
|
||||
- `Checks: Read & Write`
|
||||
- `Contents: Read & Write`
|
||||
- `Pull requests: Read & Write`
|
||||
- `Checks: Read Only`
|
||||
- `Commit Statuses: Read & Write`
|
||||
- `Commit Statuses: Read`
|
||||
- `Issues: Read & Write`
|
||||
- `Metadata: Read Only`
|
||||
- `Metadata: Read`
|
||||
- `Pull requests: Read & Write`
|
||||
- `Workflows: Read & Write`
|
||||
|
||||
Organization permissions:
|
||||
|
||||
- `Administration: Read Only`
|
||||
- `Members: Read Only`
|
||||
|
||||
### Administration (write)
|
||||
|
||||
**Used for:** Creating new repositories with a pre-configured Nx workspace during initial onboarding.
|
||||
|
||||
**When it's used:** Only when you explicitly choose to create a new workspace through Nx Cloud's setup flow. [Single tenant instances](/docs/enterprise/single-tenant/overview) can safely forego this scope and will only lose the ability to create new workspaces through the app.
|
||||
|
||||
### Checks (write)
|
||||
|
||||
**Used for:** Updating CI run statuses so you can see the progress and results of your Nx Cloud pipeline executions directly in GitHub. Also used for Self-Healing CI status check runs in PRs.
|
||||
|
||||
**When it's used:** Automatically during CI runs to provide real-time status updates.
|
||||
|
||||
### Contents (read & write)
|
||||
|
||||
**Used for:**
|
||||
|
||||
- **Read:** Detecting your workspace's current Nx version to ensure compatibility. Reading files for Self-Healing CI.
|
||||
- **Write:** Adding Nx Cloud configuration (`nxCloudId` or access token) to your repository during setup. Creating commits and pushing fixes for Self-Healing CI.
|
||||
|
||||
**When it's used:** During initial setup and configuration, and regularly if Self-Healing CI is enabled.
|
||||
|
||||
### Commit statuses (read)
|
||||
|
||||
**Used for:** Reading commit status information to coordinate with other CI tools and provide accurate pipeline context.
|
||||
|
||||
**When it's used:** During CI pipeline executions to gather context about your commits.
|
||||
|
||||
### Issues (read & write)
|
||||
|
||||
**Used for:** PR comments (GitHub uses the Issues API for PR comments — see "Pull requests" below for more detail).
|
||||
|
||||
**When it's used:** During CI runs and when posting status comments.
|
||||
|
||||
### Metadata (read)
|
||||
|
||||
**Used for:** Accessing basic repository information (name, description, visibility). This is a required baseline permission for most GitHub App functionality.
|
||||
|
||||
### Pull requests (read & write)
|
||||
|
||||
**Used for:**
|
||||
|
||||
- **Read:** Gathering branch information, SHAs, and metadata necessary for CI pipeline execution and distributed task coordination.
|
||||
- **Write:** Posting comments on PRs with CI pipeline status, command results, and Self-Healing CI fixes. Creating PRs during initial Nx Cloud setup. Creating demo PRs for optional features like Self-Healing CI (only when you opt in).
|
||||
|
||||
**When it's used:** Read operations occur during CI runs. Write operations occur during setup and when posting status comments.
|
||||
|
||||
### Workflows (write)
|
||||
|
||||
**Used for:** Automatically configuring GitHub Actions workflow files when you opt in to features like Self-Healing CI and distributed task execution.
|
||||
|
||||
**When it's used:** Only when you explicitly enable these features through the Nx Cloud interface.
|
||||
|
||||
## Your Data and Security
|
||||
|
||||
Most information accessed through these permissions is used transiently during operations and is not stored. Limited version control metadata (such as branch names, SHAs, and commit information) may be stored as part of your CI pipeline execution records for analytics and debugging purposes.
|
||||
|
||||
[Nx Cloud is SOC2 Type II certified](https://security.nx.app). We implement industry-standard security practices including encryption at rest and in transit, access logging, and regular security audits.
|
||||
|
||||
You can revoke access to the Nx Cloud GitHub app at any time through your GitHub settings. Write operations (creating repos, posting comments, modifying workflows) only occur when explicitly triggered by your actions or when you opt in to specific features.
|
||||
|
||||
## Connect Your Nx Cloud Installation
|
||||
|
||||
Provide the following values to your developer productivity engineer so they can help connect Nx Cloud to your custom GitHub app:
|
||||
|
||||
@@ -22,7 +22,7 @@ Nx Cloud Self-Healing CI is an **AI-powered system that automatically detects, a
|
||||
## Enable Self-Healing CI
|
||||
|
||||
{% aside title="VCS Integration Required" type="note" %}
|
||||
Your Nx Cloud workspace needs to have a [VCS integration enabled](/docs/guides/nx-cloud/source-control-integration) to use Self-Healing CI. Self-Healing CI supports GitHub, GitLab, and Azure DevOps.
|
||||
Your Nx Cloud workspace needs to have a [VCS integration enabled](/docs/guides/nx-cloud/source-control-integration) to use Self-Healing CI. Self-Healing CI supports GitHub, GitLab, Azure DevOps, and Bitbucket.
|
||||
{% /aside %}
|
||||
|
||||
To enable Self-Healing CI in your workspace, you'll need to connect to Nx Cloud and configure your CI pipeline.
|
||||
@@ -33,17 +33,19 @@ If you haven't already connected to Nx Cloud, run the following command:
|
||||
npx nx@latest connect
|
||||
```
|
||||
|
||||
Next, check the [Nx Cloud workspace settings](https://cloud.nx.app/go/workspace/settings) in the Nx Cloud web application to ensure that "Self-Healing CI" is enabled (it should be enabled by default).
|
||||
Next, check the [Nx Cloud workspace settings](https://cloud.nx.app/go/workspace/settings/self-healing-ci) in the Nx Cloud web application to ensure that "Self-Healing CI" is enabled.
|
||||
|
||||
### Configure your CI pipeline
|
||||
|
||||
To enable Self-Healing CI, add the `npx nx fix-ci` command to your CI configuration:
|
||||
Add a step to your CI configuration's "main" job that runs the `fix-ci` command. It doesn't matter exactly what this job is called, it is whichever job in your config where you invoke `nx-cloud start-ci-run` and kick off your `nx run-many` or `nx affected` commands.
|
||||
|
||||
{% tabs syncKey="ci-provider" %}
|
||||
By default, your CI provider will only run the step if the previous steps succeeded, but by definition we want to run Self-Healing CI even when previous steps fail. Therefore make sure you are using a condition of `if: always()` or equivalent to ensure it runs even when previous steps fail:
|
||||
|
||||
{% tabs %}
|
||||
|
||||
{% tabitem label="GitHub Actions" %}
|
||||
|
||||
```yaml {% meta="{11,12}" %}
|
||||
```yaml
|
||||
# .github/workflows/ci.yml
|
||||
name: CI
|
||||
|
||||
@@ -51,18 +53,25 @@ jobs:
|
||||
main:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
...
|
||||
# Your existing steps which check out the repo, start-ci-run, install
|
||||
# dependencies, etc.
|
||||
# These are just illustrative examples...
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
- run: npx nx-cloud start-ci-run
|
||||
- run: npm ci
|
||||
- run: npx nx affected -t lint test build
|
||||
|
||||
# NEW: Add this step at the end of your job
|
||||
- run: npx nx fix-ci
|
||||
if: always()
|
||||
if: always() # IMPORTANT: Always run
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
|
||||
{% tabitem label="GitLab CI" %}
|
||||
|
||||
```yaml {% meta="{9,10,11}" %}
|
||||
```yaml
|
||||
# .gitlab-ci.yml
|
||||
stages:
|
||||
- build
|
||||
@@ -70,9 +79,16 @@ stages:
|
||||
main:
|
||||
stage: build
|
||||
script:
|
||||
# Your existing steps which check out the repo, start-ci-run, install
|
||||
# dependencies, etc.
|
||||
- npx nx-cloud start-ci-run
|
||||
- npm ci
|
||||
- npx nx affected -t lint test build
|
||||
# NEW: Add this section at the end of your job if you don't
|
||||
# already have an after_script section
|
||||
after_script:
|
||||
# after_script runs regardless of job success/failure
|
||||
# IMPORTANT: after_script runs regardless of job success/failure
|
||||
# so it's like if: always() on GitHub
|
||||
- npx nx fix-ci
|
||||
```
|
||||
|
||||
@@ -80,7 +96,7 @@ main:
|
||||
|
||||
{% tabitem label="Azure DevOps" %}
|
||||
|
||||
```yaml {% meta="{14,15,16}" %}
|
||||
```yaml
|
||||
# azure-pipelines.yml
|
||||
trigger:
|
||||
- main
|
||||
@@ -89,295 +105,286 @@ pool:
|
||||
vmImage: 'ubuntu-latest'
|
||||
|
||||
steps:
|
||||
# Your existing steps which check out the repo, start-ci-run, install
|
||||
# dependencies, etc.
|
||||
# These are just illustrative examples...
|
||||
- task: NodeTool@0
|
||||
inputs:
|
||||
versionSpec: '22.x'
|
||||
- script: npx nx-cloud start-ci-run
|
||||
- script: npm ci
|
||||
- script: npx nx affected -t lint test build
|
||||
displayName: 'Run affected tasks'
|
||||
|
||||
# NEW: Add this step at the end of your job
|
||||
- script: npx nx fix-ci
|
||||
displayName: 'Fix CI'
|
||||
condition: always()
|
||||
condition: always() # IMPORTANT: Always run
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
|
||||
{% tabitem label="Bitbucket Pipelines" %}
|
||||
|
||||
```yaml
|
||||
# bitbucket-pipelines.yml
|
||||
image: node:22
|
||||
|
||||
pipelines:
|
||||
pull-requests:
|
||||
'**':
|
||||
- step:
|
||||
name: CI
|
||||
script:
|
||||
# Your existing steps which start-ci-run, install
|
||||
# dependencies, etc.
|
||||
# These are just illustrative examples...
|
||||
- npx nx-cloud start-ci-run
|
||||
- npm ci
|
||||
- npx nx affected -t lint test build
|
||||
after-script:
|
||||
# NEW: Add this section at the end of your step
|
||||
# IMPORTANT: after-script runs regardless of step success/failure
|
||||
# so it's like if: always() on GitHub
|
||||
- npx nx fix-ci
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
|
||||
{% /tabs %}
|
||||
|
||||
### Enable Auto-fixing
|
||||
> NOTE: If all tasks succeed then the `fix-ci` command becomes a no-op automatically, so that is why "always" is recommended.
|
||||
|
||||
{% youtube
|
||||
src="https://youtu.be/EmZcENiCG64"
|
||||
title="Enable Auto-fixing"
|
||||
/%}
|
||||
## Configuring Self-Healing CI
|
||||
|
||||
By default, Self-Healing CI proposes a fix for you to review and only applies it automatically to your PR after you confirm it. However, for some tasks, it makes sense to have them be auto-fixed without waiting for manual approval. Auto-fixes are only applied if the verification phase passes.
|
||||
Self-Healing CI configuration is primarily managed through your [Nx Cloud workspace settings](https://cloud.nx.app/go/workspace/settings/self-healing-ci) in the Nx Cloud dashboard. This provides a centralized, auditable way to control the feature's behavior.
|
||||
|
||||
Below is an example of enabling auto-fixing for the Nx `format` command and `lint` tasks using the [`--auto-apply-fixes`](/docs/reference/nx-cloud-cli#--auto-apply-fixes) flag:
|
||||
### General Settings
|
||||
|
||||
{% tabs syncKey="ci-provider" %}
|
||||
| Setting | Description |
|
||||
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Enable Self-Healing CI** | Enable Self-Healing CI for PRs in the current workspace |
|
||||
| **GitHub PR comments** | Show Self-Healing CI feedback and actions within GitHub PR comments (in addition to the Nx Cloud UI) |
|
||||
| **Auto-retry flaky tasks** | Automatically re-run tasks that are detected as flaky to improve CI reliability. This works by pushing an empty commit to the PR branch |
|
||||
| **Allow public link access** | Allow anyone with access to the link the ability to apply or reject a suggested change (not recommended unless absolutely necessary) |
|
||||
| **Draft PR handling** | Allow Self-Healing CI to create fixes for draft PRs |
|
||||
| **Protected branch prefixes** | Configure branch prefixes for which fixes should not be generated (e.g., `release/` will match `release/v1.0`). The default branch and branches named `main`, `master`, `trunk`, `dev`, `stable`, or `canary` will never have fixes generated |
|
||||
|
||||
{% tabitem label="GitHub Actions" %}
|
||||
### Eligible Tasks
|
||||
|
||||
```yaml
|
||||
# .github/workflows/ci.yml
|
||||
name: CI
|
||||
Control which failing tasks Nx Cloud will actively try and fix for pull request CI pipeline executions.
|
||||
|
||||
jobs:
|
||||
main:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
...
|
||||
- name: Start CI Run
|
||||
run: npx nx start-ci-run --auto-apply-fixes="*format*,*lint*" --no-distribution
|
||||
...
|
||||
```
|
||||
{% aside type="note" title="CLI Override Available" %}
|
||||
This is analogous to the `--fix-tasks` flag on `nx-cloud start-ci-run`. Anything set on the CLI will take precedence over the settings here.
|
||||
{% /aside %}
|
||||
|
||||
{% /tabitem %}
|
||||
You can choose between two modes:
|
||||
|
||||
{% tabitem label="GitLab CI" %}
|
||||
| Mode | Description |
|
||||
| --------------------- | -------------------------------------------------------------------------------- |
|
||||
| **Any failing task** | Any task that fails during PR CI pipeline executions is eligible (recommended) |
|
||||
| **Specific patterns** | Limit Self-Healing CI to failing PR tasks that match the specified glob patterns |
|
||||
|
||||
```yaml
|
||||
# .gitlab-ci.yml
|
||||
stages:
|
||||
- build
|
||||
You can also specify **Never fix** patterns to exclude certain tasks from ever being fixed by Self-Healing CI. For example, `*e2e*` would exclude all e2e-related tasks.
|
||||
|
||||
main:
|
||||
stage: build
|
||||
script:
|
||||
- npx nx start-ci-run --auto-apply-fixes="*format*,*lint*" --no-distribution
|
||||
...
|
||||
```
|
||||
### Auto-Apply Verified Code Changes
|
||||
|
||||
{% /tabitem %}
|
||||
Automatically commit code change suggestions to the PR branch **when ALL of these are true**:
|
||||
|
||||
{% tabitem label="Azure DevOps" %}
|
||||
1. The task **matches the glob patterns** configured below
|
||||
2. The AI agent is **highly confident** that the suggested code change will fix the failing task
|
||||
3. The suggestion has been **explicitly verified** to fix the failing task
|
||||
|
||||
```yaml
|
||||
# azure-pipelines.yml
|
||||
trigger:
|
||||
- main
|
||||
{% aside type="note" title="CLI Override Available" %}
|
||||
This is analogous to the `--auto-apply-fixes` flag on `nx-cloud start-ci-run`. Anything set on the CLI will take precedence over the settings here.
|
||||
{% /aside %}
|
||||
|
||||
pool:
|
||||
vmImage: 'ubuntu-latest'
|
||||
#### Deterministic Nx Checks
|
||||
|
||||
steps:
|
||||
- script: npx nx start-ci-run --auto-apply-fixes="*format*,*lint*" --no-distribution
|
||||
displayName: 'Start CI Run'
|
||||
...
|
||||
```
|
||||
A built-in preset that auto-fixes failures from `nx format:check`, `nx sync:check`, and `nx conformance:check` commands. The AI agent has special knowledge of these commands and will invoke the corresponding "writable" version to fix the issue (e.g., `nx format`). You can safely enable this preset even if you only use a subset of these commands.
|
||||
|
||||
{% /tabitem %}
|
||||
#### Additional Include Patterns
|
||||
|
||||
{% /tabs %}
|
||||
Tasks matching these patterns will also have high-confidence, verified code changes auto-applied. For example: `*build*`, `*test*`, `lint`.
|
||||
|
||||
Tasks are passed to the `--auto-apply-fixes` as `<project>:<task-name>:<configuration>`. Commands like `nx format` which you configure with `nx-cloud record --` are passed as `nx-cloud record -- <params>`.
|
||||
#### Exclude Patterns
|
||||
|
||||
### Specify Which Tasks to Fix
|
||||
Tasks matching these patterns will **never** have code changes auto-applied, even if they match the include patterns or presets specified above. For example: `*e2e*`.
|
||||
|
||||
{% youtube
|
||||
src="https://youtu.be/KSb48zHbaHg"
|
||||
title="Specify Which Tasks to Fix"
|
||||
/%}
|
||||
## Configuration with SELF_HEALING.md
|
||||
|
||||
By using the [`--fix-tasks`](/docs/reference/nx-cloud-cli#--fix-tasks) flag you can fine-tune which tasks should be considered by the Nx Cloud self-healing CI. Below is an example of running self-healing on all tasks except `deploy` and `test` tasks.
|
||||
Create a `.nx/SELF_HEALING.md` file in your repository to provide project-specific instructions to the Self-Healing CI agent. This file contains freeform markdown that the AI agent reads and interprets naturally.
|
||||
|
||||
{% tabs syncKey="ci-provider" %}
|
||||
{% aside title="Why a dedicated file?" type="note" %}
|
||||
Using `.nx/SELF_HEALING.md` instead of `AGENTS.md` (or equivalent) separates CI-specific instructions from local development context. The file lives in the `.nx` directory alongside other Nx Cloud configuration.
|
||||
{% /aside %}
|
||||
|
||||
{% tabitem label="GitHub Actions" %}
|
||||
|
||||
```yaml
|
||||
# .github/workflows/ci.yml
|
||||
name: CI
|
||||
|
||||
jobs:
|
||||
main:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
...
|
||||
- name: Start CI Run
|
||||
run: npx nx start-ci-run --fix-tasks="!*deploy,!*test" --no-distribution
|
||||
...
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
|
||||
{% tabitem label="GitLab CI" %}
|
||||
|
||||
```yaml
|
||||
# .gitlab-ci.yml
|
||||
stages:
|
||||
- build
|
||||
|
||||
main:
|
||||
stage: build
|
||||
script:
|
||||
- npx nx start-ci-run --fix-tasks="!*deploy,!*test" --no-distribution
|
||||
...
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
|
||||
{% tabitem label="Azure DevOps" %}
|
||||
|
||||
```yaml
|
||||
# azure-pipelines.yml
|
||||
trigger:
|
||||
- main
|
||||
|
||||
pool:
|
||||
vmImage: 'ubuntu-latest'
|
||||
|
||||
steps:
|
||||
- script: npx nx start-ci-run --fix-tasks="!*deploy,!*test" --no-distribution
|
||||
displayName: 'Start CI Run'
|
||||
...
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
|
||||
{% /tabs %}
|
||||
|
||||
Similarly, if you only want to self-heal linting tasks you'd use `--fix-tasks="*lint*"`.
|
||||
|
||||
Tasks are passed to the `--fix-tasks` as `<project>:<task-name>:<configuration>`. Commands like `nx format` which you configure with `nx-cloud record --` are passed as `nx-cloud record -- <params>`.
|
||||
|
||||
### Customize Self-Healing Behavior
|
||||
|
||||
You can customize how Self-Healing CI behaves in your workspace by creating a `CLAUDE.md` file in your repository root. This file allows you to define custom classification rules and predefined fixes tailored to your project's specific needs.
|
||||
|
||||
#### Customize Failure Classification
|
||||
|
||||
Before proposing a fix, the Self-Healing CI agent classifies each failure into one of three categories:
|
||||
|
||||
- **`code_change`** - Failures directly caused by PR changes. Self-Healing will _propose and implement code fixes_.
|
||||
- **`environment_state`** - Failures caused by environmental issues (network errors, service outages, resource constraints). Self-Healing will _not propose fixes_.
|
||||
- **`flaky_task`** - Non-deterministic failures from timing issues or race conditions. Self-Healing _detects the flakiness and retriggers a pipeline run for the flaky task_.
|
||||
|
||||
You can override the default classification behavior with custom rules in `CLAUDE.md` by describing the nature of the error as well as one of the before mentioned categories:
|
||||
### Example SELF_HEALING.md
|
||||
|
||||
```markdown
|
||||
// CLAUDE.md
|
||||
# Self-Healing Configuration
|
||||
|
||||
## Self-Healing CI
|
||||
## Confidence Rules
|
||||
|
||||
### Classification Customization
|
||||
- Fixes involving "test" targets should require high confidence
|
||||
- Formatting fixes can be applied with medium confidence
|
||||
|
||||
When analyzing failures, override the default classification in these cases:
|
||||
## Off-Limits Areas
|
||||
|
||||
- If there are errors about missing environment variables (like API_KEY, DATABASE_URL, etc.) classify them as 'environment_state'.
|
||||
- `/src/generated/` - auto-generated, do not modify
|
||||
- `/legacy/` - requires manual review
|
||||
|
||||
## Fix Preferences
|
||||
|
||||
- Prefer updating ESLint rules over adding disable comments
|
||||
- For type errors, prefer explicit types over `any`
|
||||
|
||||
## Context
|
||||
|
||||
See ARCHITECTURE.md for module boundaries.
|
||||
```
|
||||
|
||||
#### Define Predefined Fixes
|
||||
### What to Include
|
||||
|
||||
For common, deterministic failures, you can define predefined fixes that Self-Healing CI should apply automatically. This is particularly useful for tasks that have standard, repeatable solutions. Here's an example to trigger `lint --fix` instead of having the AI attempt to implement the fix:
|
||||
| Section | Purpose | Example |
|
||||
| -------------------- | --------------------------------------------------- | ---------------------------------------------------------------------------- |
|
||||
| **Confidence Rules** | Override how the AI categorizes failure severity | "Failures in `**/migrations/**` should be classified as `environment_state`" |
|
||||
| **Off-Limits Areas** | Directories or files the agent should never modify | "`/src/generated/` - auto-generated code" |
|
||||
| **Fix Preferences** | Guide the agent's approach to common issues | "Prefer updating ESLint rules over adding disable comments" |
|
||||
| **Predefined Fixes** | Specify deterministic solutions for known failures | "For lint failures, always try running `nx lint --fix` first" |
|
||||
| **Context** | Reference other documentation the agent should read | "See ARCHITECTURE.md for module boundaries" |
|
||||
|
||||
```markdown
|
||||
// CLAUDE.md
|
||||
### Using CLAUDE.md
|
||||
|
||||
## Self-Healing CI
|
||||
If your repository already has a `CLAUDE.md` file at the root, the Self-Healing CI agent will read it for additional context. When both files exist:
|
||||
|
||||
Predefined fix:
|
||||
- **SELF_HEALING.md takes precedence** for any conflicting instructions
|
||||
- Both files are read, so general context in `CLAUDE.md` is still available
|
||||
- CI-specific instructions should go in `SELF_HEALING.md`
|
||||
|
||||
- If a failed task id contains ":lint", fix it by running linting on the project where it failed with the `--fix` flag. Example: `nx run myapp:lint --fix` where "myapp" is the app the task failed on.
|
||||
```
|
||||
This allows teams to maintain `CLAUDE.md` for local development workflows while using `SELF_HEALING.md` for CI-specific behavior.
|
||||
|
||||
These predefined fixes allow Self-Healing CI to apply deterministic solutions without needing to analyze the code, speeding up the fix generation process for common scenarios.
|
||||
### Viewing Configuration Status
|
||||
|
||||
## How Self-Healing CI works
|
||||
After a CI run, navigate to the pipeline execution in Nx Cloud and check the **Configurations** tab to see whether `SELF_HEALING.md` was detected and applied.
|
||||
|
||||
Here's what happens when you push a PR with Self-Healing CI enabled:
|
||||
## Receiving Fix Notifications
|
||||
|
||||

|
||||
### In Your Editor
|
||||
|
||||
### 1. Failure Detection
|
||||
|
||||
When you push your PR and tasks fail, Nx Cloud automatically detects the failure and triggers the self-healing process.
|
||||
|
||||
### 2. Fix Generation
|
||||
|
||||
Nx Cloud starts an AI agent that analyzes the failed tasks and creates an appropriate fix, leveraging:
|
||||
|
||||
- Complete failure context, including the exact tasks that ran and their error logs
|
||||
- The [Nx graph](/docs/features/explore-graph), which provides context about project structure, dependencies, configuration, and runnable tasks
|
||||
|
||||
### 3. Notification
|
||||
|
||||
Once the fix is available, you'll be notified immediately based on where you're currently working:
|
||||
|
||||
{% tabs syncKey="notification-self-healing-fix" %}
|
||||
|
||||
{% tabitem label="PR Comments" %}
|
||||
|
||||
You will see the notification about an available fix from Nx Cloud directly in your VCS PR comments:
|
||||
|
||||

|
||||
|
||||
{% /tabitem %}
|
||||
|
||||
{% tabitem label="In your editor" %}
|
||||
|
||||
If you have [Nx Console](/docs/getting-started/editor-setup) installed, you'll get a notification directly in your editor:
|
||||
With [Nx Console](/docs/getting-started/editor-setup) installed, you'll receive notifications directly in VS Code, Cursor, or WebStorm when a fix is available:
|
||||
|
||||

|
||||
|
||||
Clicking the notification will open a dedicated view showing the failed task log, the status of the fix as well as the actual git diff.
|
||||
### On your Pull Request/Merge Request
|
||||
|
||||

|
||||
Self-Healing CI posts a comment on your PR with:
|
||||
|
||||
{% /tabitem %}
|
||||
- A summary of the reasoning behind the fix
|
||||
- A diff view showing the proposed changes
|
||||
- Buttons to apply or reject the fix
|
||||
|
||||
{% /tabs %}
|
||||

|
||||
|
||||
### 4. Verification
|
||||
## Applying and Reverting Fixes
|
||||
|
||||
While you're being notified, Nx Cloud automatically **runs a verification phase** in the background.
|
||||
### Applying a Fix
|
||||
|
||||

|
||||
You can apply a proposed fix through:
|
||||
|
||||
This reruns the failed task with the proposed fix to ensure it actually solves the issue. You can skip this step if you're confident the fix is valid, but it's useful for verifying the correctness of the change.
|
||||
1. **Editor notification** - Click "Apply" in the Nx Console notification
|
||||
2. **PR/MR comment** - Click the "Apply" button
|
||||
3. **Nx Cloud UI** - Use the apply button in the diff viewer
|
||||
|
||||
### 5. Review & Apply
|
||||
### Applying Locally for Fine-Tuning
|
||||
|
||||
You can review the fix and decide whether to apply or reject it. If you apply the fix, **Nx Cloud automatically pushes a commit to your original PR**.
|
||||
If a fix is 90% correct but needs minor adjustments:
|
||||
|
||||
{% tabs syncKey="apply-self-healing-fix" %}
|
||||
1. Click "Apply Locally" in the GitHub comment or Nx Cloud UI
|
||||
2. Run the provided command in your terminal
|
||||
3. Make your adjustments and commit
|
||||
|
||||
{% tabitem label="PR Comments" %}
|
||||

|
||||
|
||||
Review the Git diff directly in the comment and click "Apply fix" or "Reject fix". For a more detailed view, click "View interactive diff" to open the Nx Cloud app's advanced diff viewer.
|
||||
### Reverting a Fix
|
||||
|
||||

|
||||
If you accidentally applied a fix, you can:
|
||||
|
||||
{% /tabitem %}
|
||||
1. Manually revert the Git commit
|
||||
2. Use the "Revert changes" button in the Nx Cloud diff viewer
|
||||
|
||||
{% tabitem label="Nx Cloud Application" %}
|
||||
## Advanced: CLI Overrides
|
||||
|
||||

|
||||
{% aside type="caution" title="Prefer workspace settings" %}
|
||||
We recommend configuring Self-Healing CI through **[workspace settings](https://cloud.nx.app/go/workspace/settings/self-healing-ci)** in the Nx Cloud dashboard. CLI overrides should only be used for temporary, branch-specific adjustments.
|
||||
{% /aside %}
|
||||
|
||||
{% /tabitem %}
|
||||
{% youtube
|
||||
src="https://youtu.be/KSb48zHbaHg"
|
||||
title="Specify Which Tasks to Fix"
|
||||
/%}
|
||||
|
||||
{% tabitem label="In your editor" %}
|
||||
### When to Use CLI Overrides
|
||||
|
||||
With [Nx Console](/docs/getting-started/editor-setup) installed, open the dedicated CI view which will show you the fix details as well as the buttons to apply, apply locally or reject the fix.
|
||||
- **Temporarily disable** Self-Healing CI on a sensitive branch
|
||||
- **Test configurations** before committing to workspace settings
|
||||
|
||||

|
||||
### Available Flags
|
||||
|
||||
{% /tabitem %}
|
||||
Pass these flags to `nx-cloud start-ci-run`:
|
||||
|
||||
{% /tabs %}
|
||||
| Flag | Description | Example |
|
||||
| -------------------- | ------------------------------------------- | ----------------------------- |
|
||||
| `--fix-tasks` | Override which tasks are eligible for fixes | `--fix-tasks="*lint*,*test*"` |
|
||||
| `--auto-apply-fixes` | Override which tasks can be auto-applied | `--auto-apply-fixes="*lint*"` |
|
||||
|
||||
#### Apply Fixes Locally
|
||||
### Disabling Features via CLI
|
||||
|
||||
If you want to tweak a fix before committing it, you can **apply it locally** rather than having it pushed directly to your PR. To do this, use the corresponding buttons on the GitHub comment, Nx Console view, or Nx Cloud app to get the command to run locally:
|
||||
Use an empty string to **disable** a feature for a specific CI run:
|
||||
|
||||

|
||||
```shell
|
||||
# Disable fix generation entirely for this run
|
||||
npx nx-cloud start-ci-run --fix-tasks=""
|
||||
|
||||
#### Revert Changes
|
||||
# Disable auto-apply entirely for this run
|
||||
npx nx-cloud start-ci-run --auto-apply-fixes=""
|
||||
```
|
||||
|
||||
If you accidentally applied a fix or it turns out to be incorrect, you can easily revert it by clicking the link in the VCS PR comment, which opens the Nx Cloud webapp where you can revert the fix.
|
||||
Both flags treat empty string consistently as an explicit "disable" override.
|
||||
|
||||

|
||||
### Pattern Syntax
|
||||
|
||||
Alternatively, you can pull the PR and remove the Git commit manually.
|
||||
Patterns use glob syntax to match task names:
|
||||
|
||||
## Learn more
|
||||
```shell
|
||||
# Only fix lint and test tasks
|
||||
npx nx-cloud start-ci-run --fix-tasks="*lint*,*test*"
|
||||
|
||||
Self-Healing CI represents the next evolution in CI automation, moving beyond just speeding up builds to actually fixing them automatically. Learn more about this feature in our blog post: [Introducing Self-Healing CI for Nx and Nx Cloud](https://nx.dev/blog/nx-self-healing-ci).
|
||||
# Fix everything except e2e tasks
|
||||
npx nx-cloud start-ci-run --fix-tasks="!*e2e*"
|
||||
|
||||
# Auto-apply only lint fixes
|
||||
npx nx-cloud start-ci-run --auto-apply-fixes="lint"
|
||||
```
|
||||
|
||||
### Precedence Rules
|
||||
|
||||
When both workspace settings and CLI overrides are present:
|
||||
|
||||
1. **CLI override** (if provided) always takes precedence
|
||||
2. Falls back to **workspace settings** if no CLI override
|
||||
3. Empty string (`""`) is an explicit "disable", not "use defaults"
|
||||
|
||||
### Viewing Applied Configuration
|
||||
|
||||
After your CI runs, navigate to the CIPE → **Configurations** tab to see:
|
||||
|
||||
- What workspace settings were relevant at the time of the CI pipeline execution
|
||||
- What CLI overrides were applied, if any
|
||||
- What the final, effective configuration was
|
||||
|
||||
---
|
||||
|
||||
## Learn More
|
||||
|
||||
- [Nx AI Documentation](/docs/features/enhance-ai)
|
||||
- [Nx Console Editor Setup](/docs/getting-started/editor-setup)
|
||||
- [Nx Cloud](/docs/getting-started/nx-cloud)
|
||||
|
||||
@@ -1,180 +1,82 @@
|
||||
---
|
||||
title: 'Enhance Your LLM'
|
||||
description: 'Learn how Nx enhances your AI assistant by providing rich workspace metadata, architectural insights, and project relationships to make your LLM smarter and more context-aware.'
|
||||
title: 'Enhance Your AI Coding Agent'
|
||||
description: 'Learn how Nx enhances your AI assistant by providing rich workspace metadata, architectural insights, and CI integration for autonomous workflows.'
|
||||
sidebar:
|
||||
order: 3
|
||||
filter: 'type:Features'
|
||||
---
|
||||
|
||||
{% youtube src="https://youtu.be/dRQq_B1HSLA" title="We Just Shipped the Monorepo MCP for Copilot" /%}
|
||||
AI agents are moving beyond autocomplete. They can now operate independently across projects. But most setups hit a wall: agents lack workspace context (seeing files, not architecture), generate inconsistent code, and have a hard time to interact with CI.
|
||||
|
||||
Monorepos [provide an ideal foundation for AI-powered development](https://nx.dev/blog/nx-and-ai-why-they-work-together), enabling cross-project reasoning and code generation. However, without proper context, **LLMs struggle to understand your workspace architecture**, seeing only individual files rather than the complete picture.
|
||||
Nx monorepos solve this by enabling cross-project reasoning and by providing the structured metadata and CI integration that agents need to work autonomously:
|
||||
|
||||
Nx transforms your AI assistant by providing rich workspace metadata that enables it to:
|
||||
- Deep **workspace architecture** understanding and project relationships
|
||||
- **Code generators** for fast, predictable scaffolding
|
||||
- **CI pipeline integration** to fix failures autonomously
|
||||
- The ability to **iterate until CI is green** without human intervention
|
||||
|
||||
- Understand your **workspace architecture** and project relationships
|
||||
- Identify **project owners** and team responsibilities
|
||||
- Access **Nx documentation** for accurate guidance
|
||||
- Leverage **code generators** for consistent scaffolding
|
||||
- Connect to your **CI pipeline** to help fix failures
|
||||
## Setup
|
||||
|
||||
The goal is to transform your AI assistant from a generic code helper into an architecturally-aware collaborator that understands your specific workspace structure and can make intelligent, context-aware decisions.
|
||||
|
||||
## How Nx MCP Enhances Your LLM
|
||||
|
||||
The [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) is an open standard that enables AI models to interact with your development environment through a standardized interface. Nx implements an MCP server via the [Nx Console](/docs/getting-started/editor-setup) that exposes workspace metadata to compatible AI assistants like GitHub Copilot, Claude, and others.
|
||||
|
||||
With the Nx MCP server, your AI assistant gains a "map" of your entire system being able to go from just reasoning at the file level to seeing the higher-level picture. This allows the LLM to move between different abstraction levels - from high-level architecture down to specific implementation details:
|
||||
|
||||

|
||||
|
||||
The Nx MCP server exposes tools for workspace analysis, code generation, documentation lookup, and CI/CD analytics. For a complete list of available tools and their descriptions, see the [Nx MCP Server Reference](/docs/reference/nx-mcp#available-tools).
|
||||
|
||||
## Setting Up Nx MCP
|
||||
|
||||
To configure Nx for AI agents and AI-Assistants, run the following command:
|
||||
To configure your Nx workspace for AI agents, run:
|
||||
|
||||
```shell
|
||||
npx nx configure-ai-agents
|
||||
```
|
||||
|
||||
This configures Nx Console which automatically configures and serves the Nx MCP server for you if you're using VSCode or Cursor. It also sets up the corresponding AI agent configuration files (e.g. `CLAUDE.md`, `AGENTS.md`,...).
|
||||
This sets up:
|
||||
|
||||
### IDE Setup
|
||||
- **Agent configuration files**: `CLAUDE.md`, `AGENTS.md` with workspace-specific guidelines
|
||||
- **Agent skills**: Domain-specific knowledge for monorepo workflows — workspace exploration, code generation, task execution, CI monitoring, and package linking. Skills teach agents _how_ to work with Nx rather than dumping data into context.
|
||||
- **Nx MCP server**: Provides connectivity to Nx Cloud CI pipelines, self-healing fixes, running processes, and Nx documentation — things agents can't easily reach on their own
|
||||
|
||||
For VS Code, Cursor, and JetBrains IDE users:
|
||||
## What This Enables
|
||||
|
||||
1. Install [Nx Console](/docs/getting-started/editor-setup) from the marketplace
|
||||
2. You'll receive a notification to "Improve Copilot/AI agent with Nx-specific context"
|
||||
3. Click "Yes" to configure the MCP server
|
||||
### Self-Healing CI Integration
|
||||
|
||||

|
||||
Nx Cloud provides AI-powered [Self-Healing CI](/docs/features/ci-features/self-healing-ci) that analyzes failed runs and proposes verified fixes. With `configure-ai-agents`, your local agent connects to this CI counterpart via skills and the Nx MCP, gaining full context about run information, failures, and suggested fixes.
|
||||
|
||||
If you miss the notification, run the `nx.configureMcpServer` (`Nx: Setup MCP Server` in JetBrains) command from the command palette (Cursor: `Ctrl/Cmd + Shift + P`, JetBrains IDEs: `Ctrl/Cmd + Shift + A`).
|
||||
|
||||
### Other MCP-Compatible Clients
|
||||
|
||||
For other MCP-compatible clients like Claude Desktop, Claude Code, or Warp, you can configure the Nx MCP server manually. See the [Nx MCP Server Reference](/docs/reference/nx-mcp#client-specific-setup) for detailed setup instructions for each client.
|
||||
|
||||
Quick example for Claude Code:
|
||||
|
||||
```shell
|
||||
claude mcp add nx-mcp npx nx-mcp@latest
|
||||
```
|
||||
|
||||
## Powerful Use Cases
|
||||
|
||||
### Understanding Your Workspace Architecture
|
||||
|
||||
{% youtube src="https://youtu.be/RNilYmJJzdk" title="Nx Just Made Your LLM Way Smarter" /%}
|
||||
|
||||
Ask your AI assistant about your workspace structure and get detailed, accurate responses about projects, their types, and relationships:
|
||||
Your agent can autonomously iterate until CI passes:
|
||||
|
||||
```text
|
||||
What is the structure of this workspace?
|
||||
How are the projects organized?
|
||||
Commit this work, create a PR, and monitor CI until it's green.
|
||||
```
|
||||
|
||||
With Nx MCP, your AI assistant can:
|
||||
The workflow:
|
||||
|
||||
- Identify applications and libraries in your workspace
|
||||
- Understand project categorization through tags
|
||||
- Recognize technology types (feature, UI, data-access)
|
||||
- Determine project ownership and team responsibilities
|
||||
1. Agent pushes changes and creates PR
|
||||
2. Monitors CI pipeline
|
||||
3. Receives failure context from Nx Cloud and Self-Healing CI
|
||||
4. Accepts proposed fix or pulls context locally and manually applies it
|
||||
5. Repeats until CI is green
|
||||
|
||||

|
||||
This reduces context-switching—you review the final PR rather than intervening at each failure.
|
||||
|
||||
You can also get informed suggestions about where to implement new functionality:
|
||||
### Workspace Architecture Understanding
|
||||
|
||||
```text
|
||||
Where should I implement a feature for adding products to cart?
|
||||
```
|
||||
Nx exposes the project graph and relevant metadata to AI agents. This helps them move faster and more precisely:
|
||||
|
||||

|
||||
- Identify all applications and libraries in the workspace
|
||||
- Understand project relationships and dependencies
|
||||
- Recognize project types and ownership via tags
|
||||
- Determine which projects are affected by changes
|
||||
- Suggest where to implement new functionality based on existing structure
|
||||
|
||||
Learn more about workspace architecture understanding in our blog post [Nx Just Made Your LLM Way Smarter](https://nx.dev/blog/nx-just-made-your-llm-smarter).
|
||||
This architectural awareness is critical for agents operating in large monorepos where understanding project relationships determines the quality of generated code.
|
||||
|
||||
### Instant CI Failure Resolution
|
||||
### Predictable, Fast Code Generation
|
||||
|
||||
{% youtube src="https://youtu.be/fPqPh4h8RJg" title="Connect Your Editor, CI and LLMs" /%}
|
||||
AI-generated code is token-intensive, slow, and not guaranteed to align with patterns in other projects. Nx generators solve this by providing predictable scaffolding that agents can invoke and then adapt.
|
||||
|
||||
When a CI build fails, Nx Console can notify you directly in your editor:
|
||||
Your AI agent can:
|
||||
|
||||

|
||||
1. Find generators from [Nx plugins](/docs/plugin-registry) or custom [local workspace generators](/docs/extending-nx/local-generators)
|
||||
2. Run the generator with correct options
|
||||
3. Make small adjustments based on the specific situation
|
||||
|
||||
Your AI assistant can then:
|
||||
This approach is faster, produces consistent code across projects, and reduces hallucinations.
|
||||
|
||||
1. Access detailed information from Nx Cloud about the failed build
|
||||
2. Analyze your git history to understand what changed in your PR
|
||||
3. Understand the error context and affected files
|
||||
4. Help implement the fix right in your editor
|
||||
## Learn More
|
||||
|
||||
This integration dramatically improves the development velocity because you get immediately notified when an error occurs, you don't even have to leave your editor to understand what broke, and the LLM can help you implement or suggest a possible fix.
|
||||
|
||||
Learn more about CI integration in our blog post [Save Time: Connecting Your Editor, CI and LLMs](https://nx.dev/blog/nx-editor-ci-llm-integration).
|
||||
|
||||
### Smart Code Generation with AI-Enhanced Generators
|
||||
|
||||
{% youtube src="https://youtu.be/PXNjedYhZDs" title="Enhancing Nx Generators with AI" /%}
|
||||
|
||||
Nx generators provide predictable code scaffolding, while AI adds intelligence and contextual understanding. Instead of having the AI generate everything from scratch, you get the best of both worlds:
|
||||
|
||||
```text
|
||||
Create a new React library into the packages/orders/feat-cancel-orders folder
|
||||
and call the library with the same name of the folder structure. Afterwards,
|
||||
also connect it to the main shop application.
|
||||
```
|
||||
|
||||
Your AI assistant will:
|
||||
|
||||
1. Identify the appropriate generator and its parameters
|
||||
2. Open the Nx Console Generate UI with preset values
|
||||
3. Let you review and customize the options
|
||||
4. Execute the generator and help integrate the new code with your existing projects
|
||||
|
||||

|
||||
|
||||
This approach ensures consistent code that follows your organization's best practices while still being tailored to your specific needs. Learn more about AI-enhanced generators in our blog post [Enhancing Nx Generators with AI](https://nx.dev/blog/nx-generators-ai-integration).
|
||||
|
||||
### Documentation-Aware Configuration
|
||||
|
||||
{% youtube src="https://youtu.be/V2W94Sq_v6A?si=aBA-eppEw0fHrh5O&t=388" title="Making Cursor Smarter with an MCP Server" /%}
|
||||
|
||||
Get accurate guidance on Nx configuration without worrying about hallucinations or outdated information:
|
||||
|
||||
```text
|
||||
Can you configure Nx release for the packages of this workspace?
|
||||
Update nx.json with the necessary configuration using conventional commits
|
||||
as the versioning strategy.
|
||||
```
|
||||
|
||||
The AI assistant will:
|
||||
|
||||
1. Query the Nx docs for the latest information on release configuration
|
||||
2. Understand your workspace structure to identify packages
|
||||
3. Generate the correct configuration based on your specific needs
|
||||
4. Apply the changes to your nx.json file
|
||||
|
||||
Learn more about documentation-aware configuration in our blog post [Making Cursor Smarter with an MCP Server For Nx Monorepos](https://nx.dev/blog/nx-made-cursor-smarter).
|
||||
|
||||
### Cross-Project Dependency Analysis
|
||||
|
||||
{% youtube src="https://youtu.be/dRQq_B1HSLA?si=lhHsjRvwgijC1IL8&t=186" title="Nx MCP Now Available for VS Code Copilot" /%}
|
||||
|
||||
Understand the impact of changes across your monorepo with questions like:
|
||||
|
||||
```text
|
||||
If I change the public API of feat-product-detail, which other projects
|
||||
might be affected by that change?
|
||||
```
|
||||
|
||||
Your AI assistant can:
|
||||
|
||||
- Analyze the project graph to identify direct and indirect dependencies
|
||||
- Visualize affected projects using the `nx_visualize_graph` tool
|
||||
- Suggest strategies for refactoring that minimize impact
|
||||
- Identify which teams would need to be consulted for major changes
|
||||
|
||||
This architectural awareness is particularly powerful in larger monorepos where understanding project relationships is crucial for making informed development decisions.
|
||||
|
||||
Learn more about dependency analysis in our blog post [Nx MCP Now Available for VS Code Copilot](https://nx.dev/blog/nx-mcp-vscode-copilot).
|
||||
- [Autonomous AI Agents at Scale](https://nx.dev/blog/ai-agents-and-continuity): Infrastructure requirements for AI agent workflows
|
||||
- [Why Nx and AI Work So Well Together](https://nx.dev/blog/nx-and-ai-why-they-work-together): The foundation for AI-powered development
|
||||
- [Nx MCP Server Reference](/docs/reference/nx-mcp): Complete tool reference and setup instructions
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: 'Building and Testing Angular Apps in Nx'
|
||||
description: In this tutorial you'll create a frontend-focused workspace with Nx.
|
||||
description: In this tutorial you'll create a frontend-focused monorepo with Nx.
|
||||
sidebar:
|
||||
label: 'Angular Monorepo'
|
||||
filter: 'type:Guides'
|
||||
|
||||
@@ -106,7 +106,7 @@ Root project 'gradle-tutorial'
|
||||
|
||||
## Add Nx
|
||||
|
||||
Nx is a build system with built in tooling and advanced CI capabilities. It helps you maintain and scale monorepos,
|
||||
Nx is a monorepo platform with built in tooling and advanced CI capabilities. It helps you maintain and scale monorepos,
|
||||
both locally and on CI. We will explore the features of Nx in this tutorial by adding it to the Gradle workspace above.
|
||||
|
||||
To add Nx, run
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
title: 'Building and Testing React Apps in Nx'
|
||||
sidebar:
|
||||
label: 'React Monorepo'
|
||||
description: In this tutorial you'll create a frontend-focused workspace with Nx.
|
||||
description: In this tutorial you'll create a frontend-focused monorepo with Nx.
|
||||
filter: 'type:Guides'
|
||||
---
|
||||
|
||||
|
||||
@@ -7,7 +7,9 @@ sidebar:
|
||||
filter: 'type:Features'
|
||||
---
|
||||
|
||||
Nx provides deep integration with AI coding assistants through the **Nx Model Context Protocol (MCP) server**, giving your AI assistant comprehensive understanding of your monorepo structure, running processes, and development workflows. When you create a new Nx workspace, it includes AI agent configuration files (`CLAUDE.md` and `AGENTS.md`) that provide guidelines for working with Nx and the Nx MCP server.
|
||||
AI coding assistants often hallucinate outdated Nx commands and lack context about your workspace structure. Without workspace awareness, they suggest commands that don't exist or miss project relationships entirely.
|
||||
|
||||
Nx's AI integration gives assistants accurate, real-time information about your workspace, projects, and available commands—making them smarter when working in an Nx monorepo and more autonomous when iterating on CI failures.
|
||||
|
||||
## Configure Nx AI Integration
|
||||
|
||||
@@ -18,48 +20,33 @@ title="Set Up AI Agents in Nx"
|
||||
|
||||
### Automatic AI Setup
|
||||
|
||||
To automatically configure your Nx workspace to work best with AI agents and assistants, run the following command:
|
||||
To automatically configure your Nx monorepo to work best with AI agents and assistants, run the following command:
|
||||
|
||||
```shell
|
||||
npx nx configure-ai-agents
|
||||
```
|
||||
|
||||
This will prompt you for which AI agents/assistants to configure and make sure you are properly set up with both the [Nx MCP](/docs/features/enhance-ai) as well as corresponding AI agent configuration files (e.g. `AGENTS.md`, `CLAUDE.md` etc).
|
||||
This will prompt you for which AI agents/assistants to configure and set up the [Nx MCP server](/docs/reference/nx-mcp), AI agent configuration files (`AGENTS.md`, `CLAUDE.md`, etc.), and agent skills (for workspace exploration, code generation, and task execution). For Claude Code, skills are installed via a plugin; for other agents, they're copied into your workspace.
|
||||
|
||||
Watch [our Youtube video](https://youtu.be/8gdvIz2r_QM) for a full walkthrough.
|
||||
|
||||
### Manual AI Setup
|
||||
|
||||
You can of course manually configure the Nx MCP for MCP-compatible clients using the following configuration:
|
||||
|
||||
```json
|
||||
// mcp.json
|
||||
{
|
||||
"servers": {
|
||||
"nx-mcp": {
|
||||
"command": "npx",
|
||||
"args": ["nx-mcp@latest"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For Claude Code:
|
||||
Alternatively, you can install just the skills via:
|
||||
|
||||
```shell
|
||||
claude mcp add nx-mcp npx nx-mcp@latest
|
||||
npx skills add nrwl/nx-ai-agents-config
|
||||
```
|
||||
|
||||
This copies the skills into your workspace but does not install the Claude Code plugin.
|
||||
|
||||
Watch [our Youtube video](https://youtu.be/8gdvIz2r_QM) for a full walkthrough.
|
||||
|
||||
### What This Integration Enables
|
||||
|
||||
The Nx AI integration provides your coding assistant with powerful capabilities:
|
||||
|
||||
- **[Workspace Structure Understanding](https://nx.dev/blog/nx-mcp-vscode-copilot)** - Deep architectural awareness of your monorepo, project relationships, and dependencies
|
||||
- **[Real-time Terminal Integration](https://nx.dev/blog/nx-terminal-integration-ai)** - AI can read your terminal output, running processes, and error messages without copy-pasting
|
||||
- **[CI Pipeline Context](https://nx.dev/blog/nx-editor-ci-llm-integration)** - Access to build failures, test results, and deployment status from your CI/CD processes
|
||||
- **[Enhanced Code Generation](https://nx.dev/blog/nx-generators-ai-integration)** - AI-powered generator suggestions and custom scaffolding with intelligent defaults
|
||||
- **Cross-project Impact Analysis** - Understanding the implications of changes across your entire monorepo
|
||||
- **Autonomous Error Debugging** - AI independently accesses context to help fix development issues
|
||||
- **Workspace Understanding** - Graph-aware exploration of project dependencies and relationships. AI gets structured data instead of grepping through files.
|
||||
- **[Real-time Terminal Integration](https://nx.dev/blog/nx-terminal-integration-ai)** - AI can read your terminal output, running processes, and error messages without copy-pasting.
|
||||
- **Reliable Code Generation** - AI invokes Nx generators for predictable scaffolding, then adapts the result to your workspace. Faster, standardized, fewer hallucinations.
|
||||
- **Autonomous CI Workflows** - The CI monitor skill bridges your local agent with Nx Cloud. Push, monitor, get failures, fix, repeat until CI is green. Enables autonomous CI workflows ("Ralph Wiggum loop")—you review the final PR, not every intermediate fix.
|
||||
- **Cross-project Impact Analysis** - Understanding the implications of changes across your entire monorepo.
|
||||
|
||||
## Configure CI to Leverage AI Capabilities
|
||||
|
||||
@@ -69,4 +56,5 @@ Read more on the [Self-Healing CI](/docs/features/ci-features/self-healing-ci) d
|
||||
|
||||
## Learn More about Nx and AI
|
||||
|
||||
Learn more about [why Nx and AI work so well together](https://nx.dev/blog/nx-and-ai-why-they-work-together).
|
||||
- [Autonomous AI Agents at Scale](https://nx.dev/blog/ai-agents-and-continuity) - Infrastructure requirements for scaling AI agent workflows
|
||||
- [Why Nx and AI Work So Well Together](https://nx.dev/blog/nx-and-ai-why-they-work-together)
|
||||
|
||||
@@ -6,7 +6,9 @@ sidebar:
|
||||
filter: 'type:Features'
|
||||
---
|
||||
|
||||
Nx Console editor extensions make your developer experience richer. The extensions:
|
||||
Running CLI commands manually and discovering available tasks is tedious. You lose context switching between terminal and editor, and it's easy to forget which generators or tasks are available for each project.
|
||||
|
||||
Nx Console brings Nx directly into your editor. The extensions:
|
||||
|
||||
- [enhance AI integrations](/docs/features/enhance-ai) by providing workspace-level context and up-to-date docs
|
||||
- show [inferred tasks](/docs/concepts/inferred-tasks) and help you invoke them via the Project Details View
|
||||
@@ -30,11 +32,11 @@ If you are using [VSCode](https://code.visualstudio.com/) or a [JetBrains IDE](h
|
||||
|
||||

|
||||
|
||||
### Neovim
|
||||
### Neovim (Community)
|
||||
|
||||
If you are using [Neovim](https://neovim.io/), you can install [Equilibris/nx.nvim](https://github.com/Equilibris/nx.nvim) with your favorite package manager.
|
||||
|
||||
This plugin is **NOT** built or maintained by the Nx team. They are maintained by independent community contributors.
|
||||
**Community Plugin**: This plugin is maintained by independent community contributors, not the Nx team.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
---
|
||||
title: Installation
|
||||
description: Install Nx globally via npm, Homebrew, Chocolatey, or apt. Add Nx to existing repos with nx init and keep dependencies updated automatically.
|
||||
description: Install Nx globally via npm, Homebrew, Chocolatey, or apt. Add Nx to existing repos with nx init.
|
||||
sidebar:
|
||||
order: 2
|
||||
filter: 'type:Guides'
|
||||
---
|
||||
|
||||
To install Nx on your machine, choose one of the following methods based on your operating system and package manager. You can also use `npx` to run Nx without installing it globally.
|
||||
## Global Installation
|
||||
|
||||
Install Nx globally to run commands from anywhere. Choose a method based on your operating system and package manager.
|
||||
|
||||
{% tabs syncKey="install-method" %}
|
||||
{% tabitem label="npm" %}
|
||||
|
||||
@@ -14,7 +17,7 @@ To install Nx on your machine, choose one of the following methods based on your
|
||||
npm add --global nx
|
||||
```
|
||||
|
||||
**Note:** You can also use `yarn`, `pnpm`, or `bun`
|
||||
**Note:** You can also use `yarn global add nx`, `pnpm add --global nx`, or `bun add --global nx`
|
||||
{% /tabitem %}
|
||||
|
||||
{% tabitem label="Homebrew (macOS, Linux)" %}
|
||||
@@ -44,54 +47,80 @@ sudo apt install nx
|
||||
{% /tabitem %}
|
||||
{% /tabs %}
|
||||
|
||||
## Adding Nx to Your Repository
|
||||
### Verify Installation
|
||||
|
||||
```shell
|
||||
nx --version
|
||||
```
|
||||
|
||||
You should see a version number like `22.5.0`.
|
||||
|
||||
### Update Global Installation
|
||||
|
||||
{% tabs syncKey="install-method" %}
|
||||
{% tabitem label="npm" %}
|
||||
|
||||
```shell
|
||||
npm update --global nx
|
||||
```
|
||||
|
||||
**Note:** You can also use `yarn global upgrade nx`, `pnpm update --global nx`, or `bun update --global nx`
|
||||
{% /tabitem %}
|
||||
|
||||
{% tabitem label="Homebrew (macOS, Linux)" %}
|
||||
|
||||
```shell
|
||||
brew upgrade nx
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
|
||||
{% tabitem label="Chocolatey (Windows)" %}
|
||||
|
||||
```shell
|
||||
choco upgrade nx
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
|
||||
{% tabitem label="apt (Ubuntu)" %}
|
||||
|
||||
```shell
|
||||
sudo apt update
|
||||
sudo apt upgrade nx
|
||||
```
|
||||
|
||||
{% /tabitem %}
|
||||
{% /tabs %}
|
||||
|
||||
## Install in a Repository
|
||||
|
||||
To add Nx to an existing repository, run:
|
||||
|
||||
```shell
|
||||
nx init
|
||||
npx nx@latest init
|
||||
```
|
||||
|
||||
**Note:** You can also manually install the [`nx` NPM package](https://www.npmjs.com/package/nx) and create a [nx.json](/docs/reference/nx-json) to configure it.
|
||||
Learn more about [adopting Nx in an existing project](/docs/guides/adopting-nx)
|
||||
This installs the `nx` package as a dev dependency and creates an `nx.json` configuration file. If you have Nx installed globally, it will defer to the local version in your repository.
|
||||
|
||||
### Starter Repository
|
||||
{% aside type="note" title="Manual Installation" %}
|
||||
You can also manually install the [`nx` NPM package](https://www.npmjs.com/package/nx) and create an [nx.json](/docs/reference/nx-json) configuration file.
|
||||
{% /aside %}
|
||||
|
||||
To create a starter repository, you can use the `create-nx-workspace` command. This will create a new Nx workspace with a default configuration and example applications.
|
||||
### Update Nx in Your Repository
|
||||
|
||||
```shell
|
||||
npx create-nx-workspace@latest
|
||||
```
|
||||
|
||||
## Update Nx
|
||||
|
||||
When you update Nx, Nx will also [automatically update your dependencies](/docs/features/automate-updating-dependencies) if you have an [Nx plugin](/docs/concepts/nx-plugins) installed for that dependency. To update Nx, run:
|
||||
When you update Nx in your repository, it will also [automatically update your dependencies](/docs/features/automate-updating-dependencies) if you have an [Nx plugin](/docs/concepts/nx-plugins) installed for that dependency. To update Nx, run:
|
||||
|
||||
```shell
|
||||
nx migrate latest
|
||||
```
|
||||
|
||||
This will create a `migrations.json` file with any update scripts that need to be run. Run them with:
|
||||
This creates a `migrations.json` file with any update scripts that need to be run. Run them with:
|
||||
|
||||
```shell
|
||||
nx migrate --run-migrations
|
||||
```
|
||||
|
||||
{% aside type="tip" title="Update One Major Version at a Time" %}
|
||||
{% aside type="note" title="Update One Major Version at a Time" %}
|
||||
To avoid potential issues, it is [recommended to update one major version of Nx at a time](/docs/guides/tips-n-tricks/advanced-update#one-major-version-at-a-time-small-steps).
|
||||
{% /aside %}
|
||||
|
||||
## Tutorials
|
||||
|
||||
Try one of these tutorials for a full walkthrough of what to do after you install Nx:
|
||||
|
||||
- [TypeScript Monorepo Tutorial](/docs/getting-started/tutorials/typescript-packages-tutorial)
|
||||
- [React Monorepo Tutorial](/docs/getting-started/tutorials/react-monorepo-tutorial)
|
||||
- [Angular Monorepo Tutorial](/docs/getting-started/tutorials/angular-monorepo-tutorial)
|
||||
|
||||
## More Documentation
|
||||
|
||||
- [Add Nx to an Existing Repository](/docs/guides/adopting-nx)
|
||||
- [Update Nx](/docs/features/automate-updating-dependencies)
|
||||
- [Update Your Global Nx Installation](/docs/guides/installation/update-global-installation)
|
||||
- [Install Nx in a Non-Javascript Repo](/docs/guides/installation/install-non-javascript)
|
||||
|
||||
@@ -1,25 +1,44 @@
|
||||
---
|
||||
title: What is Nx?
|
||||
description: 'Nx is an AI-first build platform that connects everything from your editor to CI Helping you deliver fast, without breaking things.'
|
||||
description: 'Nx is a build system with smart caching and task orchestration for monorepos. Ship faster without breaking things.'
|
||||
sidebar:
|
||||
order: 1
|
||||
label: Introduction
|
||||
filter: 'type:Features'
|
||||
---
|
||||
|
||||
Nx is a powerful, open source, technology-agnostic build platform designed to efficiently manage codebases of any scale. From small single projects to large enterprise monorepos, Nx provides the platform to **efficiently get from starting a feature in your editor to a green PR**.
|
||||
|
||||
As teams and codebases grow, productivity bottlenecks multiply: build times increase, CI becomes flaky, and code sharing becomes complex. **Nx reduces friction across your entire development cycle.**
|
||||
Nx is a build system for monorepos. It helps you **develop faster** and **keep CI fast** as your codebase scales.
|
||||
|
||||
{% youtube src="https://youtu.be/pbAQErStl9o" title="What is Nx?" width="100%" /%}
|
||||
|
||||
## Start small, extend as you grow
|
||||
## Challenges of Monorepos
|
||||
|
||||
Nx is built in a modular fashion, allowing you to adopt as little or as much as you'd like at any moment in your development lifecycle. You can **start with just the core and add additional capabilities incrementally** as your needs grow and complexity increases.
|
||||
Monorepos have many advantages and are especially powerful for AI-assisted development. But as teams and codebases grow, monorepos are hard to scale:
|
||||
|
||||
At the **foundation is Nx Core**, a Rust-based, technology-agnostic task runner. Nx Core creates a knowledge graph of your workspace, understanding project relationships and dependencies. This enables highly optimized and fast task execution regardless of technology stack. It runs `package.json` scripts in [TypeScript monorepos](/docs/technologies/typescript/introduction) or Gradle tasks in [Java projects](/docs/technologies/java/introduction) or [can be extended](/docs/extending-nx/intro) to meet your project's specific needs.
|
||||
- **Slow builds and tests** - Hundreds or thousands of tasks compete for CI resources.
|
||||
- **Complex task pipelines** - Projects depend on each other, so tasks need to run in the right order — and that's hard to manage by hand.
|
||||
- **Flaky CI** - Longer pipelines lead to random failures and inconsistent results between local and CI environments.
|
||||
- **Architectural erosion** - Without clear boundaries, unwanted dependencies creep in and projects become tightly coupled.
|
||||
|
||||
{% callout type="deepdive" title="What do you mean by \"running NPM scripts\"?" %}
|
||||
## What Nx Does
|
||||
|
||||
**Nx reduces friction across your entire development cycle** with intelligent caching, task orchestration, and deep understanding of your codebase structure.
|
||||
|
||||
At its core, Nx:
|
||||
|
||||
1. **Runs tasks fast** - [Caches results](/docs/features/cache-task-results) so you never rebuild the same code twice.
|
||||
2. **Understands your codebase** - Builds [project and task graphs](/docs/features/explore-graph) showing how everything connects.
|
||||
3. **Orchestrates intelligently** - Runs tasks in the [right order](/docs/concepts/task-pipeline-configuration), parallelizing when possible.
|
||||
4. **Enforces boundaries** - [Module boundary rules](/docs/features/enforce-module-boundaries) prevent unwanted dependencies between projects.
|
||||
5. **Handles flakiness** - [Automatically re-runs flaky tasks](/docs/features/ci-features/flaky-tasks) and [self-heals CI failures](/docs/features/ci-features/self-healing-ci).
|
||||
|
||||
```shell
|
||||
nx build myapp # Run a task
|
||||
nx build myapp # Run again - instant cache hit
|
||||
nx run-many -t build test # Run across all projects
|
||||
```
|
||||
|
||||
{% callout type="deepdive" title="How does Nx run tasks?" %}
|
||||
|
||||
At the very core, Nx is a super fast, intelligent task runner. Let's take the example of an NPM workspace. This could be a project's `package.json`:
|
||||
|
||||
@@ -55,31 +74,48 @@ This will execute the `build` script from `my-project`'s `package.json`, equival
|
||||
|
||||
Similarly you [can run tasks across all projects](/docs/features/run-tasks), just specific ones or just those from projects you touched.
|
||||
|
||||
From there, you can gradually enhance your setup by adding features like [task caching](/docs/features/cache-task-results), adding [plugins](/docs/technologies), optimizing your CI via [task distribution](/docs/features/ci-features/distribute-task-execution), and many more powerful capabilities as your needs grow.
|
||||
From there, you can gradually enhance your setup by adding features like [task caching](/docs/features/cache-task-results), adding [plugins](/docs/plugin-registry), optimizing your CI via [task distribution](/docs/features/ci-features/distribute-task-execution), and many more powerful capabilities as your needs grow.
|
||||
|
||||
{% /callout %}
|
||||
|
||||
Nx Core provides everything you need to get started and works perfectly on its own.
|
||||
**When you're ready for more, the Nx platform offers additional capabilities you can adopt incrementally**.
|
||||
Extend your setup with [**Nx Cloud**](/docs/getting-started/nx-cloud) for remote caching, distributed task execution, and [**AI-powered self-healing CI**](/docs/features/ci-features/self-healing-ci) that automatically detects, analyzes, and fixes CI failures.
|
||||
Integrate [**Nx Console**](/docs/getting-started/editor-setup) with your editor for powerful autocomplete, project graph visualization, CI notifications, and an MCP to [make your AI coding assistant smarter](/docs/features/enhance-ai).
|
||||
Add [**Nx Plugins**](/docs/technologies) for technology-specific automation and DX improvements, or build custom platform capabilities using [Nx Devkit](/docs/extending-nx/intro).
|
||||
## Start Small, Grow as Needed
|
||||
|
||||
## Where to go from here?
|
||||
Nx is modular. Start with just the CLI and add capabilities as your needs grow.
|
||||
|
||||
| Component | What It Does |
|
||||
| ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Nx Core** | Task runner with [local caching](/docs/features/cache-task-results). Works with any tech stack. |
|
||||
| [**Nx Plugins**](/docs/plugin-registry) | Technology-specific automation (generators, executors, dependency detection). |
|
||||
| [**Nx Console**](/docs/getting-started/editor-setup) | Editor extension for VSCode/JetBrains with visual UI and [AI assistance](/docs/features/enhance-ai). |
|
||||
| [**Nx Cloud**](/docs/features/ci-features) | [Remote caching](/docs/features/ci-features/remote-cache), [affected commands](/docs/features/ci-features/affected), and [self-healing CI](/docs/features/ci-features/self-healing-ci). |
|
||||
|
||||
{% callout type="deepdive" title="Can I add Nx to a single-project repo?" %}
|
||||
Yes, Nx provides value even for single-project repositories. You get fast task caching, intelligent task orchestration, and access to Nx plugins for your specific technology stack. As your project grows into a monorepo, the foundation is already in place.
|
||||
|
||||
Nx can also connect multiple repositories into a synthetic monorepo, letting you orchestrate large changes across all connected repos.
|
||||
{% /callout %}
|
||||
|
||||
## Where to Go from Here
|
||||
|
||||
{% callout type="note" title="Choose Your Path" %}
|
||||
**Starting fresh?** → [Create a new workspace](/docs/getting-started/start-new-project)
|
||||
|
||||
**Have an existing project?** → [Add Nx to your project](/docs/getting-started/start-with-existing-project)
|
||||
|
||||
**Want hands-on learning?** → [Follow a tutorial](/docs/getting-started/tutorials)
|
||||
|
||||
**Prefer video?** → [Learn with our video courses](https://nx.dev/courses)
|
||||
{% /callout %}
|
||||
|
||||
{% cardgrid %}
|
||||
|
||||
{% linkcard title="Nx quickstart" description="Dive right in with our quickstart steps to create your first project or add Nx to your existing one." href="/docs/quickstart" /%}
|
||||
{% linkcard title="Quickstart" description="Get your first Nx project running in minutes." href="/docs/quickstart" /%}
|
||||
|
||||
{% linkcard title="Explore Technologies" description="Explore Nx's technology integrations and how it can support your specific stack." href="/docs/technologies" /%}
|
||||
{% linkcard title="Plugins" description="Find plugins for React, Angular, Node, Gradle, Maven, .NET, and more." href="/docs/plugin-registry" /%}
|
||||
|
||||
{% linkcard title="Step by step with our tutorials" description="Learn more about Nx through hands-on tutorials for different technology stacks." href="/docs/getting-started/tutorials" /%}
|
||||
{% linkcard title="Concepts" description="Improve your understanding of how Nx works under the hood." href="/docs/concepts" /%}
|
||||
|
||||
{% linkcard title="Learn with our video courses" description="Dive deeper with comprehensive video courses that walk you through Nx concepts." href="https://nx.dev/courses" /%}
|
||||
|
||||
{% linkcard title="Dive deep into Nx features" description="Discover all the powerful features that Nx provides to streamline your workflow." href="/docs/features" /%}
|
||||
|
||||
{% linkcard title="Understand underlying concepts" description="Improve your understanding of the core concepts of how Nx works under the hood." href="/docs/concepts" /%}
|
||||
{% linkcard title="Features" description="Discover all the powerful features that Nx provides to streamline your workflow." href="/docs/features" /%}
|
||||
|
||||
{% /cardgrid %}
|
||||
|
||||
|
||||
@@ -1,77 +1,48 @@
|
||||
---
|
||||
title: Start a new project with Nx
|
||||
description: Create a new Nx workspace manually with your favorite CLI or use the guided setup with presets for various technology stacks and configurations.
|
||||
title: Start a New Project
|
||||
description: Create a new Nx workspace with starter templates or via Nx Cloud in the browser.
|
||||
sidebar:
|
||||
label: Start a new project
|
||||
label: Start a New Project
|
||||
order: 3
|
||||
filter: 'type:Guides'
|
||||
---
|
||||
|
||||
When you start a new project with Nx, you have two options: manual or guided.
|
||||
Create a new Nx workspace using one of these options:
|
||||
|
||||
## Option 1: Manual setup
|
||||
- **[Option 1: Create locally with templates](#option-1-create-locally-with-templates)** - Run a command to scaffold a new monorepo on your machine
|
||||
- **[Option 2: Create via Nx Cloud](#option-2-create-via-nx-cloud)** - Use the browser-based setup with CI/CD pre-configured
|
||||
|
||||
In a nutshell, this means using your favorite CLI to create your initial project setup and then adding Nx to it.
|
||||
|
||||
Let's take the example of an NPM workspace. Create a new root-level `package.json` like:
|
||||
|
||||
```json
|
||||
// package.json
|
||||
{
|
||||
"name": "my-workspace",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"workspaces": ["packages/*", "apps/*"]
|
||||
}
|
||||
```
|
||||
|
||||
Then you can add Nx to it by using:
|
||||
|
||||
```shell
|
||||
nx@latest init
|
||||
```
|
||||
|
||||
{% aside type="note" title="Global Installs" %}
|
||||
Make sure you have [Nx installed globally](/docs/getting-started/installation) or use `npx` if you're in a JavaScript environment
|
||||
{% aside type="note" title="Adding Nx to an existing project?" %}
|
||||
If you already have a project and want to add Nx to it, see [Add to an Existing Project](/docs/getting-started/start-with-existing-project) instead.
|
||||
{% /aside %}
|
||||
|
||||
Nx will detect the underlying workspace configuration, ask you a couple of questions and install itself into the workspace. You can now [run tasks with Nx](/docs/features/run-tasks) and incrementally add functionality, like:
|
||||
## Option 1: Create Locally with Templates
|
||||
|
||||
- [Configure caching](/docs/features/cache-task-results)
|
||||
- [Adding Nx plugins to help refine your workflows](/docs/plugin-registry)
|
||||
- [Optimizing your CI](/docs/guides/nx-cloud/setup-ci)
|
||||
|
||||
## Option 2: Create a new workspace with presets
|
||||
|
||||
Alternatively, you can choose a more guided approach by leveraging some of the presets Nx comes with.
|
||||
|
||||
Run the following command to get started:
|
||||
Run the following command to create a new Nx workspace:
|
||||
|
||||
```shell
|
||||
npx create-nx-workspace@latest
|
||||
```
|
||||
|
||||
This interactive command will guide you through the setup process, allowing you to:
|
||||
This interactive command guides you through the setup:
|
||||
|
||||
- **Choose your workspace name** - This will be the name of your root directory
|
||||
- **Select your preferred package manager** - npm, yarn, or pnpm
|
||||
- **Pick a preset** - Choose from [various technology stacks and configurations](/docs/reference/create-nx-workspace#presets)
|
||||
- **Configure additional options** - Such as styling solutions, testing frameworks, and more
|
||||
- **Workspace name** - The name of your root directory
|
||||
- **Template** - Choose from [various technology stacks](/docs/reference/create-nx-workspace#presets) (React, Angular, Node, etc.)
|
||||
- **Package manager** - npm, yarn, pnpm, or bun
|
||||
- **Additional options** - Styling, testing frameworks, and more depending on your template
|
||||
|
||||
Choose a preset that matches your technology stack. This gives you a fully configured workspace.
|
||||
For a minimal setup, choose the **empty workspace** template (`--preset=ts`). This gives you a bare TypeScript monorepo that you can extend incrementally.
|
||||
|
||||
You can also choose **an empty workspace preset** (`--preset=ts`) which sets up the bare minimum configuration for TypeScript and Nx. This allows you to add technologies and features incrementally over time as you need them.
|
||||
|
||||
## Option 3: Get the complete Nx platform experience
|
||||
## Option 2: Create via Nx Cloud
|
||||
|
||||
[](https://cloud.nx.app/get-started?utm_source=nx-docs&utm_medium=nx-cloud-onboarding&utm_campaign=start-new-project)
|
||||
|
||||
For the complete experience, you can also get [started directly from the Nx Cloud application](https://cloud.nx.app/get-started?utm_source=nx-docs&utm_medium=nx-cloud-onboarding&utm_campaign=start-new-project).
|
||||
[Create your workspace directly from Nx Cloud](https://cloud.nx.app/get-started?utm_source=nx-docs&utm_medium=nx-cloud-onboarding&utm_campaign=start-new-project) for a browser-based setup experience.
|
||||
|
||||
This approach gives you a fully end-to-end development workflow right from the start, making it easy to get up and running when your project is in its initial phase.
|
||||
You'll get a fully working CI configuration that includes Nx Cloud's AI-powered features like **AI-powered self-healing CI** that automatically fixes common CI failures.
|
||||
This means you benefit from intelligent automation right from day one, without having to configure complex CI pipelines manually.
|
||||
This option gives you:
|
||||
|
||||
As your project grows and scales, you'll have access to additional features like **remote caching** to speed up builds across your team, **distributed task execution with Nx Agents** to parallelize work across multiple machines, and **automatic test splitting** to optimize your CI pipeline performance.
|
||||
- A working CI configuration out of the box
|
||||
- [Remote caching](/docs/features/ci-features/remote-cache) enabled from the start
|
||||
- [Self-healing CI](/docs/features/ci-features/self-healing-ci) that automatically fixes common failures
|
||||
|
||||
[Get started with the complete Nx platform experience →](https://cloud.nx.app/get-started?utm_source=nx-docs&utm_medium=nx-cloud-onboarding&utm_campaign=start-new-project)
|
||||
[Get started with Nx Cloud →](https://cloud.nx.app/get-started?utm_source=nx-docs&utm_medium=nx-cloud-onboarding&utm_campaign=start-new-project)
|
||||
|
||||
@@ -1,102 +1,49 @@
|
||||
---
|
||||
title: Start with an existing project
|
||||
description: Add Nx to any existing project with a single command. Start with Nx Core and gradually adopt plugins, CI integrations, and other capabilities.
|
||||
title: Add to an Existing Project
|
||||
description: Add Nx to any existing project with a single command. Start with task running and caching, then gradually adopt more capabilities.
|
||||
sidebar:
|
||||
order: 4
|
||||
label: Add to existing project
|
||||
label: Add to Existing Project
|
||||
filter: 'type:Guides'
|
||||
---
|
||||
|
||||
{% course_video src="https://youtu.be/3hW53b1IJ84" courseTitle="From PNPM Workspaces to Distributed CI" courseUrl="https://nx.dev/courses/pnpm-nx-next/lessons-01-nx-init" /%}
|
||||
|
||||
In many situations, you have an existing codebase and want to improve it with Nx using an **incremental adoption approach**.
|
||||
Nx is designed for incremental adoption. Start with just task running and [caching](/docs/features/cache-task-results), then add [plugins](/docs/technologies), [CI integrations](/docs/guides/nx-cloud/setup-ci), or other capabilities as your needs grow.
|
||||
|
||||
Thanks to [Nx's modular architecture](/docs/getting-started/intro), you can start with just **Nx Core** and then gradually add [technology-specific plugins](/docs/technologies), [CI integrations](/docs/getting-started/nx-cloud), or other capabilities as your requirements evolve.
|
||||
|
||||
Getting started is remarkably simple. You can add Nx to any existing project with a single command:
|
||||
Add Nx to any existing project with a single command:
|
||||
|
||||
```shell
|
||||
nx@latest init
|
||||
npx nx@latest init
|
||||
```
|
||||
|
||||
{% aside type="note" title="Global Installs" %}
|
||||
Make sure you have [Nx installed globally](/docs/getting-started/installation) or use `npx` if you're in a JavaScript environment
|
||||
{% /aside %}
|
||||
|
||||
Whether a monorepo, single project or something in between, `nx init` walks you through adding and configuring Nx. You can pick a minimal approach or detailed guided setup. At the end you'll have an Nx workspace ready for anything!
|
||||
Whether a monorepo, single project, or something in between, `nx init` walks you through adding and configuring Nx. At the end you'll have an Nx workspace ready for anything.
|
||||
|
||||
## Next Steps
|
||||
|
||||
After initializing Nx, you can [run tasks](/docs/features/run-tasks) with `nx <task> <project-name>` (e.g. `nx build myproject`) or run one or many tasks across all projects with `nx run-many -t <task1> <task2>`.
|
||||
After initializing Nx, try these commands:
|
||||
|
||||
You can also explore your codebase using:
|
||||
|
||||
- `nx graph` to view an interactive graph
|
||||
- `nx show projects` to see a list of all projects
|
||||
- `nx show project <project-name>` to view an interactive project detailed view
|
||||
|
||||
### Update CI Configurations
|
||||
|
||||
Now that Nx is installed, you'll want to update CI configurations to leverage Nx. You can do this by changing previous commands to use `nx` instead.
|
||||
|
||||
For example, switching from `pnpm` commands to use `nx`
|
||||
|
||||
```diff
|
||||
// .github/workflows/ci.yaml
|
||||
- - run: pnpm run -r build
|
||||
- - run: pnpm run -r test
|
||||
+ - run: npx nx run-many -t test build
|
||||
```shell
|
||||
nx build <project-name> # Run a task
|
||||
nx build <project-name> # Run again - instant cache hit
|
||||
nx run-many -t build test # Run tasks across all projects
|
||||
nx graph # Visualize project dependencies
|
||||
```
|
||||
|
||||
You can directly invoke `package.json` scripts with `nx` as well
|
||||
From here you can:
|
||||
|
||||
```diff
|
||||
// .github/workflows/ci.yaml
|
||||
- - run: npm run build
|
||||
- - run: npm run test
|
||||
+ - run: npx nx build
|
||||
+ - run: npx nx test
|
||||
```
|
||||
- [Configure task caching](/docs/features/cache-task-results) to speed up repeated builds
|
||||
- [Add Nx plugins](/docs/technologies) for your tech stack (React, Angular, Node, etc.)
|
||||
- [Set up CI](/docs/guides/nx-cloud/setup-ci) with remote caching and affected commands
|
||||
- Enable [remote caching](/docs/features/ci-features/remote-cache) with `nx connect`
|
||||
|
||||
[View CI provider specific setups](/docs/guides/nx-cloud/setup-ci) to learn more.
|
||||
|
||||
### Nx Cloud
|
||||
|
||||
{% aside type="note" title="How do I know if I enabled Nx Cloud?" %}
|
||||
Validate Nx Cloud is enabled by checking the `nx.json` file for `nxCloudId` property.
|
||||
You can add Nx Cloud at any point by running the `nx connect` command.
|
||||
{%/aside%}
|
||||
|
||||
After initializing Nx, you'll need to commit and push the changes to your repository.
|
||||
|
||||
Once your changes are pushed, you can finish setting up your workspace by clicking on the list printed to your terminal, or by visiting [Nx Cloud directly](https://cloud.nx.app/get-started?utm_source=nx.dev&utm_campaign=nx_init) and clicking _"Connect an existing Nx repository"_
|
||||
|
||||
To leverage Self Healing CI, you'll need to add the following to your CI configuration:
|
||||
|
||||
```diff
|
||||
// .github/workflows/ci.yaml
|
||||
- run: npx nx run-many -t lint test build
|
||||
+ # Enable Self Healing CI w/ Nx Cloud
|
||||
+ - run: npx nx fix-ci
|
||||
+ if: always()
|
||||
```
|
||||
|
||||
### Empower Your Editor
|
||||
|
||||
Enhance your developer experience by using the Nx Console editor extension.
|
||||
|
||||
{% install_nx_console /%}
|
||||
|
||||
## In-depth Guides
|
||||
|
||||
Here are some guides that give you more details based on the technology stack you're using:
|
||||
## In-Depth Guides
|
||||
|
||||
{% cardgrid %}
|
||||
|
||||
{% linkcard title="Add to Existing Monorepo"
|
||||
href="/docs/guides/adopting-nx/adding-to-monorepo" %}
|
||||
{% /linkcard %}
|
||||
{% linkcard title="Add to Any Project" href="/docs/guides/adopting-nx/adding-to-existing-project" /%}
|
||||
{% linkcard title="Add to Existing Monorepo" href="/docs/guides/adopting-nx/adding-to-monorepo" /%}
|
||||
|
||||
{% linkcard title="Add to Any Project" href="/docs/guides/adopting-nx/adding-to-existing-project" /%}
|
||||
|
||||
{% linkcard title="Migrate from Angular CLI" href="/docs/technologies/angular/migration/angular" /%}
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ The [Nx Cloud GitHub App](https://github.com/marketplace/official-nx-cloud-app)
|
||||
|
||||
For the best experience, install the [Nx Cloud GitHub App](https://github.com/marketplace/official-nx-cloud-app). Using the app provides the most seamless authentication experience. This is not required if you wish to authenticate with a personal access token that you generate yourself.
|
||||
|
||||
For a detailed breakdown of each permission the GitHub App requires and why, see the [GitHub App Permissions](/docs/enterprise/single-tenant/custom-github-app#configure-permissions-for-the-github-app) reference.
|
||||
|
||||
## Connecting Your Workspace
|
||||
|
||||
Once you have installed the Nx Cloud GitHub App, you must link your workspace to the installation. To do this, sign in to Nx Cloud and navigate to the VCS Integrations setup page. This page can be found in your workspace settings, you need to be admin of the organization in order to access it.
|
||||
|
||||
@@ -12,6 +12,10 @@ Nx errs on the side of caution when using inputs. Ideally, the "perfect" configu
|
||||
|
||||
For an overview of all the possible [types of inputs](/docs/reference/inputs) and how to reuse sets of inputs as [named inputs](/docs/reference/inputs#named-inputs), see the reference documentation.
|
||||
|
||||
{% aside type="caution" title="Directory Paths Require Trailing Slash or Glob" %}
|
||||
When specifying a directory as an input, you must use a trailing slash (`/`) or a glob pattern. For example, `{projectRoot}/src/` or `{projectRoot}/src/**/*` will match all files in the `src` directory, but `{projectRoot}/src` (without trailing slash) will not match any files. This differs from `outputs`, which support naked directory paths.
|
||||
{% /aside %}
|
||||
|
||||
Throughout this recipe, the following project structure of a simple workspace will be used as an example to help understand inputs better.
|
||||
|
||||
{% graph height="450px" %}
|
||||
@@ -443,6 +447,37 @@ With the above named inputs, Nx will behave in the following way:
|
||||
- When only test files are changed, Nx will restore previous compilation results from the cache and re-run the tests for the projects containing the test files
|
||||
- When any production files are changed, Nx will re-run the tests for the project as well as any projects which depend on it
|
||||
|
||||
### Specifying Dependency File Patterns Directly
|
||||
|
||||
Instead of defining a named input and referencing it with `^`, you can directly specify file patterns to consider from dependency projects using the `^{projectRoot}` syntax:
|
||||
|
||||
```jsonc
|
||||
// nx.json
|
||||
{
|
||||
"targetDefaults": {
|
||||
"build": {
|
||||
"inputs": [
|
||||
"production",
|
||||
"^{projectRoot}/src/**/*.ts", // Only consider .ts source files from dependencies
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
This is useful when you want fine-grained control over which files from dependencies affect a task's cache without creating a named input. For example, a `build` task might only need to consider `.ts` files from its dependencies rather than all production files.
|
||||
|
||||
You can also use the object format with the `dependencies` property:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"inputs": [
|
||||
"production",
|
||||
{ "fileset": "{projectRoot}/src/**/*.ts", "dependencies": true },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### Consider the Version of a Language for all Tasks
|
||||
|
||||
Many times, the version of the programming language being used will affect the behavior of all tasks for the workspace.
|
||||
|
||||
@@ -77,7 +77,7 @@ You can implement your server in any programming language or framework, as long
|
||||
"openapi": "3.0.0",
|
||||
"info": {
|
||||
"title": "Nx custom remote cache specification.",
|
||||
"description": "Nx is an AI-first build platform that connects everything from your editor to CI. Helping you deliver fast, without breaking things.",
|
||||
"description": "Nx is an AI-first monorepo platform that connects everything from your editor to CI. Helping you deliver fast, without breaking things.",
|
||||
"version": "1.0.0"
|
||||
},
|
||||
"paths": {
|
||||
|
||||
@@ -4,6 +4,10 @@ description: 'Learn how to generate package.json and pruned lock files for your
|
||||
filter: 'type:Guides'
|
||||
---
|
||||
|
||||
{% aside type="note" title="Using TS Solution Setup?" %}
|
||||
If your workspace uses TS project references (the default in Nx 20+), use the [prune workflow](/docs/technologies/node/guides/deploying-node-projects) instead. The `generatePackageJson` approach below applies to workspaces without TS Solution Setup.
|
||||
{% /aside %}
|
||||
|
||||
A common approach to deploying applications is via docker containers. Some applications can be built into bundles that are environment agnostic, while others depend on OS-specific packages being installed. For these situations, having just bundled code is not enough, we also need to have `package.json`.
|
||||
|
||||
Nx supports the generation of the project's `package.json` by identifying all the project's dependencies. The generated `package.json` is created next to the built artifacts (usually at `dist/apps/name-of-the-app`).
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: How Nx Works
|
||||
description: Core concepts and mental models behind Nx
|
||||
sidebar:
|
||||
hidden: true
|
||||
pagefind: false
|
||||
---
|
||||
|
||||
{% sidebar_group_cards group="How Nx Works" /%}
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: Angular
|
||||
description: Angular guides and best practices for Nx workspaces
|
||||
sidebar:
|
||||
hidden: true
|
||||
pagefind: false
|
||||
---
|
||||
|
||||
{% sidebar_group_cards group="Knowledge Base/Angular" /%}
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: Benchmarks
|
||||
description: Performance benchmarks for Nx
|
||||
sidebar:
|
||||
hidden: true
|
||||
pagefind: false
|
||||
---
|
||||
|
||||
{% sidebar_group_cards group="Knowledge Base/Benchmarks" /%}
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: Continuous Integration
|
||||
description: Set up and configure CI pipelines with Nx
|
||||
sidebar:
|
||||
hidden: true
|
||||
pagefind: false
|
||||
---
|
||||
|
||||
{% sidebar_group_cards group="Knowledge Base/Continuous Integration" /%}
|
||||