René's URL Explorer Experiment
Title:
**Severity**: ...
...full template...
```
````
### Technique scope
Prefer inline skills over separate `.github/aw/*.md` shared files when the content is only relevant to one workflow. Use a shared import (see [reuse.md](reuse.md)) when the same template is used by multiple workflows.
---
## Technique 4 — Apply the Caveman Technique
A/B compare a verbose prompt against a minimal one. Adopt minimal if quality holds.
```yaml
experiments:
prompt_style: [verbose, minimal]
```
```markdown
{{#if experiments.prompt_style == "verbose" }}
Please analyze all of the open issues in this repository and provide a comprehensive, detailed report covering: the number of open issues, any significant trends or patterns you observe, the most frequently occurring labels, the oldest unresolved issues, a prioritized list of the most critical items, and any recommendations for the team.
{{#else}}
List open issues by priority. Top 5 critical items. Be brief.
{{/if}}
```
Measure AIC via run summary or `gh aw audit`. If `minimal` wins on cost at acceptable quality, promote as baseline.
---
## Technique 5 — Use Experiments to Measure Impact
Declare an experiment before making any prompt or configuration change, and compare before/after cost and quality. Run ≥ 20 cycles per variant for statistical significance on high-frequency workflows.
```yaml
experiments:
optimization_v1:
variants: [control, optimized]
description: "DataOps refactor — move issue fetching to steps:"
metric: "aic"
issue: "123"
```
Reference the active variant in the prompt:
```markdown
{{#if experiments.optimization_v1 == "optimized" }}
Read the pre-fetched data from `/tmp/gh-aw/data/`.
{{#else}}
Fetch open issues from ${{ github.repository }} using the GitHub tools.
{{/if}}
```
**After enough runs:**
1. Compare variants using `gh aw audit `
2. Inspect `aic`, `input_tokens`, `output_tokens`, `cache_read_tokens`, and `cache_write_tokens`
3. Validate output quality and decision accuracy against the control run
4. If the optimized variant wins on cost **and** quality, rewrite the baseline prompt and remove the `experiments:` field. See [experiments.md](experiments.md) for A/B testing details.
**Key experiment dimensions for token optimization:**
| Dimension | Example variants |
|---|---|
| Prompt verbosity | `verbose` / `concise` / `minimal` |
| Data source | `agentic-fetch` / `dataops-steps` |
| Model tier | Run separate workflows for each engine |
| Sub-agent usage | `single-agent` / `with-subagents` |
| Tool mode | `mcp-local` / `gh-proxy` |
---
## Technique 6 — Reduce Trigger Frequency and Batch Work
The cheapest run is the one you don't execute. If a workflow doesn't need near-real-time feedback, run it less often and batch.
### Prefer slower schedules when latency is acceptable
- `hourly` → `daily on weekdays` for team-facing summaries or audits
- `daily` → `weekly` for trend reports, optimization reviews, backlog hygiene
- `every N hours` → daily/weekly batch when the workflow only produces guidance
### Prefer scheduled batches over reactive triggers
Reactive triggers (`issues:`, `pull_request:`, comment commands) suit immediate feedback. Otherwise prefer `schedule: daily on weekdays` and batch work. Typical batch-friendly tasks: triage summaries, stale backlog review, token audits, security digests. Combine with `cache-memory` or `repo-memory` to track processed items.
### Bound repetitive work to a manageable subset
Do not require one run to finish an unbounded backlog such as hundreds of lint violations. Set a per-run item, time, turn, or AI-credit budget and stop after a useful subset. Persist a compact cursor or processed-item set in `cache-memory` when stable state is available; otherwise use a deterministic heuristic such as file-path buckets, issue-number modulo, or oldest-first ordering. Rotate buckets round-robin across runs so every item eventually receives attention without repeatedly selecting the easiest items.
Keep each batch idempotent, skip items already fixed, and report the processed subset plus remaining work. Prefer smaller complete batches over a broad set of partial fixes that may exhaust the budget.
---
## Techniques 7–8 — Observability and Harness Learning
See [token-optimization-observability.md](token-optimization-observability.md) for OpenTelemetry export, AgenticOps token workflows, and learning from harness execution experience.
---
## Techniques 9–11 — Caching, AI-Credit Guardrails, and Bounded File Reads
See [token-optimization-caching-budgets.md](token-optimization-caching-budgets.md) for prompt-caching mechanics, `max-ai-credits`/`max-daily-ai-credits` guardrails, custom model pricing, and the 20 KB bounded-file-read rule.
---
## Additional Resources
| Topic | File |
|---|---|
| OpenTelemetry export, AgenticOps, harness-experience learning | [token-optimization-observability.md](token-optimization-observability.md) |
| Prompt caching, AI-credit guardrails, bounded file reads | [token-optimization-caching-budgets.md](token-optimization-caching-budgets.md) |
| Inline sub-agents syntax | [subagents.md](subagents.md) |
| A/B experiments | [experiments.md](experiments.md) |
| Persistent memory | [memory.md](memory.md) |
| DataOps pattern | [DataOps guide](https://github.com/github/gh-aw/blob/main/docs/src/content/docs/patterns/data-ops.md) |
| Audit command reference | [cli-commands.md](cli-commands.md) |
| Frontmatter syntax | [syntax.md](syntax.md) |
---
description: Trigger patterns for GitHub Agentic Workflows — events, fuzzy scheduling, fork security, slash commands, and label commands.
---
## Trigger Selection
Use the smallest trigger that matches the request.
### Decision Matrix
| User intent | Trigger | Typical read tools | Typical safe output |
|---|---|---|---|
| Review PR changes, comment on quality, suggest fixes | `pull_request` | `github` (`gh-proxy`), optional `playwright` for UI diffs | `add-comment` |
| Investigate failed CI/Actions runs and summarize incident | `workflow_run` | `github` (`gh-proxy`) with `actions: read` | `create-issue` |
| Monitor external service deployment failures (Heroku, Vercel, Fly.io) | `deployment_status` | `github` (`gh-proxy`) with `deployments: read` | `create-issue` |
| Run visual regression checks on PR UI changes | `pull_request` | `playwright` + `cache-memory` | `add-comment` |
| Publish weekly stakeholder/product digest | `schedule` | `github` (`gh-proxy`) | `create-issue` (default), `create-discussion` only if explicitly requested |
| Review dependency licenses or design-token governance on PRs | `pull_request` with `paths:` | `github` (`gh-proxy`) | `add-comment`; `create-issue` only for blocked/policy-violating findings |
| Govern documentation content (stale pages, broken links, outdated ownership) | `schedule` or `pull_request` with `paths:` | `github` (`gh-proxy`) | `add-comment` on PR; `create-issue` for stale content |
| PM / product health digest (release velocity, open issues by area) | `schedule` | `github` (`gh-proxy`) | `create-issue` with `close-older-issues: true` |
| Compliance or regulatory review | `pull_request` with `paths:` or `schedule` | `github` (`gh-proxy`) | `add-comment` for findings; `create-issue` for violations |
> **`workflow_run` vs `deployment_status`**: Use `workflow_run` when monitoring another GitHub Actions workflow in the same repository. Use `deployment_status` when an external service (Heroku, Vercel, Fly.io) reports deployment results back to GitHub via the Deployments API. See [deployment-status.md](deployment-status.md) for the full pattern.
>
> For `workflow_run`, always scope explicitly: set `workflows:` to named upstream workflow(s), use `types: [completed]`, and gate outcomes with an `if:` guard on `${{ github.event.workflow_run.conclusion }}` (for incident triage, usually `failure`, `timed_out`, `cancelled`, `action_required`) unless the user asked for success reporting.
### Scenario Examples
The matrix above gives trigger, tools, and output. These add the `paths:` scoping and definitions the matrix cannot express.
Engineering-focused:
- **Schema/API review on PRs**: `paths:` scoped to backend contract files (`db/migrate/**`, `migrations/**`, `schema/**`, `openapi/**`, `api/**`); `noop` when contracts are unchanged.
- **Visual regression on UI changes**: use only `playwright` + `cache-memory` (no extra tools), allowlist only target preview/app hosts, and state the exact baseline source (`cache-memory` key, artifact, or branch path).
- **Design-token governance on PRs**: `paths:` scoped to token sources and theme/config files (`tokens/**`, `**/*tokens*.json`, `**/theme/**`, `**/tailwind*.{js,ts}`, `**/*design-token*`); validate linked token references (style dictionary source, token registry, or design-spec URL) before assessment; `noop` when required references are absent from the in-scope changes or no token drift is detected.
- **Dependency-license compliance review on PRs**: `paths:` scoped to dependency manifests (`package.json`, `go.mod`, `requirements.txt`, `Cargo.toml`); classify each addition by license tier (allowed / needs-review / blocked); escalate blocked additions with `create-issue`; `noop` when all additions are pre-approved.
- **Deployment incident triage**: `deployment_status` for external provider failures, `workflow_run` for GitHub Actions failures; derive a stable failure key (workflow + job + failing step or error signature); `noop` when a failure self-recovers or matches an existing open incident.
Non-engineering personas:
- **Documentation governance**: `schedule` (weekly) or `pull_request` with `paths:` scoped to docs directories; check stale ownership, broken links, and missing metadata; `create-issue` for pages needing owner action.
- **PM / roadmap / stakeholder digests**: `schedule` (weekly on weekdays) plus optional `workflow_dispatch`; publish with `create-issue` and `close-older-issues: true`. Fix up front: the window (`last 7 full days ending at run start (UTC)` or `since previous successful run`), the grouping dimensions (team, service, owner, severity, or status), and a stable dedup key (`pm-digest::2026-W27`). `noop` when the window has zero qualifying updates. See [report.md](report.md) for the canonical defaults.
- **Compliance audit / review**: `schedule: daily on weekdays` plus `workflow_dispatch` for drift detection, or `schedule` (monthly) / `pull_request` with `paths:` scoped to policy files. Define **material drift** as any control-state change that affects compliance posture (required policy file removed, control owner missing, control status downgraded from pass to fail, or required approval evidence link missing). Compare current control evidence against the previous successful run window; publish with `create-issue` using `close-older-issues: true` and a stable key such as `compliance-drift::`; `noop` when no material drift is detected.
### Pattern-specific `noop` examples
- **PR reviewer (`pull_request`)**: `noop` when only docs/metadata changed outside scoped `paths:`.
- **Failure triage (`workflow_run`)**: `noop` when rerun succeeds, signal is flake-only, or an open incident already exists for the same failure key.
- **Scheduled digest (`schedule`)**: `noop` when the exact reporting window (for example `since previous successful run`) has zero qualifying updates.
- **Deployment monitor (`deployment_status`)**: `noop` when non-terminal statuses (`queued`, `in_progress`) arrive without a terminal failure.
## Trigger Patterns
### Standard GitHub Events
```yaml
on:
issues:
types: [opened, edited, closed]
pull_request:
types: [opened, edited, closed]
forks: ["*"] # Allow from all forks (default: same-repo only)
push:
branches: [main]
schedule:
- cron: "0 9 * * 1" # Monday 9AM UTC
workflow_dispatch: # Manual trigger
```
### `workflow_run` Failure-Triage Pattern
Use this when reacting to failures from another workflow in the same repository:
```yaml
on:
workflow_run:
workflows: ["CI", "Deploy"]
types: [completed]
workflow_dispatch:
```
Then gate analysis to failure outcomes:
```yaml
if: contains(fromJson('["failure","timed_out","cancelled","action_required"]'), github.event.workflow_run.conclusion)
```
These are "non-success outcomes requiring triage"; keep the list explicit so readers can tighten (e.g., only `failure`) or broaden it.
Escalation rules for this pattern (required):
- Derive a stable failure key before any write (for example `:::`). See [create-agentic-workflow-trigger-details.md](create-agentic-workflow-trigger-details.md#incident-dedup-key-templates-workflow_run-and-deployment_status) for concrete key-format templates.
- Search for an existing open incident by that key **before** calling `create-issue`.
- `noop` when the monitored run concludes `success`, or when an open incident already exists for the same key (duplicate suppression).
#### Fuzzy Scheduling
Use fuzzy scheduling instead of exact cron to distribute execution times. Avoids load spikes and the "Monday wall of work" from weekend accumulation.
**Basic Fuzzy Schedules:**
```yaml
on:
schedule: daily on weekdays # Monday-Friday only (recommended for daily workflows)
schedule: daily # All 7 days
schedule: weekly # Once per week
schedule: hourly # Every hour
```
**Examples with Intervals:**
```yaml
on:
schedule: every 2 hours on weekdays # Every 2 hours, Monday-Friday
schedule: every 6 hours # Every 6 hours, all days
```
The compiler converts fuzzy schedules to deterministic cron (e.g., `daily on weekdays` → `43 5 * * 1-5`), scatters execution to avoid load spikes, and adds `workflow_dispatch:` for manual runs.
**Recommended Pattern:**
```yaml
# ✅ GOOD - Weekday schedule avoids Monday wall of work
on:
schedule: daily on weekdays
# ⚠️ ACCEPTABLE - But may create Monday backlog
on:
schedule: daily
```
#### Fork Security for Pull Requests
By default, `pull_request` triggers **block all forks** and only allow PRs from the same repository. Use the `forks:` field to explicitly allow forks:
```yaml
# Default: same-repo PRs only (forks blocked)
on:
pull_request:
types: [opened]
# Allow all forks
on:
pull_request:
types: [opened]
forks: ["*"]
# Allow specific fork patterns
on:
pull_request:
types: [opened]
forks: ["trusted-org/*", "trusted-user/repo"]
```
`pull_request_target` supports the same `forks:` field and defaults to same-repository PRs only (omitting `forks:` is equivalent to `forks: []`). List exact `owner/repo` or `owner/*` entries to admit specific forks. Strict mode rejects `"*"` unless the main workflow's top-level `features.dangerously-allow-pull-request-target-forks-all: true` is set; an imported feature does not count as this opt-in. Non-strict mode allows `"*"` with a warning, and the warning remains when strict mode is opted in. `acknowledge-risk: true` and disabled/trusted checkout do not suppress this warning — prefer `pull_request` and avoid `pull_request_target` fork admission unless base-repository context is required.
### Command Triggers (/mentions)
```yaml
on:
slash_command:
name: my-bot # Responds to /my-bot in issues/comments
```
This automatically creates conditions to match `/my-bot` mentions in issue bodies and comments.
You can restrict where commands are active using the `events:` field:
```yaml
on:
slash_command:
name: my-bot
events: [issues, issue_comment] # Only in issue bodies and issue comments
```
**Supported event identifiers:**
- `issues` - Issue bodies (opened, edited, reopened)
- `issue_comment` - Comments on issues only (excludes PR comments)
- `pull_request_comment` - Comments on pull requests only (excludes issue comments)
- `pull_request` - Pull request bodies (opened, edited, reopened)
- `pull_request_review_comment` - Pull request review comments
- `*` - All comment-related events (default)
**Note**: `issue_comment` and `pull_request_comment` both map to GitHub Actions' `issue_comment` event with filtering to distinguish them.
### Label Command Triggers
Trigger workflows when specific labels are added to issues, PRs, or discussions:
```yaml
# Shorthand: trigger on any labeled event
on: label-command my-label
# Or with explicit configuration
on:
label_command:
name: ai-review # Single label name (or use names: [...] for multiple)
events: [pull_request] # Optional: restrict to issues, pull_request, discussion (default: all three)
strategy: decentralized # Optional: route labeled events via generated agentic_commands.yml
remove_label: false # Optional: remove triggering label after activation (default: true)
```
Use `names:` for multiple labels that activate the same workflow:
```yaml
on:
label_command:
names: [ai-review, copilot-review]
events: [pull_request]
```
By default, the triggering label is automatically removed after the workflow activates (`remove_label: true`). Set `remove_label: false` to keep the label.
The activated label name is exposed to downstream jobs as `${{ needs.activation.outputs.label_command }}`.
### Semi-Active Agent Pattern
```yaml
on:
schedule:
- cron: "0/10 * * * *" # Every 10 minutes
issues:
types: [opened, edited, closed]
issue_comment:
types: [created, edited]
pull_request:
types: [opened, edited, closed]
push:
branches: [main]
workflow_dispatch:
```
### All You Can Eat Pattern
```yaml
on:
schedule: every 30 minutes
skip-if-match: 'is:issue is:open "gh-aw-workflow-id: my-workflow" in:body'
```
A frequent schedule whose activation is skipped while the previous output of the same workflow is still open, so the next item is produced as soon as the user closes the last one. See [All You Can Eat Pattern](workflow-patterns.md#all-you-can-eat-pattern).
---
description: Update existing agentic workflows using GitHub Agentic Workflows (gh-aw) with concise guidance on minimal changes and validation.
disable-model-invocation: true
---
# GitHub Agentic Workflow Updater
Update existing workflow files in `.github/workflows/`.
## Load These References First
- [github-agentic-workflows.md](github-agentic-workflows.md)
- [workflow-editing.md](workflow-editing.md)
- [workflow-constraints.md](workflow-constraints.md)
- [safe-outputs.md](safe-outputs.md)
- [syntax.md](syntax.md)
- [intent.md](intent.md) for preserving the outcome and re-deriving evals or operational value when it changes
Load these additional files only when relevant:
- [campaign.md](campaign.md)
- [experiments.md](experiments.md)
- [visual-regression.md](visual-regression.md)
- [serena-tool.md](serena-tool.md)
- [linter-workflows.md](linter-workflows.md)
- [release-workflow.md](release-workflow.md) whenever a workflow creates or updates release notes
- [documentation-workflows.md](documentation-workflows.md) for documentation agents, required docs checks, and post-merge page/index upkeep
- [agent-runtime-instructions.md](agent-runtime-instructions.md) for changes involving Docker, Cloud Hypervisor, ARC DinD, or self-hosted runners
- [skills.md](skills.md) when the user asks to add specific skills or agent plugins
- [operational-value-designer](../skills/operational-value-designer/SKILL.md) when updating graders, their evidence contract, or legacy evaluator syntax
## Scope
This prompt is for **updating existing workflows only**. For new workflows, use the creator prompt.
## Start the Conversation
1. Ask which workflow to update.
2. Ask what change is needed.
3. Then inspect the existing file, including its `intent:`, before proposing edits.
## First Decision: Frontmatter or Prompt Body?
Use [workflow-editing.md](workflow-editing.md) as the source of truth for the frontmatter-vs-body recompilation taxonomy and the `.lock.yml` review. Always compile after any edit, even for body-only changes.
## Update Rules
- make the smallest possible change
- preserve existing style and structure unless reorganization is required
- do not rewrite unrelated frontmatter sections
- preserve the existing `intent:` for implementation-only changes, including trigger or output-channel redesigns
- when the requested outcome materially expands, contracts, or changes, update `intent:` and re-derive its applicability, required effects, no-op conditions, architecture, and evals using [intent.md](intent.md)
- when an implementation-only change selects a different architecture, revalidate activation conditions, evidence window, deduplication or previous-result strategy, no-op behavior, and evals so event-specific rules do not survive an incompatible redesign
- for Copilot inference, recommend `permissions: { copilot-requests: write }` (scope and caveats: [syntax-core.md](syntax-core.md))
- prefer `toolsets:` for GitHub tools
- require `update-release` for agent-generated release notes or release-description changes; never use direct `gh`, API, or GitHub write-tool mutations from the agent
- when the user asks for specific skills or agent plugins, add them to the top-level `skills:` / `plugins:` frontmatter fields; never add on-the-fly install steps or prompt instructions to install them at run time (see [skills.md](skills.md))
- migrate custom graders to `graders..script`: synchronous JavaScript over immutable `session`, `config`, and `helpers`; reuse `helpers.createSessionLookups(session)` and return a finite number, `null`, or an object with `value`, not a metric array
- existing repository-owned Bash may retain `graders.operational-value.run`: replace stdin requests with the unified-session JSONL path in `$1` / `GH_AW_SESSION_FILE`, JSON config in `GH_AW_GRADER_CONFIG`, and preserve metric arrays; remove file writes, live fetches, and checkout scans; shell runs only in the separate job and is not yet microVM-isolated
- never translate legacy Bash/file evaluators by wrapping them in JavaScript I/O; capture evidence before grading and use the compiler-owned isolated `graders` job, never user steps in conclusion
See [workflow-constraints.md](workflow-constraints.md) for the read-only security posture (keep the agent job read-only, route writes through `safe-outputs:`).
## Cost-Oriented Update Checks
When refining existing workflows, keep edits minimal and confirm the design still follows the [High-Volume Triage and Escalation Pattern](workflow-patterns.md#high-volume-triage-and-escalation-pattern): cheap triage before escalation, `noop`/safe output for known/duplicate/stale cases, frontier reasoning reserved for high-value cases, and context pulled on demand. Keep sub-agent fan-out bounded (see [subagents.md](subagents.md)), then measure the change with `gh aw audit` and treat token or quality regressions as failures (see [token-optimization.md](token-optimization.md)).
## Security Rules
- never suggest GitHub mutation through raw GitHub tools when a safe output exists
- do not recommend `mode: remote` for GitHub tools unless explicitly required and properly configured
- do not replace `pull_request` with `pull_request_target` unless the user explicitly needs a `pull_request_target` design
- do not use `post-steps:` for agent-driven write behavior that belongs in a safe-output job
## Safer-Alternatives Pattern
Follow the "Safer Alternatives First" pattern in [workflow-constraints.md](workflow-constraints.md) when a requested change raises risk.
## Minimal Examples
### Add a GitHub toolset
```yaml
tools:
github:
toolsets: [default]
```
### Add a safe output
```yaml
safe-outputs:
add-comment:
max: 1
```
### Add network access
```yaml
network:
allowed:
- defaults
- node
```
### Add a skill or agent plugin
```yaml
skills:
- mattpocock/skills/tdd@801dca688564c529fa84f247f64472520d9ebe28
plugins:
- octo-org/agent-plugin@v1
```
## Validation Flow
- always inspect the workflow before editing
- explicitly determine whether the existing intent is preserved or changed
- keep the workflow valid at every step
## Final Steps
1. compile with `gh aw compile `
2. fix all compile errors
3. include the updated `.lock.yml` in the PR
## Final Message Rules
At the end, tell the user:
- what changed
- whether the change touched frontmatter or prompt body
- whether recompilation was required
- any next step they should take
Keep the summary short.
---
description: Upgrade agentic workflows to the latest version of gh-aw with automated compilation and error fixing
disable-model-invocation: true
---
You are specialized in **upgrading GitHub Agentic Workflows (gh-aw)** to the latest version.
Your job is to upgrade workflows in a repository to work with the latest gh-aw version, handling breaking changes and compilation errors.
Read the ENTIRE content of this file carefully before proceeding. Follow the instructions precisely.
## Capabilities & Responsibilities
**Prerequisites**
- The `gh aw` CLI may be available in this environment.
- Always consult the **instructions file** for schema and features:
- Local copy: @.github/aw/github-agentic-workflows.md
- Canonical upstream: https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/github-agentic-workflows.md
- If the user says “campaign”, “KPI”, “pacing”, “cadence”, or “stop-after”, consult @.github/aw/campaign.md (campaign/KPI workflows are still just agentic workflows; this is a design pattern playbook).
- If the user says "experiment", "A/B test", "variants", "prompt comparison", or "measure the impact", consult @.github/aw/experiments.md (A/B experiments are configured via the `experiments:` frontmatter field).
**Key Commands Available**
- `upgrade` → upgrade repository to latest version (combines all steps below)
- `fix` → apply automatic codemods to fix deprecated fields
- `compile` → compile all workflows
- `compile ` → compile a specific workflow
> [!NOTE]
> **Command Execution**
>
> When running in GitHub Copilot Cloud, you don't have direct access to `gh aw` CLI commands. Instead, use the **agentic-workflows** MCP tool:
> - `upgrade` tool → upgrade repository to latest version (recommended)
> - `fix` tool → apply automatic codemods to fix deprecated fields
> - `compile` tool → compile workflows
>
> When running in other environments with `gh aw` CLI access, prefix commands with `gh aw` (e.g., `gh aw upgrade`, `gh aw compile`).
>
> These tools provide the same functionality through the MCP server without requiring GitHub CLI authentication.
## Instructions
### 1. Fetch Latest gh-aw Changes
Before upgrading, always review what's new:
1. **Fetch Latest Release Information**
- Use GitHub tools to fetch the CHANGELOG.md from the `github/gh-aw` repository
- Review and understand:
- Breaking changes
- New features
- Deprecations
- Migration guides or upgrade instructions
- Summarize key changes with clear indicators:
- 🚨 Breaking changes (requires action)
- ✨ New features (optional enhancements)
- ⚠️ Deprecations (plan to update)
- 📖 Migration guides (follow instructions)
### 2. Run the Upgrade Command
**The primary and recommended way to upgrade is to use the `gh aw upgrade` command**, which automates all the upgrade steps in one command:
1. **Run the Upgrade Command**
```bash
gh aw upgrade
```
This single command will automatically:
- Update all agent and prompt files to the latest templates (like `gh aw init`)
- Apply automatic codemods to fix deprecated fields in all workflows (like `gh aw fix --write`)
- Update GitHub Actions versions in `.github/aw/actions-lock.json`
- Compile all workflows to generate lock files (like `gh aw compile`)
2. **Optional Flags**
- `gh aw upgrade --create-pull-request` - Open a pull request with the upgrade changes (alias: `--pr`)
- `gh aw upgrade --no-fix` - Update agent files only (skip codemods, actions, and compilation)
- `gh aw upgrade --no-actions` - Skip updating GitHub Actions versions
- `gh aw upgrade --dir custom/workflows` - Upgrade workflows in custom directory
3. **Review the Results**
- The command will display progress for each step
- Note any warnings or errors that occur
- All changes will be applied automatically
> [!TIP]
> **Use `gh aw upgrade` for most upgrade scenarios.** It combines all necessary steps and ensures consistency. Only use the manual steps below if you need fine-grained control or if the upgrade command fails.
### 3. Manual Upgrade Steps (Fallback)
If the `gh aw upgrade` command is not available or you need more control, follow these manual steps:
#### 3.1. Apply Automatic Fixes with Codemods
Before attempting to compile, apply automatic codemods:
1. **Run Automatic Fixes**
Use the `fix` tool with the `--write` flag to apply automatic fixes.
This will automatically update workflow files with changes like:
- Replacing 'timeout_minutes' with 'timeout-minutes'
- Replacing `network.firewall: false` with `sandbox.agent: false`. To keep the sandbox disabled, explicitly add:
```yaml
features:
dangerously-disable-sandbox-agent: true
sandbox:
agent: false
strict: false
```
- Removing deprecated 'mcp-scripts.mode' field
2. **Review the Changes**
- Note which workflows were updated by the codemods
- These automatic fixes handle common deprecations
#### 3.2. Attempt Recompilation
Try to compile all workflows:
1. **Run Compilation**
Use the `compile` tool to compile all workflows.
2. **Analyze Results**
- Note any compilation errors or warnings
- Group errors by type (schema validation, breaking changes, missing features)
- Identify patterns in the errors
### 4. Fix Compilation Errors
If compilation fails, work through errors systematically:
1. **Analyze Each Error**
- Read the error message carefully
- Reference the changelog for breaking changes
- Check the gh-aw instructions for correct syntax
2. **Common Error Patterns**
**Schema Changes:**
- Old field names that have been renamed
- New required fields
- Changed field types or formats
**Breaking Changes:**
- Deprecated features that have been removed
- Changed default behaviors
- Updated tool configurations
**Example Fixes:**
```yaml
# Old format (deprecated)
mcp-servers:
github:
mode: remote
# New format (do NOT include mode: remote - it does not work with GitHub Actions token)
tools:
github:
toolsets: [default]
```
3. **Apply Fixes Incrementally**
- Fix one workflow or one error type at a time
- After each fix, use the `compile` tool with `` to verify
- Verify the fix works before moving to the next error
4. **Document Changes**
- Keep track of all changes made
- Note which breaking changes affected which workflows
- Document any manual migration steps taken
### 5. Verify All Workflows
After fixing all errors:
1. **Final Compilation Check**
Use the `compile` tool to ensure all workflows compile successfully.
2. **Review Generated Lock Files**
- Ensure all workflows have corresponding `.lock.yml` files
- Check that lock files are valid GitHub Actions YAML
> [!NOTE]
> If you used the `gh aw upgrade` command in step 2, agent files and instructions have already been updated. The manual refresh step below is only needed if you followed the manual upgrade process.
## Creating Outputs
After completing the upgrade:
### If All Workflows Compile Successfully
Create a **pull request** with:
**Title:** `Upgrade workflows to latest gh-aw version`
**Description:**
```markdown
## Summary
Upgraded all agentic workflows to gh-aw version [VERSION].
## Changes
### gh-aw Version Update
- Previous version: [OLD_VERSION]
- New version: [NEW_VERSION]
### Key Changes from Changelog
- [List relevant changes from the changelog]
- [Highlight any breaking changes that affected this repository]
### Workflows Updated
- [List all workflow files that were modified]
### Upgrade Method
- Used `gh aw upgrade` command to automatically apply all changes
### Automatic Fixes Applied
- [List changes made by the upgrade command]
- [Reference which deprecated fields were updated by codemods]
### Manual Fixes Applied (if any)
- [Describe any manual changes made to fix compilation errors after upgrade]
- [Reference specific breaking changes that required manual fixes]
### Testing
- ✅ All workflows compile successfully
- ✅ All `.lock.yml` files generated
- ✅ No compilation errors or warnings
### Post-Upgrade Steps
- ✅ Ran `gh aw upgrade` to update all components
- ✅ All agent files and instructions updated automatically
## Files Changed
- Updated `.md` workflow files: [LIST]
- Generated `.lock.yml` files: [LIST]
- Updated agent files: [LIST]
```
### If Compilation Errors Cannot Be Fixed
Create an **issue** with:
**Title:** `Failed to upgrade workflows to latest gh-aw version`
**Description:**
```markdown
## Summary
Attempted to upgrade workflows to gh-aw version [VERSION] but encountered compilation errors that could not be automatically resolved.
## Version Information
- Current gh-aw version: [VERSION]
- Target version: [NEW_VERSION]
## Compilation Errors
### Error 1: [Error Type]
```
[Full error message]
```
**Affected Workflows:**
- [List workflows with this error]
**Attempted Fixes:**
- [Describe what was tried]
- [Explain why it didn't work]
**Relevant Changelog Reference:**
- [Link to changelog section]
- [Excerpt of relevant documentation]
### Error 2: [Error Type]
[Repeat for each distinct error]
## Investigation Steps Taken
1. [Step 1]
2. [Step 2]
3. [Step 3]
## Recommendations
- [Suggest next steps]
- [Identify if this is a bug in gh-aw or requires repository changes]
- [Link to relevant documentation or issues]
## Additional Context
- Changelog review: [Link to CHANGELOG.md]
- Migration guide: [Link if available]
```
## Best Practices
1. **Always Review Changelog First**
- Understanding breaking changes upfront saves time
- Look for migration guides or specific upgrade instructions
- Pay attention to deprecation warnings
2. **Fix Errors Incrementally**
- Don't try to fix everything at once
- Validate each fix before moving to the next
- Group similar errors and fix them together
3. **Test Thoroughly**
- Compile workflows to verify fixes
- Check that all lock files are generated
- Review the generated YAML for correctness
4. **Document Everything**
- Keep track of all changes made
- Explain why changes were necessary
- Reference specific changelog entries
5. **Clear Communication**
- Use emojis to make output engaging
- Summarize complex changes clearly
- Provide actionable next steps
## Important Notes
- When running in GitHub Copilot Cloud, use the **agentic-workflows** MCP tool for all commands
- When running in environments with `gh aw` CLI access, prefix commands with `gh aw`
- Breaking changes are inevitable - expect to make manual fixes
- If stuck, create an issue with detailed information for the maintainers
---
name: visual-regression
description: Reference prompt for visual regression testing using playwright + cache-memory for baseline screenshot storage across pull requests
---
# Visual Regression Testing
Use `playwright` for screenshots and `cache-memory` to persist baselines between PR runs.
## Example Workflow
```markdown
---
description: Capture screenshots on every PR and compare against cached baselines to detect visual regressions
on:
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: read
pull-requests: read
engine: copilot
network:
allowed:
- local
- playwright
tools:
playwright:
cache-memory:
key: visual-regression-baselines-${{ github.event.pull_request.base.ref }}
retention-days: 30
allowed-extensions: [".png", ".json"]
bash:
- "mkdir *"
- "cp *"
- "diff *"
- "date *"
safe-outputs:
add-comment:
max: 1
timeout-minutes: 30
---
Build and serve the app locally, then use Playwright to capture full-page screenshots of key pages into `/tmp/visual-regression/current/`.
Use filesystem-safe timestamps (no colons — colons break artifact uploads):
`date -u "+%Y-%m-%d-%H-%M-%S"`
If `/tmp/gh-aw/cache-memory/baselines/manifest.json` does not exist, copy screenshots there as new baselines and post: "Baselines initialized — N pages captured."
Otherwise compare each screenshot to its baseline. Post a comment summarizing: pages unchanged / pages with diffs. If nothing changed, use the `noop` safe-output.
```
## Key Design Decisions
- **`cache-memory` key per base branch** — scopes baselines to `main`, `develop`, etc.
- **Explicit baseline source** — state whether baselines come from `cache-memory`, a generated artifact, or a branch directory; do not leave baseline origin implicit.
- **`network.allowed: [local, playwright]`** — prevents SSRF; serve app locally, allow browser binary downloads
- **`retention-days: 30`** — beyond the default 7-day cache expiry
- **Filesystem-safe timestamps** — `YYYY-MM-DD-HH-MM-SS`; colons break artifact filenames
- **Minimal permissions** — all PR writes go through `safe-outputs`
## Network-Minimization Reminders
- Prefer local preview (`localhost`/`127.0.0.1`) over external preview environments.
- If external previews are required, allowlist exact domains (no broad wildcards).
- Enable `network.node` only when installing/building Node deps; scope to registries and preview hosts.
- Keep Playwright navigation limited to app-under-test URLs.
---
description: Git-backed work queue agent instructions.
---
# Work Queue
`tools.work-queue` schedules immutable DAGs and Claim-scoped effects.
`work-queue.jsonl` is authoritative; V3 omits storage selectors. Issues/PRs are dependencies.
For issue-backed WorkQueueOps: [WorkQueueOps](../../docs/src/content/docs/patterns/workqueue-ops.md).
## Select the role
- **Observer:** read/explain only; never submit, dispatch or finish Work.
- **Producer/dispatcher:** submit trusted plans/request bounded pool work;
queue authority grants no arbitrary resource writes.
- **Worker:** require compiler-supplied version-3 `claims`; never override
reserved `work_queue_assignment` or caller context.
Trust runtime roles, not snapshots: AW authenticates native run/workflow/revision;
reruns cannot inherit attempt 1. Absent branches are empty;
reject malformed/unsupported logs.
## Configure deployment
Declare workers:
```yaml
tools:
work-queue:
require-assignment: true
worker: true
```
Dispatchers require `tools.work-queue: true`, worker allowlist, bounded
`dispatch-workflow.max`. Approved AW routes/credentials bind Claims to immutable
native runs; ignore moved `target-ref`.
`aw.json` `work_queue`: concurrency, pending limits, retries, pools, fairness,
Issues. Defaults: weighted-priority, concurrency 16,
pending 4,096, singleton assignments, three attempts, 30-second backoff.
Submission initializes Policy/Work. Trusted submit/dispatch install pools/profiles;
workers, observers, previews and accepted-request recovery never install.
New workers require default-revision
AW source/contract verification and active registration.
`PoolInstall.config_ref` records provenance, not authority.
Preserve installed profiles/limits/epoch.
Standalone seeding is unsupported; AW/Actions authorize submissions.
Economic/installed-authority changes require quiescence and
`policy --from-config --epoch EPOCH`; config edits never rewrite active state.
Compatible deployments need no drain. Never expose queue-write credentials to
agents/snapshot MCP. Repository access rules are GitHub's responsibility.
See [deployment](../../docs/src/content/docs/patterns/workqueue-ops.md#deploy-a-native-queue).
## Mirror admitted Work with Issues
`aw.json` `work_queue.issues: true` mirrors admitted Work with purple `work` /
`work:` labels. `label` customizes both prefixes; `title_prefix` defaults
to `[work queue]`. Titles/summaries show 12-character Work IDs; bodies use full IDs.
No per-workflow overrides. Only protected AW hooks project admissions/original Claims.
Immutable `backing_issue` binds one Work per Issue. Agents never write
mirrors; human edits never establish Result. Pre-existing Issues require exact
installed `backing_issues` grants. Only trusted admission-time `completion_policy`
permits closure, never payload. Keep uncertain writes pending; never recreate or
globally repair. Maintenance: exact-run sync; recovery: `work-queue sync-issues --request-id ID`.
Upgrade closed-schema readers. See
[backing Issue reference](../../docs/src/content/docs/reference/work-queue.md#backing-issues).
Mirroring generates `.github/workflows/agentic-workqueue.yml` for Issue lifecycle
events; disabling removes it.
## Plan and dispatch
- Read immutable snapshots; stale predictions cannot override Policy.
Submit bounded, secret-free plans within scheduling limits.
- Request a pool prefix with `work_queue_dispatch_next` (`pool`, `max_claims`,
`max_dispatches`). Never choose winners/targets or use scalar dispatch.
- Trusted processing refreshes the ledger and commits a compatible fair prefix.
CAS losers discard tentative choices/charges and recompute.
ESLint/daily-report/conformance agents only explain staged plans.
Trusted controls validate batches; empty dispatcher intents fail.
Unassigned dispatchers cannot emit `noop` or `report_incomplete`.
## Execute original Claims
- Process only the assignment's original Claims and stored plans. Scope every
safe output and finish intent to one original Claim.
- Omit `claim_handle` only for an originally single-Claim assignment.
Multi-Claim assignments require it on every message even after others
close. Reject malformed, null, foreign or conflicting selectors.
- Finish members with `work_queue_claim_finish`, using
`outcome: "completed"` or `"cancelled"`. Missing finish authorizes no effects;
valid siblings settle independently.
- Retain Work with `outcome: "completed", keep_open: true` (default: false;
invalid with cancellation). Preserve both on retries. Verified delivery permits
another fair Claim, not successor release/backing Issue closure.
Pending/failed delivery blocks Claims; never rerun uncertain effects.
- Default to one Claim; batch compatible Work with reusable setup. Native
batch conclusions are not per-Work Results.
- Treat finish as an intent: trusted processing publishes Completion before
scoped effects and Result only after independently verified delivery.
- Beyond built-in safe outputs, declare `safe-outputs.claim-adapters`
([reference](safe-outputs-runtime.md)); each adapter binds one effect-type to
an independently verified result, never job success alone.
`` takes one JSON argument. `uninitialized` plus null SHA is empty.
Submit before dispatch.
Policyless ledgers fail; workers require Policy; `status: "staged"` is no grant.
## Dependencies and recovery
Require fresh Issue completed-state/PR merge evidence. Predecessors consume no
Claims; successors wait for predecessor Results.
Lost responses, dispatcher cancellation/deadlines never prove nonlaunch/termination.
Retain reservations until exact evidence. Never rerun uncertain effects after
Completion; bounded verification yields Result/DeliveryFailure. Compatible
deployments preserve obligations, debt, Results, frozen assignments and explicit
`execution_ref` pins. Unavailable/incompatible workers pause affected Work only.
Quiesce economic Policy changes. Reject unsupported protocols/scalar assignments.
Retries/checkpoints preserve submission identity; never delete queues to retry admission.
## Load details only when needed
- Operator commands, TUI and diagnostic artifacts:
[queue reference](../../docs/src/content/docs/reference/work-queue.md).
Cancellation terminates Work, not workers; reconcile separately.
`gh aw work-queue --repo OWNER/REPO stats --json`. `dispatch-next` grants
reservations, never launches; use the authorized dispatcher.
- Destructive: `gh aw work-queue clear --reason CODE [--dry-run | --hard]`
requires repo maintain/admin, forbids CI, and requires interactive confirmation
of the exact snapshot preview; no bypass. `--hard` replaces the ledger,
forgetting Work/Claim identities, retry history and fairness debt. Admission/grants
must already be paused, without open Claims/pending deliveries.
See [hard reset](../../docs/src/content/docs/reference/work-queue.md#hard-reset).
- Daily report rotation and Claims:
[portfolio example](../../docs/src/content/docs/gallery/daily-report-portfolio.md)
and [shared worker instructions](../workflows/shared/daily-report-worker.md).
- Contracts: [specification](../../docs/src/content/docs/specs/work-queue-specification.md#91-implementation-coverage-and-remaining-requirements).
- Models/fixtures/bounded verification: [formal reference](../../specs/work-queue/README.md).
Tests prove neither Result nor live deployment.
---
description: Shared architectural and security constraints for designing or updating agentic workflows.
---
# Agentic Workflow Constraints
## Execution Model
Agentic workflows run as a **single GitHub Actions job** with one agent execution.
## Can Do
- read GitHub data, APIs, web pages, and local repository files
- run tools inside the single job
- use MCP servers and safe outputs
- create GitHub resources through `safe-outputs:`
- persist lightweight state with `cache-memory` or other approved mechanisms
## Cannot Do
- pause and resume for external events
- orchestrate multi-stage pipelines with job dependencies
- pass state between multiple AI jobs in one workflow run
- implement built-in rollback across external systems
- wait for another workflow or deployment to finish inside the same agent run
## Recommend Traditional GitHub Actions When
- multi-stage deployment pipelines
- fan-out/fan-in job orchestration
- long waits for approvals or external systems
- rollback logic across several steps or systems
- cross-job state transfer
Suggested response:
> This requires capabilities the single-job agentic model does not support. Use traditional GitHub Actions for orchestration and agentic workflows for the AI-specific step.
## Security Posture
- Keep the main agent job read-only.
- Do not add GitHub write permissions to the agent job.
- Route GitHub writes through `safe-outputs:`.
- Do not create issues directly through agent tools, `gh`, or GitHub APIs; use `safe-outputs.create-issue`, check for an existing issue first, and use `noop` when no issue is needed.
- Prefer `tools.github.mode: gh-proxy` with `gh` for GitHub reads.
- Prefer `tools.cli-proxy: true` with mounted `mcp-clis` commands for non-GitHub MCP tools.
- Constrain `network.allowed:` to the minimum required ecosystems or domains.
- For workflows that only inspect in-repo files and/or read GitHub through `gh-proxy`, default to no network access (`network.allowed: []`), not `network: defaults`. Allow `defaults` when infrastructure access is needed for install/build/test steps, alongside the required ecosystem for package downloads.
- Use `${{ steps.sanitized.outputs.text }}` for untrusted user content.
- Never pass `${{ secrets.* }}` or other credentials to `post-steps:` or custom secret-scanning steps, or write secret values to logs or artifacts. Use supported declarative authentication for agent tools, or run credential-dependent scanning in a separate least-privilege non-agent job without exposing secret values.
## Safer Alternatives First
When a requested feature increases risk:
1. explain the risk
2. propose the safer pattern first
3. require explicit confirmation before relaxing safeguards
## Common Risk Areas
- direct write permissions instead of safe outputs
- auto-merge or bypassing review
- overly broad network access
- unbounded bash allowlists for untrusted input
- shell injection: interpolating `${{ github.event.* }}` or other untrusted expressions directly into `run:` scripts; pass untrusted values through environment variables instead
- placing OIDC/secret bootstrap in `pre-steps` instead of earlier `setup-steps`
- using `post-steps:` for agent-driven write actions
- placing credentials in `post-steps:` or custom secret-scanning steps
## Self-Hosted Runner Compatibility
When `runs-on` is any value other than GitHub-hosted labels (`ubuntu-latest`, `ubuntu-slim`, `windows-latest`, `macos-latest`):
- Set `runs-on` explicitly (not inherited from imports); accepts string, array, or runner-group object. Framework jobs (activation, safe-outputs, unlock, etc.) default to hosted `ubuntu-slim`, so also set `runs-on-slim` (same forms) to route them to the self-hosted runner.
- Write transient state, tool downloads, and outputs under `$RUNNER_TEMP`, not `/tmp` (which can persist across jobs on shared runners).
- Agent steps run as the runner user, not root — don't install to system-wide paths. The egress firewall needs sudo; if unavailable, it can be disabled (removing egress filtering) — surface the trade-off to the user rather than encoding it.
- Declare every outbound domain in `network.allowed`; `defaults` covers only certificate, JSON-schema, and stock Ubuntu hosts, so add `github`, language ecosystems, or engine sets explicitly (see [network.md](network.md)). Non-allow-listed domains are blocked when the firewall is enabled.
- Do not install to `/usr/local` or the toolcache (may be read-only/shared); use job-scoped writable paths.
- Do not hardcode `/home/runner` or any literal home path — read `$HOME`; use `$RUNNER_TEMP` for transient state.
- For GitHub Enterprise Server, enable GHES compatibility (GHES-compatible artifact action versions, enterprise API endpoint).
For the full set of requirements (Docker socket, ARC / Docker-in-Docker, network egress, GHES specifics), follow the [Self-Hosted Runners](/gh-aw/reference/self-hosted-runners/) reference page.
## Shared Reminder
Reference this file from creator, updater, and debugger prompts instead of repeating the architectural explanation.
---
description: Shared guidance for editing, recompiling, and validating GitHub Agentic Workflow files.
---
# Workflow Editing Basics
Agentic workflows are single markdown files at `.github/workflows/.md`.
## File Structure
1. **YAML frontmatter** between `---` markers: triggers, permissions, tools, network, imports, safe outputs.
2. **Markdown body**: the agent prompt.
## Recompile When Changing Frontmatter Fields
Run `gh aw compile ` after changing:
- `on:`
- `permissions:`
- `tools:`
- `network:`
- `imports:`
- `safe-outputs:`
- `mcp-servers:`
- engine, timeout, concurrency, or other YAML configuration
## No Recompile Required for Runtime Behavior
Body-only text edits take effect on the next run without recompilation:
- agent instructions
- task descriptions
- examples
- formatting guidance
- clarifications and guardrails
Exception: adding or changing GitHub Actions expressions or `{{#if}}` conditions in the body or local runtime imports requires recompilation — the compiler selects their bindings and fails on malformed conditions (see [context.md](context.md)).
**Always run `gh aw compile` after any change** (frontmatter or body) to keep `.lock.yml` metadata in sync.
## Validation Commands
```bash
gh aw compile
gh aw compile --strict
gh aw compile --purge
```
Use `--strict` for production-quality validation.
## Detect Stale Lock Files
Run `gh aw list` from the repository root and check the `COMPILED` column. `No` means the source frontmatter does not match the existing `.lock.yml`; `N/A` means the lock file is missing.
To inspect stale or missing lock files interactively, use `--stale`:
```bash
gh aw list --stale
```
For an automated check that fails when any lock file is stale or missing, use:
```bash
gh aw list --json | jq -e 'all(.[]; .compiled == "Yes")'
```
Recompile any stale workflows and commit each generated `.lock.yml` with its source:
```bash
gh aw compile
```
## Editing Rules
- Smallest change that satisfies the request.
- Preserve structure unless reorganization is the task.
- Never leave a workflow broken.
- If compile fails, fix all errors before stopping.
- After any change, review the generated `.lock.yml`.
## Prompt-Authoring Rules
- Specific and imperative.
- Short examples over long tutorials.
- Reference dedicated instruction files instead of duplicating.
- Tell agents to use `noop` when no visible action is needed.
---
description: Shared design patterns for command workflows, monitoring workflows, scheduled one-item-at-a-time (All You Can Eat) workflows, large-repository workflows, database migration reviews, and cross-repository operations.
---
# Workflow Patterns
## Command Workflows
### Prefer `slash_command` when
- the action is conversational
- the user may pass arguments in the comment body
- the workflow should work across issues, pull requests, and discussions
### Prefer `label_command` when
- the action is one-shot and argument-free
- discoverability in the GitHub UI matters
- the workflow fits a label-driven process
### Combine both when
- the action is common enough to justify both invocation styles
- you want UI discoverability plus comment-based flexibility
See also: [triggers.md](triggers.md)
## Monitoring Workflows
### Use `workflow_run` when
- monitoring another GitHub Actions workflow in the **same repository**
- reacting to workflow completion/conclusion
Incident-triage pattern:
- trigger: `on.workflow_run` for the named deployment/CI workflow
- permissions: include `actions: read`; main job read-only
- reads: failed job logs/artifacts via GitHub tools
- output: `create-issue` with impact/root cause; `noop` when no action needed
Compact `workflow_run` examples:
- **Deploy workflow failure triage**: trigger on `workflow_run` for `Deploy`, read failed jobs/logs/artifacts, create one incident issue, `noop` when rerun succeeds.
- **CI regression watcher**: trigger on `workflow_run` for `CI`, compare current failure against recent runs, create issue only for new regressions, `noop` for known flakes.
Incident duplicate-suppression pattern:
- derive a stable incident key from the monitored workflow and failure signal (for example `##`)
- search open issues by title-prefix/label/key before creating a new issue
- create via `safe-outputs.create-issue` only when no matching open incident exists
- use `noop` for duplicates and include the matching issue number in the explanation
### Use `deployment_status` when
- monitoring an external deployment service reporting back to GitHub
Rule of thumb:
- `workflow_run` → GitHub Actions outcomes in this repo
- `deployment_status` → external platform outcomes via Deployments API
Do triage, evidence collection, and summary in one agent job — the single-job limits (no multi-job fan-out/fan-in, no cross-workflow waits or chaining) from [workflow-constraints.md](workflow-constraints.md) apply.
See also: [deployment-status.md](deployment-status.md)
## High-Volume Triage and Escalation Pattern
For workflows receiving many similar events (issues, PR comments, CI failures, security alerts, dependency events):
- start with a cheap triage/classification pass
- detect known/duplicate/stale/low-value cases first
- emit `noop` or a safe output when triage is confident
- escalate to the main agent only when uncertain or genuinely new/high-value
Decision flow:
```text
IF cheap triage is confident (known/duplicate/stale/low-value) THEN
emit safe output or noop
ELSE
escalate to the main agent
END IF
```
Use with pull-context workflows: fetch targeted evidence on demand instead of pushing raw logs into the initial prompt.
## All You Can Eat Pattern
Nickname for a scheduled workflow that keeps at most one *unconsumed* output alive at a time. The workflow wakes up frequently (typically every 30 minutes), but activation is skipped while the previous output from that workflow is still open. As soon as the user consumes the previous output (closes the issue, merges or closes the pull request), the next scheduled run produces the next item — content is served one plate at a time, on demand, and runs proceed sequentially.
Use when:
- the work is an open-ended backlog (improvement ideas, maintenance chores, research notes), not an event-driven reaction
- each output needs human consumption, so producing another before the previous one is closed only creates noise
- low latency matters: the next item should appear within one schedule tick after the user clears the last one
Avoid when outputs are independent and reviewable in parallel, or when the schedule is a periodic report tied to a window — use the recurring digest defaults in [report.md](report.md) instead.
### Shape
```yaml
on:
schedule: every 30 minutes
skip-if-match: 'is:issue is:open "gh-aw-workflow-id: my-workflow" in:body'
permissions: read-all
safe-outputs:
create-issue:
title-prefix: "[all-you-can-eat] "
max: 1
expires: 7
```
Rules:
- **One open item at a time.** Cap the safe output with `max: 1`. The string form of `skip-if-match` implies a threshold of `max: 1`, so any single open match skips activation; no extra field is needed.
- **Match on stable identity.** Prefer the hidden `gh-aw-workflow-id: ` marker (`in:body`) over a title prefix, because humans rename titles; see [Footer Control](https://github.com/github/gh-aw/blob/main/docs/src/content/docs/reference/footers.md). A title match (`in:title "[all-you-can-eat] "`) works when the workflow also sets `title-prefix:`. The query is auto-scoped to the current repository.
- **Pull requests use the same shape** with `is:pr is:open` and `create-pull-request`; drafts count as open. Allow a small queue depth by raising the threshold (`skip-if-match: { query: ..., max: 3 }`) when the user can consume several items in parallel.
- **Do not starve.** If the user never closes the item, the workflow never runs again. Set `expires:` on the safe output (or an equivalent auto-close) so an abandoned item eventually unblocks the schedule.
- **Skipped runs are cheap.** The check runs in the `pre_activation` job, so the agent never starts and no tokens are spent on a skipped tick.
- **Keep concurrency on.** `skip-if-match` is evaluated before activation and cannot cancel a run already in flight; default workflow concurrency prevents two runs from producing at once.
### Learn from the closed output
Because the run only activates after the previous item was closed, the closing action is the feedback signal. Instruct the agent to:
1. search the most recently closed items from this workflow (same marker or title prefix), newest first and bounded — for example the last three
2. read the close reason (`completed` vs `not planned`), the closing comment, labels, and any review feedback
3. treat "not planned" or a rejecting comment as a negative signal and do not re-propose the same idea; treat completed/merged as a positive signal for similar work
4. persist a compact accept/reject list across runs with `cache-memory`, or `repo-memory` when losing the list would cause repeat proposals (see [memory-stateful-patterns.md](memory-stateful-patterns.md))
5. emit `noop` when nothing clears the quality bar left by past rejections
See also: [triggers.md](triggers.md), [safe-outputs-content.md](safe-outputs-content.md), [maintainer.md](maintainer.md)
## Large-Repository Improvement Pattern
For recurring maintenance in large repos:
- use `cache-memory`
- process one package/module/directory per run
- store last-processed item; round-robin
- prefer small focused PRs over wide sweeps
See also: [memory.md](memory.md)
## Step Authoring Guidance
When writing `steps:`, `pre-steps:`, and `post-steps:`, choose the implementation type in this order of preference:
### 1. Preferred: `actions/github-script`
Use `actions/github-script` for GitHub API interactions and general scripting. The workflow compiler handles action pinning automatically; specify a recent major version tag (`@v7`) without a SHA.
- Provides typed access to the GitHub REST API via `github.rest.*`
- Exposes `context`, `core`, `github`, `io`, and `exec` helpers
- Eliminates shell injection risks for untrusted input
- Example:
```yaml
steps:
- name: Fetch issue data
uses: actions/github-script@v7
with:
script: |
const issue = await github.rest.issues.get({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
});
core.setOutput('title', issue.data.title);
```
### 2. Shell scripts
Use `run:` steps when `actions/github-script` is not suitable. To prevent shell injection, never interpolate untrusted values directly into the script body. Any value that originates from user input — including `github.event.issue.title`, `github.event.issue.body`, `github.event.comment.body`, `github.event.pull_request.title`, `github.event.pull_request.body`, and `github.head_ref` — must be passed through environment variables:
```yaml
# ❌ Unsafe: direct expression interpolation into the shell script
- name: Unsafe comment
run: gh issue comment ${{ github.event.issue.number }} --body "${{ github.event.issue.title }}"
# ✅ Safe: pass untrusted values through env vars and reference them as $VAR_NAME
- name: Safe comment
env:
ISSUE_NUMBER: ${{ github.event.issue.number }}
TITLE: ${{ github.event.issue.title }}
run: gh issue comment "$ISSUE_NUMBER" --body "$TITLE"
```
### 3. Python (last resort)
Use Python only when the task genuinely requires data science or numeric libraries (for example `pandas`, `numpy`, `matplotlib`). Prefer `actions/github-script` or a shell step for everything else.
## Pre-Step Data Fetching Pattern
Use deterministic `steps:` when the workflow needs large external data before the agent runs.
Rules:
- write prepared files to `/tmp/gh-aw/agent/`
- trim large outputs before handing to the agent
- set `GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}` on every `gh` step
- add `permissions: actions: read` for downloading workflow logs/artifacts
- use `jq` to reduce JSON payload size
Compact reporting/incident prefetch example:
```yaml
steps:
- name: Prefetch compact failure context
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
RUN_ID: ${{ github.event.workflow_run.id }}
run: |
gh api "repos/$REPO/actions/runs/$RUN_ID/jobs" \
--jq '[.jobs[] | select(.conclusion != "success") | {name, conclusion, started_at, completed_at}]' \
> /tmp/gh-aw/agent/failed_jobs.json
```
## PR Visual Regression Pattern
For PR UI validation and screenshot diffs:
- trigger: `pull_request`
- tools: `playwright` plus `cache-memory` for baseline metadata
- permissions: read-only repo/PR access
- output: `add-comment` with pass/fail summary and artifact links
- fallback: `noop` when no UI changes detected
## Design Token / CSS Governance Pattern
For PRs touching design tokens or CSS files that require a linked design reference (Figma link, design doc URL, or ADR token):
- trigger: `pull_request` with `paths:` scoped to token/style files (for example `tokens/**`, `**/*.tokens.json`, `**/*.css`, `src/styles/**`, `design-system/**`)
- permissions: `pull-requests: read`, `contents: read`; agent job read-only
- reads: PR body and comments via `gh pr view` to locate the linked design reference; validate the link target is reachable and matches the changed components
- output: apply the classify flow from [PR Checks with Linked References](github-agentic-workflows.md) (valid → ✅ comment; incomplete → gap comment; missing → request comment, escalating to `create-issue` only for a required blocking gate with no open issue already covering the scope)
- fallback: `noop` when the `paths:` guard excludes all changed files
## QA Coverage Report Pattern
For PR QA coverage summaries (gaps, risks, suggested test focus):
- trigger: `pull_request` (optionally scoped with `paths:`)
- tools: `github` (`gh-proxy`) for changed files, PR metadata, labels, checks
- permissions: `contents: read`, `pull-requests: read`; agent job read-only
- output: `add-comment` with coverage matrix and untested/high-risk areas
- fallback: `noop` for non-testable changes (e.g. docs-only)
## PM Stakeholder Digest Pattern
For recurring product/stakeholder digests:
- trigger: fuzzy `schedule` (e.g. `weekly on mondays`)
- tools: `github` (`gh-proxy`), optional `cache-memory` for period-over-period continuity
- permissions: read-only
- output: `create-issue` by default; `create-discussion` only when requested
- prompt: audience-aware language (summary first, details second)
## Database Migration Safety Pattern
For PRs adding/modifying migration files:
- trigger: `pull_request` with `paths:` scoped to migration dirs (e.g. `db/migrate/**`, `migrations/**`, `*.sql`)
- permissions: `contents: read`, `pull-requests: read`; agent job read-only
- reads: changed migration content via GitHub tools
- output: `add-comment` flagging risky operations; `noop` when clean
- prompt: include migration best practices
## Release Automation Pattern
For workflows that build, test, publish a GitHub release, and generate release highlights:
- trigger: `workflow_dispatch` with a `release_type` input (`patch`, `minor`, `major`); restrict with `roles: [admin, maintainer]`
- structure: **Classic + Agent** hybrid — all build/test/release jobs are standard GitHub Actions jobs; the agent job runs last and only updates the release description
- classic jobs: `config` (compute semver), `build` (compile + upload artifact), `test`, `release` (create prerelease with `--generate-notes --latest=false`); output `release_id` from the release job
- agent job: depends on `release` job; pre-fetches merged PRs and changelog in `steps:`; uses `tools: cli-proxy: true`; writes highlights via `update-release` with `operation: prepend`
- safe output: agent-generated release notes and release-description changes must use `update-release`; never mutate releases directly with `gh`, the GitHub API, or a GitHub write tool; set `threat-detection: false` because release bodies can contain code snippets
- permissions: global `contents: read`; per-job `contents: write` only on jobs that push tags or create releases
See [release-workflow.md](release-workflow.md) for the full pattern, frontmatter template, job skeletons, and reference implementation pointer.
## Cross-Repository Pattern
For cross-repo reads and writes:
- enable GitHub toolsets needed for external repos
- configure PAT or GitHub App auth in `safe-outputs:` for cross-repo writes
- tell the agent to set `target-repo` explicitly
- document required token scopes in the prompt or instructions
Cross-repo workflows inherit single-job constraints from [workflow-constraints.md](workflow-constraints.md).
direct link
Domain: github.github.com
Links:
URLs of crawlers that visited me.