Skip to content

RFC: ML/AI Infrastructure for Quality, Accuracy, and Adherence #199

Closed

Description

@admarble

Summary

A comprehensive proposal for ML/AI tooling to improve Sequant's accuracy, code quality enforcement, and spec adherence. These recommendations come from a staff AI engineer perspective, focusing on measurable improvements and data-driven iteration.

Core insight: You can't improve what you can't measure. The foundation is an evaluation infrastructure that makes everything else data-driven.


Problem Statement

Current limitations in Sequant:

Area Current State Gap
Measurement Basic success/failure metrics No systematic eval of output quality
Code Search Keyword-based (grep) Misses semantic matches
Spec Quality Natural language AC No validation of testability/completeness
Code Analysis Regex patterns for secrets Misses deep vulnerabilities
Adherence Manual review in /qa No automated AC↔code mapping
Debugging Execution logs Can't trace why Claude made decisions
Learning None Doesn't improve from past failures

Proposed Improvements

1. Evaluation & Measurement Infrastructure

Goal: Systematic measurement of AI output quality

1.1 Evals Framework

  • Integrate promptfoo or Braintrust
  • Create evaluation datasets:
    • AC extraction accuracy (issue → extracted AC vs human-labeled)
    • Plan quality (/spec output vs expert plans)
    • Verdict correctness (/qa false positives/negatives)
  • Automated regression testing on prompt changes

1.2 A/B Testing Infrastructure

  • Track prompt versions in metrics.json
  • Compare success rates per prompt version
  • Statistical significance testing for prompt changes
// Extend metrics-schema.ts
promptVersions: z.record(z.string(), z.object({
  version: z.string(),
  successRate: z.number(),
  avgTokens: z.number(),
  avgLatency: z.number(),
  sampleSize: z.number()
}))

Tools: promptfoo (OSS, local), Braintrust (cloud)


2. Semantic Code Understanding

Goal: Find relevant code by meaning, not just keywords

2.1 Local Embedding Index

  • Use Ollama + nomic-embed-text for local embeddings
  • Index codebase on sequant init, incremental updates on file changes
  • Store in LanceDB (local, no server)

2.2 RAG for Context Injection

  • Before /exec: retrieve semantically relevant code
    • Similar features
    • Related tests
    • Architectural patterns
  • Inject as context to reduce hallucination

Example query: "where do we handle authentication" → finds auth code even without keyword "auth"

Tools: Ollama (local LLM/embeddings), LanceDB (local vector DB), Chroma (alternative)


3. Formal Spec Verification

Goal: Ensure AC items are testable and complete

3.1 AC Linting

  • Static analysis of acceptance criteria before /exec
  • Flag vague terms: "should work properly", "handle edge cases"
  • Require measurable outcomes: "returns 400 status code"
  • Detect missing test criteria

3.2 Property-Based Test Generation

  • Integrate fast-check patterns
  • /testgen outputs property tests, not just unit tests
  • Auto-generate edge cases from type signatures

3.3 Contract Extraction

  • Extract TypeScript interfaces from AC
  • Validate implementation satisfies contracts
  • Use ts-morph for AST analysis

Tools: fast-check (property testing), ts-morph (TypeScript AST)


4. Advanced Code Quality Analysis

Goal: Deeper analysis than regex patterns

4.1 CodeQL Integration

  • Deep semantic analysis for vulnerabilities
  • Data flow analysis for taint tracking
  • Run locally, free for OSS

4.2 Semgrep Rules

  • Custom Sequant-specific rules
  • Pattern: "never use any in this codebase"
  • Pattern: "all API routes must validate input"
  • More powerful than regex, catches structural issues

4.3 ast-grep for Structural Search

  • Find patterns like "function without error handling"
  • Faster and more precise than regex
  • Custom rules per stack

4.4 Quality Scoring

  • Integrate complexity metrics (cyclomatic, cognitive)
  • Gate /qa verdicts on maintainability scores
  • Track quality trends over time

Tools: CodeQL (free for OSS), Semgrep (free tier), ast-grep (OSS), SonarQube (optional)


5. Adherence Verification

Goal: Automated verification that code changes address AC items

5.1 Semantic Diff Analysis

  • Embed AC items and code diffs
  • Cosine similarity to detect if changes are "on-topic"
  • Flag changes unrelated to any AC (scope creep detection)

5.2 Traceability Matrix

  • Auto-generate AC → file → test mapping
  • /qa verifies every AC has test coverage
  • Highlight untested AC items
AC-1: User login     → src/auth/login.ts      → tests/auth/login.test.ts  ✓
AC-2: Error display  → src/components/Error.tsx → (no test)               ⚠️
AC-3: Rate limiting  → (no implementation)     → (no test)                ✗

5.3 Coverage Gap Analysis

  • Beyond line coverage: branch, condition coverage
  • Flag untested branches in changed code
  • Integrate with /qa verdicts

Tools: Custom embeddings + cosine similarity, c8/nyc for coverage


6. Agent Observability & Debugging

Goal: Understand why Claude made certain decisions

6.1 Structured Tracing

  • Integrate LangFuse (OSS, self-hostable) or Arize Phoenix (local)
  • Trace every Claude call with inputs/outputs
  • Token usage, latency, cost per phase
  • Replay failed runs for debugging

6.2 Decision Explanation

  • Add reasoning field to /qa verdicts
  • Log why AC was marked NOT_MET vs PARTIALLY_MET
  • Structured reasoning chains

6.3 Cost Tracking

  • Track tokens per skill, per issue
  • Identify expensive operations
  • Optimize prompts for efficiency

Tools: LangFuse (OSS), Arize Phoenix (local), LangSmith (cloud alternative)


7. Prompt Engineering Infrastructure

Goal: Systematic prompt management and optimization

7.1 Prompt Templating

  • Separate prompts from SKILL.md logic
  • Version control prompt changes independently
  • Hot-reload prompts without code changes

7.2 Few-Shot Example Library

  • Curated examples of good outputs
    • Good /spec plans
    • Good /qa verdicts
    • Good /exec implementations
  • Inject dynamically based on issue type
  • Improves consistency without fine-tuning

7.3 Chain-of-Thought Enforcement

  • Force step-by-step reasoning before verdicts
  • Structured output format for reasoning
  • Audit trail for decisions

Tools: Custom templating, JSON schema validation


8. Test Quality Assurance

Goal: Ensure tests actually catch bugs

8.1 Mutation Testing

  • Integrate Stryker Mutator
  • Introduce bugs, verify tests catch them
  • Gate /qa on mutation score thresholds
  • Run incrementally on changed code only

8.2 Test Smell Detection

  • Flag assertion-free tests
  • Detect tests that always pass
  • Identify flaky test patterns

Tools: Stryker (mutation testing), custom linting rules


9. Self-Improvement Loop

Goal: Sequant that learns from its mistakes

9.1 Failure Analysis Pipeline

  • When /qa fails, capture structured "why"
  • Build dataset: (issue, failed_approach, working_approach)
  • Feed back into prompts as negative examples

9.2 Success Pattern Mining

  • Cluster successful implementations
  • Extract common patterns per issue type
  • "For auth issues, these 5 approaches worked"

9.3 User Feedback Collection

  • Post-merge prompt: "Was this satisfactory? [1-5]"
  • Correlate scores with prompt versions, AC quality
  • No fine-tuning needed - just prompt optimization

9.4 Continuous Prompt Optimization

  • Use eval scores to guide prompt changes
  • Automated prompt variant testing
  • Gradual rollout of improved prompts

Tools: Custom pipeline, promptfoo for automated testing


Implementation Roadmap

Phase 1: Foundation (P0)

Item Effort Impact Dependencies
Evals framework (promptfoo) M High None
Semgrep integration S High None
Basic observability (LangFuse) S Medium None

Outcome: Can measure quality, catch more issues, debug failures

Phase 2: Intelligence (P1)

Item Effort Impact Dependencies
Local embeddings + RAG M High Phase 1
AC linting M Medium Phase 1
Traceability matrix M High Embeddings

Outcome: Smarter context retrieval, better spec quality, adherence tracking

Phase 3: Quality (P2)

Item Effort Impact Dependencies
CodeQL integration M High None
Semantic diff analysis L High Embeddings
Mutation testing M Medium None

Outcome: Deep security analysis, scope creep detection, test quality assurance

Phase 4: Learning (P3)

Item Effort Impact Dependencies
Failure analysis pipeline L High Observability
Success pattern mining L High Embeddings
Continuous optimization L Very High Evals, all above

Outcome: Self-improving system


Tool Summary

Category Tool License Local-First Notes
Evals promptfoo MIT ✅ Primary recommendation
Evals Braintrust Commercial ❌ Cloud alternative
Embeddings Ollama MIT ✅ Local LLM/embeddings
Vector DB LanceDB Apache 2.0 ✅ No server needed
Static Analysis Semgrep LGPL ✅ Custom rules
Static Analysis CodeQL Custom ✅ Free for OSS
Static Analysis ast-grep MIT ✅ Structural search
Observability LangFuse MIT ✅ Self-hostable
Observability Arize Phoenix Apache 2.0 ✅ Fully local
Mutation Test Stryker Apache 2.0 ✅ JS/TS support
Property Test fast-check MIT ✅ Property-based
AST Analysis ts-morph MIT ✅ TypeScript AST

All primary recommendations are local-first and open source, consistent with Sequant's philosophy.


Success Metrics

Metric Current Target How to Measure
/qa false positive rate Unknown <5% Evals vs human review
AC extraction accuracy Unknown >90% Evals vs labeled data
Security issues caught Regex only +50% CodeQL/Semgrep findings
Context relevance Keyword Semantic User feedback, adherence
Debug time for failures Hours Minutes Time to root cause
Test mutation score Unknown >80% Stryker reports

Open Questions

  1. Embedding model choice: nomic-embed-text vs code-specific models (CodeBERT, StarCoder embeddings)?
  2. Vector DB: LanceDB vs Chroma vs SQLite with pgvector extension?
  3. Observability hosting: Self-host LangFuse vs local-only Arize Phoenix?
  4. Eval dataset creation: Manual labeling vs synthetic generation vs production sampling?
  5. Prompt versioning: Git-based vs database vs hybrid?

References


Labels

  • enhancement
  • rfc
  • ml-infrastructure

/cc @tony - Ready for prioritization and roadmap discussion

Activity

  1. admarble commented on Jan 29, 2026

    @admarble
    ContributorAuthor

    Performance Analysis by User Use Case

    Typical User Workflows

    Based on Sequant's design, here are the primary use cases and their performance profiles:

    Use Case Frequency Time Sensitivity Resource Constraints
    Single Issue Flow (/spec → /exec → /qa) Daily Medium (minutes OK) Developer laptop
    Fullsolve Automation (/fullsolve 123) Several/day Low (can run in background) Developer laptop
    Parallel Issues (multiple worktrees) Weekly Medium Memory-constrained
    CI Integration (PR validation) Per-PR High (blocks merge) CI runner (limited)
    Batch Processing (sequant run 1,2,3,4,5) Occasional Low Overnight acceptable

    Performance Impact Analysis

    1. Evals Framework (promptfoo)

    Metric Impact Notes
    Runtime overhead None in production Evals run separately, not in workflow
    CI impact +2-5 min per PR Only if evals run in CI
    Storage ~10-50 MB Eval datasets and results

    Recommendation: Run evals nightly or on prompt changes only, not every PR.


    2. Local Embeddings + RAG

    Metric Impact Mitigation
    Initial indexing 30s - 5 min (depends on codebase size) One-time on sequant init, incremental after
    Query latency +200-500ms per search Acceptable for /spec, /exec context gathering
    Memory (Ollama) 2-4 GB RAM Can use smaller models (384-dim vs 768-dim)
    Disk (LanceDB) ~1 MB per 1K files Negligible for most projects
    Embedding generation ~50 files/sec (CPU) Background indexing, watch mode

    Use Case Impact:

    Workflow Added Latency Benefit
    /spec +1-2s Much better context retrieval
    /exec +1-2s Finds similar implementations
    /qa +500ms Semantic diff analysis
    CI Not recommended Too heavy for CI runners

    Recommendation:

    • Use nomic-embed-text (768-dim, good quality/speed tradeoff)
    • Index on init, incremental updates via file watcher
    • Skip in CI - use pre-built index or skip RAG

    3. AC Linting

    Metric Impact Notes
    Runtime +100-300ms Regex + heuristic checks
    Memory Negligible No model loading
    False positives Risk May flag valid AC as "vague"

    Recommendation: Fast enough to run on every /spec. Include override mechanism.


    4. Static Analysis Tools

    Tool Runtime Memory CI-Friendly
    Semgrep 5-30s (incremental) 200-500 MB ✅ Yes
    CodeQL 2-10 min (full), 30s-2min (incremental) 2-4 GB ⚠️ Heavy
    ast-grep 1-5s 50-100 MB ✅ Yes
    ESLint (existing) 2-10s 100-200 MB ✅ Yes

    Use Case Impact:

    Workflow Semgrep CodeQL ast-grep
    /qa (laptop) ✅ +10s ⚠️ +2min ✅ +2s
    /qa (CI) ✅ +15s ❌ Too slow ✅ +3s
    /fullsolve ✅ Acceptable ⚠️ Only if backgrounded ✅ Fast

    Recommendation:

    • Always: Semgrep + ast-grep (fast, high value)
    • Optional: CodeQL for security-sensitive repos (run nightly or on-demand)
    • Skip in CI: CodeQL unless dedicated security workflow

    5. Semantic Diff Analysis

    Metric Impact Notes
    Embedding diffs +500ms - 2s Depends on diff size
    Similarity computation +100ms Fast vector math
    Total per /qa +1-3s Acceptable

    Recommendation: Enable by default in /qa. Minimal overhead, high value for scope creep detection.


    6. Observability (LangFuse/Phoenix)

    Deployment Latency Overhead Resource Usage
    LangFuse Cloud +50-100ms per call None local
    LangFuse Self-hosted +10-30ms 500 MB - 1 GB RAM (Docker)
    Arize Phoenix (local) +5-20ms 200-500 MB RAM

    Use Case Impact:

    Workflow Cloud Self-hosted Local (Phoenix)
    /spec (3-5 Claude calls) +300ms +100ms +50ms
    /exec (10-20 calls) +1.5s +400ms +200ms
    /fullsolve (30-50 calls) +4s +1s +500ms

    Recommendation:

    • Development: Arize Phoenix (fully local, minimal overhead)
    • Team/Production: LangFuse self-hosted (worth the Docker overhead)
    • Opt-in: Make observability configurable, disabled by default

    7. Mutation Testing (Stryker)

    Metric Impact Notes
    Full run 5-30 min Too slow for regular use
    Incremental 30s - 3 min Only mutate changed code
    Memory 500 MB - 2 GB Spawns multiple test processes

    Use Case Impact:

    Workflow Full Incremental
    /qa ❌ Never ⚠️ Optional flag
    /fullsolve ❌ Never ⚠️ Optional flag
    Pre-merge CI ⚠️ Nightly only ✅ On changed files
    Quality audit ✅ Monthly N/A

    Recommendation:

    • Never in default workflow - too slow
    • Add --mutation-test flag for explicit opt-in
    • Run in CI on a schedule (nightly/weekly)

    8. Property-Based Testing (fast-check)

    Metric Impact Notes
    Test generation +200-500ms One-time in /testgen
    Test execution +1-10s per test Runs 100 iterations by default
    Memory Negligible Pure JS

    Recommendation: Generate property tests in /testgen, but make iteration count configurable. Default to 100, allow reduction to 10 for CI speed.


    Resource Budget by Use Case

    Solo Developer on Laptop (8 GB RAM, no GPU)

    Phase Current With All P0+P1 Notes
    /spec 30-60s 35-70s (+15%) +RAG context
    /exec 5-15 min 5-16 min (+5%) +Semgrep checks
    /qa 1-3 min 1.5-4 min (+30%) +semantic diff, Semgrep
    Memory baseline 500 MB 2.5-3 GB +Ollama embeddings

    Verdict: ✅ Acceptable. RAM is the constraint - may need to unload Ollama between phases.

    CI Runner (GitHub Actions, 7 GB RAM, 2 cores)

    Check Time Budget Recommended Tools
    PR Validation < 5 min Semgrep, ast-grep, existing tests
    Nightly Security < 30 min + CodeQL
    Weekly Quality < 60 min + Mutation testing

    Verdict: ✅ Feasible with tiered approach. Skip heavy tools (CodeQL, Stryker) in PR checks.

    Batch Processing (5+ issues overnight)

    Concern Mitigation
    Memory accumulation Restart Ollama between issues
    Disk space (worktrees) Auto-cleanup merged worktrees
    Rate limits (GitHub API) Built-in backoff already exists

    Verdict: ✅ No new concerns. Existing patterns handle batch well.


    Latency Budget Summary

    Target: < 20% overhead on typical workflows

    Tool Latency Include By Default?
    Embeddings/RAG +1-3s ✅ Yes
    Semgrep +5-15s ✅ Yes
    ast-grep +1-3s ✅ Yes
    AC Linting +100-300ms ✅ Yes
    Semantic Diff +1-3s ✅ Yes
    Observability +200ms-1s ⚠️ Opt-in
    CodeQL +2-10 min ❌ On-demand only
    Mutation Testing +5-30 min ❌ Flag only

    Memory Budget Summary

    Target: < 4 GB additional RAM for full feature set

    Component Memory Required?
    Ollama (nomic-embed) 1.5-2 GB For RAG
    LanceDB 50-200 MB For RAG
    Semgrep 200-500 MB Recommended
    Phoenix (observability) 200-500 MB Optional
    Total (recommended) 2-3 GB
    Total (all features) 3-4 GB

    Recommended Configuration Tiers

    Tier 1: Lightweight (< 1 GB overhead)

    {
      "embeddings": false,
      "semgrep": true,
      "astGrep": true,
      "observability": false,
      "codeql": false,
      "mutationTesting": false
    }

    For: CI runners, low-RAM machines, quick iterations

    Tier 2: Balanced (2-3 GB overhead) ⭐ Recommended

    {
      "embeddings": true,
      "semgrep": true,
      "astGrep": true,
      "observability": "local",
      "codeql": false,
      "mutationTesting": false
    }

    For: Daily development on modern laptops

    Tier 3: Full (4+ GB overhead)

    {
      "embeddings": true,
      "semgrep": true,
      "astGrep": true,
      "observability": "full",
      "codeql": "on-demand",
      "mutationTesting": "on-demand"
    }

    For: Security-sensitive projects, quality audits


    Performance Testing Plan

    Before shipping each feature, validate:

    1. Micro-benchmarks

      • Embedding generation: < 50ms per file
      • Vector search: < 200ms for top-10
      • Semgrep incremental: < 15s on 100-file diff
    2. Integration benchmarks

      • /spec total time increase: < 20%
      • /qa total time increase: < 30%
      • Memory high-water mark: < 4 GB (Tier 2)
    3. User experience

      • No perceived lag on interactive commands
      • Progress indicators for operations > 5s
      • Graceful degradation if Ollama unavailable

    Summary

    Use Case Performance Impact Recommendation
    Single issue (laptop) +15-30% time, +2-3 GB RAM ✅ Ship Tier 2 as default
    Fullsolve (laptop) +10-20% time ✅ Acceptable
    CI validation Must stay < 5 min ⚠️ Use Tier 1, skip heavy tools
    Batch overnight No new concerns ✅ Use Tier 2
    Security audit +10-30 min acceptable ✅ Use Tier 3 on-demand

    Bottom line: The P0+P1 features add ~2-3 GB RAM and ~20% latency overhead. This is acceptable for the accuracy/quality gains, especially since Sequant workflows already take minutes, not seconds.

  2. admarble commented on Jan 29, 2026

    @admarble
    ContributorAuthor

    Integration & Complexity Analysis

    The Over-Engineering Risk

    Sequant's core value is discipline without friction. Adding 9 new systems risks violating this principle. This analysis evaluates each proposal against:

    1. Integration complexity - How hard to wire up?
    2. Dependency burden - What are we adding to the dependency tree?
    3. Maintenance cost - Ongoing effort to keep it working
    4. Failure modes - What breaks when it breaks?
    5. Simpler alternatives - Is there a 80/20 solution?

    Complexity Scorecard

    Proposal Integration Dependencies Maintenance Failure Risk Score
    1. Evals (promptfoo) Low 1 dev dep Low None (offline) ✅ Simple
    2. Embeddings/RAG High 3+ deps + Ollama Medium Degrades gracefully ⚠️ Complex
    3. AC Linting Low 0 new deps Low False positives ✅ Simple
    4. Semgrep Low 1 binary Low Skippable ✅ Simple
    5. CodeQL Medium 1 binary + DB Medium Slow, skippable ⚠️ Medium
    6. Semantic Diff High Requires #2 Medium Requires embeddings ⚠️ Complex
    7. Observability Medium 1-2 deps Medium Optional feature ⚠️ Medium
    8. Mutation Testing Low 1 dep Low Slow, opt-in ✅ Simple
    9. Self-Improvement Very High All of above High Complex pipeline ❌ Complex

    Detailed Integration Analysis

    1. Evals Framework (promptfoo) ✅ LOW COMPLEXITY

    Integration Points:

    promptfoo.yaml ←── defines test cases
         ↓
    npm run eval ←── runs offline, no runtime integration
         ↓
    Results in terminal/JSON
    

    Dependencies:

    "devDependencies": {
      "promptfoo": "^0.50.0"  // Single dev dep, no runtime
    }

    Failure Modes:

    • Evals fail → No impact on production workflow
    • Offline tool, zero runtime risk

    Maintenance:

    • Update eval datasets when prompts change
    • ~2 hours/month

    Verdict: ✅ Ship it. Zero runtime risk, high value for prompt iteration.


    2. Embeddings + RAG ⚠️ HIGH COMPLEXITY

    Integration Points:

                        ┌─────────────────┐
                        │     Ollama      │ ← External process
                        │ (must be running)│
                        └────────┬────────┘
                                 │
    sequant init ──► index-codebase.ts ──► LanceDB
                                 │              │
                                 ▼              ▼
                        /spec, /exec ◄──── vector-search.ts
    

    Dependencies:

    "dependencies": {
      "lancedb": "^0.4.0",      // Vector storage
      "ollama": "^0.5.0",       // Ollama client
    },
    "optionalDependencies": {
      "@xenova/transformers": "^2.0.0"  // Fallback if no Ollama
    }

    Failure Modes:

    Failure Impact Mitigation
    Ollama not installed RAG disabled Graceful skip + warning
    Ollama not running RAG disabled Auto-start or skip
    Index corrupted Stale results Rebuild command
    Out of memory Ollama crashes Smaller model option

    Maintenance:

    • Ollama version updates
    • Embedding model changes (breaking changes possible)
    • Index schema migrations
    • ~4-6 hours/month

    Simpler Alternative:

    // Instead of full RAG, enhance existing grep with ranking
    const results = await grep(pattern);
    const ranked = rankByRelevance(results, query); // TF-IDF, no embeddings
    • 80% of benefit, 20% of complexity
    • No Ollama dependency
    • But: misses semantic matches

    Verdict: ⚠️ High value but high complexity. Consider phased approach:

    1. Phase 1: Enhanced grep with TF-IDF ranking (simple)
    2. Phase 2: Optional Ollama integration (opt-in)

    3. AC Linting ✅ LOW COMPLEXITY

    Integration Points:

    /spec skill
        ↓
    ac-linter.ts ← New 200-line module
        ↓
    Warnings in output
    

    Dependencies:

    // No new dependencies - pure TypeScript

    Implementation:

    // ac-linter.ts (~200 lines)
    const VAGUE_PATTERNS = [
      /should work/i,
      /handle .* correctly/i,
      /properly/i,
      /as expected/i,
    ];
    
    const MISSING_METRICS = [
      // AC without numbers, status codes, or measurable outcomes
      /^(?!.*\b(\d+|status|error|return|response)\b).*$/i
    ];
    
    export function lintAC(ac: string[]): LintResult[] {
      return ac.flatMap(item => [
        ...checkVagueLanguage(item),
        ...checkMissingMetrics(item),
        ...checkTestability(item),
      ]);
    }

    Failure Modes:

    • False positives → User ignores warnings (annoying but safe)
    • No runtime risk

    Verdict: ✅ Ship it. Zero dependencies, immediate value, low maintenance.


    4. Semgrep ✅ LOW COMPLEXITY

    Integration Points:

    /qa skill
        ↓
    semgrep --config auto --json src/
        ↓
    Parse JSON, include in verdict
    

    Dependencies:

    # External binary, not npm dep
    brew install semgrep  # or pip install semgrep

    Failure Modes:

    Failure Impact Mitigation
    Semgrep not installed Skip check Warning + graceful skip
    Semgrep timeout Slow /qa Timeout + skip
    False positives Noise Curated rule set

    Maintenance:

    • Update rule sets quarterly
    • ~1 hour/month

    Simpler Alternative: None needed - Semgrep IS the simple solution compared to CodeQL.

    Verdict: ✅ Ship it. Optional external binary, high value, graceful degradation.


    5. CodeQL ⚠️ MEDIUM COMPLEXITY

    Integration Points:

    codeql database create ./codeql-db --language=typescript
    codeql database analyze ./codeql-db --format=sarif-latest
        ↓
    Parse SARIF, include in verdict
    

    Dependencies:

    # 500 MB+ binary download
    gh extension install github/gh-codeql

    Failure Modes:

    Failure Impact Mitigation
    CodeQL not installed Skip Expected for most users
    Database creation slow 2-10 min Background + cache
    Analysis timeout Very slow Timeout at 10 min

    Maintenance:

    • CodeQL query pack updates
    • Database schema changes
    • ~2 hours/month

    Simpler Alternative: Semgrep covers 70% of CodeQL's value with 10% of the complexity. CodeQL adds:

    • Data flow analysis (taint tracking)
    • Cross-file vulnerability detection
    • But: Most vulns are caught by Semgrep

    Verdict: ⚠️ Optional, on-demand only. Don't include in default workflow. Add sequant security-audit command that runs CodeQL explicitly.


    6. Semantic Diff Analysis ⚠️ HIGH COMPLEXITY (depends on #2)

    Integration Points:

    Requires embeddings (#2) to be implemented first
        ↓
    /qa skill
        ↓
    embed(AC items) ←→ embed(diff hunks)
        ↓
    cosine_similarity matrix
        ↓
    Flag unrelated changes
    

    Dependencies:

    Failure Modes:

    Simpler Alternative:

    // Keyword overlap analysis - no embeddings needed
    function diffRelatesToAC(diff: string, ac: string[]): boolean {
      const diffKeywords = extractKeywords(diff);
      const acKeywords = ac.flatMap(extractKeywords);
      const overlap = intersection(diffKeywords, acKeywords);
      return overlap.length / acKeywords.length > 0.3;
    }
    • Works without Ollama
    • 60% of benefit
    • Can upgrade to semantic later

    Verdict: ⚠️ Defer until #2 is proven. Start with keyword overlap, upgrade later.


    7. Observability (LangFuse/Phoenix) ⚠️ MEDIUM COMPLEXITY

    Integration Points:

    ┌─────────────────────────────────────────────┐
    │ Option A: LangFuse (self-hosted)            │
    │                                             │
    │ docker-compose up -d langfuse              │
    │       ↓                                     │
    │ LANGFUSE_HOST=http://localhost:3000        │
    │       ↓                                     │
    │ langfuse.trace() wrapper on Claude calls    │
    └─────────────────────────────────────────────┘
    
    ┌─────────────────────────────────────────────┐
    │ Option B: Arize Phoenix (local file)        │
    │                                             │
    │ phoenix.launch_app()  ← In-process          │
    │       ↓                                     │
    │ Traces stored locally                       │
    │       ↓                                     │
    │ View at localhost:6006                      │
    └─────────────────────────────────────────────┘
    

    Dependencies:

    // Option A
    "optionalDependencies": {
      "langfuse": "^3.0.0"
    }
    
    // Option B
    "optionalDependencies": {
      "arize-phoenix": "^4.0.0"  // Python, needs bridge
    }

    Failure Modes:

    Failure Impact Mitigation
    LangFuse down No traces Async, non-blocking
    Phoenix crash No traces In-process recovery
    Disk full Traces lost Rotation policy

    Maintenance:

    • Docker updates (LangFuse)
    • Trace schema evolution
    • ~2 hours/month

    Simpler Alternative:

    // Structured logging to JSON files - no infra needed
    const trace = {
      timestamp: Date.now(),
      skill: '/qa',
      claudeCalls: [
        { prompt: '...', response: '...', tokens: 1234, latency: 2000 }
      ]
    };
    fs.appendFileSync('.sequant/traces.jsonl', JSON.stringify(trace) + '\n');
    • Zero dependencies
    • Queryable with jq
    • 70% of debugging value

    Verdict: ⚠️ Start with JSONL logging, add Phoenix later. Full observability is nice-to-have, not must-have.


    8. Mutation Testing (Stryker) ✅ LOW COMPLEXITY

    Integration Points:

    sequant qa --mutation-test
        ↓
    npx stryker run --mutate "src/**/*.ts"
        ↓
    Parse JSON report
        ↓
    Include mutation score in verdict
    

    Dependencies:

    "devDependencies": {
      "@stryker-mutator/core": "^7.0.0",
      "@stryker-mutator/typescript-checker": "^7.0.0"
    }

    Failure Modes:

    Failure Impact Mitigation
    Stryker slow Long wait Incremental mode, timeout
    Test flakiness False results Retry logic

    Maintenance:

    • Update with major Vitest changes
    • ~1 hour/month

    Verdict: ✅ Ship as opt-in flag. Dev dependency only, clear value, no runtime risk.


    9. Self-Improvement Loop ❌ HIGH COMPLEXITY

    Integration Points:

                         ┌──────────────┐
                         │ Failure DB   │ ← New storage
                         └──────┬───────┘
                                │
    /qa failure ──► extract_failure_pattern() ──► store()
                                │
                                ▼
                         ┌──────────────┐
                         │ Pattern Mine │ ← ML pipeline
                         └──────┬───────┘
                                │
                                ▼
                         ┌──────────────┐
                         │ Prompt Gen   │ ← Auto-modify prompts
                         └──────┬───────┘
                                │
                                ▼
                         ┌──────────────┐
                         │ A/B Test     │ ← Requires evals
                         └──────────────┘
    

    Dependencies:

    Failure Modes:

    Failure Impact Mitigation
    Bad pattern extraction Wrong learnings Human review
    Prompt regression Worse outputs Eval gates
    Feedback loop Catastrophic drift Guardrails

    Maintenance:

    • Pipeline debugging
    • Model drift monitoring
    • ~8+ hours/month

    Simpler Alternative:

    <!-- Manual pattern file: .sequant/learned-patterns.md -->
    ## Patterns from Failures
    
    ### Auth Issues
    - Always check for RLS policies
    - Never store tokens in localStorage
    
    ### API Routes  
    - Always validate request body with zod
    - Return proper status codes
    • Human-curated
    • Injected into prompts
    • Zero ML complexity

    Verdict: ❌ Defer to v2.0+. Too complex for current stage. Start with manual pattern curation.


    Dependency Tree Impact

    Current Sequant dependencies: ~15 runtime, ~20 dev

    Proposed additions by tier:

    Tier New Runtime New Dev New External
    P0 (Foundation) 0 +2 (promptfoo, stryker) +1 (semgrep binary)
    P1 (Intelligence) +2 (lancedb, ollama) 0 +1 (ollama service)
    P2 (Quality) 0 0 +1 (codeql binary)
    P3 (Learning) +3-5 +2-3 +1 (phoenix)

    Total if all shipped:

    • Runtime deps: +5-7 (33-47% increase)
    • External services: +3 (Ollama, LangFuse, CodeQL)

    Complexity Budget Recommendation

    Given Sequant's "discipline without friction" philosophy, propose a complexity budget:

    Category Budget Proposed Status
    New runtime deps ≤ 3 2 (lancedb, ollama client) ✅ Under
    New dev deps ≤ 5 3 (promptfoo, stryker, langfuse) ✅ Under
    External services ≤ 2 2 (Ollama, Semgrep) ✅ At limit
    New CLI commands ≤ 3 2 (security-audit, benchmark) ✅ Under
    Config options ≤ 10 8 ✅ Under

    Revised Recommendations

    Based on complexity analysis, revised priority:

    Ship Now (Low Complexity, High Value)

    1. ✅ Evals framework - Zero runtime impact
    2. ✅ AC Linting - Zero dependencies
    3. ✅ Semgrep integration - Optional binary, graceful skip
    4. ✅ JSONL tracing - Simple logging, no infra

    Ship with Opt-In Flag

    1. ⚠️ Mutation testing - Dev dep only, explicit flag
    2. ⚠️ Enhanced grep (TF-IDF) - No Ollama, simpler than RAG

    Defer (Needs More Design)

    1. 🔄 Full RAG with Ollama - High value but complex, needs graceful degradation story
    2. 🔄 Semantic diff - Depends on embeddings decision

    Defer to v2.0+

    1. ❌ CodeQL - Semgrep covers most cases
    2. ❌ Self-improvement loop - Too complex, manual patterns first
    3. ❌ Full observability (LangFuse) - JSONL is good enough for now

    The 80/20 Path

    Maximum value with minimum complexity:

    Week 1-2: promptfoo + AC linting + JSONL tracing
    Week 3-4: Semgrep integration + TF-IDF search enhancement
    Week 5-6: Mutation testing (opt-in) + manual patterns file
    
    Total new deps: 2 runtime, 3 dev
    Total new external: 1 (Semgrep binary)
    Estimated value capture: 70-80% of full proposal
    Complexity: 20-30% of full proposal
    

    This gives you:

    • ✅ Measurable prompt quality (evals)
    • ✅ Better spec quality (AC linting)
    • ✅ Deeper security analysis (Semgrep)
    • ✅ Debuggable failures (JSONL traces)
    • ✅ Smarter search (TF-IDF, no Ollama)
    • ✅ Test quality assurance (mutation, opt-in)

    Without:

    • ❌ Ollama dependency
    • ❌ Docker for observability
    • ❌ Complex ML pipelines
    • ❌ Multiple external services

    Decision Framework

    For each future proposal, ask:

    1. Can we ship without new runtime deps? (Prefer yes)
    2. Does it work if the external tool is missing? (Must be yes)
    3. Is there a 50% complexity solution that gets 80% value? (Try it first)
    4. Does it align with local-first philosophy? (Must be yes)
    5. Can a new contributor understand it in < 30 min? (Should be yes)

    If any answer is "no", reconsider or defer.

  3. admarble commented on Jan 29, 2026

    @admarble
    ContributorAuthor

    Closing this RFC after assessment. The proposal adds significant complexity (12+ dependencies, 9 subsystems) for marginal gains over what Claude Code + Opus 4.5 already provides natively.

    Key concerns:

    • RAG/embeddings duplicate Claude's native code understanding
    • Observability infrastructure adds latency without actionable insights
    • Self-improvement loop assumes trainable model (Claude isn't fine-tunable)
    • Token usage would increase 50-100%
    • Complexity would ~triple the codebase

    Extracting high-value items into focused issues:

    • Semgrep/ast-grep integration for /qa (genuine quality improvement)
    • AC linting for /spec (catches vague specs early)

    These deliver 80% of the value with 20% of the complexity. See follow-up issues.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions