Skip to content

[copilot-token-optimizer] Workflow Skill Extractor β€” token optimization (5 recommendations)Β #26667

Closed

Description

@github-actions

πŸ” Optimization Target: Workflow Skill Extractor

Selected because: 4th highest token consumer in the 7-day period; not recently optimized; growing rapidly (92% more tokens run-over-run as the repo scales)
Analysis period: 2026-04-09 β†’ 2026-04-16 (weekly schedule)
Runs analyzed: 2 runs (1 audited in detail: Β§24507930245)


πŸ“Š Token Usage Profile

Metric Value
Total tokens (7d, 2 runs) 6,767,770
Latest run tokens 4,439,001
Prior run tokens (Apr 9) 2,328,769
Run-over-run growth +92% (repo growing)
Total turns (latest run) 60
Avg turns/run 60
Input tokens 4,407,537
Output tokens 31,464
Cache read tokens 4,279,605 (97% of input)
Effective tokens 4,961,354
Cache efficiency 49.3%
Duration 14.7 minutes
Engine claude-sonnet-4.6

Estimated cost per run (claude-sonnet-4.6 pricing): ~$2.14

  • Fresh input: 127,932 tokens Γ— $3/M = ~$0.38
  • Cache reads: 4,279,605 Γ— $0.30/M = ~$1.28
  • Output: 31,464 Γ— $15/M = ~$0.47

πŸ”§ Recommendations

1. Remove unused GitHub MCP toolset β€” Est. savings: ~300–500K tokens/run

The tools: github: toolsets: [default] configuration was included but made zero tool calls in the only observed run. All analysis is performed via local shell commands on repository files already checked out on the runner.

The GitHub MCP default toolset exposes ~30+ tools, each with name, description, and a JSON schema. These tool definitions are transmitted to the model in every API request (as part of the system context). Removing them reduces per-turn overhead and removes schema noise that the model must reason around.

Evidence: Gateway log confirms 0 github→tools/call events across all 60 turns. The github_api_calls: 4 in the run summary come from the Actions runner itself (git checkout, etc.), not from the agent.

Action: Remove github: from the tools: block in workflow-skill-extractor.md:

# BEFORE
tools:
  bash:
    - "find .github/workflows -name '*.md'"
    ...
  edit:
  github:
    toolsets: [default]

# AFTER
tools:
  bash:
    - "find .github/workflows -name '*.md'"
    ...

2. Remove edit tool (workflow is read-only) β€” Est. savings: ~80–150K tokens/run

The behavior fingerprint confirms actuation_style: read_only and write_actions: 0. The edit: tool was configured but never used. The workflow explicitly says: "Analyze, don't modify: This workflow only creates recommendations; it doesn't change existing workflows."

The write tool is registered in the shell allowlist (--allow-tool write) but was never invoked. Removing edit: eliminates its schema from the tool context.

Action: Remove edit: from the tools: block.


3. Add pre-agent bash step to build a workflow index β€” Est. savings: ~1.5–2.5M tokens/run

The agentic assessment explicitly flags this: "~50% of turns appear to be data-gathering that could move to deterministic steps."

The agent spent a large fraction of its 60 turns discovering and reading 191 workflow files using repeated cat, head, grep, and find shell calls. This data is entirely deterministic β€” the file structure doesn't change between turns.

A pre-agent bash step can collect the key metadata from all workflow files (frontmatter: tools, imports, engine, permissions, safe-outputs) into a compact JSON file in ~5 seconds. The agent then reads one JSON file instead of issuing 30+ file-reading shell calls.

Action: Add a steps: pre-agent step:

steps:
  - name: Build workflow index
    run: |
      python3 - << 'EOF'
      import os, re, json
      
      wf_dir = ".github/workflows"
      index = []
      for fn in sorted(os.listdir(wf_dir)):
          if not fn.endswith(".md") or fn.startswith("."):
              continue
          path = os.path.join(wf_dir, fn)
          with open(path) as f:
              content = f.read()
          # Extract frontmatter
          fm_match = re.search(r'^---\n(.*?)\n---', content, re.DOTALL)
          frontmatter = fm_match.group(1) if fm_match else ""
          index.append({
              "file": fn,
              "path": path,
              "frontmatter_preview": frontmatter[:400],
              "imports": re.findall(r"^\s+- (shared/\S+)", frontmatter, re.MULTILINE),
              "engine": re.search(r"^\s*id:\s*(\S+)", frontmatter, re.MULTILINE) and re.search(r"^\s*id:\s*(\S+)", frontmatter, re.MULTILINE).group(1),
              "has_github_tools": "github:" in frontmatter,
              "has_safe_outputs": "safe-outputs:" in frontmatter,
          })
      os.makedirs("/tmp/gh-aw/agent", exist_ok=True)
      with open("/tmp/gh-aw/agent/workflow-index.json", "w") as f:
          json.dump(index, f, indent=2)
      print(f"Indexed {len(index)} workflows")
      EOF

Then update the prompt to start from: "A workflow index is available at /tmp/gh-aw/agent/workflow-index.json. Read it first, then deep-dive into specific files."

This moves ~25 discovery turns to a deterministic pre-step, potentially reducing 60 turns to ~25–35.


4. Allow python3 for bulk analysis β€” Est. savings: ~400–700K tokens/run

The agent attempted to write a Python analysis script 3+ times but was blocked each time with "Permission denied and could not request permission from user". Each failed attempt wastes turns on retrying or switching to inferior shell-based approaches.

Python's ability to process all 191 files in a single call (vs one cat/head per file) would reduce the file-sampling phase from ~20 shell turns to 2–3 Python turns. Combined with Recommendation 3, this makes the agent dramatically more efficient.

Evidence: agent-stdio.log shows repeated Python script write/run attempts: wf_dir = '.github/workflows' appearing 3Γ— with blocked execution.

Action: Add python3 to the bash allowlist and optionally add a cat > /tmp/gh-aw/agent/analyze.py write permission:

tools:
  bash:
    - "find .github/workflows -name '*.md'"
    - "grep -r '*' .github/workflows"
    - "cat *"
    - "ls *"
    - "wc *"
    - "python3 *"    # ADD THIS
    - "cat > /tmp/gh-aw/agent/*.py"  # allow writing analysis scripts

5. Trim the verbose prompt β€” Est. savings: ~300–500K tokens/run

The workflow prompt is 450 lines in the source file (587 lines with the shared/reporting.md import). The prompt contains:

  • Detailed 8-step analysis methodology with extensive sub-bullets
  • Full Markdown issue and discussion template examples (200+ lines of templates)
  • Repeated instructions for what to look for in each step
  • Example bash commands the agent should use (these are already self-evident)

With 60 turns, every prompt token is multiplied by the conversation accumulation effect. A 30% prompt reduction (~180 lines removed) could save ~300K tokens/run.

Specific cuts:

  • Steps 1–4 methodology instructions: condense from ~200 lines to ~80 lines with a focus on goals, not how-to
  • Remove bash example code blocks from the prompt body (the agent knows how to run cat and grep)
  • The issue/discussion templates (Steps 7–8): Replace with brief structural descriptions β€” the agent fills in content, not copy-paste templates
  • Merge Step 7 (create issues) and Step 8 (create discussion) into a single instruction block

⚠️ Caveats

  • These recommendations are based on 2 runs over 7 days (weekly schedule). With only 1 detailed audit run, edge cases may exist where github MCP tools ARE used (e.g., if the workflow is extended to cross-reference GitHub issues). Verify before removing.
  • The token growth trend (+92% run-over-run) suggests the workflow will become increasingly expensive as the repository scales. Recommendation 3 (pre-agent index) is the highest-priority fix as it directly addresses the scaling issue.
  • Cache efficiency at 49.3% is moderate. The high cache hit rate (97% of input tokens are cache reads) suggests the system prompt is stable β€” this is good. Recommendations 1 and 2 (removing unused tools) may temporarily lower cache efficiency by changing the tool schema (invalidating cached prefixes), but will reduce total token volume.
Tool Usage Matrix
Tool Configured? Used (runs) Avg calls/run Recommendation
shell(find ...) βœ… 1/1 ~5 Keep
shell(grep ...) βœ… 1/1 ~15 Keep
shell(cat *) βœ… 1/1 ~25 Keep
shell(head) βœ… 1/1 ~8 Keep
shell(ls *) βœ… 1/1 ~3 Keep
shell(wc *) βœ… 1/1 ~2 Keep
shell(sort) βœ… 1/1 ~3 Keep
shell(uniq) βœ… 1/1 ~3 Keep
shell(yq) βœ… 0/1 0 Consider removing
shell(echo) βœ… 1/1 ~2 Keep (small overhead)
shell(date) βœ… 0/1 0 Consider removing
shell(tail) βœ… 0/1 0 Consider removing
shell(pwd) βœ… 0/1 0 Consider removing
edit βœ… 0/1 0 Remove
github (default) βœ… 0/1 0 Remove
safeoutputs βœ… 4/1 4 Keep
python3 ❌ β€” β€” Add (blocked 3Γ—)
Audited Run Detail
Run Date Tokens Turns Conclusion Notes
Β§24507930245 2026-04-16 4,439,001 60 βœ… success Analyzed 191 workflows, created 3 issues + 1 discussion
(Apr 9 run β€” no detailed log) 2026-04-09 2,328,769 ~50 est. unknown From snapshot only

Key behavioral observations (Apr 16 run):

  • Agent correctly identified 191 workflows and 73 shared components
  • Produced 3 high-quality refactoring issues + 1 comprehensive discussion
  • Made 4 safeoutputs calls (3 create_issue + 1 create_discussion)
  • 97% of input tokens were cache reads (excellent cache utilization)
  • Agent attempted Python scripting 3Γ— but was blocked each time β†’ fell back to shell
  • 0 GitHub MCP tool calls despite github: toolsets: [default] being configured
  • agentic_fraction: 0.50 β€” half the work is automatable data-gathering

References:

Generated by Copilot Token Usage Optimizer Β· ● 2.5M Β· β—·

  • expires on Apr 23, 2026, 3:28 PM UTC

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions