1
+# PRD: Cost Estimation and Optimization for Token-Based Copilot Billing
2
+
3
+**Author:** Leela (Lead/Architect)
4
+**Date:** 2026-05-19
5
+**Status:** Draft
6
+**Relates to:** docs/PRD.md, .squad/decisions.md (CI Architecture Decision)
7
+
8
+---
9
+
10
+## Executive Summary
11
+
12
+SquadScope runs automated AI analysis weekly using GitHub Copilot CLI and GitHub Models API inside GitHub Actions. With GitHub Copilot's shift to token-based consumption billing (AI Credits at $0.01/credit), every pipeline run has a measurable cost. This PRD quantifies per-run and annual costs, projects context growth over 6–12 months, and defines optimization strategies and budget controls to keep SquadScope economically sustainable as a zero-revenue open-source project.
13
+
14
+**Key finding:** A weekly analysis run costs approximately **$0.27–$0.35** in AI credits. The annual projection table totals **$15.96/year** at current configuration. Accounting for context growth (5–10% over 12 months), occasional fallback runs (~$0.20 each), and variance in weekly token counts, the realistic annual range is **$16–$20/year** — comparable to a cheap newsletter service, and orders of magnitude cheaper than a human analyst.
15
+
16
+---
17
+
18
+## Problem Statement
19
+
20
+### Why Cost Matters for Automated Copilot Usage
21
+
22
+1. **Predictability:** Unlike interactive Copilot chat (included in subscription), automated CI invocations consume tokens that count against plan allowances and incur overage charges.
23
+2. **Context growth:** SquadScope's wisdom, skills, and history accumulate over time, making each run progressively more expensive unless managed.
24
+3. **Budget transparency:** As a personal open-source project, jmservera needs clear visibility into the marginal cost of each published page.
25
+4. **Plan selection:** Understanding token consumption informs whether Copilot Pro ($10/month, 300 credits included) or Copilot Pro+ ($39/month, 1500 credits) is the right tier.
26
+5. **Graceful degradation:** If token budgets are exhausted, the pipeline must degrade gracefully (use cheaper models, skip optional enrichment) rather than fail silently.
27
+
28
+---
29
+
30
+## Token Pricing Model Summary
31
+
32
+*(Source: [GitHub Copilot Models and Pricing](https://docs.github.com/en/copilot/reference/copilot-billing/models-and-pricing), fetched 2026-05-19)*
33
+
34
+### Core Concepts
35
+
36
+- **1 AI Credit = $0.01 USD**
37
+- Tokens are consumed for: input (prompt + context), cached input (reused context), and output (generated text)
38
+- Plans include monthly credit allowances; overage billed at per-token rates
39
+- Code completions remain unlimited on paid plans (not relevant to SquadScope CI)
40
+
41
+### Relevant Model Pricing (per 1M tokens)
42
+
43
+| Model | Category | Input | Cached Input | Output | Cache Write |
44
+|-------|----------|-------|--------------|--------|-------------|
45
+| **Claude Sonnet 4** (primary) | Versatile | $3.00 | $0.30 | $15.00 | $3.75 |
46
+| **GPT-4.1** (fallback) | Versatile | $2.00 | $0.50 | $8.00 | — |
47
+| GPT-5 mini | Lightweight | $0.25 | $0.025 | $2.00 | — |
48
+| Claude Haiku 4.5 | Versatile | $1.00 | $0.10 | $5.00 | $1.25 |
49
+| Gemini 3 Flash | Lightweight | $0.50 | $0.05 | $3.00 | — |
50
+
51
+### Plan Allowances
52
+
53
+| Plan | Monthly Credits | Equivalent $ | Notes |
54
+|------|----------------|--------------|-------|
55
+| Copilot Free | ~13.33 | $0.13 | Very limited |
56
+| Copilot Pro | 300 | $3.00 | Likely sufficient for SquadScope alone |
57
+| Copilot Pro+ | 1500 | $15.00 | Generous headroom |
58
+| Copilot Business | 200/user pooled | $2.00/user | Org billing |
59
+
60
+---
61
+
62
+## Cost Breakdown per Pipeline Stage
63
+
64
+### Tokenization Assumptions
65
+
66
+- Average ~4 characters per token (English text/markdown)
67
+- JSON is less efficient: ~3.5 characters per token due to structural characters
68
+- 1 KB of prose ≈ 250 tokens; 1 KB of JSON ≈ 285 tokens
69
+
70
+### Stage 1: Weekly Analysis (Copilot CLI — Claude Sonnet 4)
71
+
72
+| Component | Size | Estimated Tokens |
73
+|-----------|------|-----------------|
74
+| Analyze prompt template | 6.5 KB | ~1,625 |
75
+| Raw weekly JSON (`data/raw/2026-W21.json`) | 301 KB | ~86,000 |
76
+| Wisdom file (`.squad/identity/wisdom.md`) | 3.2 KB | ~800 |
77
+| Skills directory (currently empty) | 0 KB | 0 |
78
+| Previous week summary | ~5 KB | ~1,250 |
79
+| System/tool overhead (Copilot CLI framing) | ~2 KB | ~500 |
80
+| **Total input tokens** | **~318 KB** | **~90,175** |
81
+
82
+| Output Component | Size | Estimated Tokens |
83
+|------------------|------|-----------------|
84
+| Analyzed summary markdown | ~5 KB | ~1,250 |
85
+| Tool calls/internal reasoning overhead | ~3 KB | ~750 |
86
+| **Total output tokens** | **~8 KB** | **~2,000** |
87
+
88
+**Weekly analysis cost (Claude Sonnet 4):**
89
+
90
+```
91
+Input: 90,175 tokens × $3.00/1M = $0.2705
92
+Output: 2,000 tokens × $15.00/1M = $0.0300
93
+─────────────────────────────────────────────
94
+Total per weekly run: ≈ $0.30
95
+```
96
+
97
+**In AI Credits: ~30 credits per weekly run.**
98
+
99
+### Stage 2: Reskill (Every 5th Week — GitHub Models API — GPT-4.1)
100
+
101
+The reskill run is larger because it reads 5 weeks of history plus snapshot data.
102
+
103
+| Component | Size | Estimated Tokens |
104
+|-----------|------|-----------------|
105
+| Reskill prompt template | 2.9 KB | ~725 |
106
+| Last 5 analyzed summaries (5 × ~5 KB) | ~25 KB | ~6,250 |
107
+| Wisdom file | 3.2 KB | ~800 |
108
+| Skills directory (growing) | ~2 KB (month 6) | ~500 |
109
+| Star snapshot context (5 weeks) | ~15 KB | ~4,285 |
110
+| Quality trend report | ~2 KB | ~500 |
111
+| **Total input tokens** | **~50 KB** | **~13,060** |
112
+
113
+| Output Component | Size | Estimated Tokens |
114
+|------------------|------|-----------------|
115
+| Reskill report | ~4 KB | ~1,000 |
116
+| Wisdom updates | ~1 KB | ~250 |
117
+| **Total output tokens** | **~5 KB** | **~1,250** |
118
+
119
+**Reskill cost (GPT-4.1 via GitHub Models):**
120
+
121
+```
122
+Input: 13,060 tokens × $2.00/1M = $0.0261
123
+Output: 1,250 tokens × $8.00/1M = $0.0100
124
+─────────────────────────────────────────────
125
+Total per reskill run: ≈ $0.036
126
+```
127
+
128
+**In AI Credits: ~4 credits per reskill run.**
129
+
130
+### Stage 3: Fallback Analysis (GitHub Models API — GPT-4.1)
131
+
132
+When Copilot CLI fails and the fallback triggers:
133
+
134
+```
135
+Input: 90,175 tokens × $2.00/1M = $0.1804
136
+Output: 2,000 tokens × $8.00/1M = $0.0160
137
+─────────────────────────────────────────────
138
+Total per fallback run: ≈ $0.20
139
+```
140
+
141
+**Fallback is ~33% cheaper than primary** due to GPT-4.1's lower rates vs Claude Sonnet 4.
142
+
143
+### Stage 4: GitHub Actions Compute
144
+
145
+| Job | Runner | Duration (est.) | Cost |
146
+|-----|--------|-----------------|------|
147
+| Crawl | ubuntu-latest | ~3 min | Free (public repo) |
148
+| Analyze | ubuntu-latest | ~2 min | Free (public repo) |
149
+| Generate | ubuntu-latest | ~1 min | Free (public repo) |
150
+| Deploy | ubuntu-latest | ~2 min | Free (public repo) |
151
+| Reskill | ubuntu-latest | ~2 min | Free (public repo) |
152
+
153
+**GitHub Actions is free for public repositories.** If the repo becomes private, estimate ~10 minutes/run × $0.008/min = $0.08/run.
154
+
155
+---
156
+
157
+## Context Growth Projections
158
+
159
+### Growth Vectors
160
+
161
+| Component | Current Size | Growth Rate | 6-Month Projection | 12-Month Projection |
162
+|-----------|-------------|-------------|--------------------|--------------------|
163
+| Wisdom.md | 3.2 KB | +0.5 KB per reskill (~every 5 weeks) | 5.8 KB | 8.4 KB |
164
+| Skills directory | 0 KB | +1 KB per reskill (new skill files) | 5.2 KB | 10.4 KB |
165
+| Raw JSON (per file) | 301 KB | Stable (weekly crawl scope fixed) | 301 KB | 301 KB |
166
+| Star snapshots (per file) | ~3 KB | Stable per file, linear file count | 78 KB total | 156 KB total |
167
+| Previous summary | 5 KB | Stable (only last week sent) | 5 KB | 5 KB |
168
+| Analyzed archive | 5 KB × weeks | Linear growth | 130 KB (26 files) | 260 KB (52 files) |
169
+
170
+### Token Cost Trajectory
171
+
172
+| Timeframe | Weekly Input Tokens | Weekly Cost | Reskill Input Tokens | Monthly Cost (4.3 weeks + 0.86 reskill amortized) |
173
+|-----------|--------------------:|------------:|---------------------:|---:|
174
+| Month 1 (now) | 90,175 | $0.30 | 13,060 | $1.32 |
175
+| Month 6 | 92,300 (+2.4%) | $0.31 | 16,200 (+24%) | $1.36 |
176
+| Month 12 | 94,500 (+4.8%) | $0.32 | 19,500 (+49%) | $1.40 |
177
+
178
+**Key insight:** Context growth is modest because the dominant cost driver (raw JSON at 86K tokens) is stable. Wisdom and skills growth adds only ~2-5% annually to weekly runs. Reskill grows faster (24-49%) because it accumulates more historical context, but it runs infrequently.
179
+
180
+---
181
+
182
+## Cost per Page Calculation
183
+
184
+### Annual Cost Projection (Year 1)
185
+
186
+| Line Item | Frequency | Unit Cost | Annual Cost |
187
+|-----------|-----------|-----------|-------------|
188
+| Weekly analysis (Claude Sonnet 4) | 52/year | $0.30 | $15.60 |
189
+| Reskill (GPT-4.1) | ~10/year | $0.036 | $0.36 |
190
+| GitHub Actions compute | 52/year | $0.00 (public) | $0.00 |
191
+| **Total annual AI cost** | | | **$15.96** |
192
+
193
+### Cost per Published Page
194
+
195
+```
196
+Annual AI cost / 52 pages = $15.96 / 52 = $0.307 per page
197
+```
198
+
199
+Including amortized reskill:
200
+```
201
+($15.60 + $0.36) / 52 = $0.307 per page (reskill is negligible)
202
+```
203
+
204
+### Comparative Analysis
205
+
206
+| Approach | Annual Cost | Cost per Page | Quality |
207
+|----------|-------------|---------------|---------|
208
+| **SquadScope (automated)** | **~$16/year** | **$0.31** | Consistent, opinionated, improving |
209
+| Human analyst (freelance) | $5,200–$10,400/year | $100–$200 | High but variable |
210
+| Newsletter service (Substack Pro) | $600/year | $11.50 | Platform cost only, still need writer |
211
+| Manual GPT-4 chat (copy-paste) | ~$50/year | ~$1 | Inconsistent, no learning loop |
212
+
213
+**SquadScope is 300× cheaper than a human analyst and offers compounding quality via reskill.**
214
+
215
+---
216
+
217
+## Cost Optimization Strategies
218
+
219
+### Strategy 1: Model Selection by Task Criticality
220
+
221
+| Task | Current Model | Optimized Model | Savings |
222
+|------|---------------|-----------------|---------|
223
+| Weekly analysis | Claude Sonnet 4 ($0.30) | GPT-5 mini ($0.02 input + $0.004 output) | **92%** |
224
+| Reskill | GPT-4.1 ($0.036) | Keep (already cheap, quality matters) | 0% |
225
+| Fallback analysis | GPT-4.1 ($0.20) | GPT-5 mini ($0.024) | **88%** |
226
+
227
+**Recommendation:** Start with Claude Sonnet 4 for quality. If quality_score consistently ≥ 75, experiment with GPT-4.1 or Claude Haiku 4.5 for weekly analysis. Reserve premium models for reskill where judgment quality matters most.
228
+
229
+### Strategy 2: Context Window Management
230
+
231
+1. **Summarize raw JSON before sending:** Instead of sending 301 KB of raw JSON, pre-process to extract only the fields used by the prompt (~50 KB, saving ~60% of input tokens).
232
+2. **Cap wisdom.md:** Establish a 5 KB soft limit. During reskill, retire obsolete heuristics rather than only appending.
233
+3. **Compress star snapshots:** For reskill, send only delta summaries rather than full snapshot JSON.
234
+
235
+**Potential savings:** 40-60% reduction in input tokens = ~$0.12–$0.18 savings per weekly run.
236
+
237
+### Strategy 3: Skip-If-Unchanged (Caching)
238
+
239
+If the crawled data has fewer than N significant changes from the prior week (e.g., <5 new repos, <10% topic shift), skip analysis and republish last week's summary with an "unchanged" note.
240
+
241
+**Potential savings:** 5-15% of annual runs skipped = $0.80–$2.40/year.
242
+
243
+**Risk:** Breaks the "every week has a page" contract. Implement as opt-in only.
244
+
245
+### Strategy 4: Token Budget per Run
246
+
247
+Set a hard cap on total tokens per invocation:
248
+
249
+```yaml
250
+env:
251
+ SQUADSCOPE_TOKEN_BUDGET: 150000 # tokens
252
+ SQUADSCOPE_COST_CAP: 0.50 # USD per run
253
+```
254
+
255
+If pre-calculated token estimate exceeds budget:
256
+1. Truncate raw JSON to top 50 repos by stars_gained
257
+2. Omit skills context
258
+3. Shorten previous summary to frontmatter-only
259
+
260
+### Strategy 5: Prompt Optimization
261
+
262
+| Optimization | Token Savings | Effort |
263
+|--------------|---------------|--------|
264
+| Remove output template (model knows format) | ~500 tokens | Low |
265
+| Shorten editorial stance to bullet points | ~200 tokens | Low |
266
+| Inline wisdom into prompt (skip file read) | ~100 tokens | Medium |
267
+| Use structured JSON output instead of markdown | ~300 output tokens | Medium |
268
+
269
+**Combined prompt optimization: ~1,100 tokens saved = ~$0.004/run (marginal).**
270
+
271
+Prompt optimization has low ROI because the raw JSON dominates input cost. Focus on Strategy 2 (context window management) first.
272
+
273
+### Strategy 6: Cached Input Optimization
274
+
275
+If the Copilot CLI supports prompt caching (reusing context across calls), the 86K raw JSON tokens could be served at cached rates:
276
+
277
+```
278
+Cached: 86,000 × $0.30/1M = $0.026 (vs $0.258 uncached)
279
+Savings: $0.232 per run = 77% reduction on the JSON portion
280
+```
281
+
282
+**Status:** Copilot CLI caching behavior is not yet documented for CI invocations. Monitor for updates.
283
+
284
+---
285
+
286
+## Monitoring & Alerting Design
287
+
288
+### Per-Run Token Tracking
289
+
290
+1. **Copilot CLI transcript:** The `--share=PATH` flag exports a session transcript. Parse it post-run to extract actual token counts.
291
+2. **GitHub Models API response headers (assumption to validate):** The API is expected to return `x-ratelimit-remaining` headers and usage metadata in response JSON. Current scripts only parse the JSON body and discard headers; implementation will need to explicitly capture response headers and extract usage fields. This assumption requires validation against live API responses.
292
+3. **Workflow annotations:** Log token estimates and actuals as workflow summary annotations.
293
+
294
+### Implementation
295
+
296
+```yaml
297
+- name: Log token usage
298
+ if: always()
299
+ run: |
300
+ # Parse Copilot CLI transcript for usage data
301
+ if [ -f copilot-session.md ]; then
302
+ python3 scripts/track_token_usage.py \
303
+ --transcript copilot-session.md \
304
+ --stage analysis \
305
+ --week "$WEEK"
306
+ fi
307
+```
308
+
309
+### Usage Dashboard
310
+
311
+Store per-run metrics in `data/metrics/token-usage.jsonl`:
312
+
313
+```json
314
+{"week": "2026-W21", "stage": "analysis", "model": "claude-sonnet-4", "input_tokens": 90175, "output_tokens": 2000, "cost_usd": 0.30, "timestamp": "2026-05-19T08:00:00Z"}
315
+```
316
+
317
+Render a simple chart on the SquadScope site (Hugo shortcode or static SVG) showing:
318
+- Weekly cost trend
319
+- Cumulative annual spend
320
+- Context size growth
321
+
322
+### Budget Alerts
323
+
324
+| Threshold | Action |
325
+|-----------|--------|
326
+| Single run > $0.50 | Warning annotation in workflow summary |
327
+| Single run > $1.00 | Fail the run, open issue |
328
+| Monthly cumulative > $5.00 | Email alert via GitHub Actions notification |
329
+| Monthly cumulative > $10.00 | Auto-switch to GPT-5 mini for remaining month |
330
+
331
+---
332
+
333
+## Budget Controls (Hard Limits, Graceful Degradation)
334
+
335
+### Tiered Degradation Strategy
336
+
337
+```
338
+Normal Mode (cost < $0.50/run)
339
+ └─ Full analysis with Claude Sonnet 4
340
+ └─ Full context (raw JSON + wisdom + skills + prior week)
341
+
342
+Budget Mode (cost would exceed $0.50/run)
343
+ └─ Switch to GPT-4.1 (saves ~33%)
344
+ └─ Truncate raw JSON to top 100 repos
345
+ └─ Omit skills context
346
+
347
+Minimal Mode (monthly budget exhausted)
348
+ └─ Switch to GPT-5 mini (saves ~92%)
349
+ └─ Truncate raw JSON to top 30 repos
350
+ └─ Omit all optional context
351
+ └─ Quality gate threshold lowered to 50
352
+
353
+Emergency Mode (all credits exhausted)
354
+ └─ Skip AI analysis entirely
355
+ └─ Publish raw data summary (stats only, no editorial)
356
+ └─ Open issue for manual intervention
357
+```
358
+
359
+### Pre-flight Cost Estimation
360
+
361
+Before invoking the model, estimate cost:
362
+
363
+```python
364
+def estimate_cost(input_tokens: int, output_estimate: int, model: str) -> float:
365
+ rates = {
366
+ "claude-sonnet-4": {"input": 3.00, "output": 15.00},
367
+ "openai/gpt-4.1": {"input": 2.00, "output": 8.00},
368
+ "openai/gpt-5-mini": {"input": 0.25, "output": 2.00},
369
+ }
370
+ r = rates[model]
371
+ return (input_tokens * r["input"] + output_estimate * r["output"]) / 1_000_000
372
+```
373
+
374
+---
375
+
376
+## Implementation Plan
377
+
378
+### Issues to Create
379
+
380
+| # | Title | Priority | Effort | Dependencies |
381
+|---|-------|----------|--------|--------------|
382
+| 1 | Add pre-flight token estimation to analyze workflow | High | S | None |
383
+| 2 | Implement `scripts/track_token_usage.py` for post-run metrics | High | M | None |
384
+| 3 | Create `data/metrics/token-usage.jsonl` schema and writer | Medium | S | #2 |
385
+| 4 | Add budget alerts to workflow (annotations + issue creation) | Medium | M | #2 |
386
+| 5 | Implement tiered degradation (model downgrade on budget) | Medium | M | #1 |
387
+| 6 | Pre-process raw JSON to reduce token count (Strategy 2) | Medium | M | None |
388
+| 7 | Add wisdom.md size cap and retirement policy to reskill | Low | S | None |
389
+| 8 | Create cost dashboard Hugo shortcode | Low | L | #3 |
390
+| 9 | Investigate Copilot CLI caching for CI (Strategy 6) | Low | S | None |
391
+| 10 | Document model selection decision matrix | Low | S | None |
392
+
393
+### Phasing
394
+
395
+- **Phase A (immediate):** Issues 1–3 — visibility into actual costs
396
+- **Phase B (month 2):** Issues 4–6 — active cost management
397
+- **Phase C (month 3+):** Issues 7–10 — optimization and documentation
398
+
399
+---
400
+
401
+## Open Questions
402
+
403
+| # | Question | Impact | Proposed Resolution |
404
+|---|----------|--------|---------------------|
405
+| OQ1 | Does Copilot CLI expose actual token usage in transcript or exit metadata? | High — needed for accurate tracking | Spike: parse `--share` output for usage data |
406
+| OQ2 | Does `copilot-requests: write` permission on GITHUB_TOKEN consume from org pool or personal allowance? | High — affects billing entity | Test in workflow with usage monitoring |
407
+| OQ3 | Is prompt caching available for Copilot CLI in non-interactive mode? | Medium — could save 77% on JSON input | Monitor GitHub changelog |
408
+| OQ4 | What's the actual token count for the raw JSON? (estimated 86K, need actuals) | Medium — calibration | Add tokenizer count in pre-flight step |
409
+| OQ5 | How does GitHub bill for the Copilot CLI invocation itself vs. the underlying model tokens? | High — may have additional overhead | Review billing after first month |
410
+| OQ6 | Are GitHub Models API calls billed differently from Copilot CLI calls against the same model? | Medium — affects fallback cost comparison | Compare billing line items |
411
+| OQ7 | What happens when the Copilot Pro credit allowance is consumed mid-month? | High — operational risk | Set up overage alerts, test degradation path |
412
+
413
+---
414
+
415
+## Appendix: Token Estimation Methodology
416
+
417
+### Tokenization Rules of Thumb
418
+
419
+- English prose: ~4 characters/token (or ~0.75 words/token)
420
+- JSON with short keys: ~3.5 characters/token
421
+- Markdown with formatting: ~3.8 characters/token
422
+- Code: ~3.2 characters/token
423
+
424
+### Validation Approach
425
+
426
+Once `scripts/track_token_usage.py` is live, compare estimates against actuals for 4 weeks. Adjust multipliers if estimates deviate by >20%.
427
+
428
+### Raw JSON Breakdown (2026-W21.json = 301 KB)
429
+
430
+Estimated token distribution:
431
+- Structural JSON characters (`{}[],:"`): ~20% = ~17K tokens
432
+- Repository names, URLs, descriptions: ~50% = ~43K tokens
433
+- Numeric fields (stars, dates): ~15% = ~13K tokens
434
+- Topic arrays: ~15% = ~13K tokens
435
+- **Total: ~86K tokens** (at 3.5 chars/token)
436
+
437
+---
438
+
439
+*This PRD will be updated with actuals once token tracking is implemented (Phase A, Issues 1–3).*