Skip to content

[agentic-token-optimizer] [Token Optimizer] Dead Code Removal Agent — reduce 57-turn runs by consolidating bash calls and adding sub-agent discovery #34982

@github-actions

Description

@github-actions

Target Workflow

Dead Code Removal Agent (dead-code-remover.md) — highest token workflow in the 7-day window not optimized in the last 14 days. Previous optimization was 2026-04-21 (35 days ago).

Analysis Period

Period: 2026-05-20 – 2026-05-26 (7-day window) | Runs analyzed: 1 run in window; 10 historical runs confirmed via Actions API (9 success, 1 failure on 2026-05-22)

Token Profile

Metric Value
Total tokens (7-day window) 4,030,505
Avg tokens/run 4,030,505
Total cost $0 (Copilot engine)
Avg turns/run 57
Duration 15.5 min
Effective tokens 66,312,769
Cache amplification ratio ~16.4×
Avg time between turns 16.6s
GitHub API calls 4

The 16.4× cache ratio indicates a large, growing context window. At 57 turns, each subsequent turn carries cumulative tool output history — the primary cost driver.


Ranked Recommendations

1. Consolidate Per-Function Safety Checks into One Bash Block per Function

Estimated savings: ~500,000 tokens/run (~12%)

Phase 4 currently specifies 2–4 separate bash calls per function (caller grep, WASM check, console_wasm check, constant check). For a full 5-function batch, this creates up to 20 sequential bash turns. Each turn adds output to the context window.

Action: Rewrite Phase 4 to consolidate all checks for a given function into a single bash block:

func="FuncName"
echo "=== Caller check ==="
grep -rn -m 5 "$func" --include="*.go" .
echo "=== WASM check ==="
grep -n "$func" cmd/gh-aw-wasm/main.go || true
echo "=== console_wasm check ==="
grep -n "$func" pkg/console/console_wasm.go || true

This reduces Phase 4 from ~15 turns to ~5 turns (one per function), saving ~10 turns × ~70k tokens = ~700k effective tokens, billing savings of ~500k tokens.

Evidence: The workflow has no existing batched safety-check pattern. Phase 4 has 4 numbered subsections with separate code blocks, which the agent will execute sequentially.


2. Chain Verification Commands in Phase 6

Estimated savings: ~210,000 tokens/run (~5%)

Phase 6 currently shows go build, go vet, go vet -tags=integration, make fmt, and go test as five separate code blocks. The Copilot engine executes each as a distinct turn.

Action: Replace the five separate blocks with a single chained invocation:

go build ./... && \ngo vet ./... && \ngo vet -tags=integration ./... && \nmake fmt && \ngo test ./pkg/... 2>&1 | tail -20
echo "Exit: $?"

Saves ~3 turns × ~70k tokens = ~210k tokens/run.

Evidence: Phase 6 has 5 separate fenced code blocks, none of which chain the commands with &&.


3. Move PR Body Template Out of Prompt (Use Reference Instead)

Estimated savings: ~140,000 tokens/run (~3%)

Phase 8 embeds a ~500-token PR body markdown template directly in the prompt. This template is carried in the context window for all 57 turns (~500 × 57 = 28,500 tokens just in re-reading cost per cache turn, amplified by the 16.4× cache ratio).

Action: Replace the inline template with a compressed single-line format reference:

PR title: `chore: remove dead functions — N functions removed`
PR body: Use a table of removed functions (Function | File), list removed test functions or "None", and 4 verification checkboxes (go build, go vet, go vet -tags=integration, make fmt). Include run URL at the bottom.

This reduces prompt size by ~400 tokens. At 57 turns × 16.4× cache amplification factor, this yields ~140k effective token reduction.

Evidence: Phase 8 contains 32 lines of inline template, including verbatim markdown syntax that need not be in the active context window.


4. Add Explicit Turn-Count Checkpoint After Phase 3

Estimated savings: ~200,000 tokens/run (guard rail for overruns)

The prompt's Token Budget section says "≤30 turns" but the observed run used 57 turns — nearly double. The early-exit condition (if deadcode finds 0 unprocessed functions, call noop) is correct, but there is no mid-run circuit breaker.

Action: Add to the Token Budget Guidelines section:

Turn circuit breaker: After completing Phase 5 (deletions), if the turn count exceeds 35, skip go test in Phase 6 (run only go build ./... && go vet ./...) and proceed directly to Phase 7.

The test run in Phase 6 (go test ./pkg/...) can be expensive in time and output. The build+vet gate is sufficient for correctness; tests are covered by CI. This prevents the 57-turn pattern from recurring.

Evidence: Observed run used 57 turns against a stated target of 30. The most likely overage source is the verbose test output and iterative safety checks.


Structural Optimization: Inline Sub-Agent for Discovery

Candidate: Phase 1+2 — Deadcode Discovery + Cache Deduplication

Dimension Score Rationale
Independence 3/3 Requires no prior outputs; runs first
Small-model adequacy 3/3 Runs one shell command, reads one file, emits structured JSON
Parallelism 2/2 Could complete as a pre-step before main agent starts
Size 2/2 Non-trivial: needs Go toolchain + cache file access
Total 10/10 Strong candidate

Task: Run deadcode ./cmd/... ./internal/tools/..., read /tmp/gh-aw/cache-memory/dead-code-processed.jsonl, cross-reference to exclude already-processed functions, and emit the top-5 unprocessed candidates as a JSON array.

Why a smaller model fits: The work is purely extractive — run a command, read a file, filter a list, emit structured data. No strategic reasoning or code understanding required.

Proposed invocation change (replace the current Phase 1 and Phase 2 prose with):

## agent: discover-candidates
model: small
task: |
  Run: deadcode ./cmd/... ./internal/tools/...
  Read: /tmp/gh-aw/cache-memory/dead-code-processed.jsonl (if present)
  Exclude functions whose "file:FuncName" key appears in the cache.
  Always skip: containsInNonCommentLines, indexInNonCommentLines, extractJobSection
  Output: JSON array of up to 5 unprocessed candidates:
  [{"function":"Name","file":"pkg/...","reason":"no callers"}]
  If 0 candidates remain, output: {"skip":true}

The main agent receives the structured output and begins at Phase 3. This removes ~8 discovery turns from the main agent's context, saving ~350k tokens/run.

Combined structural savings estimate: ~350,000 tokens/run (~9%)


Summary Table

# Recommendation Savings/run Effort
1 Consolidate per-function safety check calls ~500k tokens Low
2 Chain verification commands in Phase 6 ~210k tokens Low
3 Remove inline PR body template ~140k tokens Low
4 Add turn-count circuit breaker ~200k guard Low
S1 Discovery sub-agent (Phase 1+2) ~350k tokens Medium
Total ~1,400k tokens/run (~35%)

Conservative target (excluding sub-agent): ~850k tokens/run saved (~21%).

Caveats

  • Only 1 run is present in the 7-day audit window; turn/token analysis is based on a single observation.
  • The 57-turn run was a success with code changes; a noop run would have significantly fewer turns.
  • The sub-agent recommendation requires the ## agent: feature to be enabled for this workflow.
  • Circuit breaker (Rec. 4) skips go test before PR creation; CI will catch test failures.

References: §26457286118

Generated by Agentic Workflow Token Usage Optimizer · sonnet46 2.4M ·

Add this agentic workflows to your repo

To install this agentic workflow, run

gh aw add githubnext/agentic-ops/workflows/agentic-token-optimizer.md@e10687ae8f19a5b37b061db524be27948568c411
  • expires on Jun 2, 2026, 4:27 PM UTC

Metadata

Metadata

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions