From b8fe05df2bf5d789e21cd69b6b94659f981cc703 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Sat, 31 Jan 2026 20:00:23 +0000
Subject: [PATCH 1/4] Initial plan
From 64100f9b67a9bee39f4921d36dec953179a05f1a Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Sat, 31 Jan 2026 20:05:01 +0000
Subject: [PATCH 2/4] Initial plan for safe output patterns documentation
Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com>
---
.github/aw/actions-lock.json | 2 +-
pkg/workflow/data/action_pins.json | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/.github/aw/actions-lock.json b/.github/aw/actions-lock.json
index 80130e4a1a..2db5179bb9 100644
--- a/.github/aw/actions-lock.json
+++ b/.github/aw/actions-lock.json
@@ -100,7 +100,7 @@
"version": "v5.6.0",
"sha": "a26af69be951a213d495a4c3e4e4022e16d87065"
},
- "actions/upload-artifact@v4": {
+ "actions/upload-artifact@v4.6.2": {
"repo": "actions/upload-artifact",
"version": "v4.6.2",
"sha": "ea165f8d65b6e75b540449e92b4886f43607fa02"
diff --git a/pkg/workflow/data/action_pins.json b/pkg/workflow/data/action_pins.json
index 2db5179bb9..80130e4a1a 100644
--- a/pkg/workflow/data/action_pins.json
+++ b/pkg/workflow/data/action_pins.json
@@ -100,7 +100,7 @@
"version": "v5.6.0",
"sha": "a26af69be951a213d495a4c3e4e4022e16d87065"
},
- "actions/upload-artifact@v4.6.2": {
+ "actions/upload-artifact@v4": {
"repo": "actions/upload-artifact",
"version": "v4.6.2",
"sha": "ea165f8d65b6e75b540449e92b4886f43607fa02"
From 072121e7d60c09bb593f21567b9632ce53931ce7 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Sat, 31 Jan 2026 20:13:11 +0000
Subject: [PATCH 3/4] Add comprehensive safe output patterns documentation
- Created docs/safe-outputs-guide.md with decision tree and best practices
- Added 4 example workflows in docs/examples/safe-outputs/
- conditional-output.md: Security scanning with severity routing
- multi-output-analysis.md: Hierarchical parent-child pattern
- fix-or-report.md: Automated fix with manual fallback
- comment-pattern.md: Status updates with escalation
- Created scratchpad/safe-outputs-patterns.md technical deep-dive
- Updated AGENTS.md with Safe Outputs Best Practices section
- Updated scratchpad/README.md to reference new documentation
Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com>
---
AGENTS.md | 145 ++++
docs/examples/safe-outputs/comment-pattern.md | 491 +++++++++++
.../safe-outputs/conditional-output.md | 335 ++++++++
docs/examples/safe-outputs/fix-or-report.md | 506 +++++++++++
.../safe-outputs/multi-output-analysis.md | 419 ++++++++++
docs/safe-outputs-guide.md | 518 ++++++++++++
scratchpad/README.md | 1 +
scratchpad/safe-outputs-patterns.md | 787 ++++++++++++++++++
8 files changed, 3202 insertions(+)
create mode 100644 docs/examples/safe-outputs/comment-pattern.md
create mode 100644 docs/examples/safe-outputs/conditional-output.md
create mode 100644 docs/examples/safe-outputs/fix-or-report.md
create mode 100644 docs/examples/safe-outputs/multi-output-analysis.md
create mode 100644 docs/safe-outputs-guide.md
create mode 100644 scratchpad/safe-outputs-patterns.md
diff --git a/AGENTS.md b/AGENTS.md
index f483c74480..9ba7465334 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1037,6 +1037,151 @@ tools:
- Accessibility analysis and visual testing
- Multi-browser support (Chromium, Firefox, Safari)
+## Safe Outputs Best Practices
+
+Safe outputs are the primary mechanism for workflows to create GitHub issues, discussions, pull requests, and comments. Understanding when and how to use each output type is critical for creating effective workflows.
+
+### Quick Output Type Selection
+
+**Decision Guide:**
+- **Action required?** → `create-issue`
+- **Automated fix possible?** → `create-pull-request`
+- **Report/analysis only?** → `create-discussion`
+- **Updating existing item?** → `add-comment`
+
+### Output Types and When to Use Them
+
+**Create Issue (`create-issue`)** - Use when:
+- Action is required (task tracking, assignment needed)
+- Status tracking required (open/closed)
+- Needs labels, milestones, or project boards
+- Time-sensitive action items need visibility
+
+**Create Discussion (`create-discussion`)** - Use when:
+- Sharing analysis, reports, or insights
+- No specific action required
+- Community conversation welcome
+- Long-term reference material needed
+- Regular status reports or summaries
+
+**Create Pull Request (`create-pull-request`)** - Use when:
+- Automated fix can be proposed
+- Code changes are ready to review
+- Changes are non-breaking and safe
+- Tests can validate the changes
+
+**Add Comment (`add-comment`)** - Use when:
+- Updating existing issue/PR/discussion
+- Providing progress updates
+- Responding to triggers
+- Linking related items created by the workflow
+
+**Update Issue (`update-issue`)** - Use when:
+- Need to modify existing issue content, labels, or assignees
+- Changing status or milestones
+- Use sparingly - prefer comments for updates
+
+### Multi-Output Patterns
+
+74.8% of agentic workflows use multiple safe output types. Common patterns:
+
+**Pattern 1: Conditional Outputs** - Route by severity/priority
+```yaml
+safe-outputs:
+ create-issue: # Critical findings only
+ max: 5
+ create-discussion: # Summary of all findings
+ max: 1
+```
+
+**Pattern 2: Hierarchical Outputs** - Parent summary + child tasks
+```yaml
+safe-outputs:
+ create-discussion: # Overall analysis
+ max: 1
+ create-issue: # Individual actionable items
+ max: 10
+ add-comment: # Link discussion and issues
+ max: 1
+```
+
+**Pattern 3: Fix-or-Report** - Attempt automation, fallback to manual
+```yaml
+safe-outputs:
+ create-pull-request: # If fix is safe
+ max: 1
+ create-issue: # If manual review needed
+ max: 1
+```
+
+**Pattern 4: Comment-First** - Update-focused with escalation
+```yaml
+safe-outputs:
+ add-comment: # Always provide status
+ hide-older-comments: true
+ max: 1
+ create-issue: # Only for persistent problems
+ max: 1
+```
+
+### Best Practices
+
+**Avoid Duplication:**
+```yaml
+# ❌ BAD - Creates both issue and discussion for same finding
+safe-outputs:
+ create-issue: {max: 10}
+ create-discussion: {max: 1}
+# Agent duplicates content in both
+
+# ✅ GOOD - Conditional based on severity
+safe-outputs:
+ create-issue: {max: 5} # Critical only
+ create-discussion: {max: 1} # Summary with all findings
+```
+
+**Cleanup Transient Items:**
+```yaml
+safe-outputs:
+ create-issue:
+ expires: 7d # Auto-close when condition resolves
+ create-discussion:
+ close-older-discussions: true # Keep only latest
+```
+
+**Limit Output Volume:**
+```yaml
+safe-outputs:
+ create-issue:
+ max: 5 # Top 5 priorities, not all 50 findings
+```
+
+**Consistent Titles:**
+```yaml
+safe-outputs:
+ create-issue:
+ title-prefix: "[security-critical] "
+ create-discussion:
+ title-prefix: "[Security Scan] "
+```
+
+### Documentation References
+
+- **[Safe Outputs Guide](docs/safe-outputs-guide.md)** - Decision tree, patterns, best practices
+- **[Example Workflows](docs/examples/safe-outputs/)** - Conditional, multi-output, fix-or-report, comment patterns
+- **[Technical Deep-Dive](scratchpad/safe-outputs-patterns.md)** - Implementation details, advanced patterns
+- **[System Specification](scratchpad/safe-outputs-specification.md)** - Formal specification
+- **[Environment Variables](scratchpad/safe-output-environment-variables.md)** - Configuration reference
+
+### Statistics
+
+Based on 147 agentic workflows (2026-01):
+- 76.9% use `create-issue` (113 workflows)
+- 73.5% use `create-discussion` (108 workflows)
+- 36.7% use `create-pull-request` (54 workflows)
+- 23.1% use `add-comment` (34 workflows)
+- 74.8% use 2+ output types (110 workflows)
+
## Testing Strategy
**⚠️ IMPORTANT: Prefer selective testing over running all tests.**
diff --git a/docs/examples/safe-outputs/comment-pattern.md b/docs/examples/safe-outputs/comment-pattern.md
new file mode 100644
index 0000000000..135375d12a
--- /dev/null
+++ b/docs/examples/safe-outputs/comment-pattern.md
@@ -0,0 +1,491 @@
+# Comment Pattern
+
+This example demonstrates a comment-first approach for status updates with escalation to issues only when necessary.
+
+## Pattern Overview
+
+**Use Case:** CI status reporting with escalation for persistent failures
+
+**Output Strategy:**
+- Always → Add comment with CI results to PR/issue
+- Persistent failure (3+ runs) → Create issue for investigation
+- Hide older comments to reduce noise
+
+**Benefits:**
+- All status updates in one place
+- Historical context preserved (collapsed older comments)
+- Escalates only genuine problems
+- Reduces issue tracker noise
+
+## Workflow Implementation
+
+```yaml
+---
+name: CI Status Reporter
+description: Reports CI results and escalates persistent failures
+on:
+ pull_request:
+ types: [opened, synchronize]
+ push:
+ branches: [main, develop]
+permissions:
+ contents: read
+ pull-requests: write
+ issues: write
+ checks: read
+engine: copilot
+tools:
+ github:
+ toolsets: [default, actions]
+ bash:
+ - "jq *"
+safe-outputs:
+ add-comment:
+ target: triggering
+ hide-older-comments: true # Hide previous CI comments
+ max: 1
+ create-issue:
+ title-prefix: "[ci-failure] "
+ labels: [ci, bug, needs-investigation]
+ max: 1 # Only create issue for persistent failures
+timeout-minutes: 15
+---
+
+# CI Status Reporter
+
+You are a CI status reporter that provides detailed feedback on continuous integration runs and escalates persistent failures.
+
+## Objective
+
+Monitor CI status and provide feedback:
+1. **Always** → Add comment with CI results to the PR
+2. **If persistent failure** (3+ consecutive failures) → Create issue
+3. **Hide older comments** → Keep comment thread clean
+
+## Monitoring Process
+
+### Step 1: Fetch CI Results
+
+```bash
+# Get workflow runs for this commit
+gh api "/repos/${{ github.repository }}/actions/runs" \
+ --jq ".workflow_runs[] | select(.head_sha == \"${{ github.sha }}\")" \
+ > /tmp/workflow-runs.json
+
+# Get check runs for detailed status
+gh api "/repos/${{ github.repository }}/commits/${{ github.sha }}/check-runs" \
+ > /tmp/check-runs.json
+
+# Parse results
+cat /tmp/workflow-runs.json | jq '.[] | {name, status, conclusion, html_url}'
+```
+
+### Step 2: Analyze Failure Patterns
+
+```bash
+# Check for persistent failures (last 3 runs)
+gh api "/repos/${{ github.repository }}/actions/workflows/{workflow_id}/runs" \
+ --jq ".workflow_runs[:3] | map(.conclusion) | all(. == \"failure\")" \
+ > /tmp/persistent-failure.txt
+
+PERSISTENT_FAILURE=$(cat /tmp/persistent-failure.txt)
+
+# Get failure count from recent history
+FAILURE_COUNT=$(gh api "/repos/${{ github.repository }}/actions/workflows/{workflow_id}/runs" \
+ --jq '.workflow_runs[:10] | map(select(.conclusion == "failure")) | length')
+```
+
+### Step 3: Add Status Comment
+
+Always add a comment with the current CI status:
+
+```markdown
+[add-comment]
+target: triggering
+body: |
+ ## 🔄 CI Status Report
+
+ **Status:** {status_emoji} {status_text}
+
+ ### Summary
+
+ | Workflow | Status | Duration | Details |
+ |----------|--------|----------|---------|
+ {workflow_status_table}
+
+ ### {if all_passed}✅ All Checks Passed{/if}{if some_failed}❌ Some Checks Failed{/if}{if all_failed}🚫 All Checks Failed{/if}
+
+ {if all_passed}
+ All CI checks completed successfully! This PR is ready for review.
+
+ **Next Steps:**
+ - [ ] Code review
+ - [ ] Approval from maintainers
+ - [ ] Merge when ready
+ {/if}
+
+ {if some_failed}
+ Some CI checks failed. Please review the failures below.
+
+ #### Failed Checks
+
+ {failed_checks_details}
+
+ **Common Fixes:**
+ - Check test failures in the logs
+ - Verify linting and formatting
+ - Ensure all dependencies are installed
+ - Review security scan results
+ {/if}
+
+ {if all_failed}
+ ⚠️ **All CI checks failed!**
+
+ This may indicate a significant issue. Please investigate immediately.
+
+ {if persistent_failure}
+ 🔴 **Persistent Failure Detected**
+
+ This workflow has failed {failure_count} consecutive times. An issue has been created for investigation: #{issue_number}
+ {/if}
+ {/if}
+
+ ### Detailed Results
+
+
+ Test Results
+
+ {test_results_summary}
+
+ **Failed Tests:**
+ {failed_tests_list}
+
+
+
+
+ Linting Results
+
+ {linting_results}
+
+
+
+
+ Build Logs
+
+ {build_log_excerpt}
+
+ Full logs: {workflow_run_url}
+
+
+
+ ### Performance Metrics
+
+ - **Total Duration:** {total_duration}
+ - **Fastest Job:** {fastest_job} ({fastest_duration})
+ - **Slowest Job:** {slowest_job} ({slowest_duration})
+
+ {if duration_increased}
+ ⚠️ **Performance Note:** CI duration increased by {duration_increase} compared to previous run.
+ {/if}
+
+ ### Quick Actions
+
+ {if can_rerun}
+ - 🔄 [Re-run failed jobs]({rerun_url})
+ {/if}
+ - 📊 [View detailed logs]({logs_url})
+ - 📈 [View workflow history]({history_url})
+
+ ### Comparison with Previous Run
+
+ {if has_previous_run}
+ | Metric | Current | Previous | Change |
+ |--------|---------|----------|--------|
+ | Status | {current_status} | {previous_status} | {status_change} |
+ | Duration | {current_duration} | {previous_duration} | {duration_change} |
+ | Failed Tests | {current_failed} | {previous_failed} | {test_change} |
+ {/if}
+
+ ---
+
+ *Last updated: {timestamp}*
+ *Workflow: [{workflow_name}]({workflow_run_url})*
+[/add-comment]
+```
+
+**Note:** Use `hide-older-comments: true` to automatically hide previous CI comments.
+
+### Step 4: Escalate Persistent Failures
+
+If failure persists for 3+ consecutive runs, create an issue:
+
+```markdown
+[create-issue]
+title: Persistent CI failure in {workflow_name} workflow
+body: |
+ ## 🚨 Persistent CI Failure Alert
+
+ The `{workflow_name}` workflow has failed **{failure_count} consecutive times**.
+
+ ### Failure Summary
+
+ - **Workflow:** {workflow_name}
+ - **First Failure:** {first_failure_date}
+ - **Latest Failure:** {latest_failure_date}
+ - **Affected Branch:** {branch_name}
+ - **Failure Count:** {failure_count} consecutive failures
+
+ ### Recent Failure History
+
+ | Run | Date | Duration | Conclusion |
+ |-----|------|----------|------------|
+ {failure_history_table}
+
+ ### Common Failure Pattern
+
+ {if consistent_failure_reason}
+ All failures show the same root cause:
+
+ ```
+ {error_message}
+ ```
+
+ **Likely Cause:** {likely_cause}
+ {else}
+ Failures show different error messages. This may indicate:
+ - Flaky tests
+ - Environment issues
+ - Race conditions
+ - External dependency problems
+ {/if}
+
+ ### Failed Jobs
+
+ {failed_jobs_details}
+
+ ### Failing Tests
+
+ {if has_test_failures}
+ The following tests are consistently failing:
+
+ {failing_tests_list}
+ {/if}
+
+ ### Error Analysis
+
+
+ Error Logs
+
+ {error_logs}
+
+
+
+
+ Stack Traces
+
+ {stack_traces}
+
+
+
+ ### Impact Assessment
+
+ **Severity:** {high|medium|low}
+
+ {if blocks_deployment}
+ 🔴 **BLOCKING** - This failure is preventing deployments
+ {/if}
+
+ {if blocks_merges}
+ ⚠️ **IMPACTING** - This failure may be blocking PR merges
+ {/if}
+
+ **Affected Areas:**
+ - {affected_module_1}
+ - {affected_module_2}
+
+ ### Recommended Actions
+
+ 1. **Immediate Investigation**
+ - Review error logs: {logs_url}
+ - Check for environment changes
+ - Verify external dependencies
+
+ 2. **Testing**
+ - Reproduce failure locally
+ - Run failing tests in isolation
+ - Check for race conditions
+
+ 3. **Resolution**
+ - Fix identified issues
+ - Add regression tests
+ - Update CI configuration if needed
+
+ 4. **Verification**
+ - Re-run CI pipeline
+ - Monitor next 3 runs
+ - Close issue when resolved
+
+ ### Debug Information
+
+ - **Repository:** ${{ github.repository }}
+ - **Branch:** {branch_name}
+ - **Commit SHA:** {commit_sha}
+ - **Workflow File:** `.github/workflows/{workflow_file}`
+ - **Runner OS:** {runner_os}
+ - **Node Version:** {node_version}
+
+ ### Related PRs
+
+ {if has_related_prs}
+ This failure is affecting the following PRs:
+ {list_of_affected_prs}
+ {/if}
+
+ ### Historical Context
+
+ {if has_similar_past_failures}
+ Similar failures occurred previously:
+ {list_of_similar_issues}
+ {/if}
+
+ ### Acceptance Criteria
+
+ - [ ] Root cause identified
+ - [ ] Fix implemented
+ - [ ] CI passes 3 consecutive times
+ - [ ] Regression tests added
+ - [ ] Documentation updated (if needed)
+
+ ## Metadata
+
+ - **Detection Date:** {detection_date}
+ - **Latest Workflow Run:** {workflow_run_url}
+ - **Failure Threshold:** 3 consecutive failures
+
+ ---
+
+ *Automatically created by CI Status Reporter*
+ *Related PR: #{pr_number}*
+[/create-issue]
+```
+
+## Decision Logic
+
+### When to Comment vs Create Issue
+
+```javascript
+// Pseudocode for escalation logic
+
+const recentRuns = await getRecentWorkflowRuns(10);
+const consecutiveFailures = countConsecutiveFailures(recentRuns);
+
+// Always add comment with status
+await addComment({
+ target: 'triggering',
+ body: formatCIStatus(currentRun)
+});
+
+// Escalate if persistent failure
+if (consecutiveFailures >= 3 && !hasExistingIssue()) {
+ await createIssue({
+ title: `Persistent CI failure in ${workflowName}`,
+ body: formatFailureReport(recentRuns)
+ });
+}
+
+// Close issue if now passing
+if (currentRun.conclusion === 'success' && hasExistingIssue()) {
+ await addComment({
+ target: existingIssueNumber,
+ body: '✅ CI is now passing! Closing this issue.'
+ });
+ await closeIssue(existingIssueNumber);
+}
+```
+
+### Escalation Criteria
+
+| Scenario | Add Comment | Create Issue | Close Issue |
+|----------|-------------|--------------|-------------|
+| First failure | ✅ Yes | ❌ No | - |
+| Second consecutive failure | ✅ Yes | ❌ No | - |
+| Third consecutive failure | ✅ Yes | ✅ Yes | - |
+| Success after failures | ✅ Yes | ❌ No | ✅ Yes (if exists) |
+| Flaky test (intermittent) | ✅ Yes | ⚠️ Maybe (track pattern) | - |
+
+### Comment Visibility Strategy
+
+**Hide Older Comments:**
+```yaml
+safe-outputs:
+ add-comment:
+ hide-older-comments: true # Auto-hides previous comments
+```
+
+This keeps only the latest status visible, with older comments collapsed to reduce noise.
+
+**Allowed Hide Reasons:**
+- `outdated` - Status is superseded by newer run
+- `resolved` - Issue was fixed
+- `duplicate` - Multiple comments for same run
+
+## Success Metrics
+
+- **Clean Thread:** Only latest status visible
+- **Quick Escalation:** Persistent issues identified immediately
+- **Low Noise:** Issues created only for genuine problems
+- **Fast Resolution:** Clear action items in both comments and issues
+
+## Variations
+
+### Pattern 4A: Multi-Stage Escalation
+
+```markdown
+- 1st failure → Comment with status
+- 2nd failure → Comment with warning
+- 3rd failure → Create issue
+- 5th failure → Notify team (mention @team)
+```
+
+### Pattern 4B: Performance Degradation Tracking
+
+Track CI performance over time:
+
+```markdown
+[add-comment]
+body: |
+ ⚠️ **Performance Alert**
+
+ CI duration has increased 30% over last 7 days:
+ - 7 days ago: 5m 30s
+ - Today: 7m 15s
+
+ Consider investigating slow jobs.
+```
+
+### Pattern 4C: Security Scan Results
+
+For security scans, always comment but only create issue for critical findings:
+
+```markdown
+[add-comment]
+target: triggering
+body: Security scan complete. {vulnerability_count} vulnerabilities found.
+
+[create-issue] # Only if critical vulnerabilities
+title: Critical security vulnerabilities detected
+condition: has_critical_vulnerabilities
+```
+
+## Related Patterns
+
+- [Conditional Output](./conditional-output.md) - For routing by severity
+- [Multi-Output Analysis](./multi-output-analysis.md) - For comprehensive reports
+- [Fix-or-Report](./fix-or-report.md) - For automated fixes
+
+---
+
+**Pattern Type:** Comment-First (Update-Focused)
+**Complexity:** Low-Medium
+**Use Cases:** CI status, PR reviews, progress updates, monitoring
+**Related Workflows:** `ci-coach.md`, `breaking-change-checker.md`, `auto-triage-issues.md`
diff --git a/docs/examples/safe-outputs/conditional-output.md b/docs/examples/safe-outputs/conditional-output.md
new file mode 100644
index 0000000000..bc36414af0
--- /dev/null
+++ b/docs/examples/safe-outputs/conditional-output.md
@@ -0,0 +1,335 @@
+# Conditional Output Pattern
+
+This example demonstrates how to dynamically choose output types based on analysis results, specifically for security vulnerability scanning.
+
+## Pattern Overview
+
+**Use Case:** Security scanning with severity-based output routing
+
+**Output Strategy:**
+- Critical vulnerabilities (CVSS ≥ 7.0) → Create individual issues
+- Medium/Low vulnerabilities → Include in summary discussion
+- All findings → Add comment to triggering PR/issue
+
+**Benefits:**
+- Critical items get immediate visibility and tracking
+- Non-critical items documented without overwhelming the issue tracker
+- Complete audit trail via discussion
+- PR/issue gets immediate feedback via comment
+
+## Workflow Implementation
+
+```yaml
+---
+name: Security Scanner with Conditional Outputs
+description: Scans dependencies for vulnerabilities and routes findings by severity
+on:
+ pull_request:
+ types: [opened, synchronize]
+ schedule: daily
+permissions:
+ contents: read
+ security-events: read
+ issues: write
+ pull-requests: write
+engine: copilot
+tools:
+ github:
+ toolsets: [default]
+ bash:
+ - "jq *"
+safe-outputs:
+ create-issue:
+ title-prefix: "[security-critical] "
+ labels: [security, critical, automated]
+ expires: 7d # Auto-close if vulnerability is fixed
+ max: 5 # Limit to top 5 critical issues
+ create-discussion:
+ category: "Security"
+ title-prefix: "[Security Scan] "
+ close-older-discussions: true # Keep only latest report
+ max: 1
+ add-comment:
+ target: triggering # Comment on the PR that triggered this
+ hide-older-comments: true
+ max: 1
+timeout-minutes: 20
+---
+
+# Security Scanner Agent
+
+You are a security scanning agent that analyzes dependencies for known vulnerabilities and routes findings appropriately based on severity.
+
+## Objective
+
+Scan all dependencies for known vulnerabilities and create appropriate outputs:
+- **Critical vulnerabilities** (CVSS ≥ 7.0): Create individual issues for tracking and assignment
+- **All vulnerabilities**: Create summary discussion with complete findings
+- **PR context**: Add comment with scan results and links
+
+## Scanning Process
+
+### Step 1: Scan Dependencies
+
+Run vulnerability scanning tools:
+
+```bash
+# Install dependencies if needed
+npm install
+
+# Run npm audit with JSON output
+npm audit --json > /tmp/npm-audit.json
+
+# Parse the results
+cat /tmp/npm-audit.json | jq '.'
+```
+
+### Step 2: Analyze Findings
+
+Parse the scan results and categorize by severity:
+
+```bash
+# Extract critical vulnerabilities (CVSS >= 7.0)
+cat /tmp/npm-audit.json | jq -r '
+ .vulnerabilities |
+ to_entries |
+ map(select(.value.severity == "critical" or .value.severity == "high")) |
+ .[] |
+ "\(.value.name) - \(.value.severity) - CVSS: \(.value.cvss.score)"
+'
+
+# Count vulnerabilities by severity
+cat /tmp/npm-audit.json | jq -r '
+ .metadata.vulnerabilities |
+ "Critical: \(.critical), High: \(.high), Medium: \(.moderate), Low: \(.low)"
+'
+```
+
+### Step 3: Create Outputs Based on Severity
+
+#### For Critical Vulnerabilities (CVSS ≥ 7.0)
+
+Create individual issues for tracking:
+
+```markdown
+[create-issue]
+title: Security vulnerability in {package_name}: {vulnerability_title}
+body: |
+ ## Vulnerability Details
+
+ **Package:** {package_name}
+ **Current Version:** {current_version}
+ **Fixed Version:** {fixed_version}
+ **Severity:** {severity}
+ **CVSS Score:** {cvss_score}
+
+ ## Description
+
+ {vulnerability_description}
+
+ ## Impact
+
+ {impact_details}
+
+ ## Remediation
+
+ Update {package_name} to version {fixed_version} or later:
+
+ ```bash
+ npm install {package_name}@{fixed_version}
+ ```
+
+ ## References
+
+ - CVE: {cve_id}
+ - Advisory: {advisory_url}
+ - Pull Request: #{pr_number}
+
+ ## Related Items
+
+ - Security Scan Discussion: #{discussion_number}
+[/create-issue]
+```
+
+**Note:** Create one issue per critical vulnerability (up to max of 5).
+
+#### For All Vulnerabilities
+
+Create comprehensive discussion with all findings:
+
+```markdown
+[create-discussion]
+title: Security Scan Results - {date}
+body: |
+ ## Scan Summary
+
+ Scanned {total_dependencies} dependencies and found {total_vulnerabilities} vulnerabilities.
+
+ | Severity | Count |
+ |----------|-------|
+ | Critical | {critical_count} |
+ | High | {high_count} |
+ | Medium | {moderate_count} |
+ | Low | {low_count} |
+
+ ## Critical Vulnerabilities
+
+ {critical_count} critical vulnerabilities have been opened as individual issues for tracking:
+
+ {list_of_issue_links}
+
+ ## All Findings
+
+
+ Complete Vulnerability Report
+
+ ### Critical Vulnerabilities
+
+ {detailed_critical_findings}
+
+ ### High Severity Vulnerabilities
+
+ {detailed_high_findings}
+
+ ### Medium Severity Vulnerabilities
+
+ {detailed_moderate_findings}
+
+ ### Low Severity Vulnerabilities
+
+ {detailed_low_findings}
+
+
+
+ ## Remediation Summary
+
+ Run the following commands to update vulnerable dependencies:
+
+ ```bash
+ npm install {package1}@{version1} {package2}@{version2}
+ ```
+
+ ## Next Steps
+
+ 1. Review critical issues: {issue_links}
+ 2. Address high-severity vulnerabilities
+ 3. Plan updates for medium/low severity items
+ 4. Re-run security scan after updates
+
+ ## Scan Metadata
+
+ - **Scan Date:** {scan_date}
+ - **Scanner:** npm audit
+ - **Pull Request:** #{pr_number} (if applicable)
+ - **Workflow Run:** {workflow_run_url}
+[/create-discussion]
+```
+
+#### For PR Context
+
+Add comment linking to discussion and critical issues:
+
+```markdown
+[add-comment]
+target: triggering
+body: |
+ ## 🔒 Security Scan Results
+
+ Scanned this PR for security vulnerabilities.
+
+ ### Summary
+
+ - ✅ **Critical:** {critical_count} {critical_count > 0 ? '⚠️' : ''}
+ - ℹ️ **High:** {high_count}
+ - ℹ️ **Medium:** {moderate_count}
+ - ℹ️ **Low:** {low_count}
+
+ ### Action Required
+
+ {if critical_count > 0}
+ ⚠️ **Critical vulnerabilities found!** Please review and address:
+ {list_of_critical_issue_links}
+ {endif}
+
+ ### Full Report
+
+ 📋 See complete analysis: #{discussion_number}
+
+ ### Recommendations
+
+ {if critical_count > 0}
+ 1. **Do not merge** until critical vulnerabilities are addressed
+ 2. Review individual issues for remediation steps
+ 3. Update dependencies as recommended
+ 4. Re-run CI after fixes
+ {else}
+ No critical vulnerabilities detected. Review the full report for any medium/low severity items.
+ {endif}
+[/add-comment]
+```
+
+## Key Decision Points
+
+### When to Create Issue vs Discussion
+
+| Condition | Action |
+|-----------|--------|
+| CVSS Score ≥ 7.0 | ✅ Create issue |
+| Severity = "critical" | ✅ Create issue |
+| Severity = "high" AND CVSS ≥ 7.0 | ✅ Create issue |
+| Any other finding | 📋 Include in discussion only |
+| Zero vulnerabilities | 📋 Create discussion with clean report |
+
+### When to Skip Outputs
+
+- Don't create issues if no critical vulnerabilities found
+- Don't create discussion if scan failed (create issue about scan failure instead)
+- Don't add comment if not triggered by PR/issue
+
+## Success Metrics
+
+- **Noise Reduction:** Critical issues visible, non-critical archived
+- **Response Time:** Critical vulnerabilities get immediate attention
+- **Audit Trail:** Complete history preserved in discussions
+- **Developer Experience:** PR comments provide instant feedback
+
+## Variations
+
+### Pattern 1A: Thresholds by Type
+
+```yaml
+safe-outputs:
+ create-issue:
+ max: 10 # Higher limit for specific types
+ create-discussion:
+ max: 1
+```
+
+Route by vulnerability type:
+- Remote Code Execution → Always create issue
+- Denial of Service → Create issue if CVSS ≥ 5.0
+- Information Disclosure → Discussion only
+
+### Pattern 1B: Progressive Escalation
+
+Only create issue if vulnerability persists across multiple scans:
+
+```markdown
+Track vulnerability occurrence:
+- First scan: Add to discussion
+- Second scan (7 days later): Still present → Add warning to discussion
+- Third scan (14 days later): Still present → Create issue
+```
+
+## Related Patterns
+
+- [Multi-Output Analysis](./multi-output-analysis.md) - For creating issues from discussion items
+- [Fix-or-Report](./fix-or-report.md) - For attempting automated fixes
+- [Comment Pattern](./comment-pattern.md) - For PR status updates
+
+---
+
+**Pattern Type:** Conditional Outputs
+**Complexity:** Medium
+**Use Cases:** Security scanning, code quality analysis, compliance checking
+**Related Workflows:** `static-analysis-report.md`, `secret-scanning-triage.md`
diff --git a/docs/examples/safe-outputs/fix-or-report.md b/docs/examples/safe-outputs/fix-or-report.md
new file mode 100644
index 0000000000..87c34cc28a
--- /dev/null
+++ b/docs/examples/safe-outputs/fix-or-report.md
@@ -0,0 +1,506 @@
+# Fix-or-Report Pattern
+
+This example demonstrates a progressive approach where the workflow attempts an automated fix first, and falls back to creating an issue if the fix cannot be automated.
+
+## Pattern Overview
+
+**Use Case:** Dependency updates with automated and manual fallback paths
+
+**Output Strategy:**
+- Automated fix possible → Create pull request with changes
+- Manual intervention needed → Create issue with details
+- Always → Add comment with summary and status
+
+**Benefits:**
+- Maximizes automation (fixes what can be fixed)
+- Surfaces complex cases for human review
+- Complete audit trail with PR or issue
+- Reduces manual work for routine updates
+
+## Workflow Implementation
+
+```yaml
+---
+name: Dependency Update Bot
+description: Updates dependencies automatically or creates issues for manual updates
+on:
+ schedule: weekly
+ workflow_dispatch:
+permissions:
+ contents: write
+ pull-requests: write
+ issues: write
+engine: copilot
+tools:
+ github:
+ toolsets: [default]
+ bash:
+ - "*"
+ edit:
+ enabled: true
+safe-outputs:
+ create-pull-request:
+ title-prefix: "[deps] "
+ labels: [dependencies, automated]
+ draft: false # Not draft - safe updates
+ expires: 14d
+ max: 1
+ create-issue:
+ title-prefix: "[deps-manual] "
+ labels: [dependencies, needs-review, manual-update]
+ max: 5 # Multiple dependencies may need manual updates
+ add-comment:
+ target: "*"
+ max: 3
+timeout-minutes: 30
+---
+
+# Dependency Update Bot
+
+You are an automated dependency update bot that attempts to update dependencies safely, creating PRs for successful updates and issues for those requiring manual intervention.
+
+## Objective
+
+Update project dependencies following this strategy:
+1. **Analyze** all outdated dependencies
+2. **Categorize** by update safety (patch/minor/major, breaking changes)
+3. **Attempt** automated update for safe dependencies
+4. **Create PR** if update is successful and tests pass
+5. **Create Issue** if update requires manual intervention
+6. **Comment** with summary of all actions taken
+
+## Update Process
+
+### Step 1: Check for Outdated Dependencies
+
+```bash
+# Check npm dependencies
+npm outdated --json > /tmp/npm-outdated.json
+
+# Check security vulnerabilities
+npm audit --json > /tmp/npm-audit.json
+
+# Parse results
+cat /tmp/npm-outdated.json | jq '.'
+```
+
+### Step 2: Categorize Updates by Safety
+
+```bash
+# Categorize updates
+cat /tmp/npm-outdated.json | jq '
+ to_entries |
+ map({
+ package: .key,
+ current: .value.current,
+ wanted: .value.wanted,
+ latest: .value.latest,
+ type: (
+ if (.value.current | split(".")[0]) != (.value.latest | split(".")[0])
+ then "major"
+ elif (.value.current | split(".")[1]) != (.value.latest | split(".")[1])
+ then "minor"
+ else "patch"
+ end
+ )
+ }) |
+ group_by(.type)
+' > /tmp/categorized-updates.json
+```
+
+### Step 3: Attempt Automated Update
+
+Try to update safe dependencies (patch and minor versions):
+
+```bash
+# Update patch versions (safest)
+cat /tmp/categorized-updates.json | jq -r '
+ .[] |
+ select(.[0].type == "patch") |
+ .[].package
+' | xargs -I {} npm install {}@latest
+
+# Run tests to verify updates
+npm test
+
+# Check if tests pass
+if [ $? -eq 0 ]; then
+ echo "✅ Tests passed - safe to create PR"
+ UPDATE_SUCCESSFUL=true
+else
+ echo "❌ Tests failed - requires manual review"
+ UPDATE_SUCCESSFUL=false
+fi
+```
+
+### Step 4: Decision Point - PR or Issue?
+
+#### If Update Successful → Create Pull Request
+
+```markdown
+[create-pull-request]
+title: Update dependencies ({package_count} packages)
+body: |
+ ## Dependency Updates
+
+ This PR updates {package_count} dependencies to their latest compatible versions.
+
+ ### Updated Packages
+
+ | Package | From | To | Type |
+ |---------|------|-----|------|
+ {package_update_table}
+
+ ### Safety Analysis
+
+ ✅ **All updates are patch or minor versions**
+ - No breaking changes expected
+ - All tests passing
+ - No security vulnerabilities introduced
+
+ ### Test Results
+
+ ```
+ {test_results_summary}
+ ```
+
+ All {test_count} tests passed successfully.
+
+ ### Security Impact
+
+ {if security_fixes_count > 0}
+ 🔒 This update includes {security_fixes_count} security fixes:
+ {security_fixes_list}
+ {else}
+ No security vulnerabilities in updated packages.
+ {endif}
+
+ ### Changes Made
+
+ - Updated `package.json`
+ - Updated `package-lock.json`
+ - Verified tests pass
+ - Checked for breaking changes
+
+ ### Review Checklist
+
+ - [x] Tests pass
+ - [x] No breaking changes
+ - [x] Dependencies compatible
+ - [ ] Visual/manual testing (if applicable)
+
+ ### Rollback Plan
+
+ If issues arise, rollback with:
+ ```bash
+ git revert {commit_sha}
+ npm install
+ ```
+
+ ## Metadata
+
+ - **Update Date:** {update_date}
+ - **Workflow Run:** {workflow_run_url}
+ - **Previous Versions:** See commit diff
+[/create-pull-request]
+```
+
+#### If Update Failed → Create Issue
+
+```markdown
+[create-issue]
+title: Manual dependency update required: {package_name}
+body: |
+ ## Overview
+
+ The dependency `{package_name}` has a new version available but requires manual intervention to update.
+
+ ### Update Details
+
+ - **Package:** {package_name}
+ - **Current Version:** {current_version}
+ - **Latest Version:** {latest_version}
+ - **Update Type:** {major|minor|patch}
+
+ ### Why Manual Update Required
+
+ {reason_for_manual_update}
+
+ **Common reasons:**
+ - ⚠️ Major version change (breaking changes likely)
+ - ❌ Tests fail after update
+ - 🔄 Requires code changes to accommodate new API
+ - 📚 Migration guide needed
+ - 🔗 Peer dependency conflicts
+
+ ### Test Failure Details
+
+ {if tests_failed}
+ ```
+ {test_failure_output}
+ ```
+ {endif}
+
+ ### Breaking Changes
+
+ {if breaking_changes_detected}
+ Review the changelog for breaking changes:
+ {changelog_url}
+
+ **Known breaking changes:**
+ {breaking_changes_list}
+ {endif}
+
+ ### Migration Steps
+
+ 1. **Review changelog:**
+ {changelog_url}
+
+ 2. **Update package.json:**
+ ```json
+ "{package_name}": "^{latest_version}"
+ ```
+
+ 3. **Install and test:**
+ ```bash
+ npm install
+ npm test
+ ```
+
+ 4. **Address breaking changes:**
+ - Update deprecated API usage
+ - Modify code to match new patterns
+ - Update tests if needed
+
+ 5. **Verify in development:**
+ - Run application locally
+ - Test critical paths
+ - Check for console errors/warnings
+
+ ### Impact Assessment
+
+ **Priority:** {high|medium|low}
+
+ {if has_security_vulnerability}
+ 🔴 **SECURITY FIX** - This update includes security fixes for:
+ {security_vulnerability_details}
+
+ **Recommended:** Update within {timeframe}
+ {endif}
+
+ {if no_security_issues}
+ This is a routine update with no immediate security concerns.
+ {endif}
+
+ ### Additional Context
+
+ - **Dependencies affected:** {affected_dependencies_count}
+ - **Required code changes:** {estimated_change_scope}
+ - **Estimated effort:** {estimated_hours} hours
+
+ ### Related Items
+
+ - Dependency audit: #{audit_discussion_number}
+ - Previous updates: {related_prs}
+ - Upstream issue: {upstream_issue_url}
+
+ ### Acceptance Criteria
+
+ - [ ] Package updated to {latest_version}
+ - [ ] All tests passing
+ - [ ] No breaking changes in application
+ - [ ] Code changes reviewed
+ - [ ] PR created and merged
+
+ ## Metadata
+
+ - **Detection Date:** {detection_date}
+ - **Workflow Run:** {workflow_run_url}
+ - **Automated Update Attempted:** Yes (failed)
+[/create-issue]
+```
+
+### Step 5: Add Summary Comment
+
+Always create a summary comment, regardless of PR or issue creation:
+
+```markdown
+[add-comment]
+target: {related_issue_or_pr} # Or create new discussion
+body: |
+ ## 📦 Dependency Update Summary
+
+ Analyzed {total_packages} dependencies for updates.
+
+ ### Actions Taken
+
+ {if pr_created}
+ ✅ **Pull Request Created:** #{pr_number}
+ - Updated {updated_count} packages successfully
+ - All tests passing
+ - Safe to review and merge
+ {endif}
+
+ {if issues_created}
+ ⚠️ **Manual Updates Required:** {issue_count} packages
+ {list_of_created_issues}
+ - Require code changes or review
+ - See individual issues for details
+ {endif}
+
+ {if no_updates}
+ ✅ All dependencies are up to date
+ {endif}
+
+ ### Summary Table
+
+ | Status | Count | Action |
+ |--------|-------|--------|
+ | Automated | {automated_count} | PR #{pr_number} |
+ | Manual | {manual_count} | Issues created |
+ | Up to date | {uptodate_count} | No action |
+ | Skipped | {skipped_count} | See notes |
+
+ ### Security Status
+
+ {if security_vulnerabilities_fixed}
+ 🔒 Security fixes included in PR #{pr_number}
+ {endif}
+
+ {if security_vulnerabilities_remain}
+ ⚠️ Security vulnerabilities require manual updates: {security_issues_list}
+ {endif}
+
+ ### Next Steps
+
+ {if pr_created}
+ 1. Review and approve PR #{pr_number}
+ 2. Merge after approval
+ 3. Monitor production
+ {endif}
+
+ {if issues_created}
+ 1. Review manual update issues
+ 2. Prioritize by security impact
+ 3. Address breaking changes
+ {endif}
+
+ ## Full Report
+
+ See complete dependency audit: #{audit_discussion_number}
+[/add-comment]
+```
+
+## Decision Logic
+
+### When to Create PR vs Issue
+
+```javascript
+// Pseudocode for decision logic
+
+for (const dependency of outdatedDependencies) {
+ const updateType = classifyUpdate(dependency);
+
+ if (isSafeUpdate(dependency)) {
+ // Attempt automated update
+ const updated = await updateDependency(dependency);
+ const testsPass = await runTests();
+
+ if (updated && testsPass) {
+ // Safe to automate - create PR
+ await createPullRequest({
+ title: `Update ${dependency.name}`,
+ changes: dependency.changes
+ });
+ } else {
+ // Tests failed - needs manual review
+ await createIssue({
+ title: `Manual update required: ${dependency.name}`,
+ reason: 'Tests failed after update'
+ });
+ }
+ } else {
+ // Not safe to automate - create issue
+ await createIssue({
+ title: `Manual update required: ${dependency.name}`,
+ reason: determineReason(dependency)
+ });
+ }
+}
+
+function isSafeUpdate(dependency) {
+ return (
+ dependency.updateType === 'patch' ||
+ (dependency.updateType === 'minor' && !hasBreakingChanges(dependency)) &&
+ !hasSecurityVulnerabilities(dependency, 'high')
+ );
+}
+```
+
+### Safety Criteria
+
+| Criteria | Safe for PR | Needs Issue |
+|----------|-------------|-------------|
+| Patch update (0.0.X) | ✅ Yes | - |
+| Minor update (0.X.0) | ✅ Yes (if no breaking changes) | ⚠️ If breaking changes |
+| Major update (X.0.0) | ❌ No | ✅ Yes |
+| Tests pass after update | ✅ Yes | - |
+| Tests fail after update | ❌ No | ✅ Yes |
+| Peer dependency conflicts | ❌ No | ✅ Yes |
+| Deprecated API usage | ❌ No | ✅ Yes |
+| Security vulnerability | ⚠️ If patch available | ✅ If major update needed |
+
+## Success Metrics
+
+- **Automation Rate:** % of updates handled via PR
+- **Time Savings:** Manual updates identified quickly
+- **Test Coverage:** All updates validated by tests
+- **Audit Trail:** Complete history via PR or issue
+
+## Variations
+
+### Pattern 3A: Security-First
+
+Always prioritize security fixes:
+
+```markdown
+If security vulnerability:
+ - Critical (CVSS ≥ 9.0) → Create PR immediately, notify team
+ - High (CVSS 7.0-8.9) → Create PR or issue
+ - Medium/Low → Include in regular updates
+```
+
+### Pattern 3B: Staged Rollout
+
+Create PR for staging environment first:
+
+```markdown
+1. Create PR targeting `staging` branch
+2. Deploy to staging
+3. Monitor for issues
+4. If successful, create PR for `main`
+5. If issues, create issue for investigation
+```
+
+### Pattern 3C: Dependency Groups
+
+Group related dependencies:
+
+```markdown
+- Testing dependencies → One PR
+- Build tools → One PR
+- Runtime dependencies → Individual PRs (more risk)
+```
+
+## Related Patterns
+
+- [Conditional Output](./conditional-output.md) - For routing by severity
+- [Multi-Output Analysis](./multi-output-analysis.md) - For comprehensive reports
+- [Comment Pattern](./comment-pattern.md) - For status updates
+
+---
+
+**Pattern Type:** Fix-or-Report (Progressive)
+**Complexity:** High
+**Use Cases:** Dependency updates, automated refactoring, configuration updates
+**Related Workflows:** `breaking-change-checker.md`, `ci-coach.md`
diff --git a/docs/examples/safe-outputs/multi-output-analysis.md b/docs/examples/safe-outputs/multi-output-analysis.md
new file mode 100644
index 0000000000..89c2fda080
--- /dev/null
+++ b/docs/examples/safe-outputs/multi-output-analysis.md
@@ -0,0 +1,419 @@
+# Multi-Output Analysis Pattern
+
+This example demonstrates a hierarchical output strategy where a parent discussion contains the overall analysis, with child issues for actionable sub-items.
+
+## Pattern Overview
+
+**Use Case:** Code quality analysis with actionable findings
+
+**Output Strategy:**
+- Discussion → Comprehensive analysis and trends
+- Issues → Individual actionable items from analysis
+- Comment → Summary with links to discussion and issues
+
+**Benefits:**
+- Complete view in one place (discussion)
+- Individual tracking for each finding (issues)
+- Easy assignment and closure of sub-tasks
+- Historical trend tracking via discussions
+
+## Workflow Implementation
+
+```yaml
+---
+name: Code Quality Analyzer
+description: Analyzes code quality metrics and creates actionable issues for improvements
+on:
+ schedule: weekly
+ workflow_dispatch:
+permissions:
+ contents: read
+ issues: write
+engine: copilot
+tools:
+ github:
+ toolsets: [default]
+ bash:
+ - "jq *"
+ - "grep *"
+safe-outputs:
+ create-discussion:
+ category: "Reports"
+ title-prefix: "[Code Quality] "
+ close-older-discussions: true
+ max: 1
+ create-issue:
+ title-prefix: "[quality] "
+ labels: [code-quality, automated, needs-triage]
+ max: 10 # Limit to top 10 issues
+ add-comment:
+ target: "*" # Can comment on any issue/PR
+ max: 5
+timeout-minutes: 30
+---
+
+# Code Quality Analyzer
+
+You are a code quality analyzer that identifies technical debt, code smells, and improvement opportunities.
+
+## Objective
+
+Analyze the codebase for quality issues and create:
+1. **Discussion** with complete analysis, trends, and recommendations
+2. **Issues** for each actionable finding (limit to top 10 priorities)
+3. **Comments** on related PRs/issues for context
+
+## Analysis Process
+
+### Step 1: Run Quality Analysis Tools
+
+```bash
+# Run ESLint (JavaScript/TypeScript)
+npx eslint . --format json --output-file /tmp/eslint-results.json || true
+
+# Run SonarQube Scanner (if configured)
+# sonar-scanner -Dsonar.projectKey=project -Dsonar.host.url=http://localhost:9000
+
+# Analyze complexity
+npx complexity-report --format json src/ > /tmp/complexity.json || true
+
+# Check test coverage
+npm run test:coverage -- --json > /tmp/coverage.json || true
+
+# Analyze dependencies
+npm audit --json > /tmp/audit.json || true
+npx depcheck --json > /tmp/depcheck.json || true
+```
+
+### Step 2: Categorize Findings
+
+Parse and categorize the results:
+
+```bash
+# High priority issues (complexity > 20, critical lint errors, etc.)
+cat /tmp/complexity.json | jq '[.[] | select(.complexity > 20)] | length'
+
+# Medium priority (moderate complexity, warnings, etc.)
+cat /tmp/eslint-results.json | jq '[.[] | .messages[] | select(.severity == 1)] | length'
+
+# Technical debt indicators
+cat /tmp/eslint-results.json | jq '[.[] | .messages[] | select(.message | contains("TODO") or contains("FIXME"))] | length'
+```
+
+### Step 3: Create Discussion with Complete Analysis
+
+```markdown
+[create-discussion]
+title: Code Quality Report - Week {week_number} {year}
+body: |
+ ## Executive Summary
+
+ This week's code quality analysis reveals {total_issues} findings across {categories_count} categories.
+
+ ### Key Metrics
+
+ | Metric | Current | Previous | Trend |
+ |--------|---------|----------|-------|
+ | Complexity Score | {current_complexity} | {previous_complexity} | {trend_emoji} |
+ | Test Coverage | {current_coverage}% | {previous_coverage}% | {trend_emoji} |
+ | Lint Errors | {current_errors} | {previous_errors} | {trend_emoji} |
+ | Technical Debt | {debt_hours}h | {previous_debt}h | {trend_emoji} |
+
+ ### Priority Distribution
+
+ - 🔴 **High Priority:** {high_count} findings
+ - 🟡 **Medium Priority:** {medium_count} findings
+ - 🟢 **Low Priority:** {low_count} findings
+
+ ## Actionable Issues Created
+
+ The following issues have been created for high-priority findings:
+
+ {list_of_created_issues_with_links}
+
+ ## Detailed Analysis
+
+
+ High Priority Findings
+
+ ### Complexity Hotspots
+
+ The following files have cyclomatic complexity > 20:
+
+ | File | Function | Complexity | Recommendation |
+ |------|----------|------------|----------------|
+ {complexity_hotspots_table}
+
+ ### Critical Lint Errors
+
+ {critical_lint_errors_list}
+
+ ### Test Coverage Gaps
+
+ {coverage_gaps_list}
+
+
+
+
+ Medium Priority Findings
+
+ {medium_priority_details}
+
+
+
+
+ Technical Debt Analysis
+
+ ### TODO/FIXME Comments
+
+ Found {todo_count} TODO and {fixme_count} FIXME comments:
+
+ {todo_fixme_list}
+
+ ### Deprecated API Usage
+
+ {deprecated_api_usage}
+
+ ### Unused Dependencies
+
+ {unused_dependencies_list}
+
+
+
+ ## Trends Over Time
+
+ ### Complexity Trend (Last 4 Weeks)
+
+ ```
+ Week {w1}: {complexity_w1}
+ Week {w2}: {complexity_w2}
+ Week {w3}: {complexity_w3}
+ Week {w4}: {complexity_w4}
+ ```
+
+ ### Coverage Trend (Last 4 Weeks)
+
+ ```
+ Week {w1}: {coverage_w1}%
+ Week {w2}: {coverage_w2}%
+ Week {w3}: {coverage_w3}%
+ Week {w4}: {coverage_w4}%
+ ```
+
+ ## Recommendations
+
+ 1. **Immediate Actions**
+ - Address high-priority issues: {high_priority_issues_links}
+ - Focus on complexity hotspots in critical paths
+
+ 2. **Short-term Improvements** (1-2 weeks)
+ - Increase test coverage in {low_coverage_modules}
+ - Resolve critical lint errors
+ - Clean up TODO/FIXME comments
+
+ 3. **Long-term Strategy**
+ - Establish complexity thresholds in CI
+ - Implement automated code quality gates
+ - Regular refactoring sprints
+
+ ## Comparison with Previous Report
+
+ Previous report: #{previous_discussion_number}
+
+ **Changes since last report:**
+ - Complexity: {complexity_change}
+ - Coverage: {coverage_change}
+ - Errors: {errors_change}
+
+ ## Metadata
+
+ - **Analysis Date:** {analysis_date}
+ - **Branch:** {branch}
+ - **Commit:** {commit_sha}
+ - **Tools:** ESLint, complexity-report, Jest
+ - **Workflow Run:** {workflow_run_url}
+[/create-discussion]
+```
+
+### Step 4: Create Individual Issues for High-Priority Items
+
+Create one issue per high-priority finding:
+
+```markdown
+[create-issue]
+title: Reduce complexity in {file_name}::{function_name} (complexity: {score})
+body: |
+ ## Problem
+
+ The function `{function_name}` in `{file_path}` has a cyclomatic complexity of **{complexity_score}**, which exceeds the recommended threshold of 20.
+
+ ## Current State
+
+ ```{language}
+ {code_snippet}
+ ```
+
+ **Complexity Analysis:**
+ - Cyclomatic Complexity: {complexity_score}
+ - Number of Branches: {branch_count}
+ - Lines of Code: {loc}
+
+ ## Impact
+
+ High complexity reduces:
+ - Code maintainability
+ - Test coverage effectiveness
+ - Debugging efficiency
+ - Onboarding speed for new developers
+
+ ## Recommended Actions
+
+ 1. **Extract Method:** Break down into smaller functions
+ - Extract validation logic → `validate{Object}()`
+ - Extract error handling → `handle{Error}()`
+ - Extract business logic → `process{Operation}()`
+
+ 2. **Reduce Branching:** Simplify conditional logic
+ - Use early returns to reduce nesting
+ - Consider strategy pattern for multiple conditions
+ - Use lookup tables instead of switch statements
+
+ 3. **Add Unit Tests:** Target new extracted methods
+
+ ## Definition of Done
+
+ - [ ] Complexity reduced to ≤ 15
+ - [ ] All existing tests still pass
+ - [ ] New unit tests added for extracted methods
+ - [ ] Code review completed
+
+ ## Related Items
+
+ - Code Quality Report: #{discussion_number}
+ - Similar complexity issues: {related_issues}
+
+ ## Priority
+
+ {priority_level} - This function is in the {criticality} path.
+[/create-issue]
+```
+
+**Note:** Create one issue per high-priority finding (up to max 10).
+
+### Step 5: Add Comments to Related Items
+
+If there are open PRs or issues related to the findings, add contextual comments:
+
+```markdown
+[add-comment]
+target: {related_issue_number}
+body: |
+ ## 📊 Code Quality Update
+
+ This issue was mentioned in the latest code quality analysis.
+
+ **Current Status:**
+ - Complexity: {current_complexity} (target: ≤ 15)
+ - Test Coverage: {current_coverage}% (target: ≥ 80%)
+
+ **Related Findings:**
+ - New issue created: #{new_issue_number}
+ - Full report: #{discussion_number}
+
+ **Recommendation:** {specific_recommendation}
+[/add-comment]
+```
+
+## Key Decision Points
+
+### When to Create Issue vs Include in Discussion Only
+
+| Finding | Create Issue | Discussion Only |
+|---------|--------------|-----------------|
+| Complexity > 20 | ✅ Yes | Also in discussion |
+| Critical lint errors | ✅ Yes | Also in discussion |
+| Coverage < 50% for critical modules | ✅ Yes | Also in discussion |
+| Medium complexity (15-20) | ❌ No | Discussion only |
+| Warnings (not errors) | ❌ No | Discussion only |
+| Style issues | ❌ No | Discussion only |
+
+### Prioritization Logic
+
+```javascript
+// Prioritize issues for creation (limit to top 10)
+const findings = allFindings
+ .map(f => ({
+ ...f,
+ priority: calculatePriority(f)
+ }))
+ .sort((a, b) => b.priority - a.priority)
+ .slice(0, 10); // Top 10 only
+
+function calculatePriority(finding) {
+ let score = 0;
+
+ // Complexity contribution
+ if (finding.complexity > 30) score += 10;
+ else if (finding.complexity > 20) score += 5;
+
+ // Criticality of file
+ if (finding.isCriticalPath) score += 5;
+
+ // Current issues/bugs
+ if (finding.hasActiveBugs) score += 3;
+
+ // Test coverage
+ if (finding.coverage < 50) score += 3;
+
+ return score;
+}
+```
+
+## Success Metrics
+
+- **Comprehensive View:** All findings in one discussion
+- **Actionable Tracking:** Top priorities tracked as issues
+- **Historical Context:** Week-over-week trends visible
+- **Developer Efficiency:** Clear prioritization and recommendations
+
+## Variations
+
+### Pattern 2A: Category-Based Issues
+
+Create issues grouped by category:
+
+```yaml
+safe-outputs:
+ create-issue:
+ max: 5 # One per category
+```
+
+Categories:
+- Complexity hotspots issue
+- Test coverage gaps issue
+- Lint errors issue
+- Technical debt issue
+- Dependency issues issue
+
+### Pattern 2B: Team-Based Routing
+
+Create issues assigned to specific teams:
+
+```markdown
+[create-issue]
+title: [Frontend Team] Reduce complexity in UI components
+assignees: @frontend-team
+```
+
+## Related Patterns
+
+- [Conditional Output](./conditional-output.md) - For severity-based routing
+- [Fix-or-Report](./fix-or-report.md) - For automated fixes
+- [Comment Pattern](./comment-pattern.md) - For update notifications
+
+---
+
+**Pattern Type:** Hierarchical Outputs (Parent-Child)
+**Complexity:** Medium-High
+**Use Cases:** Code quality analysis, audit reports, multi-item findings
+**Related Workflows:** `static-analysis-report.md`, `glossary-maintainer.md`
diff --git a/docs/safe-outputs-guide.md b/docs/safe-outputs-guide.md
new file mode 100644
index 0000000000..7ff583141b
--- /dev/null
+++ b/docs/safe-outputs-guide.md
@@ -0,0 +1,518 @@
+# Safe Output Patterns and Best Practices
+
+This guide helps you choose the right safe output type and design effective multi-output workflows for GitHub Agentic Workflows.
+
+## Quick Reference
+
+**Safe Output Types**:
+- `create-issue` - Action required, task tracking, assignment
+- `create-discussion` - Analysis, reports, community conversation
+- `create-pull-request` - Automated fixes, code changes
+- `add-comment` - Updates to existing items, progress reports
+- `update-issue` - Modify existing issue content
+
+## When to Use Each Output Type
+
+### Create Issue (`create-issue`)
+
+**Use when:**
+- ✅ Action is required (task tracking)
+- ✅ Assignment to developer/agent needed
+- ✅ Status tracking required (open/closed)
+- ✅ Needs labels, milestones, or project boards
+- ✅ Workflow needs to create sub-tasks
+- ✅ Time-sensitive action items need visibility
+
+**Examples:**
+- Security vulnerability found in dependencies
+- Test failures requiring fixes
+- Code quality issues needing remediation
+- Breaking changes detected in PR
+- Expired certificates or credentials
+- Resource limits exceeded
+
+**Typical Configuration:**
+```yaml
+safe-outputs:
+ create-issue:
+ title-prefix: "[automated] "
+ labels: [automation, needs-triage]
+ assignees: copilot
+ expires: 7d # Auto-close if condition resolves
+ max: 5 # Limit number of issues per run
+```
+
+**Best Practices:**
+- Use `expires` for transient issues (security scans, CI failures)
+- Add descriptive labels for filtering and triage
+- Include clear action items in issue body
+- Link to source discussion or PR for context
+
+### Create Discussion (`create-discussion`)
+
+**Use when:**
+- ✅ Sharing analysis, reports, or insights
+- ✅ No specific action required
+- ✅ Community conversation welcome
+- ✅ Long-term reference material needed
+- ✅ Regular status reports or summaries
+- ✅ Archive-worthy findings
+
+**Examples:**
+- Performance analysis reports
+- Security scan summaries
+- Trend analysis over time
+- Weekly/monthly statistics
+- Code quality metrics dashboard
+- Audit logs and compliance reports
+
+**Typical Configuration:**
+```yaml
+safe-outputs:
+ create-discussion:
+ category: "Reports" # or "Audits", "Security", etc.
+ title-prefix: "[Report] "
+ close-older-discussions: true # Keep only latest
+ max: 1 # One discussion per run
+```
+
+**Best Practices:**
+- Use `close-older-discussions: true` for time-sensitive reports
+- Choose appropriate category (Reports, Audits, Security)
+- Structure content with clear sections (Summary, Details, Action Items)
+- Link to related issues for actionable items
+- Include date/timestamp in title for historical tracking
+
+### Create Pull Request (`create-pull-request`)
+
+**Use when:**
+- ✅ Automated fix can be proposed
+- ✅ Code changes are ready to review
+- ✅ Changes are non-breaking and safe
+- ✅ Tests can validate the changes
+- ✅ Human review is needed before merge
+
+**Examples:**
+- Dependency updates
+- Code formatting fixes
+- Documentation updates
+- Configuration file corrections
+- License header updates
+- Automated refactoring
+
+**Typical Configuration:**
+```yaml
+safe-outputs:
+ create-pull-request:
+ title-prefix: "[auto-fix] "
+ labels: [automation, safe-to-merge]
+ draft: true # Create as draft PR (default)
+ expires: 14d # Auto-close stale PRs
+ if-no-changes: warn # warn, error, or ignore
+```
+
+**Best Practices:**
+- Create as draft PR by default (safer)
+- Include detailed description of changes and motivation
+- Link to triggering issue or discussion
+- Add tests or validation steps in PR description
+- Use `expires` to prevent stale PR accumulation
+
+### Add Comment (`add-comment`)
+
+**Use when:**
+- ✅ Updating existing issue/PR/discussion
+- ✅ Providing progress updates
+- ✅ Responding to triggers
+- ✅ Summarizing results of analysis
+- ✅ Linking related items
+
+**Examples:**
+- CI results on PR
+- Approval status updates
+- Analysis updates on issues
+- Progress reports on long-running tasks
+- Links to created issues/discussions/PRs
+
+**Typical Configuration:**
+```yaml
+safe-outputs:
+ add-comment:
+ target: triggering # or specific number, or "*" for all
+ hide-older-comments: true # Hide previous comments
+ max: 1 # Limit comments per run
+```
+
+**Best Practices:**
+- Use `target: triggering` to comment on source item
+- Use `hide-older-comments: true` to reduce noise
+- Keep comments concise and actionable
+- Link to detailed discussion/issue for full analysis
+- Include status indicators (✅, ⚠️, ❌) for quick scanning
+
+### Update Issue (`update-issue`)
+
+**Use when:**
+- ✅ Need to modify existing issue content
+- ✅ Updating status or assignees
+- ✅ Adding/removing labels
+- ✅ Changing milestones or project board
+
+**Examples:**
+- Updating issue body with analysis results
+- Changing assignees based on triage
+- Adding labels after classification
+- Updating issue title for clarity
+
+**Typical Configuration:**
+```yaml
+safe-outputs:
+ update-issue:
+ max: 10 # Limit updates per run
+```
+
+**Best Practices:**
+- Preserve original issue content when possible
+- Add comments explaining what changed and why
+- Use sparingly - prefer comments for updates
+- Ensure idempotency (safe to run multiple times)
+
+## Multi-Output Workflow Patterns
+
+74.8% of agentic workflows use multiple safe output types. Here are proven patterns:
+
+### Pattern 1: Conditional Outputs (Decision-Based)
+
+**When to use:** Output type depends on analysis results.
+
+**Example - Security Scanning:**
+```yaml
+safe-outputs:
+ create-issue:
+ title-prefix: "[security] "
+ labels: [security, critical]
+ max: 5
+ create-discussion:
+ category: "Security"
+ title-prefix: "[Security Scan] "
+ max: 1
+```
+
+**Logic:**
+- Critical findings (CVSS ≥ 7.0) → Create issue per vulnerability
+- Low/medium findings → Create discussion with summary
+- Always → Add comment to PR with scan results
+
+**Benefits:**
+- Critical items get immediate visibility
+- Non-critical items archived for reference
+- Reduces noise from low-severity findings
+
+See [conditional-output.md](./examples/safe-outputs/conditional-output.md) for complete example.
+
+### Pattern 2: Hierarchical Outputs (Parent-Child)
+
+**When to use:** Create summary with detailed sub-items.
+
+**Example - Code Quality Analysis:**
+```yaml
+safe-outputs:
+ create-discussion:
+ category: "Reports"
+ title-prefix: "[Code Quality] "
+ max: 1
+ create-issue:
+ title-prefix: "[quality] "
+ labels: [code-quality, automated]
+ max: 10
+ add-comment:
+ target: triggering
+ max: 1
+```
+
+**Logic:**
+- Create discussion with overall analysis
+- Create issues for each actionable finding
+- Add comment linking to discussion and issues
+
+**Benefits:**
+- Comprehensive view in discussion
+- Individual tracking per issue
+- Easy to assign and close items independently
+
+See [multi-output-analysis.md](./examples/safe-outputs/multi-output-analysis.md) for complete example.
+
+### Pattern 3: Fix-or-Report (Progressive)
+
+**When to use:** Attempt automated fix, report if unable.
+
+**Example - Dependency Updates:**
+```yaml
+safe-outputs:
+ create-pull-request:
+ title-prefix: "[deps] "
+ labels: [dependencies]
+ max: 1
+ create-issue:
+ title-prefix: "[deps-failed] "
+ labels: [dependencies, needs-review]
+ max: 1
+ add-comment:
+ target: triggering
+ max: 1
+```
+
+**Logic:**
+- If update is safe → Create PR with changes
+- If conflicts/issues → Create issue for manual review
+- Always → Add comment with summary and links
+
+**Benefits:**
+- Automates safe updates
+- Surfaces problematic updates for human review
+- Provides complete audit trail
+
+See [fix-or-report.md](./examples/safe-outputs/fix-or-report.md) for complete example.
+
+### Pattern 4: Comment-First (Update-Focused)
+
+**When to use:** Primarily updating existing items.
+
+**Example - CI Status Reporter:**
+```yaml
+safe-outputs:
+ add-comment:
+ target: triggering
+ hide-older-comments: true
+ max: 1
+ create-issue:
+ title-prefix: "[ci-failure] "
+ labels: [ci, bug]
+ max: 1 # Only if persistent failure
+```
+
+**Logic:**
+- Always → Add comment with CI results
+- If persistent failure (3+ runs) → Create issue
+- Hide older comments to reduce clutter
+
+**Benefits:**
+- Keeps all status in one place
+- Escalates only persistent problems
+- Clean comment history
+
+See [comment-pattern.md](./examples/safe-outputs/comment-pattern.md) for complete example.
+
+## Best Practices
+
+### Output Hygiene
+
+**Avoid Duplication:**
+```yaml
+# ❌ BAD - Creates both issue and discussion for same finding
+safe-outputs:
+ create-issue:
+ max: 10
+ create-discussion:
+ max: 1
+# Agent creates issue and discussion for each vulnerability
+```
+
+```yaml
+# ✅ GOOD - Conditional based on severity
+safe-outputs:
+ create-issue:
+ max: 5 # Only critical
+ create-discussion:
+ max: 1 # Summary of all
+# Agent creates issues only for critical, discussion for summary
+```
+
+**Cleanup Transient Items:**
+```yaml
+# ✅ Use expires for time-sensitive items
+safe-outputs:
+ create-issue:
+ expires: 7d # Auto-close when no longer relevant
+ create-discussion:
+ close-older-discussions: true # Keep only latest report
+```
+
+**Limit Output Volume:**
+```yaml
+# ✅ Set reasonable max values
+safe-outputs:
+ create-issue:
+ max: 5 # Don't overwhelm with 100 issues
+ add-comment:
+ max: 1 # One summary comment, not per-item
+```
+
+### User Experience
+
+**Consistent Output Types:**
+- Security workflows → Issues (critical) + Discussion (summary)
+- Performance reports → Discussion (always)
+- Automated fixes → Pull Request (primary)
+- Status updates → Comment (always)
+
+**Clear Titles and Prefixes:**
+```yaml
+# ✅ GOOD - Clear, scannable titles
+safe-outputs:
+ create-issue:
+ title-prefix: "[security-critical] "
+ create-discussion:
+ title-prefix: "[Security Scan] "
+```
+
+**Standard Body Structure:**
+```markdown
+## Summary
+Brief overview of findings
+
+## Details
+
+Detailed Analysis
+Full technical details
+
+
+## Action Items
+- [ ] Task 1
+- [ ] Task 2
+
+## Related Items
+- Discussion: #123
+- Issue: #456
+```
+
+**Attribution and Context:**
+- Always include workflow run link (automatic)
+- Link to triggering item when relevant
+- Reference related outputs (issue → discussion)
+
+### Error Handling
+
+**Always Produce Output:**
+```yaml
+# Even on workflow failure, create output
+safe-outputs:
+ create-discussion: # Fallback for errors
+ category: "Reports"
+ max: 1
+```
+
+**Don't Create Issues for Workflow Failures:**
+```yaml
+# ❌ BAD - Creates noise
+safe-outputs:
+ create-issue:
+ title-prefix: "[workflow-error] "
+# Don't create issues when the workflow itself fails
+
+# ✅ GOOD - Use discussion for workflow issues
+safe-outputs:
+ create-discussion:
+ category: "Audits"
+ title-prefix: "[Workflow Status] "
+```
+
+**Include Debug Information:**
+- Workflow run URL (automatic)
+- Relevant environment variables
+- Error messages and stack traces
+- Steps to reproduce
+
+### Security Considerations
+
+**Sanitize Sensitive Data:**
+```yaml
+# ⚠️ Be careful with safe outputs containing:
+# - API keys or tokens
+# - Private repository paths
+# - Internal system details
+# - PII or confidential information
+```
+
+**Use Appropriate Visibility:**
+- Public repos → All outputs are public
+- Private repos → Outputs inherit repo visibility
+- Cross-repo → Ensure target repo permissions are correct
+
+**Validate Input:**
+- Sanitize user-provided content
+- Validate issue/PR numbers before referencing
+- Check permissions before creating cross-repo outputs
+
+## Decision Tree
+
+Use this flowchart to choose the right output type:
+
+```
+Start: What is the goal of the output?
+
+├─ Is action required?
+│ ├─ Yes: Does it need assignment/tracking?
+│ │ ├─ Yes → create-issue
+│ │ └─ No: Can it be automated?
+│ │ ├─ Yes → create-pull-request
+│ │ └─ No → create-issue
+│ └─ No: Is it updating existing item?
+│ ├─ Yes → add-comment
+│ └─ No: Is it a report/analysis?
+│ ├─ Yes → create-discussion
+│ └─ No → create-discussion or add-comment
+```
+
+**Quick Decision Table:**
+
+| Scenario | Primary Output | Secondary Output | Notes |
+|----------|---------------|------------------|-------|
+| Critical vulnerability | `create-issue` | `add-comment` | Issue for tracking, comment for context |
+| Security scan summary | `create-discussion` | `create-issue` (critical only) | Discussion for all, issues for urgent |
+| Dependency update | `create-pull-request` | `create-issue` (if fails) | PR first, issue as fallback |
+| CI results | `add-comment` | `create-issue` (persistent failure) | Comment for status, escalate failures |
+| Performance report | `create-discussion` | - | Discussion only, no action needed |
+| Code quality fix | `create-pull-request` | `add-comment` | PR for fix, comment for summary |
+| Triage results | `add-comment` + `add-labels` | `create-discussion` (summary) | Comment per issue, discussion for batch |
+
+## Examples
+
+Complete example workflows demonstrating these patterns:
+
+- [Conditional Output](./examples/safe-outputs/conditional-output.md) - Dynamic output type selection based on severity
+- [Multi-Output Analysis](./examples/safe-outputs/multi-output-analysis.md) - Discussion with sub-issues pattern
+- [Fix-or-Report](./examples/safe-outputs/fix-or-report.md) - Attempt PR, fallback to issue
+- [Comment Pattern](./examples/safe-outputs/comment-pattern.md) - Status updates with escalation
+
+## Related Documentation
+
+- [Safe Outputs System Specification](../scratchpad/safe-outputs-specification.md) - Formal specification
+- [Safe Output Messages](../scratchpad/safe-output-messages.md) - Message templates and formatting
+- [Safe Output Environment Variables](../scratchpad/safe-output-environment-variables.md) - Configuration reference
+- [Safe Output Patterns (Technical)](../scratchpad/safe-outputs-patterns.md) - Implementation details
+
+## Statistics
+
+Based on analysis of 147 agentic workflows (as of 2026-01):
+
+| Output Type | Usage | Percentage |
+|-------------|-------|------------|
+| `create-issue` | 113 workflows | 76.9% |
+| `create-discussion` | 108 workflows | 73.5% |
+| `create-pull-request` | 54 workflows | 36.7% |
+| `add-comment` | 34 workflows | 23.1% |
+| `update-issue` | 4 workflows | 2.7% |
+
+**Multi-Output Workflows:** 110 workflows (74.8%) use 2+ output types
+
+**Key Insights:**
+- Most workflows combine issues and discussions (comprehensive reporting)
+- PRs are less common but critical for automation
+- Comments are typically used in conjunction with other outputs
+- Update operations are rare (prefer comments for updates)
+
+---
+
+**Last Updated:** 2026-01-31
+**Related Issues:** [#12407](https://github.com/githubnext/gh-aw/issues/12407)
diff --git a/scratchpad/README.md b/scratchpad/README.md
index e8c1ac18b5..c924e0d68a 100644
--- a/scratchpad/README.md
+++ b/scratchpad/README.md
@@ -17,6 +17,7 @@ This directory contains design specifications and implementation documentation f
| Document | Status | Implementation |
|----------|--------|----------------|
| [Safe Outputs System Specification](./safe-outputs-specification.md) | ✅ Documented | W3C-style formal specification for safe outputs architecture, security, and operations |
+| [Safe Output Patterns and Best Practices](./safe-outputs-patterns.md) | ✅ Documented | Technical deep-dive on safe output patterns, multi-output coordination, and advanced patterns |
| [Capitalization Guidelines](./capitalization.md) | ✅ Documented | `cmd/gh-aw/capitalization_test.go` |
| [Safe Output Messages Design System](./safe-output-messages.md) | ✅ Implemented | `pkg/workflow/safe_outputs.go` |
| [Safe Output Environment Variables Reference](./safe-output-environment-variables.md) | ✅ Documented | Environment variable requirements for safe output jobs |
diff --git a/scratchpad/safe-outputs-patterns.md b/scratchpad/safe-outputs-patterns.md
new file mode 100644
index 0000000000..6da42d6e08
--- /dev/null
+++ b/scratchpad/safe-outputs-patterns.md
@@ -0,0 +1,787 @@
+# Safe Output Patterns - Technical Deep Dive
+
+This document provides implementation details, architecture notes, and advanced patterns for safe outputs in GitHub Agentic Workflows.
+
+## Table of Contents
+
+1. [Architecture Overview](#architecture-overview)
+2. [Output Type Implementation Details](#output-type-implementation-details)
+3. [Multi-Output Coordination](#multi-output-coordination)
+4. [Advanced Patterns](#advanced-patterns)
+5. [Performance Considerations](#performance-considerations)
+6. [Error Handling Strategies](#error-handling-strategies)
+7. [Security Implications](#security-implications)
+8. [Testing Strategies](#testing-strategies)
+
+## Architecture Overview
+
+### Safe Output Pipeline
+
+```
+┌─────────────────┐
+│ AI Agent │
+│ Output │
+└────────┬────────┘
+ │
+ ▼
+┌─────────────────┐
+│ Parser │ Extract [create-issue], [add-comment], etc.
+└────────┬────────┘
+ │
+ ▼
+┌─────────────────┐
+│ Validator │ Check permissions, limits, formats
+└────────┬────────┘
+ │
+ ▼
+┌─────────────────┐
+│ Orchestrator │ Sequence jobs, manage dependencies
+└────────┬────────┘
+ │
+ ▼
+┌─────────────────┐
+│ Job Generator │ Create GitHub Actions jobs
+└────────┬────────┘
+ │
+ ▼
+┌─────────────────┐
+│ GitHub API │ Execute operations
+└─────────────────┘
+```
+
+### Job Dependency Graph
+
+Multi-output workflows create job dependencies:
+
+```yaml
+jobs:
+ agent:
+ # Main agent execution
+
+ create-issue:
+ needs: [agent]
+ # Creates issues from agent output
+
+ create-discussion:
+ needs: [agent]
+ # Creates discussion from agent output
+
+ add-comment:
+ needs: [agent, create-issue, create-discussion]
+ # Can reference created items via environment variables
+```
+
+**Key Dependencies:**
+- `add-comment` typically depends on other output jobs (to reference created items)
+- `create-pull-request` runs independently (doesn't need issue/discussion numbers)
+- `update-issue` can run independently or after `create-issue`
+
+## Output Type Implementation Details
+
+### Create Issue
+
+**Implementation:** `pkg/workflow/safe_outputs.go` → `CreateIssueJob()`
+
+**Key Features:**
+- Temporary ID support for cross-referencing
+- Label validation against repository labels
+- Assignee validation (user or `copilot` special value)
+- Expiration via `expires` field
+
+**Temporary ID Pattern:**
+```markdown
+[create-issue id="vuln-1"]
+title: Critical vulnerability
+body: See details below
+[/create-issue]
+
+[create-issue]
+title: Mitigation for {vuln-1}
+body: This addresses issue #{vuln-1}
+[/create-issue]
+```
+
+**Environment Variables:**
+```bash
+GH_AW_ISSUE_TITLE_PREFIX="[ai] "
+GH_AW_ISSUE_LABELS="bug,security"
+GH_AW_ISSUE_ALLOWED_LABELS="bug,security,enhancement"
+GH_AW_ISSUE_EXPIRES="7"
+GH_AW_ASSIGN_COPILOT="true"
+GH_AW_TEMPORARY_ID_MAP='{"vuln-1": "123", "vuln-2": "124"}'
+```
+
+**Processing Logic:**
+1. Parse issue blocks from agent output
+2. Validate title, body, labels, assignees
+3. Create issue via GitHub API
+4. Track temporary ID → real issue number mapping
+5. Export mapping for downstream jobs
+
+### Create Discussion
+
+**Implementation:** `pkg/workflow/safe_outputs.go` → `CreateDiscussionJob()`
+
+**Key Features:**
+- Category resolution (name, slug, or ID)
+- Auto-close older discussions
+- GraphQL API usage (required for discussions)
+
+**Category Resolution:**
+```javascript
+// Supports multiple formats:
+category: "general" // Slug
+category: "General" // Name
+category: "DIC_kwDOABCD123" // GraphQL node ID
+```
+
+**Close Older Discussions:**
+```yaml
+safe-outputs:
+ create-discussion:
+ close-older-discussions: true
+```
+
+Automatically closes discussions from the same workflow to keep only the latest.
+
+**GraphQL Query Pattern:**
+```graphql
+mutation CreateDiscussion {
+ createDiscussion(input: {
+ repositoryId: $repoId,
+ categoryId: $categoryId,
+ title: $title,
+ body: $body
+ }) {
+ discussion {
+ id
+ number
+ url
+ }
+ }
+}
+```
+
+### Create Pull Request
+
+**Implementation:** `pkg/workflow/safe_outputs.go` → `CreatePullRequestJob()`
+
+**Key Features:**
+- File change tracking
+- Patch size limits
+- Draft PR support
+- Cross-repo support
+
+**File Change Processing:**
+```markdown
+[create-pull-request]
+title: Update dependencies
+body: Updates npm packages
+
+---file:package.json---
+{
+ "dependencies": {
+ "react": "^18.0.0"
+ }
+}
+---end-file---
+
+---file:package-lock.json---
+{...}
+---end-file---
+[/create-pull-request]
+```
+
+**Patch Size Validation:**
+```yaml
+safe-outputs:
+ create-pull-request:
+ max-patch-size: 1024 # KB (default)
+```
+
+Large patches are rejected to prevent overwhelming reviews.
+
+**Branch Naming:**
+```bash
+# Pattern: {workflow_id}/{job_name}/{timestamp}
+gh-aw/agent/20260131-120000
+```
+
+### Add Comment
+
+**Implementation:** `pkg/workflow/safe_outputs.go` → `AddCommentJob()`
+
+**Key Features:**
+- Target resolution (triggering, specific number, or wildcard)
+- Hide older comments
+- Reference created items
+
+**Target Resolution:**
+```yaml
+target: triggering # Comment on PR/issue that triggered workflow
+target: 123 # Comment on specific issue/PR #123
+target: "*" # Comment on all related items
+```
+
+**Environment Variable Injection:**
+```bash
+GH_AW_CREATED_ISSUE_NUMBER="123"
+GH_AW_CREATED_DISCUSSION_NUMBER="456"
+GH_AW_CREATED_PULL_REQUEST_NUMBER="789"
+```
+
+Available in comment body for cross-referencing:
+```markdown
+[add-comment]
+body: |
+ Created issue #${{ env.GH_AW_CREATED_ISSUE_NUMBER }}
+ See discussion #${{ env.GH_AW_CREATED_DISCUSSION_NUMBER }}
+[/add-comment]
+```
+
+### Update Issue
+
+**Implementation:** `pkg/workflow/safe_outputs.go` → `UpdateIssueJob()`
+
+**Key Features:**
+- Selective field updates
+- Preserve original content option
+- Label/assignee modification
+
+**Update Patterns:**
+```markdown
+[update-issue number="123"]
+title: Updated title
+labels: [add:bug, remove:needs-triage]
+assignees: [add:@user1, remove:@user2]
+state: closed
+[/update-issue]
+```
+
+**Partial Updates:**
+- Only specified fields are updated
+- Unspecified fields remain unchanged
+- Use `append` for body to add content without replacing
+
+## Multi-Output Coordination
+
+### Job Dependencies
+
+**Pattern 1: Sequential (Comment after Issue)**
+
+```yaml
+jobs:
+ agent:
+ ...
+
+ create-issue:
+ needs: [agent]
+ ...
+
+ add-comment:
+ needs: [agent, create-issue] # Wait for issue creation
+ env:
+ GH_AW_CREATED_ISSUE_NUMBER: ${{ needs.create-issue.outputs.issue_number }}
+```
+
+**Pattern 2: Parallel (Independent Outputs)**
+
+```yaml
+jobs:
+ agent:
+ ...
+
+ create-issue:
+ needs: [agent] # Independent
+ ...
+
+ create-discussion:
+ needs: [agent] # Independent
+ ...
+
+ # Both run in parallel
+```
+
+**Pattern 3: Fan-out, Fan-in**
+
+```yaml
+jobs:
+ agent:
+ ...
+
+ create-issue-1:
+ needs: [agent]
+
+ create-issue-2:
+ needs: [agent]
+
+ create-issue-3:
+ needs: [agent]
+
+ add-comment:
+ needs: [agent, create-issue-1, create-issue-2, create-issue-3]
+ # Waits for all issues, then comments with summary
+```
+
+### Cross-Referencing Patterns
+
+**Pattern A: Issue → Discussion Link**
+
+```markdown
+# In create-issue
+[create-issue]
+body: |
+ See full analysis in discussion #{discussion_number}
+[/create-issue]
+
+# Requires: create-discussion job runs first
+```
+
+**Pattern B: Temporary IDs**
+
+```markdown
+[create-issue id="main-issue"]
+title: Main issue
+[/create-issue]
+
+[create-issue]
+title: Sub-task
+body: Related to #{main-issue}
+[/create-issue]
+
+# System resolves {main-issue} to actual issue number
+```
+
+**Pattern C: Environment Variables**
+
+```markdown
+[add-comment]
+body: |
+ Actions taken:
+ - Issue: #${{ env.GH_AW_CREATED_ISSUE_NUMBER }}
+ - Discussion: #${{ env.GH_AW_CREATED_DISCUSSION_NUMBER }}
+[/add-comment]
+```
+
+## Advanced Patterns
+
+### Pattern: Conditional Output Generation
+
+**Technique:** Use agent logic to decide which outputs to create
+
+```markdown
+# In agent step
+if (criticalVulnerabilities.length > 0) {
+ // Create issues for critical items
+ criticalVulnerabilities.forEach(vuln => {
+ output += `[create-issue]
+title: ${vuln.title}
+body: ${vuln.description}
+[/create-issue]\n`;
+ });
+}
+
+// Always create discussion
+output += `[create-discussion]
+title: Security Scan Summary
+body: ${summary}
+[/create-discussion]\n`;
+```
+
+**Benefits:**
+- Dynamic output based on analysis
+- Avoid creating empty issues
+- Conditional escalation
+
+### Pattern: Idempotent Operations
+
+**Technique:** Check for existing items before creating
+
+```markdown
+# In agent step
+const existingIssues = await github.rest.issues.listForRepo({
+ owner,
+ repo,
+ labels: ['automated', 'security'],
+ state: 'open'
+});
+
+const hasOpenSecurityIssue = existingIssues.data.some(
+ issue => issue.title.includes(vulnerabilityName)
+);
+
+if (!hasOpenSecurityIssue) {
+ // Create new issue
+ output += `[create-issue]...`;
+} else {
+ // Update existing via comment
+ output += `[add-comment target="${existingIssues.data[0].number}"]...`;
+}
+```
+
+**Benefits:**
+- Prevents duplicate issues
+- Updates existing items instead
+- Cleaner issue tracker
+
+### Pattern: Batch Operations with Limits
+
+**Technique:** Create top-N issues, summarize rest in discussion
+
+```markdown
+# Prioritize and limit
+const topIssues = findings
+ .sort((a, b) => b.priority - a.priority)
+ .slice(0, 5); // Max 5 issues
+
+topIssues.forEach(finding => {
+ output += `[create-issue]
+title: ${finding.title}
+body: ${finding.body}
+[/create-issue]\n`;
+});
+
+// Remaining findings in discussion
+const remainingFindings = findings.slice(5);
+output += `[create-discussion]
+title: Complete Analysis
+body: |
+ Top issues created: ${topIssues.length}
+
+ Additional findings: ${remainingFindings.length}
+ ${remainingFindings.map(f => `- ${f.title}`).join('\n')}
+[/create-discussion]\n`;
+```
+
+**Benefits:**
+- Respects `max` limits
+- Complete information preserved
+- Reduces noise
+
+### Pattern: Progressive Escalation
+
+**Technique:** Track issue persistence across runs
+
+```markdown
+# In agent step (using cache or discussion for persistence)
+const previousFindings = await loadPreviousFindings();
+const currentFindings = await analyzeCurrent();
+
+currentFindings.forEach(finding => {
+ const occurrences = countOccurrences(finding, previousFindings);
+
+ if (occurrences >= 3) {
+ // Third occurrence → create issue
+ output += `[create-issue]
+title: Persistent issue: ${finding.title}
+body: This issue has persisted for ${occurrences} scans.
+[/create-issue]\n`;
+ } else {
+ // Add to discussion only
+ discussionBody += `- ${finding.title} (occurrence ${occurrences})\n`;
+ }
+});
+```
+
+**Benefits:**
+- Reduces false positives
+- Escalates only persistent issues
+- Historical tracking
+
+## Performance Considerations
+
+### API Rate Limiting
+
+**GitHub API Limits:**
+- Authenticated: 5,000 requests/hour
+- Unauthenticated: 60 requests/hour
+
+**Safe Output Consumption:**
+- create-issue: 1 request per issue
+- create-discussion: 1 GraphQL mutation
+- add-comment: 1 request per comment
+- create-pull-request: ~3-5 requests (create branch, commit, open PR)
+
+**Optimization Strategies:**
+
+1. **Batch Operations:** Create multiple issues in parallel
+2. **Limit Max Values:** Use reasonable `max` limits (5-10, not 100)
+3. **Conditional Creation:** Only create outputs when necessary
+4. **Cache Results:** Use `tools: cache-memory: true` to persist data
+
+### Job Execution Time
+
+**Typical Durations:**
+- create-issue: 5-10 seconds per issue
+- create-discussion: 10-15 seconds
+- create-pull-request: 30-60 seconds (includes file changes)
+- add-comment: 5-10 seconds per comment
+
+**Optimization:**
+- Run independent jobs in parallel
+- Use job dependencies strategically
+- Set appropriate `timeout-minutes`
+
+### Large Payloads
+
+**Limits:**
+- Issue/PR body: 65,536 characters
+- Discussion body: 65,536 characters
+- Comment body: 65,536 characters
+- PR patch size: Configurable (default 1024 KB)
+
+**Strategies for Large Content:**
+- Use collapsible `` sections
+- Link to external artifacts (logs, reports)
+- Paginate findings across multiple issues
+- Use GitHub Gist for very large content
+
+## Error Handling Strategies
+
+### Validation Errors
+
+**Common Issues:**
+- Invalid label (not in repository)
+- Invalid assignee (user doesn't exist)
+- Invalid category (discussion)
+- Malformed markdown
+
+**Handling:**
+```yaml
+# Strict mode: Fail workflow on validation error
+strict: true
+
+# Permissive mode: Log warning, continue
+strict: false
+```
+
+### API Errors
+
+**Common Issues:**
+- Rate limit exceeded
+- Insufficient permissions
+- Network timeout
+- Repository not found
+
+**Handling:**
+```javascript
+try {
+ await createIssue(...);
+} catch (error) {
+ if (error.status === 403) {
+ // Permission denied - log and skip
+ console.warn('Permission denied for issue creation');
+ } else if (error.status === 429) {
+ // Rate limit - wait and retry
+ await sleep(60000);
+ await createIssue(...);
+ } else {
+ throw error; // Fail workflow for unexpected errors
+ }
+}
+```
+
+### Partial Failures
+
+**Scenario:** Some outputs succeed, others fail
+
+**Strategy 1: Best Effort**
+```markdown
+- Created 3 of 5 issues
+- Failed to create discussion (permission denied)
+- Created summary comment
+```
+
+**Strategy 2: All-or-Nothing**
+```markdown
+- Validate all outputs first
+- Create all or none
+- Rollback on any failure
+```
+
+**Recommendation:** Use best-effort for production, all-or-nothing for critical workflows
+
+### Recovery Patterns
+
+**Pattern A: Fallback Output**
+```markdown
+Try:
+ create-pull-request
+Catch:
+ create-issue (with patch attached)
+```
+
+**Pattern B: Error Issue**
+```markdown
+Try:
+ analyze and create outputs
+Catch:
+ create-issue with error details
+```
+
+## Security Implications
+
+### Sanitization
+
+**Always sanitize:**
+- User-provided content in titles/bodies
+- File paths in PR changes
+- URLs and external links
+- Shell commands in code blocks
+
+**Implementation:**
+```javascript
+function sanitize(content) {
+ return content
+ .replace(/[<>]/g, '') // Remove HTML
+ .replace(/`{3}[\s\S]*?`{3}/g, match => {
+ // Preserve code blocks but sanitize content
+ return match.replace(/\$/g, '\\$');
+ });
+}
+```
+
+### Permission Validation
+
+**Required Permissions:**
+```yaml
+permissions:
+ issues: write # For create-issue, update-issue
+ pull-requests: write # For create-pull-request, add-comment
+ contents: write # For create-pull-request (file changes)
+```
+
+**Validation:**
+- Check permissions before job generation
+- Fail early with clear error message
+- Document required permissions in workflow
+
+### Secrets Handling
+
+**Never include in outputs:**
+- API keys
+- Passwords
+- Private repository paths
+- Internal system details
+- PII
+
+**Detection:**
+```javascript
+const SECRET_PATTERNS = [
+ /api[_-]?key[_-]?=?['\"]?([a-zA-Z0-9]{32,})/i,
+ /password[_-]?=?['\"]?([a-zA-Z0-9]{8,})/i,
+ /token[_-]?=?['\"]?([a-zA-Z0-9]{32,})/i
+];
+
+function containsSecrets(text) {
+ return SECRET_PATTERNS.some(pattern => pattern.test(text));
+}
+```
+
+### Cross-Repository Safety
+
+**Risks:**
+- Creating issues/PRs in unintended repositories
+- Leaking internal information to public repos
+- Unauthorized access attempts
+
+**Mitigations:**
+```yaml
+safe-outputs:
+ create-issue:
+ repository: owner/specific-repo # Explicit target
+ create-pull-request:
+ repository: owner/specific-repo
+ # Never use ${github.event.repository.name} from untrusted sources
+```
+
+## Testing Strategies
+
+### Unit Testing
+
+**Test Safe Output Parser:**
+```go
+func TestParseSafeOutputs(t *testing.T) {
+ input := `[create-issue]
+title: Test Issue
+body: Test Body
+[/create-issue]`
+
+ outputs := ParseSafeOutputs(input)
+ assert.Equal(t, 1, len(outputs))
+ assert.Equal(t, "create-issue", outputs[0].Type)
+ assert.Equal(t, "Test Issue", outputs[0].Title)
+}
+```
+
+**Test Job Generation:**
+```go
+func TestCreateIssueJob(t *testing.T) {
+ config := &SafeOutputConfig{
+ CreateIssue: &CreateIssueConfig{
+ TitlePrefix: "[test] ",
+ Max: 5,
+ },
+ }
+
+ job := CreateIssueJob(config)
+ assert.NotNil(t, job)
+ assert.Contains(t, job.Env["GH_AW_ISSUE_TITLE_PREFIX"], "[test] ")
+}
+```
+
+### Integration Testing
+
+**Test Workflow Compilation:**
+```bash
+# Compile workflow with safe outputs
+./gh-aw compile test-workflow.md
+
+# Verify generated jobs
+cat .github/workflows/test-workflow.lock.yml | yq '.jobs | keys'
+# Expected: agent, create-issue, create-discussion, add-comment
+```
+
+**Test Safe Output Execution:**
+```bash
+# Run workflow in staged mode (preview)
+gh workflow run test-workflow.yml -f staged=true
+
+# Verify outputs in step summary (not actual GitHub items)
+```
+
+### End-to-End Testing
+
+**Pattern:**
+1. Create test repository
+2. Run workflow with safe outputs
+3. Verify created issues/PRs/discussions
+4. Clean up test items
+
+```bash
+# Create test issue
+gh issue create --title "Test Issue" --body "Test"
+
+# Run workflow
+gh workflow run test-workflow.yml
+
+# Wait for completion
+gh run watch
+
+# Verify outputs
+gh issue list --label "automated"
+gh pr list --label "automated"
+```
+
+## Related Documentation
+
+- [Safe Outputs System Specification](./safe-outputs-specification.md)
+- [Safe Output Messages](./safe-output-messages.md)
+- [Safe Output Environment Variables](./safe-output-environment-variables.md)
+- [Safe Outputs Guide (User-Facing)](../docs/safe-outputs-guide.md)
+
+---
+
+**Last Updated:** 2026-01-31
+**Target Audience:** Advanced users, contributors, workflow developers
+**Related Issues:** [#12407](https://github.com/githubnext/gh-aw/issues/12407)
From e992bfe44d7e00a00388714cbd1b2f9fac840dba Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Sat, 31 Jan 2026 20:14:07 +0000
Subject: [PATCH 4/4] Add README for safe output examples directory
Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com>
---
docs/examples/safe-outputs/README.md | 74 ++++++++++++++++++++++++++++
1 file changed, 74 insertions(+)
create mode 100644 docs/examples/safe-outputs/README.md
diff --git a/docs/examples/safe-outputs/README.md b/docs/examples/safe-outputs/README.md
new file mode 100644
index 0000000000..6d54c822b9
--- /dev/null
+++ b/docs/examples/safe-outputs/README.md
@@ -0,0 +1,74 @@
+# Safe Output Examples
+
+This directory contains example workflows demonstrating safe output patterns and best practices for GitHub Agentic Workflows.
+
+## Examples
+
+### [Conditional Output Pattern](./conditional-output.md)
+Dynamic output type selection based on analysis results, specifically for security vulnerability scanning.
+
+**Pattern:** Route findings by severity
+- Critical vulnerabilities → Individual issues
+- Medium/low vulnerabilities → Summary discussion
+- All findings → Comment on PR
+
+**Use Cases:** Security scanning, code quality analysis, compliance checking
+
+### [Multi-Output Analysis Pattern](./multi-output-analysis.md)
+Hierarchical output strategy where a parent discussion contains the overall analysis, with child issues for actionable sub-items.
+
+**Pattern:** Parent summary + child tasks
+- Discussion → Comprehensive analysis
+- Issues → Individual actionable items
+- Comment → Links between items
+
+**Use Cases:** Code quality reports, audit findings, multi-item analysis
+
+### [Fix-or-Report Pattern](./fix-or-report.md)
+Progressive approach where the workflow attempts an automated fix first, and falls back to creating an issue if the fix cannot be automated.
+
+**Pattern:** Attempt automation, fallback to manual
+- Automated fix possible → Pull request
+- Manual intervention needed → Issue
+- Always → Summary comment
+
+**Use Cases:** Dependency updates, automated refactoring, configuration fixes
+
+### [Comment Pattern](./comment-pattern.md)
+Comment-first approach for status updates with escalation to issues only when necessary.
+
+**Pattern:** Update-focused with escalation
+- Always → Add comment with status
+- Persistent failure (3+ runs) → Create issue
+- Hide older comments → Clean thread
+
+**Use Cases:** CI status reporting, progress updates, monitoring
+
+## Common Patterns
+
+All examples demonstrate:
+- ✅ Clear decision logic for output type selection
+- ✅ Proper use of `max` limits
+- ✅ Cross-referencing between outputs
+- ✅ Appropriate use of expiration and cleanup
+- ✅ Comprehensive documentation in outputs
+
+## Pattern Selection
+
+| Goal | Pattern | Example |
+|------|---------|---------|
+| Route by severity/priority | Conditional Output | Security scan results |
+| Parent summary + sub-tasks | Multi-Output Analysis | Code quality report |
+| Try automated fix first | Fix-or-Report | Dependency updates |
+| Status updates + escalation | Comment Pattern | CI status reporting |
+
+## Related Documentation
+
+- **[Safe Outputs Guide](../safe-outputs-guide.md)** - Complete decision tree and best practices
+- **[Technical Deep-Dive](../../scratchpad/safe-outputs-patterns.md)** - Implementation details
+- **[System Specification](../../scratchpad/safe-outputs-specification.md)** - Formal specification
+
+---
+
+**Last Updated:** 2026-01-31
+**Related Issues:** [#12407](https://github.com/githubnext/gh-aw/issues/12407)