Skip to content

perf(spec): prompt compression and tiered context — reduce spec skill token cost by ~60% #515

Closed

Description

@admarble

Problem (User Impact)

The /spec skill prompt is 9,240 tokens (SKILL.md + 3 reference files = 48,321 chars). When loaded, it consumes ~10% of a standard context window before any work begins. Real-world spec executions then generate 12,000–16,000 chars of output (3,500–4,500 tokens), much of which is boilerplate ceremony rather than substantive analysis.

Measured across 3 consumer projects (workout, matcha-maps, sequant-landing):

Metric Current Problem
Prompt size 9,240 tokens Loaded every invocation regardless of issue complexity
Code blocks 45 blocks, 43% of file 7 npx tsx blocks (6%) reference libs that don't exist in consumer projects
Output size 12K–16K chars/run Simple 3-AC issues produce same-size output as 13-AC complex issues
Execution time 5–6 minutes Mandatory 3 explorer agents even for docs/config changes
Duplicated sections 13 headers defined 2–5× each "Recommended Workflow" defined 5×, output structure specified 3×
Dead code 2,727 chars npx tsx blocks importing ac-parser, ac-linter, state-manager — none exist in consumer installs

Impact: Every sequant user pays the full prompt tax on every /spec invocation. Users on metered API plans (Cursor, Windsurf, Claude API) pay real money for tokens that teach the model to call code it can never call. Longer prompts also degrade instruction-following quality — research shows models produce worse output as context noise increases, even within their window limits.

Why Now

Research: Industry Best Practices

1. Tiered Context Architecture (source)

Measured 62% reduction in per-session context:

  • Tier 1 (Always loaded): <800 tokens — purpose, critical rules, quick-start
  • Tier 2 (On demand): 500–1,500 tokens — component-specific docs loaded when relevant
  • Tier 3 (Never loaded): 0 tokens — detailed specs linked but not embedded

2. Progressive Disclosure for Skills (source)

With 42 production skills, lazy loading achieved 97% reduction in startup tokens:

  • Level 1 (Metadata): ~10-20 tokens per skill — name + description only
  • Level 2 (Documentation): ~200-2,000 tokens on-demand — usage instructions, parameters
  • Level 3 (Execution): Tool registration happens only when agent commits to invocation

3. Context Window Pollution (source)

"Including irrelevant data actively worsens hallucinations"

An 800K-token unfocused context produces confused outputs, while a 150-token curated context solves the same task correctly. The spec skill's 45 code blocks (including examples the model never needs to reference) are textbook context pollution.

4. CLAUDE.md / Skill File Best Practices (source)

"Give it 5 rules & point it to the details when it needs them. Think 'email with links', not a '2000-page employee handbook'."

MCP tool schemas inject into context on both sides — keeping skill prompts lean is even more critical for MCP/plugin users.

5. Cursor/Windsurf Rule Architecture (source)

Both major AI IDEs use two-tier rules: global (reusable) + workspace-specific. Task-oriented shortcuts (/plan, /review) encapsulate domain-specific guidance rather than requiring the full rulebook on every invocation.

Acceptance Criteria

Prompt Compression (Target: ~3,700 tokens, 60% reduction)

  • AC-1: Consolidate triple output specification into single authoritative template. The output structure is currently defined in prose (sections 1-8), verified in "Output Verification" checklist, and templated in "Output Template" — merge into one template section with inline guidance notes. Target: eliminate ~3,000 tokens of redundancy (13 headers currently defined 2-5× each)
  • AC-2: Extract dead npx tsx code blocks (ac-parser, ac-linter, state-manager, state/update.ts) into a conditional section or separate reference file. These 7 blocks (2,727 chars) import from ./src/lib/ paths that only exist in the sequant repo — consumer installs have zero npx tsx calls across all logged sessions. Guard with: "If ./src/lib/ac-parser.ts exists (sequant repo), run programmatic checks. Otherwise, perform analysis inline."
  • AC-3: Reduce example verbosity by 60%. Current: 9 example/template blocks consuming 8,274 chars (20% of file). Target: 1 concise example per concept (max 10 lines each), retaining decision framework tables (which are already dense/efficient). Remove the Improve multi-issue reliability: default to parallel worktrees and add spec retry logic #452 case study from SKILL.md (it's already in references/verification-criteria.md)
  • AC-4: Convert Feature Quality Planning from 25+ checkbox ceremony to exception-based reporting. Current: model outputs [x] N/A for 80% of checkboxes. New pattern: "All standard checks pass. Notable items: [only list gaps/concerns]". Retain full checklist in reference file for complex issues that need it

Complexity-Gated Output (Target: 40-60% output reduction for simple issues)

  • AC-5: Define concrete output tiers enforced by issue complexity:
    • Simple (simple-fix, typo, docs-only, bug with ≤2 AC): AC list + plan + Design Review Q1/Q3 only. Target: <4,000 chars
    • Standard (3-8 AC, no complexity labels): Full output minus Polish section, minus trivially-passing quality checks. Target: <8,000 chars
    • Complex (complex, refactor, breaking, or 9+ AC): Everything. Target: <15,000 chars
  • AC-6: Output tier is announced at the top of spec output: **Complexity: Standard** (5 ACs, 3 directories) — makes the gating decision transparent and overridable

Conditional Context Gathering (Target: eliminate wasted agent spawns)

  • AC-7: Make explorer agent count conditional on issue content instead of mandatory 3:
    • Has database/SQL/migration keywords in AC or labels → 3 agents (similar features + codebase + database)
    • UI/frontend only → 2 agents (similar features + codebase area, drop database)
    • Docs/config/simple-fix → 1 agent (general context only)
    • CLI/script changes → 2 agents (similar features + codebase, drop database)
  • AC-8: Agent prompts are specific to the issue, not generic templates. Current: "Find similar features for [FEATURE]. Check components/admin/, lib/queries/, docs/patterns/." — the components/admin/ and lib/queries/ paths are sequant-specific and don't exist in consumer projects. New: derive search paths from package.json structure or ls of the actual project

Platform Portability

  • AC-9: Add platform detection preamble that sets capabilities before skill execution:
    1. gh --version → sets GITHUB_AVAILABLE (gates: issue fetch, phase detection, label review, comment posting)
    2. .sequant/settings.json exists → sets SETTINGS_AVAILABLE (gates: parallel mode, scope config)
    3. If GitHub unavailable: skip phase detection, label review, auto-comment; prompt user for AC from description
    4. If settings unavailable: use defaults silently (no error)
  • AC-10: Agent search paths derived from actual project structure, not hardcoded sequant paths. Replace components/admin/, lib/queries/, docs/patterns/ with dynamic discovery: ls src/ app/ lib/ components/ 2>/dev/null to build search targets from what actually exists

Skill Versioning & Drift Prevention

  • AC-11: Add version field to skill YAML frontmatter that sequant init stamps and sequant status checks. Current drift: sequant source (1,139 lines) vs workout (813 lines) vs matcha-maps (754 lines) — no mechanism to detect or reconcile. Format: version: "2.1" in frontmatter, sequant status outputs spec skill: v1.0 (update available: v2.1)
  • AC-12: sequant init --upgrade-skills updates skill files in .claude/skills/ from installed sequant version's templates, with diff preview before overwriting. Does NOT auto-run — user must opt in

Non-Goals

  • Rewriting the spec skill from scratch — this is compression and restructuring, not a redesign
  • Changing what the spec skill produces — the output sections remain the same, just leaner
  • Automated prompt compression (LLMLingua-style) — we're doing manual structural optimization
  • MCP-native skill loading — that's arch: in-process MCP engine — eliminate subprocess indirection and enable real-time streaming #508's scope; this makes skills lean enough for MCP
  • Removing reference files entirely — they serve as Tier 3 documentation for edge cases

Scope & Gaps to Watch

  • Gap: Consumer skill sync — AC-11/AC-12 add versioning but don't auto-upgrade. Users with heavily customized skills may not want upgrades. The diff-preview approach respects this but means some users will stay on old versions
  • Gap: Agent count heuristics — AC-7 uses keyword matching which is imperfect. A database-related issue without explicit keywords would get only 2 agents. Acceptable: the model can spawn additional agents if the first round reveals database work
  • Gap: Output size enforcement — AC-5 sets targets but LLMs don't strictly respect character limits. The tier announcement (AC-6) primes the model, but actual output may vary ±30%. This is a prompt engineering constraint, not a code bug
  • Risk: Over-compression — Removing too many examples could degrade output quality for less capable models (Haiku). Test on Haiku as well as Sonnet/Opus before shipping
  • Risk: Breaking existing fullsolve pipelines — /fullsolve invokes /spec programmatically. Ensure compressed output retains all structured markers that downstream phases parse (phase markers, workflow recommendations, AC checksums)

Technical Notes

  • Skill files live in 3 mirrored directories: .claude/skills/, skills/, templates/skills/ — all three must be updated
  • Consumer projects get skills via sequant init which copies from templates/skills/
  • The references/ subdirectory within skills supports Tier 3 deferred loading — move verbose content there
  • Output template should use structured markers (<!-- SEQUANT_SPEC_TIER: standard -->) for downstream parsing
  • Test with wc -w before/after to verify token reduction targets

Dependencies

Verification Plan

AC Method How to Verify
AC-1 through AC-4 Manual measurement wc -w on SKILL.md before/after; target ≤3,700 tokens (from 9,240)
AC-5, AC-6 Integration test Run /spec on a simple-fix issue and a complex issue; measure output char counts
AC-7, AC-8 Log analysis Run /spec on 3 issue types; verify agent spawn count matches heuristic
AC-9, AC-10 Manual test Run /spec in a non-GitHub project; verify graceful fallback
AC-11, AC-12 Unit test sequant status shows version mismatch; sequant init --upgrade-skills shows diff

Activity

  1. added
    enhancement
    on Apr 9, 2026
  2. admarble commented on Apr 12, 2026

    @admarble
    ContributorAuthor

    → PROCEED — 12 ACs, spec compression + tiered context, no blockers

    spec → exec → qa · 12 ACs · -q (complex, multi-concern: prompt + output + agents + platform + versioning)

    ⚠ Sequence after #502 (dead code cleanup simplifies SKILL.md files first)

  3. admarble commented on Apr 12, 2026

    @admarble
    ContributorAuthor

    Note: AC-2's scripts/state/update.ts removal overlaps with #502 (which removes dead state references from all skill templates). #502 is sequenced first — after it lands, AC-2's remaining scope is the other dead npx tsx blocks: ac-parser, ac-linter, state-manager.

  4. added
    ai-in-progress
    on Apr 12, 2026
  5. admarble commented on Apr 12, 2026

    @admarble
    ContributorAuthor

    Spec Plan — #515: Spec prompt compression and tiered context

    Complexity: Complex (12 ACs, 5 concerns, ~30 files across 3 skill dirs)
    Dependency: #502 merged ✅

    Implementation Plan

    Phase 1: Prompt Compression (AC-1 through AC-4)

    1. AC-1: Merge triple output specification in spec SKILL.md into single authoritative template. Eliminate redundant headers.
    2. AC-2: Guard dead npx tsx blocks (ac-parser, ac-linter, state-manager) with conditional: "If ./src/lib/ac-parser.ts exists, run programmatic checks. Otherwise, perform analysis inline."
    3. AC-3: Reduce example verbosity — 1 concise example per concept (max 10 lines). Remove Improve multi-issue reliability: default to parallel worktrees and add spec retry logic #452 case study from SKILL.md (already in references/).
    4. AC-4: Convert Feature Quality Planning to exception-based: "All standard checks pass. Notable items: [only gaps]". Full checklist remains in reference file.

    Phase 2: Complexity-Gated Output (AC-5, AC-6)
    5. AC-5: Add output tier definitions gated by issue complexity (simple/standard/complex). Simple: AC list + plan + Q1/Q3 only. Standard: full minus polish. Complex: everything.
    6. AC-6: Add tier announcement at top of output: **Complexity: Standard** (5 ACs, 3 directories).

    Phase 3: Conditional Context Gathering (AC-7, AC-8)
    7. AC-7: Replace mandatory 3-agent spawn with keyword-conditional agent count. DB keywords → 3, UI → 2, docs/config → 1.
    8. AC-8: Replace hardcoded components/admin/, lib/queries/ paths with dynamic discovery: ls src/ app/ lib/ components/ 2>/dev/null.

    Phase 4: Platform Portability (AC-9, AC-10)
    9. AC-9: Add platform detection preamble checking gh, .sequant/settings.json. Gates downstream features.
    10. AC-10: Dynamic search paths (same work as AC-8, combined).

    Phase 5: Skill Versioning (AC-11, AC-12)
    11. AC-11: Add version field to skill YAML frontmatter. Add version check to sequant status output.
    12. AC-12: Add sequant init --upgrade-skills with diff preview before overwriting.

    Design Review

    1. Where? Primarily .claude/skills/spec/SKILL.md (prompt layer). AC-11/12 touch src/commands/init.ts and src/commands/status.ts.
    2. Simplest approach? AC-1 through AC-10 are pure prompt editing (no code). AC-11/12 are small TypeScript changes (frontmatter field + CLI option).
    3. Pattern? Follows existing complexity scaling in Feature Quality Planning section. Versioning follows package.json version pattern.
    4. Reviewer challenge? "Will compression degrade output quality?" — Test on Haiku before shipping. "Why not auto-upgrade?" — AC-12 explicitly requires opt-in + diff preview.

    Verification

    AC Method Measure
    AC-1–4 Manual wc -w on SKILL.md: target ≤3,700 tokens (from 5,496 words)
    AC-5–6 Manual Run /spec on simple vs complex issue, compare output sizes
    AC-7–8 Manual Run /spec on 3 issue types, verify agent count
    AC-9–10 Manual Run /spec in non-GitHub project, verify fallback
    AC-11 Integration Test sequant status shows version info
    AC-12 Integration Test sequant init --upgrade-skills shows diff preview

    Recommended Workflow

    Phases: spec → exec → qa
    Quality Loop: enabled (12 ACs, complex multi-concern)

    Risk

    • Over-compression: Removing too many examples may degrade Haiku output quality
    • Breaking fullsolve: Compressed output must retain structured markers for downstream parsing
  6. removed
    ai-in-progress
    on Apr 12, 2026
  7. added 2 commits that reference this issue on Apr 13, 2026
  8. admarble commented on Apr 13, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #515
    Status: READY_FOR_MERGE
    PR: #523

    Summary

    • Prompt compression: 5,508 → 1,370 words (75% reduction, exceeding 60% target)
    • Output tiers: Simple (<4K chars) / Standard (<8K chars) / Complex (<15K chars)
    • Conditional agents: DB→3, UI→2, CLI→2, docs→1 (was always 3)
    • Platform detection: Graceful fallback for non-GitHub environments
    • Skill versioning: version: "2.1" in frontmatter, sequant status shows updates
    • Upgrade path: sequant init --upgrade-skills with diff preview

    AC Coverage: 12/12 MET

    AC Status
    AC-1: Single output template MET
    AC-2: Conditional npx tsx guards MET
    AC-3: Example verbosity reduction MET
    AC-4: Exception-based quality planning MET
    AC-5: Output tier definitions MET
    AC-6: Tier announcement MET
    AC-7: Conditional agent count MET
    AC-8: Dynamic search paths MET
    AC-9: Platform detection MET
    AC-10: Project structure discovery MET
    AC-11: Skill version field + status MET
    AC-12: --upgrade-skills with diff MET

    Quality Metrics

    • Build: passes
    • Tests: 53 passed
    • Skill sync: 5/5 spec files synced
    • Type issues: 0
    • Security issues: 0

    Iterations

    Phase Iterations Status
    Spec 1/1 (prior) Complete
    Exec 1/1 Complete
    QA 1/2 Complete (READY_FOR_MERGE)

    Verdict: READY_FOR_MERGE

  9. added 5 commits that reference this issue on Apr 14, 2026
  10. admarble commented on Apr 15, 2026

    @admarble
    ContributorAuthor

    Documentation Generated

    File: docs/features/spec-prompt-compression.md

    Sections Included:

    • What Changed (output tiers, conditional agents, platform detection, exception-based quality planning)
    • Skill Versioning (sequant status + sequant init --upgrade-skills)
    • Reference Files (tiered loading architecture)
    • Troubleshooting (3 scenarios)

    Next Steps:

    1. Review generated documentation for accuracy
    2. Commit and include in next release

    Documentation complete.

  11. added 3 commits that reference this issue on Apr 18, 2026
  12. added a commit that references this issue on Jul 29, 2026
  13. added a commit that references this issue on Aug 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions